@fayz-ai/financial 0.3.0 → 0.3.2

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.
@@ -59,7 +59,7 @@ function addForecastTotals(totals, forecasts) {
59
59
  }
60
60
  function withProvisioned(invoices, provisioned) {
61
61
  if (provisioned.length === 0) return invoices;
62
- return [...invoices, ...provisioned].sort((a, b) => (a.dueDate ?? "").localeCompare(b.dueDate ?? ""));
62
+ return [...invoices, ...provisioned].sort((a, b) => (b.dueDate ?? "").localeCompare(a.dueDate ?? ""));
63
63
  }
64
64
  var RECEIVABLE_ONLY = /* @__PURE__ */ new Set(["service", "package", "gift_card"]);
65
65
  function availableInvoiceItemTypes(itemTypes, lookupKinds, otherLabel, direction) {
@@ -91,5 +91,5 @@ function summarizeInvoiceLines(rows, visible = 2) {
91
91
  }
92
92
 
93
93
  export { addForecastTotals, assertReschedule, availableInvoiceItemTypes, cancellationReason, hasReceivedPayment, invoiceOpensForEditing, invoiceStatusOf, invoiceTotal, itemsDescription, lineTotal, listsProvisioned, scheduleCloses, splitInstallments, summarizeInvoiceLines, withProvisioned };
94
- //# sourceMappingURL=chunk-CTJ6LVDH.js.map
95
- //# sourceMappingURL=chunk-CTJ6LVDH.js.map
94
+ //# sourceMappingURL=chunk-HPJDTBVB.js.map
95
+ //# sourceMappingURL=chunk-HPJDTBVB.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/domain/invoice.ts"],"names":[],"mappings":";;;AAqNO,SAAS,UAAU,IAAA,EAA0B;AAClD,EAAA,OAAO,MAAA,CAAO,IAAA,CAAK,QAAA,GAAW,IAAA,CAAK,SAAA,IAAa,KAAK,QAAA,IAAY,CAAA,CAAA,IAAM,IAAA,CAAK,SAAA,IAAa,CAAA,CAAE,CAAA;AAC7F;AAGO,SAAS,aAAa,KAAA,EAA6B;AACxD,EAAA,OAAO,MAAA,CAAO,KAAA,CAAM,MAAA,CAAO,CAAC,GAAA,EAAK,IAAA,KA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AClC;AAEA,EAAA,MAAM,SAAA,uBAAgB,GAAA,EAAoB;AAC1C,EAAA,KAAA,MAAW,CAAC,SAAA,EAAW,KAAK,CAAA,IAAK,SAAA,EAAW;AAC1C,IAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,KAAA,CAAM,CAAA,EAAG,OAAO,CAAA;AACpC,IAAA,MAAM,SAAA,GAAY,KAAA,CAAM,MAAA,GAAS,KAAA,CAAM,MAAA;AACvC,IAAA,SAAA,CAAU,GAAA,CAAI,SAAA,EAAW,CAAA,EAAG,KAAA,CAAM,KAAK,QAAK,CAAC,CAAA,EAAG,SAAA,GAAY,CAAA,GAAI,CAAA,OAAA,EAAO,SAAS,CAAA,MAAA,CAAA,GAAW,EAAE,CAAA,CAAE,CAAA;AAAA,EACjG;AACA,EAAA,OAAO,SAAA;AACT","file":"chunk-CTJ6LVDH.js","sourcesContent":["import { round2 } from './money'\nimport type { CreateMovementInput, FinancialMovement, TransactionDirection } from './movement'\nimport type { DateRange, MoneyTotals } 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 /** The price table the sale was written in (spine 215). `null` clears it on update. */\n priceTableId?: string | null\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 /** The price table the lines were priced from (spine 215). Kept in metadata. */\n priceTableId?: 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 /** Also sum amount and paid over every matching line (the list's footer). */\n withTotals?: boolean\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/** Footer sums plus the forecasts, which the server cannot see (they are not bills). */\nexport function addForecastTotals(totals: MoneyTotals[], forecasts: Invoice[]): MoneyTotals[] {\n if (forecasts.length === 0) return totals\n const out = totals.map((t) => ({ ...t }))\n let house = out.find((t) => !t.currency)\n if (!house) { house = { total: 0, paid: 0 }; out.push(house) }\n for (const row of forecasts) house.total += row.totalAmount\n return out\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"]}
1
+ {"version":3,"sources":["../src/domain/invoice.ts"],"names":[],"mappings":";;;AAuNO,SAAS,UAAU,IAAA,EAA0B;AAClD,EAAA,OAAO,MAAA,CAAO,IAAA,CAAK,QAAA,GAAW,IAAA,CAAK,SAAA,IAAa,KAAK,QAAA,IAAY,CAAA,CAAA,IAAM,IAAA,CAAK,SAAA,IAAa,CAAA,CAAE,CAAA;AAC7F;AAGO,SAAS,aAAa,KAAA,EAA6B;AACxD,EAAA,OAAO,MAAA,CAAO,KAAA,CAAM,MAAA,CAAO,CAAC,GAAA,EAAK,IAAA,KAAS,GAAA,GAAM,SAAA,CAAU,IAAI,CAAA,EAAG,CAAC,CAAC,CAAA;AACrE;AAEO,SAAS,iBAAiB,KAAA,EAA8D;AAC7F,EAAA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A,EAAW;AAC1C,IAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,KAAA,CAAM,CAAA,EAAG,OAAO,CAAA;AACpC,IAAA,MAAM,SAAA,GAAY,KAAA,CAAM,MAAA,GAAS,KAAA,CAAM,MAAA;AACvC,IAAA,SAAA,CAAU,GAAA,CAAI,SAAA,EAAW,CAAA,EAAG,KAAA,CAAM,KAAK,QAAK,CAAC,CAAA,EAAG,SAAA,GAAY,CAAA,GAAI,CAAA,OAAA,EAAO,SAAS,CAAA,MAAA,CAAA,GAAW,EAAE,CAAA,CAAE,CAAA;AAAA,EACjG;AACA,EAAA,OAAO,SAAA;AACT","file":"chunk-HPJDTBVB.js","sourcesContent":["import { round2 } from './money'\nimport type { CreateMovementInput, FinancialMovement, TransactionDirection } from './movement'\nimport type { DateRange, MoneyTotals } 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 /** The price table the sale was written in (spine 215). `null` clears it on update. */\n priceTableId?: string | null\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 /** The price table the lines were priced from (spine 215). Kept in metadata. */\n priceTableId?: 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 /** Lines posted to any of these accounts — a chart group and its descendants. Wins over `accountId`. */\n accountIds?: 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 /** Also sum amount and paid over every matching line (the list's footer). */\n withTotals?: boolean\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/** Footer sums plus the forecasts, which the server cannot see (they are not bills). */\nexport function addForecastTotals(totals: MoneyTotals[], forecasts: Invoice[]): MoneyTotals[] {\n if (forecasts.length === 0) return totals\n const out = totals.map((t) => ({ ...t }))\n let house = out.find((t) => !t.currency)\n if (!house) { house = { total: 0, paid: 0 }; out.push(house) }\n for (const row of forecasts) house.total += row.totalAmount\n return out\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 // Newest due date first, the order the list reads in.\n return [...invoices, ...provisioned].sort((a, b) => (b.dueDate ?? '').localeCompare(a.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"]}
@@ -1,4 +1,4 @@
1
- import { buildBillInvoice, buildPayment, adjustmentDescription, adjustmentInvoice } from './chunk-MCSPCXQK.js';
1
+ import { buildBillInvoice, buildPayment, adjustmentDescription, adjustmentInvoice } from './chunk-NAEXIF3W.js';
2
2
  import { round2 } from './chunk-XVELDCSL.js';
3
3
 
4
4
  // src/data/reconcile.ts
@@ -77,5 +77,5 @@ async function runReconcileLink(provider, line, target, options = {}) {
77
77
  }
78
78
 
79
79
  export { runReconcileAsBill, runReconcileLink };
80
- //# sourceMappingURL=chunk-FNXIAIUZ.js.map
81
- //# sourceMappingURL=chunk-FNXIAIUZ.js.map
80
+ //# sourceMappingURL=chunk-IVIMTPAV.js.map
81
+ //# sourceMappingURL=chunk-IVIMTPAV.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/data/reconc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AEA,EAAA,MAAM,OAAA,GAAU,MAAM,QAAA,CAAS,WAAA;AAAA,IAC7B,aAAa,IAAA,EAAM,MAAA,CAAO,YAAY,MAAA,CAAO,UAAA,EAAY,QAAQ,OAAO;AAAA,GAC1E;AACA,EAAA,MAAM,SAAA,GAAY,MAAM,WAAA,CAAY,QAAA,EAAU,OAAO,CAAA;AACrD,EAAA,MAAM,QAAA,CAAS,kBAAkB,EAAE,cAAA,EAAgB,KAAK,EAAA,EAAI,iBAAA,EAAmB,WAAW,CAAA;AAE1F,EAAA,KAAA,MAAW,OAAO,WAAA,EAAa;AAC7B,IAAA,MAAM,UAAU,MAAM,QAAA,CAAS,cAAc,iBAAA,CAAkB,IAAA,EAAM,GAAG,CAAC,CAAA;AACzE,IAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,QAAA,EAAU,QAAQ,EAAE,CAAA;AAC9C,IAAA,MAAM,QAAA,CAAS,WAAA;AAAA,MACb,YAAA,CAAa,IAAA,EAAM,IAAA,CAAK,EAAA,EAAI,MAAA,CAAO,GAAA,CAAI,MAAM,CAAA,EAAG,OAAA,CAAQ,OAAA,EAAS,qBAAA,CAAsB,GAAG,CAAC;AAAA,KAC7F;AAAA,EACF;AACF","file":"chunk-FNXIAIUZ.js","sourcesContent":["import type { CreateInvoiceInput, InstallmentChargeInput } from '../domain/invoice'\nimport { round2 } from '../domain/money'\nimport type { FinancialMovement, MovementQuery, PayMovementInput } from '../domain/movement'\nimport {\n adjustmentInvoice, buildBillInvoice, buildPayment, adjustmentDescription,\n type ReconcileAdjustment, type ReconcileAsBillInput, type ReconcileLine, type ReconcilePaymentInput,\n} from '../domain/reconciliation'\n\n/**\n * The provider primitives reconciling runs on. Both adapters lend theirs, so the workflow is written\n * once; `reconcileMovement` here is the raw mark, never the public method, which would re-enter.\n */\nexport interface ReconcileCapableProvider {\n createInvoice(input: CreateInvoiceInput): Promise<{ id: string }>\n getMovements(query: MovementQuery): Promise<{ data: FinancialMovement[] }>\n payMovement(input: PayMovementInput): Promise<FinancialMovement>\n reconcileMovement(input: { bankMovementId: string; matchedMovementId?: string }): Promise<void>\n /** When present, interest/fine/discount become a line of the bill being settled (V1). */\n addInstallmentCharge?(input: InstallmentChargeInput): Promise<void>\n}\n\nasync function billOf(provider: ReconcileCapableProvider, invoiceId: string): Promise<FinancialMovement> {\n const { data } = await provider.getMovements({ invoiceId })\n const bill = data.find((m) => m.movementKind === 'bill')\n if (!bill) throw new Error('A conta foi criada sem parcela')\n return bill\n}\n\n/**\n * The payment's id, not what `payMovement` returned. The Supabase adapter returns the settled\n * installment, and the line's `matched_movement_id` references movements: tying it to the\n * installment id is refused by the foreign key, leaving the bill paid and the line pending.\n */\nasync function paymentIdOf(provider: ReconcileCapableProvider, settled: FinancialMovement): Promise<string> {\n if (settled.movementKind === 'payment') return settled.id\n const invoiceId = settled.invoiceId\n if (!invoiceId) throw new Error('A parcela quitada não aponta para uma conta')\n const { data } = await provider.getMovements({ invoiceId })\n const payments = data.filter((m) => m.movementKind === 'payment')\n const last = payments[payments.length - 1]\n if (!last) throw new Error('A conta foi quitada mas o pagamento não foi encontrado')\n return last.id\n}\n\n/** \"Post as bill\": the bill is born classified, paid, and proven by the line. */\nexport async function runReconcileAsBill(\n provider: ReconcileCapableProvider,\n line: ReconcileLine,\n input: ReconcileAsBillInput,\n): Promise<{ invoiceId: string }> {\n const invoice = await provider.createInvoice(buildBillInvoice(line, input))\n const bill = await billOf(provider, invoice.id)\n const settled = await provider.payMovement({\n ...buildPayment(line, bill.id, round2(line.amount), input.payment),\n metadata: input.receiptUrl ? { receiptUrl: input.receiptUrl } : undefined,\n })\n const paymentId = await paymentIdOf(provider, settled)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paymentId })\n return { invoiceId: invoice.id }\n}\n\n/** \"Link\": an open bill is settled by the line; a paid one is only tied, never paid again. */\nexport async function runReconcileLink(\n provider: ReconcileCapableProvider,\n line: ReconcileLine,\n target: { movementId: string; mode: 'settle' | 'link_only'; openAmount: number },\n options: { payment?: ReconcilePaymentInput; adjustments?: ReconcileAdjustment[]; partial?: boolean } = {},\n): Promise<void> {\n if (target.mode === 'link_only') {\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: target.movementId })\n return\n }\n\n // Paid in parts: this line pays what it carries and the bill keeps the rest\n // open, so the next transfer reconciles against the same bill.\n if (options.partial) {\n const amount = round2(line.amount)\n if (amount <= 0 || amount >= round2(target.openAmount)) {\n throw new Error('Pagamento parcial só quando a linha é menor que o saldo em aberto')\n }\n const paga = await provider.payMovement(buildPayment(line, target.movementId, amount, options.payment))\n const paymentId = await paymentIdOf(provider, paga)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paymentId })\n return\n }\n\n // Interest, fine and discount go onto the bill itself, as in V1: the line is\n // added, the installment becomes what the bank charged, and one payment\n // settles it all. The stand-alone adjustment bill is only for a provider\n // that cannot amend.\n const adjustments = (options.adjustments ?? []).filter((adj) => round2(adj.amount) > 0)\n if (provider.addInstallmentCharge && adjustments.length) {\n let due = target.openAmount\n for (const adj of adjustments) {\n await provider.addInstallmentCharge({\n installmentId: target.movementId,\n kind: adj.type,\n amount: round2(adj.amount),\n accountId: adj.accountId,\n description: adjustmentDescription(adj),\n })\n due += adj.type === 'discount' ? -round2(adj.amount) : round2(adj.amount)\n }\n const paid = await provider.payMovement(buildPayment(line, target.movementId, round2(due), options.payment))\n const paidId = await paymentIdOf(provider, paid)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paidId })\n return\n }\n\n const settled = await provider.payMovement(\n buildPayment(line, target.movementId, target.openAmount, options.payment),\n )\n const paymentId = await paymentIdOf(provider, settled)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paymentId })\n\n for (const adj of adjustments) {\n const invoice = await provider.createInvoice(adjustmentInvoice(line, adj))\n const bill = await billOf(provider, invoice.id)\n await provider.payMovement(\n buildPayment(line, bill.id, round2(adj.amount), options.payment, adjustmentDescription(adj)),\n )\n }\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QAAQ,CAAA;AACvF,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,OAAA,GAAU,MAAM,QAAA,CAAS,WAAA;AAAA,IAC7B,aAAa,IAAA,EAAM,MAAA,CAAO,YAAY,MAAA,CAAO,UAAA,EAAY,QAAQ,OAAO;AAAA,GAC1E;AACA,EAAA,MAAM,SAAA,GAAY,MAAM,WAAA,CAAY,QAAA,EAAU,OAAO,CAAA;AACrD,EAAA,MAAM,QAAA,CAAS,kBAAkB,EAAE,cAAA,EAAgB,KAAK,EAAA,EAAI,iBAAA,EAAmB,WAAW,CAAA;AAE1F,EAAA,KAAA,MAAW,OAAO,WAAA,EAAa;AAC7B,IAAA,MAAM,UAAU,MAAM,QAAA,CAAS,cAAc,iBAAA,CAAkB,IAAA,EAAM,GAAG,CAAC,CAAA;AACzE,IAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,QAAA,EAAU,QAAQ,EAAE,CAAA;AAC9C,IAAA,MAAM,QAAA,CAAS,WAAA;AAAA,MACb,YAAA,CAAa,IAAA,EAAM,IAAA,CAAK,EAAA,EAAI,MAAA,CAAO,GAAA,CAAI,MAAM,CAAA,EAAG,OAAA,CAAQ,OAAA,EAAS,qBAAA,CAAsB,GAAG,CAAC;AAAA,KAC7F;AAAA,EACF;AACF","file":"chunk-IVIMTPAV.js","sourcesContent":["import type { CreateInvoiceInput, InstallmentChargeInput } from '../domain/invoice'\nimport { round2 } from '../domain/money'\nimport type { FinancialMovement, MovementQuery, PayMovementInput } from '../domain/movement'\nimport {\n adjustmentInvoice, buildBillInvoice, buildPayment, adjustmentDescription,\n type ReconcileAdjustment, type ReconcileAsBillInput, type ReconcileLine, type ReconcilePaymentInput,\n} from '../domain/reconciliation'\n\n/**\n * The provider primitives reconciling runs on. Both adapters lend theirs, so the workflow is written\n * once; `reconcileMovement` here is the raw mark, never the public method, which would re-enter.\n */\nexport interface ReconcileCapableProvider {\n createInvoice(input: CreateInvoiceInput): Promise<{ id: string }>\n getMovements(query: MovementQuery): Promise<{ data: FinancialMovement[] }>\n payMovement(input: PayMovementInput): Promise<FinancialMovement>\n reconcileMovement(input: { bankMovementId: string; matchedMovementId?: string }): Promise<void>\n /** When present, interest/fine/discount become a line of the bill being settled (V1). */\n addInstallmentCharge?(input: InstallmentChargeInput): Promise<void>\n}\n\nasync function billOf(provider: ReconcileCapableProvider, invoiceId: string): Promise<FinancialMovement> {\n const { data } = await provider.getMovements({ invoiceId })\n const bill = data.find((m) => m.movementKind === 'bill')\n if (!bill) throw new Error('A conta foi criada sem parcela')\n return bill\n}\n\n/**\n * The payment's id, not what `payMovement` returned. The Supabase adapter returns the settled\n * installment, and the line's `matched_movement_id` references movements: tying it to the\n * installment id is refused by the foreign key, leaving the bill paid and the line pending.\n */\nasync function paymentIdOf(provider: ReconcileCapableProvider, settled: FinancialMovement): Promise<string> {\n if (settled.movementKind === 'payment') return settled.id\n const invoiceId = settled.invoiceId\n if (!invoiceId) throw new Error('A parcela quitada não aponta para uma conta')\n const { data } = await provider.getMovements({ invoiceId })\n const payments = data.filter((m) => m.movementKind === 'payment')\n const last = payments[payments.length - 1]\n if (!last) throw new Error('A conta foi quitada mas o pagamento não foi encontrado')\n return last.id\n}\n\n/** \"Post as bill\": the bill is born classified, paid, and proven by the line. */\nexport async function runReconcileAsBill(\n provider: ReconcileCapableProvider,\n line: ReconcileLine,\n input: ReconcileAsBillInput,\n): Promise<{ invoiceId: string }> {\n const invoice = await provider.createInvoice(buildBillInvoice(line, input))\n const bill = await billOf(provider, invoice.id)\n const settled = await provider.payMovement({\n ...buildPayment(line, bill.id, round2(line.amount), input.payment),\n metadata: input.receiptUrl ? { receiptUrl: input.receiptUrl } : undefined,\n })\n const paymentId = await paymentIdOf(provider, settled)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paymentId })\n return { invoiceId: invoice.id }\n}\n\n/** \"Link\": an open bill is settled by the line; a paid one is only tied, never paid again. */\nexport async function runReconcileLink(\n provider: ReconcileCapableProvider,\n line: ReconcileLine,\n target: { movementId: string; mode: 'settle' | 'link_only'; openAmount: number },\n options: { payment?: ReconcilePaymentInput; adjustments?: ReconcileAdjustment[]; partial?: boolean } = {},\n): Promise<void> {\n if (target.mode === 'link_only') {\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: target.movementId })\n return\n }\n\n // Paid in parts: this line pays what it carries and the bill keeps the rest\n // open, so the next transfer reconciles against the same bill.\n if (options.partial) {\n const amount = round2(line.amount)\n if (amount <= 0 || amount >= round2(target.openAmount)) {\n throw new Error('Pagamento parcial só quando a linha é menor que o saldo em aberto')\n }\n const paga = await provider.payMovement(buildPayment(line, target.movementId, amount, options.payment))\n const paymentId = await paymentIdOf(provider, paga)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paymentId })\n return\n }\n\n // Interest, fine and discount go onto the bill itself, as in V1: the line is\n // added, the installment becomes what the bank charged, and one payment\n // settles it all. The stand-alone adjustment bill is only for a provider\n // that cannot amend.\n const adjustments = (options.adjustments ?? []).filter((adj) => round2(adj.amount) > 0)\n if (provider.addInstallmentCharge && adjustments.length) {\n let due = target.openAmount\n for (const adj of adjustments) {\n await provider.addInstallmentCharge({\n installmentId: target.movementId,\n kind: adj.type,\n amount: round2(adj.amount),\n accountId: adj.accountId,\n description: adjustmentDescription(adj),\n })\n due += adj.type === 'discount' ? -round2(adj.amount) : round2(adj.amount)\n }\n const paid = await provider.payMovement(buildPayment(line, target.movementId, round2(due), options.payment))\n const paidId = await paymentIdOf(provider, paid)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paidId })\n return\n }\n\n const settled = await provider.payMovement(\n buildPayment(line, target.movementId, target.openAmount, options.payment),\n )\n const paymentId = await paymentIdOf(provider, settled)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paymentId })\n\n for (const adj of adjustments) {\n const invoice = await provider.createInvoice(adjustmentInvoice(line, adj))\n const bill = await billOf(provider, invoice.id)\n await provider.payMovement(\n buildPayment(line, bill.id, round2(adj.amount), options.payment, adjustmentDescription(adj)),\n )\n }\n}\n"]}
@@ -186,5 +186,5 @@ function resolveCandidates(candidates) {
186
186
  }
187
187
 
188
188
  export { ADJUSTMENT_LABEL, adjustmentDescription, adjustmentDirection, adjustmentGap, adjustmentInvoice, adjustmentsMismatch, buildBillInvoice, buildPayment, candidateScore, candidateTolerance, itemsMismatch, pageTotals, reconciliationPaymentNote, resolveCandidates, signedAdjustment, statementLegOf, statementLinesPage, sumItems, toReconcileLine, transferForStatementLine };
189
- //# sourceMappingURL=chunk-MCSPCXQK.js.map
190
- //# sourceMappingURL=chunk-MCSPCXQK.js.map
189
+ //# sourceMappingURL=chunk-NAEXIF3W.js.map
190
+ //# sourceMappingURL=chunk-NAEXIF3W.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/domain/reconciliation.ts"],"names":[],"mappings":";;;AAgPO,SAAS,gBAAgB,IAAA,EAA4C;AAC1E,EAAA,OAAO;AAAA,IACL,IAAI,IAAA,CAAK,EAAA;AAAA,IACT,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,MAAM,IAAA,CAAK,IAAA;AAAA,IACX,WAAW,IAAA,CAAK,SAAA;AAAA,IAChB,aAAa,IAAA,CAAK,WAAA;AAAA,IAClB,eAAe,IAAA,CAAK,aAAA;AAAA,IACpB,gBAAgB,IAAA,CAAK;AAAA,GACvB;AACF;AAGO,SAAS,mBAAmB,KAAA,EAA4F;AAC7H,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,KAAK,GAAA,CAAI,CAAA,EAAG,KAAK,KAAA,CAAM,KAAA,EAAO,IAAA,IAAQ,CAAC,CAAC,CAAA;AAAA,IAC9C,QAAA,EAAU,IAAA,CAAK,GAAA,CAAI,GAAA,EAAK,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,KAAA,CAAM,KAAA,EAAO,QAAA,IAAY,EAAE,CAAC,CAAC;AAAA,GACxE;AACF;AAEO,SAAS,WAAW,IAAA,EAAuI;AA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AAS,EAAE,EAAE,CAAA,CACjF,GAAA,CAAI,CAAC,CAAA,KAAM;AACV,IAAA,MAAM,IAAI,CAAA,CAAE,QAAA;AACZ,IAAA,MAAM,IAAA,GAAO,OAAO,CAAC,CAAA;AACrB,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,CAAA;AAAA,MACX,IAAA,EAAM,OAAO,WAAA,GAAuB,QAAA;AAAA,MACpC,YAAY,IAAA,GAAO,CAAA,GAAI,OAAO,CAAA,CAAE,MAAA,GAAS,EAAE,UAAU;AAAA,KACvD;AAAA,EACF,CAAC,CAAA;AACL","file":"chunk-NAEXIF3W.js","sourcesContent":["import type { CreateInvoiceInput, Invoice } from './invoice'\nimport { round2 } from './money'\nimport type { FinancialMovement, PayMovementInput, TransactionDirection } from './movement'\nimport type { DateRange } from './query'\nimport type { CreateTransferInput, TransferResult } from './transfer'\n\n/** A normalized bank-statement line, ready to import. */\nexport interface BankStatementLine {\n /** Provider-unique id; with `externalSource`, the idempotency key. */\n externalId: string\n externalSource: string\n /** `credit` is money in, `debit` money out. */\n direction: TransactionDirection\n /** Always positive; the sign is the direction. */\n amount: number\n /** YYYY-MM-DD settlement date. */\n date: string\n description: string\n /** Falls back to the import's account. */\n bankAccountId?: string\n effectiveAt?: string\n /** The bank's balance after this line, what proves the statement adds up. */\n balanceAfter?: number\n counterpartyName?: string\n counterpartyDocument?: string\n document?: string\n code?: string\n category?: string\n transactionType?: string\n rawPayload?: Record<string, unknown>\n}\n\n/**\n * A statement line as stored: evidence, not a ledger entry. A fresh line cannot have two legs\n * because nothing says yet what it posts against; matched, the movement is the economic event.\n */\nexport interface ImportedStatementLine extends BankStatementLine {\n id: string\n tenantId?: string\n unitId?: string\n bankAccountId?: string\n /** The provider withdrew it; it stops showing instead of disappearing. */\n providerDeleted?: boolean\n reconciledAt?: string\n /** Empty with `reconciledAt` set means accepted on its own. */\n matchedMovementId?: string\n createdAt?: string\n updatedAt?: string\n /** Who is on the other side of a reconciled line, read from the matched entry. */\n matchedCounterpartyName?: string\n /** The invoice a reconciled line proves. */\n matchedInvoiceId?: string\n}\n\nexport interface ImportBankTransactionsInput {\n /** Default account for lines that carry none. */\n bankAccountId?: string\n lines: BankStatementLine[]\n}\n\nexport interface ImportBankTransactionsResult {\n imported: number\n /** Lines skipped because they were already imported. */\n duplicates: number\n}\n\nexport interface UnreconciledQuery {\n bankAccountId?: string\n dateRange?: DateRange\n}\n\nexport type StatementLineStatus = 'reconciled' | 'pending'\n\nexport interface StatementLinesQuery {\n bankAccountId?: string\n dateRange?: DateRange\n /** Absent means both. */\n direction?: TransactionDirection\n status?: StatementLineStatus\n /** Matches the description and the provider's identifiers. */\n search?: string\n /** Leaves out investments, auto-investment sweeps and their yields (code-based). */\n hideInvestments?: boolean\n /** 1-based. */\n page?: number\n pageSize?: number\n}\n\nexport interface StatementLinesResult {\n rows: ImportedStatementLine[]\n /** Lines the filter found, not the page's. */\n total: number\n page: number\n pageSize: number\n /** Sums of the page only. */\n pageCredits: number\n pageDebits: number\n pageBalance: number\n /** Sums of every line the filter found; absent when they could not be read. */\n totals?: StatementLinesTotals\n}\n\nexport interface StatementLinesTotals {\n credits: number\n debits: number\n balance: number\n}\n\n/** An internal movement that may match an imported line. */\nexport interface ReconciliationCandidate {\n movement: FinancialMovement\n invoice?: Invoice\n /** 0..1 confidence from amount and date proximity. */\n score: number\n /** Installments in the bill, for the «1/3» column. */\n installmentCount?: number\n}\n\n/** Free search over the bills a statement line can settle — V1's \"Vincular manualmente\". */\nexport interface ReconciliationTargetQuery {\n /** YYYY-MM-DD, on the due date */\n dueFrom?: string\n dueTo?: string\n /** `all` = open + paid-but-not-yet-reconciled */\n status?: 'all' | 'open' | 'paid'\n /** Counterparty, number or description */\n search?: string\n amountMin?: number\n amountMax?: number\n page?: number\n pageSize?: number\n}\n\nexport interface ReconciliationTargetResult {\n data: ReconciliationCandidate[]\n hasMore: boolean\n}\n\n/** \"Mark as transfer\": the line is money moving between two of the house's accounts. */\nexport interface ReconcileAsTransferInput {\n bankMovementId: string\n /** The other end: destination of an outflow, source of an inflow. */\n counterAccountId: string\n notes?: string\n}\n\n/** \"Post as bill\": nothing matches because the entry never existed, so it is born here. */\nexport interface ReconcileAsBillInput {\n bankMovementId: string\n /** Defaults to the line's direction; the operator may correct it for a refund. */\n direction?: TransactionDirection\n contactId?: string\n contactName?: string\n /** Falls back to the provider's description. */\n description?: string\n /** Chart account; what makes the bill appear classified in the income statement. */\n accountId?: string\n costCenterId?: string\n /** Falls back to the line's date. */\n dueDate?: string\n /** Empty means one line with the statement's description and amount; otherwise they must add up to it. */\n items?: ReconcileBillItemInput[]\n /** Absent settles against the statement's account without naming a method. */\n payment?: ReconcilePaymentInput\n receiptUrl?: string\n}\n\nexport interface ReconcileBillItemInput {\n description: string\n quantity: number\n unitPrice: number\n /** Falls back to the bill's chart account. */\n accountId?: string\n costCenterId?: string\n}\n\n/** How the money moved, in the same shape the invoice payment form speaks. */\nexport interface ReconcilePaymentInput {\n paymentMethodId?: string\n paymentMethodTypeId?: string\n bankAccountId?: string\n cashSessionId?: string\n cardBrand?: string\n cardInstallments?: number\n /** Falls back to the line's date. */\n paymentDate?: string\n notes?: string\n}\n\n/**\n * Interest, fine or discount explaining the gap between a line and the bill it settles. It is its\n * own classified entry, paid the same day against the same account, because the payment RPC\n * refuses to pay more than what is open.\n */\nexport interface ReconcileAdjustment {\n type: 'interest' | 'fine' | 'discount'\n /** Always positive; the type gives the sign. */\n amount: number\n description?: string\n accountId?: string\n}\n\nexport interface ReconcileInput {\n bankMovementId: string\n /** Omit to accept the line on its own. */\n matchedMovementId?: string\n /** `settle` pays an open bill with the line; `link_only` (the default) ties a bill already paid. */\n mode?: 'settle' | 'link_only'\n payment?: ReconcilePaymentInput\n adjustments?: ReconcileAdjustment[]\n /** The line pays only PART of the bill (paid in two transfers): it settles\n * the line's amount and the rest stays open for the next line. */\n partial?: boolean\n}\n\n/**\n * What reading a photographed receipt produced. The statement's amount, date and account stay the\n * source of truth; the receipt adds who, what and where it is classified.\n */\nexport interface ReceiptReading {\n contactName?: string\n /** A chart-account hint, by code or name. */\n accountHint?: string\n items?: ReconcileBillItemInput[]\n document?: string\n /** What the reading had to guess or could not read. */\n warnings?: string[]\n}\n\n/** A statement line reduced to what reconciling needs. */\nexport interface ReconcileLine {\n id: string\n amount: number\n date: string\n direction: TransactionDirection\n description?: string\n bankAccountId?: string\n externalSource: string\n}\n\nexport function toReconcileLine(line: ImportedStatementLine): ReconcileLine {\n return {\n id: line.id,\n amount: line.amount,\n date: line.date,\n direction: line.direction,\n description: line.description,\n bankAccountId: line.bankAccountId,\n externalSource: line.externalSource,\n }\n}\n\n/** The page the screen asked for, clamped: 1-based, 50 by default, never above 200. */\nexport function statementLinesPage(query?: Pick<StatementLinesQuery, 'page' | 'pageSize'>): { page: number; pageSize: number } {\n return {\n page: Math.max(1, Math.trunc(query?.page ?? 1)),\n pageSize: Math.min(200, Math.max(1, Math.trunc(query?.pageSize ?? 50))),\n }\n}\n\nexport function pageTotals(rows: Pick<ImportedStatementLine, 'direction' | 'amount'>[]): Pick<StatementLinesResult, 'pageCredits' | 'pageDebits' | 'pageBalance'> {\n let credits = 0\n let debits = 0\n for (const row of rows) {\n if (row.direction === 'credit') credits += row.amount\n else debits += row.amount\n }\n return { pageCredits: round2(credits), pageDebits: round2(debits), pageBalance: round2(credits - debits) }\n}\n\n/** How far a candidate's amount may be from the line: 2%, at least a cent. */\nexport function candidateTolerance(amount: number): number {\n return Math.max(0.01, round2(amount * 0.02))\n}\n\n/** Confidence that a movement is the line: 70% amount closeness, 30% date within a month. */\nexport function candidateScore(\n line: { amount: number; date?: string },\n movement: { amount: number; dueDate?: string; paymentDate?: string },\n): number {\n const amount = line.amount\n const amountScore = amount > 0 ? Math.max(0, 1 - Math.abs((Number(movement.amount) || 0) - amount) / amount) : 0\n const reference = movement.dueDate ?? movement.paymentDate\n const days = line.date && reference\n ? Math.abs((new Date(line.date).getTime() - new Date(reference).getTime()) / 86400000)\n : 30\n const dateScore = Math.max(0, 1 - days / 30)\n return round2(0.7 * amountScore + 0.3 * dateScore)\n}\n\n/**\n * The transfer a statement line evidences. The statement's account is always one end: an outflow\n * left it, so it is the source; inverting this moves the consolidated balance twice the wrong way.\n */\nexport function transferForStatementLine(line: ReconcileLine, input: ReconcileAsTransferInput): CreateTransferInput {\n if (!line.bankAccountId) throw new Error('A linha do extrato não tem conta vinculada')\n if (line.bankAccountId === input.counterAccountId) throw new Error('Origem e destino não podem ser a mesma conta')\n const isOut = line.direction === 'debit'\n return {\n fromAccountId: isOut ? line.bankAccountId : input.counterAccountId,\n toAccountId: isOut ? input.counterAccountId : line.bankAccountId,\n amount: line.amount,\n date: line.date,\n notes: input.notes || `Transferência identificada na conciliação${line.description ? ` (${line.description})` : ''}`,\n }\n}\n\n/** The leg on the statement's own account: the one the line proves. */\nexport function statementLegOf(line: Pick<ReconcileLine, 'direction'>, transfer: TransferResult): string {\n return line.direction === 'debit' ? transfer.debitMovementId : transfer.creditMovementId\n}\n\nexport function sumItems(items: ReconcileBillItemInput[] | undefined): number {\n return round2((items ?? []).reduce((total, item) =>\n total + (Number(item.quantity) || 0) * (Number(item.unitPrice) || 0), 0))\n}\n\n/** Do the items add up to the line? Returns the blocking message, or null when they do. */\nexport function itemsMismatch(\n items: ReconcileBillItemInput[] | undefined,\n lineAmount: number,\n fmt: (n: number) => string,\n): string | null {\n const filled = (items ?? []).filter((i) => i.description.trim())\n if (filled.length === 0) return null\n const sum = sumItems(filled)\n const diff = round2(sum - round2(lineAmount))\n if (Math.abs(diff) < 0.01) return null\n return diff > 0\n ? `Os itens somam ${fmt(sum)} — ${fmt(diff)} a MAIS que o extrato (${fmt(lineAmount)}).`\n : `Os itens somam ${fmt(sum)} — ${fmt(-diff)} a MENOS que o extrato (${fmt(lineAmount)}).`\n}\n\n/**\n * The bill a statement line evidences. The direction is not a choice: an outflow is a payable and an\n * inflow a receivable. The installment is always the statement's amount.\n */\nexport function buildBillInvoice(line: ReconcileLine, input: ReconcileAsBillInput): CreateInvoiceInput {\n const amount = round2(line.amount)\n const dueDate = input.dueDate || line.date\n const fallback = input.description?.trim() || line.description || 'Lançamento do extrato'\n const filled = (input.items ?? []).filter((i) => i.description.trim())\n\n const items = filled.length > 0\n ? filled.map((item) => ({\n itemKind: 'other' as const,\n description: item.description.trim(),\n quantity: Number(item.quantity) || 1,\n unitPrice: round2(item.unitPrice),\n accountId: item.accountId || input.accountId,\n costCenterId: item.costCenterId || input.costCenterId,\n }))\n : [{\n itemKind: 'other' as const,\n description: fallback,\n quantity: 1,\n unitPrice: amount,\n accountId: input.accountId,\n costCenterId: input.costCenterId,\n }]\n\n const sum = sumItems(filled)\n if (filled.length > 0 && Math.abs(sum - amount) >= 0.01) {\n throw new Error(`Os itens somam ${sum.toFixed(2)} e o extrato diz ${amount.toFixed(2)}`)\n }\n\n return {\n direction: line.direction,\n invoiceDate: line.date,\n contactId: input.contactId,\n contactName: input.contactName,\n observations: `Lançado a partir do extrato (${line.externalSource})`,\n metadata: input.receiptUrl ? { receiptUrl: input.receiptUrl } : undefined,\n items,\n installments: [{\n direction: line.direction,\n movementKind: 'bill',\n amount,\n dueDate,\n installmentNumber: 1,\n }],\n }\n}\n\nexport function reconciliationPaymentNote(line: ReconcileLine): string {\n const origin = line.description?.trim()\n return origin\n ? `Quitação via conciliação bancária — ${origin}`\n : 'Quitação via conciliação bancária'\n}\n\n/**\n * The payment a statement line makes. The line already answers when, where and how much, and the\n * method is the statement itself, so nothing is asked; `payment` exists for callers that pay\n * differently from what the statement says.\n */\nexport function buildPayment(\n line: ReconcileLine,\n movementId: string,\n amount: number,\n payment: ReconcilePaymentInput | undefined,\n notes?: string,\n): PayMovementInput {\n return {\n movementId,\n amount: round2(amount),\n paymentDate: payment?.paymentDate || line.date,\n paymentMethodId: payment?.paymentMethodId,\n paymentMethodTypeId: payment?.paymentMethodTypeId,\n bankAccountId: payment?.bankAccountId || line.bankAccountId,\n cashSessionId: payment?.cashSessionId,\n cardBrand: payment?.cardBrand,\n cardInstallments: payment?.cardInstallments,\n notes: payment?.notes?.trim() || notes || reconciliationPaymentNote(line),\n }\n}\n\nexport const ADJUSTMENT_LABEL: Record<ReconcileAdjustment['type'], string> = {\n interest: 'Juros',\n fine: 'Multa',\n discount: 'Desconto',\n}\n\n/** Interest and fines cost whoever pays the bill; a discount gives back. */\nexport function adjustmentDirection(\n billDirection: TransactionDirection,\n type: ReconcileAdjustment['type'],\n): TransactionDirection {\n const costs = type !== 'discount'\n if (billDirection === 'debit') return costs ? 'debit' : 'credit'\n return costs ? 'credit' : 'debit'\n}\n\n/** How much an adjustment pushes the total up (+) or down (−). */\nexport function signedAdjustment(adj: ReconcileAdjustment): number {\n return adj.type === 'discount' ? -round2(adj.amount) : round2(adj.amount)\n}\n\n/** Positive when the bank took more than the bill asked (interest, fine), negative for a discount. */\nexport function adjustmentGap(lineAmount: number, billOpenAmount: number): number {\n return round2(lineAmount - billOpenAmount)\n}\n\n/** Do the adjustments explain the gap? Returns what is left to explain, or null. */\nexport function adjustmentsMismatch(\n adjustments: ReconcileAdjustment[] | undefined,\n gap: number,\n fmt: (n: number) => string,\n): string | null {\n const sum = round2((adjustments ?? []).reduce((total, a) => total + signedAdjustment(a), 0))\n const rest = round2(gap - sum)\n if (Math.abs(rest) < 0.01) return null\n return rest > 0\n ? `Faltam ${fmt(rest)} para explicar a diferença — aumente os juros/multa ou reduza o desconto.`\n : `Sobram ${fmt(-rest)} nos ajustes — reduza os juros/multa ou aumente o desconto.`\n}\n\nexport function adjustmentDescription(adj: ReconcileAdjustment): string {\n return adj.description?.trim() || ADJUSTMENT_LABEL[adj.type]\n}\n\n/** The entry an adjustment becomes, paid the same day as the line. */\nexport function adjustmentInvoice(line: ReconcileLine, adj: ReconcileAdjustment): CreateInvoiceInput {\n const direction = adjustmentDirection(line.direction, adj.type)\n return {\n direction,\n invoiceDate: line.date,\n observations: `${ADJUSTMENT_LABEL[adj.type]} da conciliação (${line.externalSource})`,\n items: [{\n itemKind: 'other',\n description: adjustmentDescription(adj),\n quantity: 1,\n unitPrice: round2(adj.amount),\n accountId: adj.accountId,\n }],\n installments: [{\n direction,\n movementKind: 'bill',\n amount: round2(adj.amount),\n dueDate: line.date,\n installmentNumber: 1,\n }],\n }\n}\n\n/** A candidate and what reconciling with it does. */\nexport interface ResolvedCandidate {\n candidate: ReconciliationCandidate\n /** `settle` pays an open bill; `link_only` ties one already paid, since paying again doubles the money. */\n mode: 'settle' | 'link_only'\n /** What is still owed (0 on a settled bill). */\n openAmount: number\n}\n\nconst isPaid = (m: FinancialMovement) =>\n m.movementKind === 'payment' || m.status === 'paid' || round2(m.paidAmount) >= round2(m.amount)\n\n/**\n * Says per candidate whether reconciling settles or only links, and drops the bill whose payment is\n * also in the list: a paid bill comes back twice, and two identical rows are two chances to pick wrong.\n */\nexport function resolveCandidates(candidates: ReconciliationCandidate[]): ResolvedCandidate[] {\n const payments = candidates.filter((c) => c.movement.movementKind === 'payment')\n const settled = new Set(payments.map((c) => c.movement.settlesMovementId).filter(Boolean) as string[])\n\n return candidates\n .filter((c) => !(c.movement.movementKind === 'bill' && settled.has(c.movement.id)))\n .map((c) => {\n const m = c.movement\n const paid = isPaid(m)\n return {\n candidate: c,\n mode: paid ? 'link_only' as const : 'settle' as const,\n openAmount: paid ? 0 : round2(m.amount - m.paidAmount),\n }\n })\n}\n"]}
@@ -2,11 +2,11 @@ import { summarizeLedger, trailingWindow } from './chunk-T7WIM2V7.js';
2
2
  import { matchStatementLines } from './chunk-ZFUQBYBG.js';
3
3
  import { emptyStatement, isRealized, buildStatement, ledgerBalance } from './chunk-HJPUHTI2.js';
4
4
  import { transferLegs } from './chunk-YUNLQYOZ.js';
5
- import { cancellationReason, assertReschedule, lineTotal, invoiceTotal, itemsDescription, invoiceStatusOf } from './chunk-CTJ6LVDH.js';
5
+ import { cancellationReason, assertReschedule, lineTotal, invoiceTotal, itemsDescription, invoiceStatusOf } from './chunk-HPJDTBVB.js';
6
6
  import { openAmount, paymentFee } from './chunk-4GXBOEI3.js';
7
7
  import { sessionCashFlow, closingDifference } from './chunk-56NQHYL7.js';
8
- import { runReconcileAsBill, runReconcileLink } from './chunk-FNXIAIUZ.js';
9
- import { toReconcileLine, transferForStatementLine, statementLegOf, candidateTolerance, candidateScore, statementLinesPage, pageTotals } from './chunk-MCSPCXQK.js';
8
+ import { runReconcileAsBill, runReconcileLink } from './chunk-IVIMTPAV.js';
9
+ import { toReconcileLine, transferForStatementLine, statementLegOf, candidateTolerance, candidateScore, statementLinesPage, pageTotals } from './chunk-NAEXIF3W.js';
10
10
  import { round2 } from './chunk-XVELDCSL.js';
11
11
  import { summarizeSyncStatus } from './chunk-3QNU7XUB.js';
12
12
 
@@ -137,8 +137,9 @@ function createMockFinancialProvider(options) {
137
137
  if (query.status) results = results.filter((i) => matchesStatus(i.status, query.status));
138
138
  if (query.contactId) results = results.filter((i) => i.contactId === query.contactId);
139
139
  if (query.unitId) results = results.filter((i) => i.unitId === query.unitId);
140
- if (query.accountId) {
141
- const invoiceIds = new Set(store.invoiceItems.filter((item) => item.accountId === query.accountId).map((item) => item.invoiceId));
140
+ const accountIds = query.accountIds?.length ? query.accountIds : query.accountId ? [query.accountId] : [];
141
+ if (accountIds.length > 0) {
142
+ const invoiceIds = new Set(store.invoiceItems.filter((item) => !!item.accountId && accountIds.includes(item.accountId)).map((item) => item.invoiceId));
142
143
  results = results.filter((invoice) => invoiceIds.has(invoice.id));
143
144
  }
144
145
  if (query.costCenterId) {
@@ -728,7 +729,15 @@ function createMockFinancialProvider(options) {
728
729
  results = [...results].sort((a, b) => b.date.localeCompare(a.date));
729
730
  const { page, pageSize } = statementLinesPage(query);
730
731
  const rows = results.slice((page - 1) * pageSize, page * pageSize);
731
- return { rows, total: results.length, page, pageSize, ...pageTotals(rows) };
732
+ const all = pageTotals(results);
733
+ return {
734
+ rows,
735
+ total: results.length,
736
+ page,
737
+ pageSize,
738
+ ...pageTotals(rows),
739
+ totals: { credits: all.pageCredits, debits: all.pageDebits, balance: all.pageBalance }
740
+ };
732
741
  },
733
742
  async getUnreconciled(query) {
734
743
  let results = store.statementLines.filter((l) => !l.reconciledAt && !l.providerDeleted);
@@ -898,5 +907,5 @@ function createMockFinancialProvider(options) {
898
907
  }
899
908
 
900
909
  export { createMockFinancialProvider };
901
- //# sourceMappingURL=chunk-ZBLZLHIS.js.map
902
- //# sourceMappingURL=chunk-ZBLZLHIS.js.map
910
+ //# sourceMappingURL=chunk-TUYTZEW4.js.map
911
+ //# sourceMappingURL=chunk-TUYTZEW4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/data/mock.ts"],"names":["bill"],"mappings":";;;;;;;;;;;;;AAiCA,IAAI,MAAA,GAAS,CAAA;AACb,SAAS,GAAA,GAAc;AACrB,EAAA,OAAO,OAAO,MAAA,EAAQ,CAAA;AACxB;AAEA,SAAS,GAAA,GAAc;AACrB,EAAA,OAAA,iBAAO,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAChC;AAEA,SAAS,KAAA,GAAgB;AACvB,EAAA,OAAA,qBAAW,IAAA,EAAK,EAAE,aAAY,CAAE,KAAA,CAAM,GAAG,EAAE,CAAA;AAC7C;AAEA,SAAS,gBAAA,CAAiB,SAA6B,KAAA,EAA4B;AACjF,EAAA,IAAI,CAAC,KAAA,IAAS,CAAC,OAAA,EAAS,OAAO,IAAA;AAC/B,EAAA,OAAO,OAAA,IAAW,KAAA,CAAM,IAAA,IAAQ,OAAA,IAAW,KAAA,CAAM,EAAA;AACnD;AAEA,SAAS,aAAA,CAAgC,QAAW,MAAA,EAA2B;AAC7E,EAAA,IAAI,CAAC,QAAQ,OAAO,IAAA;AACpB,EAAA,IAAI,MAAM,OAAA,CAAQ,MAAM,GAAG,OAAO,MAAA,CAAO,SAAS,MAAM,CAAA;AACxD,EAAA,OAAO,MAAA,KAAW,MAAA;AACpB;AAEA,SAAS,QAAA,CAAY,KAAA,EAAY,IAAA,EAAe,QAAA,EAAuC;AACrF,EAAA,MAAM,IAAI,IAAA,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AAA;AAAA,IACT,CAAA;AAAA,IAEA,MAAM,UAAA,CAAW,EAAA,EAAY,MAAA,EAAsC;AACjE,MAAA,MAAM,IAAA,GAAO,MAAM,KAAA,CAAM,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,OAAO,EAAE,CAAA;AAChD,MAAA,IAAI,CAAC,IAAA,EAAM,MAAM,IAAI,MAAM,uBAAuB,CAAA;AAClD,MAAA,IAAA,CAAK,MAAA,GAAS,WAAA;AACd,MAAA,IAAA,CAAK,YAAA,GAAe,MAAA;AACpB,MAAA,IAAA,CAAK,YAAY,GAAA,EAAI;AACrB,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,GACF;AAEA,EAAA,OAAO,QAAA;AACT","file":"chunk-TUYTZEW4.js","sourcesContent":["import type { BankAccount, CreateBankAccountInput } from '../domain/account'\nimport type { CardTransaction } from '../domain/card'\nimport {\n closingDifference, sessionCashFlow,\n type CashSession, type CashSessionSummary, type CloseCashSessionInput, type OpenCashSessionInput,\n} from '../domain/cash-session'\nimport type { ChartOfAccountsNode, CostCenter } from '../domain/chart-of-accounts'\nimport {\n assertReschedule, cancellationReason, invoiceStatusOf, invoiceTotal, itemsDescription, lineTotal,\n type CreateInvoiceInput, type CreateInvoiceItemInput, type Invoice, type InvoiceItem, type InvoiceQuery, type InvoiceStatus,\n} from '../domain/invoice'\nimport { round2 } from '../domain/money'\nimport { openAmount, paymentFee, type FinancialMovement, type MovementQuery, type MovementStatus, type PayMovementInput } from '../domain/movement'\nimport type { CreateNotaFiscalInput, NotaFiscal, NotaFiscalQuery } from '../domain/nota-fiscal'\nimport type { PaymentMethod, PaymentMethodType } from '../domain/payment-method'\nimport type { DateRange, PaginatedResult } from '../domain/query'\nimport {\n candidateScore, candidateTolerance, pageTotals, statementLegOf, statementLinesPage, toReconcileLine, transferForStatementLine,\n type ImportedStatementLine,\n} from '../domain/reconciliation'\nimport type { RecurringBill, SaveRecurringBillInput } from '../domain/recurring-bill'\nimport { summarizeLedger, trailingWindow, type DreQuery, type DreRow, type FinancialSummary } from '../domain/report'\nimport { buildStatement, emptyStatement, isRealized, ledgerBalance, type StatementQuery, type StatementResult } from '../domain/statement'\nimport { matchStatementLines, type MovementContext } from '../domain/statement-match'\nimport { transferLegs, type CreateTransferInput, type TransferResult } from '../domain/transfer'\nimport type { FinancialDataProvider } from './provider'\nimport { runReconcileAsBill, runReconcileLink, type ReconcileCapableProvider } from './reconcile'\nimport { summarizeSyncStatus } from './sync-status'\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nlet nextId = 1\nfunction uid(): string {\n return String(nextId++)\n}\n\nfunction now(): string {\n return new Date().toISOString()\n}\n\nfunction today(): string {\n return new Date().toISOString().slice(0, 10)\n}\n\nfunction matchesDateRange(dateStr: string | undefined, range?: DateRange): boolean {\n if (!range || !dateStr) return true\n return dateStr >= range.from && dateStr <= range.to\n}\n\nfunction matchesStatus<T extends string>(status: T, filter?: T | T[]): boolean {\n if (!filter) return true\n if (Array.isArray(filter)) return filter.includes(status)\n return status === filter\n}\n\nfunction paginate<T>(items: T[], page?: number, pageSize?: number): PaginatedResult<T> {\n const p = page ?? 1\n const ps = pageSize ?? 50\n const start = (p - 1) * ps\n return { data: items.slice(start, start + ps), total: items.length }\n}\n\n// ---------------------------------------------------------------------------\n// In-memory store\n// ---------------------------------------------------------------------------\n\ninterface MockStore {\n invoices: Invoice[]\n invoiceItems: InvoiceItem[]\n movements: FinancialMovement[]\n /** A evidencia do extrato — nao e movimento; ver migration 112. */\n statementLines: ImportedStatementLine[]\n /** Que conta tem extrato, e por qual provedor; ver migration 113. */\n statementSources: Array<{ accountId: string; provider: string; isActive: boolean; lastSyncedAt?: string | null; lastSyncStatus?: string | null; lastSyncError?: string | null }>\n bankAccounts: BankAccount[]\n cashSessions: CashSession[]\n paymentMethods: PaymentMethod[]\n paymentMethodTypes: PaymentMethodType[]\n chartOfAccounts: ChartOfAccountsNode[]\n costCenters: CostCenter[]\n cardTransactions: CardTransaction[]\n notas: NotaFiscal[]\n recurringBills: RecurringBill[]\n}\n\nfunction createStore(options?: MockFinancialProviderOptions): MockStore {\n const tenantId = 'mock-tenant'\n const seed = options?.seed\n\n const defaultPMTypes: PaymentMethodType[] = (options?.paymentMethodTypes ?? [\n { name: 'Cash', transactionType: 'cash' },\n { name: 'Credit Card', transactionType: 'credit_card' },\n { name: 'Debit Card', transactionType: 'debit_card' },\n { name: 'PIX', transactionType: 'pix' },\n { name: 'Bank Transfer', transactionType: 'transfer' },\n ]).map((t) => ({\n id: uid(),\n name: t.name,\n transactionType: t.transactionType,\n isActive: true,\n tenantId,\n createdAt: now(),\n }))\n\n const cashAccount: BankAccount = {\n id: uid(),\n name: 'Main Cash Register',\n accountType: 'cash_physical',\n currentBalance: 0,\n initialBalance: 0,\n isActive: true,\n tenantId,\n createdAt: now(),\n updatedAt: now(),\n }\n\n const bankAccount: BankAccount = {\n id: uid(),\n name: 'Business Checking',\n accountType: 'bank',\n bankName: 'Main Bank',\n currentBalance: 0,\n initialBalance: 0,\n isActive: true,\n tenantId,\n createdAt: now(),\n updatedAt: now(),\n }\n\n return {\n // Seeded data (when provided) makes the module render as if the user already\n // has accounts + transactions — a populated Summary/Statements instead of the\n // empty onboarding state. Seed arrays are copied so the caller's data is not mutated.\n invoices: seed?.invoices ? [...seed.invoices] : [],\n invoiceItems: seed?.invoiceItems ? [...seed.invoiceItems] : [],\n movements: seed?.movements ? [...seed.movements] : [],\n statementLines: [],\n statementSources: [],\n bankAccounts: seed?.bankAccounts ? [...seed.bankAccounts] : [cashAccount, bankAccount],\n cashSessions: [],\n paymentMethods: seed?.paymentMethods ? [...seed.paymentMethods] : [],\n paymentMethodTypes: defaultPMTypes,\n chartOfAccounts: [],\n costCenters: [],\n cardTransactions: [],\n notas: [],\n recurringBills: seed?.recurringBills ? [...seed.recurringBills] : [],\n }\n}\n\n// ---------------------------------------------------------------------------\n// Mock provider factory\n// ---------------------------------------------------------------------------\n\n/**\n * Pre-populated store data. Any omitted collection stays empty (except\n * bankAccounts, which fall back to the two default mock accounts when absent).\n * Pass full domain objects — the mock treats them as the existing ledger.\n */\nexport interface MockFinancialSeed {\n bankAccounts?: BankAccount[]\n invoices?: Invoice[]\n invoiceItems?: InvoiceItem[]\n movements?: FinancialMovement[]\n paymentMethods?: PaymentMethod[]\n recurringBills?: RecurringBill[]\n}\n\nexport interface MockFinancialProviderOptions {\n paymentMethodTypes?: Array<{ name: string; transactionType?: string }>\n /** Pre-seed the in-memory store so the module renders populated (not the empty state). */\n seed?: MockFinancialSeed\n}\n\nexport function createMockFinancialProvider(options?: MockFinancialProviderOptions): FinancialDataProvider {\n const store = createStore(options)\n const tenantId = 'mock-tenant'\n\n function recalcInvoiceStatus(invoice: Invoice): void {\n const bills = store.movements.filter((m) => m.invoiceId === invoice.id && m.movementKind === 'bill')\n invoice.status = invoiceStatusOf(invoice, bills, today())\n invoice.updatedAt = now()\n }\n\n /** O carimbo cru: a linha foi conciliada, e contra quem. Sem orquestração. */\n function markReconciled(statementLineId: string, matchedMovementId?: string): void {\n const line = store.statementLines.find((l) => l.id === statementLineId)\n const internal = matchedMovementId\n ? store.movements.find((m) => m.id === matchedMovementId)\n : undefined\n if (line) {\n line.reconciledAt = now()\n line.matchedMovementId = matchedMovementId\n // A conta que a linha prova — é para onde «Ver conta» leva.\n line.matchedInvoiceId = internal?.invoiceId\n line.matchedCounterpartyName = internal?.invoiceId\n ? store.invoices.find((i) => i.id === internal.invoiceId)?.contactName\n : undefined\n line.updatedAt = now()\n }\n if (internal) { internal.reconciledAt = now(); internal.updatedAt = now() }\n }\n\n // `reconcileMovement` do facade é o carimbo, nunca o método público: o\n // público reentraria em si mesmo e a conta seria quitada duas vezes.\n function reconcileFacade(): ReconcileCapableProvider {\n return {\n createInvoice: (input) => provider.createInvoice(input),\n getMovements: (query) => provider.getMovements(query as never),\n payMovement: (input) => provider.payMovement(input as never),\n reconcileMovement: async ({ bankMovementId, matchedMovementId }) => {\n markReconciled(bankMovementId, matchedMovementId)\n },\n }\n }\n\n const provider: FinancialDataProvider = {\n // --- Invoices ---\n async getInvoices(query: InvoiceQuery): Promise<PaginatedResult<Invoice>> {\n let results = [...store.invoices]\n if (query.direction) results = results.filter((i) => i.direction === query.direction)\n if (query.status) results = results.filter((i) => matchesStatus(i.status, query.status as InvoiceStatus | InvoiceStatus[]))\n if (query.contactId) results = results.filter((i) => i.contactId === query.contactId)\n if (query.unitId) results = results.filter((i) => i.unitId === query.unitId)\n const accountIds = query.accountIds?.length ? query.accountIds : query.accountId ? [query.accountId] : []\n if (accountIds.length > 0) {\n const invoiceIds = new Set(store.invoiceItems.filter((item) => !!item.accountId && accountIds.includes(item.accountId)).map((item) => item.invoiceId))\n results = results.filter((invoice) => invoiceIds.has(invoice.id))\n }\n if (query.costCenterId) {\n const invoiceIds = new Set(store.invoiceItems.filter((item) => item.costCenterId === query.costCenterId).map((item) => item.invoiceId))\n results = results.filter((invoice) => invoiceIds.has(invoice.id))\n }\n if (query.fiscalNumber) {\n const nf = query.fiscalNumber.toLowerCase()\n results = results.filter((i) => i.fiscalNumber?.toLowerCase().includes(nf))\n }\n if (query.bankAccountId) {\n const pagas = new Set(\n store.movements\n .filter((m) => m.bankAccountId === query.bankAccountId)\n .map((m) => m.invoiceId)\n .filter(Boolean) as string[],\n )\n results = results.filter((i) => pagas.has(i.id))\n }\n if (query.dateRange) {\n const from = query.dateRange.from.slice(0, 10)\n // Same contract as the Supabase provider: unpaid lines due before the window ride along.\n const overdueBefore = (i: Invoice) => query.includeOverdue === true\n && !!i.dueDate && i.dueDate.slice(0, 10) < from\n && (i.status === 'overdue' || i.status === 'partial' || (i.status === 'open' && i.dueDate.slice(0, 10) < today()))\n results = results.filter((i) => matchesDateRange(i.invoiceDate, query.dateRange) || overdueBefore(i))\n }\n if (query.search) {\n const s = query.search.toLowerCase()\n results = results.filter((i) =>\n i.contactName?.toLowerCase().includes(s) ||\n i.observations?.toLowerCase().includes(s) ||\n i.fiscalNumber?.toLowerCase().includes(s)\n )\n }\n results.sort((a, b) => b.createdAt.localeCompare(a.createdAt))\n return paginate(results, query.page, query.pageSize)\n },\n\n async getInvoiceById(id: string): Promise<Invoice | null> {\n return store.invoices.find((i) => i.id === id) ?? null\n },\n\n async getInvoiceItems(invoiceId: string): Promise<InvoiceItem[]> {\n return store.invoiceItems.filter((i) => i.invoiceId === invoiceId)\n },\n\n async createInvoice(input: CreateInvoiceInput): Promise<Invoice> {\n const invoiceId = uid()\n const totalAmount = invoiceTotal(input.items)\n const itemsSummary = itemsDescription(input.items)\n\n const invoice: Invoice = {\n id: invoiceId,\n direction: input.direction,\n invoiceDate: input.invoiceDate,\n fiscalNumber: input.fiscalNumber,\n totalAmount,\n paidAmount: 0,\n status: 'open',\n totalInstallments: input.installments.length || 1,\n contactId: input.contactId,\n ...(input.priceTableId ? { priceTableId: input.priceTableId } : {}),\n contactName: input.contactName,\n cashSessionId: input.cashSessionId,\n unitId: input.unitId,\n observations: input.observations,\n itemsSummary: itemsSummary || undefined,\n metadata: input.metadata,\n tenantId,\n createdAt: now(),\n updatedAt: now(),\n }\n store.invoices.push(invoice)\n\n // Create items\n for (const itemInput of input.items) {\n const itemTotal = lineTotal(itemInput)\n const item: InvoiceItem = {\n id: uid(),\n invoiceId,\n itemKind: itemInput.itemKind,\n referenceId: itemInput.referenceId,\n description: itemInput.description,\n quantity: itemInput.quantity,\n unitPrice: itemInput.unitPrice,\n totalAmount: itemTotal,\n discount: itemInput.discount ?? 0,\n surcharge: itemInput.surcharge ?? 0,\n accountId: itemInput.accountId,\n costCenterId: itemInput.costCenterId,\n metadata: itemInput.metadata,\n createdAt: now(),\n }\n store.invoiceItems.push(item)\n }\n\n // Create installment movements\n for (const movInput of input.installments) {\n const movement: FinancialMovement = {\n id: uid(),\n invoiceId,\n direction: input.direction,\n movementKind: movInput.movementKind,\n amount: movInput.amount,\n paidAmount: 0,\n status: 'pending',\n dueDate: movInput.dueDate,\n installmentNumber: movInput.installmentNumber,\n paymentMethodId: movInput.paymentMethodId,\n bankAccountId: movInput.bankAccountId,\n notes: movInput.notes,\n metadata: movInput.metadata,\n tenantId,\n createdAt: now(),\n updatedAt: now(),\n }\n store.movements.push(movement)\n }\n\n return invoice\n },\n\n async updateInvoice(id: string, data: Partial<Invoice>): Promise<Invoice> {\n const invoice = store.invoices.find((i) => i.id === id)\n if (!invoice) throw new Error(`Invoice ${id} not found`)\n Object.assign(invoice, data, { updatedAt: now() })\n return invoice\n },\n\n async updateInstallment(id: string, data: { dueDate?: string; amount?: number; metadata?: Record<string, unknown> }): Promise<void> {\n const mov = store.movements.find((mv) => mv.id === id)\n if (!mov) return\n if (data.dueDate !== undefined) mov.dueDate = data.dueDate\n if (data.amount !== undefined) mov.amount = data.amount\n if (data.metadata !== undefined) mov.metadata = data.metadata\n },\n\n async replaceInvoiceItems(invoiceId: string, items: CreateInvoiceItemInput[]): Promise<void> {\n const invoice = store.invoices.find((i) => i.id === invoiceId)\n if (!invoice) throw new Error(`Invoice ${invoiceId} not found`)\n store.invoiceItems = store.invoiceItems.filter((it) => it.invoiceId !== invoiceId)\n for (const item of items) {\n store.invoiceItems.push({\n id: uid(),\n invoiceId,\n itemKind: item.itemKind,\n referenceId: item.referenceId,\n description: item.description,\n quantity: item.quantity,\n unitPrice: item.unitPrice,\n totalAmount: lineTotal(item),\n discount: item.discount ?? 0,\n surcharge: item.surcharge ?? 0,\n accountId: item.accountId,\n costCenterId: item.costCenterId,\n metadata: item.metadata,\n createdAt: now(),\n } as (typeof store.invoiceItems)[number])\n }\n // O total é a soma das linhas: gravar um sem o outro deixa a conta\n // somando um valor e cobrando outro.\n invoice.totalAmount = invoiceTotal(items)\n invoice.updatedAt = now()\n },\n\n async rescheduleInvoice(invoiceId: string, installments: Array<{ dueDate: string; amount: number; metadata?: Record<string, unknown> }>): Promise<void> {\n const invoice = store.invoices.find((i) => i.id === invoiceId)\n if (!invoice) throw new Error(`Invoice ${invoiceId} not found`)\n const old = store.movements.filter((mv) => mv.invoiceId === invoiceId && mv.movementKind === 'bill')\n assertReschedule(invoice, old, installments)\n // O que estava pendurado na parcela de número N volta para a parcela N.\n const carried = new Map(old.map((mv) => [mv.installmentNumber ?? 1, mv.metadata]))\n store.movements = store.movements.filter((mv) => !old.includes(mv))\n installments.forEach((inst, i) => {\n store.movements.push({\n id: uid(),\n invoiceId,\n direction: invoice.direction,\n movementKind: 'bill',\n amount: inst.amount,\n paidAmount: 0,\n status: 'pending',\n dueDate: inst.dueDate,\n installmentNumber: i + 1,\n metadata: inst.metadata ?? carried.get(i + 1),\n tenantId,\n createdAt: now(),\n updatedAt: now(),\n } as FinancialMovement)\n })\n },\n\n async cancelInvoice(input): Promise<void> {\n cancellationReason(input)\n const invoice = store.invoices.find((i) => i.id === input.invoiceId)\n if (!invoice) throw new Error(`Invoice ${input.invoiceId} not found`)\n invoice.status = 'cancelled'\n invoice.updatedAt = now()\n // Cancel all pending movements\n store.movements\n .filter((m) => m.invoiceId === input.invoiceId && m.status === 'pending')\n .forEach((m) => { m.status = 'cancelled'; m.updatedAt = now() })\n },\n\n // --- Movements ---\n async getMovements(query: MovementQuery): Promise<PaginatedResult<FinancialMovement>> {\n let results = [...store.movements]\n // `invoiceId` existe no contrato desde sempre e o mock o ignorava: quem\n // pedia as parcelas de UMA conta recebia as do store inteiro, e a\n // primeira da lista passava por \"a parcela desta fatura\". Foi assim que\n // o ajuste da conciliação quitou a conta errada.\n if (query.invoiceId) results = results.filter((m) => m.invoiceId === query.invoiceId)\n if (query.direction) results = results.filter((m) => m.direction === query.direction)\n if (query.status) results = results.filter((m) => matchesStatus(m.status, query.status as MovementStatus | MovementStatus[]))\n if (query.bankAccountId) results = results.filter((m) => m.bankAccountId === query.bankAccountId)\n if (query.cashSessionId) results = results.filter((m) => m.cashSessionId === query.cashSessionId)\n if (query.dateRange) results = results.filter((m) => matchesDateRange(m.dueDate, query.dateRange))\n results.sort((a, b) => a.dueDate.localeCompare(b.dueDate))\n return paginate(results, query.page, query.pageSize)\n },\n\n // O mock não guarda faturas no formato do read model; devolve a conta vazia\n // em vez de inventar números que a tela apresentaria como saldo do cliente.\n async getClientAccount(personId: string) {\n return { personId, contracted: 0, paid: 0, open: 0, invoices: [] }\n },\n\n async getCardReceivables() { return [] },\n\n async reverseMovement(movementId: string, reason: string): Promise<void> {\n const m = store.movements.find((x) => x.id === movementId)\n if (m) { m.status = 'cancelled'; m.notes = [m.notes, `Estorno: ${reason}`].filter(Boolean).join(' · ') }\n },\n\n async payMovement(input: PayMovementInput): Promise<FinancialMovement> {\n const bill = store.movements.find((m) => m.id === input.movementId)\n if (!bill) throw new Error(`Movement ${input.movementId} not found`)\n\n // Net card settlement: derive the processing/MDR fee from the payment method (credits only).\n const method = input.paymentMethodId ? store.paymentMethods.find((pm) => pm.id === input.paymentMethodId) : undefined\n const thisFee = paymentFee(input.amount, method?.discountValue ?? 0, bill.direction)\n\n // 1. Record the cash event as its OWN payment movement (one row per payment).\n const payment: FinancialMovement = {\n id: uid(),\n invoiceId: bill.invoiceId,\n direction: bill.direction,\n movementKind: 'payment',\n amount: input.amount,\n paidAmount: input.amount,\n feeAmount: thisFee,\n status: 'paid',\n settlesMovementId: bill.id,\n dueDate: bill.dueDate,\n paymentDate: input.paymentDate,\n installmentNumber: bill.installmentNumber,\n paymentMethodId: input.paymentMethodId,\n paymentMethodTypeId: input.paymentMethodTypeId,\n bankAccountId: input.bankAccountId,\n cashSessionId: input.cashSessionId,\n cardBrand: input.cardBrand,\n cardInstallments: input.cardInstallments,\n notes: input.notes,\n metadata: input.metadata,\n tenantId,\n createdAt: now(),\n updatedAt: now(),\n }\n store.movements.push(payment)\n\n // 2. Update the bill (obligation) cache: cumulative paid + status. Clear its cash\n // fields so it stops being a cash event (the payment row is now the cash event).\n bill.paidAmount = round2(bill.paidAmount + input.amount)\n bill.status = bill.paidAmount >= bill.amount ? 'paid' : 'partial'\n bill.paymentDate = undefined\n bill.bankAccountId = undefined\n bill.updatedAt = now()\n\n // Update bank account balance by the NET cash impact (credit nets the fee).\n if (input.bankAccountId) {\n const account = store.bankAccounts.find((a) => a.id === input.bankAccountId)\n if (account) {\n if (bill.direction === 'credit') {\n account.currentBalance = round2(account.currentBalance + (input.amount - thisFee))\n } else {\n account.currentBalance = round2(account.currentBalance - input.amount)\n }\n account.updatedAt = now()\n }\n }\n\n // 3. Recalculate invoice status from its bills\n if (bill.invoiceId) {\n const invoice = store.invoices.find((i) => i.id === bill.invoiceId)\n if (invoice) {\n const bills = store.movements.filter((m) => m.invoiceId === invoice.id && m.movementKind === 'bill')\n invoice.paidAmount = bills.reduce((sum, m) => sum + m.paidAmount, 0)\n recalcInvoiceStatus(invoice)\n }\n }\n\n return payment\n },\n\n async cancelMovement(id: string): Promise<void> {\n const movement = store.movements.find((m) => m.id === id)\n if (!movement) throw new Error(`Movement ${id} not found`)\n movement.status = 'cancelled'\n movement.updatedAt = now()\n },\n\n // --- Transfers (between accounts) ---\n async createTransfer(input: CreateTransferInput): Promise<TransferResult> {\n const transferId = uid()\n const [out, into] = transferLegs(input, transferId)\n const debitMovementId = uid()\n const creditMovementId = uid()\n const base = {\n movementKind: 'transfer' as const,\n amount: input.amount,\n paidAmount: input.amount,\n feeAmount: 0,\n status: 'paid' as const,\n dueDate: input.date,\n paymentDate: input.date,\n notes: input.notes,\n tenantId,\n createdAt: now(),\n updatedAt: now(),\n }\n store.movements.push({ ...base, id: debitMovementId, ...out })\n store.movements.push({ ...base, id: creditMovementId, ...into })\n // Reflect in stored balances.\n const from = store.bankAccounts.find((a) => a.id === input.fromAccountId)\n const to = store.bankAccounts.find((a) => a.id === input.toAccountId)\n if (from) { from.currentBalance = round2(from.currentBalance - input.amount); from.updatedAt = now() }\n if (to) { to.currentBalance = round2(to.currentBalance + input.amount); to.updatedAt = now() }\n return { transferId, debitMovementId, creditMovementId }\n },\n\n // --- Bank Accounts ---\n // Espelha a view da 113: só conta com ORIGEM ativa. Sem isso o mock diria\n // que o filtro funciona quando ele não filtra nada.\n async getStatementAccounts() {\n const comOrigem = new Set(store.statementSources.filter((o) => o.isActive).map((o) => o.accountId))\n return store.bankAccounts.filter((a) => comOrigem.has(a.id))\n },\n\n async getStatementSyncStatus(input) {\n return summarizeSyncStatus(store.statementSources.filter((o) =>\n o.isActive && (!input?.bankAccountId || o.accountId === input.bankAccountId)))\n },\n\n async getBankAccounts(): Promise<BankAccount[]> {\n return store.bankAccounts.filter((a) => a.isActive)\n },\n\n async getAccountsByIds(ids: string[]): Promise<BankAccount[]> {\n return store.bankAccounts.filter((a) => ids.includes(a.id))\n },\n\n async searchFinancialAccounts(query: string, limit = 20): Promise<BankAccount[]> {\n const term = query.trim().toLocaleLowerCase('pt-BR')\n if (term.length < 2) return []\n return store.bankAccounts\n .filter((account) => account.isActive && account.name.toLocaleLowerCase('pt-BR').includes(term))\n .sort((a, b) => a.name.localeCompare(b.name, 'pt-BR'))\n .slice(0, limit)\n },\n\n async createBankAccount(data: CreateBankAccountInput): Promise<BankAccount> {\n const account: BankAccount = {\n id: uid(),\n name: data.name,\n accountType: data.accountType,\n bankName: data.bankName,\n accountNumber: data.accountNumber,\n agencyNumber: data.agencyNumber,\n currentBalance: data.initialBalance ?? 0,\n initialBalance: data.initialBalance ?? 0,\n creditLimit: data.creditLimit,\n dueDay: data.dueDay,\n closingDay: data.closingDay,\n isActive: true,\n unitId: data.unitId,\n tenantId,\n createdAt: now(),\n updatedAt: now(),\n }\n store.bankAccounts.push(account)\n return account\n },\n\n async updateBankAccount(id: string, data: Partial<BankAccount>): Promise<BankAccount> {\n const account = store.bankAccounts.find((a) => a.id === id)\n if (!account) throw new Error(`Bank account ${id} not found`)\n Object.assign(account, data, { updatedAt: now() })\n return account\n },\n\n // --- Cash Sessions ---\n async getCashSessions(bankAccountId?: string): Promise<CashSession[]> {\n let results = [...store.cashSessions]\n if (bankAccountId) results = results.filter((s) => s.bankAccountId === bankAccountId)\n return results.sort((a, b) => b.openedAt.localeCompare(a.openedAt))\n },\n\n async getOpenSession(bankAccountId: string): Promise<CashSession | null> {\n return store.cashSessions.find((s) => s.bankAccountId === bankAccountId && s.status === 'open') ?? null\n },\n\n async openCashSession(input: OpenCashSessionInput): Promise<CashSession> {\n const account = store.bankAccounts.find((a) => a.id === input.bankAccountId)\n const session: CashSession = {\n id: uid(),\n bankAccountId: input.bankAccountId,\n bankAccountName: account?.name,\n status: 'open',\n openedAt: now(),\n openedByUserId: input.openedByUserId,\n openedByName: input.openedByName,\n openingBalance: input.openingBalance,\n unitId: input.unitId,\n tenantId,\n createdAt: now(),\n }\n store.cashSessions.push(session)\n return session\n },\n\n async closeCashSession(input: CloseCashSessionInput): Promise<CashSession> {\n const session = store.cashSessions.find((s) => s.id === input.sessionId)\n if (!session) throw new Error(`Cash session ${input.sessionId} not found`)\n\n const flow = sessionCashFlow(store.movements.filter((m) => m.cashSessionId === session.id && m.status === 'paid'))\n const { expectedBalance, difference } = closingDifference(session.openingBalance, flow, input.closingBalance)\n\n session.status = 'closed'\n session.closedAt = now()\n session.closedByUserId = input.closedByUserId\n session.closedByName = input.closedByName\n session.closingBalance = input.closingBalance\n session.expectedBalance = expectedBalance\n session.difference = difference\n session.notes = input.notes\n\n return session\n },\n\n async getCashSessionSummary(sessionId: string): Promise<CashSessionSummary> {\n const session = store.cashSessions.find((s) => s.id === sessionId)\n if (!session) throw new Error(`Cash session ${sessionId} not found`)\n return { session, ...sessionCashFlow(store.movements.filter((m) => m.cashSessionId === sessionId && m.status === 'paid')) }\n },\n\n // --- Payment Methods ---\n async getPaymentMethods(): Promise<PaymentMethod[]> {\n return store.paymentMethods.filter((pm) => pm.isActive)\n },\n\n async getPaymentMethodTypes(): Promise<PaymentMethodType[]> {\n return store.paymentMethodTypes.filter((t) => t.isActive)\n },\n\n // --- Chart of Accounts ---\n async getChartOfAccounts(): Promise<ChartOfAccountsNode[]> {\n return store.chartOfAccounts.filter((n) => n.isActive)\n },\n\n async resolveChartAccountRefs(refs: string[]): Promise<Record<string, string>> {\n const ids = new Set(store.chartOfAccounts.map((account) => account.id))\n return Object.fromEntries(refs.filter((ref) => ids.has(ref)).map((ref) => [ref, ref]))\n },\n\n async getCostCenters(): Promise<CostCenter[]> {\n return store.costCenters.filter((c) => c.isActive)\n },\n\n // --- Card Transactions ---\n async getCardTransactions(dateRange?: DateRange): Promise<CardTransaction[]> {\n let results = [...store.cardTransactions]\n if (dateRange) results = results.filter((t) => matchesDateRange(t.expectedDate, dateRange))\n return results.sort((a, b) => a.expectedDate.localeCompare(b.expectedDate))\n },\n\n // --- Statements (ERP extract: opening balance + realized cash + per-row net/fee) ---\n async getStatement(query: StatementQuery): Promise<StatementResult> {\n const consolidated = !query.bankAccountId\n const scopeAccounts = consolidated\n ? store.bankAccounts.filter((a) => a.isActive)\n : store.bankAccounts.filter((a) => a.id === query.bankAccountId)\n if (!consolidated && scopeAccounts.length === 0) return emptyStatement(query.bankAccountId)\n const accountIds = new Set(scopeAccounts.map((a) => a.id))\n const accountNameById = new Map(store.bankAccounts.map((a) => [a.id, a.name]))\n const initialSum = scopeAccounts.reduce((s, a) => s + a.initialBalance, 0)\n const invoiceById = (id?: string) => (id ? store.invoices.find((i) => i.id === id) : undefined)\n\n // Consolidated => all realized movements, including those with no bank account.\n const inScope = store.movements.filter((m) =>\n isRealized(m) && (consolidated || (m.bankAccountId && accountIds.has(m.bankAccountId))))\n\n const statement = buildStatement({\n openingBalance: ledgerBalance(initialSum, inScope.filter((m) => (m.paymentDate ?? '') < query.dateRange.from)),\n movements: inScope\n .filter((m) => matchesDateRange(m.paymentDate, query.dateRange))\n .sort((a, b) => (a.paymentDate ?? '').localeCompare(b.paymentDate ?? '') || a.createdAt.localeCompare(b.createdAt)),\n consolidated,\n accountNameOf: (id) => accountNameById.get(id),\n invoiceOf: (movement) => invoiceById(movement.invoiceId),\n })\n\n for (const e of statement.entries) {\n const mid = e.movement.matchedMovementId\n const mm = mid ? store.movements.find((m) => m.id === mid) : undefined\n if (!mm) continue\n const inv = invoiceById(mm.invoiceId)\n e.reconciledWith = {\n movementId: mm.id,\n description: mm.notes ?? undefined,\n invoiceId: mm.invoiceId,\n fiscalNumber: inv?.fiscalNumber,\n contactName: inv?.contactName,\n }\n }\n\n return {\n ...statement,\n accountId: query.bankAccountId,\n accountCurrentBalance: ledgerBalance(initialSum, inScope.filter((m) => (m.paymentDate ?? '') <= today())),\n }\n },\n\n async getDre(query: DreQuery): Promise<DreRow[]> {\n const rows: DreRow[] = []\n for (const account of store.chartOfAccounts.filter((candidate) => candidate.accountType === 'revenue' || candidate.accountType === 'expense')) {\n rows.push({\n accountId: account.id,\n accountCode: account.code,\n accountName: account.name,\n accountType: account.accountType as 'revenue' | 'expense',\n parentAccountId: account.parentId,\n statementCode: account.code,\n statementName: account.name,\n unclassified: false,\n amount: 0,\n discount: 0,\n lineCount: 0,\n })\n }\n for (const invoice of store.invoices.filter((candidate) =>\n candidate.invoiceDate.startsWith(String(query.year)) && (!query.unitId || candidate.unitId === query.unitId))) {\n for (const item of store.invoiceItems.filter((candidate) => candidate.invoiceId === invoice.id)) {\n const account = store.chartOfAccounts.find((candidate) => candidate.id === item.accountId)\n const accountType = invoice.direction === 'credit' ? 'revenue' : 'expense'\n rows.push({\n unitId: invoice.unitId,\n competenceMonth: `${invoice.invoiceDate.slice(0, 7)}-01`,\n accountId: account?.id,\n accountCode: account?.code,\n accountName: account?.name,\n accountType,\n parentAccountId: account?.parentId,\n statementCode: account?.accountType === accountType ? account.code : undefined,\n statementName: account?.accountType === accountType ? account.name : undefined,\n unclassified: !account || account.accountType !== accountType,\n amount: item.totalAmount,\n discount: item.discount,\n lineCount: 1,\n })\n }\n }\n return rows\n },\n\n // --- Summary ---\n async getSummary(dateRange?: DateRange): Promise<FinancialSummary> {\n const todayStr = today()\n return summarizeLedger({\n accounts: store.bankAccounts,\n movements: store.movements,\n today: todayStr,\n window: dateRange ?? trailingWindow(todayStr),\n })\n },\n\n // --- Recurring payables and receivables ---\n async getRecurringBills(direction) {\n return store.recurringBills\n .filter((bill) => bill.direction === direction)\n .sort((a, b) => Number(b.isActive) - Number(a.isActive) || a.description.localeCompare(b.description))\n },\n\n async saveRecurringBill(input: SaveRecurringBillInput) {\n const timestamp = now()\n const existing = input.id ? store.recurringBills.find((bill) => bill.id === input.id) : undefined\n const bill: RecurringBill = {\n id: existing?.id ?? uid(),\n direction: input.direction,\n description: input.description.trim(),\n counterpartyPersonId: input.counterpartyPersonId,\n counterpartyName: existing?.counterpartyName,\n amount: round2(input.amount),\n items: input.items.map((item) => ({ ...item })),\n unitId: input.unitId || null,\n chartAccountId: input.chartAccountId || null,\n costCenterId: input.costCenterId || null,\n frequency: input.frequency,\n dueDay: input.dueDay,\n startsOn: input.startsOn,\n endsOn: input.endsOn || null,\n isActive: input.isActive ?? existing?.isActive ?? true,\n notes: input.notes?.trim() || null,\n createdAt: existing?.createdAt ?? timestamp,\n updatedAt: timestamp,\n }\n if (existing) Object.assign(existing, bill)\n else store.recurringBills.push(bill)\n return bill\n },\n\n async updateRecurringBill(id, patch) {\n const bill = store.recurringBills.find((candidate) => candidate.id === id)\n if (!bill) throw new Error('Recurring bill not found')\n if (patch.isActive !== undefined) bill.isActive = patch.isActive\n if (patch.endsOn !== undefined) bill.endsOn = patch.endsOn\n bill.updatedAt = now()\n },\n\n async runRecurring() {\n return { created: 0, total: 0 }\n },\n\n // --- Conciliação Bancária ---\n // Espelha o provider real: a linha do extrato mora em `store.statementLines`,\n // não em `store.movements`. O mock tinha a linha como movimento e por isso\n // passava verde sobre o defeito que o banco recusava (migration 112).\n async importBankTransactions(input) {\n let imported = 0, duplicates = 0\n for (const line of input.lines) {\n const key = `${line.externalSource}:${line.externalId}`\n if (store.statementLines.some((l) => `${l.externalSource}:${l.externalId}` === key)) { duplicates++; continue }\n store.statementLines.push({\n ...line,\n id: uid(),\n amount: Math.abs(line.amount),\n bankAccountId: line.bankAccountId ?? input.bankAccountId,\n providerDeleted: false,\n createdAt: now(),\n updatedAt: now(),\n })\n imported++\n }\n return { imported, duplicates }\n },\n\n async getStatementLines(query) {\n let results = store.statementLines.filter((l) => !l.providerDeleted)\n if (query?.bankAccountId) results = results.filter((l) => l.bankAccountId === query.bankAccountId)\n if (query?.dateRange) results = results.filter((l) => matchesDateRange(l.date, query.dateRange))\n if (query?.direction) results = results.filter((l) => l.direction === query.direction)\n if (query?.status === 'reconciled') results = results.filter((l) => !!l.reconciledAt)\n else if (query?.status === 'pending') results = results.filter((l) => !l.reconciledAt)\n const term = (query?.search ?? '').trim().toLocaleLowerCase('pt-BR')\n if (term) {\n const casa = (v?: string) => (v ?? '').toLocaleLowerCase('pt-BR').includes(term)\n results = results.filter((l) =>\n casa(l.description) || casa(l.counterpartyName) || casa(l.counterpartyDocument)\n || casa(l.document) || casa(l.code) || casa(l.category)\n || casa(l.transactionType) || casa(l.externalId))\n }\n results = [...results].sort((a, b) => b.date.localeCompare(a.date))\n const { page, pageSize } = statementLinesPage(query)\n const rows = results.slice((page - 1) * pageSize, page * pageSize)\n const all = pageTotals(results)\n return {\n rows, total: results.length, page, pageSize, ...pageTotals(rows),\n totals: { credits: all.pageCredits, debits: all.pageDebits, balance: all.pageBalance },\n }\n },\n\n async getUnreconciled(query) {\n let results = store.statementLines.filter((l) => !l.reconciledAt && !l.providerDeleted)\n if (query?.bankAccountId) results = results.filter((l) => l.bankAccountId === query.bankAccountId)\n if (query?.dateRange) results = results.filter((l) => matchesDateRange(l.date, query.dateRange))\n return [...results].sort((a, b) => b.date.localeCompare(a.date))\n },\n\n async suggestReconciliation(statementLineId) {\n const line = store.statementLines.find((l) => l.id === statementLineId)\n if (!line) return []\n const tol = candidateTolerance(line.amount)\n return store.movements\n .filter((m) => !m.externalSource && !m.reconciledAt && m.direction === line.direction\n && Math.abs(m.amount - line.amount) <= tol)\n .map((m) => ({\n movement: m,\n invoice: m.invoiceId ? store.invoices.find((i) => i.id === m.invoiceId) : undefined,\n score: candidateScore(line, m),\n }))\n .sort((a, b) => b.score - a.score)\n .slice(0, 25)\n },\n\n async searchReconciliationTargets(statementLineId, query) {\n const line = store.statementLines.find((l) => l.id === statementLineId)\n if (!line) return { data: [], hasMore: false }\n const status = query.status ?? 'all'\n const termo = query.search?.trim().toLocaleLowerCase('pt-BR')\n const rows = store.movements\n .filter((m) => !m.externalSource && !m.reconciledAt && m.direction === line.direction)\n .filter((m) => m.status !== 'cancelled')\n .filter((m) => {\n const paga = m.movementKind === 'payment' || m.status === 'paid'\n return status === 'all' || (status === 'paid' ? paga : !paga)\n })\n .filter((m) => !query.dueFrom || (m.dueDate ?? '') >= query.dueFrom)\n .filter((m) => !query.dueTo || (m.dueDate ?? '') <= query.dueTo)\n .filter((m) => query.amountMin == null || m.amount >= query.amountMin)\n .filter((m) => query.amountMax == null || m.amount <= query.amountMax)\n .map((m) => ({ movement: m, invoice: m.invoiceId ? store.invoices.find((i) => i.id === m.invoiceId) : undefined }))\n .filter(({ movement, invoice }) => !termo\n || `${invoice?.contactName ?? ''} ${invoice?.fiscalNumber ?? ''} ${movement.notes ?? ''}`.toLocaleLowerCase('pt-BR').includes(termo))\n .sort((a, b) => (a.movement.dueDate ?? '').localeCompare(b.movement.dueDate ?? ''))\n const pageSize = query.pageSize ?? 50\n const start = ((query.page ?? 1) - 1) * pageSize\n return {\n data: rows.slice(start, start + pageSize).map((c) => ({ ...c, score: 0 })),\n hasMore: rows.length > start + pageSize,\n }\n },\n\n // A mesma cabeça da conciliação de verdade (match-statement), sobre a\n // memória: valor, nome e data, e um lançamento por linha.\n async suggestReconciliationBatch(lines) {\n const contexto = new Map<string, MovementContext>()\n for (const movement of store.movements) {\n const invoice = movement.invoiceId ? store.invoices.find((i) => i.id === movement.invoiceId) : undefined\n if (invoice) contexto.set(movement.id, { contactName: invoice.contactName, invoice })\n }\n const candidatos = store.movements.filter((m) => !m.externalSource && !m.reconciledAt)\n return matchStatementLines(lines, candidatos, contexto)\n },\n\n async reconcileMovement(input) {\n // `settle` quita a conta alvo antes de amarrar — o caminho `link` do V1.\n // Sem `mode`, a linha só é marcada: é o `link_paid`, e é o padrão porque\n // é o comportamento que esta tela sempre teve.\n if (input.mode === 'settle' && input.matchedMovementId) {\n const line = store.statementLines.find((l) => l.id === input.bankMovementId)\n if (!line) throw new Error('Linha do extrato não encontrada')\n const alvo = store.movements.find((m) => m.id === input.matchedMovementId)\n if (!alvo) throw new Error('Lançamento não encontrado')\n await runReconcileLink(\n reconcileFacade(),\n toReconcileLine(line),\n {\n movementId: alvo.id,\n mode: 'settle',\n openAmount: openAmount(alvo),\n },\n { payment: input.payment, adjustments: input.adjustments, partial: input.partial },\n )\n return\n }\n markReconciled(input.bankMovementId, input.matchedMovementId)\n },\n\n async reconcileAsTransfer(input) {\n const line = store.statementLines.find((l) => l.id === input.bankMovementId)\n if (!line) throw new Error('Linha do extrato não encontrada')\n const transfer = await provider.createTransfer(transferForStatementLine(toReconcileLine(line), input))\n await provider.reconcileMovement!({ bankMovementId: input.bankMovementId, matchedMovementId: statementLegOf(line, transfer) })\n return transfer\n },\n\n // «Lançar como conta». A conta nasce classificada, é quitada contra a conta\n // do extrato, e a linha passa a ser a prova dela. É o caminho que faz o\n // extrato BATER: sem ele, uma linha sem contrapartida fica marcada como\n // conciliada e o dinheiro continua fora do livro.\n async reconcileAsBill(input) {\n const line = store.statementLines.find((l) => l.id === input.bankMovementId)\n if (!line) throw new Error('Linha do extrato não encontrada')\n const { invoiceId } = await runReconcileAsBill(reconcileFacade(), toReconcileLine(line), input)\n const invoice = store.invoices.find((i) => i.id === invoiceId)\n if (!invoice) throw new Error('A conta não foi criada')\n return invoice\n },\n\n async unreconcileMovement(statementLineId) {\n const line = store.statementLines.find((l) => l.id === statementLineId)\n if (!line) return\n const matchedId = line.matchedMovementId\n line.reconciledAt = undefined; line.matchedMovementId = undefined; line.updatedAt = now()\n if (matchedId) {\n const internal = store.movements.find((m) => m.id === matchedId)\n if (internal) { internal.reconciledAt = undefined; internal.updatedAt = now() }\n }\n },\n\n // --- Notas fiscais (NF-e / NFC-e / NFS-e) ---\n // Os vales-presente moram na tabela da loja, que não existe em memória.\n // Responder \"não instalado\" faz a tela se explicar; deixar o método fora\n // faria ela explodir com um TypeError que não diz nada a ninguém.\n async giftCardsEnabled(): Promise<boolean> {\n return false\n },\n\n async getNotas(query: NotaFiscalQuery): Promise<PaginatedResult<NotaFiscal>> {\n let list = [...store.notas].sort((a, b) => b.createdAt.localeCompare(a.createdAt))\n if (query.status) list = list.filter((n) => matchesStatus(n.status, query.status))\n if (query.model) list = list.filter((n) => n.model === query.model)\n if (query.orderId) list = list.filter((n) => n.orderId === query.orderId)\n if (query.search) {\n const q = query.search.toLowerCase()\n list = list.filter((n) => (n.number ?? '').toLowerCase().includes(q) || (n.contactName ?? '').toLowerCase().includes(q))\n }\n return paginate(list, query.page, query.pageSize)\n },\n\n async getNotaById(id: string): Promise<NotaFiscal | null> {\n return store.notas.find((n) => n.id === id) ?? null\n },\n\n async createNota(input: CreateNotaFiscalInput): Promise<NotaFiscal> {\n const nota: NotaFiscal = {\n id: uid(),\n tenantId: 'mock-tenant',\n model: input.model ?? 'nfe',\n status: 'draft',\n number: null,\n series: input.series ?? null,\n orderId: input.orderId,\n contactId: input.contactId,\n contactName: input.contactName,\n totalAmount: input.totalAmount,\n observations: input.observations,\n createdAt: now(),\n updatedAt: now(),\n }\n store.notas.unshift(nota)\n return nota\n },\n\n async updateNota(id: string, patch: Partial<NotaFiscal>): Promise<NotaFiscal> {\n const nota = store.notas.find((n) => n.id === id)\n if (!nota) throw new Error('Nota fiscal not found')\n Object.assign(nota, patch, { updatedAt: now() })\n return nota\n },\n\n async issueNota(id: string): Promise<NotaFiscal> {\n const nota = store.notas.find((n) => n.id === id)\n if (!nota) throw new Error('Nota fiscal not found')\n const issuedCount = store.notas.filter((n) => n.status === 'issued').length\n nota.status = 'issued'\n nota.number = String(issuedCount + 1).padStart(6, '0')\n nota.series = nota.series ?? '1'\n nota.issuedAt = now()\n nota.emissor = 'manual'\n nota.updatedAt = now()\n return nota\n },\n\n async cancelNota(id: string, reason?: string): Promise<NotaFiscal> {\n const nota = store.notas.find((n) => n.id === id)\n if (!nota) throw new Error('Nota fiscal not found')\n nota.status = 'cancelled'\n nota.errorMessage = reason\n nota.updatedAt = now()\n return nota\n },\n }\n\n return provider\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"mock.d.ts","sourceRoot":"","sources":["../../src/data/mock.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAA0B,MAAM,mBAAmB,CAAA;AAO5E,OAAO,EAEiD,KAAK,OAAO,EAAE,KAAK,WAAW,EACrF,MAAM,mBAAmB,CAAA;AAE1B,OAAO,EAA0B,KAAK,iBAAiB,EAAkE,MAAM,oBAAoB,CAAA;AAEnJ,OAAO,KAAK,EAAE,aAAa,EAAqB,MAAM,0BAA0B,CAAA;AAMhF,OAAO,KAAK,EAAE,aAAa,EAA0B,MAAM,0BAA0B,CAAA;AAKrF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AAmIvD;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC,YAAY,CAAC,EAAE,WAAW,EAAE,CAAA;IAC5B,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAA;IACpB,YAAY,CAAC,EAAE,WAAW,EAAE,CAAA;IAC5B,SAAS,CAAC,EAAE,iBAAiB,EAAE,CAAA;IAC/B,cAAc,CAAC,EAAE,aAAa,EAAE,CAAA;IAChC,cAAc,CAAC,EAAE,aAAa,EAAE,CAAA;CACjC;AAED,MAAM,WAAW,4BAA4B;IAC3C,kBAAkB,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,eAAe,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IACtE,0FAA0F;IAC1F,IAAI,CAAC,EAAE,iBAAiB,CAAA;CACzB;AAED,wBAAgB,2BAA2B,CAAC,OAAO,CAAC,EAAE,4BAA4B,GAAG,qBAAqB,CA25BzG"}
1
+ {"version":3,"file":"mock.d.ts","sourceRoot":"","sources":["../../src/data/mock.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAA0B,MAAM,mBAAmB,CAAA;AAO5E,OAAO,EAEiD,KAAK,OAAO,EAAE,KAAK,WAAW,EACrF,MAAM,mBAAmB,CAAA;AAE1B,OAAO,EAA0B,KAAK,iBAAiB,EAAkE,MAAM,oBAAoB,CAAA;AAEnJ,OAAO,KAAK,EAAE,aAAa,EAAqB,MAAM,0BAA0B,CAAA;AAMhF,OAAO,KAAK,EAAE,aAAa,EAA0B,MAAM,0BAA0B,CAAA;AAKrF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AAmIvD;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC,YAAY,CAAC,EAAE,WAAW,EAAE,CAAA;IAC5B,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAA;IACpB,YAAY,CAAC,EAAE,WAAW,EAAE,CAAA;IAC5B,SAAS,CAAC,EAAE,iBAAiB,EAAE,CAAA;IAC/B,cAAc,CAAC,EAAE,aAAa,EAAE,CAAA;IAChC,cAAc,CAAC,EAAE,aAAa,EAAE,CAAA;CACjC;AAED,MAAM,WAAW,4BAA4B;IAC3C,kBAAkB,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,eAAe,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IACtE,0FAA0F;IAC1F,IAAI,CAAC,EAAE,iBAAiB,CAAA;CACzB;AAED,wBAAgB,2BAA2B,CAAC,OAAO,CAAC,EAAE,4BAA4B,GAAG,qBAAqB,CAg6BzG"}
package/dist/data/mock.js CHANGED
@@ -1,13 +1,13 @@
1
- export { createMockFinancialProvider } from '../chunk-ZBLZLHIS.js';
1
+ export { createMockFinancialProvider } from '../chunk-TUYTZEW4.js';
2
2
  import '../chunk-T7WIM2V7.js';
3
3
  import '../chunk-ZFUQBYBG.js';
4
4
  import '../chunk-HJPUHTI2.js';
5
5
  import '../chunk-YUNLQYOZ.js';
6
- import '../chunk-CTJ6LVDH.js';
6
+ import '../chunk-HPJDTBVB.js';
7
7
  import '../chunk-4GXBOEI3.js';
8
8
  import '../chunk-56NQHYL7.js';
9
- import '../chunk-FNXIAIUZ.js';
10
- import '../chunk-MCSPCXQK.js';
9
+ import '../chunk-IVIMTPAV.js';
10
+ import '../chunk-NAEXIF3W.js';
11
11
  import '../chunk-XVELDCSL.js';
12
12
  import '../chunk-3QNU7XUB.js';
13
13
  //# sourceMappingURL=mock.js.map
@@ -1,5 +1,5 @@
1
- export { runReconcileAsBill, runReconcileLink } from '../chunk-FNXIAIUZ.js';
2
- import '../chunk-MCSPCXQK.js';
1
+ export { runReconcileAsBill, runReconcileLink } from '../chunk-IVIMTPAV.js';
2
+ import '../chunk-NAEXIF3W.js';
3
3
  import '../chunk-XVELDCSL.js';
4
4
  //# sourceMappingURL=reconcile.js.map
5
5
  //# sourceMappingURL=reconcile.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"supabase.d.ts","sourceRoot":"","sources":["../../src/data/supabase.ts"],"names":[],"mappings":"AA0CA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AA2KvD;;;;;;GAMG;AACH;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,GAAG,MAAM,GAAG,SAAS,CAK1E;AA2OD,wBAAgB,+BAA+B,IAAI,qBAAqB,CA8iGvE"}
1
+ {"version":3,"file":"supabase.d.ts","sourceRoot":"","sources":["../../src/data/supabase.ts"],"names":[],"mappings":"AA0CA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AA2KvD;;;;;;GAMG;AACH;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,GAAG,MAAM,GAAG,SAAS,CAK1E;AA+PD,wBAAgB,+BAA+B,IAAI,qBAAqB,CAqjGvE"}
@@ -1,4 +1,4 @@
1
- export { createSupabaseFinancialProvider, invoiceLineOrFilter } from '../chunk-AYMB572M.js';
1
+ export { createSupabaseFinancialProvider, invoiceLineOrFilter } from '../chunk-5FESQBPQ.js';
2
2
  import '../chunk-4FWWKKZB.js';
3
3
  import '../chunk-J7BWATQU.js';
4
4
  import '../chunk-4S5GK776.js';
@@ -6,11 +6,11 @@ import '../chunk-IP5YH4S5.js';
6
6
  import '../chunk-ZFUQBYBG.js';
7
7
  import '../chunk-HJPUHTI2.js';
8
8
  import '../chunk-YUNLQYOZ.js';
9
- import '../chunk-CTJ6LVDH.js';
9
+ import '../chunk-HPJDTBVB.js';
10
10
  import '../chunk-4GXBOEI3.js';
11
11
  import '../chunk-56NQHYL7.js';
12
- import '../chunk-FNXIAIUZ.js';
13
- import '../chunk-MCSPCXQK.js';
12
+ import '../chunk-IVIMTPAV.js';
13
+ import '../chunk-NAEXIF3W.js';
14
14
  import '../chunk-XVELDCSL.js';
15
15
  import '../chunk-3QNU7XUB.js';
16
16
  //# sourceMappingURL=supabase.js.map