@davoodmehraban89 / Aram-1 / commits / 14b467b
Fork 0

Implement Phase 6 export services and UI foundation

Add export services under backend/app/export/ for CSV downloads and PDF-ready structure payloads. Add frontend HTML/JS dashboard under backend/static/index.html decoupled from accounting logic. Add automated integration tests in test_export.py (65/65 total tests passing). Preserve snapshot immutability and accounting calculation engine without refactoring. Co-authored-by: davoodmehraban89 <57283229+davoodmehraban89@users.noreply.github.com>

google-labs-jules[bot] committed Aug 23, 2026 at 09:12 UTC 14b467b6cbf162132f81076f0dd190d964e01e83
5 files changed +262
backend/app/export/endpoints.py new
+55
@@ -0,0 +1,55 @@
1 +from typing import Dict, Any
2 +from fastapi import APIRouter, Depends, Query, Response, status
3 +from sqlalchemy.orm import Session
4 +
5 +from backend.app.database import get_db
6 +from backend.app.api.auth import get_current_user
7 +from backend.app.accounting.service import generate_financial_statements
8 +from backend.app.accounting.snapshot import get_snapshots_for_year
9 +from backend.app.export.service import export_statement_to_csv, export_statement_to_pdf_structure
10 +
11 +router = APIRouter()
12 +
13 +
14 +@router.get("/export/csv")
15 +def export_statement_csv(
16 + year_id: int = Query(..., description="Fiscal Year ID"),
17 + statement_type: str = Query("TB", description="Statement Type (TB, BS, IS)"),
18 + db: Session = Depends(get_db),
19 + user: Dict[str, Any] = Depends(get_current_user),
20 +):
21 + """Exports specified financial statement calculation to CSV file response."""
22 + statements = generate_financial_statements(db, year_id=year_id)
23 + if statement_type == "BS":
24 + data = statements["balance_sheet"]
25 + elif statement_type == "IS":
26 + data = statements["income_statement"]
27 + else:
28 + data = statements["trial_balance"]
29 +
30 + csv_content = export_statement_to_csv(data)
31 + filename = f"{statement_type}_year_{year_id}.csv"
32 + return Response(
33 + content=csv_content,
34 + media_type="text/csv",
35 + headers={"Content-Disposition": f"attachment; filename={filename}"}
36 + )
37 +
38 +
39 +@router.get("/export/pdf-structure")
40 +def export_statement_pdf_structure(
41 + year_id: int = Query(..., description="Fiscal Year ID"),
42 + statement_type: str = Query("TB", description="Statement Type (TB, BS, IS)"),
43 + db: Session = Depends(get_db),
44 + user: Dict[str, Any] = Depends(get_current_user),
45 +):
46 + """Returns PDF-ready structured payload for financial statement."""
47 + statements = generate_financial_statements(db, year_id=year_id)
48 + if statement_type == "BS":
49 + data = statements["balance_sheet"]
50 + elif statement_type == "IS":
51 + data = statements["income_statement"]
52 + else:
53 + data = statements["trial_balance"]
54 +
55 + return export_statement_to_pdf_structure(data)
backend/app/export/service.py new
+50
@@ -0,0 +1,50 @@
1 +import csv
2 +import io
3 +from typing import Dict, Any
4 +
5 +
6 +def export_statement_to_csv(statement_data: Dict[str, Any]) -> str:
7 + """Exports financial statement calculation dict to CSV string."""
8 + output = io.StringIO()
9 + writer = csv.writer(output)
10 +
11 + stmt_type = statement_data.get("statement_type", "REPORT")
12 + title = statement_data.get("title", "Financial Statement")
13 + writer.writerow(["Statement", title, f"Type: {stmt_type}"])
14 + writer.writerow([])
15 +
16 + if stmt_type == "TB":
17 + writer.writerow(["Account Code", "Account Name", "Total Debit", "Total Credit", "Net Balance"])
18 + for row in statement_data.get("rows", []):
19 + writer.writerow([
20 + row.get("account_code", ""),
21 + row.get("account_name", ""),
22 + row.get("total_debit", 0.0),
23 + row.get("total_credit", 0.0),
24 + row.get("net_balance", 0.0),
25 + ])
26 + writer.writerow([])
27 + writer.writerow(["TOTALS", "", statement_data.get("total_debit", 0.0), statement_data.get("total_credit", 0.0), ""])
28 + elif stmt_type in ("BS", "IS"):
29 + writer.writerow(["Section", "Group Name", "Amount"])
30 + sections = statement_data.get("sections", {})
31 + for sec_name, groups in sections.items():
32 + for group_name, amount in groups.items():
33 + writer.writerow([sec_name, group_name, amount])
34 +
35 + return output.getvalue()
36 +
37 +
38 +def export_statement_to_pdf_structure(statement_data: Dict[str, Any]) -> Dict[str, Any]:
39 + """Formats financial statement dict into structured payload ready for PDF rendering."""
40 + return {
41 + "title": statement_data.get("title", "Financial Statement"),
42 + "statement_type": statement_data.get("statement_type"),
43 + "formatted_totals": {
44 + "total_debit": f"{statement_data.get('total_debit', 0.0):,.2f}" if "total_debit" in statement_data else None,
45 + "total_credit": f"{statement_data.get('total_credit', 0.0):,.2f}" if "total_credit" in statement_data else None,
46 + "net_profit": f"{statement_data.get('net_profit', 0.0):,.2f}" if "net_profit" in statement_data else None,
47 + "total_assets": f"{statement_data.get('total_assets', 0.0):,.2f}" if "total_assets" in statement_data else None,
48 + },
49 + "raw_data": statement_data,
50 + }
backend/app/main.py
+2
@@ -1,6 +1,7 @@
1 from fastapi import FastAPI
2 from backend.app.config import settings
3 from backend.app.api.endpoints import router as api_router
4 +from backend.app.export.endpoints import router as export_router
5
6 app = FastAPI(
7 title=settings.PROJECT_NAME,
@@ -9,6 +10,7 @@ app = FastAPI(
10 )
11
12 app.include_router(api_router, prefix=settings.API_V1_STR)
13 +app.include_router(export_router, prefix=settings.API_V1_STR)
14
15 @app.get("/")
16 def root():
backend/static/index.html new
+103
@@ -0,0 +1,103 @@
1 +<!DOCTYPE html>
2 +<html lang="fa" dir="rtl">
3 +<head>
4 + <meta charset="UTF-8">
5 + <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 + <title>پلتفرم گزارش‌گری مالی - سامانه مدیریت صورت‌های مالی</title>
7 + <style>
8 + body { font-family: Tahoma, Arial, sans-serif; background-color: #f4f6f9; margin: 0; padding: 20px; direction: rtl; }
9 + .header { background-color: #1e293b; color: #fff; padding: 15px 20px; border-radius: 8px; margin-bottom: 20px; }
10 + .nav-tabs { display: flex; gap: 10px; margin-bottom: 20px; }
11 + .tab-btn { padding: 10px 18px; border: none; background-color: #e2e8f0; cursor: pointer; border-radius: 6px; font-weight: bold; }
12 + .tab-btn.active { background-color: #2563eb; color: #fff; }
13 + .card { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 20px; }
14 + table { width: 100%; border-collapse: collapse; margin-top: 15px; }
15 + th, td { border: 1px solid #cbd5e1; padding: 10px; text-align: right; }
16 + th { background-color: #f1f5f9; }
17 + .badge { padding: 4px 8px; border-radius: 4px; font-size: 0.85em; font-weight: bold; }
18 + .badge-draft { background-color: #fef08a; color: #854d0e; }
19 + .badge-approved { background-color: #bbf7d0; color: #166534; }
20 + </style>
21 +</head>
22 +<body>
23 + <div class="header">
24 + <h2>پلتفرم گزارش‌گری مالی (Financial Reporting Platform V2)</h2>
25 + <p>داشبورد مشاهده صورت‌های مالی، تراز آزمایشی و تاریخچه اسنپ‌شات‌ها</p>
26 + </div>
27 +
28 + <div class="nav-tabs">
29 + <button class="tab-btn active" onclick="switchTab('tb')">تراز آزمایشی (TB)</button>
30 + <button class="tab-btn" onclick="switchTab('bs')">ترازنامه (BS)</button>
31 + <button class="tab-btn" onclick="switchTab('is')">صورت سود و زیان (IS)</button>
32 + <button class="tab-btn" onclick="switchTab('snapshots')">تاریخچه اسنپ‌شات‌ها</button>
33 + </div>
34 +
35 + <div id="content-area" class="card">
36 + <h3>در حال بارگذاری اطلاعات از API...</h3>
37 + </div>
38 +
39 + <script>
40 + const API_BASE = '/api/v1';
41 +
42 + async function fetchReport(type) {
43 + const area = document.getElementById('content-area');
44 + area.innerHTML = '<h3>در حال فراخوانی داده‌ها...</h3>';
45 + try {
46 + const res = await fetch(`${API_BASE}/reporting/${type}?year_id=1`);
47 + const data = await res.json();
48 + renderReport(type, data);
49 + } catch (e) {
50 + area.innerHTML = '<h3 style="color:red;">خطا در دریافت داده‌ها از API. لطفاً از فعال بودن سرور مطمئن شوید.</h3>';
51 + }
52 + }
53 +
54 + function renderReport(type, data) {
55 + const area = document.getElementById('content-area');
56 + let html = `<h3>${data.title || type}</h3>`;
57 + if (type === 'trial-balance') {
58 + html += `
59 + <p>مجموع بدهکار: <strong>${data.total_debit.toLocaleString()}</strong> | مجموع بستانکار: <strong>${data.total_credit.toLocaleString()}</strong></p>
60 + <table>
61 + <thead><tr><th>کد حساب</th><th>نام حساب</th><th>بدهکار</th><th>بستانکار</th><th>مانده خالص</th></tr></thead>
62 + <tbody>
63 + ${data.rows.map(r => `<tr><td>${r.account_code}</td><td>${r.account_name}</td><td>${r.total_debit.toLocaleString()}</td><td>${r.total_credit.toLocaleString()}</td><td>${r.net_balance.toLocaleString()}</td></tr>`).join('')}
64 + </tbody>
65 + </table>
66 + `;
67 + } else {
68 + html += '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
69 + }
70 + area.innerHTML = html;
71 + }
72 +
73 + function switchTab(tab) {
74 + document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
75 + event.target.classList.add('active');
76 + if (tab === 'tb') fetchReport('trial-balance');
77 + else if (tab === 'bs') fetchReport('balance-sheet');
78 + else if (tab === 'is') fetchReport('income-statement');
79 + else fetchSnapshots();
80 + }
81 +
82 + async function fetchSnapshots() {
83 + const area = document.getElementById('content-area');
84 + area.innerHTML = '<h3>در حال فراخوانی تاریخچه اسنپ‌شات‌ها...</h3>';
85 + try {
86 + const res = await fetch(`${API_BASE}/snapshots?year_id=1`);
87 + const data = await res.json();
88 + let html = '<h3>تاریخچه اسنپ‌شات‌های صورت‌های مالی</h3><table><thead><tr><th>نسخه</th><th>وضعیت بررسی</th><th>ایجاد کننده</th><th>توضیحات</th></tr></thead><tbody>';
89 + data.forEach(s => {
90 + html += `<tr><td>نسخه ${s.version}</td><td><span class="badge badge-draft">${s.status}</span></td><td>${s.created_by || '-'}</td><td>${s.notes || '-'}</td></tr>`;
91 + });
92 + html += '</tbody></table>';
93 + area.innerHTML = html;
94 + } catch (e) {
95 + area.innerHTML = '<h3 style="color:red;">خطا در دریافت اسنپ‌شات‌ها.</h3>';
96 + }
97 + }
98 +
99 + // Default load
100 + fetchReport('trial-balance');
101 + </script>
102 +</body>
103 +</html>
backend/tests/test_export.py new
+52
@@ -0,0 +1,52 @@
1 +import pytest
2 +from backend.app.models import Company, FiscalYear, FiscalYearStatus, SourceDocument, NormalizedFinancialRecord
3 +
4 +
5 +def test_csv_export_endpoint(client, db_session):
6 + comp = Company(code="EXP1", name="Export Corp 1")
7 + db_session.add(comp)
8 + db_session.commit()
9 +
10 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
11 + db_session.add(fy)
12 + db_session.commit()
13 +
14 + doc = SourceDocument(year_id=fy.id, filename="ledger.csv", file_hash="hex1", doc_type="ledger")
15 + db_session.add(doc)
16 + db_session.commit()
17 +
18 + rec = NormalizedFinancialRecord(
19 + year_id=fy.id,
20 + source_document_id=doc.id,
21 + row_index=1,
22 + account_code="1101",
23 + account_name="Cash",
24 + debit=1000.0,
25 + credit=0.0,
26 + net_amount=1000.0,
27 + )
28 + db_session.add(rec)
29 + db_session.commit()
30 +
31 + res = client.get(f"/api/v1/export/csv?year_id={fy.id}&statement_type=TB")
32 + assert res.status_code == 200
33 + assert "text/csv" in res.headers["content-type"]
34 + assert "1101" in res.text
35 + assert "Cash" in res.text
36 +
37 +
38 +def test_pdf_structure_export_endpoint(client, db_session):
39 + comp = Company(code="EXP2", name="Export Corp 2")
40 + db_session.add(comp)
41 + db_session.commit()
42 +
43 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
44 + db_session.add(fy)
45 + db_session.commit()
46 +
47 + res = client.get(f"/api/v1/export/pdf-structure?year_id={fy.id}&statement_type=TB")
48 + assert res.status_code == 200
49 + data = res.json()
50 + assert "title" in data
51 + assert "formatted_totals" in data
52 + assert "raw_data" in data