@fayz-ai/financial 0.1.13 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/store.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/store.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAsBO,SAAS,2BAAA,GAAqD;AACnE,EAAA,OAAO,sBAAA,CAAuB,iCAAiC,2BAA2B,CAAA;AAC5F;AAiEA,SAAS,UAAU,GAAA,EAAkC;AACnD,EAAA,OAAO,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,MAAA;AAC9C;AAGO,SAAS,qBAAqB,QAAA,EAA6D;AAChG,EAAA,MAAM,QAAA,uBAAe,GAAA,EAA8B;AACnD,EAAA,SAAS,KAAA,CAAS,KAAa,IAAA,EAAoC;AACjE,IAAA,MAAM,OAAA,GAAU,QAAA,CAAS,GAAA,CAAI,GAAG,CAAA;AAChC,IAAA,IAAI,SAAS,OAAO,OAAA;AACpB,IAAA,MAAM,OAAA,GAAU,MAAK,CAAE,OAAA,CAAQ,MAAM,QAAA,CAAS,MAAA,CAAO,GAAG,CAAC,CAAA;AACzD,IAAA,QAAA,CAAS,GAAA,CAAI,KAAK,OAAO,CAAA;AACzB,IAAA,OAAO,OAAA;AAAA,EACT;AAEA,EAAA,OAAO,WAAA,CAA8B,CAAC,GAAA,EAAK,GAAA,MAAS;AAAA,IAClD,UAAU,EAAC;AAAA,IACX,aAAA,EAAe,CAAA;AAAA,IACf,eAAA,EAAiB,KAAA;AAAA,IACjB,cAAc,EAAC;AAAA,IAEf,WAAW,EAAC;AAAA,IACZ,cAAA,EAAgB,CAAA;AAAA,IAChB,gBAAA,EAAkB,KAAA;AAAA,IAElB,cAAc,EAAC;AAAA,IACf,mBAAA,EAAqB,KAAA;AAAA,IAErB,aAAa,EAAC;AAAA,IACd,kBAAA,EAAoB,KAAA;AAAA,IACpB,cAAc,EAAC;AAAA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AgB;AACpD,QAAA,GAAA,CAAI,EAAE,cAAc,CAAA;AACpB,QAAA,KAAA,CAAM,QAAQ,qBAAqB,CAAA;AACnC,QAAA,OAAO,OAAA;AAAA,MACT,SAAS,GAAA,EAAK;AACZ,QAAA,KAAA,CAAM,MAAM,wBAAA,EAA0B,EAAE,aAAa,SAAA,CAAU,GAAG,GAAG,CAAA;AACrE,QAAA,MAAM,GAAA;AAAA,MACR;AAAA,IACF,CAAA;AAAA,IAEA,MAAM,iBAAiB,KAAA,EAAO;AAC5B,MAAA,IAAI;AACF,QAAA,MAAM,OAAA,GAAU,MAAM,QAAA,CAAS,gBAAA,CAAiB,KAAK,CAAA;AACrD,QAAA,MAAM,YAAA,GAAe,MAAM,QAAA,CAAS,eAAA,EAAgB;AACpD,QAAA,GAAA,CAAI,EAAE,cAAc,CAAA;AACpB,QAAA,KAAA,CAAM,QAAQ,qBAAqB,CAAA;AACnC,QAAA,OAAO,OAAA;AAAA,MACT,SAAS,GAAA,EAAK;AACZ,QAAA,KAAA,CAAM,MAAM,yBAAA,EAA2B,EAAE,aAAa,SAAA,CAAU,GAAG,GAAG,CAAA;AACtE,QAAA,MAAM,GAAA;AAAA,MACR;AAAA,IACF,CAAA;AAAA,IAEA,wBAAwB,IAAA,EAAM;AAC5B,MAAA,GAAA,CAAI,EAAE,oBAAA,EAAsB,IAAA,EAAM,CAAA;AAAA,IACpC;AAAA,GACF,CAAE,CAAA;AACJ","file":"store.js","sourcesContent":["import { createStore, type StoreApi } from 'zustand/vanilla'\nimport { createSafeDataProvider, reportDataError } from '@fayz-ai/core'\nimport { toast } from '@fayz-ai/ui'\nimport { createMockFinancialProvider } from './data/mock'\nimport type { FinancialDataProvider } from './data/provider'\nimport { createSupabaseFinancialProvider } from './data/supabase'\nimport type { BankAccount } from './domain/account'\nimport type { CardTransaction } from './domain/card'\nimport type { CashSession, CloseCashSessionInput, OpenCashSessionInput } from './domain/cash-session'\nimport type { CommissionEntry, CommissionGenerationResult, CommissionQuery, GenerateCommissionsInput } from './domain/commission'\nimport {\n listsProvisioned, withProvisioned,\n type CancelInvoiceInput, type CreateInvoiceInput, type Invoice, type InvoiceQuery,\n} from './domain/invoice'\nimport type { FinancialMovement, PayMovementInput } from './domain/movement'\nimport type { PaymentMethod, PaymentMethodType } from './domain/payment-method'\nimport type { DateRange } from './domain/query'\nimport type { FinancialSummary } from './domain/report'\nimport type { StatementQuery, StatementResult } from './domain/statement'\nimport type { CreateTransferInput } from './domain/transfer'\n\n/** Supabase when a client is initialized, else the in-memory mock, resolved on first use. */\nexport function createSafeFinancialProvider(): FinancialDataProvider {\n return createSafeDataProvider(createSupabaseFinancialProvider, createMockFinancialProvider)\n}\n\nexport interface FinancialUIState {\n // Data cache\n invoices: Invoice[]\n invoicesTotal: number\n invoicesLoading: boolean\n invoiceQuery: InvoiceQuery\n\n movements: FinancialMovement[]\n movementsTotal: number\n movementsLoading: boolean\n\n bankAccounts: BankAccount[]\n bankAccountsLoading: boolean\n\n commissions: CommissionEntry[]\n commissionsLoading: boolean\n cashSessions: CashSession[]\n cashSessionsLoading: boolean\n /** The abertura/fechamento dialog lives in the SHELL header (CashSessionHeaderControl),\n * outside any page's tree — a page button that wants to open \"the same modal\"\n * has to flip a flag both sides share, not local state of its own. */\n cashSessionModalOpen: boolean\n\n paymentMethods: PaymentMethod[]\n paymentMethodTypes: PaymentMethodType[]\n\n summary: FinancialSummary | null\n summaryLoading: boolean\n\n statement: StatementResult | null\n statementLoading: boolean\n statementQuery: StatementQuery | null\n\n cardTransactions: CardTransaction[]\n cardsLoading: boolean\n\n // Actions\n fetchSummary(dateRange?: DateRange): Promise<void>\n fetchInvoices(query: InvoiceQuery): Promise<void>\n fetchBankAccounts(): Promise<void>\n fetchCashSessions(bankAccountId?: string): Promise<void>\n fetchCommissions(query: CommissionQuery): Promise<void>\n generateCommissions(input: GenerateCommissionsInput): Promise<CommissionGenerationResult | null>\n fetchPaymentMethods(): Promise<void>\n fetchStatement(query: StatementQuery): Promise<void>\n fetchCardTransactions(dateRange?: DateRange): Promise<void>\n createInvoice(input: CreateInvoiceInput): Promise<Invoice>\n /** FAY-1225 \"log money in a few taps\": one call → the right provider plumbing + full surface refresh. */\n payMovement(input: PayMovementInput): Promise<void>\n reverseMovement(movementId: string, reason: string): Promise<void>\n /** Reverses several payments (all of an installment) with one refresh and one toast. */\n reverseMovements(movementIds: string[], reason: string): Promise<void>\n createTransfer(input: CreateTransferInput): Promise<void>\n cancelInvoice(input: CancelInvoiceInput): Promise<void>\n openCashSession(input: OpenCashSessionInput): Promise<CashSession>\n closeCashSession(input: CloseCashSessionInput): Promise<CashSession>\n setCashSessionModalOpen(open: boolean): void\n}\n\n// ---------------------------------------------------------------------------\n// Store factory\n// ---------------------------------------------------------------------------\n\nfunction errorText(err: unknown): string | undefined {\n return err instanceof Error ? err.message : undefined\n}\n\n/** One store per provider. Concurrent reads of the same key share one request. */\nexport function createFinancialStore(provider: FinancialDataProvider): StoreApi<FinancialUIState> {\n const inflight = new Map<string, Promise<unknown>>()\n function dedup<T>(key: string, read: () => Promise<T>): Promise<T> {\n const running = inflight.get(key) as Promise<T> | undefined\n if (running) return running\n const promise = read().finally(() => inflight.delete(key))\n inflight.set(key, promise)\n return promise\n }\n\n return createStore<FinancialUIState>((set, get) => ({\n invoices: [],\n invoicesTotal: 0,\n invoicesLoading: false,\n invoiceQuery: {},\n\n movements: [],\n movementsTotal: 0,\n movementsLoading: false,\n\n bankAccounts: [],\n bankAccountsLoading: false,\n\n commissions: [],\n commissionsLoading: false,\n cashSessions: [],\n cashSessionsLoading: false,\n cashSessionModalOpen: false,\n\n paymentMethods: [],\n paymentMethodTypes: [],\n\n summary: null,\n summaryLoading: false,\n\n statement: null,\n statementLoading: false,\n statementQuery: null,\n\n cardTransactions: [],\n cardsLoading: false,\n\n async fetchSummary(dateRange) {\n return dedup('fin:summary', async () => {\n set({ summaryLoading: true })\n try {\n const summary = await provider.getSummary(dateRange)\n set({ summary, summaryLoading: false })\n } catch (error) {\n reportDataError(error, { operation: 'o resumo financeiro', extra: { dateRange } })\n set({ summaryLoading: false })\n }\n })\n },\n\n async fetchInvoices(query) {\n return dedup('fin:invoices:' + JSON.stringify(query), async () => {\n // `invoices` serves both directions; a late answer to a query nobody asks anymore must not\n // overwrite the current one, or the list appears and then empties.\n const asked = JSON.stringify(query)\n set({ invoicesLoading: true, invoiceQuery: query })\n let result\n try {\n result = await provider.getInvoices(query)\n } catch (error) {\n reportDataError(error, {\n operation: query.direction === 'credit' ? 'as contas a receber' : 'as contas a pagar',\n resource: 'v_financial_invoice_balances',\n extra: { query },\n })\n set({ invoicesLoading: false })\n return\n }\n if (JSON.stringify(get().invoiceQuery) !== asked) return\n\n // Forecasts join the list in a second, tolerant read: failing to read them must not cost the real list.\n let provisioned: Invoice[] = []\n if (provider.getProvisionedOccurrences && listsProvisioned(query)) {\n try {\n provisioned = await provider.getProvisionedOccurrences(query)\n } catch (error) {\n console.warn('[financial] provisioned occurrences unavailable', error)\n }\n if (JSON.stringify(get().invoiceQuery) !== asked) return\n }\n\n set({\n invoices: withProvisioned(result.data, provisioned),\n invoicesTotal: result.total + provisioned.length,\n invoicesLoading: false,\n })\n })\n },\n\n async fetchBankAccounts() {\n return dedup('fin:bankAccounts', async () => {\n set({ bankAccountsLoading: true })\n const bankAccounts = await provider.getBankAccounts()\n set({ bankAccounts, bankAccountsLoading: false })\n })\n },\n\n async fetchCommissions(query) {\n if (!provider.getCommissions) { set({ commissions: [], commissionsLoading: false }); return }\n set({ commissionsLoading: true })\n try {\n const commissions = await provider.getCommissions(query)\n set({ commissions, commissionsLoading: false })\n } catch (e) {\n set({ commissionsLoading: false })\n throw e\n }\n },\n\n async generateCommissions(input) {\n if (!provider.generateCommissions) return null\n const result = await provider.generateCommissions(input)\n await get().fetchCommissions({ periodStart: input.periodStart, periodEnd: input.periodEnd })\n return result\n },\n\n async fetchCashSessions(bankAccountId) {\n return dedup('fin:cashSessions:' + (bankAccountId ?? ''), async () => {\n set({ cashSessionsLoading: true })\n const cashSessions = await provider.getCashSessions(bankAccountId)\n set({ cashSessions, cashSessionsLoading: false })\n })\n },\n\n async fetchPaymentMethods() {\n return dedup('fin:paymentMethods', async () => {\n const [paymentMethods, paymentMethodTypes] = await Promise.all([\n provider.getPaymentMethods(),\n provider.getPaymentMethodTypes(),\n ])\n set({ paymentMethods, paymentMethodTypes })\n })\n },\n\n async fetchStatement(query) {\n return dedup('fin:statement:' + JSON.stringify(query), async () => {\n set({ statementLoading: true, statementQuery: query })\n try {\n const statement = await provider.getStatement(query)\n if (JSON.stringify(get().statementQuery) !== JSON.stringify(query)) return\n set({ statement, statementLoading: false })\n } catch (error) {\n reportDataError(error, { operation: 'o extrato', extra: { query } })\n set({ statementLoading: false })\n }\n })\n },\n\n async fetchCardTransactions(dateRange) {\n return dedup('fin:cards', async () => {\n set({ cardsLoading: true })\n const cardTransactions = await provider.getCardTransactions(dateRange)\n set({ cardTransactions, cardsLoading: false })\n })\n },\n\n async createInvoice(input) {\n try {\n const invoice = await provider.createInvoice(input)\n const query = get().invoiceQuery\n const result = await provider.getInvoices(query)\n const summary = await provider.getSummary()\n set({ invoices: result.data, invoicesTotal: result.total, summary })\n toast.success('Invoice created')\n return invoice\n } catch (err) {\n toast.error('Failed to create invoice', { description: errorText(err) })\n throw err\n }\n },\n\n async payMovement(input) {\n try {\n await provider.payMovement(input)\n } catch (err) {\n toast.error('Failed to record payment', { description: errorText(err) })\n throw err\n }\n // The command is acknowledged. A projection refresh is not a second\n // chance to fail the payment and must not invite a duplicate launch.\n try {\n const query = get().invoiceQuery\n const [result, summary] = await Promise.all([provider.getInvoices(query), provider.getSummary()])\n set({ invoices: result.data, invoicesTotal: result.total, summary })\n toast.success('Payment recorded')\n } catch {\n toast.warning('Payment recorded; refresh the list to see the updated balance')\n }\n },\n\n async reverseMovements(movementIds, reason) {\n const done: string[] = []\n try {\n for (const id of movementIds) {\n await provider.reverseMovement(id, reason)\n done.push(id)\n }\n toast.success(movementIds.length > 1 ? `${movementIds.length} pagamentos estornados` : 'Pagamento estornado')\n } catch (err: any) {\n toast.error(done.length ? `Estornados ${done.length} de ${movementIds.length}` : 'Não foi possível estornar', { description: err?.message })\n throw err\n } finally {\n const query = get().invoiceQuery\n const [result, summary] = await Promise.all([provider.getInvoices(query), provider.getSummary()])\n set({ invoices: result.data, invoicesTotal: result.total, summary })\n }\n },\n\n async reverseMovement(movementId, reason) {\n try {\n await provider.reverseMovement(movementId, reason)\n const query = get().invoiceQuery\n const [result, summary] = await Promise.all([provider.getInvoices(query), provider.getSummary()])\n set({ invoices: result.data, invoicesTotal: result.total, summary })\n toast.success('Pagamento estornado')\n } catch (err) {\n toast.error('Não foi possível estornar', { description: errorText(err) })\n throw err\n }\n },\n\n async createTransfer(input) {\n try {\n await provider.createTransfer(input)\n const query = get().statementQuery\n const [bankAccounts, summary, statement] = await Promise.all([\n provider.getBankAccounts(),\n provider.getSummary(),\n query ? provider.getStatement(query) : Promise.resolve(get().statement),\n ])\n set({ bankAccounts, summary, statement })\n toast.success('Transfer recorded')\n } catch (err) {\n toast.error('Failed to record transfer', { description: errorText(err) })\n throw err\n }\n },\n\n async cancelInvoice(input) {\n try {\n await provider.cancelInvoice(input)\n const query = get().invoiceQuery\n const [result, summary] = await Promise.all([provider.getInvoices(query), provider.getSummary()])\n set({ invoices: result.data, invoicesTotal: result.total, summary })\n toast.success('Invoice cancelled')\n } catch (err) {\n toast.error('Failed to cancel invoice', { description: errorText(err) })\n throw err\n }\n },\n\n async openCashSession(input) {\n try {\n const session = await provider.openCashSession(input)\n const cashSessions = await provider.getCashSessions()\n set({ cashSessions })\n toast.success('Cash session opened')\n return session\n } catch (err) {\n toast.error('Failed to open session', { description: errorText(err) })\n throw err\n }\n },\n\n async closeCashSession(input) {\n try {\n const session = await provider.closeCashSession(input)\n const cashSessions = await provider.getCashSessions()\n set({ cashSessions })\n toast.success('Cash session closed')\n return session\n } catch (err) {\n toast.error('Failed to close session', { description: errorText(err) })\n throw err\n }\n },\n\n setCashS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A;AACnC,QAAA,OAAO,OAAA;AAAA,MACT,SAAS,GAAA,EAAK;AACZ,QAAA,KAAA,CAAM,MAAM,wBAAA,EAA0B,EAAE,aAAa,SAAA,CAAU,GAAG,GAAG,CAAA;AACrE,QAAA,MAAM,GAAA;AAAA,MACR;AAAA,IACF,CAAA;AAAA,IAEA,MAAM,iBAAiB,KAAA,EAAO;AAC5B,MAAA,IAAI;AACF,QAAA,MAAM,OAAA,GAAU,MAAM,QAAA,CAAS,gBAAA,CAAiB,KAAK,CAAA;AACrD,QAAA,MAAM,YAAA,GAAe,MAAM,QAAA,CAAS,eAAA,EAAgB;AACpD,QAAA,GAAA,CAAI,EAAE,cAAc,CAAA;AACpB,QAAA,KAAA,CAAM,QAAQ,qBAAqB,CAAA;AACnC,QAAA,OAAO,OAAA;AAAA,MACT,SAAS,GAAA,EAAK;AACZ,QAAA,KAAA,CAAM,MAAM,yBAAA,EAA2B,EAAE,aAAa,SAAA,CAAU,GAAG,GAAG,CAAA;AACtE,QAAA,MAAM,GAAA;AAAA,MACR;AAAA,IACF,CAAA;AAAA,IAEA,wBAAwB,IAAA,EAAM;AAC5B,MAAA,GAAA,CAAI,EAAE,oBAAA,EAAsB,IAAA,EAAM,CAAA;AAAA,IACpC;AAAA,GACF,CAAE,CAAA;AACJ","file":"store.js","sourcesContent":["import { createStore, type StoreApi } from 'zustand/vanilla'\nimport { createSafeDataProvider, reportDataError } from '@fayz-ai/core'\nimport { toast } from '@fayz-ai/ui'\nimport { createMockFinancialProvider } from './data/mock'\nimport type { FinancialDataProvider } from './data/provider'\nimport { createSupabaseFinancialProvider } from './data/supabase'\nimport type { BankAccount } from './domain/account'\nimport type { CardTransaction } from './domain/card'\nimport type { CashSession, CloseCashSessionInput, OpenCashSessionInput } from './domain/cash-session'\nimport type { CommissionEntry, CommissionGenerationResult, CommissionQuery, GenerateCommissionsInput } from './domain/commission'\nimport {\n listsProvisioned, withProvisioned,\n type CancelInvoiceInput, type CreateInvoiceInput, type Invoice, type InvoiceQuery,\n} from './domain/invoice'\nimport type { FinancialMovement, PayMovementInput } from './domain/movement'\nimport type { PaymentMethod, PaymentMethodType } from './domain/payment-method'\nimport type { DateRange } from './domain/query'\nimport type { FinancialSummary } from './domain/report'\nimport type { StatementQuery, StatementResult } from './domain/statement'\nimport type { CreateTransferInput } from './domain/transfer'\n\n/** Supabase when a client is initialized, else the in-memory mock, resolved on first use. */\nexport function createSafeFinancialProvider(): FinancialDataProvider {\n return createSafeDataProvider(createSupabaseFinancialProvider, createMockFinancialProvider)\n}\n\nexport interface FinancialUIState {\n // Data cache\n invoices: Invoice[]\n invoicesTotal: number\n invoicesLoading: boolean\n invoiceQuery: InvoiceQuery\n\n movements: FinancialMovement[]\n movementsTotal: number\n movementsLoading: boolean\n\n bankAccounts: BankAccount[]\n bankAccountsLoading: boolean\n\n commissions: CommissionEntry[]\n commissionsLoading: boolean\n cashSessions: CashSession[]\n cashSessionsLoading: boolean\n /** The abertura/fechamento dialog lives in the SHELL header (CashSessionHeaderControl),\n * outside any page's tree — a page button that wants to open \"the same modal\"\n * has to flip a flag both sides share, not local state of its own. */\n cashSessionModalOpen: boolean\n\n paymentMethods: PaymentMethod[]\n paymentMethodTypes: PaymentMethodType[]\n\n summary: FinancialSummary | null\n summaryLoading: boolean\n\n statement: StatementResult | null\n statementLoading: boolean\n statementQuery: StatementQuery | null\n\n cardTransactions: CardTransaction[]\n cardsLoading: boolean\n\n // Actions\n fetchSummary(dateRange?: DateRange): Promise<void>\n fetchInvoices(query: InvoiceQuery): Promise<void>\n fetchBankAccounts(): Promise<void>\n fetchCashSessions(bankAccountId?: string): Promise<void>\n fetchCommissions(query: CommissionQuery): Promise<void>\n generateCommissions(input: GenerateCommissionsInput): Promise<CommissionGenerationResult | null>\n fetchPaymentMethods(): Promise<void>\n fetchStatement(query: StatementQuery): Promise<void>\n fetchCardTransactions(dateRange?: DateRange): Promise<void>\n createInvoice(input: CreateInvoiceInput): Promise<Invoice>\n /** FAY-1225 \"log money in a few taps\": one call → the right provider plumbing + full surface refresh. */\n payMovement(input: PayMovementInput): Promise<void>\n reverseMovement(movementId: string, reason: string): Promise<void>\n /** Reverses several payments (all of an installment) with one refresh and one toast. */\n reverseMovements(movementIds: string[], reason: string): Promise<void>\n createTransfer(input: CreateTransferInput): Promise<void>\n cancelInvoice(input: CancelInvoiceInput): Promise<void>\n openCashSession(input: OpenCashSessionInput): Promise<CashSession>\n closeCashSession(input: CloseCashSessionInput): Promise<CashSession>\n setCashSessionModalOpen(open: boolean): void\n}\n\n// ---------------------------------------------------------------------------\n// Store factory\n// ---------------------------------------------------------------------------\n\nfunction errorText(err: unknown): string | undefined {\n return err instanceof Error ? err.message : undefined\n}\n\n/** One store per provider. Concurrent reads of the same key share one request. */\nexport function createFinancialStore(provider: FinancialDataProvider): StoreApi<FinancialUIState> {\n const inflight = new Map<string, Promise<unknown>>()\n function dedup<T>(key: string, read: () => Promise<T>): Promise<T> {\n const running = inflight.get(key) as Promise<T> | undefined\n if (running) return running\n const promise = read().finally(() => inflight.delete(key))\n inflight.set(key, promise)\n return promise\n }\n\n return createStore<FinancialUIState>((set, get) => ({\n invoices: [],\n invoicesTotal: 0,\n invoicesLoading: false,\n invoiceQuery: {},\n\n movements: [],\n movementsTotal: 0,\n movementsLoading: false,\n\n bankAccounts: [],\n bankAccountsLoading: false,\n\n commissions: [],\n commissionsLoading: false,\n cashSessions: [],\n cashSessionsLoading: false,\n cashSessionModalOpen: false,\n\n paymentMethods: [],\n paymentMethodTypes: [],\n\n summary: null,\n summaryLoading: false,\n\n statement: null,\n statementLoading: false,\n statementQuery: null,\n\n cardTransactions: [],\n cardsLoading: false,\n\n async fetchSummary(dateRange) {\n return dedup('fin:summary', async () => {\n set({ summaryLoading: true })\n try {\n const summary = await provider.getSummary(dateRange)\n set({ summary, summaryLoading: false })\n } catch (error) {\n reportDataError(error, { operation: 'o resumo financeiro', extra: { dateRange } })\n set({ summaryLoading: false })\n }\n })\n },\n\n async fetchInvoices(query) {\n return dedup('fin:invoices:' + JSON.stringify(query), async () => {\n // `invoices` serves both directions; a late answer to a query nobody asks anymore must not\n // overwrite the current one, or the list appears and then empties.\n const asked = JSON.stringify(query)\n set({ invoicesLoading: true, invoiceQuery: query })\n let result\n try {\n result = await provider.getInvoices(query)\n } catch (error) {\n reportDataError(error, {\n operation: query.direction === 'credit' ? 'as contas a receber' : 'as contas a pagar',\n resource: 'v_financial_invoice_balances',\n extra: { query },\n })\n set({ invoicesLoading: false })\n return\n }\n if (JSON.stringify(get().invoiceQuery) !== asked) return\n\n // Forecasts join the list in a second, tolerant read: failing to read them must not cost the real list.\n let provisioned: Invoice[] = []\n if (provider.getProvisionedOccurrences && listsProvisioned(query)) {\n try {\n provisioned = await provider.getProvisionedOccurrences(query)\n } catch (error) {\n console.warn('[financial] provisioned occurrences unavailable', error)\n }\n if (JSON.stringify(get().invoiceQuery) !== asked) return\n }\n\n set({\n invoices: withProvisioned(result.data, provisioned),\n invoicesTotal: result.total + provisioned.length,\n invoicesLoading: false,\n })\n })\n },\n\n async fetchBankAccounts() {\n return dedup('fin:bankAccounts', async () => {\n set({ bankAccountsLoading: true })\n const bankAccounts = await provider.getBankAccounts()\n set({ bankAccounts, bankAccountsLoading: false })\n })\n },\n\n async fetchCommissions(query) {\n if (!provider.getCommissions) { set({ commissions: [], commissionsLoading: false }); return }\n set({ commissionsLoading: true })\n try {\n const commissions = await provider.getCommissions(query)\n set({ commissions, commissionsLoading: false })\n } catch (e) {\n set({ commissionsLoading: false })\n throw e\n }\n },\n\n async generateCommissions(input) {\n if (!provider.generateCommissions) return null\n const result = await provider.generateCommissions(input)\n await get().fetchCommissions({ periodStart: input.periodStart, periodEnd: input.periodEnd })\n return result\n },\n\n async fetchCashSessions(bankAccountId) {\n return dedup('fin:cashSessions:' + (bankAccountId ?? ''), async () => {\n set({ cashSessionsLoading: true })\n const cashSessions = await provider.getCashSessions(bankAccountId)\n set({ cashSessions, cashSessionsLoading: false })\n })\n },\n\n async fetchPaymentMethods() {\n return dedup('fin:paymentMethods', async () => {\n const [paymentMethods, paymentMethodTypes] = await Promise.all([\n provider.getPaymentMethods(),\n provider.getPaymentMethodTypes(),\n ])\n set({ paymentMethods, paymentMethodTypes })\n })\n },\n\n async fetchStatement(query) {\n return dedup('fin:statement:' + JSON.stringify(query), async () => {\n set({ statementLoading: true, statementQuery: query })\n try {\n const statement = await provider.getStatement(query)\n if (JSON.stringify(get().statementQuery) !== JSON.stringify(query)) return\n set({ statement, statementLoading: false })\n } catch (error) {\n reportDataError(error, { operation: 'o extrato', extra: { query } })\n set({ statementLoading: false })\n }\n })\n },\n\n async fetchCardTransactions(dateRange) {\n return dedup('fin:cards', async () => {\n set({ cardsLoading: true })\n const cardTransactions = await provider.getCardTransactions(dateRange)\n set({ cardTransactions, cardsLoading: false })\n })\n },\n\n async createInvoice(input) {\n try {\n const invoice = await provider.createInvoice(input)\n const query = get().invoiceQuery\n const result = await provider.getInvoices(query)\n const summary = await provider.getSummary()\n set({ invoices: result.data, invoicesTotal: result.total, summary })\n toast.success('Invoice created')\n return invoice\n } catch (err) {\n toast.error('Failed to create invoice', { description: errorText(err) })\n throw err\n }\n },\n\n async payMovement(input) {\n try {\n await provider.payMovement(input)\n } catch (err) {\n toast.error('Failed to record payment', { description: errorText(err) })\n throw err\n }\n // The command is acknowledged. A projection refresh is not a second\n // chance to fail the payment and must not invite a duplicate launch.\n try {\n const query = get().invoiceQuery\n const [result, summary] = await Promise.all([provider.getInvoices(query), provider.getSummary()])\n set({ invoices: result.data, invoicesTotal: result.total, summary })\n toast.success('Payment recorded')\n } catch {\n toast.warning('Payment recorded; refresh the list to see the updated balance')\n }\n },\n\n async reverseMovements(movementIds, reason) {\n const done: string[] = []\n try {\n for (const id of movementIds) {\n await provider.reverseMovement(id, reason)\n done.push(id)\n }\n toast.success(movementIds.length > 1 ? `${movementIds.length} pagamentos estornados` : 'Pagamento estornado')\n } catch (err: any) {\n toast.error(done.length ? `Estornados ${done.length} de ${movementIds.length}` : 'Não foi possível estornar', { description: err?.message })\n throw err\n } finally {\n const query = get().invoiceQuery\n const [result, summary] = await Promise.all([provider.getInvoices(query), provider.getSummary()])\n set({ invoices: result.data, invoicesTotal: result.total, summary })\n }\n },\n\n async reverseMovement(movementId, reason) {\n try {\n await provider.reverseMovement(movementId, reason)\n const query = get().invoiceQuery\n const [result, summary] = await Promise.all([provider.getInvoices(query), provider.getSummary()])\n set({ invoices: result.data, invoicesTotal: result.total, summary })\n toast.success('Pagamento estornado')\n } catch (err) {\n toast.error('Não foi possível estornar', { description: errorText(err) })\n throw err\n }\n },\n\n async createTransfer(input) {\n try {\n await provider.createTransfer(input)\n const query = get().statementQuery\n const [bankAccounts, summary, statement] = await Promise.all([\n provider.getBankAccounts(),\n provider.getSummary(),\n query ? provider.getStatement(query) : Promise.resolve(get().statement),\n ])\n set({ bankAccounts, summary, statement })\n toast.success('Transfer recorded')\n } catch (err) {\n toast.error('Failed to record transfer', { description: errorText(err) })\n throw err\n }\n },\n\n async cancelInvoice(input) {\n try {\n await provider.cancelInvoice(input)\n const query = get().invoiceQuery\n const [result, summary] = await Promise.all([provider.getInvoices(query), provider.getSummary()])\n set({ invoices: result.data, invoicesTotal: result.total, summary })\n toast.success('Invoice cancelled')\n } catch (err) {\n toast.error('Failed to cancel invoice', { description: errorText(err) })\n throw err\n }\n },\n\n async openCashSession(input) {\n try {\n const session = await provider.openCashSession(input)\n const cashSessions = await provider.getCashSessions()\n set({ cashSessions })\n toast.success('Cash session opened')\n return session\n } catch (err) {\n toast.error('Failed to open session', { description: errorText(err) })\n throw err\n }\n },\n\n async closeCashSession(input) {\n try {\n const session = await provider.closeCashSession(input)\n const cashSessions = await provider.getCashSessions()\n set({ cashSessions })\n toast.success('Cash session closed')\n return session\n } catch (err) {\n toast.error('Failed to close session', { description: errorText(err) })\n throw err\n }\n },\n\n setCashSessionModalOpen(open) {\n set({ cashSessionModalOpen: open })\n },\n }))\n}\n"]}
@@ -36,5 +36,18 @@ export interface ClientAccountSlotProps extends Omit<ClientAccountInlineSlotProp
36
36
  /** Invoice screen slots other plugins fill (fiscal-br's notes button). Props: `{ invoiceId, direction }`. */
37
37
  export declare const FINANCIAL_INVOICE_ZONES: {
38
38
  readonly headerActions: "financial.invoice.header.actions";
39
+ /**
40
+ * Above the lines of a saved invoice: something another plugin knows about it
41
+ * (fiscal-br: what did not arrive of the note behind a payable). Props:
42
+ * {@link InvoiceNoticeSlotProps}.
43
+ */
44
+ readonly notices: "financial.invoice.notices";
39
45
  };
46
+ export interface InvoiceNoticeSlotProps {
47
+ invoiceId?: string;
48
+ direction?: string;
49
+ cancelled?: boolean;
50
+ /** The widget changed the invoice (e.g. abated a line): the screen reloads it. */
51
+ onChanged?: () => void;
52
+ }
40
53
  //# sourceMappingURL=zones.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"zones.d.ts","sourceRoot":"","sources":["../../src/views/zones.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AAE3D;;;GAGG;AACH,eAAO,MAAM,eAAe;IAC1B,4EAA4E;;IAE5E,sFAAsF;;IAEtF,0GAA0G;;CAElG,CAAA;AAEV,MAAM,WAAW,uBAAuB;IACtC,kFAAkF;IAClF,WAAW,EAAE,iBAAiB,CAAA;IAC9B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,OAAO,EAAE,MAAM,IAAI,CAAA;IACnB,MAAM,EAAE,MAAM,IAAI,CAAA;CACnB;AAED,MAAM,WAAW,4BAA4B;IAC3C,QAAQ,EAAE,MAAM,CAAA;IAChB,qFAAqF;IACrF,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC1B,UAAU,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAA;IACvC,QAAQ,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,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,sBAAsB;IACrC,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,kFAAkF;IAClF,SAAS,CAAC,EAAE,MAAM,IAAI,CAAA;CACvB"}
@@ -8,7 +8,13 @@ var FINANCIAL_ZONES = {
8
8
  clientAccountInline: "financial.client-account.inline"
9
9
  };
10
10
  var FINANCIAL_INVOICE_ZONES = {
11
- headerActions: "financial.invoice.header.actions"
11
+ headerActions: "financial.invoice.header.actions",
12
+ /**
13
+ * Above the lines of a saved invoice: something another plugin knows about it
14
+ * (fiscal-br: what did not arrive of the note behind a payable). Props:
15
+ * {@link InvoiceNoticeSlotProps}.
16
+ */
17
+ notices: "financial.invoice.notices"
12
18
  };
13
19
 
14
20
  export { FINANCIAL_INVOICE_ZONES, FINANCIAL_ZONES };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/views/zones.ts"],"names":[],"mappings":";AAMO,IAAM,eAAA,GAAkB;AAAA;AAAA,EAE7B,cAAA,EAAgB,2BAAA;AAAA;AAAA,EAEhB,aAAA,EAAe,0BAAA;AAAA;AAAA,EAEf,mBAAA,EAAqB;AACvB;AAwBO,IAAM,uBAAA,GAA0B;AAAA,EACrC,aAAA,EAAe;AACjB","file":"zones.js","sourcesContent":["import type { FinancialMovement } from '../domain/movement'\n\n/**\n * Widget zones other surfaces render with a `WidgetSlot` to show a financial screen in place.\n * The financial plugin fills them; a host whose app mounts no financial manifest gets an empty zone.\n */\nexport const FINANCIAL_ZONES = {\n /** Receive one open installment. Props: {@link ReceivePaymentSlotProps}. */\n receivePayment: 'financial.receive-payment',\n /** A client's account in a right-rail page. Props: {@link ClientAccountSlotProps}. */\n clientAccount: 'financial.client-account',\n /** A client's account without a frame, to embed in a tab. Props: {@link ClientAccountInlineSlotProps}. */\n clientAccountInline: 'financial.client-account.inline',\n} as const\n\nexport interface ReceivePaymentSlotProps {\n /** The open installment; its `id` is the installment id the payment RPC takes. */\n installment: FinancialMovement\n receiptUrl?: string\n onClose: () => void\n onPaid: () => void\n}\n\nexport interface ClientAccountInlineSlotProps {\n personId: string\n /** The order the screen came from: its invoice is highlighted and can be charged. */\n orderId?: string | null\n clientName?: string | null\n onGenerate?: () => Promise<void> | void\n currency?: { code: string; locale: string; symbol: string }\n}\n\nexport interface ClientAccountSlotProps extends Omit<ClientAccountInlineSlotProps, 'currency'> {\n onClose: () => void\n}\n\n/** Invoice screen slots other plugins fill (fiscal-br's notes button). Props: `{ invoiceId, direction }`. */\nexport const FINANCIAL_INVOICE_ZONES = {\n headerActions: 'financial.invoice.header.actions',\n} as const\n"]}
1
+ {"version":3,"sources":["../../src/views/zones.ts"],"names":[],"mappings":";AAMO,IAAM,eAAA,GAAkB;AAAA;AAAA,EAE7B,cAAA,EAAgB,2BAAA;AAAA;AAAA,EAEhB,aAAA,EAAe,0BAAA;AAAA;AAAA,EAEf,mBAAA,EAAqB;AACvB;AAwBO,IAAM,uBAAA,GAA0B;AAAA,EACrC,aAAA,EAAe,kCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMf,OAAA,EAAS;AACX","file":"zones.js","sourcesContent":["import type { FinancialMovement } from '../domain/movement'\n\n/**\n * Widget zones other surfaces render with a `WidgetSlot` to show a financial screen in place.\n * The financial plugin fills them; a host whose app mounts no financial manifest gets an empty zone.\n */\nexport const FINANCIAL_ZONES = {\n /** Receive one open installment. Props: {@link ReceivePaymentSlotProps}. */\n receivePayment: 'financial.receive-payment',\n /** A client's account in a right-rail page. Props: {@link ClientAccountSlotProps}. */\n clientAccount: 'financial.client-account',\n /** A client's account without a frame, to embed in a tab. Props: {@link ClientAccountInlineSlotProps}. */\n clientAccountInline: 'financial.client-account.inline',\n} as const\n\nexport interface ReceivePaymentSlotProps {\n /** The open installment; its `id` is the installment id the payment RPC takes. */\n installment: FinancialMovement\n receiptUrl?: string\n onClose: () => void\n onPaid: () => void\n}\n\nexport interface ClientAccountInlineSlotProps {\n personId: string\n /** The order the screen came from: its invoice is highlighted and can be charged. */\n orderId?: string | null\n clientName?: string | null\n onGenerate?: () => Promise<void> | void\n currency?: { code: string; locale: string; symbol: string }\n}\n\nexport interface ClientAccountSlotProps extends Omit<ClientAccountInlineSlotProps, 'currency'> {\n onClose: () => void\n}\n\n/** Invoice screen slots other plugins fill (fiscal-br's notes button). Props: `{ invoiceId, direction }`. */\nexport const FINANCIAL_INVOICE_ZONES = {\n headerActions: 'financial.invoice.header.actions',\n /**\n * Above the lines of a saved invoice: something another plugin knows about it\n * (fiscal-br: what did not arrive of the note behind a payable). Props:\n * {@link InvoiceNoticeSlotProps}.\n */\n notices: 'financial.invoice.notices',\n} as const\n\nexport interface InvoiceNoticeSlotProps {\n invoiceId?: string\n direction?: string\n cancelled?: boolean\n /** The widget changed the invoice (e.g. abated a line): the screen reloads it. */\n onChanged?: () => void\n}\n"]}
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "fayz": {
4
4
  "status": "beta"
5
5
  },
6
- "version": "0.1.13",
6
+ "version": "0.2.0",
7
7
  "description": "Fayz SDK financial context — invoices, payments, accounts and reconciliation: the domain rules, the repository port and its adapters, and the store",
8
8
  "type": "module",
9
9
  "sideEffects": false,
@@ -22,8 +22,8 @@
22
22
  "zustand": "^4.5.0 || ^5.0.0"
23
23
  },
24
24
  "dependencies": {
25
- "@fayz-ai/core": "^0.67.0",
26
- "@fayz-ai/ui": "^0.67.0"
25
+ "@fayz-ai/core": "^0.67.4",
26
+ "@fayz-ai/ui": "^0.67.3"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@supabase/supabase-js": "^2.45.0",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/domain/invoice.ts"],"names":[],"mappings":";;;AA+MO,SAAS,UAAU,IAAA,EAA0B;AAClD,EAAA,OAAO,MAAA,CAAO,IAAA,CAAK,QAAA,GAAW,IAAA,CAAK,SAAA,IAAa,KAAK,QAAA,IAAY,CAAA,CAAA,IAAM,IAA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AA,MAAA,CAAA,GAAW,EAAE,CAAA,CAAE,CAAA;AAAA,EACjG;AACA,EAAA,OAAO,SAAA;AACT","file":"chunk-5RMPZIMO.js","sourcesContent":["import { round2 } from './money'\nimport type { CreateMovementInput, FinancialMovement, TransactionDirection } from './movement'\nimport type { DateRange } from './query'\n\nexport type InvoiceStatus =\n | 'draft' | 'open' | 'partial' | 'paid' | 'cancelled' | 'overdue'\n /** A recurring occurrence not consolidated yet: forecast, not owed. No ledger entry, no charge. */\n | 'provisioned'\n\n/** What an invoice line is; the set is configured per vertical. */\nexport type InvoiceItemKind = string\n\nexport interface Invoice {\n id: string\n direction: TransactionDirection\n /** ISO code the document was written in. Absent = the house's currency. */\n currency?: string\n /** Free labels the house puts on the bill. */\n tags?: string[]\n /** Competence date: the axis of the ledger and the income statement. */\n invoiceDate: string\n /** The next open due date, or the last one once everything is paid. Lists sort by it. */\n dueDate?: string\n /** Lists are per installment: `id` is the installment and `invoiceId` the document it opens. */\n invoiceId?: string\n installmentNumber?: number\n attachmentCount?: number\n fiscalNumber?: string\n totalAmount: number\n paidAmount: number\n status: InvoiceStatus\n totalInstallments: number\n contactId?: string\n contactName?: string\n cashSessionId?: string\n unitId?: string\n observations?: string\n itemsSummary?: string\n paymentMethodId?: string\n paymentMethodTypeId?: string\n paymentAccountId?: string\n paymentCardInstallments?: number\n /** Start time of the booking the order came from, when it has one. */\n bookingStartsAt?: string\n metadata?: Record<string, unknown>\n tenantId: string\n createdAt: string\n updatedAt: string\n createdBy?: string\n /** A virtual row for a provisioned recurring occurrence; there is no invoice behind it. */\n isProvisionedOccurrence?: boolean\n occurrenceId?: string\n recurringBillId?: string\n}\n\nexport interface InvoiceItem {\n id: string\n invoiceId: string\n /** The picture of the product this line names, when it names one that has a picture. */\n imageUrl?: string\n itemKind: InvoiceItemKind\n referenceId?: string\n description: string\n quantity: number\n unitPrice: number\n totalAmount: number\n discount: number\n surcharge: number\n accountId?: string\n costCenterId?: string\n isExecuted?: boolean\n executionDate?: string\n executedByProfessionalId?: string\n metadata?: Record<string, unknown>\n /** Set when the line was cancelled on its own (cancel by item). */\n cancelledAt?: string\n cancelReason?: string\n createdAt: string\n}\n\nexport interface CreateInvoiceInput {\n direction: TransactionDirection\n invoiceDate: string\n fiscalNumber?: string\n contactId?: string\n contactName?: string\n cashSessionId?: string\n unitId?: string\n /** ISO code to write the document in. Absent = the unit's currency. */\n currency?: string\n tags?: string[]\n observations?: string\n metadata?: Record<string, unknown>\n items: CreateInvoiceItemInput[]\n installments: CreateMovementInput[]\n}\n\nexport interface CreateInvoiceItemInput {\n itemKind: InvoiceItemKind\n referenceId?: string\n description: string\n quantity: number\n unitPrice: number\n discount?: number\n surcharge?: number\n accountId?: string\n costCenterId?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface CancellationReason {\n id: string\n name: string\n}\n\n/** Goods a payable line brought into stock, still traceable to its note. */\nexport interface InvoiceStockEntry {\n itemId: string\n productId: string\n locationId: string\n /** Quantity that entered, in the product's stock unit. */\n entered: number\n /** What is still at that location — the most a return or loss can move. */\n available: number\n enteredOn: string\n}\n\nexport type StockDestination = 'devolver' | 'perda' | 'manter'\n\nexport interface CancelInvoiceItemsInput {\n invoiceId: string\n /** Empty = every live line (the whole invoice). */\n itemIds: string[]\n reasonId: string\n detail?: string\n stock: Array<{ itemId: string; destination: StockDestination; note?: string }>\n idempotencyKey?: string\n}\n\nexport interface CancelInvoiceItemsResult {\n whole: boolean\n amount: number\n /** What had been paid on the cancelled part and became counterparty credit. */\n creditAmount: number\n}\n\nexport interface InstallmentChargeInput {\n installmentId: string\n kind: 'interest' | 'fine' | 'discount'\n /** Always positive — `kind` carries the sign. */\n amount: number\n accountId?: string\n description?: string\n idempotencyKey?: string\n}\n\nexport interface CancelInvoiceInput {\n invoiceId: string\n reason: string\n /** Stable for every retry of the same cancellation attempt. */\n idempotencyKey?: string\n}\n\nexport interface InvoiceQuery {\n direction?: TransactionDirection\n status?: InvoiceStatus | InvoiceStatus[]\n contactId?: string\n unitId?: string\n accountId?: string\n costCenterId?: string\n dateRange?: DateRange\n search?: string\n fiscalNumber?: string\n /** The account the money left from or landed in. */\n bankAccountId?: string\n /**\n * With `dateRange`: also return the unpaid lines (overdue or partially paid)\n * that fell due BEFORE the range starts. A month window otherwise hides the\n * debt that is most urgent — the bill from last month that nobody paid.\n */\n includeOverdue?: boolean\n /** `due` (default): soonest due first — a queue. `recent`: newest entered first. */\n sort?: 'due' | 'recent'\n page?: number\n pageSize?: number\n}\n\n/** A receipt attached to an invoice. `pending` means the row exists but the file does not open yet. */\nexport interface InvoiceAttachment {\n id: string\n fileName: string\n fileSize?: number\n mimeType?: string\n url?: string\n pending: boolean\n createdAt?: string\n}\n\n/** One installment of a schedule, before it is written. */\nexport interface ScheduledInstallment {\n dueDate: string\n amount: number\n metadata?: Record<string, unknown>\n}\n\ntype PricedLine = Pick<CreateInvoiceItemInput, 'quantity' | 'unitPrice' | 'discount' | 'surcharge'>\n\nexport function lineTotal(item: PricedLine): number {\n return round2(item.quantity * item.unitPrice - (item.discount ?? 0) + (item.surcharge ?? 0))\n}\n\n/** An invoice is worth the sum of its lines; storing one without the other bills one value and charges another. */\nexport function invoiceTotal(items: PricedLine[]): number {\n return round2(items.reduce((sum, item) => sum + lineTotal(item), 0))\n}\n\nexport function itemsDescription(items: Pick<CreateInvoiceItemInput, 'description'>[]): string {\n return items.map((item) => item.description).filter(Boolean).join(', ')\n}\n\n/** A cancellation without a reason is refused. */\nexport function cancellationReason(input: Pick<CancelInvoiceInput, 'reason'>): string {\n const reason = input.reason.trim()\n if (!reason) throw new Error('A cancellation reason is required')\n return reason\n}\n\n/** Status from what was paid, and whether any open bill is past due. */\nexport function invoiceStatusOf(\n invoice: Pick<Invoice, 'paidAmount' | 'totalAmount'>,\n bills: Pick<FinancialMovement, 'status' | 'dueDate'>[],\n today: string,\n): InvoiceStatus {\n if (invoice.paidAmount >= invoice.totalAmount) return 'paid'\n if (invoice.paidAmount > 0) return 'partial'\n const late = bills.some((bill) => bill.status === 'overdue' || (bill.status === 'pending' && bill.dueDate < today))\n return late ? 'overdue' : 'open'\n}\n\n/** Equal shares to the cent; the first installment absorbs the rounding remainder. */\nexport function splitInstallments(total: number, count: number): number[] {\n if (count < 1) return []\n const share = Math.floor(round2(total) * 100 / count) / 100\n const remainder = round2(total - share * count)\n return Array.from({ length: count }, (_, i) => (i === 0 ? round2(share + remainder) : share))\n}\n\n/** Does the schedule close on the invoice total? The database refuses a schedule that does not. */\nexport function scheduleCloses(amounts: number[], total: number): boolean {\n return Math.round(amounts.reduce((sum, amount) => sum + amount, 0) * 100) === Math.round(total * 100)\n}\n\n/** Once any money was received the schedule and the items are history. */\nexport function hasReceivedPayment(bills: Pick<FinancialMovement, 'paidAmount'>[]): boolean {\n return bills.some((bill) => (bill.paidAmount ?? 0) > 0)\n}\n\n/** A new schedule for an invoice, refused when it cannot be applied. */\nexport function assertReschedule(\n invoice: Pick<Invoice, 'totalAmount'>,\n currentBills: Pick<FinancialMovement, 'paidAmount'>[],\n installments: ScheduledInstallment[],\n): void {\n if (hasReceivedPayment(currentBills)) throw new Error('Invoice already received; its schedule is history now')\n const sum = round2(installments.reduce((total, installment) => total + installment.amount, 0))\n if (sum !== round2(invoice.totalAmount)) {\n throw new Error(`Installments sum to ${sum} but the invoice total is ${invoice.totalAmount}`)\n }\n}\n\n/**\n * Opening an invoice means editing it while it can still change. Paid and cancelled ones became\n * statement history; `partial` stays editable because its header can still be corrected.\n */\nexport function invoiceOpensForEditing(status: string | undefined): boolean {\n return status !== 'paid' && status !== 'cancelled'\n}\n\n/**\n * Forecast rows join a list only when they can match it: not when a status was asked for, and not\n * when the filter is a document number or a paying account, which a forecast never has.\n */\nexport function listsProvisioned(query: InvoiceQuery): boolean {\n return !query.status && !query.fiscalNumber && !query.bankAccountId\n}\n\n/** Real invoices and forecasts in one list, by due date. */\nexport function withProvisioned(invoices: Invoice[], provisioned: Invoice[]): Invoice[] {\n if (provisioned.length === 0) return invoices\n return [...invoices, ...provisioned].sort((a, b) => (a.dueDate ?? '').localeCompare(b.dueDate ?? ''))\n}\n\ninterface InvoiceItemType {\n value: string\n label: string\n icon?: string\n}\n\n// What the house sells is never offered on a payable: booking an expense against its own revenue line.\nconst RECEIVABLE_ONLY = new Set(['service', 'package', 'gift_card'])\n\n/** Catalogue-backed kinds need their catalogue installed; `other` is always offered. */\nexport function availableInvoiceItemTypes<T extends InvoiceItemType>(\n itemTypes: T[],\n lookupKinds: Iterable<string>,\n otherLabel: string,\n direction?: TransactionDirection | 'payable' | 'receivable',\n): T[] {\n const installed = new Set(lookupKinds)\n const payable = direction === 'debit' || direction === 'payable'\n const visible = itemTypes.filter((type) => (\n (!payable || !RECEIVABLE_ONLY.has(type.value))\n ) && (\n type.value === 'other'\n || !['product', 'service', 'package'].includes(type.value)\n || installed.has(type.value)\n ))\n if (visible.some((type) => type.value === 'other')) return visible\n return [...visible, { value: 'other', label: otherLabel, icon: 'MoreHorizontal' } as T]\n}\n\ninterface InvoiceLineSummarySource {\n invoice_id?: string | null\n name?: string | null\n description?: string | null\n quantity?: number | string | null\n}\n\n/** The billed lines compacted for a list row: two shown, the rest counted. */\nexport function summarizeInvoiceLines(rows: InvoiceLineSummarySource[], visible = 2): Map<string, string> {\n const byInvoice = new Map<string, string[]>()\n for (const row of rows) {\n const invoiceId = row.invoice_id\n const label = String(row.name ?? row.description ?? '').trim()\n if (!invoiceId || !label) continue\n const quantity = Number(row.quantity) || 1\n const rendered = quantity === 1 ? label : `${quantity} × ${label}`\n const current = byInvoice.get(invoiceId) ?? []\n current.push(rendered)\n byInvoice.set(invoiceId, current)\n }\n\n const summaries = new Map<string, string>()\n for (const [invoiceId, lines] of byInvoice) {\n const shown = lines.slice(0, visible)\n const remainder = lines.length - shown.length\n summaries.set(invoiceId, `${shown.join(' · ')}${remainder > 0 ? ` · +${remainder} itens` : ''}`)\n }\n return summaries\n}\n"]}