@adatechnology/purchase-module 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,3326 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // ../../../node_modules/.pnpm/tsup@8.5.1_@swc+core@1.16.2_@swc+helpers@0.5.23__jiti@2.7.0_postcss@8.5.28_tsx@4.23.13_typescript@5.9.3_yaml@2.9.1/node_modules/tsup/assets/esm_shims.js
5
+ import path from "path";
6
+ import { fileURLToPath } from "url";
7
+ var getFilename = /* @__PURE__ */ __name(() => fileURLToPath(import.meta.url), "getFilename");
8
+ var getDirname = /* @__PURE__ */ __name(() => path.dirname(getFilename()), "getDirname");
9
+ var __dirname = /* @__PURE__ */ getDirname();
10
+
11
+ // src/PurchaseModule.ts
12
+ import { PurchaseConfigMissingError } from "@adatechnology/purchase-contracts";
13
+
14
+ // src/services/insights.ts
15
+ import { convertQuantity, formatDecimal, parseDecimal } from "@adatechnology/recipe-contracts";
16
+ import { add, addDays, buildSuggestion, OPEN_ORDER_STATUSES, pendingQuantity, quantityText, toStockQuantity, weightedAverageCost, ZERO } from "@adatechnology/purchase-contracts";
17
+ import { and, count, desc, eq, gte, inArray, isNotNull, lt } from "drizzle-orm";
18
+
19
+ // src/schema/schema.ts
20
+ import { sql } from "drizzle-orm";
21
+ import { boolean, check, date, index, integer, numeric, pgSchema, primaryKey, text, timestamp, uniqueIndex, uuid, varchar } from "drizzle-orm/pg-core";
22
+ var purchaseSchema = pgSchema("purchase");
23
+ var suppliers = purchaseSchema.table("suppliers", {
24
+ id: uuid("id").primaryKey().defaultRandom(),
25
+ companyId: uuid("company_id").notNull(),
26
+ name: varchar("name", {
27
+ length: 160
28
+ }).notNull(),
29
+ document: varchar("document", {
30
+ length: 20
31
+ }),
32
+ contactName: varchar("contact_name", {
33
+ length: 120
34
+ }),
35
+ email: varchar("email", {
36
+ length: 254
37
+ }),
38
+ phone: varchar("phone", {
39
+ length: 30
40
+ }),
41
+ whatsapp: varchar("whatsapp", {
42
+ length: 30
43
+ }),
44
+ paymentTermDays: integer("payment_term_days").array().notNull().default(sql`'{0}'::integer[]`),
45
+ leadTimeDays: integer("lead_time_days"),
46
+ minimumOrderAmount: numeric("minimum_order_amount", {
47
+ precision: 14,
48
+ scale: 2
49
+ }),
50
+ deliveryWeekdays: integer("delivery_weekdays").array().notNull().default(sql`'{}'::integer[]`),
51
+ notes: text("notes").notNull().default(""),
52
+ isActive: boolean("is_active").notNull().default(true),
53
+ createdAt: timestamp("created_at", {
54
+ withTimezone: true
55
+ }).notNull().defaultNow(),
56
+ updatedAt: timestamp("updated_at", {
57
+ withTimezone: true
58
+ }).notNull().defaultNow()
59
+ }, (table) => [
60
+ index("idx_purchase_suppliers_company_name").on(table.companyId, table.name),
61
+ uniqueIndex("uq_purchase_suppliers_company_document").on(table.companyId, table.document).where(sql`"document" is not null`)
62
+ ]);
63
+ var supplierItems = purchaseSchema.table("supplier_items", {
64
+ id: uuid("id").primaryKey().defaultRandom(),
65
+ companyId: uuid("company_id").notNull(),
66
+ supplierId: uuid("supplier_id").notNull().references(() => suppliers.id, {
67
+ onDelete: "cascade"
68
+ }),
69
+ itemRef: varchar("item_ref", {
70
+ length: 128
71
+ }),
72
+ itemName: varchar("item_name", {
73
+ length: 160
74
+ }).notNull(),
75
+ supplierSku: varchar("supplier_sku", {
76
+ length: 100
77
+ }),
78
+ purchaseUnit: varchar("purchase_unit", {
79
+ length: 12
80
+ }).notNull(),
81
+ unitsPerPurchase: numeric("units_per_purchase", {
82
+ precision: 14,
83
+ scale: 4
84
+ }).notNull().default("1"),
85
+ stockUnit: varchar("stock_unit", {
86
+ length: 8
87
+ }),
88
+ lastPrice: numeric("last_price", {
89
+ precision: 14,
90
+ scale: 4
91
+ }),
92
+ lastPriceAt: timestamp("last_price_at", {
93
+ withTimezone: true
94
+ }),
95
+ priority: integer("priority").notNull().default(0),
96
+ isActive: boolean("is_active").notNull().default(true),
97
+ createdAt: timestamp("created_at", {
98
+ withTimezone: true
99
+ }).notNull().defaultNow(),
100
+ updatedAt: timestamp("updated_at", {
101
+ withTimezone: true
102
+ }).notNull().defaultNow()
103
+ }, (table) => [
104
+ index("idx_purchase_supplier_items_item").on(table.companyId, table.itemRef),
105
+ uniqueIndex("uq_purchase_supplier_items_sku").on(table.companyId, table.supplierId, table.supplierSku).where(sql`"supplier_sku" is not null`),
106
+ uniqueIndex("uq_purchase_supplier_items_ref").on(table.companyId, table.supplierId, table.itemRef).where(sql`"item_ref" is not null`),
107
+ check("purchase_supplier_items_units_positive", sql`"units_per_purchase" > 0`),
108
+ check("purchase_supplier_items_price_not_negative", sql`"last_price" is null or "last_price" >= 0`)
109
+ ]);
110
+ var orderCounters = purchaseSchema.table("order_counters", {
111
+ companyId: uuid("company_id").primaryKey(),
112
+ lastNumber: integer("last_number").notNull().default(0)
113
+ });
114
+ var orders = purchaseSchema.table("orders", {
115
+ id: uuid("id").primaryKey().defaultRandom(),
116
+ companyId: uuid("company_id").notNull(),
117
+ number: integer("number").notNull(),
118
+ supplierId: uuid("supplier_id").notNull().references(() => suppliers.id),
119
+ status: varchar("status", {
120
+ length: 20
121
+ }).notNull().default("draft"),
122
+ expectedAt: date("expected_at", {
123
+ mode: "string"
124
+ }),
125
+ notes: text("notes").notNull().default(""),
126
+ subtotal: numeric("subtotal", {
127
+ precision: 14,
128
+ scale: 2
129
+ }).notNull().default("0"),
130
+ freight: numeric("freight", {
131
+ precision: 14,
132
+ scale: 2
133
+ }).notNull().default("0"),
134
+ discount: numeric("discount", {
135
+ precision: 14,
136
+ scale: 2
137
+ }).notNull().default("0"),
138
+ total: numeric("total", {
139
+ precision: 14,
140
+ scale: 2
141
+ }).notNull().default("0"),
142
+ paymentTermDays: integer("payment_term_days").array().notNull().default(sql`'{0}'::integer[]`),
143
+ requiresApproval: boolean("requires_approval").notNull().default(false),
144
+ createdBy: varchar("created_by", {
145
+ length: 128
146
+ }),
147
+ submittedBy: varchar("submitted_by", {
148
+ length: 128
149
+ }),
150
+ submittedAt: timestamp("submitted_at", {
151
+ withTimezone: true
152
+ }),
153
+ approvedBy: varchar("approved_by", {
154
+ length: 128
155
+ }),
156
+ approvedAt: timestamp("approved_at", {
157
+ withTimezone: true
158
+ }),
159
+ rejectionReason: varchar("rejection_reason", {
160
+ length: 500
161
+ }),
162
+ sentAt: timestamp("sent_at", {
163
+ withTimezone: true
164
+ }),
165
+ sentVia: varchar("sent_via", {
166
+ length: 12
167
+ }),
168
+ canceledAt: timestamp("canceled_at", {
169
+ withTimezone: true
170
+ }),
171
+ cancelReason: varchar("cancel_reason", {
172
+ length: 500
173
+ }),
174
+ closedAt: timestamp("closed_at", {
175
+ withTimezone: true
176
+ }),
177
+ lastLateAlertAt: date("last_late_alert_at", {
178
+ mode: "string"
179
+ }),
180
+ createdAt: timestamp("created_at", {
181
+ withTimezone: true
182
+ }).notNull().defaultNow(),
183
+ updatedAt: timestamp("updated_at", {
184
+ withTimezone: true
185
+ }).notNull().defaultNow()
186
+ }, (table) => [
187
+ uniqueIndex("uq_purchase_orders_company_number").on(table.companyId, table.number),
188
+ index("idx_purchase_orders_company_status").on(table.companyId, table.status, table.createdAt),
189
+ index("idx_purchase_orders_supplier").on(table.companyId, table.supplierId),
190
+ // Varredura de atraso e "a caminho": só pedido aberto.
191
+ index("idx_purchase_orders_open_expected").on(table.expectedAt).where(sql`"status" in ('approved', 'sent', 'partially_received')`)
192
+ ]);
193
+ var orderLines = purchaseSchema.table("order_lines", {
194
+ id: uuid("id").primaryKey().defaultRandom(),
195
+ orderId: uuid("order_id").notNull().references(() => orders.id, {
196
+ onDelete: "cascade"
197
+ }),
198
+ companyId: uuid("company_id").notNull(),
199
+ position: integer("position").notNull(),
200
+ supplierItemId: uuid("supplier_item_id").references(() => supplierItems.id, {
201
+ onDelete: "set null"
202
+ }),
203
+ itemRef: varchar("item_ref", {
204
+ length: 128
205
+ }),
206
+ itemName: varchar("item_name", {
207
+ length: 160
208
+ }).notNull(),
209
+ supplierSku: varchar("supplier_sku", {
210
+ length: 100
211
+ }),
212
+ purchaseUnit: varchar("purchase_unit", {
213
+ length: 12
214
+ }).notNull(),
215
+ unitsPerPurchase: numeric("units_per_purchase", {
216
+ precision: 14,
217
+ scale: 4
218
+ }).notNull().default("1"),
219
+ stockUnit: varchar("stock_unit", {
220
+ length: 8
221
+ }),
222
+ quantity: numeric("quantity", {
223
+ precision: 14,
224
+ scale: 4
225
+ }).notNull(),
226
+ unitPrice: numeric("unit_price", {
227
+ precision: 14,
228
+ scale: 4
229
+ }).notNull().default("0"),
230
+ lineTotal: numeric("line_total", {
231
+ precision: 14,
232
+ scale: 2
233
+ }).notNull().default("0"),
234
+ receivedQuantity: numeric("received_quantity", {
235
+ precision: 14,
236
+ scale: 4
237
+ }).notNull().default("0"),
238
+ canceledQuantity: numeric("canceled_quantity", {
239
+ precision: 14,
240
+ scale: 4
241
+ }).notNull().default("0"),
242
+ notes: varchar("notes", {
243
+ length: 500
244
+ })
245
+ }, (table) => [
246
+ index("idx_purchase_order_lines_order").on(table.orderId, table.position),
247
+ index("idx_purchase_order_lines_item").on(table.companyId, table.itemRef),
248
+ check("purchase_order_lines_quantity_positive", sql`"quantity" > 0`),
249
+ check("purchase_order_lines_units_positive", sql`"units_per_purchase" > 0`)
250
+ ]);
251
+ var receipts = purchaseSchema.table("receipts", {
252
+ id: uuid("id").primaryKey().defaultRandom(),
253
+ companyId: uuid("company_id").notNull(),
254
+ orderId: uuid("order_id").references(() => orders.id),
255
+ supplierId: uuid("supplier_id").notNull().references(() => suppliers.id),
256
+ receivedAt: timestamp("received_at", {
257
+ withTimezone: true
258
+ }).notNull(),
259
+ invoiceNumber: varchar("invoice_number", {
260
+ length: 30
261
+ }),
262
+ invoiceKey: varchar("invoice_key", {
263
+ length: 44
264
+ }),
265
+ invoiceIssuedAt: timestamp("invoice_issued_at", {
266
+ withTimezone: true
267
+ }),
268
+ subtotal: numeric("subtotal", {
269
+ precision: 14,
270
+ scale: 2
271
+ }).notNull(),
272
+ freight: numeric("freight", {
273
+ precision: 14,
274
+ scale: 2
275
+ }).notNull().default("0"),
276
+ discount: numeric("discount", {
277
+ precision: 14,
278
+ scale: 2
279
+ }).notNull().default("0"),
280
+ total: numeric("total", {
281
+ precision: 14,
282
+ scale: 2
283
+ }).notNull(),
284
+ notes: text("notes").notNull().default(""),
285
+ actorId: varchar("actor_id", {
286
+ length: 128
287
+ }),
288
+ idempotencyKey: varchar("idempotency_key", {
289
+ length: 128
290
+ }),
291
+ /** Parcelas combinadas no recebimento (JSON `[{number,dueDate,amount}]`), usadas pela conta a pagar. */
292
+ installments: text("installments").notNull().default("[]"),
293
+ stockStatus: varchar("stock_status", {
294
+ length: 10
295
+ }).notNull().default("skipped"),
296
+ payableStatus: varchar("payable_status", {
297
+ length: 10
298
+ }).notNull().default("skipped"),
299
+ payableRef: varchar("payable_ref", {
300
+ length: 200
301
+ }),
302
+ paymentStatus: varchar("payment_status", {
303
+ length: 10
304
+ }).notNull().default("none"),
305
+ createdAt: timestamp("created_at", {
306
+ withTimezone: true
307
+ }).notNull().defaultNow()
308
+ }, (table) => [
309
+ index("idx_purchase_receipts_company_received").on(table.companyId, table.receivedAt),
310
+ index("idx_purchase_receipts_order").on(table.orderId),
311
+ uniqueIndex("uq_purchase_receipts_invoice_key").on(table.companyId, table.invoiceKey).where(sql`"invoice_key" is not null`),
312
+ uniqueIndex("uq_purchase_receipts_idempotency").on(table.companyId, table.idempotencyKey).where(sql`"idempotency_key" is not null`),
313
+ index("idx_purchase_receipts_failed").on(table.companyId).where(sql`"stock_status" = 'failed' or "payable_status" = 'failed'`)
314
+ ]);
315
+ var receiptLines = purchaseSchema.table("receipt_lines", {
316
+ id: uuid("id").primaryKey().defaultRandom(),
317
+ receiptId: uuid("receipt_id").notNull().references(() => receipts.id, {
318
+ onDelete: "cascade"
319
+ }),
320
+ companyId: uuid("company_id").notNull(),
321
+ position: integer("position").notNull(),
322
+ orderLineId: uuid("order_line_id").references(() => orderLines.id, {
323
+ onDelete: "set null"
324
+ }),
325
+ supplierItemId: uuid("supplier_item_id").references(() => supplierItems.id, {
326
+ onDelete: "set null"
327
+ }),
328
+ itemRef: varchar("item_ref", {
329
+ length: 128
330
+ }),
331
+ itemName: varchar("item_name", {
332
+ length: 160
333
+ }).notNull(),
334
+ supplierSku: varchar("supplier_sku", {
335
+ length: 100
336
+ }),
337
+ purchaseUnit: varchar("purchase_unit", {
338
+ length: 12
339
+ }).notNull(),
340
+ unitsPerPurchase: numeric("units_per_purchase", {
341
+ precision: 14,
342
+ scale: 4
343
+ }).notNull().default("1"),
344
+ stockUnit: varchar("stock_unit", {
345
+ length: 8
346
+ }),
347
+ quantity: numeric("quantity", {
348
+ precision: 14,
349
+ scale: 4
350
+ }).notNull(),
351
+ unitPrice: numeric("unit_price", {
352
+ precision: 14,
353
+ scale: 4
354
+ }).notNull(),
355
+ lineTotal: numeric("line_total", {
356
+ precision: 14,
357
+ scale: 2
358
+ }).notNull(),
359
+ allocated: numeric("allocated", {
360
+ precision: 14,
361
+ scale: 2
362
+ }).notNull().default("0"),
363
+ landedUnitCost: numeric("landed_unit_cost", {
364
+ precision: 14,
365
+ scale: 4
366
+ }),
367
+ batchCode: varchar("batch_code", {
368
+ length: 100
369
+ }),
370
+ expiresAt: date("expires_at", {
371
+ mode: "string"
372
+ }),
373
+ divergence: varchar("divergence", {
374
+ length: 10
375
+ }).notNull().default("none"),
376
+ divergenceReason: varchar("divergence_reason", {
377
+ length: 500
378
+ }),
379
+ stockStatus: varchar("stock_status", {
380
+ length: 10
381
+ }).notNull().default("skipped")
382
+ }, (table) => [
383
+ index("idx_purchase_receipt_lines_receipt").on(table.receiptId, table.position),
384
+ // Histórico de preço e custo médio por item.
385
+ index("idx_purchase_receipt_lines_item").on(table.companyId, table.itemRef),
386
+ index("idx_purchase_receipt_lines_supplier_item").on(table.supplierItemId),
387
+ check("purchase_receipt_lines_quantity_positive", sql`"quantity" > 0`)
388
+ ]);
389
+ var receiptPayments = purchaseSchema.table("receipt_payments", {
390
+ companyId: uuid("company_id").notNull(),
391
+ receiptId: uuid("receipt_id").notNull().references(() => receipts.id, {
392
+ onDelete: "cascade"
393
+ }),
394
+ installmentNumber: integer("installment_number").notNull(),
395
+ paidAmount: numeric("paid_amount", {
396
+ precision: 14,
397
+ scale: 2
398
+ }).notNull(),
399
+ paidAt: date("paid_at", {
400
+ mode: "string"
401
+ }).notNull()
402
+ }, (table) => [
403
+ primaryKey({
404
+ columns: [
405
+ table.receiptId,
406
+ table.installmentNumber
407
+ ]
408
+ })
409
+ ]);
410
+
411
+ // src/shared/context.ts
412
+ import { civilDateIn, PurchaseDisabledError } from "@adatechnology/purchase-contracts";
413
+ async function assertEnabled(dependencies, companyId) {
414
+ const enabled = await dependencies.config.isEnabledForCompany?.(companyId) ?? true;
415
+ if (!enabled) throw new PurchaseDisabledError();
416
+ }
417
+ __name(assertEnabled, "assertEnabled");
418
+ function today(dependencies) {
419
+ return civilDateIn(dependencies.clock.now(), dependencies.timeZone);
420
+ }
421
+ __name(today, "today");
422
+ async function runHook(dependencies, name, meta, run) {
423
+ try {
424
+ await run();
425
+ } catch (error) {
426
+ dependencies.logger?.error(`purchase: gancho ${name} falhou`, {
427
+ ...meta,
428
+ error: error instanceof Error ? error.name : "unknown"
429
+ });
430
+ }
431
+ }
432
+ __name(runHook, "runHook");
433
+ function actorFields(actor) {
434
+ return {
435
+ companyId: actor.companyId,
436
+ ...actor.actorId ? {
437
+ actorId: actor.actorId
438
+ } : {}
439
+ };
440
+ }
441
+ __name(actorFields, "actorFields");
442
+ function paginated(params) {
443
+ return {
444
+ data: params.rows.map(params.map),
445
+ pagination: {
446
+ total: params.total,
447
+ page: params.page,
448
+ pageSize: params.pageSize,
449
+ totalPages: Math.max(1, Math.ceil(params.total / params.pageSize))
450
+ }
451
+ };
452
+ }
453
+ __name(paginated, "paginated");
454
+
455
+ // src/services/insights.ts
456
+ function createInsightService(dependencies, orderService) {
457
+ const { db } = dependencies;
458
+ async function incoming(params) {
459
+ await assertEnabled(dependencies, params.companyId);
460
+ const refs = [
461
+ ...new Set(params.itemRefs)
462
+ ];
463
+ if (refs.length === 0) return [];
464
+ const rows = await db.select({
465
+ line: orderLines,
466
+ expectedAt: orders.expectedAt
467
+ }).from(orderLines).innerJoin(orders, eq(orders.id, orderLines.orderId)).where(and(eq(orderLines.companyId, params.companyId), inArray(orderLines.itemRef, refs), isNotNull(orderLines.stockUnit), inArray(orders.status, [
468
+ ...OPEN_ORDER_STATUSES
469
+ ])));
470
+ const byItem = /* @__PURE__ */ new Map();
471
+ for (const { line, expectedAt } of rows) {
472
+ const pending = parseDecimal(toStockQuantity(pendingQuantity(line), line.unitsPerPurchase));
473
+ if (pending.numerator === 0n) continue;
474
+ const ref = line.itemRef;
475
+ const unit = line.stockUnit;
476
+ const current = byItem.get(ref) ?? {
477
+ quantity: ZERO,
478
+ unit,
479
+ orders: /* @__PURE__ */ new Set(),
480
+ next: null
481
+ };
482
+ const converted = convertQuantity({
483
+ quantity: pending,
484
+ from: unit,
485
+ to: current.unit
486
+ }) ?? pending;
487
+ current.quantity = add(current.quantity, converted);
488
+ current.orders.add(line.orderId);
489
+ if (expectedAt && (current.next === null || expectedAt < current.next)) current.next = expectedAt;
490
+ byItem.set(ref, current);
491
+ }
492
+ return [
493
+ ...byItem.entries()
494
+ ].map(([itemRef, value]) => ({
495
+ itemRef,
496
+ quantity: quantityText(value.quantity),
497
+ unit: value.unit,
498
+ orderCount: value.orders.size,
499
+ nextExpectedAt: value.next
500
+ }));
501
+ }
502
+ __name(incoming, "incoming");
503
+ async function itemCosts(params) {
504
+ await assertEnabled(dependencies, params.companyId);
505
+ const refs = [
506
+ ...new Set(params.itemRefs)
507
+ ];
508
+ if (refs.length === 0) return [];
509
+ const windowDays = dependencies.averageCostWindowDays;
510
+ const since = new Date(dependencies.clock.now().getTime() - windowDays * 864e5);
511
+ const rows = await db.select({
512
+ itemRef: receiptLines.itemRef,
513
+ stockUnit: receiptLines.stockUnit,
514
+ cost: receiptLines.landedUnitCost,
515
+ quantity: receiptLines.quantity,
516
+ unitsPerPurchase: receiptLines.unitsPerPurchase,
517
+ receivedAt: receipts.receivedAt,
518
+ supplierId: receipts.supplierId
519
+ }).from(receiptLines).innerJoin(receipts, eq(receipts.id, receiptLines.receiptId)).where(and(eq(receiptLines.companyId, params.companyId), inArray(receiptLines.itemRef, refs), isNotNull(receiptLines.landedUnitCost))).orderBy(desc(receipts.receivedAt));
520
+ return refs.map((itemRef) => {
521
+ const points = rows.filter((row) => row.itemRef === itemRef);
522
+ const last = points[0];
523
+ const unit = last?.stockUnit ?? null;
524
+ const recent = points.filter((row) => row.receivedAt >= since);
525
+ const normalized = recent.flatMap((row) => {
526
+ const from = row.stockUnit ?? unit;
527
+ const quantity = toStockQuantity(row.quantity, row.unitsPerPurchase);
528
+ if (!from || !unit || from === unit) return [
529
+ {
530
+ cost: row.cost,
531
+ quantity
532
+ }
533
+ ];
534
+ const factor = convertQuantity({
535
+ quantity: parseDecimal("1"),
536
+ from: unit,
537
+ to: from
538
+ });
539
+ const converted = convertQuantity({
540
+ quantity: parseDecimal(quantity),
541
+ from,
542
+ to: unit
543
+ });
544
+ if (!factor || !converted) return [];
545
+ const cost = formatDecimal({
546
+ numerator: parseDecimal(row.cost).numerator * factor.numerator,
547
+ denominator: parseDecimal(row.cost).denominator * factor.denominator
548
+ });
549
+ return [
550
+ {
551
+ cost,
552
+ quantity: formatDecimal(converted)
553
+ }
554
+ ];
555
+ });
556
+ return {
557
+ itemRef,
558
+ stockUnit: unit,
559
+ lastCost: last?.cost ?? null,
560
+ lastReceivedAt: last ? last.receivedAt.toISOString() : null,
561
+ lastSupplierId: last?.supplierId ?? null,
562
+ averageCost: weightedAverageCost(normalized),
563
+ averageWindowDays: windowDays
564
+ };
565
+ });
566
+ }
567
+ __name(itemCosts, "itemCosts");
568
+ return {
569
+ incoming,
570
+ itemCosts,
571
+ async priceHistory(params) {
572
+ await assertEnabled(dependencies, params.companyId);
573
+ const { query } = params;
574
+ const conditions = [
575
+ eq(receiptLines.companyId, params.companyId)
576
+ ];
577
+ if (query.itemRef) conditions.push(eq(receiptLines.itemRef, query.itemRef));
578
+ if (query.supplierItemId) conditions.push(eq(receiptLines.supplierItemId, query.supplierItemId));
579
+ if (query.supplierId) conditions.push(eq(receipts.supplierId, query.supplierId));
580
+ if (query.from) conditions.push(gte(receipts.receivedAt, /* @__PURE__ */ new Date(`${query.from}T00:00:00Z`)));
581
+ if (query.to) conditions.push(lt(receipts.receivedAt, /* @__PURE__ */ new Date(`${addDays(query.to, 1)}T00:00:00Z`)));
582
+ const where = and(...conditions);
583
+ const [rows, totals] = await Promise.all([
584
+ db.select({
585
+ line: receiptLines,
586
+ receipt: receipts,
587
+ supplierName: suppliers.name
588
+ }).from(receiptLines).innerJoin(receipts, eq(receipts.id, receiptLines.receiptId)).innerJoin(suppliers, eq(suppliers.id, receipts.supplierId)).where(where).orderBy(desc(receipts.receivedAt), desc(receiptLines.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
589
+ db.select({
590
+ total: count()
591
+ }).from(receiptLines).innerJoin(receipts, eq(receipts.id, receiptLines.receiptId)).where(where)
592
+ ]);
593
+ return paginated({
594
+ rows,
595
+ total: totals[0]?.total ?? 0,
596
+ page: query.page,
597
+ pageSize: query.pageSize,
598
+ map: /* @__PURE__ */ __name((row) => ({
599
+ supplierId: row.receipt.supplierId,
600
+ supplierName: row.supplierName,
601
+ receiptId: row.receipt.id,
602
+ receivedAt: row.receipt.receivedAt.toISOString(),
603
+ purchaseUnit: row.line.purchaseUnit,
604
+ unitPrice: quantityText(parseDecimal(row.line.unitPrice)),
605
+ landedUnitCost: row.line.landedUnitCost === null ? null : quantityText(parseDecimal(row.line.landedUnitCost)),
606
+ stockUnit: row.line.stockUnit ?? null
607
+ }), "map")
608
+ });
609
+ },
610
+ async suggestion(params) {
611
+ await assertEnabled(dependencies, params.companyId);
612
+ const demandSource = dependencies.providers.demand;
613
+ if (!demandSource) return {
614
+ groups: [],
615
+ hasDemandSource: false
616
+ };
617
+ const demand = await demandSource.getDemand({
618
+ companyId: params.companyId
619
+ });
620
+ const refs = demand.map((row) => row.itemRef);
621
+ if (refs.length === 0) return {
622
+ groups: [],
623
+ hasDemandSource: true
624
+ };
625
+ const [incomingRows, items, supplierRows] = await Promise.all([
626
+ incoming({
627
+ companyId: params.companyId,
628
+ itemRefs: refs
629
+ }),
630
+ db.select().from(supplierItems).where(and(eq(supplierItems.companyId, params.companyId), inArray(supplierItems.itemRef, refs))),
631
+ db.select().from(suppliers).where(eq(suppliers.companyId, params.companyId))
632
+ ]);
633
+ const demandUnits = new Map(demand.map((row) => [
634
+ row.itemRef,
635
+ row.stockUnit
636
+ ]));
637
+ const incomingMap = new Map(incomingRows.map((row) => {
638
+ const target = demandUnits.get(row.itemRef) ?? row.unit;
639
+ const converted = convertQuantity({
640
+ quantity: parseDecimal(row.quantity),
641
+ from: row.unit,
642
+ to: target
643
+ });
644
+ return [
645
+ row.itemRef,
646
+ converted ? formatDecimal(converted) : row.quantity
647
+ ];
648
+ }));
649
+ return {
650
+ hasDemandSource: true,
651
+ groups: buildSuggestion({
652
+ demand,
653
+ incoming: incomingMap,
654
+ supplierItems: items,
655
+ suppliers: new Map(supplierRows.map((row) => [
656
+ row.id,
657
+ {
658
+ id: row.id,
659
+ name: row.name,
660
+ minimumOrderAmount: row.minimumOrderAmount,
661
+ isActive: row.isActive
662
+ }
663
+ ])),
664
+ ...params.query.supplierId ? {
665
+ supplierId: params.query.supplierId
666
+ } : {}
667
+ })
668
+ };
669
+ },
670
+ /** Um rascunho por fornecedor da sugestão (itens sem fornecedor ficam de fora). */
671
+ async ordersFromSuggestion(params) {
672
+ const suggestion = await this.suggestion({
673
+ companyId: params.companyId,
674
+ query: {}
675
+ });
676
+ const wanted = params.input.supplierIds ? new Set(params.input.supplierIds) : null;
677
+ const created = [];
678
+ for (const group of suggestion.groups) {
679
+ if (!group.supplierId || wanted && !wanted.has(group.supplierId)) continue;
680
+ const lines = group.lines.filter((line) => line.supplierItemId && line.suggestedQuantity);
681
+ if (lines.length === 0) continue;
682
+ created.push(await orderService().create({
683
+ ...params,
684
+ input: {
685
+ supplierId: group.supplierId,
686
+ notes: "",
687
+ freight: "0",
688
+ discount: "0",
689
+ ...params.input.expectedAt !== void 0 ? {
690
+ expectedAt: params.input.expectedAt
691
+ } : {},
692
+ lines: lines.map((line) => ({
693
+ supplierItemId: line.supplierItemId,
694
+ quantity: line.suggestedQuantity
695
+ }))
696
+ }
697
+ }));
698
+ }
699
+ return created;
700
+ },
701
+ /** Pedidos abertos com previsão vencida, por empresa, para `scanLateOrders`. */
702
+ async lateOrders(params = {}) {
703
+ const day = today(dependencies);
704
+ const conditions = [
705
+ inArray(orders.status, [
706
+ ...OPEN_ORDER_STATUSES
707
+ ]),
708
+ lt(orders.expectedAt, day)
709
+ ];
710
+ if (params.companyId) conditions.push(eq(orders.companyId, params.companyId));
711
+ const rows = await db.select({
712
+ order: orders,
713
+ supplierName: suppliers.name
714
+ }).from(orders).innerJoin(suppliers, eq(suppliers.id, orders.supplierId)).where(and(...conditions));
715
+ return {
716
+ day,
717
+ rows
718
+ };
719
+ }
720
+ };
721
+ }
722
+ __name(createInsightService, "createInsightService");
723
+
724
+ // src/services/jobs.ts
725
+ import { inArray as inArray2 } from "drizzle-orm";
726
+ function daysLate(expectedAt, today2) {
727
+ return Math.round((Date.parse(`${today2}T00:00:00Z`) - Date.parse(`${expectedAt}T00:00:00Z`)) / 864e5);
728
+ }
729
+ __name(daysLate, "daysLate");
730
+ function createJobService(dependencies, insights) {
731
+ return {
732
+ async scanLateOrders(params = {}) {
733
+ const { day, rows } = await insights().lateOrders(params);
734
+ const fresh = rows.filter((row) => row.order.lastLateAlertAt !== day);
735
+ const byCompany = /* @__PURE__ */ new Map();
736
+ for (const row of fresh) byCompany.set(row.order.companyId, [
737
+ ...byCompany.get(row.order.companyId) ?? [],
738
+ row
739
+ ]);
740
+ for (const [companyId, items] of byCompany) {
741
+ const enabled = await dependencies.config.isEnabledForCompany?.(companyId) ?? true;
742
+ if (!enabled) continue;
743
+ await runHook(dependencies, "onOrdersLate", {
744
+ companyId
745
+ }, () => dependencies.hooks.onOrdersLate?.({
746
+ companyId,
747
+ orders: items.map((row) => ({
748
+ orderId: row.order.id,
749
+ number: row.order.number,
750
+ supplierId: row.order.supplierId,
751
+ supplierName: row.supplierName,
752
+ expectedAt: row.order.expectedAt,
753
+ daysLate: daysLate(row.order.expectedAt, day)
754
+ }))
755
+ }));
756
+ await dependencies.db.update(orders).set({
757
+ lastLateAlertAt: day
758
+ }).where(inArray2(orders.id, items.map((row) => row.order.id)));
759
+ }
760
+ return {
761
+ companies: byCompany.size,
762
+ orders: fresh.length
763
+ };
764
+ }
765
+ };
766
+ }
767
+ __name(createJobService, "createJobService");
768
+
769
+ // src/services/nfe.ts
770
+ import { normalizeDecimal, parseDecimal as parseDecimal2 } from "@adatechnology/recipe-contracts";
771
+ import { compare, NfeInvalidError, NfeParseError, OrderNotFoundError, parseNfeXml, pendingQuantity as pendingQuantity2, ZERO as ZERO2 } from "@adatechnology/purchase-contracts";
772
+ import { and as and2, eq as eq2 } from "drizzle-orm";
773
+ function createNfeService(dependencies) {
774
+ const { db } = dependencies;
775
+ return {
776
+ async preview(params) {
777
+ await assertEnabled(dependencies, params.companyId);
778
+ let nfe;
779
+ try {
780
+ nfe = parseNfeXml(params.xml);
781
+ } catch (error) {
782
+ throw new NfeInvalidError(error instanceof NfeParseError ? error.message : "XML ileg\xEDvel");
783
+ }
784
+ const [supplier] = nfe.issuer.document ? await db.select().from(suppliers).where(and2(eq2(suppliers.companyId, params.companyId), eq2(suppliers.document, nfe.issuer.document))) : [];
785
+ const [existing] = await db.select({
786
+ id: receipts.id
787
+ }).from(receipts).where(and2(eq2(receipts.companyId, params.companyId), eq2(receipts.invoiceKey, nfe.accessKey)));
788
+ const items = supplier ? await db.select().from(supplierItems).where(and2(eq2(supplierItems.companyId, params.companyId), eq2(supplierItems.supplierId, supplier.id))) : [];
789
+ const bySku = new Map(items.flatMap((item) => item.supplierSku ? [
790
+ [
791
+ item.supplierSku.toUpperCase(),
792
+ item
793
+ ]
794
+ ] : []));
795
+ let pending = [];
796
+ if (params.orderId) {
797
+ const [order] = await db.select().from(orders).where(and2(eq2(orders.companyId, params.companyId), eq2(orders.id, params.orderId)));
798
+ if (!order) throw new OrderNotFoundError(params.orderId);
799
+ if (supplier && order.supplierId !== supplier.id) pending = [];
800
+ else pending = (await db.select().from(orderLines).where(eq2(orderLines.orderId, order.id))).filter((line) => compare(parseDecimal2(pendingQuantity2(line)), ZERO2) > 0);
801
+ }
802
+ const usedOrderLines = /* @__PURE__ */ new Set();
803
+ const lines = nfe.items.flatMap((item) => {
804
+ const supplierItem = bySku.get(item.supplierSku.toUpperCase());
805
+ const orderLine = pending.find((line) => !usedOrderLines.has(line.id) && (supplierItem && line.supplierItemId === supplierItem.id || line.supplierSku !== null && line.supplierSku.toUpperCase() === item.supplierSku.toUpperCase()));
806
+ if (orderLine) usedOrderLines.add(orderLine.id);
807
+ const batches = item.batches.length > 0 ? item.batches : [
808
+ null
809
+ ];
810
+ return batches.map((batch) => ({
811
+ itemNumber: item.itemNumber,
812
+ supplierSku: item.supplierSku,
813
+ description: item.description,
814
+ unit: item.unit,
815
+ quantity: batch ? batch.quantity : item.quantity,
816
+ unitPrice: item.unitPrice,
817
+ total: item.total,
818
+ batchCode: batch?.batchCode ?? null,
819
+ expiresAt: batch?.expiresAt ?? null,
820
+ supplierItemId: supplierItem?.id ?? null,
821
+ itemRef: supplierItem?.itemRef ?? orderLine?.itemRef ?? null,
822
+ itemName: supplierItem?.itemName ?? orderLine?.itemName ?? null,
823
+ unitsPerPurchase: supplierItem ? normalizeDecimal(supplierItem.unitsPerPurchase) : null,
824
+ stockUnit: supplierItem?.stockUnit ?? orderLine?.stockUnit ?? null,
825
+ orderLineId: orderLine?.id ?? null
826
+ }));
827
+ });
828
+ return {
829
+ accessKey: nfe.accessKey,
830
+ number: nfe.number,
831
+ series: nfe.series,
832
+ issuedAt: nfe.issuedAt,
833
+ issuer: {
834
+ document: nfe.issuer.document,
835
+ name: nfe.issuer.name
836
+ },
837
+ supplierId: supplier?.id ?? null,
838
+ alreadyReceivedReceiptId: existing?.id ?? null,
839
+ freight: nfe.totals.freight,
840
+ discount: nfe.totals.discount,
841
+ total: nfe.totals.total,
842
+ installments: nfe.installments.map((installment, index2) => ({
843
+ number: index2 + 1,
844
+ dueDate: installment.dueDate,
845
+ amount: installment.amount
846
+ })),
847
+ lines
848
+ };
849
+ }
850
+ };
851
+ }
852
+ __name(createNfeService, "createNfeService");
853
+
854
+ // src/services/orders.ts
855
+ import { normalizeDecimal as normalizeDecimal3, parseDecimal as parseDecimal4 } from "@adatechnology/recipe-contracts";
856
+ import { addDays as addDays2, buildOrderMessage, canPerform, centsOf, computeTotals, DispatchUnavailableError, DISPATCH_CHANNEL, InvalidOrderTransitionError, lineTotal, money as money2, ORDER_ACTION, ORDER_STATUS, OrderNotFoundError as OrderNotFoundError2, pendingQuantity as pendingQuantity4, requiresApproval as needsApproval, SelfApprovalError, statusAfterSend, SupplierInactiveError, SupplierItemNotFoundError as SupplierItemNotFoundError2, SupplierNoContactError } from "@adatechnology/purchase-contracts";
857
+ import { and as and4, asc as asc2, count as count3, desc as desc3, eq as eq4, gte as gte2, ilike as ilike2, inArray as inArray4, lt as lt2, lte, or as or2, sql as sql2 } from "drizzle-orm";
858
+
859
+ // src/shared/mappers.ts
860
+ import { normalizeDecimal as normalizeDecimal2 } from "@adatechnology/recipe-contracts";
861
+ import { isOrderLate, money, pendingQuantity as pendingQuantity3 } from "@adatechnology/purchase-contracts";
862
+ import { parseDecimal as parseDecimal3 } from "@adatechnology/recipe-contracts";
863
+ var intList = /* @__PURE__ */ __name((value) => Array.from(value ?? []), "intList");
864
+ var iso = /* @__PURE__ */ __name((value) => value ? value.toISOString() : null, "iso");
865
+ var decimal = /* @__PURE__ */ __name((value) => normalizeDecimal2(value), "decimal");
866
+ var moneyText = /* @__PURE__ */ __name((value) => money(parseDecimal3(value)), "moneyText");
867
+ function toSupplier(row) {
868
+ return {
869
+ id: row.id,
870
+ name: row.name,
871
+ document: row.document,
872
+ contactName: row.contactName,
873
+ email: row.email,
874
+ phone: row.phone,
875
+ whatsapp: row.whatsapp,
876
+ paymentTermDays: intList(row.paymentTermDays),
877
+ leadTimeDays: row.leadTimeDays,
878
+ minimumOrderAmount: row.minimumOrderAmount === null ? null : moneyText(row.minimumOrderAmount),
879
+ deliveryWeekdays: intList(row.deliveryWeekdays),
880
+ notes: row.notes,
881
+ isActive: row.isActive,
882
+ createdAt: row.createdAt.toISOString(),
883
+ updatedAt: row.updatedAt.toISOString()
884
+ };
885
+ }
886
+ __name(toSupplier, "toSupplier");
887
+ function toSupplierItem(row) {
888
+ return {
889
+ id: row.id,
890
+ supplierId: row.supplierId,
891
+ itemRef: row.itemRef,
892
+ itemName: row.itemName,
893
+ supplierSku: row.supplierSku,
894
+ purchaseUnit: row.purchaseUnit,
895
+ unitsPerPurchase: decimal(row.unitsPerPurchase),
896
+ stockUnit: row.stockUnit ?? null,
897
+ lastPrice: row.lastPrice === null ? null : decimal(row.lastPrice),
898
+ lastPriceAt: iso(row.lastPriceAt),
899
+ priority: row.priority,
900
+ isActive: row.isActive,
901
+ createdAt: row.createdAt.toISOString(),
902
+ updatedAt: row.updatedAt.toISOString()
903
+ };
904
+ }
905
+ __name(toSupplierItem, "toSupplierItem");
906
+ function toOrderLine(row) {
907
+ return {
908
+ id: row.id,
909
+ position: row.position,
910
+ supplierItemId: row.supplierItemId,
911
+ itemRef: row.itemRef,
912
+ itemName: row.itemName,
913
+ supplierSku: row.supplierSku,
914
+ purchaseUnit: row.purchaseUnit,
915
+ unitsPerPurchase: decimal(row.unitsPerPurchase),
916
+ stockUnit: row.stockUnit ?? null,
917
+ quantity: decimal(row.quantity),
918
+ unitPrice: decimal(row.unitPrice),
919
+ lineTotal: moneyText(row.lineTotal),
920
+ receivedQuantity: decimal(row.receivedQuantity),
921
+ canceledQuantity: decimal(row.canceledQuantity),
922
+ pendingQuantity: pendingQuantity3(row),
923
+ notes: row.notes
924
+ };
925
+ }
926
+ __name(toOrderLine, "toOrderLine");
927
+ function toOrderSummary(params) {
928
+ const { row } = params;
929
+ return {
930
+ id: row.id,
931
+ number: row.number,
932
+ supplierId: row.supplierId,
933
+ supplierName: params.supplierName,
934
+ status: row.status,
935
+ expectedAt: row.expectedAt,
936
+ isLate: isOrderLate({
937
+ status: row.status,
938
+ expectedAt: row.expectedAt,
939
+ today: params.today
940
+ }),
941
+ subtotal: moneyText(row.subtotal),
942
+ freight: moneyText(row.freight),
943
+ discount: moneyText(row.discount),
944
+ total: moneyText(row.total),
945
+ paymentTermDays: intList(row.paymentTermDays),
946
+ notes: row.notes,
947
+ requiresApproval: row.requiresApproval,
948
+ createdBy: row.createdBy,
949
+ submittedAt: iso(row.submittedAt),
950
+ approvedBy: row.approvedBy,
951
+ approvedAt: iso(row.approvedAt),
952
+ rejectionReason: row.rejectionReason,
953
+ sentAt: iso(row.sentAt),
954
+ sentVia: row.sentVia ?? null,
955
+ canceledAt: iso(row.canceledAt),
956
+ cancelReason: row.cancelReason,
957
+ closedAt: iso(row.closedAt),
958
+ paymentStatus: params.paymentStatus,
959
+ createdAt: row.createdAt.toISOString(),
960
+ updatedAt: row.updatedAt.toISOString(),
961
+ lineCount: params.lineCount
962
+ };
963
+ }
964
+ __name(toOrderSummary, "toOrderSummary");
965
+ function toOrder(params) {
966
+ const { lineCount, ...summary } = toOrderSummary({
967
+ ...params,
968
+ lineCount: params.lines.length
969
+ });
970
+ return {
971
+ ...summary,
972
+ lines: params.lines.map(toOrderLine)
973
+ };
974
+ }
975
+ __name(toOrder, "toOrder");
976
+ function toReceiptLine(row) {
977
+ return {
978
+ id: row.id,
979
+ orderLineId: row.orderLineId,
980
+ itemRef: row.itemRef,
981
+ itemName: row.itemName,
982
+ supplierSku: row.supplierSku,
983
+ purchaseUnit: row.purchaseUnit,
984
+ unitsPerPurchase: decimal(row.unitsPerPurchase),
985
+ stockUnit: row.stockUnit ?? null,
986
+ quantity: decimal(row.quantity),
987
+ unitPrice: decimal(row.unitPrice),
988
+ lineTotal: moneyText(row.lineTotal),
989
+ landedUnitCost: row.landedUnitCost === null ? null : decimal(row.landedUnitCost),
990
+ batchCode: row.batchCode,
991
+ expiresAt: row.expiresAt,
992
+ divergence: row.divergence,
993
+ divergenceReason: row.divergenceReason,
994
+ stockStatus: row.stockStatus
995
+ };
996
+ }
997
+ __name(toReceiptLine, "toReceiptLine");
998
+ function toReceipt(params) {
999
+ const { row } = params;
1000
+ return {
1001
+ id: row.id,
1002
+ orderId: row.orderId,
1003
+ orderNumber: params.orderNumber,
1004
+ supplierId: row.supplierId,
1005
+ supplierName: params.supplierName,
1006
+ receivedAt: row.receivedAt.toISOString(),
1007
+ invoiceNumber: row.invoiceNumber,
1008
+ invoiceKey: row.invoiceKey,
1009
+ invoiceIssuedAt: iso(row.invoiceIssuedAt),
1010
+ subtotal: moneyText(row.subtotal),
1011
+ freight: moneyText(row.freight),
1012
+ discount: moneyText(row.discount),
1013
+ total: moneyText(row.total),
1014
+ notes: row.notes,
1015
+ actorId: row.actorId,
1016
+ stockStatus: row.stockStatus,
1017
+ payableStatus: row.payableStatus,
1018
+ payableRef: row.payableRef,
1019
+ paymentStatus: row.paymentStatus,
1020
+ createdAt: row.createdAt.toISOString(),
1021
+ lines: params.lines.map(toReceiptLine)
1022
+ };
1023
+ }
1024
+ __name(toReceipt, "toReceipt");
1025
+ function parseInstallments(text2) {
1026
+ try {
1027
+ const value = JSON.parse(text2);
1028
+ return Array.isArray(value) ? value : [];
1029
+ } catch {
1030
+ return [];
1031
+ }
1032
+ }
1033
+ __name(parseInstallments, "parseInstallments");
1034
+
1035
+ // src/shared/postgresErrors.ts
1036
+ var UNIQUE_VIOLATION = "23505";
1037
+ function hasPostgresCode(error, code) {
1038
+ let current = error;
1039
+ for (let depth = 0; depth < 3 && typeof current === "object" && current !== null; depth += 1) {
1040
+ const candidate = current;
1041
+ if (candidate.code === code || candidate.errno === code) return true;
1042
+ current = current.cause;
1043
+ }
1044
+ return false;
1045
+ }
1046
+ __name(hasPostgresCode, "hasPostgresCode");
1047
+ function isUniqueViolation(error) {
1048
+ return hasPostgresCode(error, UNIQUE_VIOLATION);
1049
+ }
1050
+ __name(isUniqueViolation, "isUniqueViolation");
1051
+ function likePattern(search) {
1052
+ return `%${search.replace(/[\\%_]/g, (character) => `\\${character}`)}%`;
1053
+ }
1054
+ __name(likePattern, "likePattern");
1055
+
1056
+ // src/services/suppliers.ts
1057
+ import { PurchaseItemNotFoundError, SupplierDocumentTakenError, SupplierInUseError, SupplierItemNotFoundError, SupplierItemTakenError, SupplierNotFoundError } from "@adatechnology/purchase-contracts";
1058
+ import { and as and3, asc, count as count2, desc as desc2, eq as eq3, ilike, inArray as inArray3, or } from "drizzle-orm";
1059
+ var SORT_COLUMNS = {
1060
+ name: suppliers.name,
1061
+ createdAt: suppliers.createdAt,
1062
+ updatedAt: suppliers.updatedAt
1063
+ };
1064
+ function defined(values) {
1065
+ return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== void 0));
1066
+ }
1067
+ __name(defined, "defined");
1068
+ async function guard(work, onUnique) {
1069
+ try {
1070
+ return await work();
1071
+ } catch (error) {
1072
+ if (isUniqueViolation(error)) throw onUnique();
1073
+ throw error;
1074
+ }
1075
+ }
1076
+ __name(guard, "guard");
1077
+ async function findSupplierRow(dependencies, companyId, supplierId2) {
1078
+ const [row] = await dependencies.db.select().from(suppliers).where(and3(eq3(suppliers.companyId, companyId), eq3(suppliers.id, supplierId2)));
1079
+ if (!row) throw new SupplierNotFoundError(supplierId2);
1080
+ return row;
1081
+ }
1082
+ __name(findSupplierRow, "findSupplierRow");
1083
+ async function loadCatalogItems(dependencies, companyId, itemRefs) {
1084
+ const catalog = dependencies.providers.catalog;
1085
+ if (!catalog) return null;
1086
+ const ids = [
1087
+ ...new Set(itemRefs)
1088
+ ];
1089
+ if (ids.length === 0) return /* @__PURE__ */ new Map();
1090
+ const found = await catalog.findItems({
1091
+ companyId,
1092
+ itemRefs: ids
1093
+ });
1094
+ return new Map(found.map((item) => [
1095
+ item.itemRef,
1096
+ item
1097
+ ]));
1098
+ }
1099
+ __name(loadCatalogItems, "loadCatalogItems");
1100
+ async function requireCatalogItems(dependencies, companyId, itemRefs) {
1101
+ const found = await loadCatalogItems(dependencies, companyId, itemRefs);
1102
+ if (!found) return null;
1103
+ for (const itemRef of itemRefs) if (!found.has(itemRef)) throw new PurchaseItemNotFoundError(itemRef);
1104
+ return found;
1105
+ }
1106
+ __name(requireCatalogItems, "requireCatalogItems");
1107
+ function createSupplierService(dependencies) {
1108
+ const { db } = dependencies;
1109
+ async function findItemRow(companyId, id) {
1110
+ const [row] = await db.select().from(supplierItems).where(and3(eq3(supplierItems.companyId, companyId), eq3(supplierItems.id, id)));
1111
+ if (!row) throw new SupplierItemNotFoundError(id);
1112
+ return row;
1113
+ }
1114
+ __name(findItemRow, "findItemRow");
1115
+ return {
1116
+ async create(params) {
1117
+ await assertEnabled(dependencies, params.companyId);
1118
+ const now = dependencies.clock.now();
1119
+ const { id, ...values } = params.input;
1120
+ const [row] = await guard(() => db.insert(suppliers).values({
1121
+ ...values,
1122
+ ...id ? {
1123
+ id
1124
+ } : {},
1125
+ companyId: params.companyId,
1126
+ createdAt: now,
1127
+ updatedAt: now
1128
+ }).returning(), () => new SupplierDocumentTakenError());
1129
+ return toSupplier(row);
1130
+ },
1131
+ async get(params) {
1132
+ await assertEnabled(dependencies, params.companyId);
1133
+ return toSupplier(await findSupplierRow(dependencies, params.companyId, params.id));
1134
+ },
1135
+ /** Para o `SupplierDirectoryPort` do estoque e outras leituras em lote do host. */
1136
+ async findMany(params) {
1137
+ await assertEnabled(dependencies, params.companyId);
1138
+ if (params.ids.length === 0) return [];
1139
+ const rows = await db.select().from(suppliers).where(and3(eq3(suppliers.companyId, params.companyId), inArray3(suppliers.id, [
1140
+ ...new Set(params.ids)
1141
+ ])));
1142
+ return rows.map(toSupplier);
1143
+ },
1144
+ async list(params) {
1145
+ await assertEnabled(dependencies, params.companyId);
1146
+ const { query } = params;
1147
+ const conditions = [
1148
+ eq3(suppliers.companyId, params.companyId)
1149
+ ];
1150
+ if (query.isActive !== void 0) conditions.push(eq3(suppliers.isActive, query.isActive));
1151
+ if (query.search) {
1152
+ const pattern = likePattern(query.search);
1153
+ conditions.push(or(ilike(suppliers.name, pattern), ilike(suppliers.document, pattern), ilike(suppliers.contactName, pattern), ilike(suppliers.email, pattern)));
1154
+ }
1155
+ const where = and3(...conditions);
1156
+ const column = SORT_COLUMNS[query.sort];
1157
+ const [rows, totals] = await Promise.all([
1158
+ db.select().from(suppliers).where(where).orderBy(query.order === "desc" ? desc2(column) : asc(column), asc(suppliers.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
1159
+ db.select({
1160
+ total: count2()
1161
+ }).from(suppliers).where(where)
1162
+ ]);
1163
+ return paginated({
1164
+ rows,
1165
+ total: totals[0]?.total ?? 0,
1166
+ page: query.page,
1167
+ pageSize: query.pageSize,
1168
+ map: toSupplier
1169
+ });
1170
+ },
1171
+ async update(params) {
1172
+ await assertEnabled(dependencies, params.companyId);
1173
+ const [row] = await guard(() => db.update(suppliers).set({
1174
+ ...defined(params.input),
1175
+ updatedAt: dependencies.clock.now()
1176
+ }).where(and3(eq3(suppliers.companyId, params.companyId), eq3(suppliers.id, params.id))).returning(), () => new SupplierDocumentTakenError());
1177
+ if (!row) throw new SupplierNotFoundError(params.id);
1178
+ return toSupplier(row);
1179
+ },
1180
+ /** Com pedido ou recebimento, o histórico depende dele: 409 (desative). */
1181
+ async remove(params) {
1182
+ await assertEnabled(dependencies, params.companyId);
1183
+ await findSupplierRow(dependencies, params.companyId, params.id);
1184
+ const [order] = await db.select({
1185
+ id: orders.id
1186
+ }).from(orders).where(and3(eq3(orders.companyId, params.companyId), eq3(orders.supplierId, params.id))).limit(1);
1187
+ const [receipt] = await db.select({
1188
+ id: receipts.id
1189
+ }).from(receipts).where(and3(eq3(receipts.companyId, params.companyId), eq3(receipts.supplierId, params.id))).limit(1);
1190
+ if (order || receipt) throw new SupplierInUseError(params.id);
1191
+ await db.delete(suppliers).where(and3(eq3(suppliers.companyId, params.companyId), eq3(suppliers.id, params.id)));
1192
+ },
1193
+ async createItem(params) {
1194
+ await assertEnabled(dependencies, params.companyId);
1195
+ await findSupplierRow(dependencies, params.companyId, params.supplierId);
1196
+ const { input } = params;
1197
+ let stockUnit = input.stockUnit;
1198
+ if (input.itemRef) {
1199
+ const catalog = await requireCatalogItems(dependencies, params.companyId, [
1200
+ input.itemRef
1201
+ ]);
1202
+ stockUnit = stockUnit ?? catalog?.get(input.itemRef)?.unit ?? null;
1203
+ }
1204
+ const now = dependencies.clock.now();
1205
+ const [row] = await guard(() => db.insert(supplierItems).values({
1206
+ ...input,
1207
+ stockUnit,
1208
+ companyId: params.companyId,
1209
+ supplierId: params.supplierId,
1210
+ lastPriceAt: input.lastPrice === null ? null : now,
1211
+ createdAt: now,
1212
+ updatedAt: now
1213
+ }).returning(), () => new SupplierItemTakenError());
1214
+ return toSupplierItem(row);
1215
+ },
1216
+ async getItem(params) {
1217
+ await assertEnabled(dependencies, params.companyId);
1218
+ return toSupplierItem(await findItemRow(params.companyId, params.id));
1219
+ },
1220
+ async listItems(params) {
1221
+ await assertEnabled(dependencies, params.companyId);
1222
+ const { query } = params;
1223
+ const conditions = [
1224
+ eq3(supplierItems.companyId, params.companyId)
1225
+ ];
1226
+ if (query.supplierId) conditions.push(eq3(supplierItems.supplierId, query.supplierId));
1227
+ if (query.itemRef) conditions.push(eq3(supplierItems.itemRef, query.itemRef));
1228
+ if (query.isActive !== void 0) conditions.push(eq3(supplierItems.isActive, query.isActive));
1229
+ if (query.search) {
1230
+ const pattern = likePattern(query.search);
1231
+ conditions.push(or(ilike(supplierItems.itemName, pattern), ilike(supplierItems.supplierSku, pattern)));
1232
+ }
1233
+ const where = and3(...conditions);
1234
+ const [rows, totals] = await Promise.all([
1235
+ db.select().from(supplierItems).where(where).orderBy(asc(supplierItems.itemName), asc(supplierItems.priority), asc(supplierItems.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
1236
+ db.select({
1237
+ total: count2()
1238
+ }).from(supplierItems).where(where)
1239
+ ]);
1240
+ return paginated({
1241
+ rows,
1242
+ total: totals[0]?.total ?? 0,
1243
+ page: query.page,
1244
+ pageSize: query.pageSize,
1245
+ map: toSupplierItem
1246
+ });
1247
+ },
1248
+ async updateItem(params) {
1249
+ await assertEnabled(dependencies, params.companyId);
1250
+ const current = await findItemRow(params.companyId, params.id);
1251
+ if (params.input.itemRef) await requireCatalogItems(dependencies, params.companyId, [
1252
+ params.input.itemRef
1253
+ ]);
1254
+ const now = dependencies.clock.now();
1255
+ const priceChanged = params.input.lastPrice !== void 0 && params.input.lastPrice !== current.lastPrice;
1256
+ const [row] = await guard(() => db.update(supplierItems).set({
1257
+ ...defined(params.input),
1258
+ ...priceChanged ? {
1259
+ lastPriceAt: now
1260
+ } : {},
1261
+ updatedAt: now
1262
+ }).where(and3(eq3(supplierItems.companyId, params.companyId), eq3(supplierItems.id, params.id))).returning(), () => new SupplierItemTakenError());
1263
+ return toSupplierItem(row);
1264
+ },
1265
+ async removeItem(params) {
1266
+ await assertEnabled(dependencies, params.companyId);
1267
+ const rows = await db.delete(supplierItems).where(and3(eq3(supplierItems.companyId, params.companyId), eq3(supplierItems.id, params.id))).returning({
1268
+ id: supplierItems.id
1269
+ });
1270
+ if (rows.length === 0) throw new SupplierItemNotFoundError(params.id);
1271
+ }
1272
+ };
1273
+ }
1274
+ __name(createSupplierService, "createSupplierService");
1275
+
1276
+ // src/services/orders.ts
1277
+ var ORDER_SORT_COLUMNS = {
1278
+ number: orders.number,
1279
+ createdAt: orders.createdAt,
1280
+ expectedAt: orders.expectedAt,
1281
+ total: orders.total
1282
+ };
1283
+ async function lockOrder(tx, companyId, orderId2) {
1284
+ const [row] = await tx.select().from(orders).where(and4(eq4(orders.companyId, companyId), eq4(orders.id, orderId2))).for("update");
1285
+ if (!row) throw new OrderNotFoundError2(orderId2);
1286
+ return row;
1287
+ }
1288
+ __name(lockOrder, "lockOrder");
1289
+ function assertAction(row, action) {
1290
+ if (!canPerform(row.status, action)) throw new InvalidOrderTransitionError({
1291
+ status: row.status,
1292
+ action
1293
+ });
1294
+ }
1295
+ __name(assertAction, "assertAction");
1296
+ async function nextOrderNumber(tx, companyId) {
1297
+ const [row] = await tx.insert(orderCounters).values({
1298
+ companyId,
1299
+ lastNumber: 1
1300
+ }).onConflictDoUpdate({
1301
+ target: orderCounters.companyId,
1302
+ set: {
1303
+ lastNumber: sql2`${orderCounters.lastNumber} + 1`
1304
+ }
1305
+ }).returning({
1306
+ lastNumber: orderCounters.lastNumber
1307
+ });
1308
+ return row?.lastNumber ?? 1;
1309
+ }
1310
+ __name(nextOrderNumber, "nextOrderNumber");
1311
+ async function paymentStatusByOrder(db, companyId, orderIds) {
1312
+ if (orderIds.length === 0) return /* @__PURE__ */ new Map();
1313
+ const rows = await db.select({
1314
+ orderId: receipts.orderId,
1315
+ status: receipts.paymentStatus
1316
+ }).from(receipts).where(and4(eq4(receipts.companyId, companyId), inArray4(receipts.orderId, [
1317
+ ...orderIds
1318
+ ])));
1319
+ const byOrder = /* @__PURE__ */ new Map();
1320
+ for (const row of rows) if (row.orderId) byOrder.set(row.orderId, [
1321
+ ...byOrder.get(row.orderId) ?? [],
1322
+ row.status
1323
+ ]);
1324
+ const result = /* @__PURE__ */ new Map();
1325
+ for (const [orderId2, statuses] of byOrder) {
1326
+ const tracked = statuses.filter((status) => status !== "none");
1327
+ if (tracked.length === 0) result.set(orderId2, "none");
1328
+ else if (tracked.every((status) => status === "paid") && tracked.length === statuses.length) result.set(orderId2, "paid");
1329
+ else if (tracked.some((status) => status === "paid" || status === "partial")) result.set(orderId2, "partial");
1330
+ else result.set(orderId2, "open");
1331
+ }
1332
+ return result;
1333
+ }
1334
+ __name(paymentStatusByOrder, "paymentStatusByOrder");
1335
+ function createOrderService(dependencies) {
1336
+ const { db } = dependencies;
1337
+ async function resolveLines(tx, params) {
1338
+ const itemIds = [
1339
+ ...new Set(params.lines.flatMap((line) => line.supplierItemId ? [
1340
+ line.supplierItemId
1341
+ ] : []))
1342
+ ];
1343
+ const items = itemIds.length === 0 ? [] : await tx.select().from(supplierItems).where(and4(eq4(supplierItems.companyId, params.companyId), eq4(supplierItems.supplierId, params.supplierId), inArray4(supplierItems.id, itemIds)));
1344
+ const byId = new Map(items.map((item) => [
1345
+ item.id,
1346
+ item
1347
+ ]));
1348
+ const resolved = params.lines.map((line, position) => {
1349
+ const item = line.supplierItemId ? byId.get(line.supplierItemId) : void 0;
1350
+ if (line.supplierItemId && !item) throw new SupplierItemNotFoundError2(line.supplierItemId);
1351
+ const unitPrice = normalizeDecimal3(line.unitPrice ?? item?.lastPrice ?? "0");
1352
+ const quantity = normalizeDecimal3(line.quantity);
1353
+ return {
1354
+ companyId: params.companyId,
1355
+ position,
1356
+ supplierItemId: item?.id ?? null,
1357
+ itemRef: line.itemRef ?? item?.itemRef ?? null,
1358
+ itemName: line.itemName ?? item?.itemName ?? "",
1359
+ supplierSku: line.supplierSku ?? item?.supplierSku ?? null,
1360
+ purchaseUnit: line.purchaseUnit ?? item?.purchaseUnit ?? "un",
1361
+ unitsPerPurchase: normalizeDecimal3(line.unitsPerPurchase ?? item?.unitsPerPurchase ?? "1"),
1362
+ stockUnit: line.stockUnit ?? item?.stockUnit ?? null,
1363
+ quantity,
1364
+ unitPrice,
1365
+ lineTotal: money2(lineTotal(quantity, unitPrice)),
1366
+ notes: line.notes ?? null
1367
+ };
1368
+ });
1369
+ const refs = resolved.flatMap((line) => line.itemRef ? [
1370
+ line.itemRef
1371
+ ] : []);
1372
+ const catalog = await requireCatalogItems(dependencies, params.companyId, refs);
1373
+ if (catalog) {
1374
+ for (const line of resolved) {
1375
+ if (!line.itemRef) continue;
1376
+ const entry = catalog.get(line.itemRef);
1377
+ if (entry && !line.stockUnit) line.stockUnit = entry.unit;
1378
+ if (entry && !line.itemName) line.itemName = entry.name;
1379
+ }
1380
+ }
1381
+ return resolved.map((line) => ({
1382
+ ...line,
1383
+ itemName: line.itemName || "Item"
1384
+ }));
1385
+ }
1386
+ __name(resolveLines, "resolveLines");
1387
+ async function load(companyId, orderId2, runner = db) {
1388
+ const [row] = await runner.select({
1389
+ order: orders,
1390
+ supplierName: suppliers.name
1391
+ }).from(orders).innerJoin(suppliers, eq4(suppliers.id, orders.supplierId)).where(and4(eq4(orders.companyId, companyId), eq4(orders.id, orderId2)));
1392
+ if (!row) throw new OrderNotFoundError2(orderId2);
1393
+ const lines = await runner.select().from(orderLines).where(eq4(orderLines.orderId, orderId2)).orderBy(asc2(orderLines.position));
1394
+ const payments = await paymentStatusByOrder(runner, companyId, [
1395
+ orderId2
1396
+ ]);
1397
+ return toOrder({
1398
+ row: row.order,
1399
+ supplierName: row.supplierName,
1400
+ lines,
1401
+ today: today(dependencies),
1402
+ paymentStatus: payments.get(orderId2) ?? "none"
1403
+ });
1404
+ }
1405
+ __name(load, "load");
1406
+ async function notifyStatus(actor, order, from, to) {
1407
+ if (from === to) return;
1408
+ await runHook(dependencies, "onOrderStatusChanged", {
1409
+ companyId: actor.companyId,
1410
+ orderId: order.id
1411
+ }, () => dependencies.hooks.onOrderStatusChanged?.({
1412
+ ...actorFields(actor),
1413
+ orderId: order.id,
1414
+ number: order.number,
1415
+ from,
1416
+ to
1417
+ }));
1418
+ }
1419
+ __name(notifyStatus, "notifyStatus");
1420
+ async function transition(actor, action, change) {
1421
+ await assertEnabled(dependencies, actor.companyId);
1422
+ const result = await db.transaction(async (tx) => {
1423
+ const row = await lockOrder(tx, actor.companyId, actor.orderId);
1424
+ assertAction(row, action);
1425
+ const values = await change(row, tx);
1426
+ const [updated] = await tx.update(orders).set({
1427
+ ...values,
1428
+ updatedAt: dependencies.clock.now()
1429
+ }).where(eq4(orders.id, row.id)).returning();
1430
+ return {
1431
+ before: row,
1432
+ after: updated
1433
+ };
1434
+ });
1435
+ await notifyStatus(actor, result.after, result.before.status, result.after.status);
1436
+ return load(actor.companyId, actor.orderId);
1437
+ }
1438
+ __name(transition, "transition");
1439
+ function defaultExpectedAt(supplier) {
1440
+ return supplier.leadTimeDays === null ? null : addDays2(today(dependencies), supplier.leadTimeDays);
1441
+ }
1442
+ __name(defaultExpectedAt, "defaultExpectedAt");
1443
+ const service = {
1444
+ load,
1445
+ async create(params) {
1446
+ await assertEnabled(dependencies, params.companyId);
1447
+ const supplier = await findSupplierRow(dependencies, params.companyId, params.input.supplierId);
1448
+ if (!supplier.isActive) throw new SupplierInactiveError(supplier.id);
1449
+ const orderId2 = await db.transaction(async (tx) => {
1450
+ const lines = await resolveLines(tx, {
1451
+ companyId: params.companyId,
1452
+ supplierId: supplier.id,
1453
+ lines: params.input.lines
1454
+ });
1455
+ const totals = computeTotals({
1456
+ lines,
1457
+ freight: params.input.freight,
1458
+ discount: params.input.discount
1459
+ });
1460
+ const now = dependencies.clock.now();
1461
+ const [order] = await tx.insert(orders).values({
1462
+ companyId: params.companyId,
1463
+ number: await nextOrderNumber(tx, params.companyId),
1464
+ supplierId: supplier.id,
1465
+ status: ORDER_STATUS.DRAFT,
1466
+ expectedAt: params.input.expectedAt === void 0 ? defaultExpectedAt(supplier) : params.input.expectedAt,
1467
+ notes: params.input.notes,
1468
+ ...totals,
1469
+ paymentTermDays: params.input.paymentTermDays ?? intList(supplier.paymentTermDays),
1470
+ createdBy: params.actorId ?? null,
1471
+ createdAt: now,
1472
+ updatedAt: now
1473
+ }).returning({
1474
+ id: orders.id
1475
+ });
1476
+ const id = order.id;
1477
+ await tx.insert(orderLines).values(lines.map((line) => ({
1478
+ ...line,
1479
+ orderId: id
1480
+ })));
1481
+ return id;
1482
+ });
1483
+ return load(params.companyId, orderId2);
1484
+ },
1485
+ async get(params) {
1486
+ await assertEnabled(dependencies, params.companyId);
1487
+ return load(params.companyId, params.id);
1488
+ },
1489
+ async list(params) {
1490
+ await assertEnabled(dependencies, params.companyId);
1491
+ const { query } = params;
1492
+ const conditions = [
1493
+ eq4(orders.companyId, params.companyId)
1494
+ ];
1495
+ if (query.status?.length) conditions.push(inArray4(orders.status, query.status));
1496
+ if (query.supplierId) conditions.push(eq4(orders.supplierId, query.supplierId));
1497
+ if (query.from) conditions.push(gte2(orders.createdAt, /* @__PURE__ */ new Date(`${query.from}T00:00:00Z`)));
1498
+ if (query.to) conditions.push(lt2(orders.createdAt, /* @__PURE__ */ new Date(`${addDays2(query.to, 1)}T00:00:00Z`)));
1499
+ if (query.late === true) {
1500
+ conditions.push(inArray4(orders.status, [
1501
+ "approved",
1502
+ "sent",
1503
+ "partially_received"
1504
+ ]));
1505
+ conditions.push(lt2(orders.expectedAt, today(dependencies)));
1506
+ }
1507
+ if (query.search) {
1508
+ const asNumber = Number(query.search.replace(/^#/, ""));
1509
+ const byName = ilike2(suppliers.name, likePattern(query.search));
1510
+ conditions.push(Number.isInteger(asNumber) && asNumber > 0 ? or2(eq4(orders.number, asNumber), byName) : byName);
1511
+ }
1512
+ const where = and4(...conditions);
1513
+ const column = ORDER_SORT_COLUMNS[query.sort];
1514
+ const lineCounts = db.select({
1515
+ orderId: orderLines.orderId,
1516
+ lineCount: count3().as("line_count")
1517
+ }).from(orderLines).where(eq4(orderLines.companyId, params.companyId)).groupBy(orderLines.orderId).as("line_counts");
1518
+ const [rows, totals] = await Promise.all([
1519
+ db.select({
1520
+ order: orders,
1521
+ supplierName: suppliers.name,
1522
+ lineCount: lineCounts.lineCount
1523
+ }).from(orders).innerJoin(suppliers, eq4(suppliers.id, orders.supplierId)).leftJoin(lineCounts, eq4(lineCounts.orderId, orders.id)).where(where).orderBy(query.order === "asc" ? asc2(column) : desc3(column), desc3(orders.number)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
1524
+ db.select({
1525
+ total: count3()
1526
+ }).from(orders).innerJoin(suppliers, eq4(suppliers.id, orders.supplierId)).where(where)
1527
+ ]);
1528
+ const payments = await paymentStatusByOrder(db, params.companyId, rows.map((row) => row.order.id));
1529
+ const currentDay = today(dependencies);
1530
+ return paginated({
1531
+ rows,
1532
+ total: totals[0]?.total ?? 0,
1533
+ page: query.page,
1534
+ pageSize: query.pageSize,
1535
+ map: /* @__PURE__ */ __name((row) => toOrderSummary({
1536
+ row: row.order,
1537
+ supplierName: row.supplierName,
1538
+ lineCount: Number(row.lineCount ?? 0),
1539
+ today: currentDay,
1540
+ paymentStatus: payments.get(row.order.id) ?? "none"
1541
+ }), "map")
1542
+ });
1543
+ },
1544
+ async update(params) {
1545
+ await assertEnabled(dependencies, params.companyId);
1546
+ const { input } = params;
1547
+ await db.transaction(async (tx) => {
1548
+ const row = await lockOrder(tx, params.companyId, params.id);
1549
+ assertAction(row, ORDER_ACTION.EDIT);
1550
+ let lineValues;
1551
+ if (input.lines) {
1552
+ const lines = await resolveLines(tx, {
1553
+ companyId: params.companyId,
1554
+ supplierId: row.supplierId,
1555
+ lines: input.lines
1556
+ });
1557
+ await tx.delete(orderLines).where(eq4(orderLines.orderId, row.id));
1558
+ await tx.insert(orderLines).values(lines.map((line) => ({
1559
+ ...line,
1560
+ orderId: row.id
1561
+ })));
1562
+ lineValues = lines;
1563
+ } else {
1564
+ lineValues = await tx.select({
1565
+ quantity: orderLines.quantity,
1566
+ unitPrice: orderLines.unitPrice
1567
+ }).from(orderLines).where(eq4(orderLines.orderId, row.id));
1568
+ }
1569
+ const totals = computeTotals({
1570
+ lines: lineValues,
1571
+ freight: input.freight ?? row.freight,
1572
+ discount: input.discount ?? row.discount
1573
+ });
1574
+ await tx.update(orders).set({
1575
+ ...input.expectedAt !== void 0 ? {
1576
+ expectedAt: input.expectedAt
1577
+ } : {},
1578
+ ...input.notes !== void 0 ? {
1579
+ notes: input.notes
1580
+ } : {},
1581
+ ...input.paymentTermDays !== void 0 ? {
1582
+ paymentTermDays: input.paymentTermDays
1583
+ } : {},
1584
+ ...totals,
1585
+ updatedAt: dependencies.clock.now()
1586
+ }).where(eq4(orders.id, row.id));
1587
+ });
1588
+ return load(params.companyId, params.id);
1589
+ },
1590
+ /** Rascunho → aprovado, ou → aguardando aprovação quando o total passa do limite da empresa. */
1591
+ async submit(params) {
1592
+ const threshold = await dependencies.config.approvalThresholdFor?.(params.companyId) ?? null;
1593
+ const thresholdCents = threshold === null ? null : centsOf(parseDecimal4(threshold));
1594
+ let approvalNeeded = false;
1595
+ const order = await transition({
1596
+ ...params,
1597
+ orderId: params.id
1598
+ }, ORDER_ACTION.SUBMIT, async (row) => {
1599
+ approvalNeeded = needsApproval({
1600
+ totalCents: centsOf(parseDecimal4(row.total)),
1601
+ thresholdCents
1602
+ });
1603
+ const now = dependencies.clock.now();
1604
+ return {
1605
+ status: approvalNeeded ? ORDER_STATUS.PENDING_APPROVAL : ORDER_STATUS.APPROVED,
1606
+ requiresApproval: approvalNeeded,
1607
+ submittedBy: params.actorId ?? null,
1608
+ submittedAt: now,
1609
+ rejectionReason: null,
1610
+ ...approvalNeeded ? {} : {
1611
+ approvedAt: now,
1612
+ approvedBy: params.actorId ?? null
1613
+ }
1614
+ };
1615
+ });
1616
+ if (approvalNeeded) await runHook(dependencies, "onApprovalRequested", {
1617
+ companyId: params.companyId,
1618
+ orderId: order.id
1619
+ }, () => dependencies.hooks.onApprovalRequested?.({
1620
+ companyId: params.companyId,
1621
+ orderId: order.id,
1622
+ number: order.number,
1623
+ total: order.total,
1624
+ ...params.actorId ? {
1625
+ requestedBy: params.actorId
1626
+ } : {}
1627
+ }));
1628
+ return order;
1629
+ },
1630
+ async approve(params) {
1631
+ return transition({
1632
+ ...params,
1633
+ orderId: params.id
1634
+ }, ORDER_ACTION.APPROVE, async (row) => {
1635
+ if (row.submittedBy && params.actorId && row.submittedBy === params.actorId) throw new SelfApprovalError();
1636
+ return {
1637
+ status: ORDER_STATUS.APPROVED,
1638
+ approvedBy: params.actorId ?? null,
1639
+ approvedAt: dependencies.clock.now()
1640
+ };
1641
+ });
1642
+ },
1643
+ async reject(params) {
1644
+ return transition({
1645
+ ...params,
1646
+ orderId: params.id
1647
+ }, ORDER_ACTION.REJECT, async () => ({
1648
+ status: ORDER_STATUS.DRAFT,
1649
+ rejectionReason: params.reason,
1650
+ submittedAt: null,
1651
+ submittedBy: null
1652
+ }));
1653
+ },
1654
+ async cancel(params) {
1655
+ return transition({
1656
+ ...params,
1657
+ orderId: params.id
1658
+ }, ORDER_ACTION.CANCEL, async () => ({
1659
+ status: ORDER_STATUS.CANCELED,
1660
+ cancelReason: params.reason,
1661
+ canceledAt: dependencies.clock.now()
1662
+ }));
1663
+ },
1664
+ /** Recebido em parte e o resto não vem: o saldo de cada linha vira cancelado e o pedido fecha. */
1665
+ async close(params) {
1666
+ return transition({
1667
+ ...params,
1668
+ orderId: params.id
1669
+ }, ORDER_ACTION.CLOSE, async (row, tx) => {
1670
+ const lines = await tx.select().from(orderLines).where(eq4(orderLines.orderId, row.id)).for("update");
1671
+ for (const line of lines) {
1672
+ const pending = pendingQuantity4(line);
1673
+ if (parseDecimal4(pending).numerator === 0n) continue;
1674
+ await tx.update(orderLines).set({
1675
+ canceledQuantity: sql2`${orderLines.canceledQuantity} + ${pending}::numeric`
1676
+ }).where(eq4(orderLines.id, line.id));
1677
+ }
1678
+ return {
1679
+ status: ORDER_STATUS.CLOSED,
1680
+ closedAt: dependencies.clock.now(),
1681
+ cancelReason: params.reason || null
1682
+ };
1683
+ });
1684
+ },
1685
+ /** Texto do pedido (o mesmo que vai no WhatsApp), para conferir ou copiar. */
1686
+ async message(params) {
1687
+ await assertEnabled(dependencies, params.companyId);
1688
+ const order = await load(params.companyId, params.id);
1689
+ const companyName = await dependencies.config.companyNameFor?.(params.companyId) ?? "";
1690
+ return {
1691
+ text: buildOrderMessage({
1692
+ companyName,
1693
+ number: order.number,
1694
+ supplierName: order.supplierName ?? "",
1695
+ expectedAt: order.expectedAt,
1696
+ paymentTermDays: order.paymentTermDays,
1697
+ notes: order.notes,
1698
+ total: order.total,
1699
+ lines: order.lines
1700
+ }, {
1701
+ withPrices: params.withPrices === true
1702
+ })
1703
+ };
1704
+ },
1705
+ /**
1706
+ * Envia pelo canal pedido (porta `dispatch`) ou só marca como enviado (`manual`). O envio acontece fora da
1707
+ * transação; se a porta falhar, o pedido continua como estava.
1708
+ */
1709
+ async send(params) {
1710
+ await assertEnabled(dependencies, params.companyId);
1711
+ const { channel } = params.input;
1712
+ const dispatch = dependencies.providers.dispatch;
1713
+ if (channel !== DISPATCH_CHANNEL.MANUAL && !dispatch?.channels.includes(channel)) throw new DispatchUnavailableError(channel);
1714
+ const current = await load(params.companyId, params.id);
1715
+ if (!canPerform(current.status, ORDER_ACTION.SEND)) throw new InvalidOrderTransitionError({
1716
+ status: current.status,
1717
+ action: ORDER_ACTION.SEND
1718
+ });
1719
+ const supplier = await findSupplierRow(dependencies, params.companyId, current.supplierId);
1720
+ const phone = supplier.whatsapp ?? supplier.phone;
1721
+ if (channel === DISPATCH_CHANNEL.WHATSAPP && !phone) throw new SupplierNoContactError(channel);
1722
+ if (channel === DISPATCH_CHANNEL.EMAIL && !supplier.email) throw new SupplierNoContactError(channel);
1723
+ const { text: text2 } = await service.message({
1724
+ ...params,
1725
+ withPrices: params.input.withPrices
1726
+ });
1727
+ let messageRef;
1728
+ if (channel !== DISPATCH_CHANNEL.MANUAL && dispatch) {
1729
+ const sent = await dispatch.dispatch({
1730
+ ...actorFields(params),
1731
+ channel,
1732
+ orderId: current.id,
1733
+ orderNumber: current.number,
1734
+ to: {
1735
+ name: supplier.contactName ?? supplier.name,
1736
+ phone,
1737
+ email: supplier.email
1738
+ },
1739
+ text: text2
1740
+ });
1741
+ messageRef = sent.messageRef;
1742
+ }
1743
+ const order = await transition({
1744
+ ...params,
1745
+ orderId: params.id
1746
+ }, ORDER_ACTION.SEND, async (row) => ({
1747
+ status: statusAfterSend(row.status),
1748
+ sentAt: dependencies.clock.now(),
1749
+ sentVia: channel
1750
+ }));
1751
+ return {
1752
+ order,
1753
+ text: text2,
1754
+ ...messageRef ? {
1755
+ messageRef
1756
+ } : {}
1757
+ };
1758
+ },
1759
+ /** Novo rascunho com as mesmas linhas e o último preço de cada item (compra de rotina). */
1760
+ async duplicate(params) {
1761
+ await assertEnabled(dependencies, params.companyId);
1762
+ const source = await load(params.companyId, params.id);
1763
+ return service.create({
1764
+ ...params,
1765
+ input: {
1766
+ supplierId: source.supplierId,
1767
+ notes: source.notes,
1768
+ freight: "0",
1769
+ discount: "0",
1770
+ paymentTermDays: [
1771
+ ...source.paymentTermDays
1772
+ ],
1773
+ lines: source.lines.map((line) => ({
1774
+ ...line.supplierItemId ? {
1775
+ supplierItemId: line.supplierItemId
1776
+ } : {},
1777
+ ...line.itemRef ? {
1778
+ itemRef: line.itemRef
1779
+ } : {},
1780
+ itemName: line.itemName,
1781
+ purchaseUnit: line.purchaseUnit,
1782
+ unitsPerPurchase: line.unitsPerPurchase,
1783
+ ...line.stockUnit ? {
1784
+ stockUnit: line.stockUnit
1785
+ } : {},
1786
+ ...line.supplierSku ? {
1787
+ supplierSku: line.supplierSku
1788
+ } : {},
1789
+ quantity: line.quantity,
1790
+ // Sem `unitPrice`: com item do fornecedor, vem o último preço; linha livre repete o anterior.
1791
+ ...line.supplierItemId ? {} : {
1792
+ unitPrice: line.unitPrice
1793
+ }
1794
+ }))
1795
+ }
1796
+ });
1797
+ },
1798
+ /** Para a varredura de atraso e o "a caminho": pedidos abertos com previsão até a data. */
1799
+ async openOrdersExpectedBefore(day) {
1800
+ return db.select({
1801
+ order: orders,
1802
+ supplierName: suppliers.name
1803
+ }).from(orders).innerJoin(suppliers, eq4(suppliers.id, orders.supplierId)).where(and4(inArray4(orders.status, [
1804
+ "approved",
1805
+ "sent",
1806
+ "partially_received"
1807
+ ]), lte(orders.expectedAt, day)));
1808
+ }
1809
+ };
1810
+ return service;
1811
+ }
1812
+ __name(createOrderService, "createOrderService");
1813
+
1814
+ // src/services/receipts.ts
1815
+ import { normalizeDecimal as normalizeDecimal4, parseDecimal as parseDecimal5, rational } from "@adatechnology/recipe-contracts";
1816
+ import { add as add2, addDays as addDays3, allocateExtras, buildInstallments, centsOf as centsOf2, civilDateIn as civilDateIn2, compare as compare2, divergenceOf, InstallmentsMismatchError, INTEGRATION_STATUS, InvoiceAlreadyReceivedError, landedUnitCost, lineTotal as lineTotal2, money as money3, ORDER_ACTION as ORDER_ACTION2, OrderLineNotFoundError, PAYMENT_STATUS, pendingQuantity as pendingQuantity5, quantityText as quantityText2, ReceiptNotFoundError, statusAfterReceipt, subtract, SupplierItemNotFoundError as SupplierItemNotFoundError3, toStockQuantity as toStockQuantity2, ZERO as ZERO3 } from "@adatechnology/purchase-contracts";
1817
+ import { and as and5, asc as asc3, count as count4, desc as desc4, eq as eq5, gte as gte3, inArray as inArray5, lt as lt3, or as or3, sql as sql3 } from "drizzle-orm";
1818
+ var AUTO_ITEM_PRIORITY = 100;
1819
+ function receiptLineSourceKey(receiptId2, lineId) {
1820
+ return `purchase-receipt:${receiptId2}:${lineId}`;
1821
+ }
1822
+ __name(receiptLineSourceKey, "receiptLineSourceKey");
1823
+ function receiptPayableRef(receiptId2) {
1824
+ return `purchase-receipt:${receiptId2}`;
1825
+ }
1826
+ __name(receiptPayableRef, "receiptPayableRef");
1827
+ function aggregateStatus(statuses) {
1828
+ if (statuses.length === 0 || statuses.every((status) => status === INTEGRATION_STATUS.SKIPPED)) return INTEGRATION_STATUS.SKIPPED;
1829
+ return statuses.some((status) => status === INTEGRATION_STATUS.FAILED) ? INTEGRATION_STATUS.FAILED : INTEGRATION_STATUS.DONE;
1830
+ }
1831
+ __name(aggregateStatus, "aggregateStatus");
1832
+ function expiryInstant(date2, timeZone) {
1833
+ if (!date2) return null;
1834
+ const noon = /* @__PURE__ */ new Date(`${date2}T12:00:00Z`);
1835
+ const offsetProbe = new Intl.DateTimeFormat("en-US", {
1836
+ timeZone,
1837
+ timeZoneName: "longOffset"
1838
+ }).formatToParts(noon).find((part) => part.type === "timeZoneName")?.value;
1839
+ const offset = /GMT([+-]\d{2}):?(\d{2})?/.exec(offsetProbe ?? "");
1840
+ const suffix = offset ? `${offset[1]}:${offset[2] ?? "00"}` : "Z";
1841
+ return (/* @__PURE__ */ new Date(`${date2}T23:59:59${suffix}`)).toISOString();
1842
+ }
1843
+ __name(expiryInstant, "expiryInstant");
1844
+ function createReceiptService(dependencies, insights) {
1845
+ const { db } = dependencies;
1846
+ async function load(companyId, receiptId2) {
1847
+ const [row] = await db.select({
1848
+ receipt: receipts,
1849
+ supplierName: suppliers.name,
1850
+ orderNumber: orders.number
1851
+ }).from(receipts).innerJoin(suppliers, eq5(suppliers.id, receipts.supplierId)).leftJoin(orders, eq5(orders.id, receipts.orderId)).where(and5(eq5(receipts.companyId, companyId), eq5(receipts.id, receiptId2)));
1852
+ if (!row) throw new ReceiptNotFoundError(receiptId2);
1853
+ const lines = await db.select().from(receiptLines).where(eq5(receiptLines.receiptId, receiptId2)).orderBy(asc3(receiptLines.position));
1854
+ return toReceipt({
1855
+ row: row.receipt,
1856
+ lines,
1857
+ supplierName: row.supplierName,
1858
+ orderNumber: row.orderNumber ?? null
1859
+ });
1860
+ }
1861
+ __name(load, "load");
1862
+ async function findByIdempotency(companyId, key) {
1863
+ const [row] = await db.select().from(receipts).where(and5(eq5(receipts.companyId, companyId), eq5(receipts.idempotencyKey, key)));
1864
+ return row;
1865
+ }
1866
+ __name(findByIdempotency, "findByIdempotency");
1867
+ async function findByInvoiceKey(companyId, key) {
1868
+ const [row] = await db.select().from(receipts).where(and5(eq5(receipts.companyId, companyId), eq5(receipts.invoiceKey, key)));
1869
+ return row;
1870
+ }
1871
+ __name(findByInvoiceKey, "findByInvoiceKey");
1872
+ async function postStock(actor, receipt) {
1873
+ const port = dependencies.providers.stock;
1874
+ if (!port) return;
1875
+ const lines = await db.select().from(receiptLines).where(and5(eq5(receiptLines.receiptId, receipt.id), eq5(receiptLines.stockStatus, INTEGRATION_STATUS.FAILED)));
1876
+ for (const line of lines) {
1877
+ let status = INTEGRATION_STATUS.DONE;
1878
+ try {
1879
+ await port.receive({
1880
+ ...actorFields(actor),
1881
+ sourceKey: receiptLineSourceKey(receipt.id, line.id),
1882
+ itemRef: line.itemRef,
1883
+ quantity: toStockQuantity2(line.quantity, line.unitsPerPurchase),
1884
+ unit: line.stockUnit,
1885
+ batchCode: line.batchCode || `NF${receipt.invoiceNumber ?? ""}-${receipt.id.slice(0, 8)}`.slice(0, 100),
1886
+ costPerUnit: line.landedUnitCost,
1887
+ expiresAt: expiryInstant(line.expiresAt, dependencies.timeZone),
1888
+ supplierId: receipt.supplierId,
1889
+ reason: `Compra${receipt.invoiceNumber ? ` NF ${receipt.invoiceNumber}` : ""}`.slice(0, 255)
1890
+ });
1891
+ } catch (error) {
1892
+ status = INTEGRATION_STATUS.FAILED;
1893
+ dependencies.logger?.error("purchase: entrada no estoque falhou", {
1894
+ companyId: actor.companyId,
1895
+ receiptId: receipt.id,
1896
+ lineId: line.id,
1897
+ error: error instanceof Error ? error.name : "unknown"
1898
+ });
1899
+ }
1900
+ await db.update(receiptLines).set({
1901
+ stockStatus: status
1902
+ }).where(eq5(receiptLines.id, line.id));
1903
+ }
1904
+ const statuses = await db.select({
1905
+ status: receiptLines.stockStatus
1906
+ }).from(receiptLines).where(eq5(receiptLines.receiptId, receipt.id));
1907
+ await db.update(receipts).set({
1908
+ stockStatus: aggregateStatus(statuses.map((row) => row.status))
1909
+ }).where(eq5(receipts.id, receipt.id));
1910
+ }
1911
+ __name(postStock, "postStock");
1912
+ async function postPayable(actor, receipt) {
1913
+ const port = dependencies.providers.payables;
1914
+ if (!port || receipt.payableStatus !== INTEGRATION_STATUS.FAILED) return;
1915
+ const supplier = await findSupplierRow(dependencies, actor.companyId, receipt.supplierId);
1916
+ let order;
1917
+ if (receipt.orderId) [order] = await db.select().from(orders).where(eq5(orders.id, receipt.orderId));
1918
+ try {
1919
+ const { payableRef } = await port.createPayable({
1920
+ ...actorFields(actor),
1921
+ sourceRef: receiptPayableRef(receipt.id),
1922
+ supplier: {
1923
+ id: supplier.id,
1924
+ name: supplier.name,
1925
+ document: supplier.document
1926
+ },
1927
+ description: [
1928
+ `Compra ${supplier.name}`,
1929
+ order ? `pedido ${order.number}` : null,
1930
+ receipt.invoiceNumber ? `NF ${receipt.invoiceNumber}` : null
1931
+ ].filter(Boolean).join(" \xB7 ").slice(0, 160),
1932
+ total: money3(parseDecimal5(receipt.total)),
1933
+ installments: parseInstallments(receipt.installments),
1934
+ invoiceNumber: receipt.invoiceNumber,
1935
+ invoiceKey: receipt.invoiceKey,
1936
+ receiptId: receipt.id,
1937
+ orderId: receipt.orderId
1938
+ });
1939
+ await db.update(receipts).set({
1940
+ payableStatus: INTEGRATION_STATUS.DONE,
1941
+ payableRef,
1942
+ paymentStatus: PAYMENT_STATUS.OPEN
1943
+ }).where(eq5(receipts.id, receipt.id));
1944
+ } catch (error) {
1945
+ dependencies.logger?.error("purchase: conta a pagar falhou", {
1946
+ companyId: actor.companyId,
1947
+ receiptId: receipt.id,
1948
+ error: error instanceof Error ? error.name : "unknown"
1949
+ });
1950
+ }
1951
+ }
1952
+ __name(postPayable, "postPayable");
1953
+ async function resolveLines(params) {
1954
+ const byOrderLine = new Map(params.orderLines.map((line) => [
1955
+ line.id,
1956
+ line
1957
+ ]));
1958
+ const itemIds = [
1959
+ ...new Set(params.lines.flatMap((line) => {
1960
+ const fromOrder = line.orderLineId ? byOrderLine.get(line.orderLineId)?.supplierItemId : null;
1961
+ return [
1962
+ line.supplierItemId,
1963
+ fromOrder
1964
+ ].filter((id) => Boolean(id));
1965
+ }))
1966
+ ];
1967
+ const items = itemIds.length === 0 ? [] : await db.select().from(supplierItems).where(and5(eq5(supplierItems.companyId, params.companyId), eq5(supplierItems.supplierId, params.supplierId), inArray5(supplierItems.id, itemIds)));
1968
+ const itemsById = new Map(items.map((item) => [
1969
+ item.id,
1970
+ item
1971
+ ]));
1972
+ const consumed = /* @__PURE__ */ new Map();
1973
+ const priceTolerance = BigInt(dependencies.config.priceToleranceCents ?? 0);
1974
+ const resolved = params.lines.map((line, position) => {
1975
+ const orderLine = line.orderLineId ? byOrderLine.get(line.orderLineId) : void 0;
1976
+ if (line.orderLineId && !orderLine) throw new OrderLineNotFoundError(line.orderLineId);
1977
+ const supplierItemId2 = line.supplierItemId ?? orderLine?.supplierItemId ?? null;
1978
+ const item = supplierItemId2 ? itemsById.get(supplierItemId2) : void 0;
1979
+ if (line.supplierItemId && !item) throw new SupplierItemNotFoundError3(line.supplierItemId);
1980
+ const quantity = normalizeDecimal4(line.quantity);
1981
+ const unitPrice = normalizeDecimal4(line.unitPrice ?? orderLine?.unitPrice ?? item?.lastPrice ?? "0");
1982
+ let divergence = "none";
1983
+ if (orderLine) {
1984
+ const already = consumed.get(orderLine.id) ?? "0";
1985
+ const pending = quantityText2(subtract(parseDecimal5(pendingQuantity5(orderLine)), parseDecimal5(already)));
1986
+ consumed.set(orderLine.id, quantityText2(add2(parseDecimal5(already), parseDecimal5(quantity))));
1987
+ divergence = divergenceOf({
1988
+ pendingQuantity: compare2(parseDecimal5(pending), ZERO3) < 0 ? "0" : pending,
1989
+ receivedQuantity: quantity,
1990
+ orderedPrice: orderLine.unitPrice,
1991
+ receivedPrice: unitPrice,
1992
+ priceToleranceCents: priceTolerance
1993
+ });
1994
+ }
1995
+ return {
1996
+ companyId: params.companyId,
1997
+ position,
1998
+ orderLineId: orderLine?.id ?? null,
1999
+ supplierItemId: item?.id ?? null,
2000
+ itemRef: line.itemRef ?? orderLine?.itemRef ?? item?.itemRef ?? null,
2001
+ itemName: line.itemName ?? orderLine?.itemName ?? item?.itemName ?? "Item",
2002
+ supplierSku: line.supplierSku ?? orderLine?.supplierSku ?? item?.supplierSku ?? null,
2003
+ purchaseUnit: line.purchaseUnit ?? orderLine?.purchaseUnit ?? item?.purchaseUnit ?? "un",
2004
+ unitsPerPurchase: normalizeDecimal4(line.unitsPerPurchase ?? orderLine?.unitsPerPurchase ?? item?.unitsPerPurchase ?? "1"),
2005
+ stockUnit: line.stockUnit ?? orderLine?.stockUnit ?? item?.stockUnit ?? null,
2006
+ quantity,
2007
+ unitPrice,
2008
+ lineTotal: money3(lineTotal2(quantity, unitPrice)),
2009
+ batchCode: line.batchCode || null,
2010
+ expiresAt: line.expiresAt ?? null,
2011
+ divergence,
2012
+ divergenceReason: line.divergenceReason || null,
2013
+ orderLine: orderLine ?? null
2014
+ };
2015
+ });
2016
+ const refs = resolved.flatMap((line) => line.itemRef ? [
2017
+ line.itemRef
2018
+ ] : []);
2019
+ const catalog = await requireCatalogItems(dependencies, params.companyId, refs);
2020
+ if (catalog) {
2021
+ for (const line of resolved) if (line.itemRef && !line.stockUnit) line.stockUnit = catalog.get(line.itemRef)?.unit ?? null;
2022
+ }
2023
+ return resolved;
2024
+ }
2025
+ __name(resolveLines, "resolveLines");
2026
+ function chooseInstallments(params) {
2027
+ if (params.input.installments) {
2028
+ const installments = [
2029
+ ...params.input.installments
2030
+ ].sort((left, right) => left.dueDate.localeCompare(right.dueDate)).map((item, index2) => ({
2031
+ number: index2 + 1,
2032
+ dueDate: item.dueDate,
2033
+ amount: money3(parseDecimal5(item.amount))
2034
+ }));
2035
+ const sum = installments.reduce((acc, item) => acc + centsOf2(parseDecimal5(item.amount)), 0n);
2036
+ if (sum !== centsOf2(parseDecimal5(params.total))) throw new InstallmentsMismatchError({
2037
+ total: params.total,
2038
+ installments: money3(rational(sum, 100n))
2039
+ });
2040
+ return installments;
2041
+ }
2042
+ return buildInstallments({
2043
+ total: params.total,
2044
+ termDays: params.termDays,
2045
+ baseDate: params.baseDate
2046
+ });
2047
+ }
2048
+ __name(chooseInstallments, "chooseInstallments");
2049
+ const service = {
2050
+ load,
2051
+ async receive(params) {
2052
+ await assertEnabled(dependencies, params.companyId);
2053
+ const { input } = params;
2054
+ if (input.idempotencyKey) {
2055
+ const existing = await findByIdempotency(params.companyId, input.idempotencyKey);
2056
+ if (existing) return load(params.companyId, existing.id);
2057
+ }
2058
+ if (input.invoiceKey) {
2059
+ const existing = await findByInvoiceKey(params.companyId, input.invoiceKey);
2060
+ if (existing) throw new InvoiceAlreadyReceivedError(existing.id);
2061
+ }
2062
+ const now = dependencies.clock.now();
2063
+ const receivedAt = input.receivedAt ? new Date(input.receivedAt) : now;
2064
+ const hasStockPort = dependencies.providers.stock !== void 0;
2065
+ const hasPayables = dependencies.providers.payables !== void 0;
2066
+ let statusChange = null;
2067
+ let receiptRow;
2068
+ try {
2069
+ receiptRow = await db.transaction(async (tx) => {
2070
+ let order = null;
2071
+ let lockedLines = [];
2072
+ let supplierId2 = input.supplierId;
2073
+ if (params.orderId) {
2074
+ order = await lockOrder(tx, params.companyId, params.orderId);
2075
+ assertAction(order, ORDER_ACTION2.RECEIVE);
2076
+ supplierId2 = order.supplierId;
2077
+ lockedLines = await tx.select().from(orderLines).where(eq5(orderLines.orderId, order.id)).for("update");
2078
+ }
2079
+ if (!supplierId2) throw new OrderLineNotFoundError("supplierId");
2080
+ const supplier = await findSupplierRow(dependencies, params.companyId, supplierId2);
2081
+ const lines = await resolveLines({
2082
+ companyId: params.companyId,
2083
+ supplierId: supplier.id,
2084
+ lines: input.lines,
2085
+ orderLines: lockedLines
2086
+ });
2087
+ const shares = allocateExtras({
2088
+ lineTotals: lines.map((line) => line.lineTotal),
2089
+ freight: input.freight,
2090
+ discount: input.discount
2091
+ });
2092
+ const subtotal = lines.reduce((acc, line) => add2(acc, parseDecimal5(line.lineTotal)), ZERO3);
2093
+ const totalValue = subtract(add2(subtotal, parseDecimal5(input.freight)), parseDecimal5(input.discount));
2094
+ const total = money3(compare2(totalValue, ZERO3) < 0 ? ZERO3 : totalValue);
2095
+ const baseDate = civilDateIn2(receivedAt, dependencies.timeZone);
2096
+ const installments = chooseInstallments({
2097
+ input,
2098
+ total,
2099
+ termDays: intList(order?.paymentTermDays ?? supplier.paymentTermDays),
2100
+ baseDate
2101
+ });
2102
+ const [inserted] = await tx.insert(receipts).values({
2103
+ companyId: params.companyId,
2104
+ orderId: order?.id ?? null,
2105
+ supplierId: supplier.id,
2106
+ receivedAt,
2107
+ invoiceNumber: input.invoiceNumber || null,
2108
+ invoiceKey: input.invoiceKey || null,
2109
+ invoiceIssuedAt: input.invoiceIssuedAt ? new Date(input.invoiceIssuedAt) : null,
2110
+ subtotal: money3(subtotal),
2111
+ freight: input.freight,
2112
+ discount: input.discount,
2113
+ total,
2114
+ notes: input.notes,
2115
+ actorId: params.actorId ?? null,
2116
+ idempotencyKey: input.idempotencyKey ?? null,
2117
+ installments: JSON.stringify(installments),
2118
+ // `failed` até a porta confirmar: um crash entre o commit e a entrada deixa o reprocessamento visível.
2119
+ stockStatus: hasStockPort ? INTEGRATION_STATUS.FAILED : INTEGRATION_STATUS.SKIPPED,
2120
+ payableStatus: hasPayables ? INTEGRATION_STATUS.FAILED : INTEGRATION_STATUS.SKIPPED,
2121
+ paymentStatus: PAYMENT_STATUS.NONE,
2122
+ createdAt: now
2123
+ }).returning();
2124
+ const receipt2 = inserted;
2125
+ await tx.insert(receiptLines).values(lines.map((resolved, index2) => {
2126
+ const { orderLine, ...line } = resolved;
2127
+ void orderLine;
2128
+ const allocated = shares[index2] ?? "0.00";
2129
+ const stockable = hasStockPort && line.itemRef !== null && line.stockUnit !== null;
2130
+ return {
2131
+ ...line,
2132
+ receiptId: receipt2.id,
2133
+ allocated,
2134
+ landedUnitCost: landedUnitCost({
2135
+ lineTotal: line.lineTotal,
2136
+ allocated,
2137
+ quantity: line.quantity,
2138
+ unitsPerPurchase: line.unitsPerPurchase
2139
+ }),
2140
+ stockStatus: stockable ? INTEGRATION_STATUS.FAILED : INTEGRATION_STATUS.SKIPPED
2141
+ };
2142
+ }));
2143
+ if (order) {
2144
+ const receivedByLine = /* @__PURE__ */ new Map();
2145
+ for (const line of lines) {
2146
+ if (!line.orderLine) continue;
2147
+ const sum = add2(parseDecimal5(receivedByLine.get(line.orderLine.id) ?? "0"), parseDecimal5(line.quantity));
2148
+ receivedByLine.set(line.orderLine.id, quantityText2(sum));
2149
+ }
2150
+ const updated = lockedLines.map((line) => {
2151
+ const extra = receivedByLine.get(line.id);
2152
+ return extra ? {
2153
+ ...line,
2154
+ receivedQuantity: quantityText2(add2(parseDecimal5(line.receivedQuantity), parseDecimal5(extra)))
2155
+ } : line;
2156
+ });
2157
+ for (const line of updated) if (receivedByLine.has(line.id)) await tx.update(orderLines).set({
2158
+ receivedQuantity: line.receivedQuantity
2159
+ }).where(eq5(orderLines.id, line.id));
2160
+ const next = statusAfterReceipt(updated);
2161
+ await tx.update(orders).set({
2162
+ status: next,
2163
+ updatedAt: now
2164
+ }).where(eq5(orders.id, order.id));
2165
+ statusChange = {
2166
+ order,
2167
+ from: order.status,
2168
+ to: next
2169
+ };
2170
+ }
2171
+ for (const line of lines) {
2172
+ if (line.supplierItemId) {
2173
+ await tx.update(supplierItems).set({
2174
+ lastPrice: line.unitPrice,
2175
+ lastPriceAt: receivedAt,
2176
+ updatedAt: now
2177
+ }).where(eq5(supplierItems.id, line.supplierItemId));
2178
+ } else if (line.itemRef) {
2179
+ await tx.insert(supplierItems).values({
2180
+ companyId: params.companyId,
2181
+ supplierId: supplier.id,
2182
+ itemRef: line.itemRef,
2183
+ itemName: line.itemName,
2184
+ supplierSku: null,
2185
+ purchaseUnit: line.purchaseUnit,
2186
+ unitsPerPurchase: line.unitsPerPurchase,
2187
+ stockUnit: line.stockUnit ?? null,
2188
+ lastPrice: line.unitPrice,
2189
+ lastPriceAt: receivedAt,
2190
+ // Cadastro criado sozinho perde para o feito à mão na escolha do preferido.
2191
+ priority: AUTO_ITEM_PRIORITY,
2192
+ createdAt: now,
2193
+ updatedAt: now
2194
+ }).onConflictDoUpdate({
2195
+ target: [
2196
+ supplierItems.companyId,
2197
+ supplierItems.supplierId,
2198
+ supplierItems.itemRef
2199
+ ],
2200
+ targetWhere: sql3`"item_ref" is not null`,
2201
+ set: {
2202
+ lastPrice: line.unitPrice,
2203
+ lastPriceAt: receivedAt,
2204
+ updatedAt: now
2205
+ }
2206
+ });
2207
+ }
2208
+ }
2209
+ return receipt2;
2210
+ });
2211
+ } catch (error) {
2212
+ if (isUniqueViolation(error)) {
2213
+ if (input.idempotencyKey) {
2214
+ const existing = await findByIdempotency(params.companyId, input.idempotencyKey);
2215
+ if (existing) return load(params.companyId, existing.id);
2216
+ }
2217
+ if (input.invoiceKey) {
2218
+ const existing = await findByInvoiceKey(params.companyId, input.invoiceKey);
2219
+ if (existing) throw new InvoiceAlreadyReceivedError(existing.id);
2220
+ }
2221
+ }
2222
+ throw error;
2223
+ }
2224
+ await postStock(params, receiptRow);
2225
+ await postPayable(params, receiptRow);
2226
+ const change = statusChange;
2227
+ if (change && change.from !== change.to) await runHook(dependencies, "onOrderStatusChanged", {
2228
+ companyId: params.companyId,
2229
+ orderId: change.order.id
2230
+ }, () => dependencies.hooks.onOrderStatusChanged?.({
2231
+ ...actorFields(params),
2232
+ orderId: change.order.id,
2233
+ number: change.order.number,
2234
+ from: change.from,
2235
+ to: change.to
2236
+ }));
2237
+ const receipt = await load(params.companyId, receiptRow.id);
2238
+ await service.notifyPosted(params, receipt);
2239
+ return receipt;
2240
+ },
2241
+ async notifyPosted(actor, receipt) {
2242
+ if (!dependencies.hooks.onReceiptPosted) return;
2243
+ const refs = receipt.lines.flatMap((line) => line.itemRef ? [
2244
+ line.itemRef
2245
+ ] : []);
2246
+ const costs = refs.length ? await insights().itemCosts({
2247
+ companyId: actor.companyId,
2248
+ itemRefs: refs
2249
+ }) : [];
2250
+ const averages = new Map(costs.map((cost) => [
2251
+ cost.itemRef,
2252
+ cost.averageCost
2253
+ ]));
2254
+ await runHook(dependencies, "onReceiptPosted", {
2255
+ companyId: actor.companyId,
2256
+ receiptId: receipt.id
2257
+ }, () => dependencies.hooks.onReceiptPosted?.({
2258
+ ...actorFields(actor),
2259
+ receiptId: receipt.id,
2260
+ orderId: receipt.orderId,
2261
+ supplierId: receipt.supplierId,
2262
+ total: receipt.total,
2263
+ lines: receipt.lines.map((line) => ({
2264
+ itemRef: line.itemRef,
2265
+ itemName: line.itemName,
2266
+ stockUnit: line.stockUnit,
2267
+ stockQuantity: toStockQuantity2(line.quantity, line.unitsPerPurchase),
2268
+ landedUnitCost: line.landedUnitCost,
2269
+ averageCost: line.itemRef ? averages.get(line.itemRef) ?? null : null
2270
+ }))
2271
+ }));
2272
+ },
2273
+ /** Reenvia ao estoque e às contas o que falhou (as mesmas chaves: nada duplica). */
2274
+ async retry(params) {
2275
+ await assertEnabled(dependencies, params.companyId);
2276
+ const [row] = await db.select().from(receipts).where(and5(eq5(receipts.companyId, params.companyId), eq5(receipts.id, params.id)));
2277
+ if (!row) throw new ReceiptNotFoundError(params.id);
2278
+ await postStock(params, row);
2279
+ await postPayable(params, row);
2280
+ return load(params.companyId, params.id);
2281
+ },
2282
+ async get(params) {
2283
+ await assertEnabled(dependencies, params.companyId);
2284
+ return load(params.companyId, params.id);
2285
+ },
2286
+ async list(params) {
2287
+ await assertEnabled(dependencies, params.companyId);
2288
+ const { query } = params;
2289
+ const conditions = [
2290
+ eq5(receipts.companyId, params.companyId)
2291
+ ];
2292
+ if (query.supplierId) conditions.push(eq5(receipts.supplierId, query.supplierId));
2293
+ if (query.orderId) conditions.push(eq5(receipts.orderId, query.orderId));
2294
+ if (query.from) conditions.push(gte3(receipts.receivedAt, /* @__PURE__ */ new Date(`${query.from}T00:00:00Z`)));
2295
+ if (query.to) conditions.push(lt3(receipts.receivedAt, /* @__PURE__ */ new Date(`${addDays3(query.to, 1)}T00:00:00Z`)));
2296
+ if (query.failed === true) conditions.push(or3(eq5(receipts.stockStatus, "failed"), eq5(receipts.payableStatus, "failed")));
2297
+ const where = and5(...conditions);
2298
+ const [rows, totals] = await Promise.all([
2299
+ db.select({
2300
+ receipt: receipts,
2301
+ supplierName: suppliers.name,
2302
+ orderNumber: orders.number
2303
+ }).from(receipts).innerJoin(suppliers, eq5(suppliers.id, receipts.supplierId)).leftJoin(orders, eq5(orders.id, receipts.orderId)).where(where).orderBy(desc4(receipts.receivedAt), desc4(receipts.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
2304
+ db.select({
2305
+ total: count4()
2306
+ }).from(receipts).where(where)
2307
+ ]);
2308
+ const ids = rows.map((row) => row.receipt.id);
2309
+ const lines = ids.length ? await db.select().from(receiptLines).where(inArray5(receiptLines.receiptId, ids)).orderBy(asc3(receiptLines.position)) : [];
2310
+ const byReceipt = /* @__PURE__ */ new Map();
2311
+ for (const line of lines) byReceipt.set(line.receiptId, [
2312
+ ...byReceipt.get(line.receiptId) ?? [],
2313
+ line
2314
+ ]);
2315
+ return paginated({
2316
+ rows,
2317
+ total: totals[0]?.total ?? 0,
2318
+ page: query.page,
2319
+ pageSize: query.pageSize,
2320
+ map: /* @__PURE__ */ __name((row) => toReceipt({
2321
+ row: row.receipt,
2322
+ lines: byReceipt.get(row.receipt.id) ?? [],
2323
+ supplierName: row.supplierName,
2324
+ orderNumber: row.orderNumber ?? null
2325
+ }), "map")
2326
+ });
2327
+ },
2328
+ /**
2329
+ * Pagamento de uma parcela, vindo do financeiro (gancho `onOccurrenceSettled` do `expense-module`). Busca pelo
2330
+ * recebimento ou pela `payableRef`. Idempotente: a mesma parcela paga de novo só atualiza o valor.
2331
+ */
2332
+ async recordPayment(params) {
2333
+ await assertEnabled(dependencies, params.companyId);
2334
+ const condition = params.receiptId ? eq5(receipts.id, params.receiptId) : eq5(receipts.payableRef, params.payableRef ?? "");
2335
+ const [row] = await db.select().from(receipts).where(and5(eq5(receipts.companyId, params.companyId), condition));
2336
+ if (!row) throw new ReceiptNotFoundError(params.receiptId ?? params.payableRef ?? "");
2337
+ if (params.paidAmount === null || params.paidAt === null) {
2338
+ await db.delete(receiptPayments).where(and5(eq5(receiptPayments.receiptId, row.id), eq5(receiptPayments.installmentNumber, params.installmentNumber)));
2339
+ } else {
2340
+ await db.insert(receiptPayments).values({
2341
+ companyId: params.companyId,
2342
+ receiptId: row.id,
2343
+ installmentNumber: params.installmentNumber,
2344
+ paidAmount: params.paidAmount,
2345
+ paidAt: params.paidAt
2346
+ }).onConflictDoUpdate({
2347
+ target: [
2348
+ receiptPayments.receiptId,
2349
+ receiptPayments.installmentNumber
2350
+ ],
2351
+ set: {
2352
+ paidAmount: params.paidAmount,
2353
+ paidAt: params.paidAt
2354
+ }
2355
+ });
2356
+ }
2357
+ const payments = await db.select().from(receiptPayments).where(eq5(receiptPayments.receiptId, row.id));
2358
+ const paid = payments.reduce((acc, payment) => acc + centsOf2(parseDecimal5(payment.paidAmount)), 0n);
2359
+ const total = centsOf2(parseDecimal5(row.total));
2360
+ const status = paid === 0n ? PAYMENT_STATUS.OPEN : paid >= total ? PAYMENT_STATUS.PAID : PAYMENT_STATUS.PARTIAL;
2361
+ await db.update(receipts).set({
2362
+ paymentStatus: status
2363
+ }).where(eq5(receipts.id, row.id));
2364
+ return load(params.companyId, row.id);
2365
+ }
2366
+ };
2367
+ return service;
2368
+ }
2369
+ __name(createReceiptService, "createReceiptService");
2370
+
2371
+ // src/services/reports.ts
2372
+ import { buildCsv, buildXlsx, CSV_BOM, CSV_CONTENT_TYPE, formatDecimal as formatDecimal2, parseDecimal as parseDecimal6, XLSX_CONTENT_TYPE } from "@adatechnology/recipe-contracts";
2373
+ import { add as add3, addDays as addDays4, centsOf as centsOf3, civilDateIn as civilDateIn3, money as money4, PURCHASE_LIMITS, REPORT_GROUP, ReportRangeTooLongError, ZERO as ZERO4 } from "@adatechnology/purchase-contracts";
2374
+ import { and as and6, eq as eq6, gte as gte4, inArray as inArray6, lt as lt4 } from "drizzle-orm";
2375
+ function daysBetween(from, to) {
2376
+ return Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 864e5);
2377
+ }
2378
+ __name(daysBetween, "daysBetween");
2379
+ function assertRange(from, to) {
2380
+ if (daysBetween(from, to) > PURCHASE_LIMITS.REPORT_DAYS) throw new ReportRangeTooLongError(PURCHASE_LIMITS.REPORT_DAYS);
2381
+ }
2382
+ __name(assertRange, "assertRange");
2383
+ function instantRange(from, to) {
2384
+ return {
2385
+ start: /* @__PURE__ */ new Date(`${addDays4(from, -1)}T00:00:00Z`),
2386
+ end: /* @__PURE__ */ new Date(`${addDays4(to, 2)}T00:00:00Z`)
2387
+ };
2388
+ }
2389
+ __name(instantRange, "instantRange");
2390
+ function createReportService(dependencies) {
2391
+ const { db } = dependencies;
2392
+ async function spend(params) {
2393
+ await assertEnabled(dependencies, params.companyId);
2394
+ const { query } = params;
2395
+ assertRange(query.from, query.to);
2396
+ const { start, end } = instantRange(query.from, query.to);
2397
+ const conditions = [
2398
+ eq6(receipts.companyId, params.companyId),
2399
+ gte4(receipts.receivedAt, start),
2400
+ lt4(receipts.receivedAt, end)
2401
+ ];
2402
+ if (query.supplierId) conditions.push(eq6(receipts.supplierId, query.supplierId));
2403
+ if (query.itemRef) conditions.push(eq6(receiptLines.itemRef, query.itemRef));
2404
+ const rows = await db.select({
2405
+ receiptId: receipts.id,
2406
+ receivedAt: receipts.receivedAt,
2407
+ supplierId: receipts.supplierId,
2408
+ supplierName: suppliers.name,
2409
+ itemRef: receiptLines.itemRef,
2410
+ itemName: receiptLines.itemName,
2411
+ lineTotal: receiptLines.lineTotal,
2412
+ allocated: receiptLines.allocated
2413
+ }).from(receiptLines).innerJoin(receipts, eq6(receipts.id, receiptLines.receiptId)).innerJoin(suppliers, eq6(suppliers.id, receipts.supplierId)).where(and6(...conditions));
2414
+ const groups = /* @__PURE__ */ new Map();
2415
+ const allReceipts = /* @__PURE__ */ new Set();
2416
+ let grand = ZERO4;
2417
+ for (const row of rows) {
2418
+ const day = civilDateIn3(row.receivedAt, dependencies.timeZone);
2419
+ if (day < query.from || day > query.to) continue;
2420
+ const value = add3(parseDecimal6(row.lineTotal), parseDecimal6(row.allocated));
2421
+ const key = query.groupBy === REPORT_GROUP.SUPPLIER ? row.supplierId : query.groupBy === REPORT_GROUP.MONTH ? day.slice(0, 7) : row.itemRef ?? `name:${row.itemName.toLowerCase()}`;
2422
+ const label = query.groupBy === REPORT_GROUP.SUPPLIER ? row.supplierName : query.groupBy === REPORT_GROUP.MONTH ? day.slice(0, 7) : row.itemName;
2423
+ const group = groups.get(key) ?? {
2424
+ label,
2425
+ receipts: /* @__PURE__ */ new Set(),
2426
+ lines: 0,
2427
+ total: ZERO4
2428
+ };
2429
+ group.receipts.add(row.receiptId);
2430
+ group.lines += 1;
2431
+ group.total = add3(group.total, value);
2432
+ groups.set(key, group);
2433
+ allReceipts.add(row.receiptId);
2434
+ grand = add3(grand, value);
2435
+ }
2436
+ const sorted = [
2437
+ ...groups.entries()
2438
+ ].sort((left, right) => {
2439
+ if (query.groupBy === REPORT_GROUP.MONTH) return left[0].localeCompare(right[0]);
2440
+ const difference = centsOf3(right[1].total) - centsOf3(left[1].total);
2441
+ return difference > 0n ? 1 : difference < 0n ? -1 : left[1].label.localeCompare(right[1].label, "pt-BR");
2442
+ });
2443
+ return {
2444
+ from: query.from,
2445
+ to: query.to,
2446
+ groupBy: query.groupBy,
2447
+ rows: sorted.map(([key, group]) => ({
2448
+ key,
2449
+ label: group.label,
2450
+ receiptCount: group.receipts.size,
2451
+ lineCount: group.lines,
2452
+ total: money4(group.total)
2453
+ })),
2454
+ total: money4(grand),
2455
+ receiptCount: allReceipts.size
2456
+ };
2457
+ }
2458
+ __name(spend, "spend");
2459
+ return {
2460
+ spend,
2461
+ async exportSpend(params) {
2462
+ const report = await spend(params);
2463
+ const table = {
2464
+ header: [
2465
+ "Grupo",
2466
+ "Recebimentos",
2467
+ "Linhas",
2468
+ "Total (R$)"
2469
+ ],
2470
+ rows: [
2471
+ ...report.rows.map((row) => [
2472
+ row.label,
2473
+ row.receiptCount,
2474
+ row.lineCount,
2475
+ row.total
2476
+ ]),
2477
+ [
2478
+ "Total",
2479
+ report.receiptCount,
2480
+ null,
2481
+ report.total
2482
+ ]
2483
+ ]
2484
+ };
2485
+ const fileName = `compras-${report.groupBy}-${report.from}-${report.to}`;
2486
+ if (params.format === "xlsx") return {
2487
+ contentType: XLSX_CONTENT_TYPE,
2488
+ fileName: `${fileName}.xlsx`,
2489
+ body: buildXlsx({
2490
+ table,
2491
+ sheetName: "Compras"
2492
+ })
2493
+ };
2494
+ return {
2495
+ contentType: CSV_CONTENT_TYPE,
2496
+ fileName: `${fileName}.csv`,
2497
+ body: CSV_BOM + buildCsv(table)
2498
+ };
2499
+ },
2500
+ async supplierPerformance(params) {
2501
+ await assertEnabled(dependencies, params.companyId);
2502
+ const { query } = params;
2503
+ assertRange(query.from, query.to);
2504
+ const { start, end } = instantRange(query.from, query.to);
2505
+ const receiptRows = await db.select({
2506
+ receipt: receipts,
2507
+ supplierName: suppliers.name
2508
+ }).from(receipts).innerJoin(suppliers, eq6(suppliers.id, receipts.supplierId)).where(and6(eq6(receipts.companyId, params.companyId), gte4(receipts.receivedAt, start), lt4(receipts.receivedAt, end)));
2509
+ const inRange = receiptRows.filter((row) => {
2510
+ const day = civilDateIn3(row.receipt.receivedAt, dependencies.timeZone);
2511
+ return day >= query.from && day <= query.to;
2512
+ });
2513
+ const receiptIds = inRange.map((row) => row.receipt.id);
2514
+ const orderIds = [
2515
+ ...new Set(inRange.flatMap((row) => row.receipt.orderId ? [
2516
+ row.receipt.orderId
2517
+ ] : []))
2518
+ ];
2519
+ const [lines, orderRows, firstReceipts] = await Promise.all([
2520
+ receiptIds.length ? db.select({
2521
+ receiptId: receiptLines.receiptId,
2522
+ divergence: receiptLines.divergence
2523
+ }).from(receiptLines).where(inArray6(receiptLines.receiptId, receiptIds)) : Promise.resolve([]),
2524
+ orderIds.length ? db.select().from(orders).where(inArray6(orders.id, orderIds)) : Promise.resolve([]),
2525
+ orderIds.length ? db.select({
2526
+ orderId: receipts.orderId,
2527
+ receivedAt: receipts.receivedAt
2528
+ }).from(receipts).where(inArray6(receipts.orderId, orderIds)) : Promise.resolve([])
2529
+ ]);
2530
+ const firstByOrder = /* @__PURE__ */ new Map();
2531
+ for (const row of firstReceipts) {
2532
+ if (!row.orderId) continue;
2533
+ const current = firstByOrder.get(row.orderId);
2534
+ if (!current || row.receivedAt < current) firstByOrder.set(row.orderId, row.receivedAt);
2535
+ }
2536
+ const supplierOf = new Map(inRange.map((row) => [
2537
+ row.receipt.id,
2538
+ row.receipt.supplierId
2539
+ ]));
2540
+ const bySupplier = /* @__PURE__ */ new Map();
2541
+ const accOf = /* @__PURE__ */ __name((supplierId2, name) => {
2542
+ const current = bySupplier.get(supplierId2) ?? {
2543
+ name,
2544
+ orders: /* @__PURE__ */ new Set(),
2545
+ onTime: 0,
2546
+ late: 0,
2547
+ lateDays: 0,
2548
+ divergent: 0,
2549
+ lines: 0,
2550
+ total: ZERO4
2551
+ };
2552
+ bySupplier.set(supplierId2, current);
2553
+ return current;
2554
+ }, "accOf");
2555
+ for (const row of inRange) {
2556
+ const acc = accOf(row.receipt.supplierId, row.supplierName);
2557
+ acc.total = add3(acc.total, parseDecimal6(row.receipt.total));
2558
+ }
2559
+ for (const line of lines) {
2560
+ const supplierId2 = supplierOf.get(line.receiptId);
2561
+ if (!supplierId2) continue;
2562
+ const acc = bySupplier.get(supplierId2);
2563
+ if (!acc) continue;
2564
+ acc.lines += 1;
2565
+ if (line.divergence !== "none") acc.divergent += 1;
2566
+ }
2567
+ for (const order of orderRows) {
2568
+ const acc = bySupplier.get(order.supplierId);
2569
+ if (!acc || acc.orders.has(order.id)) continue;
2570
+ acc.orders.add(order.id);
2571
+ const first = firstByOrder.get(order.id);
2572
+ if (!order.expectedAt || !first) continue;
2573
+ const arrived = civilDateIn3(first, dependencies.timeZone);
2574
+ const late = daysBetween(order.expectedAt, arrived);
2575
+ if (late > 0) {
2576
+ acc.late += 1;
2577
+ acc.lateDays += late;
2578
+ } else acc.onTime += 1;
2579
+ }
2580
+ return {
2581
+ from: query.from,
2582
+ to: query.to,
2583
+ rows: [
2584
+ ...bySupplier.entries()
2585
+ ].map(([supplierId2, acc]) => ({
2586
+ supplierId: supplierId2,
2587
+ supplierName: acc.name,
2588
+ orderCount: acc.orders.size,
2589
+ onTimeCount: acc.onTime,
2590
+ lateCount: acc.late,
2591
+ averageDaysLate: acc.late ? formatDecimal2({
2592
+ numerator: BigInt(acc.lateDays),
2593
+ denominator: BigInt(acc.late)
2594
+ }, 1) : null,
2595
+ divergentLineCount: acc.divergent,
2596
+ receivedLineCount: acc.lines,
2597
+ total: money4(acc.total)
2598
+ })).sort((left, right) => left.supplierName.localeCompare(right.supplierName, "pt-BR"))
2599
+ };
2600
+ }
2601
+ };
2602
+ }
2603
+ __name(createReportService, "createReportService");
2604
+
2605
+ // src/PurchaseModule.ts
2606
+ var SYSTEM_CLOCK = {
2607
+ now: /* @__PURE__ */ __name(() => /* @__PURE__ */ new Date(), "now")
2608
+ };
2609
+ var DEFAULT_TIME_ZONE = "America/Sao_Paulo";
2610
+ var DEFAULT_AVERAGE_WINDOW_DAYS = 90;
2611
+ function isTimeZone(value) {
2612
+ try {
2613
+ new Intl.DateTimeFormat("en-US", {
2614
+ timeZone: value
2615
+ });
2616
+ return true;
2617
+ } catch {
2618
+ return false;
2619
+ }
2620
+ }
2621
+ __name(isTimeZone, "isTimeZone");
2622
+ function createPurchaseModule(params) {
2623
+ if (!params.db) throw new PurchaseConfigMissingError("db");
2624
+ const config = params.config ?? {};
2625
+ const timeZone = config.timeZone ?? DEFAULT_TIME_ZONE;
2626
+ if (!isTimeZone(timeZone)) throw new PurchaseConfigMissingError("timeZone");
2627
+ const windowDays = config.averageCostWindowDays ?? DEFAULT_AVERAGE_WINDOW_DAYS;
2628
+ if (!Number.isInteger(windowDays) || windowDays < 1) throw new PurchaseConfigMissingError("averageCostWindowDays");
2629
+ if (config.priceToleranceCents !== void 0 && (!Number.isInteger(config.priceToleranceCents) || config.priceToleranceCents < 0)) throw new PurchaseConfigMissingError("priceToleranceCents");
2630
+ const providers = params.providers ?? {};
2631
+ if (providers.dispatch && providers.dispatch.channels.length === 0) throw new PurchaseConfigMissingError("providers.dispatch.channels");
2632
+ const dependencies = {
2633
+ db: params.db,
2634
+ config,
2635
+ providers,
2636
+ hooks: params.hooks ?? {},
2637
+ clock: providers.clock ?? SYSTEM_CLOCK,
2638
+ logger: providers.logger,
2639
+ timeZone,
2640
+ averageCostWindowDays: windowDays
2641
+ };
2642
+ const orders2 = createOrderService(dependencies);
2643
+ const insights = createInsightService(dependencies, () => orders2);
2644
+ const receipts2 = createReceiptService(dependencies, () => insights);
2645
+ return {
2646
+ useCases: {
2647
+ suppliers: createSupplierService(dependencies),
2648
+ orders: orders2,
2649
+ receipts: receipts2,
2650
+ insights,
2651
+ reports: createReportService(dependencies),
2652
+ nfe: createNfeService(dependencies),
2653
+ jobs: createJobService(dependencies, () => insights)
2654
+ },
2655
+ config,
2656
+ /** Quais portas estão ligadas (a tela esconde o que não se aplica). */
2657
+ capabilities: {
2658
+ catalog: providers.catalog !== void 0,
2659
+ stock: providers.stock !== void 0,
2660
+ demand: providers.demand !== void 0,
2661
+ payables: providers.payables !== void 0,
2662
+ dispatchChannels: providers.dispatch ? [
2663
+ ...providers.dispatch.channels
2664
+ ] : []
2665
+ }
2666
+ };
2667
+ }
2668
+ __name(createPurchaseModule, "createPurchaseModule");
2669
+
2670
+ // src/http/routes.ts
2671
+ import { createOrderSchema, createSupplierItemSchema, createSupplierSchema, DEFAULT_PURCHASE_SCOPES, exportFormatSchema, itemRefsLookupSchema, listOrdersQuerySchema, listReceiptsQuerySchema, listSupplierItemsQuerySchema, listSuppliersQuerySchema, nfePreviewSchema, optionalReasonSchema, OrderNotFoundError as OrderNotFoundError3, ordersFromSuggestionSchema, PurchaseUnauthenticatedError, priceHistoryQuerySchema, reasonSchema, ReceiptNotFoundError as ReceiptNotFoundError2, receiveSchema, sendOrderSchema, spendReportQuerySchema, suggestionQuerySchema, SupplierItemNotFoundError as SupplierItemNotFoundError4, supplierLookupSchema, SupplierNotFoundError as SupplierNotFoundError2, supplierPerformanceQuerySchema, updateOrderSchema, updateSupplierItemSchema, updateSupplierSchema } from "@adatechnology/purchase-contracts";
2672
+ import { z } from "zod";
2673
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2674
+ function companyOf(context) {
2675
+ if (!context.auth?.companyId) throw new PurchaseUnauthenticatedError();
2676
+ return context.auth.companyId;
2677
+ }
2678
+ __name(companyOf, "companyOf");
2679
+ function actorOf(context) {
2680
+ const companyId = companyOf(context);
2681
+ return {
2682
+ companyId,
2683
+ ...context.auth?.userId ? {
2684
+ actorId: context.auth.userId
2685
+ } : {}
2686
+ };
2687
+ }
2688
+ __name(actorOf, "actorOf");
2689
+ function uuidParam(context, name, notFound) {
2690
+ const value = context.params[name] ?? "";
2691
+ if (!UUID_PATTERN.test(value)) throw notFound(value);
2692
+ return value;
2693
+ }
2694
+ __name(uuidParam, "uuidParam");
2695
+ var json = /* @__PURE__ */ __name((status, data) => ({
2696
+ kind: "json",
2697
+ status,
2698
+ body: {
2699
+ data
2700
+ }
2701
+ }), "json");
2702
+ var empty = /* @__PURE__ */ __name(() => ({
2703
+ kind: "empty",
2704
+ status: 204
2705
+ }), "empty");
2706
+ var supplierId = /* @__PURE__ */ __name((context) => uuidParam(context, "id", (value) => new SupplierNotFoundError2(value)), "supplierId");
2707
+ var supplierItemId = /* @__PURE__ */ __name((context) => uuidParam(context, "id", (value) => new SupplierItemNotFoundError4(value)), "supplierItemId");
2708
+ var orderId = /* @__PURE__ */ __name((context) => uuidParam(context, "id", (value) => new OrderNotFoundError3(value)), "orderId");
2709
+ var receiptId = /* @__PURE__ */ __name((context) => uuidParam(context, "id", (value) => new ReceiptNotFoundError2(value)), "receiptId");
2710
+ var messageQuerySchema = z.object({
2711
+ withPrices: z.enum([
2712
+ "true",
2713
+ "false"
2714
+ ]).transform((value) => value === "true").optional()
2715
+ });
2716
+ var exportSpendQuerySchema = z.intersection(spendReportQuerySchema, exportFormatSchema);
2717
+ var paymentSchema = z.object({
2718
+ receiptId: z.string().uuid().optional(),
2719
+ payableRef: z.string().trim().min(1).max(200).optional(),
2720
+ installmentNumber: z.number().int().min(1).max(100),
2721
+ /** `null` desfaz o pagamento (reaberto no financeiro). */
2722
+ paidAmount: z.string().regex(/^\d{1,12}(\.\d{1,2})?$/).nullable(),
2723
+ paidAt: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable()
2724
+ }).refine((value) => value.receiptId !== void 0 || value.payableRef !== void 0, {
2725
+ message: "Informe receiptId ou payableRef."
2726
+ });
2727
+ function supplierRoutes(module, read, write) {
2728
+ const { suppliers: suppliers2 } = module.useCases;
2729
+ return [
2730
+ {
2731
+ ...read,
2732
+ method: "GET",
2733
+ path: "/suppliers",
2734
+ querySchema: listSuppliersQuerySchema,
2735
+ operationId: "purchaseListSuppliers",
2736
+ summary: "Fornecedores (busca, ativos, ordena\xE7\xE3o, pagina\xE7\xE3o)",
2737
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await suppliers2.list({
2738
+ companyId: companyOf(context),
2739
+ query: context.query
2740
+ })), "handler")
2741
+ },
2742
+ {
2743
+ ...write,
2744
+ method: "POST",
2745
+ path: "/suppliers",
2746
+ bodySchema: createSupplierSchema,
2747
+ operationId: "purchaseCreateSupplier",
2748
+ summary: "Cadastra fornecedor (condi\xE7\xE3o de pagamento, prazo, pedido m\xEDnimo, dias de entrega)",
2749
+ handler: /* @__PURE__ */ __name(async (context) => json(201, await suppliers2.create({
2750
+ companyId: companyOf(context),
2751
+ input: context.body
2752
+ })), "handler")
2753
+ },
2754
+ {
2755
+ ...read,
2756
+ method: "GET",
2757
+ path: "/suppliers/:id",
2758
+ operationId: "purchaseGetSupplier",
2759
+ summary: "Fornecedor",
2760
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await suppliers2.get({
2761
+ companyId: companyOf(context),
2762
+ id: supplierId(context)
2763
+ })), "handler")
2764
+ },
2765
+ {
2766
+ ...write,
2767
+ method: "PATCH",
2768
+ path: "/suppliers/:id",
2769
+ bodySchema: updateSupplierSchema,
2770
+ operationId: "purchaseUpdateSupplier",
2771
+ summary: "Altera fornecedor (s\xF3 os campos enviados; `isActive: false` desativa)",
2772
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await suppliers2.update({
2773
+ companyId: companyOf(context),
2774
+ id: supplierId(context),
2775
+ input: context.body
2776
+ })), "handler")
2777
+ },
2778
+ {
2779
+ ...write,
2780
+ method: "DELETE",
2781
+ path: "/suppliers/:id",
2782
+ operationId: "purchaseDeleteSupplier",
2783
+ summary: "Exclui fornecedor sem pedido nem recebimento (com hist\xF3rico: 409, desative)",
2784
+ handler: /* @__PURE__ */ __name(async (context) => {
2785
+ await suppliers2.remove({
2786
+ companyId: companyOf(context),
2787
+ id: supplierId(context)
2788
+ });
2789
+ return empty();
2790
+ }, "handler")
2791
+ },
2792
+ {
2793
+ ...write,
2794
+ method: "POST",
2795
+ path: "/suppliers/:id/items",
2796
+ bodySchema: createSupplierItemSchema,
2797
+ operationId: "purchaseCreateSupplierItem",
2798
+ summary: "Item que o fornecedor vende: c\xF3digo, embalagem, convers\xE3o para o estoque, pre\xE7o",
2799
+ handler: /* @__PURE__ */ __name(async (context) => json(201, await suppliers2.createItem({
2800
+ companyId: companyOf(context),
2801
+ supplierId: supplierId(context),
2802
+ input: context.body
2803
+ })), "handler")
2804
+ },
2805
+ {
2806
+ ...read,
2807
+ method: "GET",
2808
+ path: "/supplier-items",
2809
+ querySchema: listSupplierItemsQuerySchema,
2810
+ operationId: "purchaseListSupplierItems",
2811
+ summary: "Itens de fornecedor (por fornecedor, por item do cat\xE1logo, busca)",
2812
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await suppliers2.listItems({
2813
+ companyId: companyOf(context),
2814
+ query: context.query
2815
+ })), "handler")
2816
+ },
2817
+ {
2818
+ ...read,
2819
+ method: "GET",
2820
+ path: "/supplier-items/:id",
2821
+ operationId: "purchaseGetSupplierItem",
2822
+ summary: "Item de fornecedor",
2823
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await suppliers2.getItem({
2824
+ companyId: companyOf(context),
2825
+ id: supplierItemId(context)
2826
+ })), "handler")
2827
+ },
2828
+ {
2829
+ ...write,
2830
+ method: "PATCH",
2831
+ path: "/supplier-items/:id",
2832
+ bodySchema: updateSupplierItemSchema,
2833
+ operationId: "purchaseUpdateSupplierItem",
2834
+ summary: "Altera item de fornecedor",
2835
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await suppliers2.updateItem({
2836
+ companyId: companyOf(context),
2837
+ id: supplierItemId(context),
2838
+ input: context.body
2839
+ })), "handler")
2840
+ },
2841
+ {
2842
+ ...write,
2843
+ method: "DELETE",
2844
+ path: "/supplier-items/:id",
2845
+ operationId: "purchaseDeleteSupplierItem",
2846
+ summary: "Remove item de fornecedor (pedidos antigos guardam a c\xF3pia)",
2847
+ handler: /* @__PURE__ */ __name(async (context) => {
2848
+ await suppliers2.removeItem({
2849
+ companyId: companyOf(context),
2850
+ id: supplierItemId(context)
2851
+ });
2852
+ return empty();
2853
+ }, "handler")
2854
+ }
2855
+ ];
2856
+ }
2857
+ __name(supplierRoutes, "supplierRoutes");
2858
+ function orderRoutes(module, read, write, approve) {
2859
+ const { orders: orders2 } = module.useCases;
2860
+ const action = /* @__PURE__ */ __name((path2, operationId, summary, run, access = write, bodySchema) => ({
2861
+ ...access,
2862
+ method: "POST",
2863
+ path: path2,
2864
+ ...bodySchema ? {
2865
+ bodySchema
2866
+ } : {},
2867
+ operationId,
2868
+ summary,
2869
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await run(context)), "handler")
2870
+ }), "action");
2871
+ return [
2872
+ {
2873
+ ...read,
2874
+ method: "GET",
2875
+ path: "/orders",
2876
+ querySchema: listOrdersQuerySchema,
2877
+ operationId: "purchaseListOrders",
2878
+ summary: "Pedidos de compra (status, fornecedor, atrasados, per\xEDodo, n\xFAmero)",
2879
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await orders2.list({
2880
+ companyId: companyOf(context),
2881
+ query: context.query
2882
+ })), "handler")
2883
+ },
2884
+ {
2885
+ ...write,
2886
+ method: "POST",
2887
+ path: "/orders",
2888
+ bodySchema: createOrderSchema,
2889
+ operationId: "purchaseCreateOrder",
2890
+ summary: "Cria rascunho (n\xFAmero sequencial por empresa; previs\xE3o padr\xE3o pelo prazo do fornecedor)",
2891
+ handler: /* @__PURE__ */ __name(async (context) => json(201, await orders2.create({
2892
+ ...actorOf(context),
2893
+ input: context.body
2894
+ })), "handler")
2895
+ },
2896
+ {
2897
+ ...read,
2898
+ method: "GET",
2899
+ path: "/orders/:id",
2900
+ operationId: "purchaseGetOrder",
2901
+ summary: "Pedido com linhas, recebido e pendente por linha",
2902
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await orders2.get({
2903
+ companyId: companyOf(context),
2904
+ id: orderId(context)
2905
+ })), "handler")
2906
+ },
2907
+ {
2908
+ ...write,
2909
+ method: "PATCH",
2910
+ path: "/orders/:id",
2911
+ bodySchema: updateOrderSchema,
2912
+ operationId: "purchaseUpdateOrder",
2913
+ summary: "Altera rascunho (`lines` substitui todas)",
2914
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await orders2.update({
2915
+ ...actorOf(context),
2916
+ id: orderId(context),
2917
+ input: context.body
2918
+ })), "handler")
2919
+ },
2920
+ {
2921
+ ...read,
2922
+ method: "GET",
2923
+ path: "/orders/:id/message",
2924
+ querySchema: messageQuerySchema,
2925
+ operationId: "purchaseOrderMessage",
2926
+ summary: "Texto do pedido para o fornecedor (o mesmo do WhatsApp)",
2927
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await orders2.message({
2928
+ companyId: companyOf(context),
2929
+ id: orderId(context),
2930
+ withPrices: context.query.withPrices === true
2931
+ })), "handler")
2932
+ },
2933
+ action("/orders/:id/submit", "purchaseSubmitOrder", "Envia para aprova\xE7\xE3o (ou aprova direto abaixo do limite)", (context) => orders2.submit({
2934
+ ...actorOf(context),
2935
+ id: orderId(context)
2936
+ })),
2937
+ action("/orders/:id/approve", "purchaseApproveOrder", "Aprova (escopo de aprova\xE7\xE3o; quem submeteu n\xE3o aprova)", (context) => orders2.approve({
2938
+ ...actorOf(context),
2939
+ id: orderId(context)
2940
+ }), approve),
2941
+ action("/orders/:id/reject", "purchaseRejectOrder", "Recusa com motivo (volta a rascunho)", (context) => orders2.reject({
2942
+ ...actorOf(context),
2943
+ id: orderId(context),
2944
+ reason: context.body.reason
2945
+ }), approve, reasonSchema),
2946
+ action("/orders/:id/send", "purchaseSendOrder", "Envia ao fornecedor (WhatsApp/e-mail pela porta, ou `manual`)", (context) => orders2.send({
2947
+ ...actorOf(context),
2948
+ id: orderId(context),
2949
+ input: context.body
2950
+ }), write, sendOrderSchema),
2951
+ action("/orders/:id/cancel", "purchaseCancelOrder", "Cancela (at\xE9 o primeiro recebimento)", (context) => orders2.cancel({
2952
+ ...actorOf(context),
2953
+ id: orderId(context),
2954
+ reason: context.body.reason
2955
+ }), write, reasonSchema),
2956
+ action("/orders/:id/close", "purchaseCloseOrder", "Encerra o saldo de um pedido recebido em parte", (context) => orders2.close({
2957
+ ...actorOf(context),
2958
+ id: orderId(context),
2959
+ reason: context.body.reason
2960
+ }), write, optionalReasonSchema),
2961
+ {
2962
+ ...write,
2963
+ method: "POST",
2964
+ path: "/orders/:id/duplicate",
2965
+ operationId: "purchaseDuplicateOrder",
2966
+ summary: "Novo rascunho com as mesmas linhas e o \xFAltimo pre\xE7o",
2967
+ handler: /* @__PURE__ */ __name(async (context) => json(201, await orders2.duplicate({
2968
+ ...actorOf(context),
2969
+ id: orderId(context)
2970
+ })), "handler")
2971
+ }
2972
+ ];
2973
+ }
2974
+ __name(orderRoutes, "orderRoutes");
2975
+ function receiptRoutes(module, read, write) {
2976
+ const { receipts: receipts2, nfe } = module.useCases;
2977
+ return [
2978
+ {
2979
+ ...write,
2980
+ method: "POST",
2981
+ path: "/orders/:id/receipts",
2982
+ bodySchema: receiveSchema,
2983
+ operationId: "purchaseReceiveOrder",
2984
+ summary: "Recebe (parcial ou total) um pedido: lote, validade, diverg\xEAncia, custo com rateio",
2985
+ handler: /* @__PURE__ */ __name(async (context) => json(201, await receipts2.receive({
2986
+ ...actorOf(context),
2987
+ orderId: orderId(context),
2988
+ input: context.body
2989
+ })), "handler")
2990
+ },
2991
+ {
2992
+ ...write,
2993
+ method: "POST",
2994
+ path: "/receipts",
2995
+ bodySchema: receiveSchema,
2996
+ operationId: "purchaseReceiveWithoutOrder",
2997
+ summary: "Recebimento sem pedido (compra no balc\xE3o, feira)",
2998
+ handler: /* @__PURE__ */ __name(async (context) => json(201, await receipts2.receive({
2999
+ ...actorOf(context),
3000
+ input: context.body
3001
+ })), "handler")
3002
+ },
3003
+ {
3004
+ ...read,
3005
+ method: "GET",
3006
+ path: "/receipts",
3007
+ querySchema: listReceiptsQuerySchema,
3008
+ operationId: "purchaseListReceipts",
3009
+ summary: "Recebimentos (fornecedor, pedido, per\xEDodo, com falha de integra\xE7\xE3o)",
3010
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await receipts2.list({
3011
+ companyId: companyOf(context),
3012
+ query: context.query
3013
+ })), "handler")
3014
+ },
3015
+ {
3016
+ ...read,
3017
+ method: "GET",
3018
+ path: "/receipts/:id",
3019
+ operationId: "purchaseGetReceipt",
3020
+ summary: "Recebimento com linhas e situa\xE7\xE3o das integra\xE7\xF5es",
3021
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await receipts2.get({
3022
+ companyId: companyOf(context),
3023
+ id: receiptId(context)
3024
+ })), "handler")
3025
+ },
3026
+ {
3027
+ ...write,
3028
+ method: "POST",
3029
+ path: "/receipts/:id/retry",
3030
+ operationId: "purchaseRetryReceipt",
3031
+ summary: "Reenvia ao estoque e \xE0s contas o que falhou (idempotente)",
3032
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await receipts2.retry({
3033
+ ...actorOf(context),
3034
+ id: receiptId(context)
3035
+ })), "handler")
3036
+ },
3037
+ {
3038
+ ...write,
3039
+ method: "POST",
3040
+ path: "/nfe/preview",
3041
+ bodySchema: nfePreviewSchema,
3042
+ operationId: "purchasePreviewNfe",
3043
+ summary: "L\xEA o XML da NF-e e devolve a pr\xE9via do recebimento (n\xE3o grava)",
3044
+ handler: /* @__PURE__ */ __name(async (context) => {
3045
+ const body = context.body;
3046
+ return json(200, await nfe.preview({
3047
+ companyId: companyOf(context),
3048
+ xml: body.xml,
3049
+ ...body.orderId ? {
3050
+ orderId: body.orderId
3051
+ } : {}
3052
+ }));
3053
+ }, "handler")
3054
+ }
3055
+ ];
3056
+ }
3057
+ __name(receiptRoutes, "receiptRoutes");
3058
+ function insightRoutes(module, read, write) {
3059
+ const { insights, reports } = module.useCases;
3060
+ return [
3061
+ {
3062
+ ...read,
3063
+ method: "GET",
3064
+ path: "/capabilities",
3065
+ operationId: "purchaseCapabilities",
3066
+ summary: "Portas ligadas e limite de aprova\xE7\xE3o (a tela esconde o que n\xE3o se aplica)",
3067
+ handler: /* @__PURE__ */ __name(async (context) => {
3068
+ const companyId = companyOf(context);
3069
+ const threshold = await module.config.approvalThresholdFor?.(companyId) ?? null;
3070
+ return json(200, {
3071
+ ...module.capabilities,
3072
+ approvalThreshold: threshold
3073
+ });
3074
+ }, "handler")
3075
+ },
3076
+ {
3077
+ ...read,
3078
+ method: "GET",
3079
+ path: "/suggestion",
3080
+ querySchema: suggestionQuerySchema,
3081
+ operationId: "purchaseSuggestion",
3082
+ summary: "Sugest\xE3o de pedido por fornecedor (necessidade, m\xEDnimo, saldo e a caminho)",
3083
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await insights.suggestion({
3084
+ companyId: companyOf(context),
3085
+ query: context.query
3086
+ })), "handler")
3087
+ },
3088
+ {
3089
+ ...write,
3090
+ method: "POST",
3091
+ path: "/suggestion/orders",
3092
+ bodySchema: ordersFromSuggestionSchema,
3093
+ operationId: "purchaseOrdersFromSuggestion",
3094
+ summary: "Cria um rascunho por fornecedor a partir da sugest\xE3o",
3095
+ handler: /* @__PURE__ */ __name(async (context) => json(201, await insights.ordersFromSuggestion({
3096
+ ...actorOf(context),
3097
+ input: context.body
3098
+ })), "handler")
3099
+ },
3100
+ {
3101
+ ...read,
3102
+ method: "GET",
3103
+ path: "/prices/history",
3104
+ querySchema: priceHistoryQuerySchema,
3105
+ operationId: "purchasePriceHistory",
3106
+ summary: "Hist\xF3rico de pre\xE7o por item (todos os fornecedores ou um)",
3107
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await insights.priceHistory({
3108
+ companyId: companyOf(context),
3109
+ query: context.query
3110
+ })), "handler")
3111
+ },
3112
+ {
3113
+ ...read,
3114
+ method: "POST",
3115
+ path: "/items/costs",
3116
+ bodySchema: itemRefsLookupSchema,
3117
+ operationId: "purchaseItemCosts",
3118
+ summary: "\xDAltimo custo e custo m\xE9dio por item",
3119
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await insights.itemCosts({
3120
+ companyId: companyOf(context),
3121
+ itemRefs: context.body.itemRefs
3122
+ })), "handler")
3123
+ },
3124
+ {
3125
+ ...read,
3126
+ method: "POST",
3127
+ path: "/items/incoming",
3128
+ bodySchema: itemRefsLookupSchema,
3129
+ operationId: "purchaseIncomingSupply",
3130
+ summary: "Quanto j\xE1 foi pedido e ainda n\xE3o chegou, por item",
3131
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await insights.incoming({
3132
+ companyId: companyOf(context),
3133
+ itemRefs: context.body.itemRefs
3134
+ })), "handler")
3135
+ },
3136
+ {
3137
+ ...read,
3138
+ method: "GET",
3139
+ path: "/reports/spend",
3140
+ querySchema: spendReportQuerySchema,
3141
+ operationId: "purchaseSpendReport",
3142
+ summary: "Gasto por fornecedor, item ou m\xEAs",
3143
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await reports.spend({
3144
+ companyId: companyOf(context),
3145
+ query: context.query
3146
+ })), "handler")
3147
+ },
3148
+ {
3149
+ ...read,
3150
+ method: "GET",
3151
+ path: "/reports/spend/export",
3152
+ querySchema: exportSpendQuerySchema,
3153
+ operationId: "purchaseExportSpendReport",
3154
+ summary: "Gasto em CSV ou Excel",
3155
+ handler: /* @__PURE__ */ __name(async (context) => {
3156
+ const query = context.query;
3157
+ const file = await reports.exportSpend({
3158
+ companyId: companyOf(context),
3159
+ query,
3160
+ format: query.format
3161
+ });
3162
+ return {
3163
+ kind: "binary",
3164
+ status: 200,
3165
+ body: typeof file.body === "string" ? new TextEncoder().encode(file.body) : file.body,
3166
+ contentType: file.contentType,
3167
+ headers: {
3168
+ "Content-Disposition": `attachment; filename="${file.fileName}"`,
3169
+ "Cache-Control": "no-store"
3170
+ }
3171
+ };
3172
+ }, "handler")
3173
+ },
3174
+ {
3175
+ ...read,
3176
+ method: "GET",
3177
+ path: "/reports/suppliers",
3178
+ querySchema: supplierPerformanceQuerySchema,
3179
+ operationId: "purchaseSupplierPerformance",
3180
+ summary: "Desempenho do fornecedor: no prazo, atraso m\xE9dio, diverg\xEAncia, total",
3181
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await reports.supplierPerformance({
3182
+ companyId: companyOf(context),
3183
+ query: context.query
3184
+ })), "handler")
3185
+ }
3186
+ ];
3187
+ }
3188
+ __name(insightRoutes, "insightRoutes");
3189
+ function serviceRoutes(module, service) {
3190
+ const { insights, suppliers: suppliers2, receipts: receipts2 } = module.useCases;
3191
+ return [
3192
+ {
3193
+ ...service,
3194
+ method: "POST",
3195
+ path: "/service/items/incoming",
3196
+ bodySchema: itemRefsLookupSchema,
3197
+ operationId: "purchaseServiceIncoming",
3198
+ summary: "A caminho por item (IncomingSupplyPort do estoque por HTTP)",
3199
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await insights.incoming({
3200
+ companyId: companyOf(context),
3201
+ itemRefs: context.body.itemRefs
3202
+ })), "handler")
3203
+ },
3204
+ {
3205
+ ...service,
3206
+ method: "POST",
3207
+ path: "/service/items/costs",
3208
+ bodySchema: itemRefsLookupSchema,
3209
+ operationId: "purchaseServiceItemCosts",
3210
+ summary: "Custo por item (para a ficha t\xE9cnica)",
3211
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await insights.itemCosts({
3212
+ companyId: companyOf(context),
3213
+ itemRefs: context.body.itemRefs
3214
+ })), "handler")
3215
+ },
3216
+ {
3217
+ ...service,
3218
+ method: "POST",
3219
+ path: "/service/suppliers/lookup",
3220
+ bodySchema: supplierLookupSchema,
3221
+ operationId: "purchaseServiceSupplierLookup",
3222
+ summary: "Fornecedores por id (SupplierDirectoryPort do estoque por HTTP)",
3223
+ handler: /* @__PURE__ */ __name(async (context) => json(200, await suppliers2.findMany({
3224
+ companyId: companyOf(context),
3225
+ ids: context.body.ids
3226
+ })), "handler")
3227
+ },
3228
+ {
3229
+ ...service,
3230
+ method: "POST",
3231
+ path: "/service/receipts/payments",
3232
+ bodySchema: paymentSchema,
3233
+ operationId: "purchaseServiceRecordPayment",
3234
+ summary: "Pagamento (ou estorno) de parcela vindo do financeiro",
3235
+ handler: /* @__PURE__ */ __name(async (context) => {
3236
+ const body = context.body;
3237
+ return json(200, await receipts2.recordPayment({
3238
+ companyId: companyOf(context),
3239
+ installmentNumber: body.installmentNumber,
3240
+ paidAmount: body.paidAmount,
3241
+ paidAt: body.paidAt,
3242
+ ...body.receiptId ? {
3243
+ receiptId: body.receiptId
3244
+ } : {},
3245
+ ...body.payableRef ? {
3246
+ payableRef: body.payableRef
3247
+ } : {}
3248
+ }));
3249
+ }, "handler")
3250
+ }
3251
+ ];
3252
+ }
3253
+ __name(serviceRoutes, "serviceRoutes");
3254
+ function createPurchaseRoutes(params) {
3255
+ const scopes = params.module.config.scopes ?? {};
3256
+ const writeScopes = [
3257
+ ...scopes.write ?? DEFAULT_PURCHASE_SCOPES.write
3258
+ ];
3259
+ const approveScopes = [
3260
+ ...scopes.approve ?? DEFAULT_PURCHASE_SCOPES.approve
3261
+ ];
3262
+ const read = {
3263
+ scope: "admin",
3264
+ requiredScopes: [
3265
+ ...scopes.read ?? DEFAULT_PURCHASE_SCOPES.read,
3266
+ ...writeScopes,
3267
+ ...approveScopes
3268
+ ]
3269
+ };
3270
+ const write = {
3271
+ scope: "admin",
3272
+ requiredScopes: writeScopes
3273
+ };
3274
+ const approve = {
3275
+ scope: "admin",
3276
+ requiredScopes: approveScopes
3277
+ };
3278
+ const service = {
3279
+ scope: "service",
3280
+ requiredScopes: [
3281
+ ...scopes.service ?? DEFAULT_PURCHASE_SCOPES.service
3282
+ ]
3283
+ };
3284
+ return [
3285
+ ...supplierRoutes(params.module, read, write),
3286
+ ...orderRoutes(params.module, read, write, approve),
3287
+ ...receiptRoutes(params.module, read, write),
3288
+ ...insightRoutes(params.module, read, write),
3289
+ ...serviceRoutes(params.module, service)
3290
+ ];
3291
+ }
3292
+ __name(createPurchaseRoutes, "createPurchaseRoutes");
3293
+
3294
+ // src/runMigrations.ts
3295
+ import { join } from "path";
3296
+ var PURCHASE_MIGRATIONS_TABLE = "purchase_migrations";
3297
+ function purchaseMigrationsFolder() {
3298
+ return join(__dirname, "migrations");
3299
+ }
3300
+ __name(purchaseMigrationsFolder, "purchaseMigrationsFolder");
3301
+ async function runPurchaseMigrations(params) {
3302
+ await params.migrate(params.db, {
3303
+ migrationsFolder: purchaseMigrationsFolder(),
3304
+ migrationsTable: PURCHASE_MIGRATIONS_TABLE
3305
+ });
3306
+ }
3307
+ __name(runPurchaseMigrations, "runPurchaseMigrations");
3308
+ export {
3309
+ PURCHASE_MIGRATIONS_TABLE,
3310
+ createPurchaseModule,
3311
+ createPurchaseRoutes,
3312
+ orderCounters,
3313
+ orderLines,
3314
+ orders,
3315
+ purchaseMigrationsFolder,
3316
+ purchaseSchema,
3317
+ receiptLineSourceKey,
3318
+ receiptLines,
3319
+ receiptPayableRef,
3320
+ receiptPayments,
3321
+ receipts,
3322
+ runPurchaseMigrations,
3323
+ supplierItems,
3324
+ suppliers
3325
+ };
3326
+ //# sourceMappingURL=index.js.map