@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/dist/index.js ADDED
@@ -0,0 +1,1420 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/purchase.types.ts
5
+ var ORDER_STATUS = {
6
+ DRAFT: "draft",
7
+ PENDING_APPROVAL: "pending_approval",
8
+ APPROVED: "approved",
9
+ SENT: "sent",
10
+ PARTIALLY_RECEIVED: "partially_received",
11
+ RECEIVED: "received",
12
+ CLOSED: "closed",
13
+ CANCELED: "canceled"
14
+ };
15
+ var ORDER_STATUSES = Object.values(ORDER_STATUS);
16
+ var OPEN_ORDER_STATUSES = [
17
+ ORDER_STATUS.APPROVED,
18
+ ORDER_STATUS.SENT,
19
+ ORDER_STATUS.PARTIALLY_RECEIVED
20
+ ];
21
+ var DISPATCH_CHANNEL = {
22
+ WHATSAPP: "whatsapp",
23
+ EMAIL: "email",
24
+ MANUAL: "manual"
25
+ };
26
+ var DISPATCH_CHANNELS = Object.values(DISPATCH_CHANNEL);
27
+ var DIVERGENCE = {
28
+ NONE: "none",
29
+ QUANTITY: "quantity",
30
+ PRICE: "price",
31
+ BOTH: "both"
32
+ };
33
+ var INTEGRATION_STATUS = {
34
+ SKIPPED: "skipped",
35
+ DONE: "done",
36
+ FAILED: "failed"
37
+ };
38
+ var PAYMENT_STATUS = {
39
+ NONE: "none",
40
+ OPEN: "open",
41
+ PARTIAL: "partial",
42
+ PAID: "paid"
43
+ };
44
+ var SORT_ORDER = {
45
+ ASC: "asc",
46
+ DESC: "desc"
47
+ };
48
+
49
+ // src/schemas.ts
50
+ import { decimalSchema, positiveDecimalSchema, RECIPE_UNITS } from "@adatechnology/recipe-contracts";
51
+ import { z } from "zod";
52
+
53
+ // src/rules/schedule.ts
54
+ import { parseDecimal as parseDecimal2 } from "@adatechnology/recipe-contracts";
55
+
56
+ // src/rules/money.ts
57
+ import { add, compare, divide, formatDecimal, multiply, parseDecimal, rational, roundToScale, subtract, ZERO } from "@adatechnology/recipe-contracts";
58
+ var MONEY_SCALE = 2;
59
+ function money(value) {
60
+ return formatDecimal(value, MONEY_SCALE);
61
+ }
62
+ __name(money, "money");
63
+ function quantityText(value) {
64
+ return formatDecimal(value);
65
+ }
66
+ __name(quantityText, "quantityText");
67
+ function sum(values) {
68
+ return values.reduce((total, value) => add(total, value), ZERO);
69
+ }
70
+ __name(sum, "sum");
71
+ function lineTotal(quantity, unitPrice) {
72
+ return parseDecimal(money(multiply(parseDecimal(quantity), parseDecimal(unitPrice))));
73
+ }
74
+ __name(lineTotal, "lineTotal");
75
+ function centsOf(value) {
76
+ const rounded = roundToScale(value, MONEY_SCALE);
77
+ return rounded.numerator * 100n / rounded.denominator;
78
+ }
79
+ __name(centsOf, "centsOf");
80
+ function fromCentsBig(cents) {
81
+ return rational(cents, 100n);
82
+ }
83
+ __name(fromCentsBig, "fromCentsBig");
84
+ function isNegative(value) {
85
+ return compare(value, ZERO) < 0;
86
+ }
87
+ __name(isNegative, "isNegative");
88
+ function clampToZero(value) {
89
+ return isNegative(value) ? ZERO : value;
90
+ }
91
+ __name(clampToZero, "clampToZero");
92
+
93
+ // src/rules/schedule.ts
94
+ var DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
95
+ function isCivilDate(value) {
96
+ if (!DATE_PATTERN.test(value)) return false;
97
+ const date = /* @__PURE__ */ new Date(`${value}T00:00:00Z`);
98
+ return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
99
+ }
100
+ __name(isCivilDate, "isCivilDate");
101
+ function addDays(date, days) {
102
+ const base = /* @__PURE__ */ new Date(`${date}T00:00:00Z`);
103
+ base.setUTCDate(base.getUTCDate() + days);
104
+ return base.toISOString().slice(0, 10);
105
+ }
106
+ __name(addDays, "addDays");
107
+ function civilDateIn(instant, timeZone) {
108
+ const parts = new Intl.DateTimeFormat("en-CA", {
109
+ timeZone,
110
+ year: "numeric",
111
+ month: "2-digit",
112
+ day: "2-digit"
113
+ }).formatToParts(instant);
114
+ const get = /* @__PURE__ */ __name((type) => parts.find((part) => part.type === type)?.value ?? "", "get");
115
+ return `${get("year")}-${get("month")}-${get("day")}`;
116
+ }
117
+ __name(civilDateIn, "civilDateIn");
118
+ function buildInstallments(params) {
119
+ const terms = params.termDays.length > 0 ? [
120
+ ...params.termDays
121
+ ].sort((a, b) => a - b) : [
122
+ 0
123
+ ];
124
+ const totalCents = centsOf(parseDecimal2(params.total));
125
+ const count = BigInt(terms.length);
126
+ const base = totalCents / count;
127
+ const first = totalCents - base * (count - 1n);
128
+ return terms.map((days, index) => ({
129
+ number: index + 1,
130
+ dueDate: addDays(params.baseDate, days),
131
+ amount: money(fromCentsBig(index === 0 ? first : base))
132
+ }));
133
+ }
134
+ __name(buildInstallments, "buildInstallments");
135
+ function parsePaymentTerms(text) {
136
+ const clean = text.trim().toLowerCase();
137
+ if (clean === "" || clean === "a vista" || clean === "\xE0 vista" || clean === "0") return [
138
+ 0
139
+ ];
140
+ const parts = clean.split(/[\s/,;+-]+/).filter(Boolean);
141
+ const days = parts.map((part) => Number(part));
142
+ if (days.some((day) => !Number.isInteger(day) || day < 0 || day > 365)) return null;
143
+ return [
144
+ ...new Set(days)
145
+ ].sort((a, b) => a - b);
146
+ }
147
+ __name(parsePaymentTerms, "parsePaymentTerms");
148
+ function formatPaymentTerms(days) {
149
+ if (days.length === 0 || days.length === 1 && days[0] === 0) return "\xE0 vista";
150
+ return days.join("/");
151
+ }
152
+ __name(formatPaymentTerms, "formatPaymentTerms");
153
+
154
+ // src/schemas.ts
155
+ var PURCHASE_LIMITS = {
156
+ NAME: 160,
157
+ DOCUMENT: 20,
158
+ CONTACT: 120,
159
+ EMAIL: 254,
160
+ PHONE: 30,
161
+ SKU: 100,
162
+ UNIT: 12,
163
+ ITEM_REF: 128,
164
+ NOTE: 2e3,
165
+ REASON: 500,
166
+ BATCH_CODE: 100,
167
+ INVOICE_NUMBER: 30,
168
+ SEARCH: 100,
169
+ PAGE_SIZE: 100,
170
+ ORDER_LINES: 300,
171
+ TERMS: 24,
172
+ TERM_DAYS: 365,
173
+ LEAD_DAYS: 365,
174
+ PRIORITY: 1e3,
175
+ LOOKUP: 500,
176
+ IDEMPOTENCY_KEY: 128,
177
+ XML_BYTES: 5e6,
178
+ REPORT_DAYS: 400
179
+ };
180
+ var unitSchema = z.enum(RECIPE_UNITS);
181
+ var moneySchema = z.string().trim().regex(/^\d{1,12}(\.\d{1,2})?$/, "Valor com at\xE9 duas casas.");
182
+ var civilDate = z.string().refine(isCivilDate, "Data no formato aaaa-mm-dd.");
183
+ var pageShape = {
184
+ page: z.coerce.number().int().min(1).default(1),
185
+ pageSize: z.coerce.number().int().min(1).max(PURCHASE_LIMITS.PAGE_SIZE).default(20)
186
+ };
187
+ var boolText = z.enum([
188
+ "true",
189
+ "false"
190
+ ]).transform((value) => value === "true").optional();
191
+ function csvOf(allowed) {
192
+ return z.string().trim().transform((value) => value.split(",").map((item) => item.trim()).filter(Boolean)).refine((values) => values.every((value) => allowed.includes(value)), "Valor inv\xE1lido.").transform((values) => values).optional();
193
+ }
194
+ __name(csvOf, "csvOf");
195
+ function emptyToNull(schema) {
196
+ return {
197
+ create: schema.nullable().optional().transform((value) => value ? value : null),
198
+ update: schema.nullable().optional().transform((value) => value === void 0 ? void 0 : value ? value : null)
199
+ };
200
+ }
201
+ __name(emptyToNull, "emptyToNull");
202
+ var nullableText = /* @__PURE__ */ __name((max) => emptyToNull(z.string().trim().max(max)), "nullableText");
203
+ var documentField = emptyToNull(z.string().trim().max(PURCHASE_LIMITS.DOCUMENT + 10).transform((value) => value.replace(/[^0-9A-Za-z]/g, "").toUpperCase()).refine((value) => value === "" || value.length >= 11 && value.length <= PURCHASE_LIMITS.DOCUMENT, {
204
+ message: "Documento com 11 a 20 caracteres (CPF, CNPJ ou equivalente)."
205
+ }));
206
+ var phoneField = emptyToNull(z.string().trim().max(PURCHASE_LIMITS.PHONE).refine((value) => value === "" || /^\+?[0-9 ()-]{8,}$/.test(value), {
207
+ message: "Telefone inv\xE1lido."
208
+ }));
209
+ var emailField = emptyToNull(z.union([
210
+ z.literal(""),
211
+ z.string().trim().toLowerCase().email().max(PURCHASE_LIMITS.EMAIL)
212
+ ]));
213
+ var termDaysSchema = z.array(z.number().int().min(0).max(PURCHASE_LIMITS.TERM_DAYS)).max(PURCHASE_LIMITS.TERMS).transform((days) => [
214
+ ...new Set(days)
215
+ ].sort((a, b) => a - b));
216
+ var weekdaysSchema = z.array(z.number().int().min(0).max(6)).max(7).transform((days) => [
217
+ ...new Set(days)
218
+ ].sort((a, b) => a - b));
219
+ var supplierShape = {
220
+ name: z.string().trim().min(1).max(PURCHASE_LIMITS.NAME),
221
+ document: documentField.create,
222
+ contactName: nullableText(PURCHASE_LIMITS.CONTACT).create,
223
+ email: emailField.create,
224
+ phone: phoneField.create,
225
+ whatsapp: phoneField.create,
226
+ paymentTermDays: termDaysSchema.default([
227
+ 0
228
+ ]),
229
+ leadTimeDays: z.number().int().min(0).max(PURCHASE_LIMITS.LEAD_DAYS).nullable().default(null),
230
+ minimumOrderAmount: moneySchema.nullable().default(null),
231
+ deliveryWeekdays: weekdaysSchema.default([]),
232
+ notes: z.string().trim().max(PURCHASE_LIMITS.NOTE).default(""),
233
+ isActive: z.boolean().default(true)
234
+ };
235
+ var createSupplierSchema = z.object({
236
+ id: z.string().uuid().optional(),
237
+ ...supplierShape
238
+ });
239
+ var updateSupplierSchema = z.object({
240
+ name: supplierShape.name.optional(),
241
+ document: documentField.update,
242
+ contactName: nullableText(PURCHASE_LIMITS.CONTACT).update,
243
+ email: emailField.update,
244
+ phone: phoneField.update,
245
+ whatsapp: phoneField.update,
246
+ paymentTermDays: termDaysSchema.optional(),
247
+ leadTimeDays: z.number().int().min(0).max(PURCHASE_LIMITS.LEAD_DAYS).nullable().optional(),
248
+ minimumOrderAmount: moneySchema.nullable().optional(),
249
+ deliveryWeekdays: weekdaysSchema.optional(),
250
+ notes: z.string().trim().max(PURCHASE_LIMITS.NOTE).optional(),
251
+ isActive: z.boolean().optional()
252
+ }).refine((value) => Object.values(value).some((field) => field !== void 0), {
253
+ message: "Nada para alterar."
254
+ });
255
+ var SUPPLIER_SORTS = [
256
+ "name",
257
+ "createdAt",
258
+ "updatedAt"
259
+ ];
260
+ var listSuppliersQuerySchema = z.object({
261
+ ...pageShape,
262
+ search: z.string().trim().max(PURCHASE_LIMITS.SEARCH).optional(),
263
+ isActive: boolText,
264
+ sort: z.enum(SUPPLIER_SORTS).default("name"),
265
+ order: z.enum([
266
+ SORT_ORDER.ASC,
267
+ SORT_ORDER.DESC
268
+ ]).default(SORT_ORDER.ASC)
269
+ });
270
+ var supplierLookupSchema = z.object({
271
+ ids: z.array(z.string().uuid()).min(1).max(PURCHASE_LIMITS.LOOKUP)
272
+ });
273
+ var supplierItemShape = {
274
+ itemRef: z.string().trim().min(1).max(PURCHASE_LIMITS.ITEM_REF).nullable().default(null),
275
+ itemName: z.string().trim().min(1).max(PURCHASE_LIMITS.NAME),
276
+ supplierSku: nullableText(PURCHASE_LIMITS.SKU).create,
277
+ purchaseUnit: z.string().trim().min(1).max(PURCHASE_LIMITS.UNIT),
278
+ unitsPerPurchase: positiveDecimalSchema.default("1"),
279
+ stockUnit: unitSchema.nullable().default(null),
280
+ lastPrice: decimalSchema.nullable().default(null),
281
+ priority: z.number().int().min(0).max(PURCHASE_LIMITS.PRIORITY).default(0),
282
+ isActive: z.boolean().default(true)
283
+ };
284
+ var createSupplierItemSchema = z.object(supplierItemShape);
285
+ var updateSupplierItemSchema = z.object({
286
+ itemRef: supplierItemShape.itemRef.optional(),
287
+ itemName: supplierItemShape.itemName.optional(),
288
+ supplierSku: nullableText(PURCHASE_LIMITS.SKU).update,
289
+ purchaseUnit: supplierItemShape.purchaseUnit.optional(),
290
+ unitsPerPurchase: positiveDecimalSchema.optional(),
291
+ stockUnit: unitSchema.nullable().optional(),
292
+ lastPrice: decimalSchema.nullable().optional(),
293
+ priority: z.number().int().min(0).max(PURCHASE_LIMITS.PRIORITY).optional(),
294
+ isActive: z.boolean().optional()
295
+ }).refine((value) => Object.values(value).some((field) => field !== void 0), {
296
+ message: "Nada para alterar."
297
+ });
298
+ var listSupplierItemsQuerySchema = z.object({
299
+ ...pageShape,
300
+ supplierId: z.string().uuid().optional(),
301
+ itemRef: z.string().trim().max(PURCHASE_LIMITS.ITEM_REF).optional(),
302
+ search: z.string().trim().max(PURCHASE_LIMITS.SEARCH).optional(),
303
+ isActive: boolText
304
+ });
305
+ var orderLineInputSchema = z.object({
306
+ supplierItemId: z.string().uuid().optional(),
307
+ itemRef: z.string().trim().min(1).max(PURCHASE_LIMITS.ITEM_REF).optional(),
308
+ itemName: z.string().trim().min(1).max(PURCHASE_LIMITS.NAME).optional(),
309
+ supplierSku: z.string().trim().max(PURCHASE_LIMITS.SKU).optional(),
310
+ purchaseUnit: z.string().trim().min(1).max(PURCHASE_LIMITS.UNIT).optional(),
311
+ unitsPerPurchase: positiveDecimalSchema.optional(),
312
+ stockUnit: unitSchema.optional(),
313
+ quantity: positiveDecimalSchema,
314
+ unitPrice: decimalSchema.optional(),
315
+ notes: z.string().trim().max(PURCHASE_LIMITS.REASON).optional()
316
+ }).refine((line) => line.supplierItemId !== void 0 || line.itemName !== void 0 && line.purchaseUnit !== void 0, {
317
+ message: "Linha sem item do fornecedor precisa de nome e unidade de compra."
318
+ });
319
+ var createOrderSchema = z.object({
320
+ supplierId: z.string().uuid(),
321
+ expectedAt: civilDate.nullable().optional(),
322
+ notes: z.string().trim().max(PURCHASE_LIMITS.NOTE).default(""),
323
+ freight: moneySchema.default("0"),
324
+ discount: moneySchema.default("0"),
325
+ /** Ausente: a condição do fornecedor. */
326
+ paymentTermDays: termDaysSchema.optional(),
327
+ lines: z.array(orderLineInputSchema).min(1).max(PURCHASE_LIMITS.ORDER_LINES)
328
+ });
329
+ var updateOrderSchema = z.object({
330
+ expectedAt: civilDate.nullable().optional(),
331
+ notes: z.string().trim().max(PURCHASE_LIMITS.NOTE).optional(),
332
+ freight: moneySchema.optional(),
333
+ discount: moneySchema.optional(),
334
+ paymentTermDays: termDaysSchema.optional(),
335
+ lines: z.array(orderLineInputSchema).min(1).max(PURCHASE_LIMITS.ORDER_LINES).optional()
336
+ }).refine((value) => Object.values(value).some((field) => field !== void 0), {
337
+ message: "Nada para alterar."
338
+ });
339
+ var reasonSchema = z.object({
340
+ reason: z.string().trim().min(1).max(PURCHASE_LIMITS.REASON)
341
+ });
342
+ var optionalReasonSchema = z.object({
343
+ reason: z.string().trim().max(PURCHASE_LIMITS.REASON).default("")
344
+ });
345
+ var sendOrderSchema = z.object({
346
+ channel: z.enum(DISPATCH_CHANNELS).default(DISPATCH_CHANNEL.WHATSAPP),
347
+ /** Preço no texto do pedido (padrão: sem). */
348
+ withPrices: z.boolean().default(false)
349
+ });
350
+ var ORDER_SORTS = [
351
+ "number",
352
+ "createdAt",
353
+ "expectedAt",
354
+ "total"
355
+ ];
356
+ var listOrdersQuerySchema = z.object({
357
+ ...pageShape,
358
+ status: csvOf(ORDER_STATUSES),
359
+ supplierId: z.string().uuid().optional(),
360
+ /** Número do pedido ou nome do fornecedor. */
361
+ search: z.string().trim().max(PURCHASE_LIMITS.SEARCH).optional(),
362
+ late: boolText,
363
+ from: civilDate.optional(),
364
+ to: civilDate.optional(),
365
+ sort: z.enum(ORDER_SORTS).default("number"),
366
+ order: z.enum([
367
+ SORT_ORDER.ASC,
368
+ SORT_ORDER.DESC
369
+ ]).default(SORT_ORDER.DESC)
370
+ });
371
+ var receiptLineInputSchema = z.object({
372
+ /** Linha do pedido que está chegando (recebimento com pedido). */
373
+ orderLineId: z.string().uuid().optional(),
374
+ supplierItemId: z.string().uuid().optional(),
375
+ itemRef: z.string().trim().min(1).max(PURCHASE_LIMITS.ITEM_REF).optional(),
376
+ itemName: z.string().trim().min(1).max(PURCHASE_LIMITS.NAME).optional(),
377
+ supplierSku: z.string().trim().max(PURCHASE_LIMITS.SKU).optional(),
378
+ purchaseUnit: z.string().trim().min(1).max(PURCHASE_LIMITS.UNIT).optional(),
379
+ unitsPerPurchase: positiveDecimalSchema.optional(),
380
+ stockUnit: unitSchema.optional(),
381
+ /** Na unidade de compra. */
382
+ quantity: positiveDecimalSchema,
383
+ /** Ausente: o preço do pedido (ou o último do fornecedor). */
384
+ unitPrice: decimalSchema.optional(),
385
+ batchCode: z.string().trim().max(PURCHASE_LIMITS.BATCH_CODE).optional(),
386
+ expiresAt: civilDate.nullable().optional(),
387
+ divergenceReason: z.string().trim().max(PURCHASE_LIMITS.REASON).optional()
388
+ }).refine((line) => line.orderLineId !== void 0 || line.supplierItemId !== void 0 || line.itemName !== void 0 && line.purchaseUnit !== void 0, {
389
+ message: "Linha precisa da linha do pedido, do item do fornecedor ou de nome e unidade."
390
+ });
391
+ var installmentInput = z.object({
392
+ dueDate: civilDate,
393
+ amount: moneySchema
394
+ });
395
+ var receiveSchema = z.object({
396
+ /** Obrigatório no recebimento sem pedido; com pedido, vem dele. */
397
+ supplierId: z.string().uuid().optional(),
398
+ /** ISO com fuso. Ausente: agora. */
399
+ receivedAt: z.string().datetime({
400
+ offset: true
401
+ }).optional(),
402
+ invoiceNumber: z.string().trim().max(PURCHASE_LIMITS.INVOICE_NUMBER).optional(),
403
+ invoiceKey: z.string().trim().transform((value) => value.replace(/\D/g, "")).refine((value) => value === "" || value.length === 44, "Chave de acesso com 44 d\xEDgitos.").optional(),
404
+ invoiceIssuedAt: z.string().datetime({
405
+ offset: true
406
+ }).optional(),
407
+ freight: moneySchema.default("0"),
408
+ discount: moneySchema.default("0"),
409
+ notes: z.string().trim().max(PURCHASE_LIMITS.NOTE).default(""),
410
+ /** Mesmo valor reenviado devolve o recebimento já gravado (clique duplo, rede caindo). */
411
+ idempotencyKey: z.string().trim().min(1).max(PURCHASE_LIMITS.IDEMPOTENCY_KEY).optional(),
412
+ /** Parcelas da conta a pagar; ausente: pela condição do pedido/fornecedor, ou pelas duplicatas da nota. */
413
+ installments: z.array(installmentInput).min(1).max(PURCHASE_LIMITS.TERMS).optional(),
414
+ lines: z.array(receiptLineInputSchema).min(1).max(PURCHASE_LIMITS.ORDER_LINES)
415
+ });
416
+ var listReceiptsQuerySchema = z.object({
417
+ ...pageShape,
418
+ supplierId: z.string().uuid().optional(),
419
+ orderId: z.string().uuid().optional(),
420
+ from: civilDate.optional(),
421
+ to: civilDate.optional(),
422
+ /** Só os que tiveram falha numa integração (estoque ou contas), para reprocessar. */
423
+ failed: boolText
424
+ });
425
+ var priceHistoryQuerySchema = z.object({
426
+ ...pageShape,
427
+ itemRef: z.string().trim().max(PURCHASE_LIMITS.ITEM_REF).optional(),
428
+ supplierItemId: z.string().uuid().optional(),
429
+ supplierId: z.string().uuid().optional(),
430
+ from: civilDate.optional(),
431
+ to: civilDate.optional()
432
+ }).refine((query) => query.itemRef !== void 0 || query.supplierItemId !== void 0, {
433
+ message: "Informe itemRef ou supplierItemId."
434
+ });
435
+ var itemRefsLookupSchema = z.object({
436
+ itemRefs: z.array(z.string().trim().min(1).max(PURCHASE_LIMITS.ITEM_REF)).min(1).max(PURCHASE_LIMITS.LOOKUP)
437
+ });
438
+ var suggestionQuerySchema = z.object({
439
+ supplierId: z.string().uuid().optional()
440
+ });
441
+ var ordersFromSuggestionSchema = z.object({
442
+ /** Ausente: um rascunho por fornecedor sugerido. */
443
+ supplierIds: z.array(z.string().uuid()).max(100).optional(),
444
+ expectedAt: civilDate.nullable().optional()
445
+ });
446
+ var nfePreviewSchema = z.object({
447
+ xml: z.string().min(1).max(PURCHASE_LIMITS.XML_BYTES),
448
+ /** Casa os itens da nota com as linhas pendentes deste pedido. */
449
+ orderId: z.string().uuid().optional()
450
+ });
451
+ var REPORT_GROUP = {
452
+ SUPPLIER: "supplier",
453
+ ITEM: "item",
454
+ MONTH: "month"
455
+ };
456
+ var REPORT_GROUPS = Object.values(REPORT_GROUP);
457
+ var spendReportQuerySchema = z.object({
458
+ from: civilDate,
459
+ to: civilDate,
460
+ groupBy: z.enum(REPORT_GROUPS).default(REPORT_GROUP.SUPPLIER),
461
+ supplierId: z.string().uuid().optional(),
462
+ itemRef: z.string().trim().max(PURCHASE_LIMITS.ITEM_REF).optional()
463
+ }).refine((query) => query.from <= query.to, {
464
+ message: "In\xEDcio depois do fim."
465
+ });
466
+ var supplierPerformanceQuerySchema = z.object({
467
+ from: civilDate,
468
+ to: civilDate
469
+ }).refine((query) => query.from <= query.to, {
470
+ message: "In\xEDcio depois do fim."
471
+ });
472
+ var exportFormatSchema = z.object({
473
+ format: z.enum([
474
+ "csv",
475
+ "xlsx"
476
+ ]).default("csv")
477
+ });
478
+
479
+ // src/errors.ts
480
+ var PurchaseError = class extends Error {
481
+ static {
482
+ __name(this, "PurchaseError");
483
+ }
484
+ statusCode;
485
+ code;
486
+ details;
487
+ publicDetails;
488
+ constructor(message, statusCode, code, details, publicDetails) {
489
+ super(message), this.statusCode = statusCode, this.code = code, this.details = details, this.publicDetails = publicDetails;
490
+ this.name = "PurchaseError";
491
+ }
492
+ };
493
+ var PURCHASE_ERROR_CODES = {
494
+ DISABLED: "PURCHASE_DISABLED",
495
+ UNAUTHENTICATED: "PURCHASE_UNAUTHENTICATED",
496
+ CONFIG_MISSING: "PURCHASE_CONFIG_MISSING",
497
+ SUPPLIER_NOT_FOUND: "PURCHASE_SUPPLIER_NOT_FOUND",
498
+ SUPPLIER_INACTIVE: "PURCHASE_SUPPLIER_INACTIVE",
499
+ SUPPLIER_DOCUMENT_TAKEN: "PURCHASE_SUPPLIER_DOCUMENT_TAKEN",
500
+ SUPPLIER_IN_USE: "PURCHASE_SUPPLIER_IN_USE",
501
+ SUPPLIER_ITEM_NOT_FOUND: "PURCHASE_SUPPLIER_ITEM_NOT_FOUND",
502
+ SUPPLIER_ITEM_TAKEN: "PURCHASE_SUPPLIER_ITEM_TAKEN",
503
+ ITEM_NOT_FOUND: "PURCHASE_ITEM_NOT_FOUND",
504
+ ORDER_NOT_FOUND: "PURCHASE_ORDER_NOT_FOUND",
505
+ ORDER_LINE_NOT_FOUND: "PURCHASE_ORDER_LINE_NOT_FOUND",
506
+ INVALID_TRANSITION: "PURCHASE_INVALID_TRANSITION",
507
+ SELF_APPROVAL: "PURCHASE_SELF_APPROVAL",
508
+ RECEIPT_NOT_FOUND: "PURCHASE_RECEIPT_NOT_FOUND",
509
+ INVOICE_ALREADY_RECEIVED: "PURCHASE_INVOICE_ALREADY_RECEIVED",
510
+ INSTALLMENTS_MISMATCH: "PURCHASE_INSTALLMENTS_MISMATCH",
511
+ DISPATCH_UNAVAILABLE: "PURCHASE_DISPATCH_UNAVAILABLE",
512
+ NO_CONTACT: "PURCHASE_SUPPLIER_NO_CONTACT",
513
+ NFE_INVALID: "PURCHASE_NFE_INVALID",
514
+ REPORT_RANGE_TOO_LONG: "PURCHASE_REPORT_RANGE_TOO_LONG"
515
+ };
516
+ var PurchaseDisabledError = class extends PurchaseError {
517
+ static {
518
+ __name(this, "PurchaseDisabledError");
519
+ }
520
+ constructor() {
521
+ super("Compras n\xE3o habilitado para a empresa.", 404, PURCHASE_ERROR_CODES.DISABLED);
522
+ this.name = "PurchaseDisabledError";
523
+ }
524
+ };
525
+ var PurchaseUnauthenticatedError = class extends PurchaseError {
526
+ static {
527
+ __name(this, "PurchaseUnauthenticatedError");
528
+ }
529
+ constructor() {
530
+ super("Sem empresa autenticada.", 401, PURCHASE_ERROR_CODES.UNAUTHENTICATED);
531
+ this.name = "PurchaseUnauthenticatedError";
532
+ }
533
+ };
534
+ var PurchaseConfigMissingError = class extends PurchaseError {
535
+ static {
536
+ __name(this, "PurchaseConfigMissingError");
537
+ }
538
+ constructor(field) {
539
+ super(`Configura\xE7\xE3o ausente ou inv\xE1lida: ${field}.`, 500, PURCHASE_ERROR_CODES.CONFIG_MISSING, {
540
+ field
541
+ });
542
+ this.name = "PurchaseConfigMissingError";
543
+ }
544
+ };
545
+ var SupplierNotFoundError = class extends PurchaseError {
546
+ static {
547
+ __name(this, "SupplierNotFoundError");
548
+ }
549
+ constructor(supplierId) {
550
+ super("Fornecedor n\xE3o encontrado.", 404, PURCHASE_ERROR_CODES.SUPPLIER_NOT_FOUND, {
551
+ supplierId
552
+ });
553
+ this.name = "SupplierNotFoundError";
554
+ }
555
+ };
556
+ var SupplierInactiveError = class extends PurchaseError {
557
+ static {
558
+ __name(this, "SupplierInactiveError");
559
+ }
560
+ constructor(supplierId) {
561
+ super("Fornecedor desativado.", 422, PURCHASE_ERROR_CODES.SUPPLIER_INACTIVE, {
562
+ supplierId
563
+ });
564
+ this.name = "SupplierInactiveError";
565
+ }
566
+ };
567
+ var SupplierDocumentTakenError = class extends PurchaseError {
568
+ static {
569
+ __name(this, "SupplierDocumentTakenError");
570
+ }
571
+ constructor() {
572
+ super("J\xE1 existe fornecedor com este documento.", 409, PURCHASE_ERROR_CODES.SUPPLIER_DOCUMENT_TAKEN);
573
+ this.name = "SupplierDocumentTakenError";
574
+ }
575
+ };
576
+ var SupplierInUseError = class extends PurchaseError {
577
+ static {
578
+ __name(this, "SupplierInUseError");
579
+ }
580
+ constructor(supplierId) {
581
+ super("Fornecedor com pedidos ou recebimentos: desative em vez de excluir.", 409, PURCHASE_ERROR_CODES.SUPPLIER_IN_USE, {
582
+ supplierId
583
+ });
584
+ this.name = "SupplierInUseError";
585
+ }
586
+ };
587
+ var SupplierItemNotFoundError = class extends PurchaseError {
588
+ static {
589
+ __name(this, "SupplierItemNotFoundError");
590
+ }
591
+ constructor(supplierItemId) {
592
+ super("Item do fornecedor n\xE3o encontrado.", 404, PURCHASE_ERROR_CODES.SUPPLIER_ITEM_NOT_FOUND, {
593
+ supplierItemId
594
+ });
595
+ this.name = "SupplierItemNotFoundError";
596
+ }
597
+ };
598
+ var SupplierItemTakenError = class extends PurchaseError {
599
+ static {
600
+ __name(this, "SupplierItemTakenError");
601
+ }
602
+ constructor() {
603
+ super("Este fornecedor j\xE1 tem um item com este c\xF3digo ou ligado a este item do cat\xE1logo.", 409, PURCHASE_ERROR_CODES.SUPPLIER_ITEM_TAKEN);
604
+ this.name = "SupplierItemTakenError";
605
+ }
606
+ };
607
+ var PurchaseItemNotFoundError = class extends PurchaseError {
608
+ static {
609
+ __name(this, "PurchaseItemNotFoundError");
610
+ }
611
+ constructor(itemRef) {
612
+ super("Item n\xE3o encontrado no cat\xE1logo.", 404, PURCHASE_ERROR_CODES.ITEM_NOT_FOUND, {
613
+ itemRef
614
+ }, {
615
+ itemRef
616
+ });
617
+ this.name = "PurchaseItemNotFoundError";
618
+ }
619
+ };
620
+ var OrderNotFoundError = class extends PurchaseError {
621
+ static {
622
+ __name(this, "OrderNotFoundError");
623
+ }
624
+ constructor(orderId) {
625
+ super("Pedido de compra n\xE3o encontrado.", 404, PURCHASE_ERROR_CODES.ORDER_NOT_FOUND, {
626
+ orderId
627
+ });
628
+ this.name = "OrderNotFoundError";
629
+ }
630
+ };
631
+ var OrderLineNotFoundError = class extends PurchaseError {
632
+ static {
633
+ __name(this, "OrderLineNotFoundError");
634
+ }
635
+ constructor(orderLineId) {
636
+ super("Linha do pedido n\xE3o encontrada.", 422, PURCHASE_ERROR_CODES.ORDER_LINE_NOT_FOUND, {
637
+ orderLineId
638
+ }, {
639
+ orderLineId
640
+ });
641
+ this.name = "OrderLineNotFoundError";
642
+ }
643
+ };
644
+ var InvalidOrderTransitionError = class extends PurchaseError {
645
+ static {
646
+ __name(this, "InvalidOrderTransitionError");
647
+ }
648
+ constructor(params) {
649
+ super("A\xE7\xE3o n\xE3o permitida no status atual do pedido.", 409, PURCHASE_ERROR_CODES.INVALID_TRANSITION, params, params);
650
+ this.name = "InvalidOrderTransitionError";
651
+ }
652
+ };
653
+ var SelfApprovalError = class extends PurchaseError {
654
+ static {
655
+ __name(this, "SelfApprovalError");
656
+ }
657
+ constructor() {
658
+ super("Quem enviou o pedido para aprova\xE7\xE3o n\xE3o pode aprov\xE1-lo.", 403, PURCHASE_ERROR_CODES.SELF_APPROVAL);
659
+ this.name = "SelfApprovalError";
660
+ }
661
+ };
662
+ var ReceiptNotFoundError = class extends PurchaseError {
663
+ static {
664
+ __name(this, "ReceiptNotFoundError");
665
+ }
666
+ constructor(receiptId) {
667
+ super("Recebimento n\xE3o encontrado.", 404, PURCHASE_ERROR_CODES.RECEIPT_NOT_FOUND, {
668
+ receiptId
669
+ });
670
+ this.name = "ReceiptNotFoundError";
671
+ }
672
+ };
673
+ var InvoiceAlreadyReceivedError = class extends PurchaseError {
674
+ static {
675
+ __name(this, "InvoiceAlreadyReceivedError");
676
+ }
677
+ constructor(receiptId) {
678
+ super("Esta nota j\xE1 foi recebida.", 409, PURCHASE_ERROR_CODES.INVOICE_ALREADY_RECEIVED, {
679
+ receiptId
680
+ }, {
681
+ receiptId
682
+ });
683
+ this.name = "InvoiceAlreadyReceivedError";
684
+ }
685
+ };
686
+ var InstallmentsMismatchError = class extends PurchaseError {
687
+ static {
688
+ __name(this, "InstallmentsMismatchError");
689
+ }
690
+ constructor(params) {
691
+ super("A soma das parcelas n\xE3o fecha com o total do recebimento.", 422, PURCHASE_ERROR_CODES.INSTALLMENTS_MISMATCH, params, params);
692
+ this.name = "InstallmentsMismatchError";
693
+ }
694
+ };
695
+ var DispatchUnavailableError = class extends PurchaseError {
696
+ static {
697
+ __name(this, "DispatchUnavailableError");
698
+ }
699
+ constructor(channel) {
700
+ super("Envio por este canal n\xE3o est\xE1 configurado.", 422, PURCHASE_ERROR_CODES.DISPATCH_UNAVAILABLE, {
701
+ channel
702
+ }, {
703
+ channel
704
+ });
705
+ this.name = "DispatchUnavailableError";
706
+ }
707
+ };
708
+ var SupplierNoContactError = class extends PurchaseError {
709
+ static {
710
+ __name(this, "SupplierNoContactError");
711
+ }
712
+ constructor(channel) {
713
+ super("Fornecedor sem contato para este canal.", 422, PURCHASE_ERROR_CODES.NO_CONTACT, {
714
+ channel
715
+ }, {
716
+ channel
717
+ });
718
+ this.name = "SupplierNoContactError";
719
+ }
720
+ };
721
+ var NfeInvalidError = class extends PurchaseError {
722
+ static {
723
+ __name(this, "NfeInvalidError");
724
+ }
725
+ constructor(reason) {
726
+ super("XML de NF-e inv\xE1lido.", 422, PURCHASE_ERROR_CODES.NFE_INVALID, {
727
+ reason
728
+ }, {
729
+ reason
730
+ });
731
+ this.name = "NfeInvalidError";
732
+ }
733
+ };
734
+ var ReportRangeTooLongError = class extends PurchaseError {
735
+ static {
736
+ __name(this, "ReportRangeTooLongError");
737
+ }
738
+ constructor(maxDays) {
739
+ super("Per\xEDodo longo demais para o relat\xF3rio.", 422, PURCHASE_ERROR_CODES.REPORT_RANGE_TOO_LONG, {
740
+ maxDays
741
+ }, {
742
+ maxDays
743
+ });
744
+ this.name = "ReportRangeTooLongError";
745
+ }
746
+ };
747
+
748
+ // src/providers.ts
749
+ var DEFAULT_PURCHASE_SCOPES = {
750
+ read: [
751
+ "purchase:read"
752
+ ],
753
+ write: [
754
+ "purchase:write"
755
+ ],
756
+ approve: [
757
+ "purchase:approve"
758
+ ],
759
+ service: [
760
+ "purchase:service"
761
+ ]
762
+ };
763
+
764
+ // src/rules/orderStatus.ts
765
+ var ORDER_ACTION = {
766
+ EDIT: "edit",
767
+ SUBMIT: "submit",
768
+ APPROVE: "approve",
769
+ REJECT: "reject",
770
+ SEND: "send",
771
+ RECEIVE: "receive",
772
+ CLOSE: "close",
773
+ CANCEL: "cancel"
774
+ };
775
+ var ALLOWED = {
776
+ edit: [
777
+ ORDER_STATUS.DRAFT
778
+ ],
779
+ submit: [
780
+ ORDER_STATUS.DRAFT
781
+ ],
782
+ approve: [
783
+ ORDER_STATUS.PENDING_APPROVAL
784
+ ],
785
+ reject: [
786
+ ORDER_STATUS.PENDING_APPROVAL
787
+ ],
788
+ // Reenviar um pedido já enviado é permitido (fornecedor não recebeu, mudou de canal).
789
+ send: [
790
+ ORDER_STATUS.APPROVED,
791
+ ORDER_STATUS.SENT
792
+ ],
793
+ receive: [
794
+ ORDER_STATUS.APPROVED,
795
+ ORDER_STATUS.SENT,
796
+ ORDER_STATUS.PARTIALLY_RECEIVED
797
+ ],
798
+ close: [
799
+ ORDER_STATUS.PARTIALLY_RECEIVED
800
+ ],
801
+ cancel: [
802
+ ORDER_STATUS.DRAFT,
803
+ ORDER_STATUS.PENDING_APPROVAL,
804
+ ORDER_STATUS.APPROVED,
805
+ ORDER_STATUS.SENT
806
+ ]
807
+ };
808
+ function canPerform(status, action) {
809
+ return ALLOWED[action].includes(status);
810
+ }
811
+ __name(canPerform, "canPerform");
812
+ function allowedActions(status) {
813
+ return Object.keys(ALLOWED).filter((action) => canPerform(status, action));
814
+ }
815
+ __name(allowedActions, "allowedActions");
816
+ function statusAfterSend(status) {
817
+ return status === ORDER_STATUS.PARTIALLY_RECEIVED ? status : ORDER_STATUS.SENT;
818
+ }
819
+ __name(statusAfterSend, "statusAfterSend");
820
+ function requiresApproval(params) {
821
+ return params.thresholdCents !== null && params.totalCents > params.thresholdCents;
822
+ }
823
+ __name(requiresApproval, "requiresApproval");
824
+ function isOrderLate(params) {
825
+ if (!params.expectedAt) return false;
826
+ if (params.status !== ORDER_STATUS.APPROVED && params.status !== ORDER_STATUS.SENT && params.status !== ORDER_STATUS.PARTIALLY_RECEIVED) return false;
827
+ return params.expectedAt < params.today;
828
+ }
829
+ __name(isOrderLate, "isOrderLate");
830
+
831
+ // src/rules/totals.ts
832
+ import { divide as divide2, formatDecimal as formatDecimal2, multiply as multiply2, parseDecimal as parseDecimal3, rational as rational2, subtract as subtract2, ZERO as ZERO2 } from "@adatechnology/recipe-contracts";
833
+ function computeTotals(params) {
834
+ const subtotal = sum(params.lines.map((line) => lineTotal(line.quantity, line.unitPrice)));
835
+ const freight = parseDecimal3(params.freight ?? "0");
836
+ const discount = parseDecimal3(params.discount ?? "0");
837
+ const total = clampToZero(subtract2(add2(subtotal, freight), discount));
838
+ return {
839
+ subtotal: money(subtotal),
840
+ freight: money(freight),
841
+ discount: money(discount),
842
+ total: money(total)
843
+ };
844
+ }
845
+ __name(computeTotals, "computeTotals");
846
+ function add2(left, right) {
847
+ return sum([
848
+ left,
849
+ right
850
+ ]);
851
+ }
852
+ __name(add2, "add2");
853
+ function allocateExtras(params) {
854
+ const totals = params.lineTotals.map((value) => centsOf(parseDecimal3(value)));
855
+ const base = totals.reduce((acc, value) => acc + value, 0n);
856
+ const net = centsOf(parseDecimal3(params.freight)) - centsOf(parseDecimal3(params.discount));
857
+ if (totals.length === 0) return [];
858
+ if (base === 0n || net === 0n) {
859
+ if (net === 0n) return totals.map(() => "0.00");
860
+ return splitEvenly(net, totals.length).map((cents) => money(fromCentsBig(cents)));
861
+ }
862
+ const sign = net < 0n ? -1n : 1n;
863
+ const absolute = net * sign;
864
+ const shares = totals.map((value, index) => {
865
+ const exact = absolute * value;
866
+ return {
867
+ index,
868
+ floor: exact / base,
869
+ remainder: exact % base
870
+ };
871
+ });
872
+ let left = absolute - shares.reduce((acc, share) => acc + share.floor, 0n);
873
+ const byRemainder = [
874
+ ...shares
875
+ ].sort((a, b) => b.remainder > a.remainder ? 1 : b.remainder < a.remainder ? -1 : a.index - b.index);
876
+ const extra = /* @__PURE__ */ new Map();
877
+ for (const share of byRemainder) {
878
+ if (left <= 0n) break;
879
+ extra.set(share.index, 1n);
880
+ left -= 1n;
881
+ }
882
+ return shares.map((share) => money(fromCentsBig((share.floor + (extra.get(share.index) ?? 0n)) * sign)));
883
+ }
884
+ __name(allocateExtras, "allocateExtras");
885
+ function splitEvenly(cents, parts) {
886
+ const count = BigInt(parts);
887
+ const sign = cents < 0n ? -1n : 1n;
888
+ const absolute = cents * sign;
889
+ const base = absolute / count;
890
+ const rest = absolute % count;
891
+ return Array.from({
892
+ length: parts
893
+ }, (_, index) => (base + (BigInt(index) < rest ? 1n : 0n)) * sign);
894
+ }
895
+ __name(splitEvenly, "splitEvenly");
896
+ function landedUnitCost(params) {
897
+ const stockQuantity = multiply2(parseDecimal3(params.quantity), parseDecimal3(params.unitsPerPurchase));
898
+ if (compare(stockQuantity, ZERO2) <= 0) return null;
899
+ const value = clampToZero(sum([
900
+ parseDecimal3(params.lineTotal),
901
+ parseDecimal3(params.allocated)
902
+ ]));
903
+ return formatDecimal2(divide2(value, stockQuantity));
904
+ }
905
+ __name(landedUnitCost, "landedUnitCost");
906
+ function toStockQuantity(quantity, unitsPerPurchase) {
907
+ return quantityText(multiply2(parseDecimal3(quantity), parseDecimal3(unitsPerPurchase)));
908
+ }
909
+ __name(toStockQuantity, "toStockQuantity");
910
+ function pendingQuantity(params) {
911
+ const pending = subtract2(subtract2(parseDecimal3(params.quantity), parseDecimal3(params.receivedQuantity)), parseDecimal3(params.canceledQuantity));
912
+ return quantityText(clampToZero(pending));
913
+ }
914
+ __name(pendingQuantity, "pendingQuantity");
915
+ function statusAfterReceipt(lines) {
916
+ const anyPending = lines.some((line) => compare(parseDecimal3(pendingQuantity(line)), ZERO2) > 0);
917
+ return anyPending ? ORDER_STATUS.PARTIALLY_RECEIVED : ORDER_STATUS.RECEIVED;
918
+ }
919
+ __name(statusAfterReceipt, "statusAfterReceipt");
920
+ function divergenceOf(params) {
921
+ const quantity = params.pendingQuantity !== null && compare(parseDecimal3(params.receivedQuantity), parseDecimal3(params.pendingQuantity)) > 0;
922
+ const tolerance = params.priceToleranceCents ?? 0n;
923
+ let price = false;
924
+ if (params.orderedPrice !== null) {
925
+ const ordered = parseDecimal3(params.orderedPrice);
926
+ const received = parseDecimal3(params.receivedPrice);
927
+ const delta = centsOf(subtract2(received, ordered));
928
+ price = (delta < 0n ? -delta : delta) > tolerance;
929
+ }
930
+ if (quantity && price) return DIVERGENCE.BOTH;
931
+ if (quantity) return DIVERGENCE.QUANTITY;
932
+ if (price) return DIVERGENCE.PRICE;
933
+ return DIVERGENCE.NONE;
934
+ }
935
+ __name(divergenceOf, "divergenceOf");
936
+ function weightedAverageCost(points) {
937
+ const weight = sum(points.map((point) => parseDecimal3(point.quantity)));
938
+ if (compare(weight, ZERO2) <= 0) return null;
939
+ const value = sum(points.map((point) => multiply2(parseDecimal3(point.cost), parseDecimal3(point.quantity))));
940
+ return formatDecimal2(divide2(value, weight));
941
+ }
942
+ __name(weightedAverageCost, "weightedAverageCost");
943
+ var UNIT_FACTOR_ONE = formatDecimal2(rational2(1n));
944
+
945
+ // src/rules/suggestion.ts
946
+ import { divide as divide3, maximum, multiply as multiply3, parseDecimal as parseDecimal4, ROUNDING, roundToScale as roundToScale2, subtract as subtract3, ZERO as ZERO3 } from "@adatechnology/recipe-contracts";
947
+ function shortageOf(row) {
948
+ const onHand = clampToZero(parseDecimal4(row.onHandQuantity ?? "0"));
949
+ const byNeed = subtract3(parseDecimal4(row.neededQuantity), onHand);
950
+ const byMinimum = row.minimumQuantity === null ? ZERO3 : subtract3(parseDecimal4(row.minimumQuantity), onHand);
951
+ const raw = subtract3(maximum(byNeed, byMinimum), parseDecimal4(row.incomingQuantity));
952
+ return quantityText(clampToZero(raw));
953
+ }
954
+ __name(shortageOf, "shortageOf");
955
+ function packsFor(shortage, unitsPerPurchase) {
956
+ const packs = divide3(parseDecimal4(shortage), parseDecimal4(unitsPerPurchase));
957
+ return quantityText(roundToScale2(packs, 0, ROUNDING.UP));
958
+ }
959
+ __name(packsFor, "packsFor");
960
+ function comparePerStockUnit(left, right) {
961
+ if (left.lastPrice === null) return right.lastPrice === null ? 0 : 1;
962
+ if (right.lastPrice === null) return -1;
963
+ const leftCost = divide3(parseDecimal4(left.lastPrice), parseDecimal4(left.unitsPerPurchase));
964
+ const rightCost = divide3(parseDecimal4(right.lastPrice), parseDecimal4(right.unitsPerPurchase));
965
+ return compare(leftCost, rightCost);
966
+ }
967
+ __name(comparePerStockUnit, "comparePerStockUnit");
968
+ function buildSuggestion(params) {
969
+ const groups = /* @__PURE__ */ new Map();
970
+ for (const row of params.demand) {
971
+ const incomingQuantity = params.incoming.get(row.itemRef) ?? "0";
972
+ const shortage = shortageOf({
973
+ ...row,
974
+ incomingQuantity
975
+ });
976
+ if (compare(parseDecimal4(shortage), ZERO3) <= 0) continue;
977
+ const candidates = params.supplierItems.filter((item) => item.itemRef === row.itemRef && item.isActive && params.suppliers.get(item.supplierId)?.isActive === true && (params.supplierId === void 0 || item.supplierId === params.supplierId)).sort((left, right) => left.priority - right.priority || comparePerStockUnit(left, right));
978
+ const chosen = candidates[0];
979
+ if (!chosen && params.supplierId !== void 0) continue;
980
+ const suggested = chosen ? packsFor(shortage, chosen.unitsPerPurchase) : null;
981
+ const line = {
982
+ itemRef: row.itemRef,
983
+ itemName: row.itemName,
984
+ stockUnit: row.stockUnit,
985
+ neededQuantity: quantityText(parseDecimal4(row.neededQuantity)),
986
+ onHandQuantity: row.onHandQuantity === null ? null : quantityText(parseDecimal4(row.onHandQuantity)),
987
+ incomingQuantity: quantityText(parseDecimal4(incomingQuantity)),
988
+ minimumQuantity: row.minimumQuantity === null ? null : quantityText(parseDecimal4(row.minimumQuantity)),
989
+ shortageQuantity: shortage,
990
+ supplierItemId: chosen?.id ?? null,
991
+ purchaseUnit: chosen?.purchaseUnit ?? null,
992
+ unitsPerPurchase: chosen ? quantityText(parseDecimal4(chosen.unitsPerPurchase)) : null,
993
+ suggestedQuantity: suggested,
994
+ unitPrice: chosen?.lastPrice ? quantityText(parseDecimal4(chosen.lastPrice)) : null,
995
+ estimatedTotal: chosen?.lastPrice && suggested ? money(lineTotal(suggested, chosen.lastPrice)) : null
996
+ };
997
+ const key = chosen?.supplierId ?? null;
998
+ groups.set(key, [
999
+ ...groups.get(key) ?? [],
1000
+ line
1001
+ ]);
1002
+ }
1003
+ return [
1004
+ ...groups.entries()
1005
+ ].map(([supplierId, lines]) => {
1006
+ const supplier = supplierId ? params.suppliers.get(supplierId) : void 0;
1007
+ const estimated = sum(lines.map((line) => parseDecimal4(line.estimatedTotal ?? "0")));
1008
+ const minimum = supplier?.minimumOrderAmount ? parseDecimal4(supplier.minimumOrderAmount) : null;
1009
+ return {
1010
+ supplierId,
1011
+ supplierName: supplier?.name ?? null,
1012
+ lines: lines.sort((a, b) => a.itemName.localeCompare(b.itemName, "pt-BR")),
1013
+ estimatedTotal: money(estimated),
1014
+ belowMinimumOrder: minimum !== null && centsOf(estimated) < centsOf(minimum)
1015
+ };
1016
+ }).sort((left, right) => {
1017
+ if (left.supplierId === null) return 1;
1018
+ if (right.supplierId === null) return -1;
1019
+ return (left.supplierName ?? "").localeCompare(right.supplierName ?? "", "pt-BR");
1020
+ });
1021
+ }
1022
+ __name(buildSuggestion, "buildSuggestion");
1023
+ function stockQuantityOf(quantity, unitsPerPurchase) {
1024
+ return quantityText(multiply3(parseDecimal4(quantity), parseDecimal4(unitsPerPurchase)));
1025
+ }
1026
+ __name(stockQuantityOf, "stockQuantityOf");
1027
+
1028
+ // src/rules/orderMessage.ts
1029
+ import { formatDecimal as formatDecimal3, parseDecimal as parseDecimal5 } from "@adatechnology/recipe-contracts";
1030
+ function formatQuantityPt(value) {
1031
+ const [whole, fraction = ""] = value.split(".");
1032
+ const trimmed = fraction.replace(/0+$/, "");
1033
+ return trimmed ? `${whole},${trimmed}` : whole ?? value;
1034
+ }
1035
+ __name(formatQuantityPt, "formatQuantityPt");
1036
+ function formatMoneyPt(value) {
1037
+ const fixed = formatDecimal3(parseDecimal5(value), 2);
1038
+ const [whole = "0", fraction = "00"] = fixed.split(".");
1039
+ return `R$ ${whole.replace(/\B(?=(\d{3})+(?!\d))/g, ".")},${fraction}`;
1040
+ }
1041
+ __name(formatMoneyPt, "formatMoneyPt");
1042
+ function formatDatePt(date) {
1043
+ const [year, month, day] = date.split("-");
1044
+ return `${day}/${month}/${year}`;
1045
+ }
1046
+ __name(formatDatePt, "formatDatePt");
1047
+ function buildOrderMessage(input, options = {}) {
1048
+ const header = [
1049
+ `*Pedido de compra n\xBA ${input.number}* \u2014 ${input.companyName}`,
1050
+ `Fornecedor: ${input.supplierName}`
1051
+ ];
1052
+ const lines = input.lines.map((line) => {
1053
+ const sku = line.supplierSku ? ` (c\xF3d. ${line.supplierSku})` : "";
1054
+ const price = options.withPrices ? ` \u2014 ${formatMoneyPt(line.unitPrice)}/${line.purchaseUnit}` : "";
1055
+ return `\u2022 ${formatQuantityPt(line.quantity)} ${line.purchaseUnit} \u2014 ${line.itemName}${sku}${price}`;
1056
+ });
1057
+ const footer = [];
1058
+ if (input.expectedAt) footer.push(`Entrega: ${formatDatePt(input.expectedAt)}`);
1059
+ footer.push(`Pagamento: ${formatPaymentTerms(input.paymentTermDays)}`);
1060
+ if (options.withPrices) footer.push(`Total: ${formatMoneyPt(input.total)}`);
1061
+ if (input.notes.trim()) footer.push(`Obs.: ${input.notes.trim()}`);
1062
+ footer.push("Por favor, confirme o recebimento deste pedido.");
1063
+ return [
1064
+ ...header,
1065
+ "",
1066
+ ...lines,
1067
+ "",
1068
+ ...footer
1069
+ ].join("\n");
1070
+ }
1071
+ __name(buildOrderMessage, "buildOrderMessage");
1072
+
1073
+ // src/nfe/nfe.ts
1074
+ import { parseDecimal as parseDecimal6 } from "@adatechnology/recipe-contracts";
1075
+
1076
+ // src/nfe/xml.ts
1077
+ var ENTITIES = {
1078
+ amp: "&",
1079
+ lt: "<",
1080
+ gt: ">",
1081
+ quot: '"',
1082
+ apos: "'"
1083
+ };
1084
+ function decode(value) {
1085
+ return value.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (match, entity) => {
1086
+ if (entity[0] === "#") {
1087
+ const code = entity[1]?.toLowerCase() === "x" ? Number.parseInt(entity.slice(2), 16) : Number(entity.slice(1));
1088
+ return Number.isFinite(code) && code > 0 && code <= 1114111 ? String.fromCodePoint(code) : match;
1089
+ }
1090
+ return ENTITIES[entity.toLowerCase()] ?? match;
1091
+ });
1092
+ }
1093
+ __name(decode, "decode");
1094
+ function localName(name) {
1095
+ const index = name.indexOf(":");
1096
+ return index === -1 ? name : name.slice(index + 1);
1097
+ }
1098
+ __name(localName, "localName");
1099
+ var XmlParseError = class extends Error {
1100
+ static {
1101
+ __name(this, "XmlParseError");
1102
+ }
1103
+ constructor(message) {
1104
+ super(message);
1105
+ this.name = "XmlParseError";
1106
+ }
1107
+ };
1108
+ function parseXml(source) {
1109
+ const root = {
1110
+ name: "#root",
1111
+ attributes: {},
1112
+ children: [],
1113
+ text: ""
1114
+ };
1115
+ const stack = [
1116
+ root
1117
+ ];
1118
+ let index = 0;
1119
+ while (index < source.length) {
1120
+ const open = source.indexOf("<", index);
1121
+ if (open === -1) break;
1122
+ const parent = stack[stack.length - 1];
1123
+ if (open > index) parent.text += decode(source.slice(index, open));
1124
+ if (source.startsWith("<!--", open)) {
1125
+ const end = source.indexOf("-->", open + 4);
1126
+ if (end === -1) throw new XmlParseError("coment\xE1rio sem fim");
1127
+ index = end + 3;
1128
+ continue;
1129
+ }
1130
+ if (source.startsWith("<![CDATA[", open)) {
1131
+ const end = source.indexOf("]]>", open + 9);
1132
+ if (end === -1) throw new XmlParseError("CDATA sem fim");
1133
+ parent.text += source.slice(open + 9, end);
1134
+ index = end + 3;
1135
+ continue;
1136
+ }
1137
+ if (source.startsWith("<!", open)) throw new XmlParseError("DOCTYPE n\xE3o \xE9 aceito");
1138
+ if (source.startsWith("<?", open)) {
1139
+ const end = source.indexOf("?>", open + 2);
1140
+ if (end === -1) throw new XmlParseError("instru\xE7\xE3o sem fim");
1141
+ index = end + 2;
1142
+ continue;
1143
+ }
1144
+ const close = source.indexOf(">", open + 1);
1145
+ if (close === -1) throw new XmlParseError("tag sem fim");
1146
+ const raw = source.slice(open + 1, close);
1147
+ index = close + 1;
1148
+ if (raw.startsWith("/")) {
1149
+ const name = localName(raw.slice(1).trim());
1150
+ const current = stack.pop();
1151
+ if (!current || current.name !== name) throw new XmlParseError(`fechamento inesperado de ${name}`);
1152
+ continue;
1153
+ }
1154
+ const selfClosing = raw.endsWith("/");
1155
+ const body = selfClosing ? raw.slice(0, -1) : raw;
1156
+ const nameMatch = /^\s*([^\s/>]+)/.exec(body);
1157
+ if (!nameMatch?.[1]) throw new XmlParseError("tag sem nome");
1158
+ const attributes = {};
1159
+ const attributePattern = /([^\s=]+)\s*=\s*("([^"]*)"|'([^']*)')/g;
1160
+ let match;
1161
+ const rest = body.slice(nameMatch[0].length);
1162
+ while ((match = attributePattern.exec(rest)) !== null) {
1163
+ attributes[localName(match[1])] = decode(match[3] ?? match[4] ?? "");
1164
+ }
1165
+ const element = {
1166
+ name: localName(nameMatch[1]),
1167
+ attributes,
1168
+ children: [],
1169
+ text: ""
1170
+ };
1171
+ parent.children.push(element);
1172
+ if (!selfClosing) stack.push(element);
1173
+ }
1174
+ if (stack.length !== 1) throw new XmlParseError("documento incompleto");
1175
+ return root;
1176
+ }
1177
+ __name(parseXml, "parseXml");
1178
+ function child(element, name) {
1179
+ return element?.children.find((item) => item.name === name);
1180
+ }
1181
+ __name(child, "child");
1182
+ function childrenOf(element, name) {
1183
+ return element?.children.filter((item) => item.name === name) ?? [];
1184
+ }
1185
+ __name(childrenOf, "childrenOf");
1186
+ function textOf(element, name) {
1187
+ const found = child(element, name);
1188
+ const value = found?.text.trim();
1189
+ return value ? value : null;
1190
+ }
1191
+ __name(textOf, "textOf");
1192
+ function find(element, name) {
1193
+ for (const item of element.children) {
1194
+ if (item.name === name) return item;
1195
+ const nested = find(item, name);
1196
+ if (nested) return nested;
1197
+ }
1198
+ return void 0;
1199
+ }
1200
+ __name(find, "find");
1201
+
1202
+ // src/nfe/nfe.ts
1203
+ var NfeParseError = class extends Error {
1204
+ static {
1205
+ __name(this, "NfeParseError");
1206
+ }
1207
+ constructor(message) {
1208
+ super(message);
1209
+ this.name = "NfeParseError";
1210
+ }
1211
+ };
1212
+ function decimalOf(text, fallback = "0") {
1213
+ const value = (text ?? fallback).trim();
1214
+ if (!/^\d+(\.\d+)?$/.test(value)) throw new NfeParseError(`valor inv\xE1lido: ${value}`);
1215
+ const [whole = "0", fraction = ""] = value.split(".");
1216
+ const rounded = fraction.length > 4 ? roundFraction(whole, fraction) : `${whole}.${fraction || "0"}`;
1217
+ return quantityText(parseDecimal6(rounded));
1218
+ }
1219
+ __name(decimalOf, "decimalOf");
1220
+ function roundFraction(whole, fraction) {
1221
+ const scaled = BigInt(whole + fraction.slice(0, 4));
1222
+ const next = Number(fraction[4] ?? "0");
1223
+ const value = next >= 5 ? scaled + 1n : scaled;
1224
+ const text = value.toString().padStart(5, "0");
1225
+ return `${text.slice(0, -4)}.${text.slice(-4)}`;
1226
+ }
1227
+ __name(roundFraction, "roundFraction");
1228
+ function moneyOf(text) {
1229
+ return money(parseDecimal6(decimalOf(text)));
1230
+ }
1231
+ __name(moneyOf, "moneyOf");
1232
+ function dateOnly(text) {
1233
+ if (!text) return null;
1234
+ const match = /^(\d{4}-\d{2}-\d{2})/.exec(text.trim());
1235
+ return match?.[1] ?? null;
1236
+ }
1237
+ __name(dateOnly, "dateOnly");
1238
+ function parseItem(det) {
1239
+ const prod = child(det, "prod");
1240
+ if (!prod) throw new NfeParseError("item sem prod");
1241
+ const itemNumber = Number(det.attributes.nItem ?? "0");
1242
+ const ean = textOf(prod, "cEAN");
1243
+ const batches = childrenOf(prod, "rastro").map((rastro) => ({
1244
+ batchCode: textOf(rastro, "nLote") ?? "",
1245
+ quantity: decimalOf(textOf(rastro, "qLote")),
1246
+ expiresAt: dateOnly(textOf(rastro, "dVal"))
1247
+ }));
1248
+ return {
1249
+ itemNumber: Number.isInteger(itemNumber) ? itemNumber : 0,
1250
+ supplierSku: textOf(prod, "cProd") ?? "",
1251
+ ean: ean && ean.toUpperCase() !== "SEM GTIN" ? ean : null,
1252
+ description: textOf(prod, "xProd") ?? "",
1253
+ ncm: textOf(prod, "NCM"),
1254
+ cfop: textOf(prod, "CFOP"),
1255
+ unit: (textOf(prod, "uCom") ?? "UN").toUpperCase(),
1256
+ quantity: decimalOf(textOf(prod, "qCom")),
1257
+ unitPrice: decimalOf(textOf(prod, "vUnCom")),
1258
+ total: moneyOf(textOf(prod, "vProd")),
1259
+ discount: moneyOf(textOf(prod, "vDesc")),
1260
+ freight: moneyOf(textOf(prod, "vFrete")),
1261
+ batches: batches.filter((batch) => batch.batchCode !== "")
1262
+ };
1263
+ }
1264
+ __name(parseItem, "parseItem");
1265
+ function parseNfeXml(xml) {
1266
+ let root;
1267
+ try {
1268
+ root = parseXml(xml);
1269
+ } catch (error) {
1270
+ throw new NfeParseError(error instanceof XmlParseError ? error.message : "XML ileg\xEDvel");
1271
+ }
1272
+ const infNFe = find(root, "infNFe");
1273
+ if (!infNFe) throw new NfeParseError("n\xE3o \xE9 uma NF-e (sem infNFe)");
1274
+ const ide = child(infNFe, "ide");
1275
+ const model = textOf(ide, "mod");
1276
+ if (model && model !== "55" && model !== "65") throw new NfeParseError(`modelo ${model} n\xE3o \xE9 NF-e`);
1277
+ const idAttribute = infNFe.attributes.Id ?? "";
1278
+ const fromProtocol = find(root, "chNFe")?.text.trim() ?? "";
1279
+ const accessKey = (/(\d{44})/.exec(idAttribute)?.[1] ?? fromProtocol).trim();
1280
+ if (!/^\d{44}$/.test(accessKey)) throw new NfeParseError("chave de acesso ausente ou inv\xE1lida");
1281
+ const emit = child(infNFe, "emit");
1282
+ const dest = child(infNFe, "dest");
1283
+ const icmsTot = child(child(infNFe, "total"), "ICMSTot");
1284
+ const items = childrenOf(infNFe, "det").map(parseItem);
1285
+ if (items.length === 0) throw new NfeParseError("nota sem itens");
1286
+ const installments = childrenOf(child(infNFe, "cobr"), "dup").map((dup) => ({
1287
+ number: textOf(dup, "nDup") ?? "",
1288
+ dueDate: dateOnly(textOf(dup, "dVenc")) ?? "",
1289
+ amount: moneyOf(textOf(dup, "vDup"))
1290
+ }));
1291
+ return {
1292
+ accessKey,
1293
+ number: textOf(ide, "nNF") ?? "",
1294
+ series: textOf(ide, "serie"),
1295
+ issuedAt: textOf(ide, "dhEmi") ?? textOf(ide, "dEmi"),
1296
+ issuer: {
1297
+ document: textOf(emit, "CNPJ") ?? textOf(emit, "CPF"),
1298
+ name: textOf(emit, "xNome") ?? "",
1299
+ tradeName: textOf(emit, "xFant")
1300
+ },
1301
+ recipientDocument: textOf(dest, "CNPJ") ?? textOf(dest, "CPF"),
1302
+ items,
1303
+ totals: {
1304
+ products: moneyOf(textOf(icmsTot, "vProd")),
1305
+ freight: moneyOf(textOf(icmsTot, "vFrete")),
1306
+ discount: moneyOf(textOf(icmsTot, "vDesc")),
1307
+ other: moneyOf(textOf(icmsTot, "vOutro")),
1308
+ total: moneyOf(textOf(icmsTot, "vNF"))
1309
+ },
1310
+ installments: installments.filter((item) => item.dueDate !== "")
1311
+ };
1312
+ }
1313
+ __name(parseNfeXml, "parseNfeXml");
1314
+ export {
1315
+ DEFAULT_PURCHASE_SCOPES,
1316
+ DISPATCH_CHANNEL,
1317
+ DISPATCH_CHANNELS,
1318
+ DIVERGENCE,
1319
+ DispatchUnavailableError,
1320
+ INTEGRATION_STATUS,
1321
+ InstallmentsMismatchError,
1322
+ InvalidOrderTransitionError,
1323
+ InvoiceAlreadyReceivedError,
1324
+ MONEY_SCALE,
1325
+ NfeInvalidError,
1326
+ NfeParseError,
1327
+ OPEN_ORDER_STATUSES,
1328
+ ORDER_ACTION,
1329
+ ORDER_SORTS,
1330
+ ORDER_STATUS,
1331
+ ORDER_STATUSES,
1332
+ OrderLineNotFoundError,
1333
+ OrderNotFoundError,
1334
+ PAYMENT_STATUS,
1335
+ PURCHASE_ERROR_CODES,
1336
+ PURCHASE_LIMITS,
1337
+ PurchaseConfigMissingError,
1338
+ PurchaseDisabledError,
1339
+ PurchaseError,
1340
+ PurchaseItemNotFoundError,
1341
+ PurchaseUnauthenticatedError,
1342
+ REPORT_GROUP,
1343
+ REPORT_GROUPS,
1344
+ ReceiptNotFoundError,
1345
+ ReportRangeTooLongError,
1346
+ SORT_ORDER,
1347
+ SUPPLIER_SORTS,
1348
+ SelfApprovalError,
1349
+ SupplierDocumentTakenError,
1350
+ SupplierInUseError,
1351
+ SupplierInactiveError,
1352
+ SupplierItemNotFoundError,
1353
+ SupplierItemTakenError,
1354
+ SupplierNoContactError,
1355
+ SupplierNotFoundError,
1356
+ UNIT_FACTOR_ONE,
1357
+ ZERO,
1358
+ add,
1359
+ addDays,
1360
+ allocateExtras,
1361
+ allowedActions,
1362
+ buildInstallments,
1363
+ buildOrderMessage,
1364
+ buildSuggestion,
1365
+ canPerform,
1366
+ centsOf,
1367
+ civilDateIn,
1368
+ compare,
1369
+ computeTotals,
1370
+ createOrderSchema,
1371
+ createSupplierItemSchema,
1372
+ createSupplierSchema,
1373
+ divergenceOf,
1374
+ exportFormatSchema,
1375
+ formatMoneyPt,
1376
+ formatPaymentTerms,
1377
+ formatQuantityPt,
1378
+ isCivilDate,
1379
+ isOrderLate,
1380
+ itemRefsLookupSchema,
1381
+ landedUnitCost,
1382
+ lineTotal,
1383
+ listOrdersQuerySchema,
1384
+ listReceiptsQuerySchema,
1385
+ listSupplierItemsQuerySchema,
1386
+ listSuppliersQuerySchema,
1387
+ money,
1388
+ moneySchema,
1389
+ multiply,
1390
+ nfePreviewSchema,
1391
+ optionalReasonSchema,
1392
+ orderLineInputSchema,
1393
+ ordersFromSuggestionSchema,
1394
+ packsFor,
1395
+ parseNfeXml,
1396
+ parsePaymentTerms,
1397
+ pendingQuantity,
1398
+ priceHistoryQuerySchema,
1399
+ quantityText,
1400
+ reasonSchema,
1401
+ receiptLineInputSchema,
1402
+ receiveSchema,
1403
+ requiresApproval,
1404
+ sendOrderSchema,
1405
+ shortageOf,
1406
+ spendReportQuerySchema,
1407
+ statusAfterReceipt,
1408
+ statusAfterSend,
1409
+ stockQuantityOf,
1410
+ subtract,
1411
+ suggestionQuerySchema,
1412
+ supplierLookupSchema,
1413
+ supplierPerformanceQuerySchema,
1414
+ toStockQuantity,
1415
+ updateOrderSchema,
1416
+ updateSupplierItemSchema,
1417
+ updateSupplierSchema,
1418
+ weightedAverageCost
1419
+ };
1420
+ //# sourceMappingURL=index.js.map