@fayz-ai/financial 0.1.5 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-7HISDBUG.js → chunk-5RMPZIMO.js} +2 -2
- package/dist/{chunk-7HISDBUG.js.map → chunk-5RMPZIMO.js.map} +1 -1
- package/dist/{chunk-2XWEZXFT.js → chunk-RI4IUJS4.js} +18 -13
- package/dist/chunk-RI4IUJS4.js.map +1 -0
- package/dist/{chunk-UERJA7QH.js → chunk-UXALK7CT.js} +8 -4
- package/dist/chunk-UXALK7CT.js.map +1 -0
- package/dist/data/mock.d.ts.map +1 -1
- package/dist/data/mock.js +2 -2
- package/dist/data/supabase.d.ts +15 -0
- package/dist/data/supabase.d.ts.map +1 -1
- package/dist/data/supabase.js +2 -2
- package/dist/domain/invoice.d.ts +8 -0
- package/dist/domain/invoice.d.ts.map +1 -1
- package/dist/domain/invoice.js +1 -1
- package/dist/store.js +3 -3
- package/package.json +3 -3
- package/dist/chunk-2XWEZXFT.js.map +0 -1
- package/dist/chunk-UERJA7QH.js.map +0 -1
|
@@ -80,5 +80,5 @@ function summarizeInvoiceLines(rows, visible = 2) {
|
|
|
80
80
|
}
|
|
81
81
|
|
|
82
82
|
export { assertReschedule, availableInvoiceItemTypes, cancellationReason, hasReceivedPayment, invoiceOpensForEditing, invoiceStatusOf, invoiceTotal, itemsDescription, lineTotal, listsProvisioned, scheduleCloses, splitInstallments, summarizeInvoiceLines, withProvisioned };
|
|
83
|
-
//# sourceMappingURL=chunk-
|
|
84
|
-
//# sourceMappingURL=chunk-
|
|
83
|
+
//# sourceMappingURL=chunk-5RMPZIMO.js.map
|
|
84
|
+
//# sourceMappingURL=chunk-5RMPZIMO.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/domain/invoice.ts"],"names":[],"mappings":";;;AAuMO,SAAS,UAAU,IAAA,EAA0B;AAClD,EAAA,OAAO,MAAA,CAAO,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,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-7HISDBUG.js","sourcesContent":["import { round2 } from './money'\nimport type { CreateMovementInput, FinancialMovement, TransactionDirection } from './movement'\nimport type { DateRange } from './query'\n\nexport type InvoiceStatus =\n | 'draft' | 'open' | 'partial' | 'paid' | 'cancelled' | 'overdue'\n /** A recurring occurrence not consolidated yet: forecast, not owed. No ledger entry, no charge. */\n | 'provisioned'\n\n/** What an invoice line is; the set is configured per vertical. */\nexport type InvoiceItemKind = string\n\nexport interface Invoice {\n id: string\n direction: TransactionDirection\n /** ISO code the document was written in. Absent = the house's currency. */\n currency?: string\n /** Free labels the house puts on the bill. */\n tags?: string[]\n /** Competence date: the axis of the ledger and the income statement. */\n invoiceDate: string\n /** The next open due date, or the last one once everything is paid. Lists sort by it. */\n dueDate?: string\n /** Lists are per installment: `id` is the installment and `invoiceId` the document it opens. */\n invoiceId?: string\n installmentNumber?: number\n attachmentCount?: number\n fiscalNumber?: string\n totalAmount: number\n paidAmount: number\n status: InvoiceStatus\n totalInstallments: number\n contactId?: string\n contactName?: string\n cashSessionId?: string\n unitId?: string\n observations?: string\n itemsSummary?: string\n paymentMethodId?: string\n paymentMethodTypeId?: string\n paymentAccountId?: string\n paymentCardInstallments?: number\n /** Start time of the booking the order came from, when it has one. */\n bookingStartsAt?: string\n metadata?: Record<string, unknown>\n tenantId: string\n createdAt: string\n updatedAt: string\n createdBy?: string\n /** A virtual row for a provisioned recurring occurrence; there is no invoice behind it. */\n isProvisionedOccurrence?: boolean\n occurrenceId?: string\n recurringBillId?: string\n}\n\nexport interface InvoiceItem {\n id: string\n invoiceId: string\n /** The picture of the product this line names, when it names one that has a picture. */\n imageUrl?: string\n itemKind: InvoiceItemKind\n referenceId?: string\n description: string\n quantity: number\n unitPrice: number\n totalAmount: number\n discount: number\n surcharge: number\n accountId?: string\n costCenterId?: string\n isExecuted?: boolean\n executionDate?: string\n executedByProfessionalId?: string\n metadata?: Record<string, unknown>\n /** Set when the line was cancelled on its own (cancel by item). */\n cancelledAt?: string\n cancelReason?: string\n createdAt: string\n}\n\nexport interface CreateInvoiceInput {\n direction: TransactionDirection\n invoiceDate: string\n fiscalNumber?: string\n contactId?: string\n contactName?: string\n cashSessionId?: string\n unitId?: string\n /** ISO code to write the document in. Absent = the unit's currency. */\n currency?: string\n tags?: string[]\n observations?: string\n metadata?: Record<string, unknown>\n items: CreateInvoiceItemInput[]\n installments: CreateMovementInput[]\n}\n\nexport interface CreateInvoiceItemInput {\n itemKind: InvoiceItemKind\n referenceId?: string\n description: string\n quantity: number\n unitPrice: number\n discount?: number\n surcharge?: number\n accountId?: string\n costCenterId?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface CancellationReason {\n id: string\n name: string\n}\n\n/** Goods a payable line brought into stock, still traceable to its note. */\nexport interface InvoiceStockEntry {\n itemId: string\n productId: string\n locationId: string\n /** Quantity that entered, in the product's stock unit. */\n entered: number\n /** What is still at that location — the most a return or loss can move. */\n available: number\n enteredOn: string\n}\n\nexport type StockDestination = 'devolver' | 'perda' | 'manter'\n\nexport interface CancelInvoiceItemsInput {\n invoiceId: string\n /** Empty = every live line (the whole invoice). */\n itemIds: string[]\n reasonId: string\n detail?: string\n stock: Array<{ itemId: string; destination: StockDestination; note?: string }>\n idempotencyKey?: string\n}\n\nexport interface CancelInvoiceItemsResult {\n whole: boolean\n amount: number\n /** What had been paid on the cancelled part and became counterparty credit. */\n creditAmount: number\n}\n\nexport interface InstallmentChargeInput {\n installmentId: string\n kind: 'interest' | 'fine' | 'discount'\n /** Always positive — `kind` carries the sign. */\n amount: number\n accountId?: string\n description?: string\n idempotencyKey?: string\n}\n\nexport interface CancelInvoiceInput {\n invoiceId: string\n reason: string\n /** Stable for every retry of the same cancellation attempt. */\n idempotencyKey?: string\n}\n\nexport interface InvoiceQuery {\n direction?: TransactionDirection\n status?: InvoiceStatus | InvoiceStatus[]\n contactId?: string\n unitId?: string\n accountId?: string\n costCenterId?: string\n dateRange?: DateRange\n search?: string\n fiscalNumber?: string\n /** The account the money left from or landed in. */\n bankAccountId?: string\n page?: number\n pageSize?: number\n}\n\n/** A receipt attached to an invoice. `pending` means the row exists but the file does not open yet. */\nexport interface InvoiceAttachment {\n id: string\n fileName: string\n fileSize?: number\n mimeType?: string\n url?: string\n pending: boolean\n createdAt?: string\n}\n\n/** One installment of a schedule, before it is written. */\nexport interface ScheduledInstallment {\n dueDate: string\n amount: number\n metadata?: Record<string, unknown>\n}\n\ntype PricedLine = Pick<CreateInvoiceItemInput, 'quantity' | 'unitPrice' | 'discount' | 'surcharge'>\n\nexport function lineTotal(item: PricedLine): number {\n return round2(item.quantity * item.unitPrice - (item.discount ?? 0) + (item.surcharge ?? 0))\n}\n\n/** An invoice is worth the sum of its lines; storing one without the other bills one value and charges another. */\nexport function invoiceTotal(items: PricedLine[]): number {\n return round2(items.reduce((sum, item) => sum + lineTotal(item), 0))\n}\n\nexport function itemsDescription(items: Pick<CreateInvoiceItemInput, 'description'>[]): string {\n return items.map((item) => item.description).filter(Boolean).join(', ')\n}\n\n/** A cancellation without a reason is refused. */\nexport function cancellationReason(input: Pick<CancelInvoiceInput, 'reason'>): string {\n const reason = input.reason.trim()\n if (!reason) throw new Error('A cancellation reason is required')\n return reason\n}\n\n/** Status from what was paid, and whether any open bill is past due. */\nexport function invoiceStatusOf(\n invoice: Pick<Invoice, 'paidAmount' | 'totalAmount'>,\n bills: Pick<FinancialMovement, 'status' | 'dueDate'>[],\n today: string,\n): InvoiceStatus {\n if (invoice.paidAmount >= invoice.totalAmount) return 'paid'\n if (invoice.paidAmount > 0) return 'partial'\n const late = bills.some((bill) => bill.status === 'overdue' || (bill.status === 'pending' && bill.dueDate < today))\n return late ? 'overdue' : 'open'\n}\n\n/** Equal shares to the cent; the first installment absorbs the rounding remainder. */\nexport function splitInstallments(total: number, count: number): number[] {\n if (count < 1) return []\n const share = Math.floor(round2(total) * 100 / count) / 100\n const remainder = round2(total - share * count)\n return Array.from({ length: count }, (_, i) => (i === 0 ? round2(share + remainder) : share))\n}\n\n/** Does the schedule close on the invoice total? The database refuses a schedule that does not. */\nexport function scheduleCloses(amounts: number[], total: number): boolean {\n return Math.round(amounts.reduce((sum, amount) => sum + amount, 0) * 100) === Math.round(total * 100)\n}\n\n/** Once any money was received the schedule and the items are history. */\nexport function hasReceivedPayment(bills: Pick<FinancialMovement, 'paidAmount'>[]): boolean {\n return bills.some((bill) => (bill.paidAmount ?? 0) > 0)\n}\n\n/** A new schedule for an invoice, refused when it cannot be applied. */\nexport function assertReschedule(\n invoice: Pick<Invoice, 'totalAmount'>,\n currentBills: Pick<FinancialMovement, 'paidAmount'>[],\n installments: ScheduledInstallment[],\n): void {\n if (hasReceivedPayment(currentBills)) throw new Error('Invoice already received; its schedule is history now')\n const sum = round2(installments.reduce((total, installment) => total + installment.amount, 0))\n if (sum !== round2(invoice.totalAmount)) {\n throw new Error(`Installments sum to ${sum} but the invoice total is ${invoice.totalAmount}`)\n }\n}\n\n/**\n * Opening an invoice means editing it while it can still change. Paid and cancelled ones became\n * statement history; `partial` stays editable because its header can still be corrected.\n */\nexport function invoiceOpensForEditing(status: string | undefined): boolean {\n return status !== 'paid' && status !== 'cancelled'\n}\n\n/**\n * Forecast rows join a list only when they can match it: not when a status was asked for, and not\n * when the filter is a document number or a paying account, which a forecast never has.\n */\nexport function listsProvisioned(query: InvoiceQuery): boolean {\n return !query.status && !query.fiscalNumber && !query.bankAccountId\n}\n\n/** Real invoices and forecasts in one list, by due date. */\nexport function withProvisioned(invoices: Invoice[], provisioned: Invoice[]): Invoice[] {\n if (provisioned.length === 0) return invoices\n return [...invoices, ...provisioned].sort((a, b) => (a.dueDate ?? '').localeCompare(b.dueDate ?? ''))\n}\n\ninterface InvoiceItemType {\n value: string\n label: string\n icon?: string\n}\n\n// What the house sells is never offered on a payable: booking an expense against its own revenue line.\nconst RECEIVABLE_ONLY = new Set(['service', 'package', 'gift_card'])\n\n/** Catalogue-backed kinds need their catalogue installed; `other` is always offered. */\nexport function availableInvoiceItemTypes<T extends InvoiceItemType>(\n itemTypes: T[],\n lookupKinds: Iterable<string>,\n otherLabel: string,\n direction?: TransactionDirection | 'payable' | 'receivable',\n): T[] {\n const installed = new Set(lookupKinds)\n const payable = direction === 'debit' || direction === 'payable'\n const visible = itemTypes.filter((type) => (\n (!payable || !RECEIVABLE_ONLY.has(type.value))\n ) && (\n type.value === 'other'\n || !['product', 'service', 'package'].includes(type.value)\n || installed.has(type.value)\n ))\n if (visible.some((type) => type.value === 'other')) return visible\n return [...visible, { value: 'other', label: otherLabel, icon: 'MoreHorizontal' } as T]\n}\n\ninterface InvoiceLineSummarySource {\n invoice_id?: string | null\n name?: string | null\n description?: string | null\n quantity?: number | string | null\n}\n\n/** The billed lines compacted for a list row: two shown, the rest counted. */\nexport function summarizeInvoiceLines(rows: InvoiceLineSummarySource[], visible = 2): Map<string, string> {\n const byInvoice = new Map<string, string[]>()\n for (const row of rows) {\n const invoiceId = row.invoice_id\n const label = String(row.name ?? row.description ?? '').trim()\n if (!invoiceId || !label) continue\n const quantity = Number(row.quantity) || 1\n const rendered = quantity === 1 ? label : `${quantity} × ${label}`\n const current = byInvoice.get(invoiceId) ?? []\n current.push(rendered)\n byInvoice.set(invoiceId, current)\n }\n\n const summaries = new Map<string, string>()\n for (const [invoiceId, lines] of byInvoice) {\n const shown = lines.slice(0, visible)\n const remainder = lines.length - shown.length\n summaries.set(invoiceId, `${shown.join(' · ')}${remainder > 0 ? ` · +${remainder} itens` : ''}`)\n }\n return summaries\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/domain/invoice.ts"],"names":[],"mappings":";;;AA+MO,SAAS,UAAU,IAAA,EAA0B;AAClD,EAAA,OAAO,MAAA,CAAO,IAAA,CAAK,QAAA,GAAW,IAAA,CAAK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G,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-5RMPZIMO.js","sourcesContent":["import { round2 } from './money'\nimport type { CreateMovementInput, FinancialMovement, TransactionDirection } from './movement'\nimport type { DateRange } from './query'\n\nexport type InvoiceStatus =\n | 'draft' | 'open' | 'partial' | 'paid' | 'cancelled' | 'overdue'\n /** A recurring occurrence not consolidated yet: forecast, not owed. No ledger entry, no charge. */\n | 'provisioned'\n\n/** What an invoice line is; the set is configured per vertical. */\nexport type InvoiceItemKind = string\n\nexport interface Invoice {\n id: string\n direction: TransactionDirection\n /** ISO code the document was written in. Absent = the house's currency. */\n currency?: string\n /** Free labels the house puts on the bill. */\n tags?: string[]\n /** Competence date: the axis of the ledger and the income statement. */\n invoiceDate: string\n /** The next open due date, or the last one once everything is paid. Lists sort by it. */\n dueDate?: string\n /** Lists are per installment: `id` is the installment and `invoiceId` the document it opens. */\n invoiceId?: string\n installmentNumber?: number\n attachmentCount?: number\n fiscalNumber?: string\n totalAmount: number\n paidAmount: number\n status: InvoiceStatus\n totalInstallments: number\n contactId?: string\n contactName?: string\n cashSessionId?: string\n unitId?: string\n observations?: string\n itemsSummary?: string\n paymentMethodId?: string\n paymentMethodTypeId?: string\n paymentAccountId?: string\n paymentCardInstallments?: number\n /** Start time of the booking the order came from, when it has one. */\n bookingStartsAt?: string\n metadata?: Record<string, unknown>\n tenantId: string\n createdAt: string\n updatedAt: string\n createdBy?: string\n /** A virtual row for a provisioned recurring occurrence; there is no invoice behind it. */\n isProvisionedOccurrence?: boolean\n occurrenceId?: string\n recurringBillId?: string\n}\n\nexport interface InvoiceItem {\n id: string\n invoiceId: string\n /** The picture of the product this line names, when it names one that has a picture. */\n imageUrl?: string\n itemKind: InvoiceItemKind\n referenceId?: string\n description: string\n quantity: number\n unitPrice: number\n totalAmount: number\n discount: number\n surcharge: number\n accountId?: string\n costCenterId?: string\n isExecuted?: boolean\n executionDate?: string\n executedByProfessionalId?: string\n metadata?: Record<string, unknown>\n /** Set when the line was cancelled on its own (cancel by item). */\n cancelledAt?: string\n cancelReason?: string\n createdAt: string\n}\n\nexport interface CreateInvoiceInput {\n direction: TransactionDirection\n invoiceDate: string\n fiscalNumber?: string\n contactId?: string\n contactName?: string\n cashSessionId?: string\n unitId?: string\n /** ISO code to write the document in. Absent = the unit's currency. */\n currency?: string\n tags?: string[]\n observations?: string\n metadata?: Record<string, unknown>\n items: CreateInvoiceItemInput[]\n installments: CreateMovementInput[]\n}\n\nexport interface CreateInvoiceItemInput {\n itemKind: InvoiceItemKind\n referenceId?: string\n description: string\n quantity: number\n unitPrice: number\n discount?: number\n surcharge?: number\n accountId?: string\n costCenterId?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface CancellationReason {\n id: string\n name: string\n}\n\n/** Goods a payable line brought into stock, still traceable to its note. */\nexport interface InvoiceStockEntry {\n itemId: string\n productId: string\n locationId: string\n /** Quantity that entered, in the product's stock unit. */\n entered: number\n /** What is still at that location — the most a return or loss can move. */\n available: number\n enteredOn: string\n}\n\nexport type StockDestination = 'devolver' | 'perda' | 'manter'\n\nexport interface CancelInvoiceItemsInput {\n invoiceId: string\n /** Empty = every live line (the whole invoice). */\n itemIds: string[]\n reasonId: string\n detail?: string\n stock: Array<{ itemId: string; destination: StockDestination; note?: string }>\n idempotencyKey?: string\n}\n\nexport interface CancelInvoiceItemsResult {\n whole: boolean\n amount: number\n /** What had been paid on the cancelled part and became counterparty credit. */\n creditAmount: number\n}\n\nexport interface InstallmentChargeInput {\n installmentId: string\n kind: 'interest' | 'fine' | 'discount'\n /** Always positive — `kind` carries the sign. */\n amount: number\n accountId?: string\n description?: string\n idempotencyKey?: string\n}\n\nexport interface CancelInvoiceInput {\n invoiceId: string\n reason: string\n /** Stable for every retry of the same cancellation attempt. */\n idempotencyKey?: string\n}\n\nexport interface InvoiceQuery {\n direction?: TransactionDirection\n status?: InvoiceStatus | InvoiceStatus[]\n contactId?: string\n unitId?: string\n accountId?: string\n costCenterId?: string\n dateRange?: DateRange\n search?: string\n fiscalNumber?: string\n /** The account the money left from or landed in. */\n bankAccountId?: string\n /**\n * With `dateRange`: also return the unpaid lines (overdue or partially paid)\n * that fell due BEFORE the range starts. A month window otherwise hides the\n * debt that is most urgent — the bill from last month that nobody paid.\n */\n includeOverdue?: boolean\n /** `due` (default): soonest due first — a queue. `recent`: newest entered first. */\n sort?: 'due' | 'recent'\n page?: number\n pageSize?: number\n}\n\n/** A receipt attached to an invoice. `pending` means the row exists but the file does not open yet. */\nexport interface InvoiceAttachment {\n id: string\n fileName: string\n fileSize?: number\n mimeType?: string\n url?: string\n pending: boolean\n createdAt?: string\n}\n\n/** One installment of a schedule, before it is written. */\nexport interface ScheduledInstallment {\n dueDate: string\n amount: number\n metadata?: Record<string, unknown>\n}\n\ntype PricedLine = Pick<CreateInvoiceItemInput, 'quantity' | 'unitPrice' | 'discount' | 'surcharge'>\n\nexport function lineTotal(item: PricedLine): number {\n return round2(item.quantity * item.unitPrice - (item.discount ?? 0) + (item.surcharge ?? 0))\n}\n\n/** An invoice is worth the sum of its lines; storing one without the other bills one value and charges another. */\nexport function invoiceTotal(items: PricedLine[]): number {\n return round2(items.reduce((sum, item) => sum + lineTotal(item), 0))\n}\n\nexport function itemsDescription(items: Pick<CreateInvoiceItemInput, 'description'>[]): string {\n return items.map((item) => item.description).filter(Boolean).join(', ')\n}\n\n/** A cancellation without a reason is refused. */\nexport function cancellationReason(input: Pick<CancelInvoiceInput, 'reason'>): string {\n const reason = input.reason.trim()\n if (!reason) throw new Error('A cancellation reason is required')\n return reason\n}\n\n/** Status from what was paid, and whether any open bill is past due. */\nexport function invoiceStatusOf(\n invoice: Pick<Invoice, 'paidAmount' | 'totalAmount'>,\n bills: Pick<FinancialMovement, 'status' | 'dueDate'>[],\n today: string,\n): InvoiceStatus {\n if (invoice.paidAmount >= invoice.totalAmount) return 'paid'\n if (invoice.paidAmount > 0) return 'partial'\n const late = bills.some((bill) => bill.status === 'overdue' || (bill.status === 'pending' && bill.dueDate < today))\n return late ? 'overdue' : 'open'\n}\n\n/** Equal shares to the cent; the first installment absorbs the rounding remainder. */\nexport function splitInstallments(total: number, count: number): number[] {\n if (count < 1) return []\n const share = Math.floor(round2(total) * 100 / count) / 100\n const remainder = round2(total - share * count)\n return Array.from({ length: count }, (_, i) => (i === 0 ? round2(share + remainder) : share))\n}\n\n/** Does the schedule close on the invoice total? The database refuses a schedule that does not. */\nexport function scheduleCloses(amounts: number[], total: number): boolean {\n return Math.round(amounts.reduce((sum, amount) => sum + amount, 0) * 100) === Math.round(total * 100)\n}\n\n/** Once any money was received the schedule and the items are history. */\nexport function hasReceivedPayment(bills: Pick<FinancialMovement, 'paidAmount'>[]): boolean {\n return bills.some((bill) => (bill.paidAmount ?? 0) > 0)\n}\n\n/** A new schedule for an invoice, refused when it cannot be applied. */\nexport function assertReschedule(\n invoice: Pick<Invoice, 'totalAmount'>,\n currentBills: Pick<FinancialMovement, 'paidAmount'>[],\n installments: ScheduledInstallment[],\n): void {\n if (hasReceivedPayment(currentBills)) throw new Error('Invoice already received; its schedule is history now')\n const sum = round2(installments.reduce((total, installment) => total + installment.amount, 0))\n if (sum !== round2(invoice.totalAmount)) {\n throw new Error(`Installments sum to ${sum} but the invoice total is ${invoice.totalAmount}`)\n }\n}\n\n/**\n * Opening an invoice means editing it while it can still change. Paid and cancelled ones became\n * statement history; `partial` stays editable because its header can still be corrected.\n */\nexport function invoiceOpensForEditing(status: string | undefined): boolean {\n return status !== 'paid' && status !== 'cancelled'\n}\n\n/**\n * Forecast rows join a list only when they can match it: not when a status was asked for, and not\n * when the filter is a document number or a paying account, which a forecast never has.\n */\nexport function listsProvisioned(query: InvoiceQuery): boolean {\n return !query.status && !query.fiscalNumber && !query.bankAccountId\n}\n\n/** Real invoices and forecasts in one list, by due date. */\nexport function withProvisioned(invoices: Invoice[], provisioned: Invoice[]): Invoice[] {\n if (provisioned.length === 0) return invoices\n return [...invoices, ...provisioned].sort((a, b) => (a.dueDate ?? '').localeCompare(b.dueDate ?? ''))\n}\n\ninterface InvoiceItemType {\n value: string\n label: string\n icon?: string\n}\n\n// What the house sells is never offered on a payable: booking an expense against its own revenue line.\nconst RECEIVABLE_ONLY = new Set(['service', 'package', 'gift_card'])\n\n/** Catalogue-backed kinds need their catalogue installed; `other` is always offered. */\nexport function availableInvoiceItemTypes<T extends InvoiceItemType>(\n itemTypes: T[],\n lookupKinds: Iterable<string>,\n otherLabel: string,\n direction?: TransactionDirection | 'payable' | 'receivable',\n): T[] {\n const installed = new Set(lookupKinds)\n const payable = direction === 'debit' || direction === 'payable'\n const visible = itemTypes.filter((type) => (\n (!payable || !RECEIVABLE_ONLY.has(type.value))\n ) && (\n type.value === 'other'\n || !['product', 'service', 'package'].includes(type.value)\n || installed.has(type.value)\n ))\n if (visible.some((type) => type.value === 'other')) return visible\n return [...visible, { value: 'other', label: otherLabel, icon: 'MoreHorizontal' } as T]\n}\n\ninterface InvoiceLineSummarySource {\n invoice_id?: string | null\n name?: string | null\n description?: string | null\n quantity?: number | string | null\n}\n\n/** The billed lines compacted for a list row: two shown, the rest counted. */\nexport function summarizeInvoiceLines(rows: InvoiceLineSummarySource[], visible = 2): Map<string, string> {\n const byInvoice = new Map<string, string[]>()\n for (const row of rows) {\n const invoiceId = row.invoice_id\n const label = String(row.name ?? row.description ?? '').trim()\n if (!invoiceId || !label) continue\n const quantity = Number(row.quantity) || 1\n const rendered = quantity === 1 ? label : `${quantity} × ${label}`\n const current = byInvoice.get(invoiceId) ?? []\n current.push(rendered)\n byInvoice.set(invoiceId, current)\n }\n\n const summaries = new Map<string, string>()\n for (const [invoiceId, lines] of byInvoice) {\n const shown = lines.slice(0, visible)\n const remainder = lines.length - shown.length\n summaries.set(invoiceId, `${shown.join(' · ')}${remainder > 0 ? ` · +${remainder} itens` : ''}`)\n }\n return summaries\n}\n"]}
|
|
@@ -4,7 +4,7 @@ import { createIdempotencyKey } from './chunk-IP5YH4S5.js';
|
|
|
4
4
|
import { NAME_AMOUNT_TOLERANCE, matchStatementLines, scorePair } from './chunk-ZFUQBYBG.js';
|
|
5
5
|
import { emptyStatement, ledgerBalance, buildStatement } from './chunk-HJPUHTI2.js';
|
|
6
6
|
import { transferLegs } from './chunk-YUNLQYOZ.js';
|
|
7
|
-
import { cancellationReason, invoiceTotal, itemsDescription, summarizeInvoiceLines, lineTotal } from './chunk-
|
|
7
|
+
import { cancellationReason, invoiceTotal, itemsDescription, summarizeInvoiceLines, lineTotal } from './chunk-5RMPZIMO.js';
|
|
8
8
|
import { paymentFee, ledgerMethod, toLedgerDirection, fromLedgerDirection } from './chunk-4GXBOEI3.js';
|
|
9
9
|
import { sessionCashFlow } from './chunk-56NQHYL7.js';
|
|
10
10
|
import { runReconcileAsBill, runReconcileLink } from './chunk-FNXIAIUZ.js';
|
|
@@ -147,6 +147,12 @@ function mapRecurringBill(row, counterpartyName) {
|
|
|
147
147
|
updatedAt: row.updated_at
|
|
148
148
|
};
|
|
149
149
|
}
|
|
150
|
+
function invoiceLineOrFilter(groups) {
|
|
151
|
+
const active = groups.filter((g) => g.length > 0);
|
|
152
|
+
if (active.length === 0) return void 0;
|
|
153
|
+
if (active.length === 1) return active[0].join(",");
|
|
154
|
+
return `and(${active.map((g) => `or(${g.join(",")})`).join(",")})`;
|
|
155
|
+
}
|
|
150
156
|
async function findInvoiceIdsByLineAccounting(core, pub, filters) {
|
|
151
157
|
if (!filters.accountId && !filters.costCenterId) return void 0;
|
|
152
158
|
let sideQ = pub.from(T.invoiceItems).select("item_id");
|
|
@@ -459,19 +465,18 @@ function createSupabaseFinancialProvider() {
|
|
|
459
465
|
if (query.bankAccountId) qb = qb.contains("payment_account_ids", [query.bankAccountId]);
|
|
460
466
|
const unidades = query.unitId ? ["unit_id.is.null", `unit_id.eq.${query.unitId}`] : [];
|
|
461
467
|
const buscas = query.search ? ["description", "notes", "number", "counterparty_name"].map((col) => `${col}.ilike.%${query.search}%`) : [];
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
} else if (buscas.length) {
|
|
467
|
-
qb = qb.or(buscas.join(","));
|
|
468
|
-
}
|
|
468
|
+
const desde = query.dateRange?.from.slice(0, 10);
|
|
469
|
+
const vencidas = desde && query.includeOverdue ? [`due_date.gte.${desde}`, `and(due_date.lt.${desde},status.in.(overdue,partial))`] : [];
|
|
470
|
+
const grupoOr = invoiceLineOrFilter([unidades, buscas, vencidas]);
|
|
471
|
+
if (grupoOr) qb = qb.or(grupoOr);
|
|
469
472
|
if (query.dateRange) {
|
|
470
|
-
qb = qb.gte("due_date",
|
|
473
|
+
if (!vencidas.length) qb = qb.gte("due_date", desde);
|
|
474
|
+
qb = qb.lte("due_date", query.dateRange.to.slice(0, 10));
|
|
471
475
|
}
|
|
472
476
|
const page = query.page ?? 1;
|
|
473
477
|
const pageSize = query.pageSize ?? 50;
|
|
474
|
-
qb = qb.range((page - 1) * pageSize, page * pageSize - 1)
|
|
478
|
+
qb = qb.range((page - 1) * pageSize, page * pageSize - 1);
|
|
479
|
+
qb = query.sort === "recent" ? qb.order("created_at", { ascending: false }).order("due_date", { ascending: true }) : qb.order("due_date", { ascending: true });
|
|
475
480
|
const { data, count, error } = await qb;
|
|
476
481
|
if (error) throw error;
|
|
477
482
|
const linhas = (data ?? []).map(rowToInvoiceLine);
|
|
@@ -2800,6 +2805,6 @@ function createSupabaseFinancialProvider() {
|
|
|
2800
2805
|
return provider;
|
|
2801
2806
|
}
|
|
2802
2807
|
|
|
2803
|
-
export { createSupabaseFinancialProvider };
|
|
2804
|
-
//# sourceMappingURL=chunk-
|
|
2805
|
-
//# sourceMappingURL=chunk-
|
|
2808
|
+
export { createSupabaseFinancialProvider, invoiceLineOrFilter };
|
|
2809
|
+
//# sourceMappingURL=chunk-RI4IUJS4.js.map
|
|
2810
|
+
//# sourceMappingURL=chunk-RI4IUJS4.js.map
|