@adatechnology/purchase-module 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +164 -2
- package/dist/http/fetch.cjs +33 -0
- package/dist/http/fetch.cjs.map +1 -0
- package/dist/http/fetch.d.cts +2 -0
- package/dist/http/fetch.d.ts +2 -0
- package/dist/http/fetch.js +7 -0
- package/dist/http/fetch.js.map +1 -0
- package/dist/http/uws.cjs +31 -0
- package/dist/http/uws.cjs.map +1 -0
- package/dist/http/uws.d.cts +1 -0
- package/dist/http/uws.d.ts +1 -0
- package/dist/http/uws.js +6 -0
- package/dist/http/uws.js.map +1 -0
- package/dist/index.cjs +3359 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2765 -0
- package/dist/index.d.ts +2765 -0
- package/dist/index.js +3326 -0
- package/dist/index.js.map +1 -0
- package/dist/migrations/0000_initial.sql +186 -0
- package/dist/migrations/meta/0000_snapshot.json +1503 -0
- package/dist/migrations/meta/_journal.json +13 -0
- package/dist/openapi.cjs +41 -0
- package/dist/openapi.cjs.map +1 -0
- package/dist/openapi.d.cts +15 -0
- package/dist/openapi.d.ts +15 -0
- package/dist/openapi.js +18 -0
- package/dist/openapi.js.map +1 -0
- package/package.json +56 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../node_modules/.pnpm/tsup@8.5.1_@swc+core@1.16.2_@swc+helpers@0.5.23__jiti@2.7.0_postcss@8.5.28_tsx@4.23.13_typescript@5.9.3_yaml@2.9.1/node_modules/tsup/assets/esm_shims.js","../src/PurchaseModule.ts","../src/services/insights.ts","../src/schema/schema.ts","../src/shared/context.ts","../src/services/jobs.ts","../src/services/nfe.ts","../src/services/orders.ts","../src/shared/mappers.ts","../src/shared/postgresErrors.ts","../src/services/suppliers.ts","../src/services/receipts.ts","../src/services/reports.ts","../src/http/routes.ts","../src/runMigrations.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Composição raiz de Compras. Funciona sozinho; cada porta de `providers` liga um outro módulo (ver\n * `@adatechnology/purchase-contracts/providers`). As leituras que os outros módulos consomem ficam em\n * `useCases.insights` (a caminho, custo por item) e `useCases.suppliers.findMany` (diretório de fornecedores).\n */\n\nimport {\n PurchaseConfigMissingError,\n type ClockPort,\n type PurchaseHooks,\n type PurchaseModuleConfig,\n} from '@adatechnology/purchase-contracts'\n\nimport type { PurchaseDatabase } from './database.types'\nimport { createInsightService, type InsightService } from './services/insights'\nimport { createJobService } from './services/jobs'\nimport { createNfeService } from './services/nfe'\nimport { createOrderService, type OrderService } from './services/orders'\nimport { createReceiptService } from './services/receipts'\nimport { createReportService } from './services/reports'\nimport { createSupplierService } from './services/suppliers'\nimport type { PurchaseDependencies, PurchaseProviders } from './shared/context'\n\nexport type CreatePurchaseModuleParams = {\n readonly db: PurchaseDatabase\n readonly config?: PurchaseModuleConfig\n readonly providers?: PurchaseProviders\n readonly hooks?: PurchaseHooks\n}\n\nconst SYSTEM_CLOCK: ClockPort = { now: () => new Date() }\nconst DEFAULT_TIME_ZONE = 'America/Sao_Paulo'\nconst DEFAULT_AVERAGE_WINDOW_DAYS = 90\n\nfunction isTimeZone(value: string): boolean {\n try {\n new Intl.DateTimeFormat('en-US', { timeZone: value })\n return true\n } catch {\n return false\n }\n}\n\nexport function createPurchaseModule(params: CreatePurchaseModuleParams) {\n if (!params.db) throw new PurchaseConfigMissingError('db')\n const config = params.config ?? {}\n const timeZone = config.timeZone ?? DEFAULT_TIME_ZONE\n if (!isTimeZone(timeZone)) throw new PurchaseConfigMissingError('timeZone')\n const windowDays = config.averageCostWindowDays ?? DEFAULT_AVERAGE_WINDOW_DAYS\n if (!Number.isInteger(windowDays) || windowDays < 1) throw new PurchaseConfigMissingError('averageCostWindowDays')\n if (\n config.priceToleranceCents !== undefined &&\n (!Number.isInteger(config.priceToleranceCents) || config.priceToleranceCents < 0)\n )\n throw new PurchaseConfigMissingError('priceToleranceCents')\n const providers = params.providers ?? {}\n if (providers.dispatch && providers.dispatch.channels.length === 0)\n throw new PurchaseConfigMissingError('providers.dispatch.channels')\n\n const dependencies: PurchaseDependencies = {\n db: params.db,\n config,\n providers,\n hooks: params.hooks ?? {},\n clock: providers.clock ?? SYSTEM_CLOCK,\n logger: providers.logger,\n timeZone,\n averageCostWindowDays: windowDays,\n }\n\n const orders: OrderService = createOrderService(dependencies)\n const insights: InsightService = createInsightService(dependencies, () => orders)\n const receipts = createReceiptService(dependencies, () => insights)\n\n return {\n useCases: {\n suppliers: createSupplierService(dependencies),\n orders,\n receipts,\n insights,\n reports: createReportService(dependencies),\n nfe: createNfeService(dependencies),\n jobs: createJobService(dependencies, () => insights),\n },\n config,\n /** Quais portas estão ligadas (a tela esconde o que não se aplica). */\n capabilities: {\n catalog: providers.catalog !== undefined,\n stock: providers.stock !== undefined,\n demand: providers.demand !== undefined,\n payables: providers.payables !== undefined,\n dispatchChannels: providers.dispatch ? [...providers.dispatch.channels] : [],\n },\n }\n}\n\nexport type PurchaseModule = ReturnType<typeof createPurchaseModule>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Leituras que os outros módulos consomem: \"a caminho\" por item (o `IncomingSupplyPort` do estoque), custo por item\n * (último e médio, para a ficha técnica), histórico de preço e a sugestão de pedido.\n */\n\nimport { convertQuantity, formatDecimal, parseDecimal, type RecipeUnit } from '@adatechnology/recipe-contracts'\nimport {\n add,\n addDays,\n buildSuggestion,\n OPEN_ORDER_STATUSES,\n pendingQuantity,\n quantityText,\n toStockQuantity,\n weightedAverageCost,\n ZERO,\n type IncomingSupply,\n type ItemCost,\n type OrdersFromSuggestionData,\n type PriceHistoryQuery,\n type PricePoint,\n type PurchaseOrder,\n type PurchaseSuggestion,\n type SuggestionQuery,\n} from '@adatechnology/purchase-contracts'\nimport { and, count, desc, eq, gte, inArray, isNotNull, lt, type SQL } from 'drizzle-orm'\n\nimport { orderLines, orders, receiptLines, receipts, supplierItems, suppliers } from '../schema/schema'\nimport { assertEnabled, paginated, today, type Actor, type PurchaseDependencies } from '../shared/context'\nimport type { OrderService } from './orders'\n\nexport function createInsightService(dependencies: PurchaseDependencies, orderService: () => OrderService) {\n const { db } = dependencies\n\n async function incoming(params: {\n readonly companyId: string\n readonly itemRefs: readonly string[]\n }): Promise<IncomingSupply[]> {\n await assertEnabled(dependencies, params.companyId)\n const refs = [...new Set(params.itemRefs)]\n if (refs.length === 0) return []\n const rows = await db\n .select({ line: orderLines, expectedAt: orders.expectedAt })\n .from(orderLines)\n .innerJoin(orders, eq(orders.id, orderLines.orderId))\n .where(\n and(\n eq(orderLines.companyId, params.companyId),\n inArray(orderLines.itemRef, refs),\n isNotNull(orderLines.stockUnit),\n inArray(orders.status, [...OPEN_ORDER_STATUSES]),\n ),\n )\n const byItem = new Map<\n string,\n { quantity: ReturnType<typeof parseDecimal>; unit: RecipeUnit; orders: Set<string>; next: string | null }\n >()\n for (const { line, expectedAt } of rows) {\n const pending = parseDecimal(toStockQuantity(pendingQuantity(line), line.unitsPerPurchase))\n if (pending.numerator === 0n) continue\n const ref = line.itemRef as string\n const unit = line.stockUnit as RecipeUnit\n const current = byItem.get(ref) ?? { quantity: ZERO, unit, orders: new Set<string>(), next: null }\n // Linhas do mesmo item em unidades compatíveis (g e kg) somam na unidade da primeira.\n const converted = convertQuantity({ quantity: pending, from: unit, to: current.unit }) ?? pending\n current.quantity = add(current.quantity, converted)\n current.orders.add(line.orderId)\n if (expectedAt && (current.next === null || expectedAt < current.next)) current.next = expectedAt\n byItem.set(ref, current)\n }\n return [...byItem.entries()].map(([itemRef, value]) => ({\n itemRef,\n quantity: quantityText(value.quantity),\n unit: value.unit,\n orderCount: value.orders.size,\n nextExpectedAt: value.next,\n }))\n }\n\n async function itemCosts(params: {\n readonly companyId: string\n readonly itemRefs: readonly string[]\n }): Promise<ItemCost[]> {\n await assertEnabled(dependencies, params.companyId)\n const refs = [...new Set(params.itemRefs)]\n if (refs.length === 0) return []\n const windowDays = dependencies.averageCostWindowDays\n const since = new Date(dependencies.clock.now().getTime() - windowDays * 86_400_000)\n const rows = await db\n .select({\n itemRef: receiptLines.itemRef,\n stockUnit: receiptLines.stockUnit,\n cost: receiptLines.landedUnitCost,\n quantity: receiptLines.quantity,\n unitsPerPurchase: receiptLines.unitsPerPurchase,\n receivedAt: receipts.receivedAt,\n supplierId: receipts.supplierId,\n })\n .from(receiptLines)\n .innerJoin(receipts, eq(receipts.id, receiptLines.receiptId))\n .where(\n and(\n eq(receiptLines.companyId, params.companyId),\n inArray(receiptLines.itemRef, refs),\n isNotNull(receiptLines.landedUnitCost),\n ),\n )\n .orderBy(desc(receipts.receivedAt))\n return refs.map((itemRef) => {\n const points = rows.filter((row) => row.itemRef === itemRef)\n const last = points[0]\n const unit = (last?.stockUnit ?? null) as RecipeUnit | null\n const recent = points.filter((row) => row.receivedAt >= since)\n // Custo na unidade do último recebimento (custo por g → por kg multiplica por 1000).\n const normalized = recent.flatMap((row) => {\n const from = (row.stockUnit ?? unit) as RecipeUnit | null\n const quantity = toStockQuantity(row.quantity, row.unitsPerPurchase)\n if (!from || !unit || from === unit) return [{ cost: row.cost as string, quantity }]\n const factor = convertQuantity({ quantity: parseDecimal('1'), from: unit, to: from })\n const converted = convertQuantity({ quantity: parseDecimal(quantity), from, to: unit })\n if (!factor || !converted) return []\n const cost = formatDecimal({\n numerator: parseDecimal(row.cost as string).numerator * factor.numerator,\n denominator: parseDecimal(row.cost as string).denominator * factor.denominator,\n })\n return [{ cost, quantity: formatDecimal(converted) }]\n })\n return {\n itemRef,\n stockUnit: unit,\n lastCost: last?.cost ?? null,\n lastReceivedAt: last ? last.receivedAt.toISOString() : null,\n lastSupplierId: last?.supplierId ?? null,\n averageCost: weightedAverageCost(normalized),\n averageWindowDays: windowDays,\n }\n })\n }\n\n return {\n incoming,\n itemCosts,\n\n async priceHistory(params: { readonly companyId: string; readonly query: PriceHistoryQuery }) {\n await assertEnabled(dependencies, params.companyId)\n const { query } = params\n const conditions: SQL[] = [eq(receiptLines.companyId, params.companyId)]\n if (query.itemRef) conditions.push(eq(receiptLines.itemRef, query.itemRef))\n if (query.supplierItemId) conditions.push(eq(receiptLines.supplierItemId, query.supplierItemId))\n if (query.supplierId) conditions.push(eq(receipts.supplierId, query.supplierId))\n if (query.from) conditions.push(gte(receipts.receivedAt, new Date(`${query.from}T00:00:00Z`)))\n if (query.to) conditions.push(lt(receipts.receivedAt, new Date(`${addDays(query.to, 1)}T00:00:00Z`)))\n const where = and(...conditions) as SQL\n const [rows, totals] = await Promise.all([\n db\n .select({ line: receiptLines, receipt: receipts, supplierName: suppliers.name })\n .from(receiptLines)\n .innerJoin(receipts, eq(receipts.id, receiptLines.receiptId))\n .innerJoin(suppliers, eq(suppliers.id, receipts.supplierId))\n .where(where)\n .orderBy(desc(receipts.receivedAt), desc(receiptLines.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n db\n .select({ total: count() })\n .from(receiptLines)\n .innerJoin(receipts, eq(receipts.id, receiptLines.receiptId))\n .where(where),\n ])\n return paginated({\n rows,\n total: totals[0]?.total ?? 0,\n page: query.page,\n pageSize: query.pageSize,\n map: (row): PricePoint => ({\n supplierId: row.receipt.supplierId,\n supplierName: row.supplierName,\n receiptId: row.receipt.id,\n receivedAt: row.receipt.receivedAt.toISOString(),\n purchaseUnit: row.line.purchaseUnit,\n unitPrice: quantityText(parseDecimal(row.line.unitPrice)),\n landedUnitCost: row.line.landedUnitCost === null ? null : quantityText(parseDecimal(row.line.landedUnitCost)),\n stockUnit: (row.line.stockUnit ?? null) as RecipeUnit | null,\n }),\n })\n },\n\n async suggestion(params: {\n readonly companyId: string\n readonly query: SuggestionQuery\n }): Promise<PurchaseSuggestion> {\n await assertEnabled(dependencies, params.companyId)\n const demandSource = dependencies.providers.demand\n if (!demandSource) return { groups: [], hasDemandSource: false }\n const demand = await demandSource.getDemand({ companyId: params.companyId })\n const refs = demand.map((row) => row.itemRef)\n if (refs.length === 0) return { groups: [], hasDemandSource: true }\n const [incomingRows, items, supplierRows] = await Promise.all([\n incoming({ companyId: params.companyId, itemRefs: refs }),\n db\n .select()\n .from(supplierItems)\n .where(and(eq(supplierItems.companyId, params.companyId), inArray(supplierItems.itemRef, refs))),\n db.select().from(suppliers).where(eq(suppliers.companyId, params.companyId)),\n ])\n const demandUnits = new Map(demand.map((row) => [row.itemRef, row.stockUnit]))\n const incomingMap = new Map(\n incomingRows.map((row) => {\n const target = demandUnits.get(row.itemRef) ?? row.unit\n const converted = convertQuantity({ quantity: parseDecimal(row.quantity), from: row.unit, to: target })\n return [row.itemRef, converted ? formatDecimal(converted) : row.quantity]\n }),\n )\n return {\n hasDemandSource: true,\n groups: buildSuggestion({\n demand,\n incoming: incomingMap,\n supplierItems: items,\n suppliers: new Map(\n supplierRows.map((row) => [\n row.id,\n { id: row.id, name: row.name, minimumOrderAmount: row.minimumOrderAmount, isActive: row.isActive },\n ]),\n ),\n ...(params.query.supplierId ? { supplierId: params.query.supplierId } : {}),\n }),\n }\n },\n\n /** Um rascunho por fornecedor da sugestão (itens sem fornecedor ficam de fora). */\n async ordersFromSuggestion(params: Actor & { readonly input: OrdersFromSuggestionData }): Promise<PurchaseOrder[]> {\n const suggestion = await this.suggestion({ companyId: params.companyId, query: {} })\n const wanted = params.input.supplierIds ? new Set(params.input.supplierIds) : null\n const created: PurchaseOrder[] = []\n for (const group of suggestion.groups) {\n if (!group.supplierId || (wanted && !wanted.has(group.supplierId))) continue\n const lines = group.lines.filter((line) => line.supplierItemId && line.suggestedQuantity)\n if (lines.length === 0) continue\n created.push(\n await orderService().create({\n ...params,\n input: {\n supplierId: group.supplierId,\n notes: '',\n freight: '0',\n discount: '0',\n ...(params.input.expectedAt !== undefined ? { expectedAt: params.input.expectedAt } : {}),\n lines: lines.map((line) => ({\n supplierItemId: line.supplierItemId as string,\n quantity: line.suggestedQuantity as string,\n })),\n },\n }),\n )\n }\n return created\n },\n\n /** Pedidos abertos com previsão vencida, por empresa, para `scanLateOrders`. */\n async lateOrders(params: { readonly companyId?: string } = {}) {\n const day = today(dependencies)\n const conditions: SQL[] = [inArray(orders.status, [...OPEN_ORDER_STATUSES]), lt(orders.expectedAt, day)]\n if (params.companyId) conditions.push(eq(orders.companyId, params.companyId))\n const rows = await db\n .select({ order: orders, supplierName: suppliers.name })\n .from(orders)\n .innerJoin(suppliers, eq(suppliers.id, orders.supplierId))\n .where(and(...conditions))\n return { day, rows }\n },\n }\n}\n\nexport type InsightService = ReturnType<typeof createInsightService>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Schema `purchase`. Quantidade e preço em numeric(14,4), dinheiro de pedido e nota em numeric(14,2). `item_ref` é\n * texto opaco (o catálogo ligado decide o formato); sem catálogo, o item é só o nome com unidade.\n */\n\nimport { sql } from 'drizzle-orm'\nimport {\n boolean,\n check,\n date,\n index,\n integer,\n numeric,\n pgSchema,\n primaryKey,\n text,\n timestamp,\n uniqueIndex,\n uuid,\n varchar,\n} from 'drizzle-orm/pg-core'\n\nexport const purchaseSchema = pgSchema('purchase')\n\nexport const suppliers = purchaseSchema.table(\n 'suppliers',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n companyId: uuid('company_id').notNull(),\n name: varchar('name', { length: 160 }).notNull(),\n document: varchar('document', { length: 20 }),\n contactName: varchar('contact_name', { length: 120 }),\n email: varchar('email', { length: 254 }),\n phone: varchar('phone', { length: 30 }),\n whatsapp: varchar('whatsapp', { length: 30 }),\n paymentTermDays: integer('payment_term_days')\n .array()\n .notNull()\n .default(sql`'{0}'::integer[]`),\n leadTimeDays: integer('lead_time_days'),\n minimumOrderAmount: numeric('minimum_order_amount', { precision: 14, scale: 2 }),\n deliveryWeekdays: integer('delivery_weekdays')\n .array()\n .notNull()\n .default(sql`'{}'::integer[]`),\n notes: text('notes').notNull().default(''),\n isActive: boolean('is_active').notNull().default(true),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [\n index('idx_purchase_suppliers_company_name').on(table.companyId, table.name),\n uniqueIndex('uq_purchase_suppliers_company_document')\n .on(table.companyId, table.document)\n .where(sql`\"document\" is not null`),\n ],\n)\n\nexport const supplierItems = purchaseSchema.table(\n 'supplier_items',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n companyId: uuid('company_id').notNull(),\n supplierId: uuid('supplier_id')\n .notNull()\n .references(() => suppliers.id, { onDelete: 'cascade' }),\n itemRef: varchar('item_ref', { length: 128 }),\n itemName: varchar('item_name', { length: 160 }).notNull(),\n supplierSku: varchar('supplier_sku', { length: 100 }),\n purchaseUnit: varchar('purchase_unit', { length: 12 }).notNull(),\n unitsPerPurchase: numeric('units_per_purchase', { precision: 14, scale: 4 }).notNull().default('1'),\n stockUnit: varchar('stock_unit', { length: 8 }),\n lastPrice: numeric('last_price', { precision: 14, scale: 4 }),\n lastPriceAt: timestamp('last_price_at', { withTimezone: true }),\n priority: integer('priority').notNull().default(0),\n isActive: boolean('is_active').notNull().default(true),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [\n index('idx_purchase_supplier_items_item').on(table.companyId, table.itemRef),\n uniqueIndex('uq_purchase_supplier_items_sku')\n .on(table.companyId, table.supplierId, table.supplierSku)\n .where(sql`\"supplier_sku\" is not null`),\n uniqueIndex('uq_purchase_supplier_items_ref')\n .on(table.companyId, table.supplierId, table.itemRef)\n .where(sql`\"item_ref\" is not null`),\n check('purchase_supplier_items_units_positive', sql`\"units_per_purchase\" > 0`),\n check('purchase_supplier_items_price_not_negative', sql`\"last_price\" is null or \"last_price\" >= 0`),\n ],\n)\n\n/** Próximo número de pedido por empresa (`UPDATE ... RETURNING` serializa a corrida). */\nexport const orderCounters = purchaseSchema.table('order_counters', {\n companyId: uuid('company_id').primaryKey(),\n lastNumber: integer('last_number').notNull().default(0),\n})\n\nexport const orders = purchaseSchema.table(\n 'orders',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n companyId: uuid('company_id').notNull(),\n number: integer('number').notNull(),\n supplierId: uuid('supplier_id')\n .notNull()\n .references(() => suppliers.id),\n status: varchar('status', { length: 20 }).notNull().default('draft'),\n expectedAt: date('expected_at', { mode: 'string' }),\n notes: text('notes').notNull().default(''),\n subtotal: numeric('subtotal', { precision: 14, scale: 2 }).notNull().default('0'),\n freight: numeric('freight', { precision: 14, scale: 2 }).notNull().default('0'),\n discount: numeric('discount', { precision: 14, scale: 2 }).notNull().default('0'),\n total: numeric('total', { precision: 14, scale: 2 }).notNull().default('0'),\n paymentTermDays: integer('payment_term_days')\n .array()\n .notNull()\n .default(sql`'{0}'::integer[]`),\n requiresApproval: boolean('requires_approval').notNull().default(false),\n createdBy: varchar('created_by', { length: 128 }),\n submittedBy: varchar('submitted_by', { length: 128 }),\n submittedAt: timestamp('submitted_at', { withTimezone: true }),\n approvedBy: varchar('approved_by', { length: 128 }),\n approvedAt: timestamp('approved_at', { withTimezone: true }),\n rejectionReason: varchar('rejection_reason', { length: 500 }),\n sentAt: timestamp('sent_at', { withTimezone: true }),\n sentVia: varchar('sent_via', { length: 12 }),\n canceledAt: timestamp('canceled_at', { withTimezone: true }),\n cancelReason: varchar('cancel_reason', { length: 500 }),\n closedAt: timestamp('closed_at', { withTimezone: true }),\n lastLateAlertAt: date('last_late_alert_at', { mode: 'string' }),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [\n uniqueIndex('uq_purchase_orders_company_number').on(table.companyId, table.number),\n index('idx_purchase_orders_company_status').on(table.companyId, table.status, table.createdAt),\n index('idx_purchase_orders_supplier').on(table.companyId, table.supplierId),\n // Varredura de atraso e \"a caminho\": só pedido aberto.\n index('idx_purchase_orders_open_expected')\n .on(table.expectedAt)\n .where(sql`\"status\" in ('approved', 'sent', 'partially_received')`),\n ],\n)\n\nexport const orderLines = purchaseSchema.table(\n 'order_lines',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n orderId: uuid('order_id')\n .notNull()\n .references(() => orders.id, { onDelete: 'cascade' }),\n companyId: uuid('company_id').notNull(),\n position: integer('position').notNull(),\n supplierItemId: uuid('supplier_item_id').references(() => supplierItems.id, { onDelete: 'set null' }),\n itemRef: varchar('item_ref', { length: 128 }),\n itemName: varchar('item_name', { length: 160 }).notNull(),\n supplierSku: varchar('supplier_sku', { length: 100 }),\n purchaseUnit: varchar('purchase_unit', { length: 12 }).notNull(),\n unitsPerPurchase: numeric('units_per_purchase', { precision: 14, scale: 4 }).notNull().default('1'),\n stockUnit: varchar('stock_unit', { length: 8 }),\n quantity: numeric('quantity', { precision: 14, scale: 4 }).notNull(),\n unitPrice: numeric('unit_price', { precision: 14, scale: 4 }).notNull().default('0'),\n lineTotal: numeric('line_total', { precision: 14, scale: 2 }).notNull().default('0'),\n receivedQuantity: numeric('received_quantity', { precision: 14, scale: 4 }).notNull().default('0'),\n canceledQuantity: numeric('canceled_quantity', { precision: 14, scale: 4 }).notNull().default('0'),\n notes: varchar('notes', { length: 500 }),\n },\n (table) => [\n index('idx_purchase_order_lines_order').on(table.orderId, table.position),\n index('idx_purchase_order_lines_item').on(table.companyId, table.itemRef),\n check('purchase_order_lines_quantity_positive', sql`\"quantity\" > 0`),\n check('purchase_order_lines_units_positive', sql`\"units_per_purchase\" > 0`),\n ],\n)\n\nexport const receipts = purchaseSchema.table(\n 'receipts',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n companyId: uuid('company_id').notNull(),\n orderId: uuid('order_id').references(() => orders.id),\n supplierId: uuid('supplier_id')\n .notNull()\n .references(() => suppliers.id),\n receivedAt: timestamp('received_at', { withTimezone: true }).notNull(),\n invoiceNumber: varchar('invoice_number', { length: 30 }),\n invoiceKey: varchar('invoice_key', { length: 44 }),\n invoiceIssuedAt: timestamp('invoice_issued_at', { withTimezone: true }),\n subtotal: numeric('subtotal', { precision: 14, scale: 2 }).notNull(),\n freight: numeric('freight', { precision: 14, scale: 2 }).notNull().default('0'),\n discount: numeric('discount', { precision: 14, scale: 2 }).notNull().default('0'),\n total: numeric('total', { precision: 14, scale: 2 }).notNull(),\n notes: text('notes').notNull().default(''),\n actorId: varchar('actor_id', { length: 128 }),\n idempotencyKey: varchar('idempotency_key', { length: 128 }),\n /** Parcelas combinadas no recebimento (JSON `[{number,dueDate,amount}]`), usadas pela conta a pagar. */\n installments: text('installments').notNull().default('[]'),\n stockStatus: varchar('stock_status', { length: 10 }).notNull().default('skipped'),\n payableStatus: varchar('payable_status', { length: 10 }).notNull().default('skipped'),\n payableRef: varchar('payable_ref', { length: 200 }),\n paymentStatus: varchar('payment_status', { length: 10 }).notNull().default('none'),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [\n index('idx_purchase_receipts_company_received').on(table.companyId, table.receivedAt),\n index('idx_purchase_receipts_order').on(table.orderId),\n uniqueIndex('uq_purchase_receipts_invoice_key')\n .on(table.companyId, table.invoiceKey)\n .where(sql`\"invoice_key\" is not null`),\n uniqueIndex('uq_purchase_receipts_idempotency')\n .on(table.companyId, table.idempotencyKey)\n .where(sql`\"idempotency_key\" is not null`),\n index('idx_purchase_receipts_failed')\n .on(table.companyId)\n .where(sql`\"stock_status\" = 'failed' or \"payable_status\" = 'failed'`),\n ],\n)\n\nexport const receiptLines = purchaseSchema.table(\n 'receipt_lines',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n receiptId: uuid('receipt_id')\n .notNull()\n .references(() => receipts.id, { onDelete: 'cascade' }),\n companyId: uuid('company_id').notNull(),\n position: integer('position').notNull(),\n orderLineId: uuid('order_line_id').references(() => orderLines.id, { onDelete: 'set null' }),\n supplierItemId: uuid('supplier_item_id').references(() => supplierItems.id, { onDelete: 'set null' }),\n itemRef: varchar('item_ref', { length: 128 }),\n itemName: varchar('item_name', { length: 160 }).notNull(),\n supplierSku: varchar('supplier_sku', { length: 100 }),\n purchaseUnit: varchar('purchase_unit', { length: 12 }).notNull(),\n unitsPerPurchase: numeric('units_per_purchase', { precision: 14, scale: 4 }).notNull().default('1'),\n stockUnit: varchar('stock_unit', { length: 8 }),\n quantity: numeric('quantity', { precision: 14, scale: 4 }).notNull(),\n unitPrice: numeric('unit_price', { precision: 14, scale: 4 }).notNull(),\n lineTotal: numeric('line_total', { precision: 14, scale: 2 }).notNull(),\n allocated: numeric('allocated', { precision: 14, scale: 2 }).notNull().default('0'),\n landedUnitCost: numeric('landed_unit_cost', { precision: 14, scale: 4 }),\n batchCode: varchar('batch_code', { length: 100 }),\n expiresAt: date('expires_at', { mode: 'string' }),\n divergence: varchar('divergence', { length: 10 }).notNull().default('none'),\n divergenceReason: varchar('divergence_reason', { length: 500 }),\n stockStatus: varchar('stock_status', { length: 10 }).notNull().default('skipped'),\n },\n (table) => [\n index('idx_purchase_receipt_lines_receipt').on(table.receiptId, table.position),\n // Histórico de preço e custo médio por item.\n index('idx_purchase_receipt_lines_item').on(table.companyId, table.itemRef),\n index('idx_purchase_receipt_lines_supplier_item').on(table.supplierItemId),\n check('purchase_receipt_lines_quantity_positive', sql`\"quantity\" > 0`),\n ],\n)\n\n/** Pagamentos informados pela porta de contas (`onOccurrenceSettled` do `expense-module`), por recebimento. */\nexport const receiptPayments = purchaseSchema.table(\n 'receipt_payments',\n {\n companyId: uuid('company_id').notNull(),\n receiptId: uuid('receipt_id')\n .notNull()\n .references(() => receipts.id, { onDelete: 'cascade' }),\n installmentNumber: integer('installment_number').notNull(),\n paidAmount: numeric('paid_amount', { precision: 14, scale: 2 }).notNull(),\n paidAt: date('paid_at', { mode: 'string' }).notNull(),\n },\n (table) => [primaryKey({ columns: [table.receiptId, table.installmentNumber] })],\n)\n\nexport type SupplierRow = typeof suppliers.$inferSelect\nexport type NewSupplierRow = typeof suppliers.$inferInsert\nexport type SupplierItemRow = typeof supplierItems.$inferSelect\nexport type NewSupplierItemRow = typeof supplierItems.$inferInsert\nexport type OrderRow = typeof orders.$inferSelect\nexport type NewOrderRow = typeof orders.$inferInsert\nexport type OrderLineRow = typeof orderLines.$inferSelect\nexport type NewOrderLineRow = typeof orderLines.$inferInsert\nexport type ReceiptRow = typeof receipts.$inferSelect\nexport type NewReceiptRow = typeof receipts.$inferInsert\nexport type ReceiptLineRow = typeof receiptLines.$inferSelect\nexport type NewReceiptLineRow = typeof receiptLines.$inferInsert\nexport type ReceiptPaymentRow = typeof receiptPayments.$inferSelect\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport {\n civilDateIn,\n PurchaseDisabledError,\n type ClockPort,\n type DemandSourcePort,\n type ItemCatalogPort,\n type LoggerPort,\n type LogMeta,\n type OrderDispatchPort,\n type PayablesPort,\n type PurchaseHooks,\n type PurchaseModuleConfig,\n type StockReceiptPort,\n} from '@adatechnology/purchase-contracts'\n\nimport type { PurchaseDatabase } from '../database.types'\n\nexport type PurchaseProviders = {\n readonly catalog?: ItemCatalogPort\n readonly stock?: StockReceiptPort\n readonly demand?: DemandSourcePort\n readonly payables?: PayablesPort\n readonly dispatch?: OrderDispatchPort\n readonly clock?: ClockPort\n readonly logger?: LoggerPort\n}\n\nexport type PurchaseDependencies = {\n readonly db: PurchaseDatabase\n readonly config: PurchaseModuleConfig\n readonly providers: PurchaseProviders\n readonly hooks: PurchaseHooks\n readonly clock: ClockPort\n readonly logger: LoggerPort | undefined\n readonly timeZone: string\n readonly averageCostWindowDays: number\n}\n\nexport type Actor = { readonly companyId: string; readonly actorId?: string }\n\nexport async function assertEnabled(dependencies: PurchaseDependencies, companyId: string): Promise<void> {\n const enabled = (await dependencies.config.isEnabledForCompany?.(companyId)) ?? true\n if (!enabled) throw new PurchaseDisabledError()\n}\n\nexport function today(dependencies: PurchaseDependencies): string {\n return civilDateIn(dependencies.clock.now(), dependencies.timeZone)\n}\n\n/** Gancho do host roda depois do commit: erro é logado (só ids) e não desfaz a gravação. */\nexport async function runHook(\n dependencies: PurchaseDependencies,\n name: string,\n meta: LogMeta,\n run: () => void | Promise<void> | undefined,\n): Promise<void> {\n try {\n await run()\n } catch (error) {\n dependencies.logger?.error(`purchase: gancho ${name} falhou`, {\n ...meta,\n error: error instanceof Error ? error.name : 'unknown',\n })\n }\n}\n\nexport function actorFields(actor: Actor): { companyId: string; actorId?: string } {\n return { companyId: actor.companyId, ...(actor.actorId ? { actorId: actor.actorId } : {}) }\n}\n\nexport type Page<TRow> = { readonly rows: readonly TRow[]; readonly total: number }\n\nexport function paginated<TRow, TItem>(params: {\n readonly rows: readonly TRow[]\n readonly total: number\n readonly page: number\n readonly pageSize: number\n readonly map: (row: TRow) => TItem\n}) {\n return {\n data: params.rows.map(params.map),\n pagination: {\n total: params.total,\n page: params.page,\n pageSize: params.pageSize,\n totalPages: Math.max(1, Math.ceil(params.total / params.pageSize)),\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Rotina do host (cron diário): pedidos atrasados por empresa, avisados uma vez por dia (`last_late_alert_at`).\n */\n\nimport { inArray } from 'drizzle-orm'\n\nimport { orders } from '../schema/schema'\nimport { runHook, type PurchaseDependencies } from '../shared/context'\nimport type { InsightService } from './insights'\n\nexport type ScanLateOrdersResult = { readonly companies: number; readonly orders: number }\n\nfunction daysLate(expectedAt: string, today: string): number {\n return Math.round((Date.parse(`${today}T00:00:00Z`) - Date.parse(`${expectedAt}T00:00:00Z`)) / 86_400_000)\n}\n\nexport function createJobService(dependencies: PurchaseDependencies, insights: () => InsightService) {\n return {\n async scanLateOrders(params: { readonly companyId?: string } = {}): Promise<ScanLateOrdersResult> {\n const { day, rows } = await insights().lateOrders(params)\n const fresh = rows.filter((row) => row.order.lastLateAlertAt !== day)\n const byCompany = new Map<string, typeof fresh>()\n for (const row of fresh) byCompany.set(row.order.companyId, [...(byCompany.get(row.order.companyId) ?? []), row])\n for (const [companyId, items] of byCompany) {\n const enabled = (await dependencies.config.isEnabledForCompany?.(companyId)) ?? true\n if (!enabled) continue\n await runHook(dependencies, 'onOrdersLate', { companyId }, () =>\n dependencies.hooks.onOrdersLate?.({\n companyId,\n orders: items.map((row) => ({\n orderId: row.order.id,\n number: row.order.number,\n supplierId: row.order.supplierId,\n supplierName: row.supplierName,\n expectedAt: row.order.expectedAt as string,\n daysLate: daysLate(row.order.expectedAt as string, day),\n })),\n }),\n )\n await dependencies.db\n .update(orders)\n .set({ lastLateAlertAt: day })\n .where(\n inArray(\n orders.id,\n items.map((row) => row.order.id),\n ),\n )\n }\n return { companies: byCompany.size, orders: fresh.length }\n },\n }\n}\n\nexport type JobService = ReturnType<typeof createJobService>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Prévia do recebimento a partir do XML da NF-e: casa o emitente com o fornecedor (pelo documento), cada item com o\n * item do fornecedor (pelo código `cProd`) e com a linha pendente do pedido. Não grava nada: a pessoa confere a\n * prévia e confirma pelo `receive` de sempre (com `invoiceKey`, que impede receber a mesma nota duas vezes).\n */\n\nimport { normalizeDecimal, parseDecimal } from '@adatechnology/recipe-contracts'\nimport {\n compare,\n NfeInvalidError,\n NfeParseError,\n OrderNotFoundError,\n parseNfeXml,\n pendingQuantity,\n ZERO,\n type NfePreview,\n type NfePreviewLine,\n} from '@adatechnology/purchase-contracts'\nimport { and, eq } from 'drizzle-orm'\n\nimport { orderLines, orders, receipts, supplierItems, suppliers } from '../schema/schema'\nimport { assertEnabled, type PurchaseDependencies } from '../shared/context'\n\nexport function createNfeService(dependencies: PurchaseDependencies) {\n const { db } = dependencies\n return {\n async preview(params: {\n readonly companyId: string\n readonly xml: string\n readonly orderId?: string\n }): Promise<NfePreview> {\n await assertEnabled(dependencies, params.companyId)\n let nfe\n try {\n nfe = parseNfeXml(params.xml)\n } catch (error) {\n throw new NfeInvalidError(error instanceof NfeParseError ? error.message : 'XML ilegível')\n }\n const [supplier] = nfe.issuer.document\n ? await db\n .select()\n .from(suppliers)\n .where(and(eq(suppliers.companyId, params.companyId), eq(suppliers.document, nfe.issuer.document)))\n : []\n const [existing] = await db\n .select({ id: receipts.id })\n .from(receipts)\n .where(and(eq(receipts.companyId, params.companyId), eq(receipts.invoiceKey, nfe.accessKey)))\n const items = supplier\n ? await db\n .select()\n .from(supplierItems)\n .where(and(eq(supplierItems.companyId, params.companyId), eq(supplierItems.supplierId, supplier.id)))\n : []\n const bySku = new Map(\n items.flatMap((item) => (item.supplierSku ? [[item.supplierSku.toUpperCase(), item] as const] : [])),\n )\n let pending: (typeof orderLines.$inferSelect)[] = []\n if (params.orderId) {\n const [order] = await db\n .select()\n .from(orders)\n .where(and(eq(orders.companyId, params.companyId), eq(orders.id, params.orderId)))\n if (!order) throw new OrderNotFoundError(params.orderId)\n if (supplier && order.supplierId !== supplier.id) pending = []\n else\n pending = (await db.select().from(orderLines).where(eq(orderLines.orderId, order.id))).filter(\n (line) => compare(parseDecimal(pendingQuantity(line)), ZERO) > 0,\n )\n }\n const usedOrderLines = new Set<string>()\n const lines: NfePreviewLine[] = nfe.items.flatMap((item) => {\n const supplierItem = bySku.get(item.supplierSku.toUpperCase())\n const orderLine = pending.find(\n (line) =>\n !usedOrderLines.has(line.id) &&\n ((supplierItem && line.supplierItemId === supplierItem.id) ||\n (line.supplierSku !== null && line.supplierSku.toUpperCase() === item.supplierSku.toUpperCase())),\n )\n if (orderLine) usedOrderLines.add(orderLine.id)\n const batches = item.batches.length > 0 ? item.batches : [null]\n // Um item com vários lotes vira uma linha por lote (cada um com a sua validade).\n return batches.map((batch) => ({\n itemNumber: item.itemNumber,\n supplierSku: item.supplierSku,\n description: item.description,\n unit: item.unit,\n quantity: batch ? batch.quantity : item.quantity,\n unitPrice: item.unitPrice,\n total: item.total,\n batchCode: batch?.batchCode ?? null,\n expiresAt: batch?.expiresAt ?? null,\n supplierItemId: supplierItem?.id ?? null,\n itemRef: supplierItem?.itemRef ?? orderLine?.itemRef ?? null,\n itemName: supplierItem?.itemName ?? orderLine?.itemName ?? null,\n unitsPerPurchase: supplierItem ? normalizeDecimal(supplierItem.unitsPerPurchase) : null,\n stockUnit: (supplierItem?.stockUnit ?? orderLine?.stockUnit ?? null) as NfePreviewLine['stockUnit'],\n orderLineId: orderLine?.id ?? null,\n }))\n })\n return {\n accessKey: nfe.accessKey,\n number: nfe.number,\n series: nfe.series,\n issuedAt: nfe.issuedAt,\n issuer: { document: nfe.issuer.document, name: nfe.issuer.name },\n supplierId: supplier?.id ?? null,\n alreadyReceivedReceiptId: existing?.id ?? null,\n freight: nfe.totals.freight,\n discount: nfe.totals.discount,\n total: nfe.totals.total,\n installments: nfe.installments.map((installment, index) => ({\n number: index + 1,\n dueDate: installment.dueDate,\n amount: installment.amount,\n })),\n lines,\n }\n },\n }\n}\n\nexport type NfeService = ReturnType<typeof createNfeService>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Pedido de compra: rascunho, aprovação acima do limite, envio ao fornecedor, cancelamento e encerramento do saldo.\n * Toda transição trava a linha do pedido (`FOR UPDATE`): dois cliques não aprovam nem cancelam duas vezes.\n */\n\nimport { normalizeDecimal, parseDecimal } from '@adatechnology/recipe-contracts'\nimport {\n addDays,\n buildOrderMessage,\n canPerform,\n centsOf,\n computeTotals,\n DispatchUnavailableError,\n DISPATCH_CHANNEL,\n InvalidOrderTransitionError,\n lineTotal,\n money,\n ORDER_ACTION,\n ORDER_STATUS,\n OrderNotFoundError,\n pendingQuantity,\n requiresApproval as needsApproval,\n SelfApprovalError,\n statusAfterSend,\n SupplierInactiveError,\n SupplierItemNotFoundError,\n SupplierNoContactError,\n type CreateOrderData,\n type ListOrdersQuery,\n type OrderAction,\n type OrderLineData,\n type OrderStatus,\n type PaymentStatus,\n type PurchaseOrder,\n type SendOrderData,\n type UpdateOrderData,\n} from '@adatechnology/purchase-contracts'\nimport { and, asc, count, desc, eq, gte, ilike, inArray, lt, lte, or, sql, type SQL } from 'drizzle-orm'\n\nimport type { PurchaseDatabase } from '../database.types'\nimport {\n orderCounters,\n orderLines,\n orders,\n receipts,\n supplierItems,\n suppliers,\n type NewOrderLineRow,\n type OrderLineRow,\n type OrderRow,\n type SupplierRow,\n} from '../schema/schema'\nimport {\n actorFields,\n assertEnabled,\n paginated,\n runHook,\n today,\n type Actor,\n type PurchaseDependencies,\n} from '../shared/context'\nimport { intList, toOrder, toOrderSummary } from '../shared/mappers'\nimport { likePattern } from '../shared/postgresErrors'\nimport { findSupplierRow, requireCatalogItems } from './suppliers'\n\ntype Tx = PurchaseDatabase\n\nconst ORDER_SORT_COLUMNS = {\n number: orders.number,\n createdAt: orders.createdAt,\n expectedAt: orders.expectedAt,\n total: orders.total,\n} as const\n\nexport async function lockOrder(tx: Tx, companyId: string, orderId: string): Promise<OrderRow> {\n const [row] = await tx\n .select()\n .from(orders)\n .where(and(eq(orders.companyId, companyId), eq(orders.id, orderId)))\n .for('update')\n if (!row) throw new OrderNotFoundError(orderId)\n return row\n}\n\nexport function assertAction(row: OrderRow, action: OrderAction): void {\n if (!canPerform(row.status as OrderStatus, action))\n throw new InvalidOrderTransitionError({ status: row.status, action })\n}\n\nasync function nextOrderNumber(tx: Tx, companyId: string): Promise<number> {\n const [row] = await tx\n .insert(orderCounters)\n .values({ companyId, lastNumber: 1 })\n .onConflictDoUpdate({ target: orderCounters.companyId, set: { lastNumber: sql`${orderCounters.lastNumber} + 1` } })\n .returning({ lastNumber: orderCounters.lastNumber })\n return row?.lastNumber ?? 1\n}\n\n/** Pagamento do pedido a partir dos recebimentos: todos pagos = `paid`, algum pago = `partial`. */\nexport async function paymentStatusByOrder(\n db: PurchaseDatabase,\n companyId: string,\n orderIds: readonly string[],\n): Promise<Map<string, PaymentStatus>> {\n if (orderIds.length === 0) return new Map()\n const rows = await db\n .select({ orderId: receipts.orderId, status: receipts.paymentStatus })\n .from(receipts)\n .where(and(eq(receipts.companyId, companyId), inArray(receipts.orderId, [...orderIds])))\n const byOrder = new Map<string, string[]>()\n for (const row of rows) if (row.orderId) byOrder.set(row.orderId, [...(byOrder.get(row.orderId) ?? []), row.status])\n const result = new Map<string, PaymentStatus>()\n for (const [orderId, statuses] of byOrder) {\n const tracked = statuses.filter((status) => status !== 'none')\n if (tracked.length === 0) result.set(orderId, 'none')\n else if (tracked.every((status) => status === 'paid') && tracked.length === statuses.length)\n result.set(orderId, 'paid')\n else if (tracked.some((status) => status === 'paid' || status === 'partial')) result.set(orderId, 'partial')\n else result.set(orderId, 'open')\n }\n return result\n}\n\nexport function createOrderService(dependencies: PurchaseDependencies) {\n const { db } = dependencies\n\n /** Completa cada linha pelo item do fornecedor (que precisa ser deste fornecedor) e confere o catálogo. */\n async function resolveLines(\n tx: Tx,\n params: { readonly companyId: string; readonly supplierId: string; readonly lines: readonly OrderLineData[] },\n ): Promise<(Omit<NewOrderLineRow, 'orderId'> & { quantity: string; unitPrice: string })[]> {\n const itemIds = [...new Set(params.lines.flatMap((line) => (line.supplierItemId ? [line.supplierItemId] : [])))]\n const items =\n itemIds.length === 0\n ? []\n : await tx\n .select()\n .from(supplierItems)\n .where(\n and(\n eq(supplierItems.companyId, params.companyId),\n eq(supplierItems.supplierId, params.supplierId),\n inArray(supplierItems.id, itemIds),\n ),\n )\n const byId = new Map(items.map((item) => [item.id, item]))\n const resolved = params.lines.map((line, position) => {\n const item = line.supplierItemId ? byId.get(line.supplierItemId) : undefined\n if (line.supplierItemId && !item) throw new SupplierItemNotFoundError(line.supplierItemId)\n const unitPrice = normalizeDecimal(line.unitPrice ?? item?.lastPrice ?? '0')\n const quantity = normalizeDecimal(line.quantity)\n return {\n companyId: params.companyId,\n position,\n supplierItemId: item?.id ?? null,\n itemRef: line.itemRef ?? item?.itemRef ?? null,\n itemName: line.itemName ?? item?.itemName ?? '',\n supplierSku: line.supplierSku ?? item?.supplierSku ?? null,\n purchaseUnit: line.purchaseUnit ?? item?.purchaseUnit ?? 'un',\n unitsPerPurchase: normalizeDecimal(line.unitsPerPurchase ?? item?.unitsPerPurchase ?? '1'),\n stockUnit: line.stockUnit ?? item?.stockUnit ?? null,\n quantity,\n unitPrice,\n lineTotal: money(lineTotal(quantity, unitPrice)),\n notes: line.notes ?? null,\n }\n })\n const refs = resolved.flatMap((line) => (line.itemRef ? [line.itemRef] : []))\n const catalog = await requireCatalogItems(dependencies, params.companyId, refs)\n if (catalog) {\n for (const line of resolved) {\n if (!line.itemRef) continue\n const entry = catalog.get(line.itemRef)\n if (entry && !line.stockUnit) line.stockUnit = entry.unit\n if (entry && !line.itemName) line.itemName = entry.name\n }\n }\n return resolved.map((line) => ({ ...line, itemName: line.itemName || 'Item' }))\n }\n\n async function load(companyId: string, orderId: string, runner: Tx = db): Promise<PurchaseOrder> {\n const [row] = await runner\n .select({ order: orders, supplierName: suppliers.name })\n .from(orders)\n .innerJoin(suppliers, eq(suppliers.id, orders.supplierId))\n .where(and(eq(orders.companyId, companyId), eq(orders.id, orderId)))\n if (!row) throw new OrderNotFoundError(orderId)\n const lines = await runner\n .select()\n .from(orderLines)\n .where(eq(orderLines.orderId, orderId))\n .orderBy(asc(orderLines.position))\n const payments = await paymentStatusByOrder(runner, companyId, [orderId])\n return toOrder({\n row: row.order,\n supplierName: row.supplierName,\n lines,\n today: today(dependencies),\n paymentStatus: payments.get(orderId) ?? 'none',\n })\n }\n\n async function notifyStatus(actor: Actor, order: OrderRow, from: OrderStatus, to: OrderStatus): Promise<void> {\n if (from === to) return\n await runHook(dependencies, 'onOrderStatusChanged', { companyId: actor.companyId, orderId: order.id }, () =>\n dependencies.hooks.onOrderStatusChanged?.({\n ...actorFields(actor),\n orderId: order.id,\n number: order.number,\n from,\n to,\n }),\n )\n }\n\n /** Transição simples com trava: valida a ação, grava e avisa depois do commit. */\n async function transition(\n actor: Actor & { readonly orderId: string },\n action: OrderAction,\n change: (row: OrderRow, tx: Tx) => Promise<Partial<OrderRow>>,\n ): Promise<PurchaseOrder> {\n await assertEnabled(dependencies, actor.companyId)\n const result = await db.transaction(async (tx) => {\n const row = await lockOrder(tx, actor.companyId, actor.orderId)\n assertAction(row, action)\n const values = await change(row, tx)\n const [updated] = await tx\n .update(orders)\n .set({ ...values, updatedAt: dependencies.clock.now() })\n .where(eq(orders.id, row.id))\n .returning()\n return { before: row, after: updated as OrderRow }\n })\n await notifyStatus(actor, result.after, result.before.status as OrderStatus, result.after.status as OrderStatus)\n return load(actor.companyId, actor.orderId)\n }\n\n function defaultExpectedAt(supplier: SupplierRow): string | null {\n return supplier.leadTimeDays === null ? null : addDays(today(dependencies), supplier.leadTimeDays)\n }\n\n const service = {\n load,\n\n async create(params: Actor & { readonly input: CreateOrderData }): Promise<PurchaseOrder> {\n await assertEnabled(dependencies, params.companyId)\n const supplier = await findSupplierRow(dependencies, params.companyId, params.input.supplierId)\n if (!supplier.isActive) throw new SupplierInactiveError(supplier.id)\n const orderId = await db.transaction(async (tx) => {\n const lines = await resolveLines(tx, {\n companyId: params.companyId,\n supplierId: supplier.id,\n lines: params.input.lines,\n })\n const totals = computeTotals({ lines, freight: params.input.freight, discount: params.input.discount })\n const now = dependencies.clock.now()\n const [order] = await tx\n .insert(orders)\n .values({\n companyId: params.companyId,\n number: await nextOrderNumber(tx, params.companyId),\n supplierId: supplier.id,\n status: ORDER_STATUS.DRAFT,\n expectedAt: params.input.expectedAt === undefined ? defaultExpectedAt(supplier) : params.input.expectedAt,\n notes: params.input.notes,\n ...totals,\n paymentTermDays: params.input.paymentTermDays ?? intList(supplier.paymentTermDays),\n createdBy: params.actorId ?? null,\n createdAt: now,\n updatedAt: now,\n })\n .returning({ id: orders.id })\n const id = (order as { id: string }).id\n await tx.insert(orderLines).values(lines.map((line) => ({ ...line, orderId: id })))\n return id\n })\n return load(params.companyId, orderId)\n },\n\n async get(params: { readonly companyId: string; readonly id: string }): Promise<PurchaseOrder> {\n await assertEnabled(dependencies, params.companyId)\n return load(params.companyId, params.id)\n },\n\n async list(params: { readonly companyId: string; readonly query: ListOrdersQuery }) {\n await assertEnabled(dependencies, params.companyId)\n const { query } = params\n const conditions: SQL[] = [eq(orders.companyId, params.companyId)]\n if (query.status?.length) conditions.push(inArray(orders.status, query.status))\n if (query.supplierId) conditions.push(eq(orders.supplierId, query.supplierId))\n if (query.from) conditions.push(gte(orders.createdAt, new Date(`${query.from}T00:00:00Z`)))\n if (query.to) conditions.push(lt(orders.createdAt, new Date(`${addDays(query.to, 1)}T00:00:00Z`)))\n if (query.late === true) {\n conditions.push(inArray(orders.status, ['approved', 'sent', 'partially_received']))\n conditions.push(lt(orders.expectedAt, today(dependencies)))\n }\n if (query.search) {\n const asNumber = Number(query.search.replace(/^#/, ''))\n const byName = ilike(suppliers.name, likePattern(query.search))\n conditions.push(\n (Number.isInteger(asNumber) && asNumber > 0 ? or(eq(orders.number, asNumber), byName) : byName) as SQL,\n )\n }\n const where = and(...conditions) as SQL\n const column = ORDER_SORT_COLUMNS[query.sort]\n const lineCounts = db\n .select({ orderId: orderLines.orderId, lineCount: count().as('line_count') })\n .from(orderLines)\n .where(eq(orderLines.companyId, params.companyId))\n .groupBy(orderLines.orderId)\n .as('line_counts')\n const [rows, totals] = await Promise.all([\n db\n .select({ order: orders, supplierName: suppliers.name, lineCount: lineCounts.lineCount })\n .from(orders)\n .innerJoin(suppliers, eq(suppliers.id, orders.supplierId))\n .leftJoin(lineCounts, eq(lineCounts.orderId, orders.id))\n .where(where)\n .orderBy(query.order === 'asc' ? asc(column) : desc(column), desc(orders.number))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n db\n .select({ total: count() })\n .from(orders)\n .innerJoin(suppliers, eq(suppliers.id, orders.supplierId))\n .where(where),\n ])\n const payments = await paymentStatusByOrder(\n db,\n params.companyId,\n rows.map((row) => row.order.id),\n )\n const currentDay = today(dependencies)\n return paginated({\n rows,\n total: totals[0]?.total ?? 0,\n page: query.page,\n pageSize: query.pageSize,\n map: (row) =>\n toOrderSummary({\n row: row.order,\n supplierName: row.supplierName,\n lineCount: Number(row.lineCount ?? 0),\n today: currentDay,\n paymentStatus: payments.get(row.order.id) ?? 'none',\n }),\n })\n },\n\n async update(params: Actor & { readonly id: string; readonly input: UpdateOrderData }): Promise<PurchaseOrder> {\n await assertEnabled(dependencies, params.companyId)\n const { input } = params\n await db.transaction(async (tx) => {\n const row = await lockOrder(tx, params.companyId, params.id)\n assertAction(row, ORDER_ACTION.EDIT)\n let lineValues: { quantity: string; unitPrice: string }[]\n if (input.lines) {\n const lines = await resolveLines(tx, {\n companyId: params.companyId,\n supplierId: row.supplierId,\n lines: input.lines,\n })\n await tx.delete(orderLines).where(eq(orderLines.orderId, row.id))\n await tx.insert(orderLines).values(lines.map((line) => ({ ...line, orderId: row.id })))\n lineValues = lines\n } else {\n lineValues = await tx\n .select({ quantity: orderLines.quantity, unitPrice: orderLines.unitPrice })\n .from(orderLines)\n .where(eq(orderLines.orderId, row.id))\n }\n const totals = computeTotals({\n lines: lineValues,\n freight: input.freight ?? row.freight,\n discount: input.discount ?? row.discount,\n })\n await tx\n .update(orders)\n .set({\n ...(input.expectedAt !== undefined ? { expectedAt: input.expectedAt } : {}),\n ...(input.notes !== undefined ? { notes: input.notes } : {}),\n ...(input.paymentTermDays !== undefined ? { paymentTermDays: input.paymentTermDays } : {}),\n ...totals,\n updatedAt: dependencies.clock.now(),\n })\n .where(eq(orders.id, row.id))\n })\n return load(params.companyId, params.id)\n },\n\n /** Rascunho → aprovado, ou → aguardando aprovação quando o total passa do limite da empresa. */\n async submit(params: Actor & { readonly id: string }): Promise<PurchaseOrder> {\n const threshold = (await dependencies.config.approvalThresholdFor?.(params.companyId)) ?? null\n const thresholdCents = threshold === null ? null : centsOf(parseDecimal(threshold))\n let approvalNeeded = false\n const order = await transition({ ...params, orderId: params.id }, ORDER_ACTION.SUBMIT, async (row) => {\n approvalNeeded = needsApproval({ totalCents: centsOf(parseDecimal(row.total)), thresholdCents })\n const now = dependencies.clock.now()\n return {\n status: approvalNeeded ? ORDER_STATUS.PENDING_APPROVAL : ORDER_STATUS.APPROVED,\n requiresApproval: approvalNeeded,\n submittedBy: params.actorId ?? null,\n submittedAt: now,\n rejectionReason: null,\n ...(approvalNeeded ? {} : { approvedAt: now, approvedBy: params.actorId ?? null }),\n }\n })\n if (approvalNeeded)\n await runHook(dependencies, 'onApprovalRequested', { companyId: params.companyId, orderId: order.id }, () =>\n dependencies.hooks.onApprovalRequested?.({\n companyId: params.companyId,\n orderId: order.id,\n number: order.number,\n total: order.total,\n ...(params.actorId ? { requestedBy: params.actorId } : {}),\n }),\n )\n return order\n },\n\n async approve(params: Actor & { readonly id: string }): Promise<PurchaseOrder> {\n return transition({ ...params, orderId: params.id }, ORDER_ACTION.APPROVE, async (row) => {\n if (row.submittedBy && params.actorId && row.submittedBy === params.actorId) throw new SelfApprovalError()\n return {\n status: ORDER_STATUS.APPROVED,\n approvedBy: params.actorId ?? null,\n approvedAt: dependencies.clock.now(),\n }\n })\n },\n\n async reject(params: Actor & { readonly id: string; readonly reason: string }): Promise<PurchaseOrder> {\n return transition({ ...params, orderId: params.id }, ORDER_ACTION.REJECT, async () => ({\n status: ORDER_STATUS.DRAFT,\n rejectionReason: params.reason,\n submittedAt: null,\n submittedBy: null,\n }))\n },\n\n async cancel(params: Actor & { readonly id: string; readonly reason: string }): Promise<PurchaseOrder> {\n return transition({ ...params, orderId: params.id }, ORDER_ACTION.CANCEL, async () => ({\n status: ORDER_STATUS.CANCELED,\n cancelReason: params.reason,\n canceledAt: dependencies.clock.now(),\n }))\n },\n\n /** Recebido em parte e o resto não vem: o saldo de cada linha vira cancelado e o pedido fecha. */\n async close(params: Actor & { readonly id: string; readonly reason: string }): Promise<PurchaseOrder> {\n return transition({ ...params, orderId: params.id }, ORDER_ACTION.CLOSE, async (row, tx) => {\n const lines = await tx.select().from(orderLines).where(eq(orderLines.orderId, row.id)).for('update')\n for (const line of lines) {\n const pending = pendingQuantity(line)\n if (parseDecimal(pending).numerator === 0n) continue\n await tx\n .update(orderLines)\n .set({ canceledQuantity: sql`${orderLines.canceledQuantity} + ${pending}::numeric` })\n .where(eq(orderLines.id, line.id))\n }\n return {\n status: ORDER_STATUS.CLOSED,\n closedAt: dependencies.clock.now(),\n cancelReason: params.reason || null,\n }\n })\n },\n\n /** Texto do pedido (o mesmo que vai no WhatsApp), para conferir ou copiar. */\n async message(params: { readonly companyId: string; readonly id: string; readonly withPrices?: boolean }) {\n await assertEnabled(dependencies, params.companyId)\n const order = await load(params.companyId, params.id)\n const companyName = (await dependencies.config.companyNameFor?.(params.companyId)) ?? ''\n return {\n text: buildOrderMessage(\n {\n companyName,\n number: order.number,\n supplierName: order.supplierName ?? '',\n expectedAt: order.expectedAt,\n paymentTermDays: order.paymentTermDays,\n notes: order.notes,\n total: order.total,\n lines: order.lines,\n },\n { withPrices: params.withPrices === true },\n ),\n }\n },\n\n /**\n * Envia pelo canal pedido (porta `dispatch`) ou só marca como enviado (`manual`). O envio acontece fora da\n * transação; se a porta falhar, o pedido continua como estava.\n */\n async send(params: Actor & { readonly id: string; readonly input: SendOrderData }) {\n await assertEnabled(dependencies, params.companyId)\n const { channel } = params.input\n const dispatch = dependencies.providers.dispatch\n if (channel !== DISPATCH_CHANNEL.MANUAL && !dispatch?.channels.includes(channel))\n throw new DispatchUnavailableError(channel)\n const current = await load(params.companyId, params.id)\n if (!canPerform(current.status, ORDER_ACTION.SEND))\n throw new InvalidOrderTransitionError({ status: current.status, action: ORDER_ACTION.SEND })\n const supplier = await findSupplierRow(dependencies, params.companyId, current.supplierId)\n const phone = supplier.whatsapp ?? supplier.phone\n if (channel === DISPATCH_CHANNEL.WHATSAPP && !phone) throw new SupplierNoContactError(channel)\n if (channel === DISPATCH_CHANNEL.EMAIL && !supplier.email) throw new SupplierNoContactError(channel)\n const { text } = await service.message({ ...params, withPrices: params.input.withPrices })\n let messageRef: string | undefined\n if (channel !== DISPATCH_CHANNEL.MANUAL && dispatch) {\n const sent = await dispatch.dispatch({\n ...actorFields(params),\n channel,\n orderId: current.id,\n orderNumber: current.number,\n to: { name: supplier.contactName ?? supplier.name, phone, email: supplier.email },\n text,\n })\n messageRef = sent.messageRef\n }\n const order = await transition({ ...params, orderId: params.id }, ORDER_ACTION.SEND, async (row) => ({\n status: statusAfterSend(row.status as OrderStatus),\n sentAt: dependencies.clock.now(),\n sentVia: channel,\n }))\n return { order, text, ...(messageRef ? { messageRef } : {}) }\n },\n\n /** Novo rascunho com as mesmas linhas e o último preço de cada item (compra de rotina). */\n async duplicate(params: Actor & { readonly id: string }): Promise<PurchaseOrder> {\n await assertEnabled(dependencies, params.companyId)\n const source = await load(params.companyId, params.id)\n return service.create({\n ...params,\n input: {\n supplierId: source.supplierId,\n notes: source.notes,\n freight: '0',\n discount: '0',\n paymentTermDays: [...source.paymentTermDays],\n lines: source.lines.map((line) => ({\n ...(line.supplierItemId ? { supplierItemId: line.supplierItemId } : {}),\n ...(line.itemRef ? { itemRef: line.itemRef } : {}),\n itemName: line.itemName,\n purchaseUnit: line.purchaseUnit,\n unitsPerPurchase: line.unitsPerPurchase,\n ...(line.stockUnit ? { stockUnit: line.stockUnit } : {}),\n ...(line.supplierSku ? { supplierSku: line.supplierSku } : {}),\n quantity: line.quantity,\n // Sem `unitPrice`: com item do fornecedor, vem o último preço; linha livre repete o anterior.\n ...(line.supplierItemId ? {} : { unitPrice: line.unitPrice }),\n })),\n },\n })\n },\n\n /** Para a varredura de atraso e o \"a caminho\": pedidos abertos com previsão até a data. */\n async openOrdersExpectedBefore(day: string) {\n return db\n .select({ order: orders, supplierName: suppliers.name })\n .from(orders)\n .innerJoin(suppliers, eq(suppliers.id, orders.supplierId))\n .where(and(inArray(orders.status, ['approved', 'sent', 'partially_received']), lte(orders.expectedAt, day)))\n },\n }\n return service\n}\n\nexport type OrderService = ReturnType<typeof createOrderService>\nexport type { OrderLineRow }\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { normalizeDecimal, type RecipeUnit } from '@adatechnology/recipe-contracts'\nimport {\n isOrderLate,\n money,\n pendingQuantity,\n type DispatchChannel,\n type Divergence,\n type Installment,\n type IntegrationStatus,\n type OrderLine,\n type OrderStatus,\n type PaymentStatus,\n type PurchaseOrder,\n type PurchaseOrderSummary,\n type Receipt,\n type ReceiptLine,\n type Supplier,\n type SupplierItem,\n} from '@adatechnology/purchase-contracts'\nimport { parseDecimal } from '@adatechnology/recipe-contracts'\n\nimport type { OrderLineRow, OrderRow, ReceiptLineRow, ReceiptRow, SupplierItemRow, SupplierRow } from '../schema/schema'\n\n/** Bun SQL devolve `integer[]` como `Int32Array`; node-postgres, como array. */\nexport const intList = (value: ArrayLike<number> | null | undefined): number[] => Array.from(value ?? [])\nconst iso = (value: Date | null) => (value ? value.toISOString() : null)\nconst decimal = (value: string) => normalizeDecimal(value)\nconst moneyText = (value: string) => money(parseDecimal(value))\n\nexport function toSupplier(row: SupplierRow): Supplier {\n return {\n id: row.id,\n name: row.name,\n document: row.document,\n contactName: row.contactName,\n email: row.email,\n phone: row.phone,\n whatsapp: row.whatsapp,\n paymentTermDays: intList(row.paymentTermDays),\n leadTimeDays: row.leadTimeDays,\n minimumOrderAmount: row.minimumOrderAmount === null ? null : moneyText(row.minimumOrderAmount),\n deliveryWeekdays: intList(row.deliveryWeekdays),\n notes: row.notes,\n isActive: row.isActive,\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n }\n}\n\nexport function toSupplierItem(row: SupplierItemRow): SupplierItem {\n return {\n id: row.id,\n supplierId: row.supplierId,\n itemRef: row.itemRef,\n itemName: row.itemName,\n supplierSku: row.supplierSku,\n purchaseUnit: row.purchaseUnit,\n unitsPerPurchase: decimal(row.unitsPerPurchase),\n stockUnit: (row.stockUnit ?? null) as RecipeUnit | null,\n lastPrice: row.lastPrice === null ? null : decimal(row.lastPrice),\n lastPriceAt: iso(row.lastPriceAt),\n priority: row.priority,\n isActive: row.isActive,\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n }\n}\n\nexport function toOrderLine(row: OrderLineRow): OrderLine {\n return {\n id: row.id,\n position: row.position,\n supplierItemId: row.supplierItemId,\n itemRef: row.itemRef,\n itemName: row.itemName,\n supplierSku: row.supplierSku,\n purchaseUnit: row.purchaseUnit,\n unitsPerPurchase: decimal(row.unitsPerPurchase),\n stockUnit: (row.stockUnit ?? null) as RecipeUnit | null,\n quantity: decimal(row.quantity),\n unitPrice: decimal(row.unitPrice),\n lineTotal: moneyText(row.lineTotal),\n receivedQuantity: decimal(row.receivedQuantity),\n canceledQuantity: decimal(row.canceledQuantity),\n pendingQuantity: pendingQuantity(row),\n notes: row.notes,\n }\n}\n\nexport function toOrderSummary(params: {\n readonly row: OrderRow\n readonly supplierName: string | null\n readonly lineCount: number\n readonly today: string\n readonly paymentStatus: PaymentStatus\n}): PurchaseOrderSummary {\n const { row } = params\n return {\n id: row.id,\n number: row.number,\n supplierId: row.supplierId,\n supplierName: params.supplierName,\n status: row.status as OrderStatus,\n expectedAt: row.expectedAt,\n isLate: isOrderLate({ status: row.status as OrderStatus, expectedAt: row.expectedAt, today: params.today }),\n subtotal: moneyText(row.subtotal),\n freight: moneyText(row.freight),\n discount: moneyText(row.discount),\n total: moneyText(row.total),\n paymentTermDays: intList(row.paymentTermDays),\n notes: row.notes,\n requiresApproval: row.requiresApproval,\n createdBy: row.createdBy,\n submittedAt: iso(row.submittedAt),\n approvedBy: row.approvedBy,\n approvedAt: iso(row.approvedAt),\n rejectionReason: row.rejectionReason,\n sentAt: iso(row.sentAt),\n sentVia: (row.sentVia ?? null) as DispatchChannel | null,\n canceledAt: iso(row.canceledAt),\n cancelReason: row.cancelReason,\n closedAt: iso(row.closedAt),\n paymentStatus: params.paymentStatus,\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n lineCount: params.lineCount,\n }\n}\n\nexport function toOrder(params: {\n readonly row: OrderRow\n readonly supplierName: string | null\n readonly lines: readonly OrderLineRow[]\n readonly today: string\n readonly paymentStatus: PaymentStatus\n}): PurchaseOrder {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { lineCount, ...summary } = toOrderSummary({ ...params, lineCount: params.lines.length })\n return { ...summary, lines: params.lines.map(toOrderLine) }\n}\n\nexport function toReceiptLine(row: ReceiptLineRow): ReceiptLine {\n return {\n id: row.id,\n orderLineId: row.orderLineId,\n itemRef: row.itemRef,\n itemName: row.itemName,\n supplierSku: row.supplierSku,\n purchaseUnit: row.purchaseUnit,\n unitsPerPurchase: decimal(row.unitsPerPurchase),\n stockUnit: (row.stockUnit ?? null) as RecipeUnit | null,\n quantity: decimal(row.quantity),\n unitPrice: decimal(row.unitPrice),\n lineTotal: moneyText(row.lineTotal),\n landedUnitCost: row.landedUnitCost === null ? null : decimal(row.landedUnitCost),\n batchCode: row.batchCode,\n expiresAt: row.expiresAt,\n divergence: row.divergence as Divergence,\n divergenceReason: row.divergenceReason,\n stockStatus: row.stockStatus as IntegrationStatus,\n }\n}\n\nexport function toReceipt(params: {\n readonly row: ReceiptRow\n readonly lines: readonly ReceiptLineRow[]\n readonly supplierName: string | null\n readonly orderNumber: number | null\n}): Receipt {\n const { row } = params\n return {\n id: row.id,\n orderId: row.orderId,\n orderNumber: params.orderNumber,\n supplierId: row.supplierId,\n supplierName: params.supplierName,\n receivedAt: row.receivedAt.toISOString(),\n invoiceNumber: row.invoiceNumber,\n invoiceKey: row.invoiceKey,\n invoiceIssuedAt: iso(row.invoiceIssuedAt),\n subtotal: moneyText(row.subtotal),\n freight: moneyText(row.freight),\n discount: moneyText(row.discount),\n total: moneyText(row.total),\n notes: row.notes,\n actorId: row.actorId,\n stockStatus: row.stockStatus as IntegrationStatus,\n payableStatus: row.payableStatus as IntegrationStatus,\n payableRef: row.payableRef,\n paymentStatus: row.paymentStatus as PaymentStatus,\n createdAt: row.createdAt.toISOString(),\n lines: params.lines.map(toReceiptLine),\n }\n}\n\nexport function parseInstallments(text: string): Installment[] {\n try {\n const value = JSON.parse(text) as unknown\n return Array.isArray(value) ? (value as Installment[]) : []\n } catch {\n return []\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nconst FOREIGN_KEY_VIOLATION = '23503'\nconst UNIQUE_VIOLATION = '23505'\n\n// O driver embrulha o erro do Postgres em `cause` conforme a versão, e o Bun SQL põe o SQLSTATE em\n// `errno` (o `code` dele é `ERR_POSTGRES_SERVER_ERROR`): procura os dois, alguns níveis abaixo.\nfunction hasPostgresCode(error: unknown, code: string): boolean {\n let current: unknown = error\n for (let depth = 0; depth < 3 && typeof current === 'object' && current !== null; depth += 1) {\n const candidate = current as { code?: unknown; errno?: unknown }\n if (candidate.code === code || candidate.errno === code) return true\n current = (current as { cause?: unknown }).cause\n }\n return false\n}\n\nexport function isForeignKeyViolation(error: unknown): boolean {\n return hasPostgresCode(error, FOREIGN_KEY_VIOLATION)\n}\n\nexport function isUniqueViolation(error: unknown): boolean {\n return hasPostgresCode(error, UNIQUE_VIOLATION)\n}\n\n/** `%` e `_` digitados na busca são literais, não curingas. */\nexport function likePattern(search: string): string {\n return `%${search.replace(/[\\\\%_]/g, (character) => `\\\\${character}`)}%`\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Fornecedores e o que cada um vende. Tudo por empresa do token: id de outra empresa responde 404.\n */\n\nimport {\n PurchaseItemNotFoundError,\n SupplierDocumentTakenError,\n SupplierInUseError,\n SupplierItemNotFoundError,\n SupplierItemTakenError,\n SupplierNotFoundError,\n type CatalogItem,\n type CreateSupplierData,\n type CreateSupplierItemData,\n type ListSupplierItemsQuery,\n type ListSuppliersQuery,\n type Supplier,\n type SupplierItem,\n type UpdateSupplierData,\n type UpdateSupplierItemData,\n} from '@adatechnology/purchase-contracts'\nimport { and, asc, count, desc, eq, ilike, inArray, or, type SQL } from 'drizzle-orm'\n\nimport { orders, receipts, supplierItems, suppliers, type SupplierItemRow, type SupplierRow } from '../schema/schema'\nimport { assertEnabled, paginated, type PurchaseDependencies } from '../shared/context'\nimport { toSupplier, toSupplierItem } from '../shared/mappers'\nimport { isUniqueViolation, likePattern } from '../shared/postgresErrors'\n\nconst SORT_COLUMNS = { name: suppliers.name, createdAt: suppliers.createdAt, updatedAt: suppliers.updatedAt } as const\n\nfunction defined<T extends Record<string, unknown>>(values: T): Partial<T> {\n return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined)) as Partial<T>\n}\n\nasync function guard<TResult>(work: () => Promise<TResult>, onUnique: () => Error): Promise<TResult> {\n try {\n return await work()\n } catch (error) {\n if (isUniqueViolation(error)) throw onUnique()\n throw error\n }\n}\n\nexport async function findSupplierRow(\n dependencies: PurchaseDependencies,\n companyId: string,\n supplierId: string,\n): Promise<SupplierRow> {\n const [row] = await dependencies.db\n .select()\n .from(suppliers)\n .where(and(eq(suppliers.companyId, companyId), eq(suppliers.id, supplierId)))\n if (!row) throw new SupplierNotFoundError(supplierId)\n return row\n}\n\n/** Itens do catálogo ligado; sem porta, cada `itemRef` é aceito como veio (nome e unidade do próprio cadastro). */\nexport async function loadCatalogItems(\n dependencies: PurchaseDependencies,\n companyId: string,\n itemRefs: readonly string[],\n): Promise<Map<string, CatalogItem> | null> {\n const catalog = dependencies.providers.catalog\n if (!catalog) return null\n const ids = [...new Set(itemRefs)]\n if (ids.length === 0) return new Map()\n const found = await catalog.findItems({ companyId, itemRefs: ids })\n return new Map(found.map((item) => [item.itemRef, item]))\n}\n\nexport async function requireCatalogItems(\n dependencies: PurchaseDependencies,\n companyId: string,\n itemRefs: readonly string[],\n): Promise<Map<string, CatalogItem> | null> {\n const found = await loadCatalogItems(dependencies, companyId, itemRefs)\n if (!found) return null\n for (const itemRef of itemRefs) if (!found.has(itemRef)) throw new PurchaseItemNotFoundError(itemRef)\n return found\n}\n\nexport function createSupplierService(dependencies: PurchaseDependencies) {\n const { db } = dependencies\n\n async function findItemRow(companyId: string, id: string): Promise<SupplierItemRow> {\n const [row] = await db\n .select()\n .from(supplierItems)\n .where(and(eq(supplierItems.companyId, companyId), eq(supplierItems.id, id)))\n if (!row) throw new SupplierItemNotFoundError(id)\n return row\n }\n\n return {\n async create(params: { readonly companyId: string; readonly input: CreateSupplierData }): Promise<Supplier> {\n await assertEnabled(dependencies, params.companyId)\n const now = dependencies.clock.now()\n const { id, ...values } = params.input\n const [row] = await guard(\n () =>\n db\n .insert(suppliers)\n .values({ ...values, ...(id ? { id } : {}), companyId: params.companyId, createdAt: now, updatedAt: now })\n .returning(),\n () => new SupplierDocumentTakenError(),\n )\n return toSupplier(row as SupplierRow)\n },\n\n async get(params: { readonly companyId: string; readonly id: string }): Promise<Supplier> {\n await assertEnabled(dependencies, params.companyId)\n return toSupplier(await findSupplierRow(dependencies, params.companyId, params.id))\n },\n\n /** Para o `SupplierDirectoryPort` do estoque e outras leituras em lote do host. */\n async findMany(params: { readonly companyId: string; readonly ids: readonly string[] }): Promise<Supplier[]> {\n await assertEnabled(dependencies, params.companyId)\n if (params.ids.length === 0) return []\n const rows = await db\n .select()\n .from(suppliers)\n .where(and(eq(suppliers.companyId, params.companyId), inArray(suppliers.id, [...new Set(params.ids)])))\n return rows.map(toSupplier)\n },\n\n async list(params: { readonly companyId: string; readonly query: ListSuppliersQuery }) {\n await assertEnabled(dependencies, params.companyId)\n const { query } = params\n const conditions: SQL[] = [eq(suppliers.companyId, params.companyId)]\n if (query.isActive !== undefined) conditions.push(eq(suppliers.isActive, query.isActive))\n if (query.search) {\n const pattern = likePattern(query.search)\n conditions.push(\n or(\n ilike(suppliers.name, pattern),\n ilike(suppliers.document, pattern),\n ilike(suppliers.contactName, pattern),\n ilike(suppliers.email, pattern),\n ) as SQL,\n )\n }\n const where = and(...conditions) as SQL\n const column = SORT_COLUMNS[query.sort]\n const [rows, totals] = await Promise.all([\n db\n .select()\n .from(suppliers)\n .where(where)\n .orderBy(query.order === 'desc' ? desc(column) : asc(column), asc(suppliers.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n db.select({ total: count() }).from(suppliers).where(where),\n ])\n return paginated({\n rows,\n total: totals[0]?.total ?? 0,\n page: query.page,\n pageSize: query.pageSize,\n map: toSupplier,\n })\n },\n\n async update(params: {\n readonly companyId: string\n readonly id: string\n readonly input: UpdateSupplierData\n }): Promise<Supplier> {\n await assertEnabled(dependencies, params.companyId)\n const [row] = await guard(\n () =>\n db\n .update(suppliers)\n .set({ ...defined(params.input), updatedAt: dependencies.clock.now() })\n .where(and(eq(suppliers.companyId, params.companyId), eq(suppliers.id, params.id)))\n .returning(),\n () => new SupplierDocumentTakenError(),\n )\n if (!row) throw new SupplierNotFoundError(params.id)\n return toSupplier(row)\n },\n\n /** Com pedido ou recebimento, o histórico depende dele: 409 (desative). */\n async remove(params: { readonly companyId: string; readonly id: string }): Promise<void> {\n await assertEnabled(dependencies, params.companyId)\n await findSupplierRow(dependencies, params.companyId, params.id)\n const [order] = await db\n .select({ id: orders.id })\n .from(orders)\n .where(and(eq(orders.companyId, params.companyId), eq(orders.supplierId, params.id)))\n .limit(1)\n const [receipt] = await db\n .select({ id: receipts.id })\n .from(receipts)\n .where(and(eq(receipts.companyId, params.companyId), eq(receipts.supplierId, params.id)))\n .limit(1)\n if (order || receipt) throw new SupplierInUseError(params.id)\n await db.delete(suppliers).where(and(eq(suppliers.companyId, params.companyId), eq(suppliers.id, params.id)))\n },\n\n async createItem(params: {\n readonly companyId: string\n readonly supplierId: string\n readonly input: CreateSupplierItemData\n }): Promise<SupplierItem> {\n await assertEnabled(dependencies, params.companyId)\n await findSupplierRow(dependencies, params.companyId, params.supplierId)\n const { input } = params\n let stockUnit = input.stockUnit\n if (input.itemRef) {\n const catalog = await requireCatalogItems(dependencies, params.companyId, [input.itemRef])\n stockUnit = stockUnit ?? catalog?.get(input.itemRef)?.unit ?? null\n }\n const now = dependencies.clock.now()\n const [row] = await guard(\n () =>\n db\n .insert(supplierItems)\n .values({\n ...input,\n stockUnit,\n companyId: params.companyId,\n supplierId: params.supplierId,\n lastPriceAt: input.lastPrice === null ? null : now,\n createdAt: now,\n updatedAt: now,\n })\n .returning(),\n () => new SupplierItemTakenError(),\n )\n return toSupplierItem(row as SupplierItemRow)\n },\n\n async getItem(params: { readonly companyId: string; readonly id: string }): Promise<SupplierItem> {\n await assertEnabled(dependencies, params.companyId)\n return toSupplierItem(await findItemRow(params.companyId, params.id))\n },\n\n async listItems(params: { readonly companyId: string; readonly query: ListSupplierItemsQuery }) {\n await assertEnabled(dependencies, params.companyId)\n const { query } = params\n const conditions: SQL[] = [eq(supplierItems.companyId, params.companyId)]\n if (query.supplierId) conditions.push(eq(supplierItems.supplierId, query.supplierId))\n if (query.itemRef) conditions.push(eq(supplierItems.itemRef, query.itemRef))\n if (query.isActive !== undefined) conditions.push(eq(supplierItems.isActive, query.isActive))\n if (query.search) {\n const pattern = likePattern(query.search)\n conditions.push(or(ilike(supplierItems.itemName, pattern), ilike(supplierItems.supplierSku, pattern)) as SQL)\n }\n const where = and(...conditions) as SQL\n const [rows, totals] = await Promise.all([\n db\n .select()\n .from(supplierItems)\n .where(where)\n .orderBy(asc(supplierItems.itemName), asc(supplierItems.priority), asc(supplierItems.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n db.select({ total: count() }).from(supplierItems).where(where),\n ])\n return paginated({\n rows,\n total: totals[0]?.total ?? 0,\n page: query.page,\n pageSize: query.pageSize,\n map: toSupplierItem,\n })\n },\n\n async updateItem(params: {\n readonly companyId: string\n readonly id: string\n readonly input: UpdateSupplierItemData\n }): Promise<SupplierItem> {\n await assertEnabled(dependencies, params.companyId)\n const current = await findItemRow(params.companyId, params.id)\n if (params.input.itemRef) await requireCatalogItems(dependencies, params.companyId, [params.input.itemRef])\n const now = dependencies.clock.now()\n const priceChanged = params.input.lastPrice !== undefined && params.input.lastPrice !== current.lastPrice\n const [row] = await guard(\n () =>\n db\n .update(supplierItems)\n .set({ ...defined(params.input), ...(priceChanged ? { lastPriceAt: now } : {}), updatedAt: now })\n .where(and(eq(supplierItems.companyId, params.companyId), eq(supplierItems.id, params.id)))\n .returning(),\n () => new SupplierItemTakenError(),\n )\n return toSupplierItem(row as SupplierItemRow)\n },\n\n async removeItem(params: { readonly companyId: string; readonly id: string }): Promise<void> {\n await assertEnabled(dependencies, params.companyId)\n const rows = await db\n .delete(supplierItems)\n .where(and(eq(supplierItems.companyId, params.companyId), eq(supplierItems.id, params.id)))\n .returning({ id: supplierItems.id })\n if (rows.length === 0) throw new SupplierItemNotFoundError(params.id)\n },\n }\n}\n\nexport type SupplierService = ReturnType<typeof createSupplierService>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Recebimento: confere o que chegou (parcial ou com diferença), grava lote, validade e custo com frete e desconto\n * rateados, e só depois do commit fala com as portas ligadas: entrada no estoque (idempotente por linha) e conta a\n * pagar (idempotente pelo recebimento). Porta que falha deixa a integração `failed`, e `retry` reenvia as mesmas\n * chaves sem duplicar nada.\n */\n\nimport { normalizeDecimal, parseDecimal, rational } from '@adatechnology/recipe-contracts'\nimport {\n add,\n addDays,\n allocateExtras,\n buildInstallments,\n centsOf,\n civilDateIn,\n compare,\n divergenceOf,\n InstallmentsMismatchError,\n INTEGRATION_STATUS,\n InvoiceAlreadyReceivedError,\n landedUnitCost,\n lineTotal,\n money,\n ORDER_ACTION,\n OrderLineNotFoundError,\n PAYMENT_STATUS,\n pendingQuantity,\n quantityText,\n ReceiptNotFoundError,\n statusAfterReceipt,\n subtract,\n SupplierItemNotFoundError,\n toStockQuantity,\n ZERO,\n type Installment,\n type IntegrationStatus,\n type ListReceiptsQuery,\n type OrderStatus,\n type PaymentStatus,\n type Receipt,\n type ReceiptLineData,\n type ReceiveData,\n} from '@adatechnology/purchase-contracts'\nimport { and, asc, count, desc, eq, gte, inArray, lt, or, sql, type SQL } from 'drizzle-orm'\n\nimport {\n orderLines,\n orders,\n receiptLines,\n receiptPayments,\n receipts,\n supplierItems,\n suppliers,\n type NewReceiptLineRow,\n type OrderLineRow,\n type OrderRow,\n type ReceiptLineRow,\n type ReceiptRow,\n} from '../schema/schema'\nimport {\n actorFields,\n assertEnabled,\n paginated,\n runHook,\n type Actor,\n type PurchaseDependencies,\n} from '../shared/context'\nimport { intList, parseInstallments, toReceipt } from '../shared/mappers'\nimport { isUniqueViolation } from '../shared/postgresErrors'\nimport { assertAction, lockOrder } from './orders'\nimport { findSupplierRow, requireCatalogItems } from './suppliers'\nimport type { InsightService } from './insights'\n\nexport const AUTO_ITEM_PRIORITY = 100\n\nexport function receiptLineSourceKey(receiptId: string, lineId: string): string {\n return `purchase-receipt:${receiptId}:${lineId}`\n}\n\nexport function receiptPayableRef(receiptId: string): string {\n return `purchase-receipt:${receiptId}`\n}\n\ntype ResolvedLine = Omit<NewReceiptLineRow, 'receiptId'> & { readonly orderLine: OrderLineRow | null }\n\nfunction aggregateStatus(statuses: readonly string[]): IntegrationStatus {\n if (statuses.length === 0 || statuses.every((status) => status === INTEGRATION_STATUS.SKIPPED))\n return INTEGRATION_STATUS.SKIPPED\n return statuses.some((status) => status === INTEGRATION_STATUS.FAILED)\n ? INTEGRATION_STATUS.FAILED\n : INTEGRATION_STATUS.DONE\n}\n\n/** Fim do dia da validade no fuso da empresa, em ISO (o estoque guarda instante). */\nfunction expiryInstant(date: string | null, timeZone: string): string | null {\n if (!date) return null\n const noon = new Date(`${date}T12:00:00Z`)\n const offsetProbe = new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' })\n .formatToParts(noon)\n .find((part) => part.type === 'timeZoneName')?.value\n const offset = /GMT([+-]\\d{2}):?(\\d{2})?/.exec(offsetProbe ?? '')\n const suffix = offset ? `${offset[1]}:${offset[2] ?? '00'}` : 'Z'\n return new Date(`${date}T23:59:59${suffix}`).toISOString()\n}\n\nexport function createReceiptService(dependencies: PurchaseDependencies, insights: () => InsightService) {\n const { db } = dependencies\n\n async function load(companyId: string, receiptId: string): Promise<Receipt> {\n const [row] = await db\n .select({ receipt: receipts, supplierName: suppliers.name, orderNumber: orders.number })\n .from(receipts)\n .innerJoin(suppliers, eq(suppliers.id, receipts.supplierId))\n .leftJoin(orders, eq(orders.id, receipts.orderId))\n .where(and(eq(receipts.companyId, companyId), eq(receipts.id, receiptId)))\n if (!row) throw new ReceiptNotFoundError(receiptId)\n const lines = await db\n .select()\n .from(receiptLines)\n .where(eq(receiptLines.receiptId, receiptId))\n .orderBy(asc(receiptLines.position))\n return toReceipt({ row: row.receipt, lines, supplierName: row.supplierName, orderNumber: row.orderNumber ?? null })\n }\n\n async function findByIdempotency(companyId: string, key: string): Promise<ReceiptRow | undefined> {\n const [row] = await db\n .select()\n .from(receipts)\n .where(and(eq(receipts.companyId, companyId), eq(receipts.idempotencyKey, key)))\n return row\n }\n\n async function findByInvoiceKey(companyId: string, key: string): Promise<ReceiptRow | undefined> {\n const [row] = await db\n .select()\n .from(receipts)\n .where(and(eq(receipts.companyId, companyId), eq(receipts.invoiceKey, key)))\n return row\n }\n\n /** Entrada no estoque das linhas ainda não confirmadas. */\n async function postStock(actor: Actor, receipt: ReceiptRow): Promise<void> {\n const port = dependencies.providers.stock\n if (!port) return\n const lines = await db\n .select()\n .from(receiptLines)\n .where(and(eq(receiptLines.receiptId, receipt.id), eq(receiptLines.stockStatus, INTEGRATION_STATUS.FAILED)))\n for (const line of lines) {\n let status: IntegrationStatus = INTEGRATION_STATUS.DONE\n try {\n await port.receive({\n ...actorFields(actor),\n sourceKey: receiptLineSourceKey(receipt.id, line.id),\n itemRef: line.itemRef as string,\n quantity: toStockQuantity(line.quantity, line.unitsPerPurchase),\n unit: line.stockUnit as never,\n batchCode: line.batchCode || `NF${receipt.invoiceNumber ?? ''}-${receipt.id.slice(0, 8)}`.slice(0, 100),\n costPerUnit: line.landedUnitCost,\n expiresAt: expiryInstant(line.expiresAt, dependencies.timeZone),\n supplierId: receipt.supplierId,\n reason: `Compra${receipt.invoiceNumber ? ` NF ${receipt.invoiceNumber}` : ''}`.slice(0, 255),\n })\n } catch (error) {\n status = INTEGRATION_STATUS.FAILED\n dependencies.logger?.error('purchase: entrada no estoque falhou', {\n companyId: actor.companyId,\n receiptId: receipt.id,\n lineId: line.id,\n error: error instanceof Error ? error.name : 'unknown',\n })\n }\n await db.update(receiptLines).set({ stockStatus: status }).where(eq(receiptLines.id, line.id))\n }\n const statuses = await db\n .select({ status: receiptLines.stockStatus })\n .from(receiptLines)\n .where(eq(receiptLines.receiptId, receipt.id))\n await db\n .update(receipts)\n .set({ stockStatus: aggregateStatus(statuses.map((row) => row.status)) })\n .where(eq(receipts.id, receipt.id))\n }\n\n async function postPayable(actor: Actor, receipt: ReceiptRow): Promise<void> {\n const port = dependencies.providers.payables\n if (!port || receipt.payableStatus !== INTEGRATION_STATUS.FAILED) return\n const supplier = await findSupplierRow(dependencies, actor.companyId, receipt.supplierId)\n let order: OrderRow | undefined\n if (receipt.orderId) [order] = await db.select().from(orders).where(eq(orders.id, receipt.orderId))\n try {\n const { payableRef } = await port.createPayable({\n ...actorFields(actor),\n sourceRef: receiptPayableRef(receipt.id),\n supplier: { id: supplier.id, name: supplier.name, document: supplier.document },\n description: [\n `Compra ${supplier.name}`,\n order ? `pedido ${order.number}` : null,\n receipt.invoiceNumber ? `NF ${receipt.invoiceNumber}` : null,\n ]\n .filter(Boolean)\n .join(' · ')\n .slice(0, 160),\n total: money(parseDecimal(receipt.total)),\n installments: parseInstallments(receipt.installments),\n invoiceNumber: receipt.invoiceNumber,\n invoiceKey: receipt.invoiceKey,\n receiptId: receipt.id,\n orderId: receipt.orderId,\n })\n await db\n .update(receipts)\n .set({ payableStatus: INTEGRATION_STATUS.DONE, payableRef, paymentStatus: PAYMENT_STATUS.OPEN })\n .where(eq(receipts.id, receipt.id))\n } catch (error) {\n dependencies.logger?.error('purchase: conta a pagar falhou', {\n companyId: actor.companyId,\n receiptId: receipt.id,\n error: error instanceof Error ? error.name : 'unknown',\n })\n }\n }\n\n async function resolveLines(params: {\n readonly companyId: string\n readonly supplierId: string\n readonly lines: readonly ReceiptLineData[]\n readonly orderLines: readonly OrderLineRow[]\n }): Promise<ResolvedLine[]> {\n const byOrderLine = new Map(params.orderLines.map((line) => [line.id, line]))\n const itemIds = [\n ...new Set(\n params.lines.flatMap((line) => {\n const fromOrder = line.orderLineId ? byOrderLine.get(line.orderLineId)?.supplierItemId : null\n return [line.supplierItemId, fromOrder].filter((id): id is string => Boolean(id))\n }),\n ),\n ]\n const items =\n itemIds.length === 0\n ? []\n : await db\n .select()\n .from(supplierItems)\n .where(\n and(\n eq(supplierItems.companyId, params.companyId),\n eq(supplierItems.supplierId, params.supplierId),\n inArray(supplierItems.id, itemIds),\n ),\n )\n const itemsById = new Map(items.map((item) => [item.id, item]))\n // Duas linhas da nota para a mesma linha do pedido somam contra o mesmo pendente.\n const consumed = new Map<string, string>()\n const priceTolerance = BigInt(dependencies.config.priceToleranceCents ?? 0)\n const resolved = params.lines.map((line, position) => {\n const orderLine = line.orderLineId ? byOrderLine.get(line.orderLineId) : undefined\n if (line.orderLineId && !orderLine) throw new OrderLineNotFoundError(line.orderLineId)\n const supplierItemId = line.supplierItemId ?? orderLine?.supplierItemId ?? null\n const item = supplierItemId ? itemsById.get(supplierItemId) : undefined\n if (line.supplierItemId && !item) throw new SupplierItemNotFoundError(line.supplierItemId)\n const quantity = normalizeDecimal(line.quantity)\n const unitPrice = normalizeDecimal(line.unitPrice ?? orderLine?.unitPrice ?? item?.lastPrice ?? '0')\n let divergence: ResolvedLine['divergence'] = 'none'\n if (orderLine) {\n const already = consumed.get(orderLine.id) ?? '0'\n const pending = quantityText(subtract(parseDecimal(pendingQuantity(orderLine)), parseDecimal(already)))\n consumed.set(orderLine.id, quantityText(add(parseDecimal(already), parseDecimal(quantity))))\n divergence = divergenceOf({\n pendingQuantity: compare(parseDecimal(pending), ZERO) < 0 ? '0' : pending,\n receivedQuantity: quantity,\n orderedPrice: orderLine.unitPrice,\n receivedPrice: unitPrice,\n priceToleranceCents: priceTolerance,\n })\n }\n return {\n companyId: params.companyId,\n position,\n orderLineId: orderLine?.id ?? null,\n supplierItemId: item?.id ?? null,\n itemRef: line.itemRef ?? orderLine?.itemRef ?? item?.itemRef ?? null,\n itemName: line.itemName ?? orderLine?.itemName ?? item?.itemName ?? 'Item',\n supplierSku: line.supplierSku ?? orderLine?.supplierSku ?? item?.supplierSku ?? null,\n purchaseUnit: line.purchaseUnit ?? orderLine?.purchaseUnit ?? item?.purchaseUnit ?? 'un',\n unitsPerPurchase: normalizeDecimal(\n line.unitsPerPurchase ?? orderLine?.unitsPerPurchase ?? item?.unitsPerPurchase ?? '1',\n ),\n stockUnit: line.stockUnit ?? orderLine?.stockUnit ?? item?.stockUnit ?? null,\n quantity,\n unitPrice,\n lineTotal: money(lineTotal(quantity, unitPrice)),\n batchCode: line.batchCode || null,\n expiresAt: line.expiresAt ?? null,\n divergence,\n divergenceReason: line.divergenceReason || null,\n orderLine: orderLine ?? null,\n }\n })\n const refs = resolved.flatMap((line) => (line.itemRef ? [line.itemRef] : []))\n const catalog = await requireCatalogItems(dependencies, params.companyId, refs)\n if (catalog)\n for (const line of resolved)\n if (line.itemRef && !line.stockUnit) line.stockUnit = catalog.get(line.itemRef)?.unit ?? null\n return resolved\n }\n\n function chooseInstallments(params: {\n readonly input: ReceiveData\n readonly total: string\n readonly termDays: readonly number[]\n readonly baseDate: string\n }): Installment[] {\n if (params.input.installments) {\n const installments = [...params.input.installments]\n .sort((left, right) => left.dueDate.localeCompare(right.dueDate))\n .map((item, index) => ({ number: index + 1, dueDate: item.dueDate, amount: money(parseDecimal(item.amount)) }))\n const sum = installments.reduce((acc, item) => acc + centsOf(parseDecimal(item.amount)), 0n)\n if (sum !== centsOf(parseDecimal(params.total)))\n throw new InstallmentsMismatchError({ total: params.total, installments: money(rational(sum, 100n)) })\n return installments\n }\n return buildInstallments({ total: params.total, termDays: params.termDays, baseDate: params.baseDate })\n }\n\n const service = {\n load,\n\n async receive(params: Actor & { readonly orderId?: string; readonly input: ReceiveData }): Promise<Receipt> {\n await assertEnabled(dependencies, params.companyId)\n const { input } = params\n if (input.idempotencyKey) {\n const existing = await findByIdempotency(params.companyId, input.idempotencyKey)\n if (existing) return load(params.companyId, existing.id)\n }\n if (input.invoiceKey) {\n const existing = await findByInvoiceKey(params.companyId, input.invoiceKey)\n if (existing) throw new InvoiceAlreadyReceivedError(existing.id)\n }\n const now = dependencies.clock.now()\n const receivedAt = input.receivedAt ? new Date(input.receivedAt) : now\n const hasStockPort = dependencies.providers.stock !== undefined\n const hasPayables = dependencies.providers.payables !== undefined\n let statusChange: { order: OrderRow; from: OrderStatus; to: OrderStatus } | null = null\n let receiptRow: ReceiptRow\n try {\n receiptRow = await db.transaction(async (tx) => {\n let order: OrderRow | null = null\n let lockedLines: OrderLineRow[] = []\n let supplierId = input.supplierId\n if (params.orderId) {\n order = await lockOrder(tx, params.companyId, params.orderId)\n assertAction(order, ORDER_ACTION.RECEIVE)\n supplierId = order.supplierId\n lockedLines = await tx.select().from(orderLines).where(eq(orderLines.orderId, order.id)).for('update')\n }\n if (!supplierId) throw new OrderLineNotFoundError('supplierId')\n const supplier = await findSupplierRow(dependencies, params.companyId, supplierId)\n const lines = await resolveLines({\n companyId: params.companyId,\n supplierId: supplier.id,\n lines: input.lines,\n orderLines: lockedLines,\n })\n const shares = allocateExtras({\n lineTotals: lines.map((line) => line.lineTotal as string),\n freight: input.freight,\n discount: input.discount,\n })\n const subtotal = lines.reduce((acc, line) => add(acc, parseDecimal(line.lineTotal as string)), ZERO)\n const totalValue = subtract(add(subtotal, parseDecimal(input.freight)), parseDecimal(input.discount))\n const total = money(compare(totalValue, ZERO) < 0 ? ZERO : totalValue)\n const baseDate = civilDateIn(receivedAt, dependencies.timeZone)\n const installments = chooseInstallments({\n input,\n total,\n termDays: intList(order?.paymentTermDays ?? supplier.paymentTermDays),\n baseDate,\n })\n const [inserted] = await tx\n .insert(receipts)\n .values({\n companyId: params.companyId,\n orderId: order?.id ?? null,\n supplierId: supplier.id,\n receivedAt,\n invoiceNumber: input.invoiceNumber || null,\n invoiceKey: input.invoiceKey || null,\n invoiceIssuedAt: input.invoiceIssuedAt ? new Date(input.invoiceIssuedAt) : null,\n subtotal: money(subtotal),\n freight: input.freight,\n discount: input.discount,\n total,\n notes: input.notes,\n actorId: params.actorId ?? null,\n idempotencyKey: input.idempotencyKey ?? null,\n installments: JSON.stringify(installments),\n // `failed` até a porta confirmar: um crash entre o commit e a entrada deixa o reprocessamento visível.\n stockStatus: hasStockPort ? INTEGRATION_STATUS.FAILED : INTEGRATION_STATUS.SKIPPED,\n payableStatus: hasPayables ? INTEGRATION_STATUS.FAILED : INTEGRATION_STATUS.SKIPPED,\n paymentStatus: PAYMENT_STATUS.NONE,\n createdAt: now,\n })\n .returning()\n const receipt = inserted as ReceiptRow\n await tx.insert(receiptLines).values(\n lines.map((resolved, index) => {\n const { orderLine, ...line } = resolved\n void orderLine\n const allocated = shares[index] ?? '0.00'\n const stockable = hasStockPort && line.itemRef !== null && line.stockUnit !== null\n return {\n ...line,\n receiptId: receipt.id,\n allocated,\n landedUnitCost: landedUnitCost({\n lineTotal: line.lineTotal as string,\n allocated,\n quantity: line.quantity,\n unitsPerPurchase: line.unitsPerPurchase as string,\n }),\n stockStatus: stockable ? INTEGRATION_STATUS.FAILED : INTEGRATION_STATUS.SKIPPED,\n }\n }),\n )\n if (order) {\n const receivedByLine = new Map<string, string>()\n for (const line of lines) {\n if (!line.orderLine) continue\n const sum = add(parseDecimal(receivedByLine.get(line.orderLine.id) ?? '0'), parseDecimal(line.quantity))\n receivedByLine.set(line.orderLine.id, quantityText(sum))\n }\n const updated = lockedLines.map((line) => {\n const extra = receivedByLine.get(line.id)\n return extra\n ? {\n ...line,\n receivedQuantity: quantityText(add(parseDecimal(line.receivedQuantity), parseDecimal(extra))),\n }\n : line\n })\n for (const line of updated)\n if (receivedByLine.has(line.id))\n await tx\n .update(orderLines)\n .set({ receivedQuantity: line.receivedQuantity })\n .where(eq(orderLines.id, line.id))\n const next = statusAfterReceipt(updated)\n await tx.update(orders).set({ status: next, updatedAt: now }).where(eq(orders.id, order.id))\n statusChange = { order, from: order.status as OrderStatus, to: next }\n }\n // Último preço por item do fornecedor; linha com item do catálogo sem cadastro ganha o cadastro.\n for (const line of lines) {\n if (line.supplierItemId) {\n await tx\n .update(supplierItems)\n .set({ lastPrice: line.unitPrice, lastPriceAt: receivedAt, updatedAt: now })\n .where(eq(supplierItems.id, line.supplierItemId))\n } else if (line.itemRef) {\n await tx\n .insert(supplierItems)\n .values({\n companyId: params.companyId,\n supplierId: supplier.id,\n itemRef: line.itemRef,\n itemName: line.itemName,\n supplierSku: null,\n purchaseUnit: line.purchaseUnit as string,\n unitsPerPurchase: line.unitsPerPurchase as string,\n stockUnit: line.stockUnit ?? null,\n lastPrice: line.unitPrice,\n lastPriceAt: receivedAt,\n // Cadastro criado sozinho perde para o feito à mão na escolha do preferido.\n priority: AUTO_ITEM_PRIORITY,\n createdAt: now,\n updatedAt: now,\n })\n .onConflictDoUpdate({\n target: [supplierItems.companyId, supplierItems.supplierId, supplierItems.itemRef],\n targetWhere: sql`\"item_ref\" is not null`,\n set: { lastPrice: line.unitPrice, lastPriceAt: receivedAt, updatedAt: now },\n })\n }\n }\n return receipt\n })\n } catch (error) {\n if (isUniqueViolation(error)) {\n if (input.idempotencyKey) {\n const existing = await findByIdempotency(params.companyId, input.idempotencyKey)\n if (existing) return load(params.companyId, existing.id)\n }\n if (input.invoiceKey) {\n const existing = await findByInvoiceKey(params.companyId, input.invoiceKey)\n if (existing) throw new InvoiceAlreadyReceivedError(existing.id)\n }\n }\n throw error\n }\n await postStock(params, receiptRow)\n await postPayable(params, receiptRow)\n const change = statusChange as { order: OrderRow; from: OrderStatus; to: OrderStatus } | null\n if (change && change.from !== change.to)\n await runHook(\n dependencies,\n 'onOrderStatusChanged',\n { companyId: params.companyId, orderId: change.order.id },\n () =>\n dependencies.hooks.onOrderStatusChanged?.({\n ...actorFields(params),\n orderId: change.order.id,\n number: change.order.number,\n from: change.from,\n to: change.to,\n }),\n )\n const receipt = await load(params.companyId, receiptRow.id)\n await service.notifyPosted(params, receipt)\n return receipt\n },\n\n async notifyPosted(actor: Actor, receipt: Receipt): Promise<void> {\n if (!dependencies.hooks.onReceiptPosted) return\n const refs = receipt.lines.flatMap((line) => (line.itemRef ? [line.itemRef] : []))\n const costs = refs.length ? await insights().itemCosts({ companyId: actor.companyId, itemRefs: refs }) : []\n const averages = new Map(costs.map((cost) => [cost.itemRef, cost.averageCost]))\n await runHook(dependencies, 'onReceiptPosted', { companyId: actor.companyId, receiptId: receipt.id }, () =>\n dependencies.hooks.onReceiptPosted?.({\n ...actorFields(actor),\n receiptId: receipt.id,\n orderId: receipt.orderId,\n supplierId: receipt.supplierId,\n total: receipt.total,\n lines: receipt.lines.map((line) => ({\n itemRef: line.itemRef,\n itemName: line.itemName,\n stockUnit: line.stockUnit,\n stockQuantity: toStockQuantity(line.quantity, line.unitsPerPurchase),\n landedUnitCost: line.landedUnitCost,\n averageCost: line.itemRef ? (averages.get(line.itemRef) ?? null) : null,\n })),\n }),\n )\n },\n\n /** Reenvia ao estoque e às contas o que falhou (as mesmas chaves: nada duplica). */\n async retry(params: Actor & { readonly id: string }): Promise<Receipt> {\n await assertEnabled(dependencies, params.companyId)\n const [row] = await db\n .select()\n .from(receipts)\n .where(and(eq(receipts.companyId, params.companyId), eq(receipts.id, params.id)))\n if (!row) throw new ReceiptNotFoundError(params.id)\n await postStock(params, row)\n await postPayable(params, row)\n return load(params.companyId, params.id)\n },\n\n async get(params: { readonly companyId: string; readonly id: string }): Promise<Receipt> {\n await assertEnabled(dependencies, params.companyId)\n return load(params.companyId, params.id)\n },\n\n async list(params: { readonly companyId: string; readonly query: ListReceiptsQuery }) {\n await assertEnabled(dependencies, params.companyId)\n const { query } = params\n const conditions: SQL[] = [eq(receipts.companyId, params.companyId)]\n if (query.supplierId) conditions.push(eq(receipts.supplierId, query.supplierId))\n if (query.orderId) conditions.push(eq(receipts.orderId, query.orderId))\n if (query.from) conditions.push(gte(receipts.receivedAt, new Date(`${query.from}T00:00:00Z`)))\n if (query.to) conditions.push(lt(receipts.receivedAt, new Date(`${addDays(query.to, 1)}T00:00:00Z`)))\n if (query.failed === true)\n conditions.push(or(eq(receipts.stockStatus, 'failed'), eq(receipts.payableStatus, 'failed')) as SQL)\n const where = and(...conditions) as SQL\n const [rows, totals] = await Promise.all([\n db\n .select({ receipt: receipts, supplierName: suppliers.name, orderNumber: orders.number })\n .from(receipts)\n .innerJoin(suppliers, eq(suppliers.id, receipts.supplierId))\n .leftJoin(orders, eq(orders.id, receipts.orderId))\n .where(where)\n .orderBy(desc(receipts.receivedAt), desc(receipts.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n db.select({ total: count() }).from(receipts).where(where),\n ])\n const ids = rows.map((row) => row.receipt.id)\n const lines: ReceiptLineRow[] = ids.length\n ? await db\n .select()\n .from(receiptLines)\n .where(inArray(receiptLines.receiptId, ids))\n .orderBy(asc(receiptLines.position))\n : []\n const byReceipt = new Map<string, ReceiptLineRow[]>()\n for (const line of lines) byReceipt.set(line.receiptId, [...(byReceipt.get(line.receiptId) ?? []), line])\n return paginated({\n rows,\n total: totals[0]?.total ?? 0,\n page: query.page,\n pageSize: query.pageSize,\n map: (row) =>\n toReceipt({\n row: row.receipt,\n lines: byReceipt.get(row.receipt.id) ?? [],\n supplierName: row.supplierName,\n orderNumber: row.orderNumber ?? null,\n }),\n })\n },\n\n /**\n * Pagamento de uma parcela, vindo do financeiro (gancho `onOccurrenceSettled` do `expense-module`). Busca pelo\n * recebimento ou pela `payableRef`. Idempotente: a mesma parcela paga de novo só atualiza o valor.\n */\n async recordPayment(params: {\n readonly companyId: string\n readonly receiptId?: string\n readonly payableRef?: string\n readonly installmentNumber: number\n readonly paidAmount: string | null\n readonly paidAt: string | null\n }): Promise<Receipt> {\n await assertEnabled(dependencies, params.companyId)\n const condition = params.receiptId\n ? eq(receipts.id, params.receiptId)\n : eq(receipts.payableRef, params.payableRef ?? '')\n const [row] = await db\n .select()\n .from(receipts)\n .where(and(eq(receipts.companyId, params.companyId), condition))\n if (!row) throw new ReceiptNotFoundError(params.receiptId ?? params.payableRef ?? '')\n if (params.paidAmount === null || params.paidAt === null) {\n await db\n .delete(receiptPayments)\n .where(\n and(eq(receiptPayments.receiptId, row.id), eq(receiptPayments.installmentNumber, params.installmentNumber)),\n )\n } else {\n await db\n .insert(receiptPayments)\n .values({\n companyId: params.companyId,\n receiptId: row.id,\n installmentNumber: params.installmentNumber,\n paidAmount: params.paidAmount,\n paidAt: params.paidAt,\n })\n .onConflictDoUpdate({\n target: [receiptPayments.receiptId, receiptPayments.installmentNumber],\n set: { paidAmount: params.paidAmount, paidAt: params.paidAt },\n })\n }\n const payments = await db.select().from(receiptPayments).where(eq(receiptPayments.receiptId, row.id))\n const paid = payments.reduce((acc, payment) => acc + centsOf(parseDecimal(payment.paidAmount)), 0n)\n const total = centsOf(parseDecimal(row.total))\n const status: PaymentStatus =\n paid === 0n ? PAYMENT_STATUS.OPEN : paid >= total ? PAYMENT_STATUS.PAID : PAYMENT_STATUS.PARTIAL\n await db.update(receipts).set({ paymentStatus: status }).where(eq(receipts.id, row.id))\n return load(params.companyId, row.id)\n },\n }\n return service\n}\n\nexport type ReceiptService = ReturnType<typeof createReceiptService>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Gasto por fornecedor, item ou mês (linha + rateio = o que saiu do caixa) e desempenho do fornecedor (entrega no\n * prazo e divergência). Datas civis no fuso da configuração.\n */\n\nimport {\n buildCsv,\n buildXlsx,\n CSV_BOM,\n CSV_CONTENT_TYPE,\n formatDecimal,\n parseDecimal,\n XLSX_CONTENT_TYPE,\n} from '@adatechnology/recipe-contracts'\nimport {\n add,\n addDays,\n centsOf,\n civilDateIn,\n money,\n PURCHASE_LIMITS,\n REPORT_GROUP,\n ReportRangeTooLongError,\n ZERO,\n type Rational,\n type SpendReport,\n type SpendReportQuery,\n type SupplierPerformanceQuery,\n type SupplierPerformanceReport,\n} from '@adatechnology/purchase-contracts'\nimport { and, eq, gte, inArray, lt, type SQL } from 'drizzle-orm'\n\nimport { orders, receiptLines, receipts, suppliers } from '../schema/schema'\nimport { assertEnabled, type PurchaseDependencies } from '../shared/context'\n\nfunction daysBetween(from: string, to: string): number {\n return Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 86_400_000)\n}\n\nfunction assertRange(from: string, to: string): void {\n if (daysBetween(from, to) > PURCHASE_LIMITS.REPORT_DAYS)\n throw new ReportRangeTooLongError(PURCHASE_LIMITS.REPORT_DAYS)\n}\n\n/** Margem de um dia nas pontas (fuso) e o filtro fino pela data civil no módulo. */\nfunction instantRange(from: string, to: string): { start: Date; end: Date } {\n return { start: new Date(`${addDays(from, -1)}T00:00:00Z`), end: new Date(`${addDays(to, 2)}T00:00:00Z`) }\n}\n\nexport function createReportService(dependencies: PurchaseDependencies) {\n const { db } = dependencies\n\n async function spend(params: { readonly companyId: string; readonly query: SpendReportQuery }): Promise<SpendReport> {\n await assertEnabled(dependencies, params.companyId)\n const { query } = params\n assertRange(query.from, query.to)\n const { start, end } = instantRange(query.from, query.to)\n const conditions: SQL[] = [\n eq(receipts.companyId, params.companyId),\n gte(receipts.receivedAt, start),\n lt(receipts.receivedAt, end),\n ]\n if (query.supplierId) conditions.push(eq(receipts.supplierId, query.supplierId))\n if (query.itemRef) conditions.push(eq(receiptLines.itemRef, query.itemRef))\n const rows = await db\n .select({\n receiptId: receipts.id,\n receivedAt: receipts.receivedAt,\n supplierId: receipts.supplierId,\n supplierName: suppliers.name,\n itemRef: receiptLines.itemRef,\n itemName: receiptLines.itemName,\n lineTotal: receiptLines.lineTotal,\n allocated: receiptLines.allocated,\n })\n .from(receiptLines)\n .innerJoin(receipts, eq(receipts.id, receiptLines.receiptId))\n .innerJoin(suppliers, eq(suppliers.id, receipts.supplierId))\n .where(and(...conditions))\n const groups = new Map<string, { label: string; receipts: Set<string>; lines: number; total: Rational }>()\n const allReceipts = new Set<string>()\n let grand: Rational = ZERO\n for (const row of rows) {\n const day = civilDateIn(row.receivedAt, dependencies.timeZone)\n if (day < query.from || day > query.to) continue\n const value = add(parseDecimal(row.lineTotal), parseDecimal(row.allocated))\n const key =\n query.groupBy === REPORT_GROUP.SUPPLIER\n ? row.supplierId\n : query.groupBy === REPORT_GROUP.MONTH\n ? day.slice(0, 7)\n : (row.itemRef ?? `name:${row.itemName.toLowerCase()}`)\n const label =\n query.groupBy === REPORT_GROUP.SUPPLIER\n ? row.supplierName\n : query.groupBy === REPORT_GROUP.MONTH\n ? day.slice(0, 7)\n : row.itemName\n const group = groups.get(key) ?? { label, receipts: new Set<string>(), lines: 0, total: ZERO }\n group.receipts.add(row.receiptId)\n group.lines += 1\n group.total = add(group.total, value)\n groups.set(key, group)\n allReceipts.add(row.receiptId)\n grand = add(grand, value)\n }\n const sorted = [...groups.entries()].sort((left, right) => {\n if (query.groupBy === REPORT_GROUP.MONTH) return left[0].localeCompare(right[0])\n const difference = centsOf(right[1].total) - centsOf(left[1].total)\n return difference > 0n ? 1 : difference < 0n ? -1 : left[1].label.localeCompare(right[1].label, 'pt-BR')\n })\n return {\n from: query.from,\n to: query.to,\n groupBy: query.groupBy,\n rows: sorted.map(([key, group]) => ({\n key,\n label: group.label,\n receiptCount: group.receipts.size,\n lineCount: group.lines,\n total: money(group.total),\n })),\n total: money(grand),\n receiptCount: allReceipts.size,\n }\n }\n\n return {\n spend,\n\n async exportSpend(params: {\n readonly companyId: string\n readonly query: SpendReportQuery\n readonly format: 'csv' | 'xlsx'\n }): Promise<{ readonly contentType: string; readonly fileName: string; readonly body: Uint8Array | string }> {\n const report = await spend(params)\n const table = {\n header: ['Grupo', 'Recebimentos', 'Linhas', 'Total (R$)'],\n rows: [\n ...report.rows.map((row) => [row.label, row.receiptCount, row.lineCount, row.total]),\n ['Total', report.receiptCount, null, report.total],\n ],\n }\n const fileName = `compras-${report.groupBy}-${report.from}-${report.to}`\n if (params.format === 'xlsx')\n return {\n contentType: XLSX_CONTENT_TYPE,\n fileName: `${fileName}.xlsx`,\n body: buildXlsx({ table, sheetName: 'Compras' }),\n }\n return { contentType: CSV_CONTENT_TYPE, fileName: `${fileName}.csv`, body: CSV_BOM + buildCsv(table) }\n },\n\n async supplierPerformance(params: {\n readonly companyId: string\n readonly query: SupplierPerformanceQuery\n }): Promise<SupplierPerformanceReport> {\n await assertEnabled(dependencies, params.companyId)\n const { query } = params\n assertRange(query.from, query.to)\n const { start, end } = instantRange(query.from, query.to)\n const receiptRows = await db\n .select({ receipt: receipts, supplierName: suppliers.name })\n .from(receipts)\n .innerJoin(suppliers, eq(suppliers.id, receipts.supplierId))\n .where(\n and(eq(receipts.companyId, params.companyId), gte(receipts.receivedAt, start), lt(receipts.receivedAt, end)),\n )\n const inRange = receiptRows.filter((row) => {\n const day = civilDateIn(row.receipt.receivedAt, dependencies.timeZone)\n return day >= query.from && day <= query.to\n })\n const receiptIds = inRange.map((row) => row.receipt.id)\n const orderIds = [...new Set(inRange.flatMap((row) => (row.receipt.orderId ? [row.receipt.orderId] : [])))]\n const [lines, orderRows, firstReceipts] = await Promise.all([\n receiptIds.length\n ? db\n .select({ receiptId: receiptLines.receiptId, divergence: receiptLines.divergence })\n .from(receiptLines)\n .where(inArray(receiptLines.receiptId, receiptIds))\n : Promise.resolve([]),\n orderIds.length ? db.select().from(orders).where(inArray(orders.id, orderIds)) : Promise.resolve([]),\n orderIds.length\n ? db\n .select({ orderId: receipts.orderId, receivedAt: receipts.receivedAt })\n .from(receipts)\n .where(inArray(receipts.orderId, orderIds))\n : Promise.resolve([]),\n ])\n const firstByOrder = new Map<string, Date>()\n for (const row of firstReceipts) {\n if (!row.orderId) continue\n const current = firstByOrder.get(row.orderId)\n if (!current || row.receivedAt < current) firstByOrder.set(row.orderId, row.receivedAt)\n }\n const supplierOf = new Map(inRange.map((row) => [row.receipt.id, row.receipt.supplierId]))\n type Acc = {\n name: string\n orders: Set<string>\n onTime: number\n late: number\n lateDays: number\n divergent: number\n lines: number\n total: Rational\n }\n const bySupplier = new Map<string, Acc>()\n const accOf = (supplierId: string, name: string): Acc => {\n const current = bySupplier.get(supplierId) ?? {\n name,\n orders: new Set<string>(),\n onTime: 0,\n late: 0,\n lateDays: 0,\n divergent: 0,\n lines: 0,\n total: ZERO,\n }\n bySupplier.set(supplierId, current)\n return current\n }\n for (const row of inRange) {\n const acc = accOf(row.receipt.supplierId, row.supplierName)\n acc.total = add(acc.total, parseDecimal(row.receipt.total))\n }\n for (const line of lines) {\n const supplierId = supplierOf.get(line.receiptId)\n if (!supplierId) continue\n const acc = bySupplier.get(supplierId)\n if (!acc) continue\n acc.lines += 1\n if (line.divergence !== 'none') acc.divergent += 1\n }\n for (const order of orderRows) {\n const acc = bySupplier.get(order.supplierId)\n if (!acc || acc.orders.has(order.id)) continue\n acc.orders.add(order.id)\n const first = firstByOrder.get(order.id)\n if (!order.expectedAt || !first) continue\n const arrived = civilDateIn(first, dependencies.timeZone)\n const late = daysBetween(order.expectedAt, arrived)\n if (late > 0) {\n acc.late += 1\n acc.lateDays += late\n } else acc.onTime += 1\n }\n return {\n from: query.from,\n to: query.to,\n rows: [...bySupplier.entries()]\n .map(([supplierId, acc]) => ({\n supplierId,\n supplierName: acc.name,\n orderCount: acc.orders.size,\n onTimeCount: acc.onTime,\n lateCount: acc.late,\n averageDaysLate: acc.late\n ? formatDecimal({ numerator: BigInt(acc.lateDays), denominator: BigInt(acc.late) }, 1)\n : null,\n divergentLineCount: acc.divergent,\n receivedLineCount: acc.lines,\n total: money(acc.total),\n }))\n .sort((left, right) => left.supplierName.localeCompare(right.supplierName, 'pt-BR')),\n }\n },\n }\n}\n\nexport type ReportService = ReturnType<typeof createReportService>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Rotas do painel (`admin`: leitura, escrita e aprovação) e de serviço (leituras em lote e pagamento vindo do\n * financeiro). `companyId` sai sempre do token, nunca do corpo.\n */\n\nimport {\n createOrderSchema,\n createSupplierItemSchema,\n createSupplierSchema,\n DEFAULT_PURCHASE_SCOPES,\n exportFormatSchema,\n itemRefsLookupSchema,\n listOrdersQuerySchema,\n listReceiptsQuerySchema,\n listSupplierItemsQuerySchema,\n listSuppliersQuerySchema,\n nfePreviewSchema,\n optionalReasonSchema,\n OrderNotFoundError,\n ordersFromSuggestionSchema,\n PurchaseUnauthenticatedError,\n priceHistoryQuerySchema,\n reasonSchema,\n ReceiptNotFoundError,\n receiveSchema,\n sendOrderSchema,\n spendReportQuerySchema,\n suggestionQuerySchema,\n SupplierItemNotFoundError,\n supplierLookupSchema,\n SupplierNotFoundError,\n supplierPerformanceQuerySchema,\n updateOrderSchema,\n updateSupplierItemSchema,\n updateSupplierSchema,\n type CreateOrderData,\n type CreateSupplierData,\n type CreateSupplierItemData,\n type ExportFormatQuery,\n type ItemRefsLookupData,\n type ListOrdersQuery,\n type ListReceiptsQuery,\n type ListSupplierItemsQuery,\n type ListSuppliersQuery,\n type NfePreviewData,\n type OptionalReasonData,\n type OrdersFromSuggestionData,\n type PriceHistoryQuery,\n type ReasonData,\n type ReceiveData,\n type SendOrderData,\n type SpendReportQuery,\n type SuggestionQuery,\n type SupplierLookupData,\n type SupplierPerformanceQuery,\n type UpdateOrderData,\n type UpdateSupplierData,\n type UpdateSupplierItemData,\n} from '@adatechnology/purchase-contracts'\nimport type { HttpResult, ModuleRoute, ModuleRouteTable, RequestContext } from '@adatechnology/module-http'\nimport { z } from 'zod'\n\nimport type { PurchaseModule } from '../PurchaseModule'\n\nexport type CreatePurchaseRoutesParams = { readonly module: PurchaseModule }\n\ntype RouteAccess = Pick<ModuleRoute, 'scope' | 'requiredScopes'>\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nfunction companyOf(context: RequestContext): string {\n if (!context.auth?.companyId) throw new PurchaseUnauthenticatedError()\n return context.auth.companyId\n}\n\nfunction actorOf(context: RequestContext): { companyId: string; actorId?: string } {\n const companyId = companyOf(context)\n return { companyId, ...(context.auth?.userId ? { actorId: context.auth.userId } : {}) }\n}\n\n/** Id de caminho inválido responde o mesmo 404 de \"não existe\". */\nfunction uuidParam(context: RequestContext, name: string, notFound: (value: string) => Error): string {\n const value = context.params[name] ?? ''\n if (!UUID_PATTERN.test(value)) throw notFound(value)\n return value\n}\n\nconst json = (status: number, data: unknown): HttpResult => ({ kind: 'json', status, body: { data } })\nconst empty = (): HttpResult => ({ kind: 'empty', status: 204 })\nconst supplierId = (context: RequestContext) => uuidParam(context, 'id', (value) => new SupplierNotFoundError(value))\nconst supplierItemId = (context: RequestContext) =>\n uuidParam(context, 'id', (value) => new SupplierItemNotFoundError(value))\nconst orderId = (context: RequestContext) => uuidParam(context, 'id', (value) => new OrderNotFoundError(value))\nconst receiptId = (context: RequestContext) => uuidParam(context, 'id', (value) => new ReceiptNotFoundError(value))\n\nconst messageQuerySchema = z.object({\n withPrices: z\n .enum(['true', 'false'])\n .transform((value) => value === 'true')\n .optional(),\n})\n\nconst exportSpendQuerySchema = z.intersection(spendReportQuerySchema, exportFormatSchema)\n\nconst paymentSchema = z\n .object({\n receiptId: z.string().uuid().optional(),\n payableRef: z.string().trim().min(1).max(200).optional(),\n installmentNumber: z.number().int().min(1).max(100),\n /** `null` desfaz o pagamento (reaberto no financeiro). */\n paidAmount: z\n .string()\n .regex(/^\\d{1,12}(\\.\\d{1,2})?$/)\n .nullable(),\n paidAt: z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/)\n .nullable(),\n })\n .refine((value) => value.receiptId !== undefined || value.payableRef !== undefined, {\n message: 'Informe receiptId ou payableRef.',\n })\n\nfunction supplierRoutes(module: PurchaseModule, read: RouteAccess, write: RouteAccess): ModuleRoute[] {\n const { suppliers } = module.useCases\n return [\n {\n ...read,\n method: 'GET',\n path: '/suppliers',\n querySchema: listSuppliersQuerySchema,\n operationId: 'purchaseListSuppliers',\n summary: 'Fornecedores (busca, ativos, ordenação, paginação)',\n handler: async (context) =>\n json(\n 200,\n await suppliers.list({\n companyId: companyOf(context),\n query: context.query as unknown as ListSuppliersQuery,\n }),\n ),\n },\n {\n ...write,\n method: 'POST',\n path: '/suppliers',\n bodySchema: createSupplierSchema,\n operationId: 'purchaseCreateSupplier',\n summary: 'Cadastra fornecedor (condição de pagamento, prazo, pedido mínimo, dias de entrega)',\n handler: async (context) =>\n json(201, await suppliers.create({ companyId: companyOf(context), input: context.body as CreateSupplierData })),\n },\n {\n ...read,\n method: 'GET',\n path: '/suppliers/:id',\n operationId: 'purchaseGetSupplier',\n summary: 'Fornecedor',\n handler: async (context) =>\n json(200, await suppliers.get({ companyId: companyOf(context), id: supplierId(context) })),\n },\n {\n ...write,\n method: 'PATCH',\n path: '/suppliers/:id',\n bodySchema: updateSupplierSchema,\n operationId: 'purchaseUpdateSupplier',\n summary: 'Altera fornecedor (só os campos enviados; `isActive: false` desativa)',\n handler: async (context) =>\n json(\n 200,\n await suppliers.update({\n companyId: companyOf(context),\n id: supplierId(context),\n input: context.body as UpdateSupplierData,\n }),\n ),\n },\n {\n ...write,\n method: 'DELETE',\n path: '/suppliers/:id',\n operationId: 'purchaseDeleteSupplier',\n summary: 'Exclui fornecedor sem pedido nem recebimento (com histórico: 409, desative)',\n handler: async (context) => {\n await suppliers.remove({ companyId: companyOf(context), id: supplierId(context) })\n return empty()\n },\n },\n {\n ...write,\n method: 'POST',\n path: '/suppliers/:id/items',\n bodySchema: createSupplierItemSchema,\n operationId: 'purchaseCreateSupplierItem',\n summary: 'Item que o fornecedor vende: código, embalagem, conversão para o estoque, preço',\n handler: async (context) =>\n json(\n 201,\n await suppliers.createItem({\n companyId: companyOf(context),\n supplierId: supplierId(context),\n input: context.body as CreateSupplierItemData,\n }),\n ),\n },\n {\n ...read,\n method: 'GET',\n path: '/supplier-items',\n querySchema: listSupplierItemsQuerySchema,\n operationId: 'purchaseListSupplierItems',\n summary: 'Itens de fornecedor (por fornecedor, por item do catálogo, busca)',\n handler: async (context) =>\n json(\n 200,\n await suppliers.listItems({\n companyId: companyOf(context),\n query: context.query as unknown as ListSupplierItemsQuery,\n }),\n ),\n },\n {\n ...read,\n method: 'GET',\n path: '/supplier-items/:id',\n operationId: 'purchaseGetSupplierItem',\n summary: 'Item de fornecedor',\n handler: async (context) =>\n json(200, await suppliers.getItem({ companyId: companyOf(context), id: supplierItemId(context) })),\n },\n {\n ...write,\n method: 'PATCH',\n path: '/supplier-items/:id',\n bodySchema: updateSupplierItemSchema,\n operationId: 'purchaseUpdateSupplierItem',\n summary: 'Altera item de fornecedor',\n handler: async (context) =>\n json(\n 200,\n await suppliers.updateItem({\n companyId: companyOf(context),\n id: supplierItemId(context),\n input: context.body as UpdateSupplierItemData,\n }),\n ),\n },\n {\n ...write,\n method: 'DELETE',\n path: '/supplier-items/:id',\n operationId: 'purchaseDeleteSupplierItem',\n summary: 'Remove item de fornecedor (pedidos antigos guardam a cópia)',\n handler: async (context) => {\n await suppliers.removeItem({ companyId: companyOf(context), id: supplierItemId(context) })\n return empty()\n },\n },\n ]\n}\n\nfunction orderRoutes(\n module: PurchaseModule,\n read: RouteAccess,\n write: RouteAccess,\n approve: RouteAccess,\n): ModuleRoute[] {\n const { orders } = module.useCases\n const action = (\n path: string,\n operationId: string,\n summary: string,\n run: (context: RequestContext) => Promise<unknown>,\n access: RouteAccess = write,\n bodySchema?: z.ZodTypeAny,\n ): ModuleRoute => ({\n ...access,\n method: 'POST',\n path,\n ...(bodySchema ? { bodySchema } : {}),\n operationId,\n summary,\n handler: async (context) => json(200, await run(context)),\n })\n return [\n {\n ...read,\n method: 'GET',\n path: '/orders',\n querySchema: listOrdersQuerySchema,\n operationId: 'purchaseListOrders',\n summary: 'Pedidos de compra (status, fornecedor, atrasados, período, número)',\n handler: async (context) =>\n json(\n 200,\n await orders.list({ companyId: companyOf(context), query: context.query as unknown as ListOrdersQuery }),\n ),\n },\n {\n ...write,\n method: 'POST',\n path: '/orders',\n bodySchema: createOrderSchema,\n operationId: 'purchaseCreateOrder',\n summary: 'Cria rascunho (número sequencial por empresa; previsão padrão pelo prazo do fornecedor)',\n handler: async (context) =>\n json(201, await orders.create({ ...actorOf(context), input: context.body as CreateOrderData })),\n },\n {\n ...read,\n method: 'GET',\n path: '/orders/:id',\n operationId: 'purchaseGetOrder',\n summary: 'Pedido com linhas, recebido e pendente por linha',\n handler: async (context) => json(200, await orders.get({ companyId: companyOf(context), id: orderId(context) })),\n },\n {\n ...write,\n method: 'PATCH',\n path: '/orders/:id',\n bodySchema: updateOrderSchema,\n operationId: 'purchaseUpdateOrder',\n summary: 'Altera rascunho (`lines` substitui todas)',\n handler: async (context) =>\n json(\n 200,\n await orders.update({ ...actorOf(context), id: orderId(context), input: context.body as UpdateOrderData }),\n ),\n },\n {\n ...read,\n method: 'GET',\n path: '/orders/:id/message',\n querySchema: messageQuerySchema,\n operationId: 'purchaseOrderMessage',\n summary: 'Texto do pedido para o fornecedor (o mesmo do WhatsApp)',\n handler: async (context) =>\n json(\n 200,\n await orders.message({\n companyId: companyOf(context),\n id: orderId(context),\n withPrices: (context.query as { withPrices?: boolean }).withPrices === true,\n }),\n ),\n },\n action(\n '/orders/:id/submit',\n 'purchaseSubmitOrder',\n 'Envia para aprovação (ou aprova direto abaixo do limite)',\n (context) => orders.submit({ ...actorOf(context), id: orderId(context) }),\n ),\n action(\n '/orders/:id/approve',\n 'purchaseApproveOrder',\n 'Aprova (escopo de aprovação; quem submeteu não aprova)',\n (context) => orders.approve({ ...actorOf(context), id: orderId(context) }),\n approve,\n ),\n action(\n '/orders/:id/reject',\n 'purchaseRejectOrder',\n 'Recusa com motivo (volta a rascunho)',\n (context) =>\n orders.reject({ ...actorOf(context), id: orderId(context), reason: (context.body as ReasonData).reason }),\n approve,\n reasonSchema,\n ),\n action(\n '/orders/:id/send',\n 'purchaseSendOrder',\n 'Envia ao fornecedor (WhatsApp/e-mail pela porta, ou `manual`)',\n (context) => orders.send({ ...actorOf(context), id: orderId(context), input: context.body as SendOrderData }),\n write,\n sendOrderSchema,\n ),\n action(\n '/orders/:id/cancel',\n 'purchaseCancelOrder',\n 'Cancela (até o primeiro recebimento)',\n (context) =>\n orders.cancel({ ...actorOf(context), id: orderId(context), reason: (context.body as ReasonData).reason }),\n write,\n reasonSchema,\n ),\n action(\n '/orders/:id/close',\n 'purchaseCloseOrder',\n 'Encerra o saldo de um pedido recebido em parte',\n (context) =>\n orders.close({\n ...actorOf(context),\n id: orderId(context),\n reason: (context.body as OptionalReasonData).reason,\n }),\n write,\n optionalReasonSchema,\n ),\n {\n ...write,\n method: 'POST',\n path: '/orders/:id/duplicate',\n operationId: 'purchaseDuplicateOrder',\n summary: 'Novo rascunho com as mesmas linhas e o último preço',\n handler: async (context) => json(201, await orders.duplicate({ ...actorOf(context), id: orderId(context) })),\n },\n ]\n}\n\nfunction receiptRoutes(module: PurchaseModule, read: RouteAccess, write: RouteAccess): ModuleRoute[] {\n const { receipts, nfe } = module.useCases\n return [\n {\n ...write,\n method: 'POST',\n path: '/orders/:id/receipts',\n bodySchema: receiveSchema,\n operationId: 'purchaseReceiveOrder',\n summary: 'Recebe (parcial ou total) um pedido: lote, validade, divergência, custo com rateio',\n handler: async (context) =>\n json(\n 201,\n await receipts.receive({\n ...actorOf(context),\n orderId: orderId(context),\n input: context.body as ReceiveData,\n }),\n ),\n },\n {\n ...write,\n method: 'POST',\n path: '/receipts',\n bodySchema: receiveSchema,\n operationId: 'purchaseReceiveWithoutOrder',\n summary: 'Recebimento sem pedido (compra no balcão, feira)',\n handler: async (context) =>\n json(201, await receipts.receive({ ...actorOf(context), input: context.body as ReceiveData })),\n },\n {\n ...read,\n method: 'GET',\n path: '/receipts',\n querySchema: listReceiptsQuerySchema,\n operationId: 'purchaseListReceipts',\n summary: 'Recebimentos (fornecedor, pedido, período, com falha de integração)',\n handler: async (context) =>\n json(\n 200,\n await receipts.list({ companyId: companyOf(context), query: context.query as unknown as ListReceiptsQuery }),\n ),\n },\n {\n ...read,\n method: 'GET',\n path: '/receipts/:id',\n operationId: 'purchaseGetReceipt',\n summary: 'Recebimento com linhas e situação das integrações',\n handler: async (context) =>\n json(200, await receipts.get({ companyId: companyOf(context), id: receiptId(context) })),\n },\n {\n ...write,\n method: 'POST',\n path: '/receipts/:id/retry',\n operationId: 'purchaseRetryReceipt',\n summary: 'Reenvia ao estoque e às contas o que falhou (idempotente)',\n handler: async (context) => json(200, await receipts.retry({ ...actorOf(context), id: receiptId(context) })),\n },\n {\n ...write,\n method: 'POST',\n path: '/nfe/preview',\n bodySchema: nfePreviewSchema,\n operationId: 'purchasePreviewNfe',\n summary: 'Lê o XML da NF-e e devolve a prévia do recebimento (não grava)',\n handler: async (context) => {\n const body = context.body as NfePreviewData\n return json(\n 200,\n await nfe.preview({\n companyId: companyOf(context),\n xml: body.xml,\n ...(body.orderId ? { orderId: body.orderId } : {}),\n }),\n )\n },\n },\n ]\n}\n\nfunction insightRoutes(module: PurchaseModule, read: RouteAccess, write: RouteAccess): ModuleRoute[] {\n const { insights, reports } = module.useCases\n return [\n {\n ...read,\n method: 'GET',\n path: '/capabilities',\n operationId: 'purchaseCapabilities',\n summary: 'Portas ligadas e limite de aprovação (a tela esconde o que não se aplica)',\n handler: async (context) => {\n const companyId = companyOf(context)\n const threshold = (await module.config.approvalThresholdFor?.(companyId)) ?? null\n return json(200, { ...module.capabilities, approvalThreshold: threshold })\n },\n },\n {\n ...read,\n method: 'GET',\n path: '/suggestion',\n querySchema: suggestionQuerySchema,\n operationId: 'purchaseSuggestion',\n summary: 'Sugestão de pedido por fornecedor (necessidade, mínimo, saldo e a caminho)',\n handler: async (context) =>\n json(\n 200,\n await insights.suggestion({ companyId: companyOf(context), query: context.query as SuggestionQuery }),\n ),\n },\n {\n ...write,\n method: 'POST',\n path: '/suggestion/orders',\n bodySchema: ordersFromSuggestionSchema,\n operationId: 'purchaseOrdersFromSuggestion',\n summary: 'Cria um rascunho por fornecedor a partir da sugestão',\n handler: async (context) =>\n json(\n 201,\n await insights.ordersFromSuggestion({ ...actorOf(context), input: context.body as OrdersFromSuggestionData }),\n ),\n },\n {\n ...read,\n method: 'GET',\n path: '/prices/history',\n querySchema: priceHistoryQuerySchema,\n operationId: 'purchasePriceHistory',\n summary: 'Histórico de preço por item (todos os fornecedores ou um)',\n handler: async (context) =>\n json(\n 200,\n await insights.priceHistory({\n companyId: companyOf(context),\n query: context.query as unknown as PriceHistoryQuery,\n }),\n ),\n },\n {\n ...read,\n method: 'POST',\n path: '/items/costs',\n bodySchema: itemRefsLookupSchema,\n operationId: 'purchaseItemCosts',\n summary: 'Último custo e custo médio por item',\n handler: async (context) =>\n json(\n 200,\n await insights.itemCosts({\n companyId: companyOf(context),\n itemRefs: (context.body as ItemRefsLookupData).itemRefs,\n }),\n ),\n },\n {\n ...read,\n method: 'POST',\n path: '/items/incoming',\n bodySchema: itemRefsLookupSchema,\n operationId: 'purchaseIncomingSupply',\n summary: 'Quanto já foi pedido e ainda não chegou, por item',\n handler: async (context) =>\n json(\n 200,\n await insights.incoming({\n companyId: companyOf(context),\n itemRefs: (context.body as ItemRefsLookupData).itemRefs,\n }),\n ),\n },\n {\n ...read,\n method: 'GET',\n path: '/reports/spend',\n querySchema: spendReportQuerySchema,\n operationId: 'purchaseSpendReport',\n summary: 'Gasto por fornecedor, item ou mês',\n handler: async (context) =>\n json(\n 200,\n await reports.spend({ companyId: companyOf(context), query: context.query as unknown as SpendReportQuery }),\n ),\n },\n {\n ...read,\n method: 'GET',\n path: '/reports/spend/export',\n querySchema: exportSpendQuerySchema,\n operationId: 'purchaseExportSpendReport',\n summary: 'Gasto em CSV ou Excel',\n handler: async (context) => {\n const query = context.query as unknown as SpendReportQuery & ExportFormatQuery\n const file = await reports.exportSpend({ companyId: companyOf(context), query, format: query.format })\n return {\n kind: 'binary',\n status: 200,\n body: typeof file.body === 'string' ? new TextEncoder().encode(file.body) : file.body,\n contentType: file.contentType,\n headers: { 'Content-Disposition': `attachment; filename=\"${file.fileName}\"`, 'Cache-Control': 'no-store' },\n }\n },\n },\n {\n ...read,\n method: 'GET',\n path: '/reports/suppliers',\n querySchema: supplierPerformanceQuerySchema,\n operationId: 'purchaseSupplierPerformance',\n summary: 'Desempenho do fornecedor: no prazo, atraso médio, divergência, total',\n handler: async (context) =>\n json(\n 200,\n await reports.supplierPerformance({\n companyId: companyOf(context),\n query: context.query as unknown as SupplierPerformanceQuery,\n }),\n ),\n },\n ]\n}\n\nfunction serviceRoutes(module: PurchaseModule, service: RouteAccess): ModuleRoute[] {\n const { insights, suppliers, receipts } = module.useCases\n return [\n {\n ...service,\n method: 'POST',\n path: '/service/items/incoming',\n bodySchema: itemRefsLookupSchema,\n operationId: 'purchaseServiceIncoming',\n summary: 'A caminho por item (IncomingSupplyPort do estoque por HTTP)',\n handler: async (context) =>\n json(\n 200,\n await insights.incoming({\n companyId: companyOf(context),\n itemRefs: (context.body as ItemRefsLookupData).itemRefs,\n }),\n ),\n },\n {\n ...service,\n method: 'POST',\n path: '/service/items/costs',\n bodySchema: itemRefsLookupSchema,\n operationId: 'purchaseServiceItemCosts',\n summary: 'Custo por item (para a ficha técnica)',\n handler: async (context) =>\n json(\n 200,\n await insights.itemCosts({\n companyId: companyOf(context),\n itemRefs: (context.body as ItemRefsLookupData).itemRefs,\n }),\n ),\n },\n {\n ...service,\n method: 'POST',\n path: '/service/suppliers/lookup',\n bodySchema: supplierLookupSchema,\n operationId: 'purchaseServiceSupplierLookup',\n summary: 'Fornecedores por id (SupplierDirectoryPort do estoque por HTTP)',\n handler: async (context) =>\n json(\n 200,\n await suppliers.findMany({ companyId: companyOf(context), ids: (context.body as SupplierLookupData).ids }),\n ),\n },\n {\n ...service,\n method: 'POST',\n path: '/service/receipts/payments',\n bodySchema: paymentSchema,\n operationId: 'purchaseServiceRecordPayment',\n summary: 'Pagamento (ou estorno) de parcela vindo do financeiro',\n handler: async (context) => {\n const body = context.body as z.output<typeof paymentSchema>\n return json(\n 200,\n await receipts.recordPayment({\n companyId: companyOf(context),\n installmentNumber: body.installmentNumber,\n paidAmount: body.paidAmount,\n paidAt: body.paidAt,\n ...(body.receiptId ? { receiptId: body.receiptId } : {}),\n ...(body.payableRef ? { payableRef: body.payableRef } : {}),\n }),\n )\n },\n },\n ]\n}\n\nexport function createPurchaseRoutes(params: CreatePurchaseRoutesParams): ModuleRouteTable {\n const scopes = params.module.config.scopes ?? {}\n const writeScopes = [...(scopes.write ?? DEFAULT_PURCHASE_SCOPES.write)]\n const approveScopes = [...(scopes.approve ?? DEFAULT_PURCHASE_SCOPES.approve)]\n const read: RouteAccess = {\n scope: 'admin',\n requiredScopes: [...(scopes.read ?? DEFAULT_PURCHASE_SCOPES.read), ...writeScopes, ...approveScopes],\n }\n const write: RouteAccess = { scope: 'admin', requiredScopes: writeScopes }\n const approve: RouteAccess = { scope: 'admin', requiredScopes: approveScopes }\n const service: RouteAccess = {\n scope: 'service',\n requiredScopes: [...(scopes.service ?? DEFAULT_PURCHASE_SCOPES.service)],\n }\n return [\n ...supplierRoutes(params.module, read, write),\n ...orderRoutes(params.module, read, write, approve),\n ...receiptRoutes(params.module, read, write),\n ...insightRoutes(params.module, read, write),\n ...serviceRoutes(params.module, service),\n ]\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { join } from 'node:path'\n\nimport type { PurchaseDatabase, DrizzleMigrateFunction } from './database.types'\n\n// Journal próprio, fora do pgSchema `stock`: a primeira migration é quem cria esse schema\n// (mesmo raciocínio de `catalog-module/runMigrations.ts`).\nexport const PURCHASE_MIGRATIONS_TABLE = 'purchase_migrations'\n\n/** Pasta no formato clássico (`meta/_journal.json`), lida pelos migrators do drizzle 0.x e 1.x. */\nexport function purchaseMigrationsFolder(): string {\n return join(__dirname, 'migrations')\n}\n\nexport type RunPurchaseMigrationsParams = {\n readonly db: PurchaseDatabase\n /** O `migrate` do driver do host (`drizzle-orm/node-postgres/migrator`, `.../bun-sql/migrator`…). */\n readonly migrate: DrizzleMigrateFunction\n}\n\nexport async function runPurchaseMigrations(params: RunPurchaseMigrationsParams): Promise<void> {\n await params.migrate(params.db as never, {\n migrationsFolder: purchaseMigrationsFolder(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oE,OAAO;IAASC,gBAAgBF;EAAc;AAC7E,QAAMT,UAAuB;IAC3BU,OAAO;IACPC,gBAAgB;SAAKL,OAAON,WAAWQ,wBAAwBR;;EACjE;AACA,SAAO;OACF3F,eAAe5C,OAAO6C,QAAQC,MAAMC,KAAAA;OACpC6B,YAAY5E,OAAO6C,QAAQC,MAAMC,OAAO8B,OAAAA;OACxCkB,cAAc/F,OAAO6C,QAAQC,MAAMC,KAAAA;OACnC0D,cAAczG,OAAO6C,QAAQC,MAAMC,KAAAA;OACnCuF,cAActI,OAAO6C,QAAQ0F,OAAAA;;AAEpC;AArBgBK;;;AC/rBhB,SAASO,YAAY;AAMd,IAAMC,4BAA4B;AAGlC,SAASC,2BAAAA;AACd,SAAOC,KAAKC,WAAW,YAAA;AACzB;AAFgBF;AAUhB,eAAsBG,sBAAsBC,QAAmC;AAC7E,QAAMA,OAAOC,QAAQD,OAAOE,IAAa;IACvCC,kBAAkBP,yBAAAA;IAClBQ,iBAAiBT;EACnB,CAAA;AACF;AALsBI;","names":["path","fileURLToPath","getFilename","fileURLToPath","url","getDirname","path","dirname","__dirname","PurchaseConfigMissingError","convertQuantity","formatDecimal","parseDecimal","add","addDays","buildSuggestion","OPEN_ORDER_STATUSES","pendingQuantity","quantityText","toStockQuantity","weightedAverageCost","ZERO","and","count","desc","eq","gte","inArray","isNotNull","lt","sql","boolean","check","date","index","integer","numeric","pgSchema","primaryKey","text","timestamp","uniqueIndex","uuid","varchar","purchaseSchema","suppliers","table","id","defaultRandom","companyId","notNull","name","length","document","contactName","email","phone","whatsapp","paymentTermDays","array","default","leadTimeDays","minimumOrderAmount","precision","scale","deliveryWeekdays","notes","isActive","createdAt","withTimezone","defaultNow","updatedAt","on","where","supplierItems","supplierId","references","onDelete","itemRef","itemName","supplierSku","purchaseUnit","unitsPerPurchase","stockUnit","lastPrice","lastPriceAt","priority","orderCounters","lastNumber","orders","number","status","expectedAt","mode","subtotal","freight","discount","total","requiresApproval","createdBy","submittedBy","submittedAt","approvedBy","approvedAt","rejectionReason","sentAt","sentVia","canceledAt","cancelReason","closedAt","lastLateAlertAt","orderLines","orderId","position","supplierItemId","quantity","unitPrice","lineTotal","receivedQuantity","canceledQuantity","receipts","receivedAt","invoiceNumber","invoiceKey","invoiceIssuedAt","actorId","idempotencyKey","installments","stockStatus","payableStatus","payableRef","paymentStatus","receiptLines","receiptId","orderLineId","allocated","landedUnitCost","batchCode","expiresAt","divergence","divergenceReason","receiptPayments","installmentNumber","paidAmount","paidAt","columns","civilDateIn","PurchaseDisabledError","assertEnabled","dependencies","companyId","enabled","config","isEnabledForCompany","PurchaseDisabledError","today","civilDateIn","clock","now","timeZone","runHook","name","meta","run","error","logger","Error","actorFields","actor","actorId","paginated","params","data","rows","map","pagination","total","page","pageSize","totalPages","Math","max","ceil","createInsightService","dependencies","orderService","db","incoming","params","assertEnabled","companyId","refs","Set","itemRefs","length","rows","select","line","orderLines","expectedAt","orders","from","innerJoin","eq","id","orderId","where","and","inArray","itemRef","isNotNull","stockUnit","status","OPEN_ORDER_STATUSES","byItem","Map","pending","parseDecimal","toStockQuantity","pendingQuantity","unitsPerPurchase","numerator","ref","unit","current","get","quantity","ZERO","next","converted","convertQuantity","to","add","set","entries","map","value","quantityText","orderCount","size","nextExpectedAt","itemCosts","windowDays","averageCostWindowDays","since","Date","clock","now","getTime","receiptLines","cost","landedUnitCost","receivedAt","receipts","supplierId","receiptId","orderBy","desc","points","filter","row","last","recent","normalized","flatMap","factor","formatDecimal","denominator","lastCost","lastReceivedAt","toISOString","lastSupplierId","averageCost","weightedAverageCost","averageWindowDays","priceHistory","query","conditions","push","supplierItemId","gte","lt","addDays","totals","Promise","all","receipt","supplierName","suppliers","name","limit","pageSize","offset","page","total","count","paginated","purchaseUnit","unitPrice","suggestion","demandSource","providers","demand","groups","hasDemandSource","getDemand","incomingRows","items","supplierRows","supplierItems","demandUnits","incomingMap","target","buildSuggestion","minimumOrderAmount","isActive","ordersFromSuggestion","wanted","input","supplierIds","created","group","has","lines","suggestedQuantity","create","notes","freight","discount","undefined","lateOrders","day","today","order","inArray","daysLate","expectedAt","today","Math","round","Date","parse","createJobService","dependencies","insights","scanLateOrders","params","day","rows","lateOrders","fresh","filter","row","order","lastLateAlertAt","byCompany","Map","set","companyId","get","items","enabled","config","isEnabledForCompany","runHook","hooks","onOrdersLate","orders","map","orderId","id","number","supplierId","supplierName","db","update","where","inArray","companies","size","length","normalizeDecimal","parseDecimal","compare","NfeInvalidError","NfeParseError","OrderNotFoundError","parseNfeXml","pendingQuantity","ZERO","and","eq","createNfeService","dependencies","db","preview","params","assertEnabled","companyId","nfe","parseNfeXml","xml","error","NfeInvalidError","NfeParseError","message","supplier","issuer","document","select","from","suppliers","where","and","eq","existing","id","receipts","invoiceKey","accessKey","items","supplierItems","supplierId","bySku","Map","flatMap","item","supplierSku","toUpperCase","pending","orderId","order","orders","OrderNotFoundError","orderLines","filter","line","compare","parseDecimal","pendingQuantity","ZERO","usedOrderLines","Set","lines","supplierItem","get","orderLine","find","has","supplierItemId","add","batches","length","map","batch","itemNumber","description","unit","quantity","unitPrice","total","batchCode","expiresAt","itemRef","itemName","unitsPerPurchase","normalizeDecimal","stockUnit","orderLineId","number","series","issuedAt","name","alreadyReceivedReceiptId","freight","totals","discount","installments","installment","index","dueDate","amount","normalizeDecimal","parseDecimal","addDays","buildOrderMessage","canPerform","centsOf","computeTotals","DispatchUnavailableError","DISPATCH_CHANNEL","InvalidOrderTransitionError","lineTotal","money","ORDER_ACTION","ORDER_STATUS","OrderNotFoundError","pendingQuantity","requiresApproval","needsApproval","SelfApprovalError","statusAfterSend","SupplierInactiveError","SupplierItemNotFoundError","SupplierNoContactError","and","asc","count","desc","eq","gte","ilike","inArray","lt","lte","or","sql","normalizeDecimal","isOrderLate","money","pendingQuantity","parseDecimal","intList","value","Array","from","iso","toISOString","decimal","normalizeDecimal","moneyText","money","parseDecimal","toSupplier","row","id","name","document","contactName","email","phone","whatsapp","paymentTermDays","leadTimeDays","minimumOrderAmount","deliveryWeekdays","notes","isActive","createdAt","updatedAt","toSupplierItem","supplierId","itemRef","itemName","supplierSku","purchaseUnit","unitsPerPurchase","stockUnit","lastPrice","lastPriceAt","priority","toOrderLine","position","supplierItemId","quantity","unitPrice","lineTotal","receivedQuantity","canceledQuantity","pendingQuantity","toOrderSummary","params","number","supplierName","status","expectedAt","isLate","isOrderLate","today","subtotal","freight","discount","total","requiresApproval","createdBy","submittedAt","approvedBy","approvedAt","rejectionReason","sentAt","sentVia","canceledAt","cancelReason","closedAt","paymentStatus","lineCount","toOrder","summary","lines","length","map","toReceiptLine","orderLineId","landedUnitCost","batchCode","expiresAt","divergence","divergenceReason","stockStatus","toReceipt","orderId","orderNumber","receivedAt","invoiceNumber","invoiceKey","invoiceIssuedAt","actorId","payableStatus","payableRef","parseInstallments","text","JSON","parse","isArray","UNIQUE_VIOLATION","hasPostgresCode","error","code","current","depth","candidate","errno","cause","isUniqueViolation","error","hasPostgresCode","UNIQUE_VIOLATION","likePattern","search","replace","character","PurchaseItemNotFoundError","SupplierDocumentTakenError","SupplierInUseError","SupplierItemNotFoundError","SupplierItemTakenError","SupplierNotFoundError","and","asc","count","desc","eq","ilike","inArray","or","SORT_COLUMNS","name","suppliers","createdAt","updatedAt","defined","values","Object","fromEntries","entries","filter","value","undefined","guard","work","onUnique","error","isUniqueViolation","findSupplierRow","dependencies","companyId","supplierId","row","db","select","from","where","and","eq","id","SupplierNotFoundError","loadCatalogItems","itemRefs","catalog","providers","ids","Set","length","Map","found","findItems","map","item","itemRef","requireCatalogItems","has","PurchaseItemNotFoundError","createSupplierService","findItemRow","supplierItems","SupplierItemNotFoundError","create","params","assertEnabled","now","clock","input","insert","returning","SupplierDocumentTakenError","toSupplier","get","findMany","rows","inArray","list","query","conditions","isActive","push","search","pattern","likePattern","or","ilike","document","contactName","email","column","sort","totals","Promise","all","orderBy","order","desc","asc","limit","pageSize","offset","page","total","count","paginated","update","set","remove","orders","receipt","receipts","SupplierInUseError","delete","createItem","stockUnit","unit","lastPriceAt","lastPrice","SupplierItemTakenError","toSupplierItem","getItem","listItems","itemName","supplierSku","priority","updateItem","current","priceChanged","removeItem","ORDER_SORT_COLUMNS","number","orders","createdAt","expectedAt","total","lockOrder","tx","companyId","orderId","row","select","from","where","and","eq","id","for","OrderNotFoundError","assertAction","action","canPerform","status","InvalidOrderTransitionError","nextOrderNumber","insert","orderCounters","values","lastNumber","onConflictDoUpdate","target","set","sql","returning","paymentStatusByOrder","db","orderIds","length","Map","rows","receipts","paymentStatus","inArray","byOrder","get","result","statuses","tracked","filter","every","some","createOrderService","dependencies","resolveLines","params","itemIds","Set","lines","flatMap","line","supplierItemId","items","supplierItems","supplierId","byId","map","item","resolved","position","undefined","SupplierItemNotFoundError","unitPrice","normalizeDecimal","lastPrice","quantity","itemRef","itemName","supplierSku","purchaseUnit","unitsPerPurchase","stockUnit","lineTotal","money","notes","refs","catalog","requireCatalogItems","entry","unit","name","load","runner","order","supplierName","suppliers","innerJoin","orderLines","orderBy","asc","payments","toOrder","today","notifyStatus","actor","to","runHook","hooks","onOrderStatusChanged","actorFields","transition","change","assertEnabled","transaction","updated","update","updatedAt","clock","now","before","after","defaultExpectedAt","supplier","leadTimeDays","addDays","service","create","findSupplierRow","input","isActive","SupplierInactiveError","totals","computeTotals","freight","discount","ORDER_STATUS","DRAFT","paymentTermDays","intList","createdBy","actorId","list","query","conditions","push","gte","Date","lt","late","search","asNumber","Number","replace","byName","ilike","likePattern","isInteger","or","column","sort","lineCounts","lineCount","count","as","groupBy","Promise","all","leftJoin","desc","limit","pageSize","offset","page","currentDay","paginated","toOrderSummary","ORDER_ACTION","EDIT","lineValues","delete","submit","threshold","config","approvalThresholdFor","thresholdCents","centsOf","parseDecimal","approvalNeeded","SUBMIT","needsApproval","totalCents","PENDING_APPROVAL","APPROVED","requiresApproval","submittedBy","submittedAt","rejectionReason","approvedAt","approvedBy","onApprovalRequested","requestedBy","approve","APPROVE","SelfApprovalError","reject","REJECT","reason","cancel","CANCEL","CANCELED","cancelReason","canceledAt","close","CLOSE","pending","pendingQuantity","numerator","canceledQuantity","CLOSED","closedAt","message","companyName","companyNameFor","text","buildOrderMessage","withPrices","send","channel","dispatch","providers","DISPATCH_CHANNEL","MANUAL","channels","includes","DispatchUnavailableError","current","SEND","phone","whatsapp","WHATSAPP","SupplierNoContactError","EMAIL","email","messageRef","sent","orderNumber","contactName","statusAfterSend","sentAt","sentVia","duplicate","source","openOrdersExpectedBefore","day","lte","normalizeDecimal","parseDecimal","rational","add","addDays","allocateExtras","buildInstallments","centsOf","civilDateIn","compare","divergenceOf","InstallmentsMismatchError","INTEGRATION_STATUS","InvoiceAlreadyReceivedError","landedUnitCost","lineTotal","money","ORDER_ACTION","OrderLineNotFoundError","PAYMENT_STATUS","pendingQuantity","quantityText","ReceiptNotFoundError","statusAfterReceipt","subtract","SupplierItemNotFoundError","toStockQuantity","ZERO","and","asc","count","desc","eq","gte","inArray","lt","or","sql","AUTO_ITEM_PRIORITY","receiptLineSourceKey","receiptId","lineId","receiptPayableRef","aggregateStatus","statuses","length","every","status","INTEGRATION_STATUS","SKIPPED","some","FAILED","DONE","expiryInstant","date","timeZone","noon","Date","offsetProbe","Intl","DateTimeFormat","timeZoneName","formatToParts","find","part","type","value","offset","exec","suffix","toISOString","createReceiptService","dependencies","insights","db","load","companyId","row","select","receipt","receipts","supplierName","suppliers","name","orderNumber","orders","number","from","innerJoin","eq","id","supplierId","leftJoin","orderId","where","and","ReceiptNotFoundError","lines","receiptLines","orderBy","asc","position","toReceipt","findByIdempotency","key","idempotencyKey","findByInvoiceKey","invoiceKey","postStock","actor","port","providers","stock","stockStatus","line","receive","actorFields","sourceKey","itemRef","quantity","toStockQuantity","unitsPerPurchase","unit","stockUnit","batchCode","invoiceNumber","slice","costPerUnit","landedUnitCost","expiresAt","reason","error","logger","Error","update","set","map","postPayable","payables","payableStatus","supplier","findSupplierRow","order","payableRef","createPayable","sourceRef","document","description","filter","Boolean","join","total","money","parseDecimal","installments","parseInstallments","paymentStatus","PAYMENT_STATUS","OPEN","resolveLines","params","byOrderLine","Map","orderLines","itemIds","Set","flatMap","fromOrder","orderLineId","get","supplierItemId","items","supplierItems","inArray","itemsById","item","consumed","priceTolerance","BigInt","config","priceToleranceCents","resolved","orderLine","undefined","OrderLineNotFoundError","SupplierItemNotFoundError","normalizeDecimal","unitPrice","lastPrice","divergence","already","pending","quantityText","subtract","pendingQuantity","add","divergenceOf","compare","ZERO","receivedQuantity","orderedPrice","receivedPrice","itemName","supplierSku","purchaseUnit","lineTotal","divergenceReason","refs","catalog","requireCatalogItems","chooseInstallments","input","sort","left","right","dueDate","localeCompare","index","amount","sum","reduce","acc","centsOf","InstallmentsMismatchError","rational","buildInstallments","termDays","baseDate","service","assertEnabled","existing","InvoiceAlreadyReceivedError","now","clock","receivedAt","hasStockPort","hasPayables","statusChange","receiptRow","transaction","tx","lockedLines","lockOrder","assertAction","ORDER_ACTION","RECEIVE","for","shares","allocateExtras","lineTotals","freight","discount","subtotal","totalValue","civilDateIn","intList","paymentTermDays","inserted","insert","values","invoiceIssuedAt","notes","actorId","JSON","stringify","NONE","createdAt","returning","allocated","stockable","receivedByLine","updated","extra","has","next","statusAfterReceipt","updatedAt","to","lastPriceAt","priority","onConflictDoUpdate","target","targetWhere","sql","isUniqueViolation","change","runHook","hooks","onOrderStatusChanged","notifyPosted","onReceiptPosted","costs","itemCosts","itemRefs","averages","cost","averageCost","stockQuantity","retry","list","query","conditions","push","gte","lt","addDays","failed","or","rows","totals","Promise","all","desc","limit","pageSize","page","count","ids","byReceipt","paginated","recordPayment","condition","paidAmount","paidAt","delete","receiptPayments","installmentNumber","payments","paid","payment","PAID","PARTIAL","buildCsv","buildXlsx","CSV_BOM","CSV_CONTENT_TYPE","formatDecimal","parseDecimal","XLSX_CONTENT_TYPE","add","addDays","centsOf","civilDateIn","money","PURCHASE_LIMITS","REPORT_GROUP","ReportRangeTooLongError","ZERO","and","eq","gte","inArray","lt","daysBetween","from","to","Math","round","Date","parse","assertRange","PURCHASE_LIMITS","REPORT_DAYS","ReportRangeTooLongError","instantRange","start","addDays","end","createReportService","dependencies","db","spend","params","assertEnabled","companyId","query","conditions","eq","receipts","gte","receivedAt","lt","supplierId","push","itemRef","receiptLines","rows","select","receiptId","id","supplierName","suppliers","name","itemName","lineTotal","allocated","innerJoin","where","and","groups","Map","allReceipts","Set","grand","ZERO","row","day","civilDateIn","timeZone","value","add","parseDecimal","key","groupBy","REPORT_GROUP","SUPPLIER","MONTH","slice","toLowerCase","label","group","get","lines","total","set","sorted","entries","sort","left","right","localeCompare","difference","centsOf","map","receiptCount","size","lineCount","money","exportSpend","report","table","header","fileName","format","contentType","XLSX_CONTENT_TYPE","body","buildXlsx","sheetName","CSV_CONTENT_TYPE","CSV_BOM","buildCsv","supplierPerformance","receiptRows","receipt","inRange","filter","receiptIds","orderIds","flatMap","orderId","orderRows","firstReceipts","Promise","all","length","divergence","inArray","resolve","orders","firstByOrder","current","supplierOf","bySupplier","accOf","onTime","late","lateDays","divergent","acc","line","order","has","first","expectedAt","arrived","orderCount","onTimeCount","lateCount","averageDaysLate","formatDecimal","numerator","BigInt","denominator","divergentLineCount","receivedLineCount","SYSTEM_CLOCK","now","Date","DEFAULT_TIME_ZONE","DEFAULT_AVERAGE_WINDOW_DAYS","isTimeZone","value","Intl","DateTimeFormat","timeZone","createPurchaseModule","params","db","PurchaseConfigMissingError","config","windowDays","averageCostWindowDays","Number","isInteger","priceToleranceCents","undefined","providers","dispatch","channels","length","dependencies","hooks","clock","logger","orders","createOrderService","insights","createInsightService","receipts","createReceiptService","useCases","suppliers","createSupplierService","reports","createReportService","nfe","createNfeService","jobs","createJobService","capabilities","catalog","stock","demand","payables","dispatchChannels","createOrderSchema","createSupplierItemSchema","createSupplierSchema","DEFAULT_PURCHASE_SCOPES","exportFormatSchema","itemRefsLookupSchema","listOrdersQuerySchema","listReceiptsQuerySchema","listSupplierItemsQuerySchema","listSuppliersQuerySchema","nfePreviewSchema","optionalReasonSchema","OrderNotFoundError","ordersFromSuggestionSchema","PurchaseUnauthenticatedError","priceHistoryQuerySchema","reasonSchema","ReceiptNotFoundError","receiveSchema","sendOrderSchema","spendReportQuerySchema","suggestionQuerySchema","SupplierItemNotFoundError","supplierLookupSchema","SupplierNotFoundError","supplierPerformanceQuerySchema","updateOrderSchema","updateSupplierItemSchema","updateSupplierSchema","z","UUID_PATTERN","companyOf","context","auth","companyId","PurchaseUnauthenticatedError","actorOf","userId","actorId","uuidParam","name","notFound","value","params","test","json","status","data","kind","body","empty","supplierId","SupplierNotFoundError","supplierItemId","SupplierItemNotFoundError","orderId","OrderNotFoundError","receiptId","ReceiptNotFoundError","messageQuerySchema","z","object","withPrices","enum","transform","optional","exportSpendQuerySchema","intersection","spendReportQuerySchema","exportFormatSchema","paymentSchema","string","uuid","payableRef","trim","min","max","installmentNumber","number","int","paidAmount","regex","nullable","paidAt","refine","undefined","message","supplierRoutes","module","read","write","suppliers","useCases","method","path","querySchema","listSuppliersQuerySchema","operationId","summary","handler","list","query","bodySchema","createSupplierSchema","create","input","get","id","updateSupplierSchema","update","remove","createSupplierItemSchema","createItem","listSupplierItemsQuerySchema","listItems","getItem","updateSupplierItemSchema","updateItem","removeItem","orderRoutes","approve","orders","action","run","access","listOrdersQuerySchema","createOrderSchema","updateOrderSchema","submit","reject","reason","reasonSchema","send","sendOrderSchema","cancel","close","optionalReasonSchema","duplicate","receiptRoutes","receipts","nfe","receiveSchema","receive","listReceiptsQuerySchema","retry","nfePreviewSchema","preview","xml","insightRoutes","insights","reports","threshold","config","approvalThresholdFor","capabilities","approvalThreshold","suggestionQuerySchema","suggestion","ordersFromSuggestionSchema","ordersFromSuggestion","priceHistoryQuerySchema","priceHistory","itemRefsLookupSchema","itemCosts","itemRefs","incoming","spend","file","exportSpend","format","TextEncoder","encode","contentType","headers","fileName","supplierPerformanceQuerySchema","supplierPerformance","serviceRoutes","service","supplierLookupSchema","findMany","ids","recordPayment","createPurchaseRoutes","scopes","writeScopes","DEFAULT_PURCHASE_SCOPES","approveScopes","scope","requiredScopes","join","PURCHASE_MIGRATIONS_TABLE","purchaseMigrationsFolder","join","__dirname","runPurchaseMigrations","params","migrate","db","migrationsFolder","migrationsTable"]}
|