@davoodmehraban89 / Aram-2 Mirror · read-only
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 4, 10:30 UTC

arena/2d4eda07-aram
add-index-html-10623938925177053894 arena/094f314c-aram arena/2d4eda07-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
ts 183 lines 6.72 KB
Raw
1 import type {
2 ApproveResult,
3 BuildResult,
4 CompanyResult,
5 DrillDownResult,
6 LedgerImportResult,
7 MappingImportResult,
8 MappingResult,
9 NoteResult,
10 PreflightResult,
11 StatementsResult,
12 UnknownAccountsResult,
13 } from './types'
14 import { authHeaders, clearSession, setSession, type Identity } from './session'
15
16 const BASE = '/api/v1'
17
18 export class ApiError extends Error {
19 status: number
20 constructor(status: number, message: string) {
21 super(message)
22 this.status = status
23 this.name = 'ApiError'
24 }
25 }
26
27 async function request<T>(path: string, init?: RequestInit): Promise<T> {
28 const res = await fetch(`${BASE}${path}`, {
29 ...init,
30 headers: { ...authHeaders(), ...(init?.headers as Record<string, string> | undefined) },
31 })
32 if (res.status === 401) {
33 // The session is gone (expired, revoked, or never existed): drop it so the
34 // UI returns to the login screen instead of retrying with a dead token.
35 clearSession()
36 }
37 if (!res.ok) {
38 let detail = `HTTP ${res.status}`
39 try {
40 const body = (await res.json()) as { detail?: unknown }
41 if (body.detail !== undefined) {
42 detail = typeof body.detail === 'string' ? body.detail : JSON.stringify(body.detail)
43 }
44 } catch {
45 /* keep default detail */
46 }
47 throw new ApiError(res.status, detail)
48 }
49 return (await res.json()) as T
50 }
51
52 /** Download a file with the session attached (a plain <a href> cannot send it). */
53 async function download(path: string, filename: string): Promise<void> {
54 const res = await fetch(`${BASE}${path}`, { headers: authHeaders() })
55 if (res.status === 401) clearSession()
56 if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`)
57 const url = URL.createObjectURL(await res.blob())
58 try {
59 const link = document.createElement('a')
60 link.href = url
61 link.download = filename
62 document.body.appendChild(link)
63 link.click()
64 link.remove()
65 } finally {
66 URL.revokeObjectURL(url)
67 }
68 }
69
70 function json(body: unknown): RequestInit {
71 return {
72 method: 'POST',
73 headers: { 'Content-Type': 'application/json' },
74 body: JSON.stringify(body),
75 }
76 }
77
78 function multipart(file: File): RequestInit {
79 const form = new FormData()
80 form.append('file', file)
81 return { method: 'POST', body: form }
82 }
83
84 export const api = {
85 createCompany: (code: string, name: string, year: number) =>
86 request<CompanyResult>('/companies', json({ code, name, year })),
87
88 uploadLedger: (yearId: number, file: File) =>
89 request<LedgerImportResult>(`/years/${yearId}/ledger`, multipart(file)),
90
91 createNote: (yearId: number, noteNumber: string, title: string, statement: string, section: string) =>
92 request<NoteResult>(`/years/${yearId}/notes`, json({ note_number: noteNumber, title, statement, section })),
93
94 createMapping: (yearId: number, accountCode: string, targetNoteId: number) =>
95 request<MappingResult>(`/years/${yearId}/mappings`, json({ account_code: accountCode, target_note_id: targetNoteId })),
96
97 buildStatements: (yearId: number) => request<BuildResult>(`/years/${yearId}/statements/build`, { method: 'POST' }),
98
99 listStatements: (yearId: number) => request<StatementsResult>(`/years/${yearId}/statements`),
100
101 drillDown: (lineId: number) => request<DrillDownResult>(`/statement-lines/${lineId}/drilldown`),
102
103 preflight: (yearId: number) => request<PreflightResult>(`/years/${yearId}/preflight`),
104
105 approve: (yearId: number) => request<ApproveResult>(`/years/${yearId}/approve`, { method: 'POST' }),
106
107 unknownAccounts: (yearId: number) => request<UnknownAccountsResult>(`/years/${yearId}/unknown-accounts`),
108
109 importMappings: (yearId: number, file: File) =>
110 request<MappingImportResult>(`/years/${yearId}/mappings/import`, multipart(file)),
111
112 downloadMappings: (yearId: number) =>
113 download(`/years/${yearId}/mappings/export`, `mappings-${yearId}.xlsx`),
114
115 downloadStatements: (yearId: number, format: 'xlsx' | 'json') =>
116 download(`/years/${yearId}/statements/export?format=${format}`, `statements-${yearId}.${format}`),
117
118 listNotes: (yearId: number) =>
119 request<{ notes: { note_id: number; note_number: string; title: string; statement: string; section: string }[] }>(
120 `/years/${yearId}/notes`,
121 ),
122
123 listMappings: (yearId: number) =>
124 request<{ mappings: { mapping_id: number; account_code: string; target_note_id: number; mapping_type: string }[] }>(
125 `/years/${yearId}/mappings`,
126 ),
127
128 updateNote: (yearId: number, noteId: number, patch: { title?: string; note_number?: string; statement?: string; section?: string }) =>
129 request<{ note_id: number; note_number: string; title: string }>(`/years/${yearId}/notes/${noteId}`, {
130 method: 'PUT',
131 headers: { 'Content-Type': 'application/json' },
132 body: JSON.stringify(patch),
133 }),
134
135 deleteNote: (yearId: number, noteId: number) =>
136 request<{ deleted: number }>(`/years/${yearId}/notes/${noteId}`, { method: 'DELETE' }),
137
138 deleteMapping: (yearId: number, mappingId: number) =>
139 request<{ deleted: number }>(`/years/${yearId}/mappings/${mappingId}`, { method: 'DELETE' }),
140
141 login: async (username: string, password: string): Promise<Identity> => {
142 const res = await request<Identity & { token: string }>('/auth/login', json({ username, password }))
143 const who: Identity = { username: res.username, display_name: res.display_name, role: res.role }
144 setSession(res.token, who)
145 return who
146 },
147
148 logout: async (): Promise<void> => {
149 try {
150 await request<{ logged_out: boolean }>('/auth/logout', { method: 'POST' })
151 } finally {
152 clearSession()
153 }
154 },
155
156 me: () => request<Identity>('/auth/me'),
157
158 bootstrapAdmin: (username: string, password: string) =>
159 request<{ username: string; role: string }>('/users', json({ username, password })),
160
161 createUser: (username: string, password: string, role: string) =>
162 request<{ username: string; role: string }>('/users', json({ username, password, role })),
163
164 auditVerify: () => request<{ chain_valid: boolean }>('/audit/verify'),
165
166 lockYear: (yearId: number) =>
167 request<{ year_id: number; status: string }>(`/years/${yearId}/lock`, { method: 'POST' }),
168
169 requestReopen: (yearId: number, reason: string) =>
170 request<{ request_id: number; status: string }>(`/years/${yearId}/reopen/request`, json({ reason })),
171
172 approveReopen: (requestId: number) =>
173 request<{ request_id: number; status: string }>(`/reopen/${requestId}/approve`, { method: 'POST' }),
174
175 reopenYear: (yearId: number) =>
176 request<{ year_id: number; status: string }>(`/years/${yearId}/reopen`, { method: 'POST' }),
177
178 backup: (dest: string) =>
179 request<{ dest: string; manifest: { audit_chain_valid: boolean } }>('/backup', json({ dest })),
180
181 verifyBackup: (dest: string) =>
182 request<{ valid: boolean; source_files: number; audit_entries: number }>('/backup/verify', json({ dest })),
183 }