You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
sims-hq/apps/hq-web/src/api.ts

599 lines
31 KiB
TypeScript

/** HQ web ↔ hq-server client; token survives reloads via localStorage['hq.token']. */
const TOKEN_KEY = 'hq.token'
const NAME_KEY = 'hq.name'
const ROLE_KEY = 'hq.role'
const ID_KEY = 'hq.id'
export function hasSession(): boolean {
return (localStorage.getItem(TOKEN_KEY) ?? '') !== ''
}
export function displayName(): string {
return localStorage.getItem(NAME_KEY) ?? ''
}
/** The signed-in employee's id ('' for sessions minted before it was stored). */
export function staffId(): string {
return localStorage.getItem(ID_KEY) ?? ''
}
/** 'owner' | 'manager' | 'staff' — pages gate write actions on this. */
export function role(): string {
return localStorage.getItem(ROLE_KEY) ?? 'staff'
}
/** True for the managerial roles (owner|manager); mirrors the server-side gate. */
export function isManagerial(): boolean {
const r = role()
return r === 'owner' || r === 'manager'
}
export function clearSession(): void {
localStorage.removeItem(TOKEN_KEY)
localStorage.removeItem(NAME_KEY)
localStorage.removeItem(ROLE_KEY)
localStorage.removeItem(ID_KEY)
}
/**
* Fetch `/api${path}` with the session bearer token. On 401 (outside the login
* call itself) the session is cleared and the app redirects to /login.
*/
export async function apiFetch<T>(path: string, opts?: RequestInit): Promise<T> {
const token = localStorage.getItem(TOKEN_KEY) ?? ''
const res = await fetch(`/api${path}`, {
...opts,
headers: {
'content-type': 'application/json',
...(token !== '' ? { authorization: `Bearer ${token}` } : {}),
...(opts?.headers ?? {}),
},
}).catch(() => undefined)
if (res === undefined) throw new Error('HQ server unreachable — is it running on port 5182?')
if (res.status === 401 && !path.startsWith('/auth/')) {
clearSession()
window.location.hash = '#/login'
throw new Error('Not signed in')
}
const body = (await res.json().catch(() => ({}))) as T & { error?: string }
if (!res.ok) throw new Error(body.error ?? `Server error HTTP ${res.status}`)
return body
}
export async function login(email: string, password: string): Promise<{ displayName: string; role: string }> {
const out = await apiFetch<{ token: string; staff: { id: string; displayName: string; role: string } }>(
'/auth/login',
{ method: 'POST', body: JSON.stringify({ email, password }) },
)
localStorage.setItem(TOKEN_KEY, out.token)
localStorage.setItem(NAME_KEY, out.staff.displayName)
localStorage.setItem(ROLE_KEY, out.staff.role)
localStorage.setItem(ID_KEY, out.staff.id)
return { displayName: out.staff.displayName, role: out.staff.role }
}
export interface EmailStatus { connected: boolean; address?: string; dead: boolean }
export const getEmailStatus = (): Promise<EmailStatus> => apiFetch<EmailStatus>('/email/status')
// ---------- shared server shapes (mirror apps/hq repos — camelCase JSON) ----------
export interface ClientContact { name: string; phone?: string; email?: string; role?: string }
export type ClientStatus = 'lead' | 'active' | 'dormant' | 'lost'
export const CLIENT_STATUSES: ClientStatus[] = ['lead', 'active', 'dormant', 'lost']
export interface Client {
id: string; code: string; name: string; gstin?: string; stateCode: string
address: string; contacts: ClientContact[]; status: ClientStatus; notes: string
/** Account/enquiry owner (→ employee id); absent = unassigned. */
ownerId?: string
}
export type Kind = 'one_time' | 'monthly' | 'yearly' | 'usage'
export const KIND_LABEL: Record<Kind, string> = {
one_time: 'One-time', monthly: 'Monthly', yearly: 'Yearly', usage: 'Usage',
}
export interface Module {
id: string; code: string; name: string; sac: string
allowedKinds: Kind[]; multiSubscription: boolean; active: boolean
quoteContent: string[]
}
export interface ModulePrice {
id: string; moduleId: string; edition: string; kind: Kind
pricePaise: number; effectiveFrom: string
}
export type ClientModuleStatus =
| 'quoted' | 'ordered' | 'installing' | 'installed'
| 'trained' | 'live' | 'expired' | 'cancelled'
export const CLIENT_MODULE_STATUSES: ClientModuleStatus[] = [
'quoted', 'ordered', 'installing', 'installed', 'trained', 'live', 'expired', 'cancelled',
]
export interface ClientModule {
id: string; clientId: string; moduleId: string; status: ClientModuleStatus
kind: Kind; edition: string
installedOn: string | null; completedOn: string | null; trainedOn: string | null
nextRenewal: string | null; active: boolean
}
export type DocType = 'QUOTATION' | 'PROFORMA' | 'INVOICE' | 'RECEIPT' | 'CREDIT_NOTE'
export type DocStatus =
| 'draft' | 'sent' | 'accepted' | 'invoiced' | 'part_paid' | 'paid' | 'lost' | 'cancelled'
export const DOC_STATUSES: DocStatus[] = [
'draft', 'sent', 'accepted', 'invoiced', 'part_paid', 'paid', 'lost', 'cancelled',
]
export interface DocLine {
itemId: string; name: string; hsn: string; qty: number; unitCode: string
unitPricePaise: number; taxablePaise: number; lineTotalPaise: number
}
export interface Doc {
id: string; docType: DocType; docNo: string | null; fy: string; clientId: string
docDate: string; status: DocStatus; refDocId: string | null
taxablePaise: number; cgstPaise: number; sgstPaise: number; igstPaise: number
roundOffPaise: number; payablePaise: number
payload: { lines: DocLine[]; terms?: string; lineContents?: string[][] }
source: string; createdBy: string; createdAt: string
}
export interface DocumentEvent {
id: string; documentId: string; atWall: string; kind: string; meta: Record<string, unknown>
}
/** A public share link for one document (mirrors apps/hq repos-shares — camelCase JSON). */
export interface Share {
id: string; documentId: string; token: string; createdBy: string
createdAt: string; expiresAt: string | null; revoked: boolean
}
/** email_log rows come straight off the table (snake_case). */
export interface EmailLogRow {
id: string; document_id: string | null; to_addr: string; subject: string
status: 'sent' | 'failed'; gmail_message_id: string | null; error: string | null; at_wall: string
}
export type PaymentMode = 'bank' | 'upi' | 'cheque' | 'cash' | 'other'
export const PAYMENT_MODES: PaymentMode[] = ['bank', 'upi', 'cheque', 'cash', 'other']
export interface Payment {
id: string; clientId: string; receivedOn: string; mode: PaymentMode
reference: string; amountPaise: number; tdsPaise: number
createdBy: string; createdAt: string
}
export interface Ledger {
documents: Doc[]; payments: Payment[]; advancePaise: number
modulePaid: { moduleId: string; billedPaise: number; settledPaise: number }[]
}
// ---------- typed calls ----------
export const getClients = (q?: string): Promise<Client[]> =>
apiFetch<{ clients: Client[] }>(`/clients${q !== undefined && q !== '' ? `?q=${encodeURIComponent(q)}` : ''}`)
.then((r) => r.clients)
export const getClient = (id: string): Promise<Client> =>
apiFetch<{ client: Client }>(`/clients/${id}`).then((r) => r.client)
export const createClient = (body: Record<string, unknown>): Promise<Client> =>
apiFetch<{ client: Client }>('/clients', { method: 'POST', body: JSON.stringify(body) }).then((r) => r.client)
export const patchClient = (id: string, body: Record<string, unknown>): Promise<Client> =>
apiFetch<{ client: Client }>(`/clients/${id}`, { method: 'PATCH', body: JSON.stringify(body) }).then((r) => r.client)
/** Assign/clear the account owner — owner/manager only; audited server-side. `null` clears. */
export const setClientOwner = (id: string, ownerId: string | null): Promise<Client> =>
apiFetch<{ client: Client }>(`/clients/${id}/owner`, { method: 'PATCH', body: JSON.stringify({ ownerId }) }).then((r) => r.client)
export const getModules = (): Promise<Module[]> =>
apiFetch<{ modules: Module[] }>('/modules').then((r) => r.modules)
export const createModule = (body: Record<string, unknown>): Promise<Module> =>
apiFetch<{ module: Module }>('/modules', { method: 'POST', body: JSON.stringify(body) }).then((r) => r.module)
export const patchModule = (id: string, body: Record<string, unknown>): Promise<Module> =>
apiFetch<{ module: Module }>(`/modules/${id}`, { method: 'PATCH', body: JSON.stringify(body) }).then((r) => r.module)
export const getPrices = (moduleId: string): Promise<ModulePrice[]> =>
apiFetch<{ prices: ModulePrice[] }>(`/modules/${moduleId}/prices`).then((r) => r.prices)
export const addPrice = (moduleId: string, body: Record<string, unknown>): Promise<ModulePrice[]> =>
apiFetch<{ prices: ModulePrice[] }>(`/modules/${moduleId}/prices`, { method: 'POST', body: JSON.stringify(body) })
.then((r) => r.prices)
export const getClientModules = (clientId: string): Promise<ClientModule[]> =>
apiFetch<{ clientModules: ClientModule[] }>(`/clients/${clientId}/modules`).then((r) => r.clientModules)
export const assignClientModule = (clientId: string, body: Record<string, unknown>): Promise<ClientModule> =>
apiFetch<{ clientModule: ClientModule }>(`/clients/${clientId}/modules`, { method: 'POST', body: JSON.stringify(body) })
.then((r) => r.clientModule)
export const patchClientModule = (id: string, body: Record<string, unknown>): Promise<ClientModule> =>
apiFetch<{ clientModule: ClientModule }>(`/client-modules/${id}`, { method: 'PATCH', body: JSON.stringify(body) })
.then((r) => r.clientModule)
export const getBillingSettings = (): Promise<{ paymentTermsDays: number }> =>
apiFetch<{ paymentTermsDays: number }>('/settings/billing')
/** One Documents-list row: the document plus the server-joined client name (no N+1). */
export type DocListRow = Doc & { clientName: string }
export interface DocumentsPage { documents: DocListRow[]; total: number; page: number; pageSize: number }
/** Server-paginated document list with an honest total (rule 8); filters compose. */
export const getDocuments = (
opts: { type?: DocType; status?: DocStatus; clientId?: string; page?: number; pageSize?: number } = {},
): Promise<DocumentsPage> => {
const p = new URLSearchParams()
if (opts.type !== undefined) p.set('type', opts.type)
if (opts.status !== undefined) p.set('status', opts.status)
if (opts.clientId !== undefined && opts.clientId !== '') p.set('clientId', opts.clientId)
if (opts.page !== undefined) p.set('page', String(opts.page))
if (opts.pageSize !== undefined) p.set('pageSize', String(opts.pageSize))
const q = p.toString()
return apiFetch<DocumentsPage>(`/documents${q === '' ? '' : `?${q}`}`)
}
export const createDocument = (body: Record<string, unknown>): Promise<Doc> =>
apiFetch<{ document: Doc }>('/documents', { method: 'POST', body: JSON.stringify(body) }).then((r) => r.document)
export const getDocumentFull = (id: string): Promise<{ document: Doc; events: DocumentEvent[]; emails: EmailLogRow[]; shares: Share[] }> =>
apiFetch(`/documents/${id}`)
/** issue / status / convert / cancel / credit-note / send — all POST → { document }. */
export const documentAction = (id: string, action: string, body?: Record<string, unknown>): Promise<Doc> =>
apiFetch<{ document: Doc }>(`/documents/${id}/${action}`, {
method: 'POST', body: JSON.stringify(body ?? {}),
}).then((r) => r.document)
/** Mint a public share link for a document. `expiresDays: null` = never expires; omit for the +30d default. */
export const createShare = (id: string, expiresDays?: number | null): Promise<{ share: Share; shares: Share[] }> =>
apiFetch<{ share: Share; shares: Share[] }>(`/documents/${id}/share`, {
method: 'POST', body: JSON.stringify(expiresDays !== undefined ? { expiresDays } : {}),
})
/** Revoke a share (owner-gated, audited); returns the refreshed share list. */
export const revokeShare = (id: string, shareId: string): Promise<{ share: Share; shares: Share[] }> =>
apiFetch<{ share: Share; shares: Share[] }>(`/documents/${id}/share/${shareId}/revoke`, {
method: 'POST', body: '{}',
})
export const recordPayment = (body: Record<string, unknown>): Promise<Payment> =>
apiFetch<{ payment: Payment }>('/payments', { method: 'POST', body: JSON.stringify(body) }).then((r) => r.payment)
export const getLedger = (clientId: string): Promise<Ledger> =>
apiFetch<Ledger>(`/clients/${clientId}/ledger`)
// ---------- employees (staff_user; D16) ----------
export type EmployeeRole = 'owner' | 'manager' | 'staff'
export const EMPLOYEE_ROLES: EmployeeRole[] = ['owner', 'manager', 'staff']
export interface Employee {
id: string; email: string; displayName: string; role: EmployeeRole; active: boolean
phone: string | null; title: string | null
}
/** Full list + server-echoed total (bounded set, no truncation) — any signed-in user. */
export const getEmployees = (): Promise<{ employees: Employee[]; total: number }> =>
apiFetch<{ employees: Employee[]; total: number }>('/employees')
export const createEmployee = (
body: { email: string; displayName: string; role: EmployeeRole; password: string },
): Promise<Employee> =>
apiFetch<{ employee: Employee }>('/employees', { method: 'POST', body: JSON.stringify(body) }).then((r) => r.employee)
/** Email is the login id — immutable; name, role, phone and title may change. */
export const patchEmployee = (
id: string, body: { displayName?: string; role?: EmployeeRole; phone?: string; title?: string },
): Promise<Employee> =>
apiFetch<{ employee: Employee }>(`/employees/${id}`, { method: 'PATCH', body: JSON.stringify(body) }).then((r) => r.employee)
// ---------- self-service profile (D18 WS-E) ----------
export const getMe = (): Promise<Employee> =>
apiFetch<{ employee: Employee }>('/me').then((r) => r.employee)
/** Self-scoped: only name + phone; role/email untouchable server-side. */
export const patchMe = (body: { displayName?: string; phone?: string }): Promise<Employee> =>
apiFetch<{ employee: Employee }>('/me', { method: 'PATCH', body: JSON.stringify(body) })
.then((r) => { if (r.employee.displayName !== '') localStorage.setItem(NAME_KEY, r.employee.displayName); return r.employee })
export const changeMyPassword = (currentPassword: string, newPassword: string): Promise<void> =>
apiFetch<{ ok: boolean }>('/me/password', {
method: 'POST', body: JSON.stringify({ currentPassword, newPassword }),
}).then(() => undefined)
export const deactivateEmployee = (id: string): Promise<Employee> =>
apiFetch<{ employee: Employee }>(`/employees/${id}/deactivate`, { method: 'POST', body: '{}' }).then((r) => r.employee)
export const reactivateEmployee = (id: string): Promise<Employee> =>
apiFetch<{ employee: Employee }>(`/employees/${id}/reactivate`, { method: 'POST', body: '{}' }).then((r) => r.employee)
export const resetEmployeePassword = (id: string, password: string): Promise<Employee> =>
apiFetch<{ employee: Employee }>(`/employees/${id}/password`, {
method: 'POST', body: JSON.stringify({ password }),
}).then((r) => r.employee)
// ---------- pipeline chase-list (D-PIPE; spec §6b/§9) ----------
export type PipelineStage = 'enquiry' | 'new_project' | 'quoted_waiting' | 'won' | 'lost'
export type PipelineBand = 'green' | 'amber' | 'red'
export type PipelineNextAction =
| 'send_quote' | 'waiting' | 'chase' | 'nudge' | 'final_nudge' | 'convert_invoice' | 'none'
export type PipelineFilter = 'all' | 'mine' | 'overdue' | 'lost'
export interface PipelineRow {
clientId: string; clientCode: string; clientName: string
docId: string | null; docNo: string | null; docStatus: string | null
amountPaise: number | null
ownerId: string | null; ownerName: string | null
stage: PipelineStage; ageDays: number | null
nextAction: PipelineNextAction; band: PipelineBand | null
}
export interface PipelinePage {
rows: PipelineRow[]; total: number; page: number; pageSize: number; dayOffsets: number[]
}
/** Server-paginated, role-gated (staff forced to own rows server-side). */
export const getPipeline = (
opts: { filter?: PipelineFilter; owner?: string; page?: number; pageSize?: number } = {},
): Promise<PipelinePage> => {
const p = new URLSearchParams()
if (opts.filter !== undefined) p.set('filter', opts.filter)
if (opts.owner !== undefined && opts.owner !== '') p.set('owner', opts.owner)
if (opts.page !== undefined) p.set('page', String(opts.page))
if (opts.pageSize !== undefined) p.set('pageSize', String(opts.pageSize))
const q = p.toString()
return apiFetch<PipelinePage>(`/pipeline${q === '' ? '' : `?${q}`}`)
}
// ---------- HQ-2 shapes ----------
export type Cadence = 'monthly' | 'yearly'
export interface RecurringPlan {
id: string; clientId: string; clientModuleId: string | null; cadence: Cadence
amountPaise: number | null; nextRun: string; policy: 'auto' | 'manual'; active: boolean
}
export type AmcPaidStatus = 'paid' | 'unpaid' | 'unbilled'
export interface AmcContract {
id: string; clientId: string; coverage: string; periodFrom: string; periodTo: string
amountPaise: number; renewalReminderDays: number; legacyPaid: boolean | null
invoiceDocId: string | null; active: boolean; paidStatus: AmcPaidStatus
}
export interface InteractionType { code: string; label: string }
export type Outcome = 'positive' | 'neutral' | 'negative'
export interface Interaction {
id: string; clientId: string; typeCode: string; onDate: string; staffId: string
notes: string; outcome: Outcome | null; followUpOn: string | null; createdAt: string
}
export type ReminderRuleKind =
| 'invoice_overdue' | 'renewal_due' | 'amc_expiring' | 'follow_up' | 'recurring_generated'
| 'email_bounced' | 'quote_followup'
export type ReminderStatus = 'queued' | 'sent' | 'failed' | 'dismissed'
export interface Reminder {
id: string; ruleKind: ReminderRuleKind; subjectId: string; duePeriod: string; clientId: string
docId: string | null; status: ReminderStatus; policyApplied: 'auto' | 'manual'
error: string | null; createdAt: string; sentAt: string | null
}
/** One queue row: the reminder + server-derived display fields (client name, doc no, owner, label). */
export type QueueItem = Reminder & {
clientName: string; docNo: string | null; ownerId: string | null; label: string
}
export interface DashboardView {
today: string
overdue: { docId: string; docNo: string | null; clientId: string; clientName: string; outstandingPaise: number; daysOverdue: number }[]
dueThisWeek: { planId: string; clientId: string; clientName: string; nextRun: string; amountPaise: number | null }[]
renewalsThisMonth: { clientModuleId: string; clientId: string; clientName: string; nextRenewal: string }[]
followUpsToday: { id: string; clientId: string; clientName: string; onDate: string; followUpOn: string; notes: string }[]
recentPayments: { id: string; clientId: string; clientName: string; receivedOn: string; amountPaise: number; mode: string }[]
queue: QueueItem[]
/** Honest queue size — `queue` is the first page only. */
queueTotal: number
totals: { overduePaise: number; queued: number; failed: number }
}
// ---------- HQ-2 calls ----------
export const getDashboard = (): Promise<DashboardView> =>
apiFetch<{ view: DashboardView }>('/dashboard').then((r) => r.view)
export interface RemindersPage { reminders: QueueItem[]; total: number; page: number; pageSize: number }
/**
* Viewer-scoped, paginated queue slice + honest total (staff are server-forced to their
* own rows). No `status` = the working set (queued|failed); `owner` narrows — managerial only.
*/
export const getReminders = (
opts: { status?: ReminderStatus; owner?: string; page?: number; pageSize?: number } = {},
): Promise<RemindersPage> => {
const p = new URLSearchParams()
if (opts.status !== undefined) p.set('status', opts.status)
if (opts.owner !== undefined && opts.owner !== '') p.set('owner', opts.owner)
if (opts.page !== undefined) p.set('page', String(opts.page))
if (opts.pageSize !== undefined) p.set('pageSize', String(opts.pageSize))
const q = p.toString()
return apiFetch<RemindersPage>(`/reminders${q === '' ? '' : `?${q}`}`)
}
export const sendReminder = (id: string): Promise<Reminder> =>
apiFetch<{ reminder: Reminder }>(`/reminders/${id}/send`, { method: 'POST', body: '{}' }).then((r) => r.reminder)
export const dismissReminder = (id: string): Promise<Reminder> =>
apiFetch<{ reminder: Reminder }>(`/reminders/${id}/dismiss`, { method: 'POST', body: '{}' }).then((r) => r.reminder)
export const getRecurringPlans = (clientId: string): Promise<RecurringPlan[]> =>
apiFetch<{ plans: RecurringPlan[] }>(`/recurring?clientId=${clientId}`).then((r) => r.plans)
export const createRecurringPlan = (clientId: string, body: Record<string, unknown>): Promise<RecurringPlan> =>
apiFetch<{ plan: RecurringPlan }>(`/clients/${clientId}/recurring`, { method: 'POST', body: JSON.stringify(body) }).then((r) => r.plan)
export const updateRecurringPlan = (id: string, body: Record<string, unknown>): Promise<RecurringPlan> =>
apiFetch<{ plan: RecurringPlan }>(`/recurring/${id}`, { method: 'PATCH', body: JSON.stringify(body) }).then((r) => r.plan)
export const deactivateRecurringPlan = (id: string): Promise<RecurringPlan> =>
apiFetch<{ plan: RecurringPlan }>(`/recurring/${id}/deactivate`, { method: 'POST', body: '{}' }).then((r) => r.plan)
export const getAmc = (clientId: string): Promise<AmcContract[]> =>
apiFetch<{ contracts: AmcContract[] }>(`/clients/${clientId}/amc`).then((r) => r.contracts)
export const createAmc = (clientId: string, body: Record<string, unknown>): Promise<AmcContract> =>
apiFetch<{ contract: AmcContract }>(`/clients/${clientId}/amc`, { method: 'POST', body: JSON.stringify(body) }).then((r) => r.contract)
export const updateAmc = (id: string, body: Record<string, unknown>): Promise<AmcContract> =>
apiFetch<{ contract: AmcContract }>(`/amc/${id}`, { method: 'PATCH', body: JSON.stringify(body) }).then((r) => r.contract)
export const deactivateAmc = (id: string): Promise<AmcContract> =>
apiFetch<{ contract: AmcContract }>(`/amc/${id}/deactivate`, { method: 'POST', body: '{}' }).then((r) => r.contract)
export const generateAmcRenewalInvoice = (id: string): Promise<Doc> =>
apiFetch<{ document: Doc }>(`/amc/${id}/renewal-invoice`, { method: 'POST', body: '{}' }).then((r) => r.document)
export const getInteractionTypes = (): Promise<InteractionType[]> =>
apiFetch<{ types: InteractionType[] }>('/interaction-types').then((r) => r.types)
export const getInteractions = (clientId: string): Promise<Interaction[]> =>
apiFetch<{ interactions: Interaction[] }>(`/clients/${clientId}/interactions`).then((r) => r.interactions)
export const createInteraction = (clientId: string, body: Record<string, unknown>): Promise<Interaction> =>
apiFetch<{ interaction: Interaction }>(`/clients/${clientId}/interactions`, { method: 'POST', body: JSON.stringify(body) }).then((r) => r.interaction)
export const updateInteraction = (id: string, body: Record<string, unknown>): Promise<Interaction> =>
apiFetch<{ interaction: Interaction }>(`/interactions/${id}`, { method: 'PATCH', body: JSON.stringify(body) }).then((r) => r.interaction)
// ---------- HQ-3a shapes ----------
export interface DuesAgingRow {
clientId: string; clientName: string
b0_30: number; b31_60: number; b61_90: number; b90p: number; totalPaise: number
}
export interface ModuleRevenueRow {
moduleId: string; moduleCode: string; moduleName: string; billedPaise: number; settledPaise: number
}
export interface ProfitabilityRow {
clientId: string; clientName: string
billedPaise: number; settledPaise: number; awsCostPaise: number; marginPaise: number
}
export interface CostRankRow { clientId: string; clientName: string; costPaise: number; sharePctBp: number }
export interface AwsUsageRow {
id: string; clientId: string; month: string
storageGb: number; transferGb: number; costPaise: number; source: 'auto' | 'manual'; updatedAt: string
}
// ---------- HQ-3a calls ----------
const rangeQs = (from?: string, to?: string): string => {
const p = new URLSearchParams()
if (from !== undefined && from !== '') p.set('from', from)
if (to !== undefined && to !== '') p.set('to', to)
const q = p.toString()
return q === '' ? '' : `?${q}`
}
export const getDuesAging = (): Promise<DuesAgingRow[]> =>
apiFetch<{ rows: DuesAgingRow[] }>('/reports/dues-aging').then((r) => r.rows)
export const getModuleRevenue = (from?: string, to?: string): Promise<ModuleRevenueRow[]> =>
apiFetch<{ rows: ModuleRevenueRow[] }>(`/reports/module-revenue${rangeQs(from, to)}`).then((r) => r.rows)
export const getProfitability = (from?: string, to?: string): Promise<ProfitabilityRow[]> =>
apiFetch<{ rows: ProfitabilityRow[] }>(`/reports/profitability${rangeQs(from, to)}`).then((r) => r.rows)
export const getAwsRanking = (month?: string): Promise<{ month: string; total: number; rows: CostRankRow[] }> =>
apiFetch<{ month: string; total: number; rows: CostRankRow[] }>(`/aws/ranking${month !== undefined && month !== '' ? `?month=${month}` : ''}`)
export const getClientAwsUsage = (clientId: string): Promise<AwsUsageRow[]> =>
apiFetch<{ usage: AwsUsageRow[] }>(`/clients/${clientId}/aws-usage`).then((r) => r.usage)
export const upsertAwsUsage = (body: Record<string, unknown>): Promise<AwsUsageRow> =>
apiFetch<{ usage: AwsUsageRow }>('/aws/usage', { method: 'POST', body: JSON.stringify(body) }).then((r) => r.usage)
export const pullAwsCosts = (month?: string): Promise<{ upserted: number; totalPaise: number; unknownTags: { tag: string; costPaise: number }[] }> =>
apiFetch('/aws/pull', { method: 'POST', body: JSON.stringify(month !== undefined ? { month } : {}) })
export const getCompanyProfile = (): Promise<Record<string, string>> =>
apiFetch<{ company: Record<string, string> }>('/settings/company').then((r) => r.company)
export const putCompanyProfile = (body: Record<string, string>): Promise<Record<string, string>> =>
apiFetch<{ company: Record<string, string> }>('/settings/company', { method: 'PUT', body: JSON.stringify(body) }).then((r) => r.company)
export const getTemplateSettings = (): Promise<Record<string, string>> =>
apiFetch<{ settings: Record<string, string> }>('/settings/template').then((r) => r.settings)
export const putTemplateSettings = (
body: { company?: Record<string, string>; template?: Record<string, string>; titles?: Record<string, string> },
): Promise<Record<string, string>> =>
apiFetch<{ settings: Record<string, string> }>('/settings/template', { method: 'PUT', body: JSON.stringify(body) }).then((r) => r.settings)
export const uploadTemplateLogo = (dataUri: string): Promise<string> =>
apiFetch<{ logo: string }>('/settings/template/logo', { method: 'POST', body: JSON.stringify({ dataUri }) }).then((r) => r.logo)
// ---------- module → client roster (spec §10) ----------
export interface ModuleClientRow {
clientId: string; clientName: string; clientCode: string
status: string; kind: Kind; edition: string
nextRenewal: string | null; pricePaise: number | null
}
export interface ModuleClientsPage {
clients: ModuleClientRow[]; total: number; page: number; pageSize: number; totalPricePaise: number
}
export const getModuleClients = (moduleId: string, page = 1): Promise<ModuleClientsPage> =>
apiFetch<ModuleClientsPage & { ok: boolean }>(`/modules/${moduleId}/clients?page=${page}`)
export const notifyModuleClients = (
moduleId: string, body: { subject: string; body: string },
): Promise<{ sent: number; total: number; failed: { client: string; error: string }[] }> =>
apiFetch(`/modules/${moduleId}/notify`, { method: 'POST', body: JSON.stringify(body) })
/** CSV export needs the bearer header an <a href> can't carry — blob + transient anchor. */
export async function downloadModuleClientsCsv(moduleId: string, moduleCode: string): Promise<void> {
const token = localStorage.getItem(TOKEN_KEY) ?? ''
const res = await fetch(`/api/modules/${moduleId}/clients.csv`, {
headers: token !== '' ? { authorization: `Bearer ${token}` } : {},
})
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string }
throw new Error(body.error ?? `CSV failed: HTTP ${res.status}`)
}
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `module-${moduleCode}-clients.csv`
document.body.appendChild(a)
a.click()
a.remove()
URL.revokeObjectURL(url)
}
/** The PDF route needs the bearer header, which an <iframe src> can't carry — fetch a blob instead. */
export async function fetchPdfBlob(documentId: string): Promise<Blob> {
const token = localStorage.getItem(TOKEN_KEY) ?? ''
const res = await fetch(`/api/documents/${documentId}/pdf`, {
headers: token !== '' ? { authorization: `Bearer ${token}` } : {},
})
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string }
throw new Error(body.error ?? `PDF failed: HTTP ${res.status}`)
}
return res.blob()
}
/**
* Download the document PDF as a file. Hits `?download=1` (attachment disposition) but,
* because the route needs the bearer header an <a href> can't carry, fetches a blob and
* saves it via a transient object-URL anchor named after the doc-no (slugged, `/` → `-`).
*/
export async function downloadDocumentPdf(documentId: string, docNo: string | null): Promise<void> {
const token = localStorage.getItem(TOKEN_KEY) ?? ''
const res = await fetch(`/api/documents/${documentId}/pdf?download=1`, {
headers: token !== '' ? { authorization: `Bearer ${token}` } : {},
})
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string }
throw new Error(body.error ?? `PDF failed: HTTP ${res.status}`)
}
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `${(docNo ?? 'draft').replaceAll('/', '-')}.pdf`
document.body.appendChild(a)
a.click()
a.remove()
URL.revokeObjectURL(url)
}
export interface DocTotals {
taxablePaise: number; cgstPaise: number; sgstPaise: number
igstPaise: number; roundOffPaise: number; payablePaise: number
}
export interface DocPreview { html: string; totals: DocTotals; warnings: string[] }
/**
* Dedicated preview POST (mirrors fetchPdfBlob): carries the bearer token and the
* AbortSignal, and — unlike apiFetch — lets an aborted fetch reject as AbortError
* so LivePreview can silently drop superseded requests instead of surfacing a
* spurious "server unreachable".
*/
async function postPreview<T>(path: string, body: unknown, signal?: AbortSignal): Promise<T> {
const token = localStorage.getItem(TOKEN_KEY) ?? ''
const res = await fetch(`/api${path}`, {
method: 'POST', signal,
headers: { 'content-type': 'application/json', ...(token !== '' ? { authorization: `Bearer ${token}` } : {}) },
body: JSON.stringify(body),
})
const json = (await res.json().catch(() => ({}))) as T & { error?: string }
if (!res.ok) throw new Error((json as { error?: string }).error ?? `Preview failed: HTTP ${res.status}`)
return json
}
export const previewDocument = (body: unknown, signal?: AbortSignal): Promise<DocPreview> =>
postPreview<DocPreview>('/documents/preview', body, signal)
export const previewSample = (body: unknown, signal?: AbortSignal): Promise<{ html: string }> =>
postPreview<{ html: string }>('/previews/sample', body, signal)
export const getReminderPreview = (id: string): Promise<{ subject: string; body: string }> =>
apiFetch<{ subject: string; body: string }>(`/reminders/${id}/preview`)