@adatechnology/purchase-contracts 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 +16 -2
- package/dist/index.cjs +1548 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2005 -0
- package/dist/index.d.ts +2005 -0
- package/dist/index.js +1420 -0
- package/dist/index.js.map +1 -0
- package/package.json +34 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/purchase.types.ts","../src/schemas.ts","../src/rules/schedule.ts","../src/rules/money.ts","../src/errors.ts","../src/providers.ts","../src/rules/orderStatus.ts","../src/rules/totals.ts","../src/rules/suggestion.ts","../src/rules/orderMessage.ts","../src/nfe/nfe.ts","../src/nfe/xml.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport * from './purchase.types'\nexport * from './reports.types'\nexport * from './schemas'\nexport * from './errors'\nexport * from './providers'\nexport * from './rules/orderStatus'\nexport * from './rules/totals'\nexport * from './rules/suggestion'\nexport * from './rules/schedule'\nexport * from './rules/orderMessage'\nexport { money, quantityText, lineTotal, centsOf, MONEY_SCALE } from './rules/money'\nexport { parseNfeXml, NfeParseError } from './nfe/nfe'\nexport type { ParsedNfe, NfeItem, NfeInstallment } from './nfe/nfe'\n// Aritmética exata do `recipe-contracts`, reexportada para o módulo e a tela não precisarem de dois imports.\nexport { add, compare, subtract, multiply, ZERO } from './rules/money'\nexport type { Rational } from './rules/money'\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Compras funciona sozinho: o item comprado é um texto com unidade de compra (`cx`, `fardo`, `kg`). Com um catálogo\n * ligado (ficha técnica, estoque ou o do host), o item aponta para ele por `itemRef`, opaco para o módulo. Quantidade\n * e preço são texto decimal exato (até 4 casas); dinheiro de pedido e nota fecha em 2 casas.\n */\n\nimport type { RecipeUnit } from '@adatechnology/recipe-contracts'\n\nexport const ORDER_STATUS = {\n DRAFT: 'draft',\n PENDING_APPROVAL: 'pending_approval',\n APPROVED: 'approved',\n SENT: 'sent',\n PARTIALLY_RECEIVED: 'partially_received',\n RECEIVED: 'received',\n CLOSED: 'closed',\n CANCELED: 'canceled',\n} as const\nexport type OrderStatus = (typeof ORDER_STATUS)[keyof typeof ORDER_STATUS]\nexport const ORDER_STATUSES = Object.values(ORDER_STATUS) as readonly OrderStatus[]\n\n/** Pedido que ainda pode chegar: conta como \"a caminho\" no estoque previsto. */\nexport const OPEN_ORDER_STATUSES: readonly OrderStatus[] = [\n ORDER_STATUS.APPROVED,\n ORDER_STATUS.SENT,\n ORDER_STATUS.PARTIALLY_RECEIVED,\n]\n\nexport const DISPATCH_CHANNEL = { WHATSAPP: 'whatsapp', EMAIL: 'email', MANUAL: 'manual' } as const\nexport type DispatchChannel = (typeof DISPATCH_CHANNEL)[keyof typeof DISPATCH_CHANNEL]\nexport const DISPATCH_CHANNELS = Object.values(DISPATCH_CHANNEL) as readonly DispatchChannel[]\n\nexport const DIVERGENCE = { NONE: 'none', QUANTITY: 'quantity', PRICE: 'price', BOTH: 'both' } as const\nexport type Divergence = (typeof DIVERGENCE)[keyof typeof DIVERGENCE]\n\n/** Situação de cada integração de um recebimento: `skipped` = porta não ligada. */\nexport const INTEGRATION_STATUS = { SKIPPED: 'skipped', DONE: 'done', FAILED: 'failed' } as const\nexport type IntegrationStatus = (typeof INTEGRATION_STATUS)[keyof typeof INTEGRATION_STATUS]\n\nexport const PAYMENT_STATUS = { NONE: 'none', OPEN: 'open', PARTIAL: 'partial', PAID: 'paid' } as const\nexport type PaymentStatus = (typeof PAYMENT_STATUS)[keyof typeof PAYMENT_STATUS]\n\nexport const SORT_ORDER = { ASC: 'asc', DESC: 'desc' } as const\nexport type SortOrder = (typeof SORT_ORDER)[keyof typeof SORT_ORDER]\n\nexport type Supplier = {\n readonly id: string\n readonly name: string\n /** CPF/CNPJ só com dígitos (ou alfanumérico), sem máscara. */\n readonly document: string | null\n readonly contactName: string | null\n readonly email: string | null\n readonly phone: string | null\n /** Número para receber o pedido (E.164 sem `+` ou com). */\n readonly whatsapp: string | null\n /** Condição de pagamento em dias a partir do recebimento: `[0]` à vista, `[30, 60, 90]`. */\n readonly paymentTermDays: readonly number[]\n /** Dias entre o envio e a entrega, para a previsão padrão do pedido. */\n readonly leadTimeDays: number | null\n /** Valor mínimo de pedido (2 casas). */\n readonly minimumOrderAmount: string | null\n /** 0 = domingo … 6 = sábado. Vazio = qualquer dia. */\n readonly deliveryWeekdays: readonly number[]\n readonly notes: string\n readonly isActive: boolean\n readonly createdAt: string\n readonly updatedAt: string\n}\n\n/** O que o fornecedor vende: código dele, embalagem e conversão para a unidade do estoque. */\nexport type SupplierItem = {\n readonly id: string\n readonly supplierId: string\n /** Id do item no catálogo ligado (insumo do `recipe-module`, produto do host); `null` = item livre. */\n readonly itemRef: string | null\n readonly itemName: string\n readonly supplierSku: string | null\n /** Unidade em que se compra: `cx`, `fardo`, `kg`, `un`… */\n readonly purchaseUnit: string\n /** Quantas unidades de estoque vêm em uma unidade de compra (caixa com 12 = `12`). */\n readonly unitsPerPurchase: string\n /** Unidade de estoque (`kg`, `un`…); `null` em item livre sem estoque. */\n readonly stockUnit: RecipeUnit | null\n /** Último preço por unidade de compra (do último recebimento ou digitado). */\n readonly lastPrice: string | null\n readonly lastPriceAt: string | null\n /** Menor = preferido primeiro, entre os fornecedores do mesmo item. */\n readonly priority: number\n readonly isActive: boolean\n readonly createdAt: string\n readonly updatedAt: string\n}\n\nexport type OrderLine = {\n readonly id: string\n readonly position: number\n readonly supplierItemId: string | null\n readonly itemRef: string | null\n readonly itemName: string\n readonly supplierSku: string | null\n readonly purchaseUnit: string\n readonly unitsPerPurchase: string\n readonly stockUnit: RecipeUnit | null\n /** Na unidade de compra. */\n readonly quantity: string\n readonly unitPrice: string\n /** `quantity × unitPrice`, 2 casas. */\n readonly lineTotal: string\n readonly receivedQuantity: string\n readonly canceledQuantity: string\n /** `quantity − received − canceled` (nunca negativo). */\n readonly pendingQuantity: string\n readonly notes: string | null\n}\n\nexport type PurchaseOrder = {\n readonly id: string\n /** Sequencial por empresa: o número que se fala com o fornecedor. */\n readonly number: number\n readonly supplierId: string\n readonly supplierName: string | null\n readonly status: OrderStatus\n /** `aaaa-mm-dd`. */\n readonly expectedAt: string | null\n readonly isLate: boolean\n readonly subtotal: string\n readonly freight: string\n readonly discount: string\n readonly total: string\n readonly paymentTermDays: readonly number[]\n readonly notes: string\n readonly requiresApproval: boolean\n readonly createdBy: string | null\n readonly submittedAt: string | null\n readonly approvedBy: string | null\n readonly approvedAt: string | null\n readonly rejectionReason: string | null\n readonly sentAt: string | null\n readonly sentVia: DispatchChannel | null\n readonly canceledAt: string | null\n readonly cancelReason: string | null\n readonly closedAt: string | null\n readonly paymentStatus: PaymentStatus\n readonly createdAt: string\n readonly updatedAt: string\n readonly lines: readonly OrderLine[]\n}\n\nexport type PurchaseOrderSummary = Omit<PurchaseOrder, 'lines'> & {\n readonly lineCount: number\n}\n\nexport type ReceiptLine = {\n readonly id: string\n readonly orderLineId: string | null\n readonly itemRef: string | null\n readonly itemName: string\n readonly supplierSku: string | null\n readonly purchaseUnit: string\n readonly unitsPerPurchase: string\n readonly stockUnit: RecipeUnit | null\n /** Na unidade de compra. */\n readonly quantity: string\n readonly unitPrice: string\n readonly lineTotal: string\n /** Custo por unidade de estoque com frete e desconto rateados (4 casas). */\n readonly landedUnitCost: string | null\n readonly batchCode: string | null\n readonly expiresAt: string | null\n readonly divergence: Divergence\n readonly divergenceReason: string | null\n readonly stockStatus: IntegrationStatus\n}\n\nexport type Receipt = {\n readonly id: string\n readonly orderId: string | null\n readonly orderNumber: number | null\n readonly supplierId: string\n readonly supplierName: string | null\n readonly receivedAt: string\n readonly invoiceNumber: string | null\n /** Chave de acesso da NF-e (44 dígitos), única por empresa. */\n readonly invoiceKey: string | null\n readonly invoiceIssuedAt: string | null\n readonly subtotal: string\n readonly freight: string\n readonly discount: string\n readonly total: string\n readonly notes: string\n readonly actorId: string | null\n readonly stockStatus: IntegrationStatus\n readonly payableStatus: IntegrationStatus\n /** Referência da conta a pagar criada pela porta `payables` (opaca). */\n readonly payableRef: string | null\n readonly paymentStatus: PaymentStatus\n readonly createdAt: string\n readonly lines: readonly ReceiptLine[]\n}\n\nexport type PricePoint = {\n readonly supplierId: string\n readonly supplierName: string | null\n readonly receiptId: string\n readonly receivedAt: string\n readonly purchaseUnit: string\n readonly unitPrice: string\n /** Por unidade de estoque, com rateio. */\n readonly landedUnitCost: string | null\n readonly stockUnit: RecipeUnit | null\n}\n\nexport type ItemCost = {\n readonly itemRef: string\n readonly stockUnit: RecipeUnit | null\n readonly lastCost: string | null\n readonly lastReceivedAt: string | null\n readonly lastSupplierId: string | null\n /** Média ponderada pela quantidade, na janela de dias da configuração. */\n readonly averageCost: string | null\n readonly averageWindowDays: number\n}\n\n/** Quanto do item já foi pedido e ainda não chegou, em unidade de estoque. */\nexport type IncomingSupply = {\n readonly itemRef: string\n readonly quantity: string\n readonly unit: RecipeUnit\n readonly orderCount: number\n /** Previsão mais próxima (`aaaa-mm-dd`) entre os pedidos abertos. */\n readonly nextExpectedAt: string | null\n}\n\nexport type SuggestionLine = {\n readonly itemRef: string\n readonly itemName: string\n readonly stockUnit: RecipeUnit\n readonly neededQuantity: string\n readonly onHandQuantity: string | null\n readonly incomingQuantity: string\n readonly minimumQuantity: string | null\n /** Falta, já descontando o que está a caminho, na unidade de estoque. */\n readonly shortageQuantity: string\n readonly supplierItemId: string | null\n readonly purchaseUnit: string | null\n readonly unitsPerPurchase: string | null\n /** Quantidade sugerida na unidade de compra (arredondada para cima). */\n readonly suggestedQuantity: string | null\n readonly unitPrice: string | null\n readonly estimatedTotal: string | null\n}\n\nexport type SuggestionGroup = {\n readonly supplierId: string | null\n readonly supplierName: string | null\n readonly lines: readonly SuggestionLine[]\n readonly estimatedTotal: string\n /** Total abaixo do pedido mínimo do fornecedor. */\n readonly belowMinimumOrder: boolean\n}\n\nexport type PurchaseSuggestion = {\n readonly groups: readonly SuggestionGroup[]\n /** `false` sem porta de demanda: a sugestão sai vazia. */\n readonly hasDemandSource: boolean\n}\n\nexport type Installment = {\n readonly number: number\n /** `aaaa-mm-dd`. */\n readonly dueDate: string\n /** 2 casas. A soma das parcelas é exatamente o total. */\n readonly amount: string\n}\n\n/** Item da nota já casado com o cadastro, pronto para virar linha de recebimento (a pessoa confere antes). */\nexport type NfePreviewLine = {\n readonly itemNumber: number\n readonly supplierSku: string\n readonly description: string\n readonly unit: string\n readonly quantity: string\n readonly unitPrice: string\n readonly total: string\n readonly batchCode: string | null\n readonly expiresAt: string | null\n /** Item do fornecedor com o mesmo código (`cProd`); `null` = item novo, precisa ligar. */\n readonly supplierItemId: string | null\n readonly itemRef: string | null\n readonly itemName: string | null\n readonly unitsPerPurchase: string | null\n readonly stockUnit: RecipeUnit | null\n /** Linha pendente do pedido para o mesmo item. */\n readonly orderLineId: string | null\n}\n\nexport type NfePreview = {\n readonly accessKey: string\n readonly number: string\n readonly series: string | null\n readonly issuedAt: string | null\n readonly issuer: { readonly document: string | null; readonly name: string }\n /** Fornecedor com o mesmo CNPJ/CPF do emitente; `null` = cadastrar antes de receber. */\n readonly supplierId: string | null\n /** Recebimento que já usou esta chave (nota repetida). */\n readonly alreadyReceivedReceiptId: string | null\n readonly freight: string\n readonly discount: string\n readonly total: string\n readonly installments: readonly Installment[]\n readonly lines: readonly NfePreviewLine[]\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { decimalSchema, positiveDecimalSchema, RECIPE_UNITS, type RecipeUnit } from '@adatechnology/recipe-contracts'\nimport { z } from 'zod'\n\nimport {\n DISPATCH_CHANNEL,\n DISPATCH_CHANNELS,\n ORDER_STATUSES,\n SORT_ORDER,\n type DispatchChannel,\n type OrderStatus,\n} from './purchase.types'\nimport { isCivilDate } from './rules/schedule'\n\nexport const PURCHASE_LIMITS = {\n NAME: 160,\n DOCUMENT: 20,\n CONTACT: 120,\n EMAIL: 254,\n PHONE: 30,\n SKU: 100,\n UNIT: 12,\n ITEM_REF: 128,\n NOTE: 2000,\n REASON: 500,\n BATCH_CODE: 100,\n INVOICE_NUMBER: 30,\n SEARCH: 100,\n PAGE_SIZE: 100,\n ORDER_LINES: 300,\n TERMS: 24,\n TERM_DAYS: 365,\n LEAD_DAYS: 365,\n PRIORITY: 1000,\n LOOKUP: 500,\n IDEMPOTENCY_KEY: 128,\n XML_BYTES: 5_000_000,\n REPORT_DAYS: 400,\n} as const\n\nconst unitSchema = z.enum(RECIPE_UNITS as [RecipeUnit, ...RecipeUnit[]])\n/** Dinheiro: até 2 casas. */\nexport const moneySchema = z\n .string()\n .trim()\n .regex(/^\\d{1,12}(\\.\\d{1,2})?$/, 'Valor com até duas casas.')\nconst civilDate = z.string().refine(isCivilDate, 'Data no formato aaaa-mm-dd.')\nconst pageShape = {\n page: z.coerce.number().int().min(1).default(1),\n pageSize: z.coerce.number().int().min(1).max(PURCHASE_LIMITS.PAGE_SIZE).default(20),\n}\nconst boolText = z\n .enum(['true', 'false'])\n .transform((value) => value === 'true')\n .optional()\n\nfunction csvOf<TValue extends string>(allowed: readonly TValue[]) {\n return z\n .string()\n .trim()\n .transform((value) =>\n value\n .split(',')\n .map((item) => item.trim())\n .filter(Boolean),\n )\n .refine((values) => values.every((value) => (allowed as readonly string[]).includes(value)), 'Valor inválido.')\n .transform((values) => values as TValue[])\n .optional()\n}\n\nfunction emptyToNull<TSchema extends z.ZodTypeAny>(schema: TSchema) {\n return {\n create: schema\n .nullable()\n .optional()\n .transform((value: string | null | undefined) => (value ? value : null)),\n update: schema\n .nullable()\n .optional()\n .transform((value: string | null | undefined) => (value === undefined ? undefined : value ? value : null)),\n }\n}\n\nconst nullableText = (max: number) => emptyToNull(z.string().trim().max(max))\n\nconst documentField = emptyToNull(\n z\n .string()\n .trim()\n .max(PURCHASE_LIMITS.DOCUMENT + 10)\n .transform((value) => value.replace(/[^0-9A-Za-z]/g, '').toUpperCase())\n .refine((value) => value === '' || (value.length >= 11 && value.length <= PURCHASE_LIMITS.DOCUMENT), {\n message: 'Documento com 11 a 20 caracteres (CPF, CNPJ ou equivalente).',\n }),\n)\n\nconst phoneField = emptyToNull(\n z\n .string()\n .trim()\n .max(PURCHASE_LIMITS.PHONE)\n .refine((value) => value === '' || /^\\+?[0-9 ()-]{8,}$/.test(value), { message: 'Telefone inválido.' }),\n)\n\nconst emailField = emptyToNull(\n z.union([z.literal(''), z.string().trim().toLowerCase().email().max(PURCHASE_LIMITS.EMAIL)]),\n)\n\nconst termDaysSchema = z\n .array(z.number().int().min(0).max(PURCHASE_LIMITS.TERM_DAYS))\n .max(PURCHASE_LIMITS.TERMS)\n .transform((days) => [...new Set(days)].sort((a, b) => a - b))\nconst weekdaysSchema = z\n .array(z.number().int().min(0).max(6))\n .max(7)\n .transform((days) => [...new Set(days)].sort((a, b) => a - b))\n\nconst supplierShape = {\n name: z.string().trim().min(1).max(PURCHASE_LIMITS.NAME),\n document: documentField.create,\n contactName: nullableText(PURCHASE_LIMITS.CONTACT).create,\n email: emailField.create,\n phone: phoneField.create,\n whatsapp: phoneField.create,\n paymentTermDays: termDaysSchema.default([0]),\n leadTimeDays: z.number().int().min(0).max(PURCHASE_LIMITS.LEAD_DAYS).nullable().default(null),\n minimumOrderAmount: moneySchema.nullable().default(null),\n deliveryWeekdays: weekdaysSchema.default([]),\n notes: z.string().trim().max(PURCHASE_LIMITS.NOTE).default(''),\n isActive: z.boolean().default(true),\n}\n\n/** `id` opcional: o host que já tem fornecedores (no estoque, por exemplo) importa mantendo o mesmo id. */\nexport const createSupplierSchema = z.object({ id: z.string().uuid().optional(), ...supplierShape })\nexport type CreateSupplierInput = z.input<typeof createSupplierSchema>\nexport type CreateSupplierData = z.output<typeof createSupplierSchema>\n\nexport const updateSupplierSchema = z\n .object({\n name: supplierShape.name.optional(),\n document: documentField.update,\n contactName: nullableText(PURCHASE_LIMITS.CONTACT).update,\n email: emailField.update,\n phone: phoneField.update,\n whatsapp: phoneField.update,\n paymentTermDays: termDaysSchema.optional(),\n leadTimeDays: z.number().int().min(0).max(PURCHASE_LIMITS.LEAD_DAYS).nullable().optional(),\n minimumOrderAmount: moneySchema.nullable().optional(),\n deliveryWeekdays: weekdaysSchema.optional(),\n notes: z.string().trim().max(PURCHASE_LIMITS.NOTE).optional(),\n isActive: z.boolean().optional(),\n })\n .refine((value) => Object.values(value).some((field) => field !== undefined), { message: 'Nada para alterar.' })\nexport type UpdateSupplierInput = z.input<typeof updateSupplierSchema>\nexport type UpdateSupplierData = z.output<typeof updateSupplierSchema>\n\nexport const SUPPLIER_SORTS = ['name', 'createdAt', 'updatedAt'] as const\nexport type SupplierSort = (typeof SUPPLIER_SORTS)[number]\n\nexport const listSuppliersQuerySchema = z.object({\n ...pageShape,\n search: z.string().trim().max(PURCHASE_LIMITS.SEARCH).optional(),\n isActive: boolText,\n sort: z.enum(SUPPLIER_SORTS).default('name'),\n order: z.enum([SORT_ORDER.ASC, SORT_ORDER.DESC]).default(SORT_ORDER.ASC),\n})\nexport type ListSuppliersQuery = z.output<typeof listSuppliersQuerySchema>\n\nexport const supplierLookupSchema = z.object({\n ids: z.array(z.string().uuid()).min(1).max(PURCHASE_LIMITS.LOOKUP),\n})\nexport type SupplierLookupData = z.output<typeof supplierLookupSchema>\n\nconst supplierItemShape = {\n itemRef: z.string().trim().min(1).max(PURCHASE_LIMITS.ITEM_REF).nullable().default(null),\n itemName: z.string().trim().min(1).max(PURCHASE_LIMITS.NAME),\n supplierSku: nullableText(PURCHASE_LIMITS.SKU).create,\n purchaseUnit: z.string().trim().min(1).max(PURCHASE_LIMITS.UNIT),\n unitsPerPurchase: positiveDecimalSchema.default('1'),\n stockUnit: unitSchema.nullable().default(null),\n lastPrice: decimalSchema.nullable().default(null),\n priority: z.number().int().min(0).max(PURCHASE_LIMITS.PRIORITY).default(0),\n isActive: z.boolean().default(true),\n}\n\nexport const createSupplierItemSchema = z.object(supplierItemShape)\nexport type CreateSupplierItemInput = z.input<typeof createSupplierItemSchema>\nexport type CreateSupplierItemData = z.output<typeof createSupplierItemSchema>\n\nexport const updateSupplierItemSchema = z\n .object({\n itemRef: supplierItemShape.itemRef.optional(),\n itemName: supplierItemShape.itemName.optional(),\n supplierSku: nullableText(PURCHASE_LIMITS.SKU).update,\n purchaseUnit: supplierItemShape.purchaseUnit.optional(),\n unitsPerPurchase: positiveDecimalSchema.optional(),\n stockUnit: unitSchema.nullable().optional(),\n lastPrice: decimalSchema.nullable().optional(),\n priority: z.number().int().min(0).max(PURCHASE_LIMITS.PRIORITY).optional(),\n isActive: z.boolean().optional(),\n })\n .refine((value) => Object.values(value).some((field) => field !== undefined), { message: 'Nada para alterar.' })\nexport type UpdateSupplierItemData = z.output<typeof updateSupplierItemSchema>\n\nexport const listSupplierItemsQuerySchema = z.object({\n ...pageShape,\n supplierId: z.string().uuid().optional(),\n itemRef: z.string().trim().max(PURCHASE_LIMITS.ITEM_REF).optional(),\n search: z.string().trim().max(PURCHASE_LIMITS.SEARCH).optional(),\n isActive: boolText,\n})\nexport type ListSupplierItemsQuery = z.output<typeof listSupplierItemsQuerySchema>\n\n/**\n * Linha de pedido. Com `supplierItemId`, item, código, unidade e conversão vêm do cadastro (e o preço, do último\n * preço se não vier). Sem ele, a linha é livre: `itemName` e `purchaseUnit` são obrigatórios.\n */\nexport const orderLineInputSchema = z\n .object({\n supplierItemId: z.string().uuid().optional(),\n itemRef: z.string().trim().min(1).max(PURCHASE_LIMITS.ITEM_REF).optional(),\n itemName: z.string().trim().min(1).max(PURCHASE_LIMITS.NAME).optional(),\n supplierSku: z.string().trim().max(PURCHASE_LIMITS.SKU).optional(),\n purchaseUnit: z.string().trim().min(1).max(PURCHASE_LIMITS.UNIT).optional(),\n unitsPerPurchase: positiveDecimalSchema.optional(),\n stockUnit: unitSchema.optional(),\n quantity: positiveDecimalSchema,\n unitPrice: decimalSchema.optional(),\n notes: z.string().trim().max(PURCHASE_LIMITS.REASON).optional(),\n })\n .refine(\n (line) => line.supplierItemId !== undefined || (line.itemName !== undefined && line.purchaseUnit !== undefined),\n {\n message: 'Linha sem item do fornecedor precisa de nome e unidade de compra.',\n },\n )\nexport type OrderLineInput = z.input<typeof orderLineInputSchema>\nexport type OrderLineData = z.output<typeof orderLineInputSchema>\n\nexport const createOrderSchema = z.object({\n supplierId: z.string().uuid(),\n expectedAt: civilDate.nullable().optional(),\n notes: z.string().trim().max(PURCHASE_LIMITS.NOTE).default(''),\n freight: moneySchema.default('0'),\n discount: moneySchema.default('0'),\n /** Ausente: a condição do fornecedor. */\n paymentTermDays: termDaysSchema.optional(),\n lines: z.array(orderLineInputSchema).min(1).max(PURCHASE_LIMITS.ORDER_LINES),\n})\nexport type CreateOrderInput = z.input<typeof createOrderSchema>\nexport type CreateOrderData = z.output<typeof createOrderSchema>\n\n/** Só no rascunho. `lines` presente substitui todas as linhas. */\nexport const updateOrderSchema = z\n .object({\n expectedAt: civilDate.nullable().optional(),\n notes: z.string().trim().max(PURCHASE_LIMITS.NOTE).optional(),\n freight: moneySchema.optional(),\n discount: moneySchema.optional(),\n paymentTermDays: termDaysSchema.optional(),\n lines: z.array(orderLineInputSchema).min(1).max(PURCHASE_LIMITS.ORDER_LINES).optional(),\n })\n .refine((value) => Object.values(value).some((field) => field !== undefined), { message: 'Nada para alterar.' })\nexport type UpdateOrderData = z.output<typeof updateOrderSchema>\n\nexport const reasonSchema = z.object({ reason: z.string().trim().min(1).max(PURCHASE_LIMITS.REASON) })\nexport type ReasonData = z.output<typeof reasonSchema>\n\nexport const optionalReasonSchema = z.object({ reason: z.string().trim().max(PURCHASE_LIMITS.REASON).default('') })\nexport type OptionalReasonData = z.output<typeof optionalReasonSchema>\n\nexport const sendOrderSchema = z.object({\n channel: z.enum(DISPATCH_CHANNELS as [DispatchChannel, ...DispatchChannel[]]).default(DISPATCH_CHANNEL.WHATSAPP),\n /** Preço no texto do pedido (padrão: sem). */\n withPrices: z.boolean().default(false),\n})\nexport type SendOrderData = z.output<typeof sendOrderSchema>\n\nexport const ORDER_SORTS = ['number', 'createdAt', 'expectedAt', 'total'] as const\nexport type OrderSort = (typeof ORDER_SORTS)[number]\n\nexport const listOrdersQuerySchema = z.object({\n ...pageShape,\n status: csvOf(ORDER_STATUSES as readonly OrderStatus[]),\n supplierId: z.string().uuid().optional(),\n /** Número do pedido ou nome do fornecedor. */\n search: z.string().trim().max(PURCHASE_LIMITS.SEARCH).optional(),\n late: boolText,\n from: civilDate.optional(),\n to: civilDate.optional(),\n sort: z.enum(ORDER_SORTS).default('number'),\n order: z.enum([SORT_ORDER.ASC, SORT_ORDER.DESC]).default(SORT_ORDER.DESC),\n})\nexport type ListOrdersQuery = z.output<typeof listOrdersQuerySchema>\n\nexport const receiptLineInputSchema = z\n .object({\n /** Linha do pedido que está chegando (recebimento com pedido). */\n orderLineId: z.string().uuid().optional(),\n supplierItemId: z.string().uuid().optional(),\n itemRef: z.string().trim().min(1).max(PURCHASE_LIMITS.ITEM_REF).optional(),\n itemName: z.string().trim().min(1).max(PURCHASE_LIMITS.NAME).optional(),\n supplierSku: z.string().trim().max(PURCHASE_LIMITS.SKU).optional(),\n purchaseUnit: z.string().trim().min(1).max(PURCHASE_LIMITS.UNIT).optional(),\n unitsPerPurchase: positiveDecimalSchema.optional(),\n stockUnit: unitSchema.optional(),\n /** Na unidade de compra. */\n quantity: positiveDecimalSchema,\n /** Ausente: o preço do pedido (ou o último do fornecedor). */\n unitPrice: decimalSchema.optional(),\n batchCode: z.string().trim().max(PURCHASE_LIMITS.BATCH_CODE).optional(),\n expiresAt: civilDate.nullable().optional(),\n divergenceReason: z.string().trim().max(PURCHASE_LIMITS.REASON).optional(),\n })\n .refine(\n (line) =>\n line.orderLineId !== undefined ||\n line.supplierItemId !== undefined ||\n (line.itemName !== undefined && line.purchaseUnit !== undefined),\n { message: 'Linha precisa da linha do pedido, do item do fornecedor ou de nome e unidade.' },\n )\nexport type ReceiptLineInput = z.input<typeof receiptLineInputSchema>\nexport type ReceiptLineData = z.output<typeof receiptLineInputSchema>\n\nconst installmentInput = z.object({ dueDate: civilDate, amount: moneySchema })\n\nexport const receiveSchema = z.object({\n /** Obrigatório no recebimento sem pedido; com pedido, vem dele. */\n supplierId: z.string().uuid().optional(),\n /** ISO com fuso. Ausente: agora. */\n receivedAt: z.string().datetime({ offset: true }).optional(),\n invoiceNumber: z.string().trim().max(PURCHASE_LIMITS.INVOICE_NUMBER).optional(),\n invoiceKey: z\n .string()\n .trim()\n .transform((value) => value.replace(/\\D/g, ''))\n .refine((value) => value === '' || value.length === 44, 'Chave de acesso com 44 dígitos.')\n .optional(),\n invoiceIssuedAt: z.string().datetime({ offset: true }).optional(),\n freight: moneySchema.default('0'),\n discount: moneySchema.default('0'),\n notes: z.string().trim().max(PURCHASE_LIMITS.NOTE).default(''),\n /** Mesmo valor reenviado devolve o recebimento já gravado (clique duplo, rede caindo). */\n idempotencyKey: z.string().trim().min(1).max(PURCHASE_LIMITS.IDEMPOTENCY_KEY).optional(),\n /** Parcelas da conta a pagar; ausente: pela condição do pedido/fornecedor, ou pelas duplicatas da nota. */\n installments: z.array(installmentInput).min(1).max(PURCHASE_LIMITS.TERMS).optional(),\n lines: z.array(receiptLineInputSchema).min(1).max(PURCHASE_LIMITS.ORDER_LINES),\n})\nexport type ReceiveInput = z.input<typeof receiveSchema>\nexport type ReceiveData = z.output<typeof receiveSchema>\n\nexport const listReceiptsQuerySchema = z.object({\n ...pageShape,\n supplierId: z.string().uuid().optional(),\n orderId: z.string().uuid().optional(),\n from: civilDate.optional(),\n to: civilDate.optional(),\n /** Só os que tiveram falha numa integração (estoque ou contas), para reprocessar. */\n failed: boolText,\n})\nexport type ListReceiptsQuery = z.output<typeof listReceiptsQuerySchema>\n\nexport const priceHistoryQuerySchema = z\n .object({\n ...pageShape,\n itemRef: z.string().trim().max(PURCHASE_LIMITS.ITEM_REF).optional(),\n supplierItemId: z.string().uuid().optional(),\n supplierId: z.string().uuid().optional(),\n from: civilDate.optional(),\n to: civilDate.optional(),\n })\n .refine((query) => query.itemRef !== undefined || query.supplierItemId !== undefined, {\n message: 'Informe itemRef ou supplierItemId.',\n })\nexport type PriceHistoryQuery = z.output<typeof priceHistoryQuerySchema>\n\nexport const itemRefsLookupSchema = z.object({\n itemRefs: z.array(z.string().trim().min(1).max(PURCHASE_LIMITS.ITEM_REF)).min(1).max(PURCHASE_LIMITS.LOOKUP),\n})\nexport type ItemRefsLookupData = z.output<typeof itemRefsLookupSchema>\n\nexport const suggestionQuerySchema = z.object({ supplierId: z.string().uuid().optional() })\nexport type SuggestionQuery = z.output<typeof suggestionQuerySchema>\n\nexport const ordersFromSuggestionSchema = z.object({\n /** Ausente: um rascunho por fornecedor sugerido. */\n supplierIds: z.array(z.string().uuid()).max(100).optional(),\n expectedAt: civilDate.nullable().optional(),\n})\nexport type OrdersFromSuggestionData = z.output<typeof ordersFromSuggestionSchema>\n\nexport const nfePreviewSchema = z.object({\n xml: z.string().min(1).max(PURCHASE_LIMITS.XML_BYTES),\n /** Casa os itens da nota com as linhas pendentes deste pedido. */\n orderId: z.string().uuid().optional(),\n})\nexport type NfePreviewData = z.output<typeof nfePreviewSchema>\n\nexport const REPORT_GROUP = { SUPPLIER: 'supplier', ITEM: 'item', MONTH: 'month' } as const\nexport type ReportGroup = (typeof REPORT_GROUP)[keyof typeof REPORT_GROUP]\nexport const REPORT_GROUPS = Object.values(REPORT_GROUP) as readonly ReportGroup[]\n\nexport const spendReportQuerySchema = z\n .object({\n from: civilDate,\n to: civilDate,\n groupBy: z.enum(REPORT_GROUPS as [ReportGroup, ...ReportGroup[]]).default(REPORT_GROUP.SUPPLIER),\n supplierId: z.string().uuid().optional(),\n itemRef: z.string().trim().max(PURCHASE_LIMITS.ITEM_REF).optional(),\n })\n .refine((query) => query.from <= query.to, { message: 'Início depois do fim.' })\nexport type SpendReportQuery = z.output<typeof spendReportQuerySchema>\n\nexport const supplierPerformanceQuerySchema = z\n .object({ from: civilDate, to: civilDate })\n .refine((query) => query.from <= query.to, { message: 'Início depois do fim.' })\nexport type SupplierPerformanceQuery = z.output<typeof supplierPerformanceQuerySchema>\n\nexport const exportFormatSchema = z.object({ format: z.enum(['csv', 'xlsx']).default('csv') })\nexport type ExportFormatQuery = z.output<typeof exportFormatSchema>\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Parcelas pela condição de pagamento do fornecedor (`[30, 60, 90]` dias a partir da data base). Centavos exatos:\n * a diferença do arredondamento vai na primeira parcela, como no boleto.\n */\n\nimport { parseDecimal } from '@adatechnology/recipe-contracts'\n\nimport type { Installment } from '../purchase.types'\nimport { centsOf, fromCentsBig, money } from './money'\n\nconst DATE_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/\n\nexport function isCivilDate(value: string): boolean {\n if (!DATE_PATTERN.test(value)) return false\n const date = new Date(`${value}T00:00:00Z`)\n return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value\n}\n\nexport function addDays(date: string, days: number): string {\n const base = new Date(`${date}T00:00:00Z`)\n base.setUTCDate(base.getUTCDate() + days)\n return base.toISOString().slice(0, 10)\n}\n\n/** Data civil de um instante num fuso (`America/Sao_Paulo`). */\nexport function civilDateIn(instant: Date, timeZone: string): string {\n const parts = new Intl.DateTimeFormat('en-CA', {\n timeZone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n }).formatToParts(instant)\n const get = (type: string) => parts.find((part) => part.type === type)?.value ?? ''\n return `${get('year')}-${get('month')}-${get('day')}`\n}\n\nexport function buildInstallments(params: {\n readonly total: string\n readonly termDays: readonly number[]\n readonly baseDate: string\n}): Installment[] {\n const terms = params.termDays.length > 0 ? [...params.termDays].sort((a, b) => a - b) : [0]\n const totalCents = centsOf(parseDecimal(params.total))\n const count = BigInt(terms.length)\n const base = totalCents / count\n const first = totalCents - base * (count - 1n)\n return terms.map((days, index) => ({\n number: index + 1,\n dueDate: addDays(params.baseDate, days),\n amount: money(fromCentsBig(index === 0 ? first : base)),\n }))\n}\n\n/** `\"30/60/90\"`, `\"30 60 90\"`, `\"à vista\"` → `[30, 60, 90]` / `[0]`. `null` quando ilegível. */\nexport function parsePaymentTerms(text: string): number[] | null {\n const clean = text.trim().toLowerCase()\n if (clean === '' || clean === 'a vista' || clean === 'à vista' || clean === '0') return [0]\n const parts = clean.split(/[\\s/,;+-]+/).filter(Boolean)\n const days = parts.map((part) => Number(part))\n if (days.some((day) => !Number.isInteger(day) || day < 0 || day > 365)) return null\n return [...new Set(days)].sort((a, b) => a - b)\n}\n\nexport function formatPaymentTerms(days: readonly number[]): string {\n if (days.length === 0 || (days.length === 1 && days[0] === 0)) return 'à vista'\n return days.join('/')\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Contas de pedido e nota sobre a aritmética exata do `recipe-contracts`: nada de ponto flutuante. Linha e total\n * fecham em centavos (meio para cima); custo por unidade de estoque fica com 4 casas.\n */\n\nimport {\n add,\n compare,\n divide,\n formatDecimal,\n multiply,\n parseDecimal,\n rational,\n roundToScale,\n subtract,\n ZERO,\n type Rational,\n} from '@adatechnology/recipe-contracts'\n\nexport const MONEY_SCALE = 2\n\nexport function money(value: Rational): string {\n return formatDecimal(value, MONEY_SCALE)\n}\n\nexport function quantityText(value: Rational): string {\n return formatDecimal(value)\n}\n\nexport function sum(values: readonly Rational[]): Rational {\n return values.reduce((total, value) => add(total, value), ZERO)\n}\n\n/** `quantity × unitPrice` em centavos (a linha mostrada ao fornecedor). */\nexport function lineTotal(quantity: string, unitPrice: string): Rational {\n return parseDecimal(money(multiply(parseDecimal(quantity), parseDecimal(unitPrice))))\n}\n\n/** Centavos exatos (arredonda meio para cima antes). */\nexport function centsOf(value: Rational): bigint {\n const rounded = roundToScale(value, MONEY_SCALE)\n return (rounded.numerator * 100n) / rounded.denominator\n}\n\nexport function fromCentsBig(cents: bigint): Rational {\n return rational(cents, 100n)\n}\n\nexport function isNegative(value: Rational): boolean {\n return compare(value, ZERO) < 0\n}\n\nexport function clampToZero(value: Rational): Rational {\n return isNegative(value) ? ZERO : value\n}\n\nexport { add, compare, divide, multiply, parseDecimal, subtract, ZERO }\nexport type { Rational }\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Mesma forma dos erros dos outros módulos (`statusCode`, `code`, `publicDetails`): o filtro do `module-http`\n * reconhece pela forma.\n */\n\nexport class PurchaseError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number,\n public readonly code: string,\n public readonly details?: Record<string, unknown>,\n public readonly publicDetails?: Readonly<Record<string, unknown>>,\n ) {\n super(message)\n this.name = 'PurchaseError'\n }\n}\n\nexport const PURCHASE_ERROR_CODES = {\n DISABLED: 'PURCHASE_DISABLED',\n UNAUTHENTICATED: 'PURCHASE_UNAUTHENTICATED',\n CONFIG_MISSING: 'PURCHASE_CONFIG_MISSING',\n SUPPLIER_NOT_FOUND: 'PURCHASE_SUPPLIER_NOT_FOUND',\n SUPPLIER_INACTIVE: 'PURCHASE_SUPPLIER_INACTIVE',\n SUPPLIER_DOCUMENT_TAKEN: 'PURCHASE_SUPPLIER_DOCUMENT_TAKEN',\n SUPPLIER_IN_USE: 'PURCHASE_SUPPLIER_IN_USE',\n SUPPLIER_ITEM_NOT_FOUND: 'PURCHASE_SUPPLIER_ITEM_NOT_FOUND',\n SUPPLIER_ITEM_TAKEN: 'PURCHASE_SUPPLIER_ITEM_TAKEN',\n ITEM_NOT_FOUND: 'PURCHASE_ITEM_NOT_FOUND',\n ORDER_NOT_FOUND: 'PURCHASE_ORDER_NOT_FOUND',\n ORDER_LINE_NOT_FOUND: 'PURCHASE_ORDER_LINE_NOT_FOUND',\n INVALID_TRANSITION: 'PURCHASE_INVALID_TRANSITION',\n SELF_APPROVAL: 'PURCHASE_SELF_APPROVAL',\n RECEIPT_NOT_FOUND: 'PURCHASE_RECEIPT_NOT_FOUND',\n INVOICE_ALREADY_RECEIVED: 'PURCHASE_INVOICE_ALREADY_RECEIVED',\n INSTALLMENTS_MISMATCH: 'PURCHASE_INSTALLMENTS_MISMATCH',\n DISPATCH_UNAVAILABLE: 'PURCHASE_DISPATCH_UNAVAILABLE',\n NO_CONTACT: 'PURCHASE_SUPPLIER_NO_CONTACT',\n NFE_INVALID: 'PURCHASE_NFE_INVALID',\n REPORT_RANGE_TOO_LONG: 'PURCHASE_REPORT_RANGE_TOO_LONG',\n} as const\n\nexport class PurchaseDisabledError extends PurchaseError {\n constructor() {\n super('Compras não habilitado para a empresa.', 404, PURCHASE_ERROR_CODES.DISABLED)\n this.name = 'PurchaseDisabledError'\n }\n}\n\nexport class PurchaseUnauthenticatedError extends PurchaseError {\n constructor() {\n super('Sem empresa autenticada.', 401, PURCHASE_ERROR_CODES.UNAUTHENTICATED)\n this.name = 'PurchaseUnauthenticatedError'\n }\n}\n\nexport class PurchaseConfigMissingError extends PurchaseError {\n constructor(field: string) {\n super(`Configuração ausente ou inválida: ${field}.`, 500, PURCHASE_ERROR_CODES.CONFIG_MISSING, { field })\n this.name = 'PurchaseConfigMissingError'\n }\n}\n\nexport class SupplierNotFoundError extends PurchaseError {\n constructor(supplierId: string) {\n super('Fornecedor não encontrado.', 404, PURCHASE_ERROR_CODES.SUPPLIER_NOT_FOUND, { supplierId })\n this.name = 'SupplierNotFoundError'\n }\n}\n\nexport class SupplierInactiveError extends PurchaseError {\n constructor(supplierId: string) {\n super('Fornecedor desativado.', 422, PURCHASE_ERROR_CODES.SUPPLIER_INACTIVE, { supplierId })\n this.name = 'SupplierInactiveError'\n }\n}\n\nexport class SupplierDocumentTakenError extends PurchaseError {\n constructor() {\n super('Já existe fornecedor com este documento.', 409, PURCHASE_ERROR_CODES.SUPPLIER_DOCUMENT_TAKEN)\n this.name = 'SupplierDocumentTakenError'\n }\n}\n\nexport class SupplierInUseError extends PurchaseError {\n constructor(supplierId: string) {\n super(\n 'Fornecedor com pedidos ou recebimentos: desative em vez de excluir.',\n 409,\n PURCHASE_ERROR_CODES.SUPPLIER_IN_USE,\n {\n supplierId,\n },\n )\n this.name = 'SupplierInUseError'\n }\n}\n\nexport class SupplierItemNotFoundError extends PurchaseError {\n constructor(supplierItemId: string) {\n super('Item do fornecedor não encontrado.', 404, PURCHASE_ERROR_CODES.SUPPLIER_ITEM_NOT_FOUND, { supplierItemId })\n this.name = 'SupplierItemNotFoundError'\n }\n}\n\nexport class SupplierItemTakenError extends PurchaseError {\n constructor() {\n super(\n 'Este fornecedor já tem um item com este código ou ligado a este item do catálogo.',\n 409,\n PURCHASE_ERROR_CODES.SUPPLIER_ITEM_TAKEN,\n )\n this.name = 'SupplierItemTakenError'\n }\n}\n\nexport class PurchaseItemNotFoundError extends PurchaseError {\n constructor(itemRef: string) {\n super('Item não encontrado no catálogo.', 404, PURCHASE_ERROR_CODES.ITEM_NOT_FOUND, { itemRef }, { itemRef })\n this.name = 'PurchaseItemNotFoundError'\n }\n}\n\nexport class OrderNotFoundError extends PurchaseError {\n constructor(orderId: string) {\n super('Pedido de compra não encontrado.', 404, PURCHASE_ERROR_CODES.ORDER_NOT_FOUND, { orderId })\n this.name = 'OrderNotFoundError'\n }\n}\n\nexport class OrderLineNotFoundError extends PurchaseError {\n constructor(orderLineId: string) {\n super(\n 'Linha do pedido não encontrada.',\n 422,\n PURCHASE_ERROR_CODES.ORDER_LINE_NOT_FOUND,\n { orderLineId },\n { orderLineId },\n )\n this.name = 'OrderLineNotFoundError'\n }\n}\n\nexport class InvalidOrderTransitionError extends PurchaseError {\n constructor(params: { readonly status: string; readonly action: string }) {\n super('Ação não permitida no status atual do pedido.', 409, PURCHASE_ERROR_CODES.INVALID_TRANSITION, params, params)\n this.name = 'InvalidOrderTransitionError'\n }\n}\n\nexport class SelfApprovalError extends PurchaseError {\n constructor() {\n super('Quem enviou o pedido para aprovação não pode aprová-lo.', 403, PURCHASE_ERROR_CODES.SELF_APPROVAL)\n this.name = 'SelfApprovalError'\n }\n}\n\nexport class ReceiptNotFoundError extends PurchaseError {\n constructor(receiptId: string) {\n super('Recebimento não encontrado.', 404, PURCHASE_ERROR_CODES.RECEIPT_NOT_FOUND, { receiptId })\n this.name = 'ReceiptNotFoundError'\n }\n}\n\nexport class InvoiceAlreadyReceivedError extends PurchaseError {\n constructor(receiptId: string) {\n super(\n 'Esta nota já foi recebida.',\n 409,\n PURCHASE_ERROR_CODES.INVOICE_ALREADY_RECEIVED,\n { receiptId },\n { receiptId },\n )\n this.name = 'InvoiceAlreadyReceivedError'\n }\n}\n\nexport class InstallmentsMismatchError extends PurchaseError {\n constructor(params: { readonly total: string; readonly installments: string }) {\n super(\n 'A soma das parcelas não fecha com o total do recebimento.',\n 422,\n PURCHASE_ERROR_CODES.INSTALLMENTS_MISMATCH,\n params,\n params,\n )\n this.name = 'InstallmentsMismatchError'\n }\n}\n\nexport class DispatchUnavailableError extends PurchaseError {\n constructor(channel: string) {\n super(\n 'Envio por este canal não está configurado.',\n 422,\n PURCHASE_ERROR_CODES.DISPATCH_UNAVAILABLE,\n { channel },\n { channel },\n )\n this.name = 'DispatchUnavailableError'\n }\n}\n\nexport class SupplierNoContactError extends PurchaseError {\n constructor(channel: string) {\n super('Fornecedor sem contato para este canal.', 422, PURCHASE_ERROR_CODES.NO_CONTACT, { channel }, { channel })\n this.name = 'SupplierNoContactError'\n }\n}\n\nexport class NfeInvalidError extends PurchaseError {\n constructor(reason: string) {\n super('XML de NF-e inválido.', 422, PURCHASE_ERROR_CODES.NFE_INVALID, { reason }, { reason })\n this.name = 'NfeInvalidError'\n }\n}\n\nexport class ReportRangeTooLongError extends PurchaseError {\n constructor(maxDays: number) {\n super(\n 'Período longo demais para o relatório.',\n 422,\n PURCHASE_ERROR_CODES.REPORT_RANGE_TOO_LONG,\n { maxDays },\n { maxDays },\n )\n this.name = 'ReportRangeTooLongError'\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Portas que o host implementa. Todas opcionais: sem nenhuma, Compras funciona sozinho (itens livres, recebimento\n * só registrado, sem conta a pagar, envio por \"copiar texto\"). Cada porta liga um outro módulo sem que este pacote\n * dependa dele; a implementação natural de cada uma está no comentário.\n */\n\nimport type { RecipeUnit } from '@adatechnology/recipe-contracts'\n\nimport type { DispatchChannel, Installment, OrderStatus } from './purchase.types'\nimport type { DemandRow } from './rules/suggestion'\n\nexport type LogMeta = Readonly<Record<string, unknown>>\n\nexport interface LoggerPort {\n debug(message: string, meta?: LogMeta): void\n info(message: string, meta?: LogMeta): void\n warn(message: string, meta?: LogMeta): void\n error(message: string, meta?: LogMeta): void\n}\n\nexport interface ClockPort {\n now(): Date\n}\n\nexport type CatalogItem = { readonly itemRef: string; readonly name: string; readonly unit: RecipeUnit }\n\n/**\n * Itens do catálogo ligado. Com a porta, `itemRef` de linha e de item do fornecedor é conferido (de outra empresa\n * = 404) e o nome/unidade vêm de lá. Sem ela, `itemRef` é aceito como veio (opaco).\n * Natural: `recipeModule` (`ingredients.findByIds`) ou o cadastro de produtos do host.\n */\nexport interface ItemCatalogPort {\n findItems(params: {\n readonly companyId: string\n readonly itemRefs: readonly string[]\n }): Promise<readonly CatalogItem[]>\n}\n\n/**\n * Entrada no estoque, uma chamada por linha recebida com `itemRef` e unidade de estoque. Precisa ser idempotente por\n * `sourceKey`: o módulo reenvia a mesma chave quando reprocessa um recebimento que falhou.\n * Natural: `stockModule.useCases.receiveBatch.execute({ ..., input: { ..., sourceKey } })`.\n */\nexport interface StockReceiptPort {\n receive(params: {\n readonly companyId: string\n readonly actorId?: string\n readonly sourceKey: string\n readonly itemRef: string\n /** Em unidade de estoque (já convertida da unidade de compra). */\n readonly quantity: string\n readonly unit: RecipeUnit\n readonly batchCode: string\n readonly costPerUnit: string | null\n /** ISO com fuso (fim do dia da validade) ou `null`. */\n readonly expiresAt: string | null\n readonly supplierId: string\n readonly reason: string\n }): Promise<void>\n}\n\n/**\n * Necessidade por item para a sugestão de pedido. Natural: os níveis do `stock-module` (saldo e mínimo) somados à\n * lista de compras do `recipe-module` (ficha técnica × pedidos/reservas previstos).\n */\nexport interface DemandSourcePort {\n getDemand(params: { readonly companyId: string }): Promise<readonly DemandRow[]>\n}\n\nexport type PayableRequest = {\n readonly companyId: string\n readonly actorId?: string\n /** Idempotência: `purchase-receipt:<receiptId>`. Reenviar a mesma chave não cria outra conta. */\n readonly sourceRef: string\n readonly supplier: { readonly id: string; readonly name: string; readonly document: string | null }\n readonly description: string\n readonly total: string\n readonly installments: readonly Installment[]\n readonly invoiceNumber: string | null\n readonly invoiceKey: string | null\n readonly receiptId: string\n readonly orderId: string | null\n}\n\n/**\n * Conta a pagar do recebimento. Natural: `expense-module` (`createExpense` com `installments` e `sourceRef`, 0.2+).\n * Devolve a referência da conta, guardada no recebimento.\n */\nexport interface PayablesPort {\n createPayable(params: PayableRequest): Promise<{ readonly payableRef: string }>\n}\n\n/**\n * Envio do pedido ao fornecedor. Natural: `meta-whatsapp-module` (mensagem de texto; fora da janela de 24 h, um\n * modelo aprovado) e `email-provider`. Sem a porta, só o canal `manual` (o painel mostra o texto para copiar).\n */\nexport interface OrderDispatchPort {\n readonly channels: readonly DispatchChannel[]\n dispatch(params: {\n readonly companyId: string\n readonly actorId?: string\n readonly channel: DispatchChannel\n readonly orderId: string\n readonly orderNumber: number\n readonly to: { readonly name: string; readonly phone: string | null; readonly email: string | null }\n readonly text: string\n }): Promise<{ readonly messageRef?: string }>\n}\n\nexport type ReceiptPostedLine = {\n readonly itemRef: string | null\n readonly itemName: string\n readonly stockUnit: RecipeUnit | null\n /** Em unidade de estoque. */\n readonly stockQuantity: string\n readonly landedUnitCost: string | null\n /** Média ponderada do item na janela da configuração, já contando este recebimento. */\n readonly averageCost: string | null\n}\n\nexport type PurchaseHooks = {\n readonly onOrderStatusChanged?: (event: {\n readonly companyId: string\n readonly actorId?: string\n readonly orderId: string\n readonly number: number\n readonly from: OrderStatus\n readonly to: OrderStatus\n }) => void | Promise<void>\n /** Pedido acima do limite esperando aprovação (avisar quem aprova). */\n readonly onApprovalRequested?: (event: {\n readonly companyId: string\n readonly orderId: string\n readonly number: number\n readonly total: string\n readonly requestedBy?: string\n }) => void | Promise<void>\n /**\n * Depois do recebimento gravado. Natural, com ficha técnica: atualizar o `costPerUnit` do insumo\n * (`landedUnitCost` ou `averageCost`, política do host) para o custo do prato acompanhar a compra.\n */\n readonly onReceiptPosted?: (event: {\n readonly companyId: string\n readonly actorId?: string\n readonly receiptId: string\n readonly orderId: string | null\n readonly supplierId: string\n readonly total: string\n readonly lines: readonly ReceiptPostedLine[]\n }) => void | Promise<void>\n /** Pedidos atrasados, por empresa, a cada rodada de `scanLateOrders`. */\n readonly onOrdersLate?: (event: {\n readonly companyId: string\n readonly orders: readonly {\n readonly orderId: string\n readonly number: number\n readonly supplierId: string\n readonly supplierName: string | null\n readonly expectedAt: string\n readonly daysLate: number\n }[]\n }) => void | Promise<void>\n}\n\nexport const DEFAULT_PURCHASE_SCOPES = {\n read: ['purchase:read'],\n write: ['purchase:write'],\n approve: ['purchase:approve'],\n service: ['purchase:service'],\n} as const\n\nexport type PurchaseScopes = {\n readonly read?: readonly string[]\n readonly write?: readonly string[]\n readonly approve?: readonly string[]\n readonly service?: readonly string[]\n}\n\nexport type PurchaseModuleConfig = {\n readonly scopes?: PurchaseScopes\n /** Liga Compras por empresa. Ausente: ligado para todas. Desligado: rotas 404. */\n readonly isEnabledForCompany?: (companyId: string) => boolean | Promise<boolean>\n /**\n * Total (2 casas) acima do qual o pedido precisa de aprovação, por empresa. `null`/ausente: nunca precisa.\n * Aprovar exige o escopo `approve`, e quem submeteu não aprova o próprio pedido.\n */\n readonly approvalThresholdFor?: (companyId: string) => string | null | Promise<string | null>\n /** Nome que vai no texto do pedido ao fornecedor. */\n readonly companyNameFor?: (companyId: string) => string | Promise<string>\n /** Fuso das datas civis (previsão, vencimento, atraso). Padrão: `America/Sao_Paulo`. */\n readonly timeZone?: string\n /** Janela da média ponderada de custo. Padrão: 90 dias. */\n readonly averageCostWindowDays?: number\n /** Diferença de preço tolerada antes de marcar divergência, em centavos. Padrão: 0. */\n readonly priceToleranceCents?: number\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Máquina de estados do pedido. Uma regra só, usada pelo módulo (para recusar) e pela tela (para esconder botão).\n *\n * draft ─submit─▶ pending_approval ─approve─▶ approved ─send─▶ sent\n * ▲ │ reject │ │\n * └─────────────────┘ └──receive──────┴─▶ partially_received ─▶ received\n * cancel: até o primeiro recebimento · close: encerra o saldo de um pedido recebido em parte\n */\n\nimport { ORDER_STATUS, type OrderStatus } from '../purchase.types'\n\nexport const ORDER_ACTION = {\n EDIT: 'edit',\n SUBMIT: 'submit',\n APPROVE: 'approve',\n REJECT: 'reject',\n SEND: 'send',\n RECEIVE: 'receive',\n CLOSE: 'close',\n CANCEL: 'cancel',\n} as const\nexport type OrderAction = (typeof ORDER_ACTION)[keyof typeof ORDER_ACTION]\n\nconst ALLOWED: Readonly<Record<OrderAction, readonly OrderStatus[]>> = {\n edit: [ORDER_STATUS.DRAFT],\n submit: [ORDER_STATUS.DRAFT],\n approve: [ORDER_STATUS.PENDING_APPROVAL],\n reject: [ORDER_STATUS.PENDING_APPROVAL],\n // Reenviar um pedido já enviado é permitido (fornecedor não recebeu, mudou de canal).\n send: [ORDER_STATUS.APPROVED, ORDER_STATUS.SENT],\n receive: [ORDER_STATUS.APPROVED, ORDER_STATUS.SENT, ORDER_STATUS.PARTIALLY_RECEIVED],\n close: [ORDER_STATUS.PARTIALLY_RECEIVED],\n cancel: [ORDER_STATUS.DRAFT, ORDER_STATUS.PENDING_APPROVAL, ORDER_STATUS.APPROVED, ORDER_STATUS.SENT],\n}\n\nexport function canPerform(status: OrderStatus, action: OrderAction): boolean {\n return ALLOWED[action].includes(status)\n}\n\nexport function allowedActions(status: OrderStatus): OrderAction[] {\n return (Object.keys(ALLOWED) as OrderAction[]).filter((action) => canPerform(status, action))\n}\n\n/** Depois do `send`, um pedido recebido em parte continua `partially_received`. */\nexport function statusAfterSend(status: OrderStatus): OrderStatus {\n return status === ORDER_STATUS.PARTIALLY_RECEIVED ? status : ORDER_STATUS.SENT\n}\n\n/** Total acima do limite precisa de aprovação. Limite ausente = nunca precisa. */\nexport function requiresApproval(params: {\n readonly totalCents: bigint\n readonly thresholdCents: bigint | null\n}): boolean {\n return params.thresholdCents !== null && params.totalCents > params.thresholdCents\n}\n\n/** Atrasado: aberto, com previsão, e a previsão já passou (comparação de data civil `aaaa-mm-dd`). */\nexport function isOrderLate(params: {\n readonly status: OrderStatus\n readonly expectedAt: string | null\n readonly today: string\n}): boolean {\n if (!params.expectedAt) return false\n if (\n params.status !== ORDER_STATUS.APPROVED &&\n params.status !== ORDER_STATUS.SENT &&\n params.status !== ORDER_STATUS.PARTIALLY_RECEIVED\n )\n return false\n return params.expectedAt < params.today\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Totais do pedido e da nota, rateio de frete e desconto e progresso do recebimento.\n */\n\nimport {\n divide,\n formatDecimal,\n multiply,\n parseDecimal,\n rational,\n subtract,\n ZERO,\n type Rational,\n} from '@adatechnology/recipe-contracts'\n\nimport { DIVERGENCE, ORDER_STATUS, type Divergence, type OrderStatus } from '../purchase.types'\nimport { centsOf, clampToZero, compare, fromCentsBig, lineTotal, money, quantityText, sum } from './money'\n\nexport type PricedLine = { readonly quantity: string; readonly unitPrice: string }\n\nexport type Totals = {\n readonly subtotal: string\n readonly freight: string\n readonly discount: string\n readonly total: string\n}\n\n/** Desconto maior que subtotal + frete não deixa total negativo (fica zero). */\nexport function computeTotals(params: {\n readonly lines: readonly PricedLine[]\n readonly freight?: string\n readonly discount?: string\n}): Totals {\n const subtotal = sum(params.lines.map((line) => lineTotal(line.quantity, line.unitPrice)))\n const freight = parseDecimal(params.freight ?? '0')\n const discount = parseDecimal(params.discount ?? '0')\n const total = clampToZero(subtract(add2(subtotal, freight), discount))\n return { subtotal: money(subtotal), freight: money(freight), discount: money(discount), total: money(total) }\n}\n\nfunction add2(left: Rational, right: Rational): Rational {\n return sum([left, right])\n}\n\n/**\n * Frete menos desconto distribuído pelas linhas na proporção do valor de cada uma, em centavos exatos: a soma do\n * rateio é igual ao líquido (o resto vai para as maiores frações, maior resto). Devolve o valor rateado por linha.\n */\nexport function allocateExtras(params: {\n readonly lineTotals: readonly string[]\n readonly freight: string\n readonly discount: string\n}): string[] {\n const totals = params.lineTotals.map((value) => centsOf(parseDecimal(value)))\n const base = totals.reduce((acc, value) => acc + value, 0n)\n const net = centsOf(parseDecimal(params.freight)) - centsOf(parseDecimal(params.discount))\n if (totals.length === 0) return []\n if (base === 0n || net === 0n) {\n // Sem valor para ponderar: divide igual entre as linhas.\n if (net === 0n) return totals.map(() => '0.00')\n return splitEvenly(net, totals.length).map((cents) => money(fromCentsBig(cents)))\n }\n const sign = net < 0n ? -1n : 1n\n const absolute = net * sign\n const shares = totals.map((value, index) => {\n const exact = absolute * value\n return { index, floor: exact / base, remainder: exact % base }\n })\n let left = absolute - shares.reduce((acc, share) => acc + share.floor, 0n)\n const byRemainder = [...shares].sort((a, b) =>\n b.remainder > a.remainder ? 1 : b.remainder < a.remainder ? -1 : a.index - b.index,\n )\n const extra = new Map<number, bigint>()\n for (const share of byRemainder) {\n if (left <= 0n) break\n extra.set(share.index, 1n)\n left -= 1n\n }\n return shares.map((share) => money(fromCentsBig((share.floor + (extra.get(share.index) ?? 0n)) * sign)))\n}\n\nfunction splitEvenly(cents: bigint, parts: number): bigint[] {\n const count = BigInt(parts)\n const sign = cents < 0n ? -1n : 1n\n const absolute = cents * sign\n const base = absolute / count\n const rest = absolute % count\n return Array.from({ length: parts }, (_, index) => (base + (BigInt(index) < rest ? 1n : 0n)) * sign)\n}\n\n/**\n * Custo por unidade de estoque: (valor da linha + rateio) ÷ (quantidade × unidades por compra). 4 casas.\n * `null` quando a quantidade em estoque é zero.\n */\nexport function landedUnitCost(params: {\n readonly lineTotal: string\n readonly allocated: string\n readonly quantity: string\n readonly unitsPerPurchase: string\n}): string | null {\n const stockQuantity = multiply(parseDecimal(params.quantity), parseDecimal(params.unitsPerPurchase))\n if (compare(stockQuantity, ZERO) <= 0) return null\n const value = clampToZero(sum([parseDecimal(params.lineTotal), parseDecimal(params.allocated)]))\n return formatDecimal(divide(value, stockQuantity))\n}\n\n/** Quantidade em unidade de estoque (`2 cx × 12` = `24`). */\nexport function toStockQuantity(quantity: string, unitsPerPurchase: string): string {\n return quantityText(multiply(parseDecimal(quantity), parseDecimal(unitsPerPurchase)))\n}\n\nexport function pendingQuantity(params: {\n readonly quantity: string\n readonly receivedQuantity: string\n readonly canceledQuantity: string\n}): string {\n const pending = subtract(\n subtract(parseDecimal(params.quantity), parseDecimal(params.receivedQuantity)),\n parseDecimal(params.canceledQuantity),\n )\n return quantityText(clampToZero(pending))\n}\n\n/** Status depois de um recebimento: tudo chegou (ou foi encerrado) = `received`. */\nexport function statusAfterReceipt(\n lines: readonly { readonly quantity: string; readonly receivedQuantity: string; readonly canceledQuantity: string }[],\n): OrderStatus {\n const anyPending = lines.some((line) => compare(parseDecimal(pendingQuantity(line)), ZERO) > 0)\n return anyPending ? ORDER_STATUS.PARTIALLY_RECEIVED : ORDER_STATUS.RECEIVED\n}\n\n/** Diferença entre o pedido e o que chegou. Tolerância de preço em centavos (padrão: zero). */\nexport function divergenceOf(params: {\n readonly pendingQuantity: string | null\n readonly receivedQuantity: string\n readonly orderedPrice: string | null\n readonly receivedPrice: string\n readonly priceToleranceCents?: bigint\n}): Divergence {\n const quantity =\n params.pendingQuantity !== null &&\n compare(parseDecimal(params.receivedQuantity), parseDecimal(params.pendingQuantity)) > 0\n const tolerance = params.priceToleranceCents ?? 0n\n let price = false\n if (params.orderedPrice !== null) {\n const ordered = parseDecimal(params.orderedPrice)\n const received = parseDecimal(params.receivedPrice)\n const delta = centsOf(subtract(received, ordered))\n price = (delta < 0n ? -delta : delta) > tolerance\n }\n if (quantity && price) return DIVERGENCE.BOTH\n if (quantity) return DIVERGENCE.QUANTITY\n if (price) return DIVERGENCE.PRICE\n return DIVERGENCE.NONE\n}\n\n/** Média ponderada pela quantidade (custo × quantidade ÷ quantidade). `null` sem nada para ponderar. */\nexport function weightedAverageCost(\n points: readonly { readonly cost: string; readonly quantity: string }[],\n): string | null {\n const weight = sum(points.map((point) => parseDecimal(point.quantity)))\n if (compare(weight, ZERO) <= 0) return null\n const value = sum(points.map((point) => multiply(parseDecimal(point.cost), parseDecimal(point.quantity))))\n return formatDecimal(divide(value, weight))\n}\n\nexport const UNIT_FACTOR_ONE = formatDecimal(rational(1n))\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Sugestão de pedido: falta = max(necessidade − saldo, mínimo − saldo) − a caminho. A falta vira unidades de compra\n * do fornecedor preferido, arredondadas para cima (não se compra meia caixa), e o resultado é agrupado por fornecedor.\n */\n\nimport {\n divide,\n maximum,\n multiply,\n parseDecimal,\n ROUNDING,\n roundToScale,\n subtract,\n ZERO,\n type RecipeUnit,\n} from '@adatechnology/recipe-contracts'\n\nimport type { SuggestionGroup, SuggestionLine } from '../purchase.types'\nimport { centsOf, clampToZero, compare, lineTotal, money, quantityText, sum } from './money'\n\nexport type DemandRow = {\n readonly itemRef: string\n readonly itemName: string\n readonly stockUnit: RecipeUnit\n /** Necessidade prevista (ficha técnica × reservas/pedidos); `'0'` quando só o mínimo importa. */\n readonly neededQuantity: string\n readonly onHandQuantity: string | null\n readonly minimumQuantity: string | null\n}\n\nexport type SuggestionSupplierItem = {\n readonly id: string\n readonly supplierId: string\n readonly itemRef: string | null\n readonly purchaseUnit: string\n readonly unitsPerPurchase: string\n readonly lastPrice: string | null\n readonly priority: number\n readonly isActive: boolean\n}\n\nexport type SuggestionSupplier = {\n readonly id: string\n readonly name: string\n readonly minimumOrderAmount: string | null\n readonly isActive: boolean\n}\n\nexport function shortageOf(row: DemandRow & { readonly incomingQuantity: string }): string {\n const onHand = clampToZero(parseDecimal(row.onHandQuantity ?? '0'))\n const byNeed = subtract(parseDecimal(row.neededQuantity), onHand)\n const byMinimum = row.minimumQuantity === null ? ZERO : subtract(parseDecimal(row.minimumQuantity), onHand)\n const raw = subtract(maximum(byNeed, byMinimum), parseDecimal(row.incomingQuantity))\n return quantityText(clampToZero(raw))\n}\n\n/** Unidades de compra para cobrir a falta: `ceil(falta ÷ unidadesPorCompra)`. */\nexport function packsFor(shortage: string, unitsPerPurchase: string): string {\n const packs = divide(parseDecimal(shortage), parseDecimal(unitsPerPurchase))\n return quantityText(roundToScale(packs, 0, ROUNDING.UP))\n}\n\n/** Empate de prioridade: o mais barato por unidade de estoque; sem preço vai por último. */\nfunction comparePerStockUnit(left: SuggestionSupplierItem, right: SuggestionSupplierItem): number {\n if (left.lastPrice === null) return right.lastPrice === null ? 0 : 1\n if (right.lastPrice === null) return -1\n const leftCost = divide(parseDecimal(left.lastPrice), parseDecimal(left.unitsPerPurchase))\n const rightCost = divide(parseDecimal(right.lastPrice), parseDecimal(right.unitsPerPurchase))\n return compare(leftCost, rightCost)\n}\n\nexport function buildSuggestion(params: {\n readonly demand: readonly DemandRow[]\n readonly incoming: ReadonlyMap<string, string>\n readonly supplierItems: readonly SuggestionSupplierItem[]\n readonly suppliers: ReadonlyMap<string, SuggestionSupplier>\n /** Só este fornecedor (sugestão para um pedido já aberto). */\n readonly supplierId?: string\n}): SuggestionGroup[] {\n const groups = new Map<string | null, SuggestionLine[]>()\n for (const row of params.demand) {\n const incomingQuantity = params.incoming.get(row.itemRef) ?? '0'\n const shortage = shortageOf({ ...row, incomingQuantity })\n if (compare(parseDecimal(shortage), ZERO) <= 0) continue\n const candidates = params.supplierItems\n .filter(\n (item) =>\n item.itemRef === row.itemRef &&\n item.isActive &&\n params.suppliers.get(item.supplierId)?.isActive === true &&\n (params.supplierId === undefined || item.supplierId === params.supplierId),\n )\n .sort((left, right) => left.priority - right.priority || comparePerStockUnit(left, right))\n const chosen = candidates[0]\n if (!chosen && params.supplierId !== undefined) continue\n const suggested = chosen ? packsFor(shortage, chosen.unitsPerPurchase) : null\n const line: SuggestionLine = {\n itemRef: row.itemRef,\n itemName: row.itemName,\n stockUnit: row.stockUnit,\n neededQuantity: quantityText(parseDecimal(row.neededQuantity)),\n onHandQuantity: row.onHandQuantity === null ? null : quantityText(parseDecimal(row.onHandQuantity)),\n incomingQuantity: quantityText(parseDecimal(incomingQuantity)),\n minimumQuantity: row.minimumQuantity === null ? null : quantityText(parseDecimal(row.minimumQuantity)),\n shortageQuantity: shortage,\n supplierItemId: chosen?.id ?? null,\n purchaseUnit: chosen?.purchaseUnit ?? null,\n unitsPerPurchase: chosen ? quantityText(parseDecimal(chosen.unitsPerPurchase)) : null,\n suggestedQuantity: suggested,\n unitPrice: chosen?.lastPrice ? quantityText(parseDecimal(chosen.lastPrice)) : null,\n estimatedTotal: chosen?.lastPrice && suggested ? money(lineTotal(suggested, chosen.lastPrice)) : null,\n }\n const key = chosen?.supplierId ?? null\n groups.set(key, [...(groups.get(key) ?? []), line])\n }\n return [...groups.entries()]\n .map(([supplierId, lines]) => {\n const supplier = supplierId ? params.suppliers.get(supplierId) : undefined\n const estimated = sum(lines.map((line) => parseDecimal(line.estimatedTotal ?? '0')))\n const minimum = supplier?.minimumOrderAmount ? parseDecimal(supplier.minimumOrderAmount) : null\n return {\n supplierId,\n supplierName: supplier?.name ?? null,\n lines: lines.sort((a, b) => a.itemName.localeCompare(b.itemName, 'pt-BR')),\n estimatedTotal: money(estimated),\n belowMinimumOrder: minimum !== null && centsOf(estimated) < centsOf(minimum),\n }\n })\n .sort((left, right) => {\n if (left.supplierId === null) return 1\n if (right.supplierId === null) return -1\n return (left.supplierName ?? '').localeCompare(right.supplierName ?? '', 'pt-BR')\n })\n}\n\n/** Para mostrar a falta em unidade de compra na tela: `quantidade × unidadesPorCompra`. */\nexport function stockQuantityOf(quantity: string, unitsPerPurchase: string): string {\n return quantityText(multiply(parseDecimal(quantity), parseDecimal(unitsPerPurchase)))\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Texto do pedido para o fornecedor (WhatsApp ou copiar e colar). Sem preço por padrão: o combinado fica no\n * sistema, o fornecedor confirma quantidade e entrega.\n */\n\nimport { formatDecimal, parseDecimal } from '@adatechnology/recipe-contracts'\n\nimport { formatPaymentTerms } from './schedule'\n\nexport type OrderMessageInput = {\n readonly companyName: string\n readonly number: number\n readonly supplierName: string\n readonly expectedAt: string | null\n readonly paymentTermDays: readonly number[]\n readonly notes: string\n readonly total: string\n readonly lines: readonly {\n readonly itemName: string\n readonly supplierSku: string | null\n readonly quantity: string\n readonly purchaseUnit: string\n readonly unitPrice: string\n }[]\n}\n\n/** `12.5000` → `12,5`; `3.0000` → `3`. */\nexport function formatQuantityPt(value: string): string {\n const [whole, fraction = ''] = value.split('.')\n const trimmed = fraction.replace(/0+$/, '')\n return trimmed ? `${whole},${trimmed}` : (whole ?? value)\n}\n\nexport function formatMoneyPt(value: string): string {\n const fixed = formatDecimal(parseDecimal(value), 2)\n const [whole = '0', fraction = '00'] = fixed.split('.')\n return `R$ ${whole.replace(/\\B(?=(\\d{3})+(?!\\d))/g, '.')},${fraction}`\n}\n\nfunction formatDatePt(date: string): string {\n const [year, month, day] = date.split('-')\n return `${day}/${month}/${year}`\n}\n\nexport function buildOrderMessage(input: OrderMessageInput, options: { readonly withPrices?: boolean } = {}): string {\n const header = [`*Pedido de compra nº ${input.number}* — ${input.companyName}`, `Fornecedor: ${input.supplierName}`]\n const lines = input.lines.map((line) => {\n const sku = line.supplierSku ? ` (cód. ${line.supplierSku})` : ''\n const price = options.withPrices ? ` — ${formatMoneyPt(line.unitPrice)}/${line.purchaseUnit}` : ''\n return `• ${formatQuantityPt(line.quantity)} ${line.purchaseUnit} — ${line.itemName}${sku}${price}`\n })\n const footer: string[] = []\n if (input.expectedAt) footer.push(`Entrega: ${formatDatePt(input.expectedAt)}`)\n footer.push(`Pagamento: ${formatPaymentTerms(input.paymentTermDays)}`)\n if (options.withPrices) footer.push(`Total: ${formatMoneyPt(input.total)}`)\n if (input.notes.trim()) footer.push(`Obs.: ${input.notes.trim()}`)\n footer.push('Por favor, confirme o recebimento deste pedido.')\n return [...header, '', ...lines, '', ...footer].join('\\n')\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Lê o XML de uma NF-e modelo 55 recebida (`nfeProc` ou `NFe` sozinha) e devolve o que o recebimento precisa:\n * emitente, número, chave, itens (código do fornecedor, quantidade, unidade, preço, lote e validade do `rastro`),\n * frete, desconto e duplicatas. Não valida assinatura nem consulta a SEFAZ: é leitura para preencher a conferência.\n */\n\nimport { parseDecimal } from '@adatechnology/recipe-contracts'\n\nimport { money, quantityText } from '../rules/money'\nimport { child, childrenOf, find, parseXml, textOf, XmlParseError, type XmlElement } from './xml'\n\nexport type NfeItem = {\n /** `nItem` da nota (1…990). */\n readonly itemNumber: number\n readonly supplierSku: string\n readonly ean: string | null\n readonly description: string\n readonly ncm: string | null\n readonly cfop: string | null\n /** Unidade comercial (`CX`, `UN`, `KG`), como veio. */\n readonly unit: string\n readonly quantity: string\n readonly unitPrice: string\n readonly total: string\n readonly discount: string\n readonly freight: string\n readonly batches: readonly {\n readonly batchCode: string\n readonly quantity: string\n readonly expiresAt: string | null\n }[]\n}\n\nexport type NfeInstallment = { readonly number: string; readonly dueDate: string; readonly amount: string }\n\nexport type ParsedNfe = {\n readonly accessKey: string\n readonly number: string\n readonly series: string | null\n /** ISO com fuso, como na nota. */\n readonly issuedAt: string | null\n readonly issuer: { readonly document: string | null; readonly name: string; readonly tradeName: string | null }\n readonly recipientDocument: string | null\n readonly items: readonly NfeItem[]\n readonly totals: {\n readonly products: string\n readonly freight: string\n readonly discount: string\n readonly other: string\n readonly total: string\n }\n readonly installments: readonly NfeInstallment[]\n}\n\nexport class NfeParseError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'NfeParseError'\n }\n}\n\n/** Valor da nota (`10.50`, `3.0000`) → texto decimal normalizado; aceita até 10 casas e arredonda para 4. */\nfunction decimalOf(text: string | null, fallback = '0'): string {\n const value = (text ?? fallback).trim()\n if (!/^\\d+(\\.\\d+)?$/.test(value)) throw new NfeParseError(`valor inválido: ${value}`)\n const [whole = '0', fraction = ''] = value.split('.')\n const rounded = fraction.length > 4 ? roundFraction(whole, fraction) : `${whole}.${fraction || '0'}`\n return quantityText(parseDecimal(rounded))\n}\n\nfunction roundFraction(whole: string, fraction: string): string {\n const scaled = BigInt(whole + fraction.slice(0, 4))\n const next = Number(fraction[4] ?? '0')\n const value = next >= 5 ? scaled + 1n : scaled\n const text = value.toString().padStart(5, '0')\n return `${text.slice(0, -4)}.${text.slice(-4)}`\n}\n\nfunction moneyOf(text: string | null): string {\n return money(parseDecimal(decimalOf(text)))\n}\n\nfunction dateOnly(text: string | null): string | null {\n if (!text) return null\n const match = /^(\\d{4}-\\d{2}-\\d{2})/.exec(text.trim())\n return match?.[1] ?? null\n}\n\nfunction parseItem(det: XmlElement): NfeItem {\n const prod = child(det, 'prod')\n if (!prod) throw new NfeParseError('item sem prod')\n const itemNumber = Number(det.attributes.nItem ?? '0')\n const ean = textOf(prod, 'cEAN')\n const batches = childrenOf(prod, 'rastro').map((rastro) => ({\n batchCode: textOf(rastro, 'nLote') ?? '',\n quantity: decimalOf(textOf(rastro, 'qLote')),\n expiresAt: dateOnly(textOf(rastro, 'dVal')),\n }))\n // Medicamento usa `med` sem `rastro` em versões antigas; o lote fica sem informação.\n return {\n itemNumber: Number.isInteger(itemNumber) ? itemNumber : 0,\n supplierSku: textOf(prod, 'cProd') ?? '',\n ean: ean && ean.toUpperCase() !== 'SEM GTIN' ? ean : null,\n description: textOf(prod, 'xProd') ?? '',\n ncm: textOf(prod, 'NCM'),\n cfop: textOf(prod, 'CFOP'),\n unit: (textOf(prod, 'uCom') ?? 'UN').toUpperCase(),\n quantity: decimalOf(textOf(prod, 'qCom')),\n unitPrice: decimalOf(textOf(prod, 'vUnCom')),\n total: moneyOf(textOf(prod, 'vProd')),\n discount: moneyOf(textOf(prod, 'vDesc')),\n freight: moneyOf(textOf(prod, 'vFrete')),\n batches: batches.filter((batch) => batch.batchCode !== ''),\n }\n}\n\nexport function parseNfeXml(xml: string): ParsedNfe {\n let root: XmlElement\n try {\n root = parseXml(xml)\n } catch (error) {\n throw new NfeParseError(error instanceof XmlParseError ? error.message : 'XML ilegível')\n }\n const infNFe = find(root, 'infNFe')\n if (!infNFe) throw new NfeParseError('não é uma NF-e (sem infNFe)')\n const ide = child(infNFe, 'ide')\n const model = textOf(ide, 'mod')\n if (model && model !== '55' && model !== '65') throw new NfeParseError(`modelo ${model} não é NF-e`)\n const idAttribute = infNFe.attributes.Id ?? ''\n const fromProtocol = find(root, 'chNFe')?.text.trim() ?? ''\n const accessKey = (/(\\d{44})/.exec(idAttribute)?.[1] ?? fromProtocol).trim()\n if (!/^\\d{44}$/.test(accessKey)) throw new NfeParseError('chave de acesso ausente ou inválida')\n const emit = child(infNFe, 'emit')\n const dest = child(infNFe, 'dest')\n const icmsTot = child(child(infNFe, 'total'), 'ICMSTot')\n const items = childrenOf(infNFe, 'det').map(parseItem)\n if (items.length === 0) throw new NfeParseError('nota sem itens')\n const installments = childrenOf(child(infNFe, 'cobr'), 'dup').map((dup) => ({\n number: textOf(dup, 'nDup') ?? '',\n dueDate: dateOnly(textOf(dup, 'dVenc')) ?? '',\n amount: moneyOf(textOf(dup, 'vDup')),\n }))\n return {\n accessKey,\n number: textOf(ide, 'nNF') ?? '',\n series: textOf(ide, 'serie'),\n issuedAt: textOf(ide, 'dhEmi') ?? textOf(ide, 'dEmi'),\n issuer: {\n document: textOf(emit, 'CNPJ') ?? textOf(emit, 'CPF'),\n name: textOf(emit, 'xNome') ?? '',\n tradeName: textOf(emit, 'xFant'),\n },\n recipientDocument: textOf(dest, 'CNPJ') ?? textOf(dest, 'CPF'),\n items,\n totals: {\n products: moneyOf(textOf(icmsTot, 'vProd')),\n freight: moneyOf(textOf(icmsTot, 'vFrete')),\n discount: moneyOf(textOf(icmsTot, 'vDesc')),\n other: moneyOf(textOf(icmsTot, 'vOutro')),\n total: moneyOf(textOf(icmsTot, 'vNF')),\n },\n installments: installments.filter((item) => item.dueDate !== ''),\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Leitor de XML mínimo para documento fiscal: elementos, atributos e texto. Sem DTD, sem entidade externa (nada de\n * XXE), sem dependência. Prefixo de namespace é descartado (`nfe:det` = `det`).\n */\n\nexport type XmlElement = {\n readonly name: string\n readonly attributes: Readonly<Record<string, string>>\n readonly children: XmlElement[]\n text: string\n}\n\nconst ENTITIES: Readonly<Record<string, string>> = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\" }\n\nfunction decode(value: string): string {\n return value.replace(/&(#x[0-9a-f]+|#\\d+|[a-z]+);/gi, (match, entity: string) => {\n if (entity[0] === '#') {\n const code = entity[1]?.toLowerCase() === 'x' ? Number.parseInt(entity.slice(2), 16) : Number(entity.slice(1))\n return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match\n }\n return ENTITIES[entity.toLowerCase()] ?? match\n })\n}\n\nfunction localName(name: string): string {\n const index = name.indexOf(':')\n return index === -1 ? name : name.slice(index + 1)\n}\n\nexport class XmlParseError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'XmlParseError'\n }\n}\n\n/** Limite de tamanho fica no chamador (o schema recusa XML acima de 5 MB). */\nexport function parseXml(source: string): XmlElement {\n const root: XmlElement = { name: '#root', attributes: {}, children: [], text: '' }\n const stack: XmlElement[] = [root]\n let index = 0\n while (index < source.length) {\n const open = source.indexOf('<', index)\n if (open === -1) break\n const parent = stack[stack.length - 1] as XmlElement\n if (open > index) parent.text += decode(source.slice(index, open))\n if (source.startsWith('<!--', open)) {\n const end = source.indexOf('-->', open + 4)\n if (end === -1) throw new XmlParseError('comentário sem fim')\n index = end + 3\n continue\n }\n if (source.startsWith('<![CDATA[', open)) {\n const end = source.indexOf(']]>', open + 9)\n if (end === -1) throw new XmlParseError('CDATA sem fim')\n parent.text += source.slice(open + 9, end)\n index = end + 3\n continue\n }\n if (source.startsWith('<!', open)) throw new XmlParseError('DOCTYPE não é aceito')\n if (source.startsWith('<?', open)) {\n const end = source.indexOf('?>', open + 2)\n if (end === -1) throw new XmlParseError('instrução sem fim')\n index = end + 2\n continue\n }\n const close = source.indexOf('>', open + 1)\n if (close === -1) throw new XmlParseError('tag sem fim')\n const raw = source.slice(open + 1, close)\n index = close + 1\n if (raw.startsWith('/')) {\n const name = localName(raw.slice(1).trim())\n const current = stack.pop()\n if (!current || current.name !== name) throw new XmlParseError(`fechamento inesperado de ${name}`)\n continue\n }\n const selfClosing = raw.endsWith('/')\n const body = selfClosing ? raw.slice(0, -1) : raw\n const nameMatch = /^\\s*([^\\s/>]+)/.exec(body)\n if (!nameMatch?.[1]) throw new XmlParseError('tag sem nome')\n const attributes: Record<string, string> = {}\n const attributePattern = /([^\\s=]+)\\s*=\\s*(\"([^\"]*)\"|'([^']*)')/g\n let match: RegExpExecArray | null\n const rest = body.slice(nameMatch[0].length)\n while ((match = attributePattern.exec(rest)) !== null) {\n attributes[localName(match[1] as string)] = decode(match[3] ?? match[4] ?? '')\n }\n const element: XmlElement = { name: localName(nameMatch[1]), attributes, children: [], text: '' }\n parent.children.push(element)\n if (!selfClosing) stack.push(element)\n }\n if (stack.length !== 1) throw new XmlParseError('documento incompleto')\n return root\n}\n\nexport function child(element: XmlElement | undefined, name: string): XmlElement | undefined {\n return element?.children.find((item) => item.name === name)\n}\n\nexport function childrenOf(element: XmlElement | undefined, name: string): XmlElement[] {\n return element?.children.filter((item) => item.name === name) ?? []\n}\n\nexport function textOf(element: XmlElement | undefined, name: string): string | null {\n const found = child(element, name)\n const value = found?.text.trim()\n return value ? value : null\n}\n\n/** Primeiro elemento com o nome em qualquer profundidade. */\nexport function find(element: XmlElement, name: string): XmlElement | undefined {\n for (const item of element.children) {\n if (item.name === name) return item\n const nested = find(item, name)\n if (nested) return nested\n }\n return undefined\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACUO,IAAMA,eAAe;EAC1BC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ANUAL","DISPATCH_CHANNELS","DIVERGENCE","NONE","QUANTITY","PRICE","BOTH","INTEGRATION_STATUS","SKIPPED","DONE","FAILED","PAYMENT_STATUS","OPEN","PARTIAL","PAID","SORT_ORDER","ASC","DESC","import_recipe_contracts","import_recipe_contracts","MONEY_SCALE","money","value","formatDecimal","quantityText","sum","values","reduce","total","add","ZERO","lineTotal","quantity","unitPrice","parseDecimal","multiply","centsOf","rounded","roundToScale","numerator","denominator","fromCentsBig","cents","rational","isNegative","compare","clampToZero","DATE_PATTERN","isCivilDate","value","test","date","Date","Number","isNaN","getTime","toISOString","slice","addDays","days","base","setUTCDate","getUTCDate","civilDateIn","instant","timeZone","parts","Intl","DateTimeFormat","year","month","day","formatToParts","get","type","find","part","buildInstallments","params","terms","termDays","length","sort","a","b","totalCents","centsOf","parseDecimal","total","count","BigInt","first","map","index","number","dueDate","baseDate","amount","money","fromCentsBig","parsePaymentTerms","text","clean","trim","toLowerCase","split","filter","Boolean","some","isInteger","Set","formatPaymentTerms","join","PURCHASE_LIMITS","NAME","DOCUMENT","CONTACT","EMAIL","PHONE","SKU","UNIT","ITEM_REF","NOTE","REASON","BATCH_CODE","INVOICE_NUMBER","SEARCH","PAGE_SIZE","ORDER_LINES","TERMS","TERM_DAYS","LEAD_DAYS","PRIORITY","LOOKUP","IDEMPOTENCY_KEY","XML_BYTES","REPORT_DAYS","unitSchema","z","enum","RECIPE_UNITS","moneySchema","string","trim","regex","civilDate","refine","isCivilDate","pageShape","page","coerce","number","int","min","default","pageSize","max","boolText","transform","value","optional","csvOf","allowed","split","map","item","filter","Boolean","values","every","includes","emptyToNull","schema","create","nullable","update","undefined","nullableText","documentField","replace","toUpperCase","length","message","phoneField","test","emailField","union","literal","toLowerCase","email","termDaysSchema","array","days","Set","sort","a","b","weekdaysSchema","supplierShape","name","document","contactName","phone","whatsapp","paymentTermDays","leadTimeDays","minimumOrderAmount","deliveryWeekdays","notes","isActive","boolean","createSupplierSchema","object","id","uuid","updateSupplierSchema","Object","some","field","SUPPLIER_SORTS","listSuppliersQuerySchema","search","order","SORT_ORDER","ASC","DESC","supplierLookupSchema","ids","supplierItemShape","itemRef","itemName","supplierSku","purchaseUnit","unitsPerPurchase","positiveDecimalSchema","stockUnit","lastPrice","decimalSchema","priority","createSupplierItemSchema","updateSupplierItemSchema","listSupplierItemsQuerySchema","supplierId","orderLineInputSchema","supplierItemId","quantity","unitPrice","line","createOrderSchema","expectedAt","freight","discount","lines","updateOrderSchema","reasonSchema","reason","optionalReasonSchema","sendOrderSchema","channel","DISPATCH_CHANNELS","DISPATCH_CHANNEL","WHATSAPP","withPrices","ORDER_SORTS","listOrdersQuerySchema","status","ORDER_STATUSES","late","from","to","receiptLineInputSchema","orderLineId","batchCode","expiresAt","divergenceReason","installmentInput","dueDate","amount","receiveSchema","receivedAt","datetime","offset","invoiceNumber","invoiceKey","invoiceIssuedAt","idempotencyKey","installments","listReceiptsQuerySchema","orderId","failed","priceHistoryQuerySchema","query","itemRefsLookupSchema","itemRefs","suggestionQuerySchema","ordersFromSuggestionSchema","supplierIds","nfePreviewSchema","xml","REPORT_GROUP","SUPPLIER","ITEM","MONTH","REPORT_GROUPS","spendReportQuerySchema","groupBy","supplierPerformanceQuerySchema","exportFormatSchema","format","PurchaseError","Error","message","statusCode","code","details","publicDetails","name","PURCHASE_ERROR_CODES","DISABLED","UNAUTHENTICATED","CONFIG_MISSING","SUPPLIER_NOT_FOUND","SUPPLIER_INACTIVE","SUPPLIER_DOCUMENT_TAKEN","SUPPLIER_IN_USE","SUPPLIER_ITEM_NOT_FOUND","SUPPLIER_ITEM_TAKEN","ITEM_NOT_FOUND","ORDER_NOT_FOUND","ORDER_LINE_NOT_FOUND","INVALID_TRANSITION","SELF_APPROVAL","RECEIPT_NOT_FOUND","INVOICE_ALREADY_RECEIVED","INSTALLMENTS_MISMATCH","DISPATCH_UNAVAILABLE","NO_CONTACT","NFE_INVALID","REPORT_RANGE_TOO_LONG","PurchaseDisabledError","PurchaseUnauthenticatedError","PurchaseConfigMissingError","field","SupplierNotFoundError","supplierId","SupplierInactiveError","SupplierDocumentTakenError","SupplierInUseError","SupplierItemNotFoundError","supplierItemId","SupplierItemTakenError","PurchaseItemNotFoundError","itemRef","OrderNotFoundError","orderId","OrderLineNotFoundError","orderLineId","InvalidOrderTransitionError","params","SelfApprovalError","ReceiptNotFoundError","receiptId","InvoiceAlreadyReceivedError","InstallmentsMismatchError","DispatchUnavailableError","channel","SupplierNoContactError","NfeInvalidError","reason","ReportRangeTooLongError","maxDays","DEFAULT_PURCHASE_SCOPES","read","write","approve","service","ORDER_ACTION","EDIT","SUBMIT","APPROVE","REJECT","SEND","RECEIVE","CLOSE","CANCEL","ALLOWED","edit","ORDER_STATUS","DRAFT","submit","approve","PENDING_APPROVAL","reject","send","APPROVED","SENT","receive","PARTIALLY_RECEIVED","close","cancel","canPerform","status","action","includes","allowedActions","Object","keys","filter","statusAfterSend","requiresApproval","params","thresholdCents","totalCents","isOrderLate","expectedAt","today","import_recipe_contracts","computeTotals","params","subtotal","sum","lines","map","line","lineTotal","quantity","unitPrice","freight","parseDecimal","discount","total","clampToZero","subtract","add2","money","left","right","allocateExtras","totals","lineTotals","value","centsOf","base","reduce","acc","net","length","splitEvenly","cents","fromCentsBig","sign","absolute","shares","index","exact","floor","remainder","share","byRemainder","sort","a","b","extra","Map","set","get","parts","count","BigInt","rest","Array","from","_","landedUnitCost","stockQuantity","multiply","unitsPerPurchase","compare","ZERO","allocated","formatDecimal","divide","toStockQuantity","quantityText","pendingQuantity","pending","receivedQuantity","canceledQuantity","statusAfterReceipt","anyPending","some","ORDER_STATUS","PARTIALLY_RECEIVED","RECEIVED","divergenceOf","tolerance","priceToleranceCents","price","orderedPrice","ordered","received","receivedPrice","delta","DIVERGENCE","BOTH","QUANTITY","PRICE","NONE","weightedAverageCost","points","weight","point","cost","UNIT_FACTOR_ONE","rational","import_recipe_contracts","shortageOf","row","onHand","clampToZero","parseDecimal","onHandQuantity","byNeed","subtract","neededQuantity","byMinimum","minimumQuantity","ZERO","raw","maximum","incomingQuantity","quantityText","packsFor","shortage","unitsPerPurchase","packs","divide","roundToScale","ROUNDING","UP","comparePerStockUnit","left","right","lastPrice","leftCost","rightCost","compare","buildSuggestion","params","groups","Map","demand","incoming","get","itemRef","candidates","supplierItems","filter","item","isActive","suppliers","supplierId","undefined","sort","priority","chosen","suggested","line","itemName","stockUnit","shortageQuantity","supplierItemId","id","purchaseUnit","suggestedQuantity","unitPrice","estimatedTotal","money","lineTotal","key","set","entries","map","lines","supplier","estimated","sum","minimum","minimumOrderAmount","supplierName","name","a","b","localeCompare","belowMinimumOrder","centsOf","stockQuantityOf","quantity","multiply","import_recipe_contracts","formatQuantityPt","value","whole","fraction","split","trimmed","replace","formatMoneyPt","fixed","formatDecimal","parseDecimal","formatDatePt","date","year","month","day","buildOrderMessage","input","options","header","number","companyName","supplierName","lines","map","line","sku","supplierSku","price","withPrices","unitPrice","purchaseUnit","quantity","itemName","footer","expectedAt","push","formatPaymentTerms","paymentTermDays","total","notes","trim","join","import_recipe_contracts","ENTITIES","amp","lt","gt","quot","apos","decode","value","replace","match","entity","code","toLowerCase","Number","parseInt","slice","isFinite","String","fromCodePoint","localName","name","index","indexOf","XmlParseError","Error","message","parseXml","source","root","attributes","children","text","stack","length","open","parent","startsWith","end","close","raw","trim","current","pop","selfClosing","endsWith","body","nameMatch","exec","attributePattern","rest","element","push","child","find","item","childrenOf","filter","textOf","found","nested","undefined","NfeParseError","Error","message","name","decimalOf","text","fallback","value","trim","test","whole","fraction","split","rounded","length","roundFraction","quantityText","parseDecimal","scaled","BigInt","slice","next","Number","toString","padStart","moneyOf","money","dateOnly","match","exec","parseItem","det","prod","child","itemNumber","attributes","nItem","ean","textOf","batches","childrenOf","map","rastro","batchCode","quantity","expiresAt","isInteger","supplierSku","toUpperCase","description","ncm","cfop","unit","unitPrice","total","discount","freight","filter","batch","parseNfeXml","xml","root","parseXml","error","XmlParseError","infNFe","find","ide","model","idAttribute","Id","fromProtocol","accessKey","emit","dest","icmsTot","items","installments","dup","number","dueDate","amount","series","issuedAt","issuer","document","tradeName","recipientDocument","totals","products","other","item"]}
|