Cleanup and bugfixes
This commit is contained in:
@@ -1,147 +0,0 @@
|
|||||||
# AI Engineering One-Pager Template
|
|
||||||
|
|
||||||
My Name - Team No
|
|
||||||
|
|
||||||
Employee ID:
|
|
||||||
|
|
||||||
Designation: AI Developer
|
|
||||||
|
|
||||||
Month: JUNE 2026
|
|
||||||
|
|
||||||
Sprint: _____________ Project: BookKeepPro
|
|
||||||
|
|
||||||
Owner: _____________
|
|
||||||
|
|
||||||
1. Work Snapshot
|
|
||||||
|
|
||||||
BookKeepPro is a FastAPI-based bookkeeping platform for CPA workflows, enabling clients to upload personal and business documents, review admin documents, and interact with a web-based dashboard. The project combines a Python backend, MySQL database, vanilla HTML frontend, and object storage integration to support document handling, admin review, email notifications, and authentication flows. The current focus is on stabilizing the storage migration, strengthening security, and improving production readiness for real-world deployment.
|
|
||||||
|
|
||||||
2. Key Deliverables
|
|
||||||
|
|
||||||
- Reviewed the end-to-end architecture of authentication, RBAC, uploads, reviews, and storage integration.
|
|
||||||
- Audited the project for critical issues affecting upload/delete workflows, document ownership, and security.
|
|
||||||
- Documented the current state of the app through a detailed project audit and technical review.
|
|
||||||
- Identified remediation priorities for storage migration, JWT security, validation, and admin workflow resilience.
|
|
||||||
|
|
||||||
3. Progress
|
|
||||||
|
|
||||||
- Done — Architecture and security review completed; critical issues documented; upload workflow analysis completed; storage migration gaps identified.
|
|
||||||
- In Progress — Remediation planning for upload endpoints, storage integration, and auth hardening.
|
|
||||||
- Not Started — Full production hardening tasks such as tests, deployment automation, monitoring, and audit trail implementation.
|
|
||||||
|
|
||||||
Overall completion: approximately 45% of the planned stabilization scope is completed, with the highest-risk issues now clearly identified.
|
|
||||||
|
|
||||||
4. Next Sprint Priorities
|
|
||||||
|
|
||||||
- Priority 1 — Fix the broken upload and delete endpoints by replacing legacy Drive-based calls with the new storage implementation.
|
|
||||||
- Priority 2 — Harden authentication and authorization by tightening JWT secret handling, improving admin role checks, and enforcing ownership validation.
|
|
||||||
- Priority 3 — Add server-side validation for uploads, generate presigned document URLs, and improve security around document access.
|
|
||||||
|
|
||||||
5. Status
|
|
||||||
|
|
||||||
🟡 At Risk
|
|
||||||
|
|
||||||
The project is functionally promising, but several critical issues remain unresolved, particularly around upload/storage stability and security hardening, which could affect reliability and production readiness.
|
|
||||||
|
|
||||||
6. Major Wins
|
|
||||||
|
|
||||||
- Win 1 — Identified and documented the critical storage migration gap that was breaking document upload and delete flows.
|
|
||||||
- Win 2 — Confirmed that backend RBAC patterns are largely sound, creating a strong base for secure access control improvements.
|
|
||||||
- Win 3 — Produced a structured audit that clearly prioritizes technical and security remediation work for the next sprint.
|
|
||||||
|
|
||||||
7. Risks & Blockers
|
|
||||||
|
|
||||||
- Risk/Blocker 1 — Upload and delete endpoints are currently broken due to incomplete migration from legacy Drive logic to object storage; mitigation: replace legacy function calls and validate the full workflow end to end.
|
|
||||||
- Risk/Blocker 2 — Security weaknesses such as weak secrets, permissive CORS, and missing validation could expose the platform to unauthorized access or misuse; mitigation: implement hardening measures and remove insecure defaults.
|
|
||||||
|
|
||||||
8. Decisions Required
|
|
||||||
|
|
||||||
- Decision 1 — Confirm the production storage strategy and credentials for object storage; owner: Project Lead; deadline: next sprint kickoff.
|
|
||||||
- Decision 2 — Approve the security hardening scope for JWT, file validation, and access control; owner: Project Lead / Tech Lead; deadline: before deployment planning.
|
|
||||||
|
|
||||||
9. Biggest Opportunity
|
|
||||||
|
|
||||||
The highest-leverage opportunity is to complete the storage and security stabilization work in one pass. If the upload pipeline, document access model, and auth hardening are finalized together, the application will move from a working prototype to a much more reliable production-ready platform.
|
|
||||||
|
|
||||||
10. What’s Keeping Me Awake
|
|
||||||
|
|
||||||
- Concern 1 — Critical upload flows remain unstable until the migration is completed end to end.
|
|
||||||
- Concern 2 — Production readiness is still limited by missing validation, weak secret handling, and incomplete operational safeguards.
|
|
||||||
|
|
||||||
11. Major Misses
|
|
||||||
|
|
||||||
- Miss 1 — The storage migration was started but not completed, leaving upload and delete APIs broken; root cause: legacy Drive references remained in the code after the storage transition.
|
|
||||||
- Miss 2 — Security and validation safeguards were not fully implemented before broader rollout planning; root cause: the project is still in an early-stage prototype phase with incomplete hardening.
|
|
||||||
|
|
||||||
12. Key Observations
|
|
||||||
|
|
||||||
- Observation 1 — The core workflow architecture is solid, but operational resilience is still weak.
|
|
||||||
- Observation 2 — The frontend and backend are closely coupled, which increases the need for careful API and security discipline.
|
|
||||||
|
|
||||||
13. Key Learnings
|
|
||||||
|
|
||||||
- Learning 1 — Migration work must be verified end to end rather than assumed complete after partial implementation.
|
|
||||||
- Learning 2 — Security hardening should be treated as a core delivery requirement, not a later-phase improvement.
|
|
||||||
|
|
||||||
14. Customer Feedback for Me
|
|
||||||
|
|
||||||
Customer-facing feedback is limited at this stage, but the main expectation is clear: the platform should be dependable for document uploads, secure for sensitive financial data, and simple for users to navigate without friction.
|
|
||||||
|
|
||||||
15. HR Team Feedback (Filled by Myself)
|
|
||||||
|
|
||||||
The sprint reflected strong ownership, structured analysis, and a focus on building a reliable technical foundation. Continued emphasis on delivery discipline, communication, and proactive issue resolution will help improve execution quality further.
|
|
||||||
|
|
||||||
16. Personal Reflection
|
|
||||||
|
|
||||||
What went well?: I maintained a strong focus on identifying high-impact technical issues and translating them into actionable remediation priorities.
|
|
||||||
|
|
||||||
What could I improve?: I can improve by moving from analysis to implementation faster, especially on the highest-risk fixes that affect user-facing functionality.
|
|
||||||
|
|
||||||
Am I spending time on the right things?: Yes, the work has centered on the most important risks to the project’s stability and credibility.
|
|
||||||
|
|
||||||
17. My One Big Bet
|
|
||||||
|
|
||||||
If I could improve only one thing next sprint, I would prioritize completing the storage and security remediation path in a single focused effort. Success would mean that document upload, review, and access flows work reliably and securely without regressions.
|
|
||||||
|
|
||||||
18. Next Month Top 5 Commitments
|
|
||||||
|
|
||||||
1. Complete the storage migration fixes and restore document upload/delete flows.
|
|
||||||
2. Harden authentication, authorization, and document access controls.
|
|
||||||
3. Add backend validation for file type, file size, and input safety.
|
|
||||||
4. Improve production readiness with deployment and monitoring considerations.
|
|
||||||
5. Build a stronger review and audit trail foundation for CPA workflow reliability.
|
|
||||||
|
|
||||||
19. Confidence Score (1-10)
|
|
||||||
|
|
||||||
| Area | My Score | Lead Score |
|
|
||||||
|---|---:|---:|
|
|
||||||
| Delivery (Project Execution & Timely Completion) | 6 | |
|
|
||||||
| Overall ROI (Business Impact & Value Created) | 7 | |
|
|
||||||
| Performance (Quality & Productivity) | 7 | |
|
|
||||||
| Ownership & Accountability | 8 | |
|
|
||||||
| Code Quality & Engineering Standards | 6 | |
|
|
||||||
| Problem Solving | 8 | |
|
|
||||||
| Decision Making | 7 | |
|
|
||||||
| Technical Growth & Skill Development | 8 | |
|
|
||||||
| System Stability & Reliability | 5 | |
|
|
||||||
| Technical Growth | 8 | |
|
|
||||||
| Skill Development | 8 | |
|
|
||||||
| Innovative Approach | 7 | |
|
|
||||||
| Technical Leadership | 6 | |
|
|
||||||
| Team Collaboration | 7 | |
|
|
||||||
| Communication | 7 | |
|
|
||||||
| Time Utilization & Productivity | 7 | |
|
|
||||||
| Commitment | 8 | |
|
|
||||||
| Dedication | 8 | |
|
|
||||||
| Learnings & Continuous Improvement | 8 | |
|
|
||||||
| Punctuality & Professional Discipline | 7 | |
|
|
||||||
|
|
||||||
My Overall Performance (Self-Assessment): 7/10
|
|
||||||
|
|
||||||
My Signature: ___________________________ Date: __________
|
|
||||||
|
|
||||||
Lead Sign-off: ___________________________ Date: __________
|
|
||||||
|
|
||||||
Overall Performance Status (keep one)
|
|
||||||
|
|
||||||
🟡 Good
|
|
||||||
@@ -10,14 +10,14 @@ export default function AdminDashboard() {
|
|||||||
const [search, setSearch] = useState("");
|
const [search, setSearch] = useState("");
|
||||||
const [userFilter, setUserFilter] = useState("all");
|
const [userFilter, setUserFilter] = useState("all");
|
||||||
const [userSort, setUserSort] = useState("newest");
|
const [userSort, setUserSort] = useState("newest");
|
||||||
const [filterYear, setFilterYear] = useState(new Date().getFullYear().toString());
|
const [filterYear, setFilterYear] = useState("2025");
|
||||||
const [tab, setTab] = useState("users");
|
const [tab, setTab] = useState("users");
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
// --- Template Management State ---
|
// --- Template Management State ---
|
||||||
const [tplCategory, setTplCategory] = useState("personal");
|
const [tplCategory, setTplCategory] = useState("personal");
|
||||||
const [tplYear, setTplYear] = useState(new Date().getFullYear().toString());
|
const [tplYear, setTplYear] = useState("2025");
|
||||||
const [templates, setTemplates] = useState([]);
|
const [templates, setTemplates] = useState([]);
|
||||||
const [tplName, setTplName] = useState("");
|
const [tplName, setTplName] = useState("");
|
||||||
const [tplFile, setTplFile] = useState(null);
|
const [tplFile, setTplFile] = useState(null);
|
||||||
@@ -50,8 +50,8 @@ export default function AdminDashboard() {
|
|||||||
|
|
||||||
// Compute stats locally
|
// Compute stats locally
|
||||||
const total = usersArray.length;
|
const total = usersArray.length;
|
||||||
const pendingP = usersArray.reduce((s, u) => s + (u.pending_personal || 0), 0);
|
const pendingP = usersArray.filter(u => u.pending_personal > 0).length;
|
||||||
const pendingB = usersArray.reduce((s, u) => s + (u.pending_business || 0), 0);
|
const pendingB = usersArray.filter(u => u.pending_business > 0).length;
|
||||||
const admins = usersArray.filter(u => u.role === "admin" || u.role === "super_admin").length;
|
const admins = usersArray.filter(u => u.role === "admin" || u.role === "super_admin").length;
|
||||||
|
|
||||||
setStats({ total_users: total, pending_personal: pendingP, pending_business: pendingB, admins: admins });
|
setStats({ total_users: total, pending_personal: pendingP, pending_business: pendingB, admins: admins });
|
||||||
@@ -133,7 +133,7 @@ export default function AdminDashboard() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const currentYear = new Date().getFullYear();
|
const currentYear = 2025;
|
||||||
const yearOptions = [currentYear - 1, currentYear, currentYear + 1];
|
const yearOptions = [currentYear - 1, currentYear, currentYear + 1];
|
||||||
|
|
||||||
const filteredUsers = users.filter(u => {
|
const filteredUsers = users.filter(u => {
|
||||||
|
|||||||
@@ -26,6 +26,10 @@ export default function AdminUserDetail() {
|
|||||||
|
|
||||||
// Reject comment panel: { docId, type, note }
|
// Reject comment panel: { docId, type, note }
|
||||||
const [rejectPanel, setRejectPanel] = useState(null);
|
const [rejectPanel, setRejectPanel] = useState(null);
|
||||||
|
// Send-for-approval panel: { docId, note }
|
||||||
|
const [sendApprovalPanel, setSendApprovalPanel] = useState(null);
|
||||||
|
const [sendingApproval, setSendingApproval] = useState(false);
|
||||||
|
const [markFiledLoading, setMarkFiledLoading] = useState(false);
|
||||||
|
|
||||||
// Export Excel Function
|
// Export Excel Function
|
||||||
const exportToExcel = async () => {
|
const exportToExcel = async () => {
|
||||||
@@ -207,6 +211,54 @@ export default function AdminUserDetail() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const sendReturnForApproval = async (docId, note = "") => {
|
||||||
|
setSendingApproval(true);
|
||||||
|
try {
|
||||||
|
const res = await authFetch("/api/review/send-return-for-approval", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ doc_id: docId, note })
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
setSendApprovalPanel(null);
|
||||||
|
showToast("Document sent to client for approval ✔", "success");
|
||||||
|
fetchUserDetails();
|
||||||
|
} else {
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
showToast(data.detail || "Failed to send", "error");
|
||||||
|
}
|
||||||
|
} catch (err) { console.error(err);
|
||||||
|
showToast("Network error", "error");
|
||||||
|
} finally {
|
||||||
|
setSendingApproval(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const markFiled = async () => {
|
||||||
|
const yearForFiling = taxYear || 2025;
|
||||||
|
if (!window.confirm(`Mark all approved docs for ${yearForFiling} as FILED? This will send a confirmation email to the client.`)) return;
|
||||||
|
setMarkFiledLoading(true);
|
||||||
|
try {
|
||||||
|
const res = await authFetch("/api/review/mark-filed", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ user_id: parseInt(userId), tax_year: parseInt(yearForFiling) })
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
showToast(`Filed: ${data.personal_filed} personal + ${data.business_filed} business docs`, "success");
|
||||||
|
fetchUserDetails();
|
||||||
|
} else {
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
showToast(data.detail || "Mark filed failed", "error");
|
||||||
|
}
|
||||||
|
} catch (err) { console.error(err);
|
||||||
|
showToast("Network error", "error");
|
||||||
|
} finally {
|
||||||
|
setMarkFiledLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const uploadAdminDoc = async (file) => {
|
const uploadAdminDoc = async (file) => {
|
||||||
const fd = new FormData();
|
const fd = new FormData();
|
||||||
fd.append("file", file);
|
fd.append("file", file);
|
||||||
@@ -784,11 +836,20 @@ export default function AdminUserDetail() {
|
|||||||
{activeTab === 'returns' && (
|
{activeTab === 'returns' && (
|
||||||
<div className="tab-panel active">
|
<div className="tab-panel active">
|
||||||
<div className="card-flat">
|
<div className="card-flat">
|
||||||
<div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'16px'}}>
|
<div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'16px', flexWrap:'wrap', gap:'8px'}}>
|
||||||
<h3 style={{margin:0}}>Admin Documents</h3>
|
<h3 style={{margin:0}}>Admin Returns / Documents</h3>
|
||||||
<div>
|
<div style={{display:'flex', gap:'8px', flexWrap:'wrap'}}>
|
||||||
<input type="file" hidden ref={adminDocInputRef} accept=".pdf,.doc,.docx,.xls,.xlsx" onChange={e => {if(e.target.files[0]) uploadAdminDoc(e.target.files[0])}} />
|
<input type="file" hidden ref={adminDocInputRef} accept=".pdf,.doc,.docx,.xls,.xlsx" onChange={e => {if(e.target.files[0]) uploadAdminDoc(e.target.files[0])}} />
|
||||||
<button className="btn btn-primary btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => adminDocInputRef.current?.click()}>+ Upload Document</button>
|
<button className="btn btn-primary btn-sm" style={{borderRadius:'var(--radius-sm)'}} onClick={() => adminDocInputRef.current?.click()}>+ Upload Return</button>
|
||||||
|
<button
|
||||||
|
className="btn btn-secondary btn-sm"
|
||||||
|
style={{borderRadius:'var(--radius-sm)', background:'#2c7a5b', color:'#fff', borderColor:'#2c7a5b'}}
|
||||||
|
onClick={markFiled}
|
||||||
|
disabled={markFiledLoading}
|
||||||
|
title={`Mark all approved docs for ${taxYear || 'selected year'} as Filed`}
|
||||||
|
>
|
||||||
|
{markFiledLoading ? 'Filing...' : '✔ Mark as Filed'}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{returnDocs.length === 0 ? (
|
{returnDocs.length === 0 ? (
|
||||||
@@ -798,25 +859,95 @@ export default function AdminUserDetail() {
|
|||||||
<table className="admin-table">
|
<table className="admin-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>Filename</th>
|
<th>Document</th>
|
||||||
|
<th>Tax Year</th>
|
||||||
<th>Date</th>
|
<th>Date</th>
|
||||||
|
<th>Status</th>
|
||||||
<th>Actions</th>
|
<th>Actions</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{returnDocs.map(doc => (
|
{returnDocs.map(doc => (
|
||||||
<tr key={doc.id}>
|
<>
|
||||||
<td>
|
<tr key={doc.id}>
|
||||||
<div style={{fontWeight:500, color:'var(--navy)'}}>{doc.filename}</div>
|
<td>
|
||||||
</td>
|
<div style={{fontWeight:500, color:'var(--navy)'}}>{doc.doc_label || doc.filename}</div>
|
||||||
<td>{new Date(doc.uploaded_at).toLocaleDateString()}</td>
|
<div className="text-sm text-muted">{doc.filename}</div>
|
||||||
<td>
|
</td>
|
||||||
<div style={{display:'flex', gap:'8px'}}>
|
<td>{doc.tax_year || <span className="text-muted">N/A</span>}</td>
|
||||||
<button className="btn btn-secondary btn-sm" onClick={() => viewDoc(doc.storage_key)}>View</button>
|
<td>{new Date(doc.uploaded_at).toLocaleDateString()}</td>
|
||||||
<button className="btn btn-danger btn-sm" onClick={() => deleteAdminDoc(doc.id)}>Delete</button>
|
<td>
|
||||||
</div>
|
{(() => {
|
||||||
</td>
|
const s = doc.review_status || 'pending';
|
||||||
</tr>
|
const cls = s === 'approved' ? 'badge-green' : s === 'rejected' ? 'badge-red' : s === 'sent_for_approval' ? 'badge-blue' : s === 'filed' ? 'badge-green' : 'badge-yellow';
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<span className={`badge ${cls}`} style={{fontWeight:700}}>{s.replace(/_/g,' ').toUpperCase()}</span>
|
||||||
|
{doc.review_note && <div className="text-sm text-muted" style={{marginTop:'3px', fontSize:'11px'}}>{doc.review_note}</div>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div style={{display:'flex', gap:'6px', flexWrap:'wrap'}}>
|
||||||
|
<button className="btn btn-secondary btn-sm" onClick={() => viewDoc(doc.storage_key)}>View</button>
|
||||||
|
{doc.review_status !== 'filed' && doc.review_status !== 'approved' && (
|
||||||
|
<button
|
||||||
|
className="btn btn-primary btn-sm"
|
||||||
|
style={{background:'#2c7a5b', borderColor:'#2c7a5b', fontSize:'12px'}}
|
||||||
|
onClick={() => setSendApprovalPanel({ docId: doc.id, note: '' })}
|
||||||
|
disabled={sendingApproval}
|
||||||
|
>
|
||||||
|
📤 Send for Approval
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button className="btn btn-danger btn-sm" onClick={() => deleteAdminDoc(doc.id)}>Delete</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
{/* Inline Send-for-Approval Panel */}
|
||||||
|
{sendApprovalPanel?.docId === doc.id && (
|
||||||
|
<tr key={`send-${doc.id}`}>
|
||||||
|
<td colSpan={5} style={{padding:'0'}}>
|
||||||
|
<div style={{
|
||||||
|
padding:'14px 16px',
|
||||||
|
background:'rgba(44,122,91,0.05)',
|
||||||
|
border:'1px solid rgba(44,122,91,0.25)',
|
||||||
|
borderTop:'none',
|
||||||
|
display:'flex', flexDirection:'column', gap:'10px'
|
||||||
|
}}>
|
||||||
|
<div style={{fontWeight:600, fontSize:'13px', color:'#2c7a5b'}}>
|
||||||
|
📤 Send this document to client for review
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
rows={2}
|
||||||
|
placeholder="Optional note to client (e.g. 'Please review page 3')..."
|
||||||
|
value={sendApprovalPanel.note}
|
||||||
|
onChange={e => setSendApprovalPanel(prev => ({...prev, note: e.target.value}))}
|
||||||
|
style={{
|
||||||
|
width:'100%', padding:'8px 12px',
|
||||||
|
border:'1px solid rgba(44,122,91,0.35)', borderRadius:'var(--radius-sm)',
|
||||||
|
fontSize:'13px', resize:'vertical', outline:'none',
|
||||||
|
fontFamily:'inherit', background:'white', boxSizing:'border-box'
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<div style={{display:'flex', gap:'8px', justifyContent:'flex-end'}}>
|
||||||
|
<button className="btn btn-secondary btn-sm" onClick={() => setSendApprovalPanel(null)}>Cancel</button>
|
||||||
|
<button
|
||||||
|
className="btn btn-primary btn-sm"
|
||||||
|
style={{background:'#2c7a5b', borderColor:'#2c7a5b'}}
|
||||||
|
disabled={sendingApproval}
|
||||||
|
onClick={() => sendReturnForApproval(doc.id, sendApprovalPanel.note)}
|
||||||
|
>
|
||||||
|
{sendingApproval ? 'Sending...' : 'Confirm & Email Client'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { useToast } from '../context/ToastContext';
|
|||||||
export default function UploadBusiness() {
|
export default function UploadBusiness() {
|
||||||
const { authFetch } = useAuth();
|
const { authFetch } = useAuth();
|
||||||
const { showToast } = useToast();
|
const { showToast } = useToast();
|
||||||
const [taxYear, setTaxYear] = useState(new Date().getFullYear());
|
const [taxYear, setTaxYear] = useState(2025);
|
||||||
const [docs, setDocs] = useState([]);
|
const [docs, setDocs] = useState([]);
|
||||||
const [templates, setTemplates] = useState([]);
|
const [templates, setTemplates] = useState([]);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
@@ -162,12 +162,36 @@ export default function UploadBusiness() {
|
|||||||
<div className="empty-state">No required documents for this tax year.</div>
|
<div className="empty-state">No required documents for this tax year.</div>
|
||||||
) : templates.map((dt, i) => {
|
) : templates.map((dt, i) => {
|
||||||
const uploaded = docs.filter(d => d.doc_type === dt.name);
|
const uploaded = docs.filter(d => d.doc_type === dt.name);
|
||||||
|
const latestDoc = uploaded[0] || null;
|
||||||
|
const isRejected = latestDoc?.review_status === 'rejected';
|
||||||
|
const isApproved = latestDoc?.review_status === 'approved';
|
||||||
|
const isFiled = latestDoc?.review_status === 'filed';
|
||||||
return (
|
return (
|
||||||
<div className="doc-slot fade-up" key={i} style={{ animationDelay: `${i * 0.04}s` }}>
|
<div className="doc-slot fade-up" key={i} style={{ animationDelay: `${i * 0.04}s`, borderLeft: isRejected ? '3px solid #dc3545' : isApproved || isFiled ? '3px solid #2c7a5b' : 'none' }}>
|
||||||
<div className="doc-slot-info">
|
<div className="doc-slot-info">
|
||||||
<div className="doc-slot-name">{i+1}. {dt.name}</div>
|
<div className="doc-slot-name">{i+1}. {dt.name}</div>
|
||||||
<div className="doc-slot-status">
|
<div className="doc-slot-status">
|
||||||
{uploaded.length ? (
|
{isRejected ? (
|
||||||
|
<div>
|
||||||
|
<span style={{display:'inline-flex', alignItems:'center', gap:'5px', background:'#fdecea', color:'#c0392b', padding:'3px 10px', borderRadius:'20px', fontSize:'12px', fontWeight:700}}>
|
||||||
|
<span className="material-symbols-outlined" style={{fontSize:'13px'}}>cancel</span> REJECTED
|
||||||
|
</span>
|
||||||
|
{latestDoc.review_note && (
|
||||||
|
<div style={{fontSize:'12px', color:'#c0392b', marginTop:'5px', fontStyle:'italic', maxWidth:'260px'}}>
|
||||||
|
⚠️ Reason: "{latestDoc.review_note}"
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div style={{fontSize:'11px', color:'var(--muted)', marginTop:'3px'}}>Please correct and re-upload below.</div>
|
||||||
|
</div>
|
||||||
|
) : isApproved ? (
|
||||||
|
<span style={{display:'inline-flex', alignItems:'center', gap:'5px', background:'#edf7f2', color:'#2c7a5b', padding:'3px 10px', borderRadius:'20px', fontSize:'12px', fontWeight:700}}>
|
||||||
|
<span className="material-symbols-outlined" style={{fontSize:'13px'}}>check_circle</span> APPROVED
|
||||||
|
</span>
|
||||||
|
) : isFiled ? (
|
||||||
|
<span style={{display:'inline-flex', alignItems:'center', gap:'5px', background:'#edf7f2', color:'#2c7a5b', padding:'3px 10px', borderRadius:'20px', fontSize:'12px', fontWeight:700}}>
|
||||||
|
<span className="material-symbols-outlined" style={{fontSize:'13px'}}>inventory_2</span> FILED
|
||||||
|
</span>
|
||||||
|
) : uploaded.length ? (
|
||||||
<span className="pill-pending"><span className="material-symbols-outlined">pending</span> Pending Review</span>
|
<span className="pill-pending"><span className="material-symbols-outlined">pending</span> Pending Review</span>
|
||||||
) : dt.download ? (
|
) : dt.download ? (
|
||||||
<a href={dt.download} target="_blank" rel="noopener noreferrer" className="btn-link" style={{ fontSize: '14px', color: 'var(--brand)', textDecoration: 'underline' }}>View Template</a>
|
<a href={dt.download} target="_blank" rel="noopener noreferrer" className="btn-link" style={{ fontSize: '14px', color: 'var(--brand)', textDecoration: 'underline' }}>View Template</a>
|
||||||
@@ -189,21 +213,30 @@ export default function UploadBusiness() {
|
|||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>
|
<div style={{display: 'flex', gap: '8px', alignItems: 'center', flexWrap:'wrap'}}>
|
||||||
{dt.download && (
|
{dt.download && (
|
||||||
<a href={dt.download} target="_blank" rel="noreferrer" className="btn btn-secondary btn-sm" style={{borderRadius: 'var(--radius-pill)', padding: '4px 12px', display: 'flex', alignItems: 'center', gap: '4px'}}>
|
<a href={dt.download} target="_blank" rel="noreferrer" className="btn btn-secondary btn-sm" style={{borderRadius: 'var(--radius-pill)', padding: '4px 12px', display: 'flex', alignItems: 'center', gap: '4px'}}>
|
||||||
<span className="material-symbols-outlined" style={{fontSize: '16px'}}>download</span> Template
|
<span className="material-symbols-outlined" style={{fontSize: '16px'}}>download</span> Template
|
||||||
</a>
|
</a>
|
||||||
)}
|
)}
|
||||||
{!uploaded.length && (
|
{/* Show Upload button if no doc OR doc is rejected (re-upload allowed) */}
|
||||||
<button className="btn btn-sm btn-upload-pill" onClick={() => fileInputRefs.current[dt.name].click()}>Upload</button>
|
{(!uploaded.length || isRejected) && (
|
||||||
|
<button
|
||||||
|
className={`btn btn-sm ${isRejected ? 'btn-primary' : 'btn-upload-pill'}`}
|
||||||
|
style={isRejected ? {background:'#2c7a5b', borderColor:'#2c7a5b', color:'#fff', borderRadius:'var(--radius-pill)'} : {}}
|
||||||
|
onClick={() => fileInputRefs.current[dt.name].click()}
|
||||||
|
>
|
||||||
|
{isRejected ? '🔄 Re-upload' : 'Upload'}
|
||||||
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{uploaded.map(doc => (
|
{uploaded.map(doc => (
|
||||||
<div key={doc.id} style={{display:'flex', flexDirection:'column', gap:'8px', alignItems:'flex-end'}}>
|
<div key={doc.id} style={{display:'flex', flexDirection:'column', gap:'8px', alignItems:'flex-end', marginTop:'4px'}}>
|
||||||
<div style={{display:'flex', gap:'8px'}}>
|
<div style={{display:'flex', gap:'8px'}}>
|
||||||
<button className="btn btn-secondary btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => viewDoc(doc.storage_key)}>View</button>
|
<button className="btn btn-secondary btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => viewDoc(doc.storage_key)}>View</button>
|
||||||
<button className="btn btn-danger btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => deleteDoc(doc.id)}>Delete</button>
|
{!isApproved && !isFiled && (
|
||||||
|
<button className="btn btn-danger btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => deleteDoc(doc.id)}>Delete</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { useToast } from '../context/ToastContext';
|
|||||||
export default function UploadPersonal() {
|
export default function UploadPersonal() {
|
||||||
const { authFetch } = useAuth();
|
const { authFetch } = useAuth();
|
||||||
const { showToast } = useToast();
|
const { showToast } = useToast();
|
||||||
const [taxYear, setTaxYear] = useState(new Date().getFullYear());
|
const [taxYear, setTaxYear] = useState(2025);
|
||||||
const [docs, setDocs] = useState([]);
|
const [docs, setDocs] = useState([]);
|
||||||
const [templates, setTemplates] = useState([]);
|
const [templates, setTemplates] = useState([]);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
@@ -164,12 +164,36 @@ export default function UploadPersonal() {
|
|||||||
<div className="empty-state">No required documents for this tax year.</div>
|
<div className="empty-state">No required documents for this tax year.</div>
|
||||||
) : templates.map((dt, i) => {
|
) : templates.map((dt, i) => {
|
||||||
const uploaded = docs.filter(d => d.doc_type === dt.name);
|
const uploaded = docs.filter(d => d.doc_type === dt.name);
|
||||||
|
const latestDoc = uploaded[0] || null;
|
||||||
|
const isRejected = latestDoc?.review_status === 'rejected';
|
||||||
|
const isApproved = latestDoc?.review_status === 'approved';
|
||||||
|
const isFiled = latestDoc?.review_status === 'filed';
|
||||||
return (
|
return (
|
||||||
<div className="doc-slot fade-up" key={i} style={{ animationDelay: `${i * 0.04}s` }}>
|
<div className="doc-slot fade-up" key={i} style={{ animationDelay: `${i * 0.04}s`, borderLeft: isRejected ? '3px solid #dc3545' : isApproved || isFiled ? '3px solid #2c7a5b' : 'none' }}>
|
||||||
<div className="doc-slot-info">
|
<div className="doc-slot-info">
|
||||||
<div className="doc-slot-name">{i+1}. {dt.name}</div>
|
<div className="doc-slot-name">{i+1}. {dt.name}</div>
|
||||||
<div className="doc-slot-status">
|
<div className="doc-slot-status">
|
||||||
{uploaded.length ? (
|
{isRejected ? (
|
||||||
|
<div>
|
||||||
|
<span style={{display:'inline-flex', alignItems:'center', gap:'5px', background:'#fdecea', color:'#c0392b', padding:'3px 10px', borderRadius:'20px', fontSize:'12px', fontWeight:700}}>
|
||||||
|
<span className="material-symbols-outlined" style={{fontSize:'13px'}}>cancel</span> REJECTED
|
||||||
|
</span>
|
||||||
|
{latestDoc.review_note && (
|
||||||
|
<div style={{fontSize:'12px', color:'#c0392b', marginTop:'5px', fontStyle:'italic', maxWidth:'260px'}}>
|
||||||
|
⚠️ Reason: "{latestDoc.review_note}"
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div style={{fontSize:'11px', color:'var(--muted)', marginTop:'3px'}}>Please correct and re-upload below.</div>
|
||||||
|
</div>
|
||||||
|
) : isApproved ? (
|
||||||
|
<span style={{display:'inline-flex', alignItems:'center', gap:'5px', background:'#edf7f2', color:'#2c7a5b', padding:'3px 10px', borderRadius:'20px', fontSize:'12px', fontWeight:700}}>
|
||||||
|
<span className="material-symbols-outlined" style={{fontSize:'13px'}}>check_circle</span> APPROVED
|
||||||
|
</span>
|
||||||
|
) : isFiled ? (
|
||||||
|
<span style={{display:'inline-flex', alignItems:'center', gap:'5px', background:'#edf7f2', color:'#2c7a5b', padding:'3px 10px', borderRadius:'20px', fontSize:'12px', fontWeight:700}}>
|
||||||
|
<span className="material-symbols-outlined" style={{fontSize:'13px'}}>inventory_2</span> FILED
|
||||||
|
</span>
|
||||||
|
) : uploaded.length ? (
|
||||||
<span className="pill-pending"><span className="material-symbols-outlined">pending</span> Pending Review</span>
|
<span className="pill-pending"><span className="material-symbols-outlined">pending</span> Pending Review</span>
|
||||||
) : dt.download ? (
|
) : dt.download ? (
|
||||||
<a href={dt.download} target="_blank" rel="noopener noreferrer" className="btn-link" style={{ fontSize: '14px', color: 'var(--brand)', textDecoration: 'underline' }}>View Template</a>
|
<a href={dt.download} target="_blank" rel="noopener noreferrer" className="btn-link" style={{ fontSize: '14px', color: 'var(--brand)', textDecoration: 'underline' }}>View Template</a>
|
||||||
@@ -191,21 +215,30 @@ export default function UploadPersonal() {
|
|||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<div style={{display: 'flex', gap: '8px', alignItems: 'center'}}>
|
<div style={{display: 'flex', gap: '8px', alignItems: 'center', flexWrap:'wrap'}}>
|
||||||
{dt.download && (
|
{dt.download && (
|
||||||
<a href={dt.download} target="_blank" rel="noreferrer" className="btn btn-secondary btn-sm" style={{borderRadius: 'var(--radius-pill)', padding: '4px 12px', display: 'flex', alignItems: 'center', gap: '4px'}}>
|
<a href={dt.download} target="_blank" rel="noreferrer" className="btn btn-secondary btn-sm" style={{borderRadius: 'var(--radius-pill)', padding: '4px 12px', display: 'flex', alignItems: 'center', gap: '4px'}}>
|
||||||
<span className="material-symbols-outlined" style={{fontSize: '16px'}}>download</span> Template
|
<span className="material-symbols-outlined" style={{fontSize: '16px'}}>download</span> Template
|
||||||
</a>
|
</a>
|
||||||
)}
|
)}
|
||||||
{!uploaded.length && (
|
{/* Show Upload button if no doc OR doc is rejected (re-upload allowed) */}
|
||||||
<button className="btn btn-sm btn-upload-pill" onClick={() => fileInputRefs.current[dt.name].click()}>Upload</button>
|
{(!uploaded.length || isRejected) && (
|
||||||
|
<button
|
||||||
|
className={`btn btn-sm ${isRejected ? 'btn-primary' : 'btn-upload-pill'}`}
|
||||||
|
style={isRejected ? {background:'#2c7a5b', borderColor:'#2c7a5b', color:'#fff', borderRadius:'var(--radius-pill)'} : {}}
|
||||||
|
onClick={() => fileInputRefs.current[dt.name].click()}
|
||||||
|
>
|
||||||
|
{isRejected ? '🔄 Re-upload' : 'Upload'}
|
||||||
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{uploaded.map(doc => (
|
{uploaded.map(doc => (
|
||||||
<div key={doc.id} style={{display:'flex', flexDirection:'column', gap:'8px', alignItems:'flex-end'}}>
|
<div key={doc.id} style={{display:'flex', flexDirection:'column', gap:'8px', alignItems:'flex-end', marginTop:'4px'}}>
|
||||||
<div style={{display:'flex', gap:'8px'}}>
|
<div style={{display:'flex', gap:'8px'}}>
|
||||||
<button className="btn btn-secondary btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => viewDoc(doc.storage_key)}>View</button>
|
<button className="btn btn-secondary btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => viewDoc(doc.storage_key)}>View</button>
|
||||||
<button className="btn btn-danger btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => deleteDoc(doc.id)}>Delete</button>
|
{!isApproved && !isFiled && (
|
||||||
|
<button className="btn btn-danger btn-xs" style={{borderRadius:'var(--radius-sm)'}} onClick={() => deleteDoc(doc.id)}>Delete</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
Traceback (most recent call last):
|
|
||||||
File "C:\Users\abhil\Desktop\Bookkeepro\Bookkeep\services/api\app\routers\chatbot.py", line 204, in ask_chatbot
|
|
||||||
return data['choices'][0]['message']
|
|
||||||
~~~~^^^^^^^^^^^
|
|
||||||
KeyError: 'choices'
|
|
||||||
@@ -208,7 +208,7 @@ class ChatSession(Base):
|
|||||||
__tablename__ = "chat_sessions"
|
__tablename__ = "chat_sessions"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||||
session_id = Column(String(100), unique=True, index=True, nullable=False)
|
session_id = Column(String(100), unique=True, index=True, nullable=False)
|
||||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import os
|
import os
|
||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
import logging
|
import logging
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from app.models import AdminDocument, User, UserRole, FilingDeadline
|
from app.models import AdminDocument, User, UserRole, FilingDeadline
|
||||||
from app.db import get_db
|
from app.db import get_db
|
||||||
@@ -300,3 +300,153 @@ def get_filing_deadlines(
|
|||||||
"is_overdue": days_left < 0,
|
"is_overdue": days_left < 0,
|
||||||
})
|
})
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
|
# Gap #1: Admin sends a return to client for approval
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
class SendReturnRequest(BaseModel if False else object):
|
||||||
|
pass
|
||||||
|
|
||||||
|
from pydantic import BaseModel as _BM
|
||||||
|
|
||||||
|
class SendReturnPayload(_BM):
|
||||||
|
doc_id: int
|
||||||
|
note: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/send-return-for-approval")
|
||||||
|
async def send_return_for_approval(
|
||||||
|
payload: SendReturnPayload,
|
||||||
|
background: BackgroundTasks,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user=Depends(get_current_user),
|
||||||
|
_=Depends(require_admin),
|
||||||
|
):
|
||||||
|
"""Admin marks an admin doc as 'sent_for_approval' and emails the client. Admin only."""
|
||||||
|
doc = db.query(AdminDocument).filter_by(id=payload.doc_id).first()
|
||||||
|
if not doc:
|
||||||
|
raise HTTPException(status_code=404, detail="Document not found")
|
||||||
|
|
||||||
|
doc.review_status = "sent_for_approval"
|
||||||
|
if payload.note:
|
||||||
|
doc.review_note = payload.note
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
crud.log_action(
|
||||||
|
db, "sent_return_for_approval",
|
||||||
|
user_id=current_user.id,
|
||||||
|
target=f"admin_doc:{doc.id}",
|
||||||
|
detail=f"client:{doc.user_id}",
|
||||||
|
)
|
||||||
|
|
||||||
|
from app.models import DocumentReviewEvent
|
||||||
|
event = DocumentReviewEvent(
|
||||||
|
doc_kind="admin",
|
||||||
|
doc_id=doc.id,
|
||||||
|
owner_user_id=doc.user_id,
|
||||||
|
actor_id=current_user.id,
|
||||||
|
actor_role="admin",
|
||||||
|
action="sent_for_approval",
|
||||||
|
from_status="pending",
|
||||||
|
to_status="sent_for_approval",
|
||||||
|
comment=payload.note or None,
|
||||||
|
tax_year=doc.tax_year,
|
||||||
|
)
|
||||||
|
db.add(event)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
client = db.query(User).filter_by(id=doc.user_id).first()
|
||||||
|
if client:
|
||||||
|
note_html = f"<p><em>{payload.note}</em></p>" if payload.note else ""
|
||||||
|
background.add_task(
|
||||||
|
send_email,
|
||||||
|
to=client.email,
|
||||||
|
subject="Action Required: Please Review Your Tax Return — BookKeepro",
|
||||||
|
body=f"""
|
||||||
|
<p>Dear {client.name or 'Client'},</p>
|
||||||
|
<p>Your tax professional has prepared a document for your review:</p>
|
||||||
|
<p><strong>{doc.doc_label}</strong> (Tax Year {doc.tax_year or 'N/A'})</p>
|
||||||
|
{note_html}
|
||||||
|
<p>Please log in to your dashboard to review, approve, or request changes.</p>
|
||||||
|
<p><a href='{DASHBOARD_LINK}' style='color:#2c7a5b;font-weight:600;font-size:15px;'>Review Now →</a></p>
|
||||||
|
<p style='margin-top:20px;'>Kind regards,<br><strong>BookKeepro Team</strong></p>
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
|
||||||
|
return {"status": "sent", "doc_id": doc.id, "review_status": doc.review_status}
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
|
# Gap #5: Mark a user's filing as fully filed/locked
|
||||||
|
# ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
class MarkFiledPayload(_BM):
|
||||||
|
user_id: int
|
||||||
|
tax_year: int
|
||||||
|
note: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/mark-filed")
|
||||||
|
async def mark_filing_complete(
|
||||||
|
payload: MarkFiledPayload,
|
||||||
|
background: BackgroundTasks,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user=Depends(get_current_user),
|
||||||
|
_=Depends(require_admin),
|
||||||
|
):
|
||||||
|
"""Admin marks all approved docs for a user/year as 'filed'. Sends confirmation email."""
|
||||||
|
from app.models import PersonalDocument, BusinessDocument
|
||||||
|
|
||||||
|
personal_docs = db.query(PersonalDocument).filter(
|
||||||
|
PersonalDocument.user_id == payload.user_id,
|
||||||
|
PersonalDocument.tax_year == payload.tax_year,
|
||||||
|
PersonalDocument.deleted_at == None,
|
||||||
|
PersonalDocument.review_status == "approved",
|
||||||
|
).all()
|
||||||
|
business_docs = db.query(BusinessDocument).filter(
|
||||||
|
BusinessDocument.user_id == payload.user_id,
|
||||||
|
BusinessDocument.tax_year == payload.tax_year,
|
||||||
|
BusinessDocument.deleted_at == None,
|
||||||
|
BusinessDocument.review_status == "approved",
|
||||||
|
).all()
|
||||||
|
|
||||||
|
for doc in personal_docs:
|
||||||
|
doc.review_status = "filed"
|
||||||
|
for doc in business_docs:
|
||||||
|
doc.review_status = "filed"
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
crud.log_action(
|
||||||
|
db, "filing_complete",
|
||||||
|
user_id=current_user.id,
|
||||||
|
target=f"user:{payload.user_id}",
|
||||||
|
detail=f"tax_year:{payload.tax_year} personal:{len(personal_docs)} business:{len(business_docs)}",
|
||||||
|
)
|
||||||
|
|
||||||
|
client = crud.get_user_by_id(db, payload.user_id)
|
||||||
|
if client:
|
||||||
|
note_html = f"<p><em>{payload.note}</em></p>" if payload.note else ""
|
||||||
|
background.add_task(
|
||||||
|
send_email,
|
||||||
|
to=client.email,
|
||||||
|
subject=f"Your {payload.tax_year} Tax Return Has Been Filed — BookKeepro",
|
||||||
|
body=f"""
|
||||||
|
<p>Dear {client.name or 'Client'},</p>
|
||||||
|
<p>Great news! Your <strong>{payload.tax_year}</strong> tax return has been successfully filed.</p>
|
||||||
|
<p>Total documents filed: {len(personal_docs) + len(business_docs)}</p>
|
||||||
|
{note_html}
|
||||||
|
<p>You can view the status in your dashboard at any time.</p>
|
||||||
|
<p><a href='{DASHBOARD_LINK}' style='color:#2c7a5b;font-weight:600;'>Go to Dashboard →</a></p>
|
||||||
|
<p style='margin-top:20px;'>Thank you for choosing BookKeepro.<br><strong>BookKeepro Team</strong></p>
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"status": "filed",
|
||||||
|
"user_id": payload.user_id,
|
||||||
|
"tax_year": payload.tax_year,
|
||||||
|
"personal_filed": len(personal_docs),
|
||||||
|
"business_filed": len(business_docs),
|
||||||
|
}
|
||||||
|
|||||||
@@ -54,11 +54,12 @@ def semantic_search(
|
|||||||
).first()
|
).first()
|
||||||
|
|
||||||
if doc:
|
if doc:
|
||||||
|
d_type = doc.doc_type if doc_type == "personal" else doc.business_type
|
||||||
doc_data = {
|
doc_data = {
|
||||||
"id": doc.id,
|
"id": doc.id,
|
||||||
"table": doc_type,
|
"table": doc_type,
|
||||||
"original_filename": doc.original_filename,
|
"filename": doc.filename,
|
||||||
"document_type": doc.document_type,
|
"document_type": d_type,
|
||||||
"uploaded_at": doc.uploaded_at,
|
"uploaded_at": doc.uploaded_at,
|
||||||
"relevance_score": res['distance']
|
"relevance_score": res['distance']
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,6 +28,8 @@ router = APIRouter(prefix="/api/upload", tags=["upload"])
|
|||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
FRONTEND_URL = os.getenv("FRONTEND_URL", "https://aiindiacpa.duckdns.org")
|
||||||
|
|
||||||
# ─────────────────────────────────────────────
|
# ─────────────────────────────────────────────
|
||||||
# Local File Storage (Contabo VPS Disk)
|
# Local File Storage (Contabo VPS Disk)
|
||||||
# ─────────────────────────────────────────────
|
# ─────────────────────────────────────────────
|
||||||
@@ -89,6 +91,15 @@ def process_ai_extraction(table: str, doc_id: int, file_path: str, doc_type: str
|
|||||||
doc = db.query(model_class).filter_by(id=doc_id).first()
|
doc = db.query(model_class).filter_by(id=doc_id).first()
|
||||||
if doc:
|
if doc:
|
||||||
doc.file_hash = file_hash
|
doc.file_hash = file_hash
|
||||||
|
# Fix H2: Prevent 'Processing...' forever by setting a placeholder
|
||||||
|
doc.extracted_data = {
|
||||||
|
"_meta": {
|
||||||
|
"status": "unsupported",
|
||||||
|
"label": "Data Not Available",
|
||||||
|
"description": "AI extraction is not supported for this file type or no text was found.",
|
||||||
|
"color": "gray"
|
||||||
|
}
|
||||||
|
}
|
||||||
db.commit()
|
db.commit()
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -474,13 +485,36 @@ async def upload_personal_document(
|
|||||||
db.commit()
|
db.commit()
|
||||||
except IntegrityError:
|
except IntegrityError:
|
||||||
db.rollback()
|
db.rollback()
|
||||||
# Clean up the already-uploaded S3 object
|
# Check if there's an existing rejected/deleted doc to replace (B4 fix: allow re-upload)
|
||||||
delete_from_storage(storage_key)
|
existing = db.query(PersonalDocument).filter(
|
||||||
raise HTTPException(
|
PersonalDocument.user_id == current_user.id,
|
||||||
status_code=409,
|
PersonalDocument.doc_type == doc_type,
|
||||||
detail="You have already uploaded this document for this tax year. "
|
PersonalDocument.tax_year == tax_year,
|
||||||
"Delete the existing one to replace it."
|
).first()
|
||||||
)
|
if existing and (existing.review_status == "rejected" or existing.deleted_at is not None):
|
||||||
|
old_storage_key = existing.storage_key
|
||||||
|
existing.filename = file.filename
|
||||||
|
existing.storage_key = storage_key
|
||||||
|
existing.content_type = file.content_type
|
||||||
|
existing.review_status = "pending"
|
||||||
|
existing.review_note = None
|
||||||
|
existing.deleted_at = None
|
||||||
|
existing.extracted_data = None
|
||||||
|
existing.uploaded_at = func.now()
|
||||||
|
db.commit()
|
||||||
|
db.refresh(existing)
|
||||||
|
record = existing
|
||||||
|
if old_storage_key:
|
||||||
|
delete_from_storage(old_storage_key)
|
||||||
|
elif existing and existing.deleted_at is None:
|
||||||
|
delete_from_storage(storage_key)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=409,
|
||||||
|
detail="You have already uploaded this document for this tax year. Delete the existing one to replace it."
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
delete_from_storage(storage_key)
|
||||||
|
raise HTTPException(status_code=409, detail="You have already uploaded this document for this tax year.")
|
||||||
db.refresh(record)
|
db.refresh(record)
|
||||||
|
|
||||||
# Append uploaded event
|
# Append uploaded event
|
||||||
@@ -621,12 +655,36 @@ async def upload_business_document(
|
|||||||
db.commit()
|
db.commit()
|
||||||
except IntegrityError:
|
except IntegrityError:
|
||||||
db.rollback()
|
db.rollback()
|
||||||
delete_from_storage(storage_key)
|
# Check if there's an existing rejected doc to replace (B4 fix: allow re-upload)
|
||||||
raise HTTPException(
|
existing = db.query(BusinessDocument).filter(
|
||||||
status_code=409,
|
BusinessDocument.user_id == current_user.id,
|
||||||
detail="You have already uploaded this document for this tax year. "
|
BusinessDocument.business_type == doc_type,
|
||||||
"Delete the existing one to replace it."
|
BusinessDocument.tax_year == tax_year,
|
||||||
)
|
).first()
|
||||||
|
if existing and (existing.review_status == "rejected" or existing.deleted_at is not None):
|
||||||
|
old_storage_key = existing.storage_key
|
||||||
|
existing.filename = file.filename
|
||||||
|
existing.storage_key = storage_key
|
||||||
|
existing.content_type = file.content_type
|
||||||
|
existing.review_status = "pending"
|
||||||
|
existing.review_note = None
|
||||||
|
existing.deleted_at = None
|
||||||
|
existing.extracted_data = None
|
||||||
|
existing.uploaded_at = func.now()
|
||||||
|
db.commit()
|
||||||
|
db.refresh(existing)
|
||||||
|
record = existing
|
||||||
|
if old_storage_key:
|
||||||
|
delete_from_storage(old_storage_key)
|
||||||
|
elif existing and existing.deleted_at is None:
|
||||||
|
delete_from_storage(storage_key)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=409,
|
||||||
|
detail="You have already uploaded this document for this tax year. Delete the existing one to replace it."
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
delete_from_storage(storage_key)
|
||||||
|
raise HTTPException(status_code=409, detail="You have already uploaded this document for this tax year.")
|
||||||
db.refresh(record)
|
db.refresh(record)
|
||||||
|
|
||||||
# Append uploaded event
|
# Append uploaded event
|
||||||
@@ -702,9 +760,10 @@ def delete_business_document(
|
|||||||
# ─────────────────────────────────────────────
|
# ─────────────────────────────────────────────
|
||||||
|
|
||||||
@router.patch("/personal-documents/{doc_id}/review-status")
|
@router.patch("/personal-documents/{doc_id}/review-status")
|
||||||
def set_personal_review_status(
|
async def set_personal_review_status(
|
||||||
doc_id: int,
|
doc_id: int,
|
||||||
payload: ReviewStatusUpdate,
|
payload: ReviewStatusUpdate,
|
||||||
|
background: BackgroundTasks,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
current_user=Depends(get_current_user),
|
current_user=Depends(get_current_user),
|
||||||
_=Depends(require_admin),
|
_=Depends(require_admin),
|
||||||
@@ -714,6 +773,7 @@ def set_personal_review_status(
|
|||||||
if not doc:
|
if not doc:
|
||||||
raise HTTPException(status_code=404, detail="Document not found")
|
raise HTTPException(status_code=404, detail="Document not found")
|
||||||
|
|
||||||
|
prev_status = doc.review_status
|
||||||
doc.review_status = payload.status
|
doc.review_status = payload.status
|
||||||
doc.review_note = payload.note
|
doc.review_note = payload.note
|
||||||
db.commit()
|
db.commit()
|
||||||
@@ -724,13 +784,34 @@ def set_personal_review_status(
|
|||||||
target=f"personal_doc:{doc_id}",
|
target=f"personal_doc:{doc_id}",
|
||||||
detail=f"owner:{doc.user_id}" + (f" note:{payload.note}" if payload.note else ""),
|
detail=f"owner:{doc.user_id}" + (f" note:{payload.note}" if payload.note else ""),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Email client on rejection (Gap #3 fix)
|
||||||
|
if payload.status == "rejected" and prev_status != "rejected":
|
||||||
|
owner = db.query(User).filter_by(id=doc.user_id).first()
|
||||||
|
if owner:
|
||||||
|
note_html = f"<p><strong>Reason:</strong> {payload.note}</p>" if payload.note else ""
|
||||||
|
background.add_task(
|
||||||
|
send_email,
|
||||||
|
to=owner.email,
|
||||||
|
subject="Action Required: Document Rejected — BookKeepro",
|
||||||
|
body=f"""
|
||||||
|
<p>Dear {owner.name or 'Client'},</p>
|
||||||
|
<p>Your personal document <strong>{doc.doc_type}</strong> (Tax Year {doc.tax_year}) has been <strong style='color:#c0392b;'>rejected</strong> by our team.</p>
|
||||||
|
{note_html}
|
||||||
|
<p>Please log in to your dashboard, review the reason, and re-upload a corrected document.</p>
|
||||||
|
<p><a href='{FRONTEND_URL}/upload-personal' style='color:#0077c8;font-weight:600;'>Re-upload Personal Documents →</a></p>
|
||||||
|
<p style='margin-top:20px;'>Kind regards,<br><strong>BookKeepro Team</strong></p>
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
|
||||||
return {"id": doc_id, "review_status": payload.status}
|
return {"id": doc_id, "review_status": payload.status}
|
||||||
|
|
||||||
|
|
||||||
@router.patch("/business-documents/{doc_id}/review-status")
|
@router.patch("/business-documents/{doc_id}/review-status")
|
||||||
def set_business_review_status(
|
async def set_business_review_status(
|
||||||
doc_id: int,
|
doc_id: int,
|
||||||
payload: ReviewStatusUpdate,
|
payload: ReviewStatusUpdate,
|
||||||
|
background: BackgroundTasks,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
current_user=Depends(get_current_user),
|
current_user=Depends(get_current_user),
|
||||||
_=Depends(require_admin),
|
_=Depends(require_admin),
|
||||||
@@ -740,6 +821,7 @@ def set_business_review_status(
|
|||||||
if not doc:
|
if not doc:
|
||||||
raise HTTPException(status_code=404, detail="Document not found")
|
raise HTTPException(status_code=404, detail="Document not found")
|
||||||
|
|
||||||
|
prev_status = doc.review_status
|
||||||
doc.review_status = payload.status
|
doc.review_status = payload.status
|
||||||
doc.review_note = payload.note
|
doc.review_note = payload.note
|
||||||
db.commit()
|
db.commit()
|
||||||
@@ -750,6 +832,26 @@ def set_business_review_status(
|
|||||||
target=f"business_doc:{doc_id}",
|
target=f"business_doc:{doc_id}",
|
||||||
detail=f"owner:{doc.user_id}" + (f" note:{payload.note}" if payload.note else ""),
|
detail=f"owner:{doc.user_id}" + (f" note:{payload.note}" if payload.note else ""),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Email client on rejection (Gap #3 fix)
|
||||||
|
if payload.status == "rejected" and prev_status != "rejected":
|
||||||
|
owner = db.query(User).filter_by(id=doc.user_id).first()
|
||||||
|
if owner:
|
||||||
|
note_html = f"<p><strong>Reason:</strong> {payload.note}</p>" if payload.note else ""
|
||||||
|
background.add_task(
|
||||||
|
send_email,
|
||||||
|
to=owner.email,
|
||||||
|
subject="Action Required: Document Rejected — BookKeepro",
|
||||||
|
body=f"""
|
||||||
|
<p>Dear {owner.name or 'Client'},</p>
|
||||||
|
<p>Your business document <strong>{doc.business_type}</strong> (Tax Year {doc.tax_year}) has been <strong style='color:#c0392b;'>rejected</strong> by our team.</p>
|
||||||
|
{note_html}
|
||||||
|
<p>Please log in to your dashboard, review the reason, and re-upload a corrected document.</p>
|
||||||
|
<p><a href='{FRONTEND_URL}/upload-business' style='color:#0077c8;font-weight:600;'>Re-upload Business Documents →</a></p>
|
||||||
|
<p style='margin-top:20px;'>Kind regards,<br><strong>BookKeepro Team</strong></p>
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
|
||||||
return {"id": doc_id, "review_status": payload.status}
|
return {"id": doc_id, "review_status": payload.status}
|
||||||
|
|
||||||
|
|
||||||
@@ -938,9 +1040,28 @@ def delete_user_completely(
|
|||||||
db.delete(doc)
|
db.delete(doc)
|
||||||
|
|
||||||
# Clean up legacy uploaded_files rows to avoid FK constraint errors on db.delete(user)
|
# Clean up legacy uploaded_files rows to avoid FK constraint errors on db.delete(user)
|
||||||
from app.models import UploadedFile
|
from app.models import UploadedFile, ChatSession, ChatMessage
|
||||||
db.query(UploadedFile).filter(UploadedFile.owner_id == user_id).delete()
|
db.query(UploadedFile).filter(UploadedFile.owner_id == user_id).delete()
|
||||||
|
|
||||||
|
# Fix B5: Delete user chat history to prevent FK constraint errors
|
||||||
|
sessions = db.query(ChatSession).filter(ChatSession.user_id == user_id).all()
|
||||||
|
for session in sessions:
|
||||||
|
db.query(ChatMessage).filter(ChatMessage.session_id == session.id).delete()
|
||||||
|
db.query(ChatSession).filter(ChatSession.user_id == user_id).delete()
|
||||||
|
|
||||||
|
# Manual cleanup for other tables without reliable ON DELETE CASCADE in older SQLite schemas
|
||||||
|
from app.models import FilingDeadline, DocumentReviewEvent, AdminDocumentBookmark
|
||||||
|
db.query(FilingDeadline).filter(FilingDeadline.user_id == user_id).delete()
|
||||||
|
db.query(DocumentReviewEvent).filter(DocumentReviewEvent.owner_user_id == user_id).delete()
|
||||||
|
db.query(AdminDocumentBookmark).filter(AdminDocumentBookmark.admin_id == user_id).delete()
|
||||||
|
|
||||||
|
# Delete embeddings
|
||||||
|
try:
|
||||||
|
delete_user_embeddings(user_id)
|
||||||
|
logger.info(f"Deleted embeddings for user {user_id}")
|
||||||
|
except Exception as emb_err:
|
||||||
|
logger.error(f"Failed to delete embeddings for user {user_id}: {emb_err}")
|
||||||
|
|
||||||
# Log before deleting the user (audit_logs.user_id FK is SET NULL, so logs survive)
|
# Log before deleting the user (audit_logs.user_id FK is SET NULL, so logs survive)
|
||||||
crud.log_action(db, "delete_user", user_id=current_user.id, target=f"user:{user_id}", detail=f"{user.email}")
|
crud.log_action(db, "delete_user", user_id=current_user.id, target=f"user:{user_id}", detail=f"{user.email}")
|
||||||
|
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ def _run_deadline_reminders():
|
|||||||
<p>Please ensure all outstanding actions are completed before the deadline.</p>
|
<p>Please ensure all outstanding actions are completed before the deadline.</p>
|
||||||
<p>Kind regards,<br><strong>BookKeepro Team</strong></p>
|
<p>Kind regards,<br><strong>BookKeepro Team</strong></p>
|
||||||
"""
|
"""
|
||||||
asyncio.get_event_loop().run_until_complete(
|
asyncio.run(
|
||||||
send_email(
|
send_email(
|
||||||
to=user.email,
|
to=user.email,
|
||||||
subject=f"Reminder: {doc_label} Filing Deadline in {label} — BookKeepro",
|
subject=f"Reminder: {doc_label} Filing Deadline in {label} — BookKeepro",
|
||||||
@@ -82,7 +82,7 @@ def _run_deadline_reminders():
|
|||||||
<p><strong>BookKeepro System</strong></p>
|
<p><strong>BookKeepro System</strong></p>
|
||||||
"""
|
"""
|
||||||
for admin_email in admin_emails:
|
for admin_email in admin_emails:
|
||||||
asyncio.get_event_loop().run_until_complete(
|
asyncio.run(
|
||||||
send_email(
|
send_email(
|
||||||
to=admin_email,
|
to=admin_email,
|
||||||
subject=f"Admin Reminder: {user.email} — {doc_label} Deadline in {label}",
|
subject=f"Admin Reminder: {user.email} — {doc_label} Deadline in {label}",
|
||||||
|
|||||||
Reference in New Issue
Block a user