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