@adatechnology/purchase-ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1662 @@
1
+ // src/providers/PurchaseProvider.tsx
2
+ import { useRecipesText } from "@adatechnology/recipes-ui";
3
+ import { createContext, useContext, useMemo } from "react";
4
+
5
+ // src/locales/en.json
6
+ var en_default = {
7
+ ordersTitle: "Purchase orders",
8
+ newOrder: "New order",
9
+ searchOrders: "Order number or supplier",
10
+ onlyLate: "Late only",
11
+ status_draft: "Draft",
12
+ status_pending_approval: "Awaiting approval",
13
+ status_approved: "Approved",
14
+ status_sent: "Sent",
15
+ status_partially_received: "Partially received",
16
+ status_received: "Received",
17
+ status_closed: "Closed",
18
+ status_canceled: "Canceled",
19
+ payment_none: "No bill",
20
+ payment_open: "To pay",
21
+ payment_partial: "Partially paid",
22
+ payment_paid: "Paid",
23
+ late: "Late",
24
+ columnNumber: "Order",
25
+ columnSupplier: "Supplier",
26
+ columnStatus: "Status",
27
+ columnExpectedAt: "Expected",
28
+ columnTotal: "Total",
29
+ columnPayment: "Payment",
30
+ columnItem: "Item",
31
+ columnQuantity: "Quantity",
32
+ columnPending: "Pending",
33
+ columnUnitPrice: "Price",
34
+ columnLineTotal: "Subtotal",
35
+ columnReceived: "Arrived",
36
+ columnBatch: "Batch",
37
+ columnExpiresAt: "Expiry",
38
+ emptyOrders: "No orders yet. Create one or use the purchase suggestion.",
39
+ loading: "Loading\u2026",
40
+ loadError: "Could not load.",
41
+ retry: "Try again",
42
+ genericError: "Something went wrong. Try again.",
43
+ close: "Close",
44
+ cancel: "Cancel",
45
+ save: "Save",
46
+ confirm: "Confirm",
47
+ orderTitle: "Order {number}",
48
+ subtotal: "Items",
49
+ freight: "Freight",
50
+ discount: "Discount",
51
+ total: "Total",
52
+ paymentTerms: "Payment terms (days)",
53
+ paymentTermsHint: "E.g. 0 upfront, 30/60/90",
54
+ notes: "Notes",
55
+ actionSubmit: "Submit for approval",
56
+ actionApprove: "Approve",
57
+ actionReject: "Reject",
58
+ actionSend: "Send to supplier",
59
+ actionReceive: "Record arrival",
60
+ actionClose: "Close short",
61
+ actionCancel: "Cancel order",
62
+ actionDuplicate: "Repeat order",
63
+ rejectReason: "Rejection reason",
64
+ cancelReason: "Cancellation reason",
65
+ closeReason: "Reason (what is missing will not come)",
66
+ reasonRequired: "Give a reason.",
67
+ approvalNeeded: "Above the limit: someone else must approve.",
68
+ rejectedBecause: "Rejected: {reason}",
69
+ canceledBecause: "Canceled: {reason}",
70
+ selfApproval: "Whoever created the order cannot approve it.",
71
+ sendTitle: "Send order",
72
+ channel_whatsapp: "WhatsApp",
73
+ channel_email: "E-mail",
74
+ channel_manual: "Copy the text",
75
+ withPrices: "Show prices in the order",
76
+ copyText: "Copy text",
77
+ copied: "Copied. Paste it in the supplier chat, then mark as sent.",
78
+ markSent: "Mark as sent",
79
+ sentVia: "Sent by {channel} on {date}",
80
+ dispatchUnavailable: "This channel is not set up. Copy the text.",
81
+ receiveTitle: "Arrival of order {number}",
82
+ receiveHint: "Check what arrived. You can receive part of it: the rest stays incoming.",
83
+ importNfe: "Import invoice XML",
84
+ nfeImported: "Invoice {number} from {issuer}: {count} items matched with the order.",
85
+ nfeNotMatched: "{count} invoice items did not match the order; check them by hand.",
86
+ nfeInvalid: "This file is not an NF-e XML.",
87
+ nfeAlreadyReceived: "This invoice was already recorded.",
88
+ invoiceNumber: "Invoice number",
89
+ invoiceKey: "Access key (44 digits)",
90
+ installments: "Installments",
91
+ installmentsHint: "Empty: from the order terms.",
92
+ installmentLine: "#{number} on {date}: {amount}",
93
+ divergenceReason: "Reason for the difference",
94
+ divergence_quantity: "Quantity differs from the order",
95
+ divergence_price: "Price differs from the order",
96
+ divergence_both: "Quantity and price differ",
97
+ nothingToReceive: "Enter the quantity of at least one item.",
98
+ invalidNumber: "Invalid number.",
99
+ invoiceTaken: "This invoice was already recorded.",
100
+ received: "Arrival recorded.",
101
+ receiptsTitle: "Arrivals",
102
+ noReceipts: "Nothing arrived yet.",
103
+ integrationFailed: "Stock or the bill were not updated.",
104
+ retryIntegration: "Try again",
105
+ stockDone: "Stock updated",
106
+ payableDone: "Bill created",
107
+ suggestionTitle: "Purchase suggestion",
108
+ suggestionHint: "What is below minimum or missing for production, minus what is already incoming.",
109
+ suggestionEmpty: "Nothing to buy now.",
110
+ noSupplier: "No supplier set",
111
+ belowMinimumOrder: "Below the supplier minimum order",
112
+ columnNeeded: "Needed",
113
+ columnOnHand: "On hand",
114
+ columnIncoming: "Incoming",
115
+ columnSuggested: "Buy",
116
+ estimated: "Estimated",
117
+ createOrders: "Create drafts for the selected",
118
+ ordersCreated: "{count} draft(s) created.",
119
+ suppliersTitle: "Suppliers",
120
+ searchSuppliers: "Name or tax id",
121
+ newSupplier: "New supplier",
122
+ editSupplier: "Edit supplier",
123
+ supplierName: "Name",
124
+ supplierDocument: "Tax id",
125
+ supplierContact: "Contact",
126
+ supplierEmail: "E-mail",
127
+ supplierPhone: "Phone",
128
+ supplierWhatsapp: "WhatsApp",
129
+ supplierLeadTime: "Lead time (days)",
130
+ supplierMinimumOrder: "Minimum order",
131
+ supplierActive: "Active",
132
+ supplierInactive: "Inactive",
133
+ documentTaken: "A supplier with this tax id already exists.",
134
+ requiredField: "Required.",
135
+ emptySuppliers: "No suppliers yet.",
136
+ edit: "Edit",
137
+ chooseSupplier: "Choose the supplier",
138
+ addLine: "Add item",
139
+ removeLine: "Remove",
140
+ itemName: "Item",
141
+ purchaseUnit: "Purchase unit",
142
+ lastPrice: "Last price: {price}",
143
+ noLines: "Add at least one item.",
144
+ orderCreated: "Order {number} created.",
145
+ reportsTitle: "Purchase reports",
146
+ periodFrom: "From",
147
+ periodTo: "To",
148
+ groupBy: "Group by",
149
+ group_supplier: "Supplier",
150
+ group_item: "Item",
151
+ group_month: "Month",
152
+ columnGroup: "Group",
153
+ columnReceipts: "Arrivals",
154
+ spendTotal: "Total purchased: {total} in {count} arrival(s)",
155
+ performanceTitle: "Supplier delivery",
156
+ columnOrders: "Orders",
157
+ columnOnTime: "On time",
158
+ columnLate: "Late",
159
+ columnAverageLate: "Average delay (days)",
160
+ columnDivergent: "Items with differences",
161
+ emptyReport: "Nothing in this period."
162
+ };
163
+
164
+ // src/locales/pt-BR.json
165
+ var pt_BR_default = {
166
+ ordersTitle: "Pedidos de compra",
167
+ newOrder: "Novo pedido",
168
+ searchOrders: "N\xFAmero do pedido ou fornecedor",
169
+ onlyLate: "S\xF3 atrasados",
170
+ status_draft: "Rascunho",
171
+ status_pending_approval: "Aguardando aprova\xE7\xE3o",
172
+ status_approved: "Aprovado",
173
+ status_sent: "Enviado",
174
+ status_partially_received: "Recebido em parte",
175
+ status_received: "Recebido",
176
+ status_closed: "Encerrado",
177
+ status_canceled: "Cancelado",
178
+ payment_none: "Sem conta",
179
+ payment_open: "A pagar",
180
+ payment_partial: "Pago em parte",
181
+ payment_paid: "Pago",
182
+ late: "Atrasado",
183
+ columnNumber: "Pedido",
184
+ columnSupplier: "Fornecedor",
185
+ columnStatus: "Situa\xE7\xE3o",
186
+ columnExpectedAt: "Previsto para",
187
+ columnTotal: "Total",
188
+ columnPayment: "Pagamento",
189
+ columnItem: "Item",
190
+ columnQuantity: "Quantidade",
191
+ columnPending: "Falta chegar",
192
+ columnUnitPrice: "Pre\xE7o",
193
+ columnLineTotal: "Subtotal",
194
+ columnReceived: "Chegou",
195
+ columnBatch: "Lote",
196
+ columnExpiresAt: "Validade",
197
+ emptyOrders: "Nenhum pedido ainda. Crie um ou use a sugest\xE3o de compra.",
198
+ loading: "Carregando\u2026",
199
+ loadError: "N\xE3o foi poss\xEDvel carregar.",
200
+ retry: "Tentar de novo",
201
+ genericError: "N\xE3o deu certo. Tente de novo.",
202
+ close: "Fechar",
203
+ cancel: "Cancelar",
204
+ save: "Salvar",
205
+ confirm: "Confirmar",
206
+ orderTitle: "Pedido {number}",
207
+ subtotal: "Itens",
208
+ freight: "Frete",
209
+ discount: "Desconto",
210
+ total: "Total",
211
+ paymentTerms: "Condi\xE7\xE3o de pagamento (dias)",
212
+ paymentTermsHint: "Ex.: 0 \xE0 vista, 30/60/90",
213
+ notes: "Observa\xE7\xF5es",
214
+ actionSubmit: "Enviar para aprova\xE7\xE3o",
215
+ actionApprove: "Aprovar",
216
+ actionReject: "Recusar",
217
+ actionSend: "Enviar ao fornecedor",
218
+ actionReceive: "Registrar chegada",
219
+ actionClose: "Encerrar com falta",
220
+ actionCancel: "Cancelar pedido",
221
+ actionDuplicate: "Repetir pedido",
222
+ rejectReason: "Motivo da recusa",
223
+ cancelReason: "Motivo do cancelamento",
224
+ closeReason: "Motivo (o que faltou n\xE3o vem mais)",
225
+ reasonRequired: "Diga o motivo.",
226
+ approvalNeeded: "Acima do limite: precisa de aprova\xE7\xE3o de outra pessoa.",
227
+ rejectedBecause: "Recusado: {reason}",
228
+ canceledBecause: "Cancelado: {reason}",
229
+ selfApproval: "Quem fez o pedido n\xE3o pode aprovar.",
230
+ sendTitle: "Enviar pedido",
231
+ channel_whatsapp: "WhatsApp",
232
+ channel_email: "E-mail",
233
+ channel_manual: "Copiar o texto",
234
+ withPrices: "Mostrar os pre\xE7os no pedido",
235
+ copyText: "Copiar texto",
236
+ copied: "Copiado. Cole na conversa com o fornecedor e depois marque como enviado.",
237
+ markSent: "Marcar como enviado",
238
+ sentVia: "Enviado por {channel} em {date}",
239
+ dispatchUnavailable: "Esse canal n\xE3o est\xE1 ligado. Copie o texto.",
240
+ receiveTitle: "Chegada do pedido {number}",
241
+ receiveHint: "Confira o que chegou. Pode receber s\xF3 uma parte: o resto continua a caminho.",
242
+ importNfe: "Importar XML da nota",
243
+ nfeImported: "Nota {number} de {issuer}: {count} itens conferidos com o pedido.",
244
+ nfeNotMatched: "{count} itens da nota n\xE3o casaram com o pedido; confira \xE0 m\xE3o.",
245
+ nfeInvalid: "Esse arquivo n\xE3o \xE9 o XML de uma NF-e.",
246
+ nfeAlreadyReceived: "Essa nota j\xE1 foi registrada.",
247
+ invoiceNumber: "N\xFAmero da nota",
248
+ invoiceKey: "Chave de acesso (44 d\xEDgitos)",
249
+ installments: "Parcelas",
250
+ installmentsHint: "Vazio: pela condi\xE7\xE3o do pedido.",
251
+ installmentLine: "{number}\xAA em {date}: {amount}",
252
+ divergenceReason: "Motivo da diferen\xE7a",
253
+ divergence_quantity: "Quantidade diferente do pedido",
254
+ divergence_price: "Pre\xE7o diferente do pedido",
255
+ divergence_both: "Quantidade e pre\xE7o diferentes",
256
+ nothingToReceive: "Informe a quantidade de ao menos um item.",
257
+ invalidNumber: "N\xFAmero inv\xE1lido.",
258
+ invoiceTaken: "Essa nota j\xE1 foi registrada.",
259
+ received: "Chegada registrada.",
260
+ receiptsTitle: "Chegadas",
261
+ noReceipts: "Nada chegou ainda.",
262
+ integrationFailed: "Estoque ou conta a pagar n\xE3o foram atualizados.",
263
+ retryIntegration: "Tentar de novo",
264
+ stockDone: "Estoque atualizado",
265
+ payableDone: "Conta a pagar lan\xE7ada",
266
+ suggestionTitle: "Sugest\xE3o de compra",
267
+ suggestionHint: "O que est\xE1 abaixo do m\xEDnimo ou falta para a produ\xE7\xE3o, j\xE1 descontado o que est\xE1 a caminho.",
268
+ suggestionEmpty: "Nada a comprar agora.",
269
+ noSupplier: "Sem fornecedor cadastrado",
270
+ belowMinimumOrder: "Abaixo do pedido m\xEDnimo do fornecedor",
271
+ columnNeeded: "Precisa",
272
+ columnOnHand: "Tem",
273
+ columnIncoming: "A caminho",
274
+ columnSuggested: "Comprar",
275
+ estimated: "Estimado",
276
+ createOrders: "Criar rascunhos dos selecionados",
277
+ ordersCreated: "{count} rascunho(s) criado(s).",
278
+ suppliersTitle: "Fornecedores",
279
+ searchSuppliers: "Nome ou CNPJ",
280
+ newSupplier: "Novo fornecedor",
281
+ editSupplier: "Editar fornecedor",
282
+ supplierName: "Nome",
283
+ supplierDocument: "CNPJ ou CPF",
284
+ supplierContact: "Contato",
285
+ supplierEmail: "E-mail",
286
+ supplierPhone: "Telefone",
287
+ supplierWhatsapp: "WhatsApp",
288
+ supplierLeadTime: "Prazo de entrega (dias)",
289
+ supplierMinimumOrder: "Pedido m\xEDnimo",
290
+ supplierActive: "Ativo",
291
+ supplierInactive: "Inativo",
292
+ documentTaken: "J\xE1 existe um fornecedor com esse documento.",
293
+ requiredField: "Obrigat\xF3rio.",
294
+ emptySuppliers: "Nenhum fornecedor ainda.",
295
+ edit: "Editar",
296
+ chooseSupplier: "Escolha o fornecedor",
297
+ addLine: "Adicionar item",
298
+ removeLine: "Remover",
299
+ itemName: "Item",
300
+ purchaseUnit: "Unidade de compra",
301
+ lastPrice: "\xDAltimo pre\xE7o: {price}",
302
+ noLines: "Adicione ao menos um item.",
303
+ orderCreated: "Pedido {number} criado.",
304
+ reportsTitle: "Relat\xF3rios de compras",
305
+ periodFrom: "De",
306
+ periodTo: "At\xE9",
307
+ groupBy: "Agrupar por",
308
+ group_supplier: "Fornecedor",
309
+ group_item: "Item",
310
+ group_month: "M\xEAs",
311
+ columnGroup: "Grupo",
312
+ columnReceipts: "Chegadas",
313
+ spendTotal: "Total comprado: {total} em {count} chegada(s)",
314
+ performanceTitle: "Entrega dos fornecedores",
315
+ columnOrders: "Pedidos",
316
+ columnOnTime: "No prazo",
317
+ columnLate: "Atrasados",
318
+ columnAverageLate: "Atraso m\xE9dio (dias)",
319
+ columnDivergent: "Itens com diferen\xE7a",
320
+ emptyReport: "Nada no per\xEDodo."
321
+ };
322
+
323
+ // src/locales/index.ts
324
+ var MESSAGES_BY_LOCALE = { "pt-BR": pt_BR_default, en: en_default };
325
+ function resolvePurchaseMessages(locale) {
326
+ return MESSAGES_BY_LOCALE[locale] ?? pt_BR_default;
327
+ }
328
+ function interpolate(message, values) {
329
+ return message.replace(/\{(\w+)\}/g, (match, key) => key in values ? String(values[key]) : match);
330
+ }
331
+
332
+ // src/providers/PurchaseProvider.tsx
333
+ import { jsx } from "react/jsx-runtime";
334
+ var PurchaseContext = createContext(null);
335
+ function PurchaseProvider({ api, messages, children }) {
336
+ const { locale } = useRecipesText();
337
+ const value = useMemo(
338
+ () => ({ api, messages: { ...resolvePurchaseMessages(locale), ...messages } }),
339
+ [api, locale, messages]
340
+ );
341
+ return /* @__PURE__ */ jsx(PurchaseContext.Provider, { value, children });
342
+ }
343
+ function usePurchaseContext() {
344
+ const value = useContext(PurchaseContext);
345
+ if (!value) throw new Error("purchase-ui: componente usado fora de <PurchaseProvider>");
346
+ return value;
347
+ }
348
+ function usePurchaseApi() {
349
+ return usePurchaseContext().api;
350
+ }
351
+ function usePurchaseText() {
352
+ const { messages } = usePurchaseContext();
353
+ const { locale, currency } = useRecipesText();
354
+ return useMemo(
355
+ () => ({ messages, locale, currency, format: (key, values) => interpolate(messages[key], values) }),
356
+ [messages, locale, currency]
357
+ );
358
+ }
359
+
360
+ // src/components/PurchaseOrdersWorkspace.tsx
361
+ import { ListToolbar, Pagination, useAsyncResource as useAsyncResource4, useDebouncedValue } from "@adatechnology/recipes-ui";
362
+ import { OPEN_ORDER_STATUSES } from "@adatechnology/purchase-contracts";
363
+ import { Plus as Plus2 } from "lucide-react";
364
+ import { useState as useState6 } from "react";
365
+
366
+ // src/lib/format.ts
367
+ import { formatMoney } from "@adatechnology/recipes-ui";
368
+ function formatCivilDate(value, locale) {
369
+ if (!value) return "\u2014";
370
+ return new Intl.DateTimeFormat(locale, { timeZone: "UTC" }).format(/* @__PURE__ */ new Date(`${value.slice(0, 10)}T12:00:00Z`));
371
+ }
372
+ function money(value, text) {
373
+ return formatMoney({ value, locale: text.locale, currency: text.currency });
374
+ }
375
+ function monthToDate(now = /* @__PURE__ */ new Date()) {
376
+ const pad = (value) => String(value).padStart(2, "0");
377
+ const year = now.getFullYear();
378
+ const month = pad(now.getMonth() + 1);
379
+ return { from: `${year}-${month}-01`, to: `${year}-${month}-${pad(now.getDate())}` };
380
+ }
381
+
382
+ // src/components/NewOrderDialog.tsx
383
+ import { Field, SelectField, fromInputDecimal, toInputDecimal, useAsyncResource } from "@adatechnology/recipes-ui";
384
+ import { Plus, Trash2 } from "lucide-react";
385
+ import { useState } from "react";
386
+ import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
387
+ var FREE_ITEM = "";
388
+ function NewOrderDialog({ supplierId: initialSupplier, onCreated, onCancel }) {
389
+ const api = usePurchaseApi();
390
+ const text = usePurchaseText();
391
+ const { messages, format, locale } = text;
392
+ const [supplierId, setSupplierId] = useState(initialSupplier ?? "");
393
+ const [lines, setLines] = useState([]);
394
+ const [expectedAt, setExpectedAt] = useState("");
395
+ const [notes, setNotes] = useState("");
396
+ const [error, setError] = useState();
397
+ const [isSaving, setIsSaving] = useState(false);
398
+ const suppliers = useAsyncResource(() => api.listSuppliers({ page: 1, pageSize: 100, isActive: true }), "suppliers");
399
+ const items = useAsyncResource(
400
+ () => supplierId && api.listSupplierItems ? api.listSupplierItems(supplierId) : Promise.resolve([]),
401
+ supplierId
402
+ );
403
+ const itemList = (items.data ?? []).filter((item) => item.isActive);
404
+ function addLine() {
405
+ const first = itemList[0];
406
+ setLines((current) => [
407
+ ...current,
408
+ {
409
+ key: Date.now() + current.length,
410
+ supplierItemId: first?.id ?? FREE_ITEM,
411
+ itemName: "",
412
+ purchaseUnit: "",
413
+ quantity: "1",
414
+ unitPrice: first?.lastPrice ? toInputDecimal({ value: first.lastPrice, locale }) : ""
415
+ }
416
+ ]);
417
+ }
418
+ function update(key, patch) {
419
+ setLines((current) => current.map((line) => line.key === key ? { ...line, ...patch } : line));
420
+ }
421
+ function chooseItem(key, supplierItemId) {
422
+ const item = itemList.find((candidate) => candidate.id === supplierItemId);
423
+ update(key, {
424
+ supplierItemId,
425
+ ...item?.lastPrice ? { unitPrice: toInputDecimal({ value: item.lastPrice, locale }) } : {}
426
+ });
427
+ }
428
+ async function handleSubmit(event) {
429
+ event.preventDefault();
430
+ if (!api.createOrder) return;
431
+ if (!supplierId) {
432
+ setError(messages.chooseSupplier);
433
+ return;
434
+ }
435
+ if (lines.length === 0) {
436
+ setError(messages.noLines);
437
+ return;
438
+ }
439
+ const input = [];
440
+ for (const line of lines) {
441
+ const quantity = fromInputDecimal(line.quantity);
442
+ const unitPrice = line.unitPrice.trim() === "" ? "" : fromInputDecimal(line.unitPrice);
443
+ if (quantity === void 0 || unitPrice === void 0) {
444
+ setError(messages.invalidNumber);
445
+ return;
446
+ }
447
+ const free = line.supplierItemId === FREE_ITEM;
448
+ if (free && (line.itemName.trim() === "" || line.purchaseUnit.trim() === "")) {
449
+ setError(messages.requiredField);
450
+ return;
451
+ }
452
+ input.push({
453
+ quantity,
454
+ ...unitPrice !== "" ? { unitPrice } : {},
455
+ ...free ? { itemName: line.itemName.trim(), purchaseUnit: line.purchaseUnit.trim() } : { supplierItemId: line.supplierItemId }
456
+ });
457
+ }
458
+ setIsSaving(true);
459
+ setError(void 0);
460
+ try {
461
+ onCreated(
462
+ await api.createOrder({
463
+ supplierId,
464
+ lines: input,
465
+ ...expectedAt ? { expectedAt } : {},
466
+ ...notes.trim() ? { notes: notes.trim() } : {}
467
+ })
468
+ );
469
+ } catch {
470
+ setError(messages.genericError);
471
+ } finally {
472
+ setIsSaving(false);
473
+ }
474
+ }
475
+ const itemOptions = [
476
+ ...itemList.map((item) => ({
477
+ id: item.id,
478
+ label: `${item.itemName} (${item.purchaseUnit})${item.lastPrice ? ` \xB7 ${format("lastPrice", { price: money(item.lastPrice, text) })}` : ""}`
479
+ })),
480
+ { id: FREE_ITEM, label: `${messages.itemName}\u2026` }
481
+ ];
482
+ return /* @__PURE__ */ jsx2("div", { className: "arc-root arc-scrim", onClick: (event) => event.target === event.currentTarget && onCancel(), children: /* @__PURE__ */ jsxs("form", { className: "arc-dialog apu-dialog apu-dialog--wide", role: "dialog", "aria-modal": "true", "aria-labelledby": "apu-new-order-title", onSubmit: handleSubmit, noValidate: true, children: [
483
+ /* @__PURE__ */ jsx2("h2", { className: "arc-title", id: "apu-new-order-title", children: messages.newOrder }),
484
+ /* @__PURE__ */ jsxs("div", { className: "arc-grid", children: [
485
+ /* @__PURE__ */ jsx2(
486
+ SelectField,
487
+ {
488
+ id: "apu-new-order-supplier",
489
+ label: messages.columnSupplier,
490
+ value: supplierId,
491
+ options: [
492
+ { id: "", label: messages.chooseSupplier },
493
+ ...(suppliers.data?.data ?? []).map((supplier) => ({ id: supplier.id, label: supplier.name }))
494
+ ],
495
+ onChange: (value) => {
496
+ setSupplierId(value);
497
+ setLines([]);
498
+ }
499
+ }
500
+ ),
501
+ /* @__PURE__ */ jsx2(Field, { id: "apu-new-order-expected", label: messages.columnExpectedAt, children: (aria) => /* @__PURE__ */ jsx2("input", { id: "apu-new-order-expected", type: "date", className: "arc-input", value: expectedAt, onChange: (event) => setExpectedAt(event.target.value), ...aria }) })
502
+ ] }),
503
+ lines.map((line, index) => /* @__PURE__ */ jsxs("div", { className: "apu-line", children: [
504
+ /* @__PURE__ */ jsx2(SelectField, { id: `apu-line-item-${line.key}`, label: `${messages.columnItem} ${index + 1}`, value: line.supplierItemId, options: itemOptions, onChange: (value) => chooseItem(line.key, value) }),
505
+ line.supplierItemId === FREE_ITEM ? /* @__PURE__ */ jsxs(Fragment, { children: [
506
+ /* @__PURE__ */ jsx2(Field, { id: `apu-line-name-${line.key}`, label: messages.itemName, children: (aria) => /* @__PURE__ */ jsx2("input", { id: `apu-line-name-${line.key}`, className: "arc-input", maxLength: 160, value: line.itemName, onChange: (event) => update(line.key, { itemName: event.target.value }), ...aria }) }),
507
+ /* @__PURE__ */ jsx2(Field, { id: `apu-line-unit-${line.key}`, label: messages.purchaseUnit, children: (aria) => /* @__PURE__ */ jsx2("input", { id: `apu-line-unit-${line.key}`, className: "arc-input", maxLength: 20, value: line.purchaseUnit, onChange: (event) => update(line.key, { purchaseUnit: event.target.value }), ...aria }) })
508
+ ] }) : null,
509
+ /* @__PURE__ */ jsx2(Field, { id: `apu-line-qty-${line.key}`, label: messages.columnQuantity, children: (aria) => /* @__PURE__ */ jsx2("input", { id: `apu-line-qty-${line.key}`, className: "arc-input arc-number-input", inputMode: "decimal", value: line.quantity, onChange: (event) => update(line.key, { quantity: event.target.value }), ...aria }) }),
510
+ /* @__PURE__ */ jsx2(Field, { id: `apu-line-price-${line.key}`, label: messages.columnUnitPrice, children: (aria) => /* @__PURE__ */ jsx2("input", { id: `apu-line-price-${line.key}`, className: "arc-input arc-number-input", inputMode: "decimal", value: line.unitPrice, onChange: (event) => update(line.key, { unitPrice: event.target.value }), ...aria }) }),
511
+ /* @__PURE__ */ jsx2("button", { type: "button", className: "arc-button arc-button--ghost", "aria-label": `${messages.removeLine} ${index + 1}`, onClick: () => setLines((current) => current.filter((candidate) => candidate.key !== line.key)), children: /* @__PURE__ */ jsx2(Trash2, { "aria-hidden": true, size: 16 }) })
512
+ ] }, line.key)),
513
+ /* @__PURE__ */ jsxs("button", { type: "button", className: "arc-button arc-button--ghost", disabled: !supplierId, onClick: addLine, children: [
514
+ /* @__PURE__ */ jsx2(Plus, { "aria-hidden": true, size: 16 }),
515
+ " ",
516
+ messages.addLine
517
+ ] }),
518
+ /* @__PURE__ */ jsx2(Field, { id: "apu-new-order-notes", label: messages.notes, children: (aria) => /* @__PURE__ */ jsx2("textarea", { id: "apu-new-order-notes", className: "arc-input arc-textarea", maxLength: 1e3, value: notes, onChange: (event) => setNotes(event.target.value), ...aria }) }),
519
+ error ? /* @__PURE__ */ jsx2("p", { className: "arc-error", role: "alert", children: error }) : null,
520
+ /* @__PURE__ */ jsxs("div", { className: "arc-form-actions", children: [
521
+ /* @__PURE__ */ jsx2("button", { type: "button", className: "arc-button arc-button--ghost", onClick: onCancel, children: messages.cancel }),
522
+ /* @__PURE__ */ jsx2("button", { type: "submit", className: "arc-button", disabled: isSaving, children: messages.save })
523
+ ] })
524
+ ] }) });
525
+ }
526
+
527
+ // src/components/OrderStatusChip.tsx
528
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
529
+ function OrderStatusChip({ status, isLate }) {
530
+ const { messages } = usePurchaseText();
531
+ return /* @__PURE__ */ jsxs2("span", { className: "apu-status-group", children: [
532
+ /* @__PURE__ */ jsx3("span", { className: `arc-chip apu-status apu-status--${status}`, children: messages[`status_${status}`] }),
533
+ isLate ? /* @__PURE__ */ jsx3("span", { className: "arc-chip apu-status apu-status--late", children: messages.late }) : null
534
+ ] });
535
+ }
536
+
537
+ // src/components/PurchaseOrderPanel.tsx
538
+ import { formatDateTime, readErrorCode as readErrorCode3, toInputDecimal as toInputDecimal3, useAsyncResource as useAsyncResource3 } from "@adatechnology/recipes-ui";
539
+ import {
540
+ PURCHASE_ERROR_CODES as PURCHASE_ERROR_CODES3,
541
+ allowedActions
542
+ } from "@adatechnology/purchase-contracts";
543
+ import { useState as useState5 } from "react";
544
+
545
+ // src/components/ReasonDialog.tsx
546
+ import { Field as Field2 } from "@adatechnology/recipes-ui";
547
+ import { useState as useState2 } from "react";
548
+ import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
549
+ function ReasonDialog({ title, label, isRequired = true, isDanger, onConfirm, onCancel }) {
550
+ const { messages } = usePurchaseText();
551
+ const [reason, setReason] = useState2("");
552
+ const [error, setError] = useState2();
553
+ const [isSaving, setIsSaving] = useState2(false);
554
+ async function handleSubmit(event) {
555
+ event.preventDefault();
556
+ if (isRequired && reason.trim() === "") {
557
+ setError(messages.reasonRequired);
558
+ return;
559
+ }
560
+ setIsSaving(true);
561
+ try {
562
+ await onConfirm(reason.trim());
563
+ } finally {
564
+ setIsSaving(false);
565
+ }
566
+ }
567
+ return /* @__PURE__ */ jsx4("div", { className: "arc-root arc-scrim", onClick: (event) => event.target === event.currentTarget && onCancel(), children: /* @__PURE__ */ jsxs3("form", { className: "arc-dialog", role: "dialog", "aria-modal": "true", "aria-labelledby": "apu-reason-title", onSubmit: handleSubmit, noValidate: true, children: [
568
+ /* @__PURE__ */ jsx4("h2", { className: "arc-title", id: "apu-reason-title", children: title }),
569
+ /* @__PURE__ */ jsx4(Field2, { id: "apu-reason", label, ...error ? { error } : {}, children: (aria) => /* @__PURE__ */ jsx4(
570
+ "textarea",
571
+ {
572
+ id: "apu-reason",
573
+ className: "arc-input arc-textarea",
574
+ value: reason,
575
+ maxLength: 500,
576
+ onChange: (event) => {
577
+ setReason(event.target.value);
578
+ setError(void 0);
579
+ },
580
+ ...aria
581
+ }
582
+ ) }),
583
+ /* @__PURE__ */ jsxs3("div", { className: "arc-form-actions", children: [
584
+ /* @__PURE__ */ jsx4("button", { type: "button", className: "arc-button arc-button--ghost", onClick: onCancel, children: messages.cancel }),
585
+ /* @__PURE__ */ jsx4("button", { type: "submit", className: `arc-button${isDanger ? " arc-button--danger" : ""}`, disabled: isSaving, children: messages.confirm })
586
+ ] })
587
+ ] }) });
588
+ }
589
+
590
+ // src/components/ReceiveOrderForm.tsx
591
+ import { Field as Field3, fromInputDecimal as fromInputDecimal2, readErrorCode, toInputDecimal as toInputDecimal2 } from "@adatechnology/recipes-ui";
592
+ import { PURCHASE_ERROR_CODES } from "@adatechnology/purchase-contracts";
593
+ import { FileUp } from "lucide-react";
594
+ import { useMemo as useMemo2, useRef, useState as useState3 } from "react";
595
+
596
+ // src/lib/receiveDraft.ts
597
+ import { compare, parseDecimal } from "@adatechnology/recipe-contracts";
598
+ function buildReceiveRows(order) {
599
+ return order.lines.filter((line) => !isZero(line.pendingQuantity)).map((line) => ({
600
+ orderLineId: line.id,
601
+ itemName: line.itemName,
602
+ purchaseUnit: line.purchaseUnit,
603
+ orderedPrice: line.unitPrice,
604
+ pendingQuantity: line.pendingQuantity,
605
+ quantity: line.pendingQuantity,
606
+ unitPrice: line.unitPrice,
607
+ batchCode: "",
608
+ expiresAt: "",
609
+ divergenceReason: ""
610
+ }));
611
+ }
612
+ function applyNfePreview(rows, preview) {
613
+ const byLine = new Map(preview.lines.filter((line) => line.orderLineId).map((line) => [line.orderLineId, line]));
614
+ const next = rows.map((row) => {
615
+ const line = byLine.get(row.orderLineId);
616
+ if (!line) return { ...row, quantity: "" };
617
+ return {
618
+ ...row,
619
+ quantity: line.quantity,
620
+ unitPrice: line.unitPrice,
621
+ batchCode: line.batchCode ?? row.batchCode,
622
+ expiresAt: line.expiresAt ?? row.expiresAt
623
+ };
624
+ });
625
+ const matched = next.filter((row) => byLine.has(row.orderLineId)).length;
626
+ return { rows: next, matched, unmatched: preview.lines.length - matched };
627
+ }
628
+ function rowDivergence(row) {
629
+ if (row.quantity === "") return "none";
630
+ const quantity = compare(parseDecimal(row.quantity), parseDecimal(row.pendingQuantity)) !== 0;
631
+ const price = row.unitPrice !== "" && compare(parseDecimal(row.unitPrice), parseDecimal(row.orderedPrice)) !== 0;
632
+ if (quantity && price) return "both";
633
+ if (quantity) return "quantity";
634
+ return price ? "price" : "none";
635
+ }
636
+ function toReceiveInput(params) {
637
+ const lines = params.rows.filter((row) => row.quantity !== "" && !isZero(row.quantity)).map((row) => ({
638
+ orderLineId: row.orderLineId,
639
+ quantity: row.quantity,
640
+ ...row.unitPrice !== "" ? { unitPrice: row.unitPrice } : {},
641
+ ...row.batchCode.trim() !== "" ? { batchCode: row.batchCode.trim() } : {},
642
+ ...row.expiresAt !== "" ? { expiresAt: row.expiresAt } : {},
643
+ ...row.divergenceReason.trim() !== "" ? { divergenceReason: row.divergenceReason.trim() } : {}
644
+ }));
645
+ if (lines.length === 0) return null;
646
+ const { extras } = params;
647
+ return {
648
+ lines,
649
+ idempotencyKey: params.idempotencyKey,
650
+ ...extras.invoiceNumber.trim() !== "" ? { invoiceNumber: extras.invoiceNumber.trim() } : {},
651
+ ...extras.invoiceKey.trim() !== "" ? { invoiceKey: extras.invoiceKey.trim() } : {},
652
+ ...extras.freight !== "" ? { freight: extras.freight } : {},
653
+ ...extras.discount !== "" ? { discount: extras.discount } : {},
654
+ ...extras.notes.trim() !== "" ? { notes: extras.notes.trim() } : {},
655
+ ...extras.installments.length > 0 ? { installments: [...extras.installments] } : {}
656
+ };
657
+ }
658
+ function isZero(value) {
659
+ return compare(parseDecimal(value), parseDecimal("0")) === 0;
660
+ }
661
+
662
+ // src/components/ReceiveOrderForm.tsx
663
+ import { Fragment as Fragment2, jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
664
+ function newKey() {
665
+ return typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`;
666
+ }
667
+ function ReceiveOrderForm({ order, onReceived, onCancel }) {
668
+ const api = usePurchaseApi();
669
+ const text = usePurchaseText();
670
+ const { messages, format, locale } = text;
671
+ const [rows, setRows] = useState3(() => buildReceiveRows(order));
672
+ const [texts, setTexts] = useState3(() => textsOf(buildReceiveRows(order), locale));
673
+ const [invalid, setInvalid] = useState3(/* @__PURE__ */ new Set());
674
+ const [invoiceNumber, setInvoiceNumber] = useState3("");
675
+ const [invoiceKey, setInvoiceKey] = useState3("");
676
+ const [freight, setFreight] = useState3("");
677
+ const [discount, setDiscount] = useState3("");
678
+ const [notes, setNotes] = useState3("");
679
+ const [installments, setInstallments] = useState3([]);
680
+ const [info, setInfo] = useState3();
681
+ const [error, setError] = useState3();
682
+ const [isSaving, setIsSaving] = useState3(false);
683
+ const fileInput = useRef(null);
684
+ const idempotencyKey = useMemo2(newKey, []);
685
+ function textsOf(list, currentLocale) {
686
+ const next = {};
687
+ for (const row of list) {
688
+ next[`${row.orderLineId}:quantity`] = row.quantity === "" ? "" : toInputDecimal2({ value: row.quantity, locale: currentLocale });
689
+ next[`${row.orderLineId}:unitPrice`] = toInputDecimal2({ value: row.unitPrice, locale: currentLocale });
690
+ }
691
+ return next;
692
+ }
693
+ function changeNumber(row, field, text2) {
694
+ const key = `${row.orderLineId}:${field}`;
695
+ setTexts((current) => ({ ...current, [key]: text2 }));
696
+ const parsed = text2.trim() === "" ? "" : fromInputDecimal2(text2);
697
+ setInvalid((current) => {
698
+ const next = new Set(current);
699
+ if (parsed === void 0) next.add(key);
700
+ else next.delete(key);
701
+ return next;
702
+ });
703
+ if (parsed !== void 0) update(row.orderLineId, { [field]: parsed });
704
+ }
705
+ function update(orderLineId, patch) {
706
+ setRows((current) => current.map((row) => row.orderLineId === orderLineId ? { ...row, ...patch } : row));
707
+ }
708
+ async function importNfe(file) {
709
+ if (!api.previewNfe) return;
710
+ setError(void 0);
711
+ setInfo(void 0);
712
+ try {
713
+ const preview = await api.previewNfe({ xml: await file.text(), orderId: order.id });
714
+ if (preview.alreadyReceivedReceiptId) {
715
+ setError(messages.nfeAlreadyReceived);
716
+ return;
717
+ }
718
+ const applied = applyNfePreview(rows, preview);
719
+ setRows(applied.rows);
720
+ setTexts(textsOf(applied.rows, locale));
721
+ setInvalid(/* @__PURE__ */ new Set());
722
+ setInvoiceNumber(preview.number);
723
+ setInvoiceKey(preview.accessKey);
724
+ setFreight(toInputDecimal2({ value: preview.freight, locale }));
725
+ setDiscount(toInputDecimal2({ value: preview.discount, locale }));
726
+ setInstallments(preview.installments.map(({ dueDate, amount }) => ({ dueDate, amount })));
727
+ const parts = [format("nfeImported", { number: preview.number, issuer: preview.issuer.name, count: applied.matched })];
728
+ if (applied.unmatched > 0) parts.push(format("nfeNotMatched", { count: applied.unmatched }));
729
+ setInfo(parts.join(" "));
730
+ } catch (caught) {
731
+ setError(readErrorCode(caught) === PURCHASE_ERROR_CODES.NFE_INVALID ? messages.nfeInvalid : messages.genericError);
732
+ }
733
+ }
734
+ async function handleSubmit(event) {
735
+ event.preventDefault();
736
+ if (!api.receiveOrder) return;
737
+ const freightValue = freight.trim() === "" ? "" : fromInputDecimal2(freight);
738
+ const discountValue = discount.trim() === "" ? "" : fromInputDecimal2(discount);
739
+ if (invalid.size > 0 || freightValue === void 0 || discountValue === void 0) {
740
+ setError(messages.invalidNumber);
741
+ return;
742
+ }
743
+ const input = toReceiveInput({
744
+ rows,
745
+ idempotencyKey,
746
+ extras: { invoiceNumber, invoiceKey, freight: freightValue, discount: discountValue, notes, installments }
747
+ });
748
+ if (!input) {
749
+ setError(messages.nothingToReceive);
750
+ return;
751
+ }
752
+ setIsSaving(true);
753
+ setError(void 0);
754
+ try {
755
+ onReceived(await api.receiveOrder(order.id, input));
756
+ } catch (caught) {
757
+ const code = readErrorCode(caught);
758
+ setError(
759
+ code === PURCHASE_ERROR_CODES.INVOICE_ALREADY_RECEIVED ? messages.invoiceTaken : code === PURCHASE_ERROR_CODES.INSTALLMENTS_MISMATCH ? messages.installmentsHint : messages.genericError
760
+ );
761
+ } finally {
762
+ setIsSaving(false);
763
+ }
764
+ }
765
+ const numberInput = (row, field, label) => {
766
+ const key = `${row.orderLineId}:${field}`;
767
+ return /* @__PURE__ */ jsx5(
768
+ "input",
769
+ {
770
+ className: "arc-input arc-number-input",
771
+ inputMode: "decimal",
772
+ "aria-label": `${label} \xB7 ${row.itemName}`,
773
+ "aria-invalid": invalid.has(key),
774
+ value: texts[key] ?? "",
775
+ onChange: (event) => changeNumber(row, field, event.target.value)
776
+ }
777
+ );
778
+ };
779
+ return /* @__PURE__ */ jsx5("div", { className: "arc-root arc-scrim", onClick: (event) => event.target === event.currentTarget && onCancel(), children: /* @__PURE__ */ jsxs4("form", { className: "arc-dialog apu-dialog apu-dialog--wide", role: "dialog", "aria-modal": "true", "aria-labelledby": "apu-receive-title", onSubmit: handleSubmit, noValidate: true, children: [
780
+ /* @__PURE__ */ jsx5("h2", { className: "arc-title", id: "apu-receive-title", children: format("receiveTitle", { number: order.number }) }),
781
+ /* @__PURE__ */ jsx5("p", { className: "arc-hint", children: messages.receiveHint }),
782
+ api.previewNfe ? /* @__PURE__ */ jsxs4("div", { className: "arc-toolbar", children: [
783
+ /* @__PURE__ */ jsx5(
784
+ "input",
785
+ {
786
+ ref: fileInput,
787
+ type: "file",
788
+ accept: ".xml,text/xml,application/xml",
789
+ className: "arc-visually-hidden",
790
+ "aria-label": messages.importNfe,
791
+ onChange: (event) => {
792
+ const file = event.target.files?.[0];
793
+ event.target.value = "";
794
+ if (file) void importNfe(file);
795
+ }
796
+ }
797
+ ),
798
+ /* @__PURE__ */ jsxs4("button", { type: "button", className: "arc-button arc-button--ghost", onClick: () => fileInput.current?.click(), children: [
799
+ /* @__PURE__ */ jsx5(FileUp, { "aria-hidden": true, size: 16 }),
800
+ " ",
801
+ messages.importNfe
802
+ ] })
803
+ ] }) : null,
804
+ info ? /* @__PURE__ */ jsx5("p", { className: "arc-hint", role: "status", children: info }) : null,
805
+ /* @__PURE__ */ jsx5("div", { className: "arc-table-wrap", children: /* @__PURE__ */ jsxs4("table", { className: "arc-table arc-table--cards", children: [
806
+ /* @__PURE__ */ jsx5("thead", { children: /* @__PURE__ */ jsxs4("tr", { children: [
807
+ /* @__PURE__ */ jsx5("th", { scope: "col", children: messages.columnItem }),
808
+ /* @__PURE__ */ jsx5("th", { scope: "col", children: messages.columnPending }),
809
+ /* @__PURE__ */ jsx5("th", { scope: "col", children: messages.columnReceived }),
810
+ /* @__PURE__ */ jsx5("th", { scope: "col", children: messages.columnUnitPrice }),
811
+ /* @__PURE__ */ jsx5("th", { scope: "col", children: messages.columnBatch }),
812
+ /* @__PURE__ */ jsx5("th", { scope: "col", children: messages.columnExpiresAt })
813
+ ] }) }),
814
+ /* @__PURE__ */ jsx5("tbody", { children: rows.map((row) => {
815
+ const divergence = rowDivergence(row);
816
+ return /* @__PURE__ */ jsxs4("tr", { children: [
817
+ /* @__PURE__ */ jsxs4("td", { "data-label": messages.columnItem, children: [
818
+ row.itemName,
819
+ divergence !== "none" ? /* @__PURE__ */ jsxs4(Fragment2, { children: [
820
+ /* @__PURE__ */ jsx5("span", { className: "arc-chip apu-divergence", children: messages[`divergence_${divergence}`] }),
821
+ /* @__PURE__ */ jsx5(
822
+ "input",
823
+ {
824
+ className: "arc-input",
825
+ "aria-label": `${messages.divergenceReason} \xB7 ${row.itemName}`,
826
+ placeholder: messages.divergenceReason,
827
+ maxLength: 500,
828
+ value: row.divergenceReason,
829
+ onChange: (event) => update(row.orderLineId, { divergenceReason: event.target.value })
830
+ }
831
+ )
832
+ ] }) : null
833
+ ] }),
834
+ /* @__PURE__ */ jsx5("td", { "data-label": messages.columnPending, className: "arc-number", children: `${toInputDecimal2({ value: row.pendingQuantity, locale })} ${row.purchaseUnit}` }),
835
+ /* @__PURE__ */ jsx5("td", { "data-label": messages.columnReceived, children: numberInput(row, "quantity", messages.columnReceived) }),
836
+ /* @__PURE__ */ jsx5("td", { "data-label": messages.columnUnitPrice, children: numberInput(row, "unitPrice", messages.columnUnitPrice) }),
837
+ /* @__PURE__ */ jsx5("td", { "data-label": messages.columnBatch, children: /* @__PURE__ */ jsx5(
838
+ "input",
839
+ {
840
+ className: "arc-input",
841
+ "aria-label": `${messages.columnBatch} \xB7 ${row.itemName}`,
842
+ maxLength: 80,
843
+ value: row.batchCode,
844
+ onChange: (event) => update(row.orderLineId, { batchCode: event.target.value })
845
+ }
846
+ ) }),
847
+ /* @__PURE__ */ jsx5("td", { "data-label": messages.columnExpiresAt, children: /* @__PURE__ */ jsx5(
848
+ "input",
849
+ {
850
+ type: "date",
851
+ className: "arc-input",
852
+ "aria-label": `${messages.columnExpiresAt} \xB7 ${row.itemName}`,
853
+ value: row.expiresAt,
854
+ onChange: (event) => update(row.orderLineId, { expiresAt: event.target.value })
855
+ }
856
+ ) })
857
+ ] }, row.orderLineId);
858
+ }) })
859
+ ] }) }),
860
+ /* @__PURE__ */ jsxs4("div", { className: "arc-grid", children: [
861
+ /* @__PURE__ */ jsx5(Field3, { id: "apu-receive-invoice", label: messages.invoiceNumber, children: (aria) => /* @__PURE__ */ jsx5("input", { id: "apu-receive-invoice", className: "arc-input", maxLength: 20, value: invoiceNumber, onChange: (event) => setInvoiceNumber(event.target.value), ...aria }) }),
862
+ /* @__PURE__ */ jsx5(Field3, { id: "apu-receive-key", label: messages.invoiceKey, children: (aria) => /* @__PURE__ */ jsx5("input", { id: "apu-receive-key", className: "arc-input", inputMode: "numeric", maxLength: 60, value: invoiceKey, onChange: (event) => setInvoiceKey(event.target.value), ...aria }) }),
863
+ /* @__PURE__ */ jsx5(Field3, { id: "apu-receive-freight", label: messages.freight, children: (aria) => /* @__PURE__ */ jsx5("input", { id: "apu-receive-freight", className: "arc-input", inputMode: "decimal", value: freight, onChange: (event) => setFreight(event.target.value), ...aria }) }),
864
+ /* @__PURE__ */ jsx5(Field3, { id: "apu-receive-discount", label: messages.discount, children: (aria) => /* @__PURE__ */ jsx5("input", { id: "apu-receive-discount", className: "arc-input", inputMode: "decimal", value: discount, onChange: (event) => setDiscount(event.target.value), ...aria }) })
865
+ ] }),
866
+ installments.length > 0 ? /* @__PURE__ */ jsxs4("div", { children: [
867
+ /* @__PURE__ */ jsx5("h3", { className: "arc-subtitle", children: messages.installments }),
868
+ /* @__PURE__ */ jsx5("ul", { className: "apu-installments", children: installments.map((installment, index) => /* @__PURE__ */ jsx5("li", { children: format("installmentLine", {
869
+ number: index + 1,
870
+ date: formatCivilDate(installment.dueDate, locale),
871
+ amount: money(installment.amount, text)
872
+ }) }, `${installment.dueDate}:${index}`)) })
873
+ ] }) : /* @__PURE__ */ jsx5("p", { className: "arc-hint", children: messages.installmentsHint }),
874
+ /* @__PURE__ */ jsx5(Field3, { id: "apu-receive-notes", label: messages.notes, children: (aria) => /* @__PURE__ */ jsx5("textarea", { id: "apu-receive-notes", className: "arc-input arc-textarea", maxLength: 1e3, value: notes, onChange: (event) => setNotes(event.target.value), ...aria }) }),
875
+ error ? /* @__PURE__ */ jsx5("p", { className: "arc-error", role: "alert", children: error }) : null,
876
+ /* @__PURE__ */ jsxs4("div", { className: "arc-form-actions", children: [
877
+ /* @__PURE__ */ jsx5("button", { type: "button", className: "arc-button arc-button--ghost", onClick: onCancel, children: messages.cancel }),
878
+ /* @__PURE__ */ jsx5("button", { type: "submit", className: "arc-button", disabled: isSaving || !api.receiveOrder, children: messages.actionReceive })
879
+ ] })
880
+ ] }) });
881
+ }
882
+
883
+ // src/components/SendOrderDialog.tsx
884
+ import { readErrorCode as readErrorCode2, useAsyncResource as useAsyncResource2 } from "@adatechnology/recipes-ui";
885
+ import { PURCHASE_ERROR_CODES as PURCHASE_ERROR_CODES2 } from "@adatechnology/purchase-contracts";
886
+ import { Copy, Send } from "lucide-react";
887
+ import { useState as useState4 } from "react";
888
+ import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
889
+ function SendOrderDialog({ order, channels, onSent, onCancel }) {
890
+ const api = usePurchaseApi();
891
+ const { messages, format } = usePurchaseText();
892
+ const [withPrices, setWithPrices] = useState4(false);
893
+ const [feedback, setFeedback] = useState4();
894
+ const [isSending, setIsSending] = useState4(false);
895
+ const text = useAsyncResource2(
896
+ () => api.getOrderMessage ? api.getOrderMessage(order.id, { withPrices }) : Promise.resolve({ text: "" }),
897
+ `${order.id}:${withPrices}`
898
+ );
899
+ const available = channels.filter((channel) => channel !== "manual");
900
+ async function send(channel) {
901
+ if (!api.sendOrder) return;
902
+ setIsSending(true);
903
+ setFeedback(void 0);
904
+ try {
905
+ onSent(await api.sendOrder(order.id, { channel, withPrices }));
906
+ } catch (error) {
907
+ setFeedback(
908
+ readErrorCode2(error) === PURCHASE_ERROR_CODES2.DISPATCH_UNAVAILABLE ? messages.dispatchUnavailable : messages.genericError
909
+ );
910
+ } finally {
911
+ setIsSending(false);
912
+ }
913
+ }
914
+ async function copy() {
915
+ if (!text.data?.text) return;
916
+ try {
917
+ await navigator.clipboard.writeText(text.data.text);
918
+ setFeedback(messages.copied);
919
+ } catch {
920
+ setFeedback(messages.genericError);
921
+ }
922
+ }
923
+ return /* @__PURE__ */ jsx6("div", { className: "arc-root arc-scrim", onClick: (event) => event.target === event.currentTarget && onCancel(), children: /* @__PURE__ */ jsxs5("div", { className: "arc-dialog apu-dialog", role: "dialog", "aria-modal": "true", "aria-labelledby": "apu-send-title", children: [
924
+ /* @__PURE__ */ jsx6("h2", { className: "arc-title", id: "apu-send-title", children: `${messages.sendTitle} \xB7 ${format("orderTitle", { number: order.number })}` }),
925
+ /* @__PURE__ */ jsxs5("label", { className: "apu-check", children: [
926
+ /* @__PURE__ */ jsx6("input", { type: "checkbox", checked: withPrices, onChange: (event) => setWithPrices(event.target.checked) }),
927
+ messages.withPrices
928
+ ] }),
929
+ /* @__PURE__ */ jsx6("pre", { className: "apu-message", "aria-live": "polite", children: text.isLoading ? messages.loading : text.data?.text ?? "" }),
930
+ feedback ? /* @__PURE__ */ jsx6("p", { className: "arc-hint", role: "status", children: feedback }) : null,
931
+ /* @__PURE__ */ jsxs5("div", { className: "arc-form-actions", children: [
932
+ /* @__PURE__ */ jsx6("button", { type: "button", className: "arc-button arc-button--ghost", onClick: onCancel, children: messages.close }),
933
+ api.getOrderMessage ? /* @__PURE__ */ jsxs5("button", { type: "button", className: "arc-button arc-button--ghost", onClick: () => void copy(), children: [
934
+ /* @__PURE__ */ jsx6(Copy, { "aria-hidden": true, size: 16 }),
935
+ " ",
936
+ messages.copyText
937
+ ] }) : null,
938
+ api.sendOrder ? /* @__PURE__ */ jsx6("button", { type: "button", className: "arc-button arc-button--ghost", disabled: isSending, onClick: () => void send("manual"), children: messages.markSent }) : null,
939
+ api.sendOrder ? available.map((channel) => /* @__PURE__ */ jsxs5("button", { type: "button", className: "arc-button", disabled: isSending, onClick: () => void send(channel), children: [
940
+ /* @__PURE__ */ jsx6(Send, { "aria-hidden": true, size: 16 }),
941
+ " ",
942
+ messages[`channel_${channel}`]
943
+ ] }, channel)) : null
944
+ ] })
945
+ ] }) });
946
+ }
947
+
948
+ // src/components/PurchaseOrderPanel.tsx
949
+ import { Fragment as Fragment3, jsx as jsx7, jsxs as jsxs6 } from "react/jsx-runtime";
950
+ function PurchaseOrderPanel(props) {
951
+ const api = usePurchaseApi();
952
+ const text = usePurchaseText();
953
+ const { messages, format, locale } = text;
954
+ const [version, setVersion] = useState5(0);
955
+ const [modal, setModal] = useState5();
956
+ const [error, setError] = useState5();
957
+ const [isBusy, setIsBusy] = useState5(false);
958
+ const order = useAsyncResource3(() => api.getOrder(props.orderId), `${props.orderId}:${version}`);
959
+ const receipts = useAsyncResource3(
960
+ () => api.listReceipts ? api.listReceipts({ orderId: props.orderId, page: 1, pageSize: 50 }) : Promise.resolve({ data: [], pagination: { total: 0, page: 1, pageSize: 50, totalPages: 1 } }),
961
+ `${props.orderId}:${version}`
962
+ );
963
+ function changed(next) {
964
+ setModal(void 0);
965
+ setVersion((value) => value + 1);
966
+ props.onChanged?.(next);
967
+ }
968
+ async function run(action) {
969
+ setIsBusy(true);
970
+ setError(void 0);
971
+ try {
972
+ const next = await action();
973
+ if (next) changed(next);
974
+ } catch (caught) {
975
+ setError(readErrorCode3(caught) === PURCHASE_ERROR_CODES3.SELF_APPROVAL ? messages.selfApproval : messages.genericError);
976
+ } finally {
977
+ setIsBusy(false);
978
+ }
979
+ }
980
+ const data = order.data;
981
+ const actions = data ? allowedActions(data.status) : [];
982
+ const can = (action) => actions.includes(action);
983
+ const id = props.orderId;
984
+ return /* @__PURE__ */ jsx7("div", { className: "arc-root arc-scrim", onClick: (event) => event.target === event.currentTarget && props.onClose(), children: /* @__PURE__ */ jsx7("section", { className: "arc-dialog apu-dialog apu-dialog--wide", role: "dialog", "aria-modal": "true", "aria-labelledby": "apu-order-title", children: !data ? /* @__PURE__ */ jsx7("p", { className: "arc-empty", children: order.error ? messages.loadError : messages.loading }) : /* @__PURE__ */ jsxs6(Fragment3, { children: [
985
+ /* @__PURE__ */ jsxs6("header", { className: "apu-order-head", children: [
986
+ /* @__PURE__ */ jsx7("h2", { className: "arc-title", id: "apu-order-title", children: format("orderTitle", { number: data.number }) }),
987
+ /* @__PURE__ */ jsx7(OrderStatusChip, { status: data.status, isLate: data.isLate })
988
+ ] }),
989
+ /* @__PURE__ */ jsxs6("dl", { className: "apu-facts", children: [
990
+ /* @__PURE__ */ jsxs6("div", { children: [
991
+ /* @__PURE__ */ jsx7("dt", { children: messages.columnSupplier }),
992
+ /* @__PURE__ */ jsx7("dd", { children: data.supplierName ?? "\u2014" })
993
+ ] }),
994
+ /* @__PURE__ */ jsxs6("div", { children: [
995
+ /* @__PURE__ */ jsx7("dt", { children: messages.columnExpectedAt }),
996
+ /* @__PURE__ */ jsx7("dd", { children: formatCivilDate(data.expectedAt, locale) })
997
+ ] }),
998
+ /* @__PURE__ */ jsxs6("div", { children: [
999
+ /* @__PURE__ */ jsx7("dt", { children: messages.columnPayment }),
1000
+ /* @__PURE__ */ jsx7("dd", { children: messages[`payment_${data.paymentStatus}`] })
1001
+ ] })
1002
+ ] }),
1003
+ data.status === "pending_approval" ? /* @__PURE__ */ jsx7("p", { className: "arc-hint", children: messages.approvalNeeded }) : null,
1004
+ data.rejectionReason ? /* @__PURE__ */ jsx7("p", { className: "arc-hint", children: format("rejectedBecause", { reason: data.rejectionReason }) }) : null,
1005
+ data.cancelReason ? /* @__PURE__ */ jsx7("p", { className: "arc-hint", children: format("canceledBecause", { reason: data.cancelReason }) }) : null,
1006
+ data.sentAt && data.sentVia ? /* @__PURE__ */ jsx7("p", { className: "arc-hint", children: format("sentVia", { channel: messages[`channel_${data.sentVia}`], date: formatDateTime({ value: data.sentAt, locale }) }) }) : null,
1007
+ /* @__PURE__ */ jsx7("div", { className: "arc-table-wrap", children: /* @__PURE__ */ jsxs6("table", { className: "arc-table arc-table--cards", children: [
1008
+ /* @__PURE__ */ jsx7("thead", { children: /* @__PURE__ */ jsxs6("tr", { children: [
1009
+ /* @__PURE__ */ jsx7("th", { scope: "col", children: messages.columnItem }),
1010
+ /* @__PURE__ */ jsx7("th", { scope: "col", children: messages.columnQuantity }),
1011
+ /* @__PURE__ */ jsx7("th", { scope: "col", children: messages.columnPending }),
1012
+ /* @__PURE__ */ jsx7("th", { scope: "col", children: messages.columnUnitPrice }),
1013
+ /* @__PURE__ */ jsx7("th", { scope: "col", children: messages.columnLineTotal })
1014
+ ] }) }),
1015
+ /* @__PURE__ */ jsx7("tbody", { children: data.lines.map((line) => /* @__PURE__ */ jsxs6("tr", { children: [
1016
+ /* @__PURE__ */ jsx7("td", { "data-label": messages.columnItem, children: line.itemName }),
1017
+ /* @__PURE__ */ jsx7("td", { "data-label": messages.columnQuantity, className: "arc-number", children: `${toInputDecimal3({ value: line.quantity, locale })} ${line.purchaseUnit}` }),
1018
+ /* @__PURE__ */ jsx7("td", { "data-label": messages.columnPending, className: "arc-number", children: `${toInputDecimal3({ value: line.pendingQuantity, locale })} ${line.purchaseUnit}` }),
1019
+ /* @__PURE__ */ jsx7("td", { "data-label": messages.columnUnitPrice, className: "arc-number", children: money(line.unitPrice, text) }),
1020
+ /* @__PURE__ */ jsx7("td", { "data-label": messages.columnLineTotal, className: "arc-number", children: money(line.lineTotal, text) })
1021
+ ] }, line.id)) })
1022
+ ] }) }),
1023
+ /* @__PURE__ */ jsxs6("dl", { className: "apu-totals", children: [
1024
+ /* @__PURE__ */ jsxs6("div", { children: [
1025
+ /* @__PURE__ */ jsx7("dt", { children: messages.subtotal }),
1026
+ /* @__PURE__ */ jsx7("dd", { children: money(data.subtotal, text) })
1027
+ ] }),
1028
+ /* @__PURE__ */ jsxs6("div", { children: [
1029
+ /* @__PURE__ */ jsx7("dt", { children: messages.freight }),
1030
+ /* @__PURE__ */ jsx7("dd", { children: money(data.freight, text) })
1031
+ ] }),
1032
+ /* @__PURE__ */ jsxs6("div", { children: [
1033
+ /* @__PURE__ */ jsx7("dt", { children: messages.discount }),
1034
+ /* @__PURE__ */ jsx7("dd", { children: money(data.discount, text) })
1035
+ ] }),
1036
+ /* @__PURE__ */ jsxs6("div", { className: "apu-totals-total", children: [
1037
+ /* @__PURE__ */ jsx7("dt", { children: messages.total }),
1038
+ /* @__PURE__ */ jsx7("dd", { children: money(data.total, text) })
1039
+ ] })
1040
+ ] }),
1041
+ /* @__PURE__ */ jsx7(ReceiptsList, { receipts: receipts.data?.data ?? [], onRetry: api.retryReceipt ? (receiptId) => run(async () => {
1042
+ await api.retryReceipt?.(receiptId);
1043
+ return data;
1044
+ }) : void 0 }),
1045
+ error ? /* @__PURE__ */ jsx7("p", { className: "arc-error", role: "alert", children: error }) : null,
1046
+ /* @__PURE__ */ jsxs6("div", { className: "arc-form-actions apu-actions", children: [
1047
+ /* @__PURE__ */ jsx7("button", { type: "button", className: "arc-button arc-button--ghost", onClick: props.onClose, children: messages.close }),
1048
+ api.duplicateOrder ? /* @__PURE__ */ jsx7("button", { type: "button", className: "arc-button arc-button--ghost", disabled: isBusy, onClick: () => void run(async () => {
1049
+ const copy = await api.duplicateOrder(id);
1050
+ props.onDuplicated?.(copy);
1051
+ return copy;
1052
+ }), children: messages.actionDuplicate }) : null,
1053
+ can("cancel") && api.cancelOrder ? /* @__PURE__ */ jsx7("button", { type: "button", className: "arc-button arc-button--danger", disabled: isBusy, onClick: () => setModal("cancel"), children: messages.actionCancel }) : null,
1054
+ can("close") && api.closeOrder ? /* @__PURE__ */ jsx7("button", { type: "button", className: "arc-button arc-button--ghost", disabled: isBusy, onClick: () => setModal("close"), children: messages.actionClose }) : null,
1055
+ can("reject") && api.rejectOrder ? /* @__PURE__ */ jsx7("button", { type: "button", className: "arc-button arc-button--ghost", disabled: isBusy, onClick: () => setModal("reject"), children: messages.actionReject }) : null,
1056
+ can("submit") && api.submitOrder ? /* @__PURE__ */ jsx7("button", { type: "button", className: "arc-button", disabled: isBusy, onClick: () => void run(() => api.submitOrder?.(id)), children: messages.actionSubmit }) : null,
1057
+ can("approve") && api.approveOrder ? /* @__PURE__ */ jsx7("button", { type: "button", className: "arc-button", disabled: isBusy, onClick: () => void run(() => api.approveOrder?.(id)), children: messages.actionApprove }) : null,
1058
+ can("send") && (api.sendOrder || api.getOrderMessage) ? /* @__PURE__ */ jsx7("button", { type: "button", className: "arc-button", disabled: isBusy, onClick: () => setModal("send"), children: messages.actionSend }) : null,
1059
+ can("receive") && api.receiveOrder ? /* @__PURE__ */ jsx7("button", { type: "button", className: "arc-button", disabled: isBusy, onClick: () => setModal("receive"), children: messages.actionReceive }) : null
1060
+ ] }),
1061
+ modal === "send" ? /* @__PURE__ */ jsx7(SendOrderDialog, { order: data, channels: props.dispatchChannels ?? ["manual"], onSent: changed, onCancel: () => setModal(void 0) }) : null,
1062
+ modal === "receive" ? /* @__PURE__ */ jsx7(ReceiveOrderForm, { order: data, onReceived: () => changed(data), onCancel: () => setModal(void 0) }) : null,
1063
+ modal === "reject" ? /* @__PURE__ */ jsx7(ReasonDialog, { title: messages.actionReject, label: messages.rejectReason, onCancel: () => setModal(void 0), onConfirm: (reason) => run(() => api.rejectOrder?.(id, reason)) }) : null,
1064
+ modal === "cancel" ? /* @__PURE__ */ jsx7(ReasonDialog, { title: messages.actionCancel, label: messages.cancelReason, isDanger: true, onCancel: () => setModal(void 0), onConfirm: (reason) => run(() => api.cancelOrder?.(id, reason)) }) : null,
1065
+ modal === "close" ? /* @__PURE__ */ jsx7(ReasonDialog, { title: messages.actionClose, label: messages.closeReason, isRequired: false, onCancel: () => setModal(void 0), onConfirm: (reason) => run(() => api.closeOrder?.(id, reason === "" ? void 0 : reason)) }) : null
1066
+ ] }) }) });
1067
+ }
1068
+ function ReceiptsList({
1069
+ receipts,
1070
+ onRetry
1071
+ }) {
1072
+ const text = usePurchaseText();
1073
+ const { messages, locale } = text;
1074
+ return /* @__PURE__ */ jsxs6("div", { children: [
1075
+ /* @__PURE__ */ jsx7("h3", { className: "arc-subtitle", children: messages.receiptsTitle }),
1076
+ receipts.length === 0 ? /* @__PURE__ */ jsx7("p", { className: "arc-hint", children: messages.noReceipts }) : /* @__PURE__ */ jsx7("ul", { className: "apu-receipts", children: receipts.map((receipt) => {
1077
+ const failed = receipt.stockStatus === "failed" || receipt.payableStatus === "failed";
1078
+ return /* @__PURE__ */ jsxs6("li", { children: [
1079
+ /* @__PURE__ */ jsx7("span", { children: formatDateTime({ value: receipt.receivedAt, locale }) }),
1080
+ /* @__PURE__ */ jsx7("span", { children: receipt.invoiceNumber ?? "\u2014" }),
1081
+ /* @__PURE__ */ jsx7("span", { className: "arc-number", children: money(receipt.total, text) }),
1082
+ receipt.stockStatus === "done" ? /* @__PURE__ */ jsx7("span", { className: "arc-chip", children: messages.stockDone }) : null,
1083
+ receipt.payableStatus === "done" ? /* @__PURE__ */ jsx7("span", { className: "arc-chip", children: messages.payableDone }) : null,
1084
+ failed ? /* @__PURE__ */ jsxs6("span", { className: "apu-failed", children: [
1085
+ /* @__PURE__ */ jsx7("span", { className: "arc-chip apu-status--late", children: messages.integrationFailed }),
1086
+ onRetry ? /* @__PURE__ */ jsx7("button", { type: "button", className: "arc-button arc-button--ghost", onClick: () => void onRetry(receipt.id), children: messages.retryIntegration }) : null
1087
+ ] }) : null
1088
+ ] }, receipt.id);
1089
+ }) })
1090
+ ] });
1091
+ }
1092
+
1093
+ // src/components/PurchaseOrdersWorkspace.tsx
1094
+ import { Fragment as Fragment4, jsx as jsx8, jsxs as jsxs7 } from "react/jsx-runtime";
1095
+ var STATUS_FILTERS = [
1096
+ { id: "draft", statuses: ["draft"] },
1097
+ { id: "pending_approval", statuses: ["pending_approval"] },
1098
+ { id: "open", statuses: OPEN_ORDER_STATUSES },
1099
+ { id: "received", statuses: ["received", "closed"] },
1100
+ { id: "canceled", statuses: ["canceled"] }
1101
+ ];
1102
+ function PurchaseOrdersWorkspace({ dispatchChannels }) {
1103
+ const api = usePurchaseApi();
1104
+ const text = usePurchaseText();
1105
+ const { messages, locale } = text;
1106
+ const [search, setSearch] = useState6("");
1107
+ const debounced = useDebouncedValue(search, 300);
1108
+ const [statusFilter, setStatusFilter] = useState6();
1109
+ const [lateOnly, setLateOnly] = useState6(false);
1110
+ const [page, setPage] = useState6(1);
1111
+ const [pageSize, setPageSize] = useState6(20);
1112
+ const [openId, setOpenId] = useState6();
1113
+ const [isCreating, setIsCreating] = useState6(false);
1114
+ const [version, setVersion] = useState6(0);
1115
+ const statuses = STATUS_FILTERS.find((filter) => filter.id === statusFilter)?.statuses;
1116
+ const orders = useAsyncResource4(
1117
+ () => api.listOrders({
1118
+ page,
1119
+ pageSize,
1120
+ ...statuses ? { status: statuses } : {},
1121
+ ...lateOnly ? { lateOnly: true } : {},
1122
+ ...debounced.trim() !== "" ? { search: debounced.trim() } : {}
1123
+ }),
1124
+ `${page}:${pageSize}:${statusFilter}:${lateOnly}:${debounced}:${version}`
1125
+ );
1126
+ const rows = orders.data?.data ?? [];
1127
+ const reload = () => setVersion((value) => value + 1);
1128
+ const statusLabel = (id) => id === "open" ? messages.status_sent : id === "received" ? messages.status_received : messages[`status_${id}`];
1129
+ return /* @__PURE__ */ jsxs7("section", { className: "arc-root arc-workspace", "aria-labelledby": "apu-orders-title", children: [
1130
+ /* @__PURE__ */ jsx8("h1", { className: "arc-title", id: "apu-orders-title", children: messages.ordersTitle }),
1131
+ /* @__PURE__ */ jsx8(
1132
+ ListToolbar,
1133
+ {
1134
+ id: "apu-orders",
1135
+ search,
1136
+ searchPlaceholder: messages.searchOrders,
1137
+ onSearchChange: (value) => {
1138
+ setSearch(value);
1139
+ setPage(1);
1140
+ },
1141
+ total: orders.data?.pagination.total,
1142
+ hasFilters: statusFilter !== void 0 || lateOnly,
1143
+ onClearFilters: () => {
1144
+ setStatusFilter(void 0);
1145
+ setLateOnly(false);
1146
+ setPage(1);
1147
+ },
1148
+ filters: /* @__PURE__ */ jsxs7(Fragment4, { children: [
1149
+ STATUS_FILTERS.map((filter) => /* @__PURE__ */ jsx8(
1150
+ "button",
1151
+ {
1152
+ type: "button",
1153
+ className: `arc-filter-chip${statusFilter === filter.id ? " arc-filter-chip--on" : ""}`,
1154
+ "aria-pressed": statusFilter === filter.id,
1155
+ onClick: () => {
1156
+ setStatusFilter((current) => current === filter.id ? void 0 : filter.id);
1157
+ setPage(1);
1158
+ },
1159
+ children: statusLabel(filter.id)
1160
+ },
1161
+ filter.id
1162
+ )),
1163
+ /* @__PURE__ */ jsx8(
1164
+ "button",
1165
+ {
1166
+ type: "button",
1167
+ className: `arc-filter-chip${lateOnly ? " arc-filter-chip--on" : ""}`,
1168
+ "aria-pressed": lateOnly,
1169
+ onClick: () => {
1170
+ setLateOnly((value) => !value);
1171
+ setPage(1);
1172
+ },
1173
+ children: messages.onlyLate
1174
+ }
1175
+ )
1176
+ ] }),
1177
+ actions: api.createOrder ? /* @__PURE__ */ jsxs7("button", { type: "button", className: "arc-button", onClick: () => setIsCreating(true), children: [
1178
+ /* @__PURE__ */ jsx8(Plus2, { "aria-hidden": true, size: 16 }),
1179
+ " ",
1180
+ messages.newOrder
1181
+ ] }) : null
1182
+ }
1183
+ ),
1184
+ orders.error ? /* @__PURE__ */ jsxs7("div", { className: "arc-empty", role: "alert", children: [
1185
+ /* @__PURE__ */ jsx8("p", { children: messages.loadError }),
1186
+ /* @__PURE__ */ jsx8("button", { type: "button", className: "arc-button arc-button--ghost", onClick: orders.reload, children: messages.retry })
1187
+ ] }) : rows.length === 0 ? /* @__PURE__ */ jsx8("p", { className: "arc-empty", children: orders.isLoading ? messages.loading : messages.emptyOrders }) : /* @__PURE__ */ jsx8("div", { className: "arc-table-wrap", children: /* @__PURE__ */ jsxs7("table", { className: "arc-table arc-table--cards", children: [
1188
+ /* @__PURE__ */ jsx8("thead", { children: /* @__PURE__ */ jsxs7("tr", { children: [
1189
+ /* @__PURE__ */ jsx8("th", { scope: "col", children: messages.columnNumber }),
1190
+ /* @__PURE__ */ jsx8("th", { scope: "col", children: messages.columnSupplier }),
1191
+ /* @__PURE__ */ jsx8("th", { scope: "col", children: messages.columnStatus }),
1192
+ /* @__PURE__ */ jsx8("th", { scope: "col", children: messages.columnExpectedAt }),
1193
+ /* @__PURE__ */ jsx8("th", { scope: "col", children: messages.columnTotal }),
1194
+ /* @__PURE__ */ jsx8("th", { scope: "col", children: messages.columnPayment })
1195
+ ] }) }),
1196
+ /* @__PURE__ */ jsx8("tbody", { children: rows.map((order) => /* @__PURE__ */ jsxs7("tr", { children: [
1197
+ /* @__PURE__ */ jsx8("td", { "data-label": messages.columnNumber, children: /* @__PURE__ */ jsx8("button", { type: "button", className: "arc-link", onClick: () => setOpenId(order.id), children: `#${order.number}` }) }),
1198
+ /* @__PURE__ */ jsx8("td", { "data-label": messages.columnSupplier, children: order.supplierName ?? "\u2014" }),
1199
+ /* @__PURE__ */ jsx8("td", { "data-label": messages.columnStatus, children: /* @__PURE__ */ jsx8(OrderStatusChip, { status: order.status, isLate: order.isLate }) }),
1200
+ /* @__PURE__ */ jsx8("td", { "data-label": messages.columnExpectedAt, children: formatCivilDate(order.expectedAt, locale) }),
1201
+ /* @__PURE__ */ jsx8("td", { "data-label": messages.columnTotal, className: "arc-number", children: money(order.total, text) }),
1202
+ /* @__PURE__ */ jsx8("td", { "data-label": messages.columnPayment, children: messages[`payment_${order.paymentStatus}`] })
1203
+ ] }, order.id)) })
1204
+ ] }) }),
1205
+ /* @__PURE__ */ jsx8(
1206
+ Pagination,
1207
+ {
1208
+ id: "apu-orders-pagination",
1209
+ page,
1210
+ totalPages: orders.data?.pagination.totalPages ?? 1,
1211
+ pageSize,
1212
+ onPageChange: setPage,
1213
+ onPageSizeChange: (size) => {
1214
+ setPageSize(size);
1215
+ setPage(1);
1216
+ }
1217
+ }
1218
+ ),
1219
+ openId ? /* @__PURE__ */ jsx8(
1220
+ PurchaseOrderPanel,
1221
+ {
1222
+ orderId: openId,
1223
+ ...dispatchChannels ? { dispatchChannels } : {},
1224
+ onChanged: reload,
1225
+ onDuplicated: (copy) => {
1226
+ reload();
1227
+ setOpenId(copy.id);
1228
+ },
1229
+ onClose: () => setOpenId(void 0)
1230
+ }
1231
+ ) : null,
1232
+ isCreating ? /* @__PURE__ */ jsx8(
1233
+ NewOrderDialog,
1234
+ {
1235
+ onCreated: (order) => {
1236
+ setIsCreating(false);
1237
+ reload();
1238
+ setOpenId(order.id);
1239
+ },
1240
+ onCancel: () => setIsCreating(false)
1241
+ }
1242
+ ) : null
1243
+ ] });
1244
+ }
1245
+
1246
+ // src/components/PurchaseSuggestionWorkspace.tsx
1247
+ import { Feedback, toInputDecimal as toInputDecimal4, useAsyncResource as useAsyncResource5, useRecipesText as useRecipesText2 } from "@adatechnology/recipes-ui";
1248
+ import { useState as useState7 } from "react";
1249
+ import { jsx as jsx9, jsxs as jsxs8 } from "react/jsx-runtime";
1250
+ function PurchaseSuggestionWorkspace({ onOrdersCreated }) {
1251
+ const api = usePurchaseApi();
1252
+ const text = usePurchaseText();
1253
+ const { messages, format, locale } = text;
1254
+ const recipesText = useRecipesText2();
1255
+ const [version, setVersion] = useState7(0);
1256
+ const [selected, setSelected] = useState7(/* @__PURE__ */ new Set());
1257
+ const [feedback, setFeedback] = useState7();
1258
+ const [isSaving, setIsSaving] = useState7(false);
1259
+ const suggestion = useAsyncResource5(
1260
+ () => api.getSuggestion ? api.getSuggestion({}) : Promise.resolve({ groups: [], hasDemandSource: false }),
1261
+ String(version)
1262
+ );
1263
+ const groups = suggestion.data?.groups ?? [];
1264
+ const quantity = (value, unit) => value === null ? "\u2014" : `${toInputDecimal4({ value, locale })} ${unit}`;
1265
+ const unitLabel = (unit) => recipesText.messages[`unit_${unit}`] ?? unit;
1266
+ function toggle(supplierId) {
1267
+ setSelected((current) => {
1268
+ const next = new Set(current);
1269
+ if (next.has(supplierId)) next.delete(supplierId);
1270
+ else next.add(supplierId);
1271
+ return next;
1272
+ });
1273
+ }
1274
+ async function createOrders() {
1275
+ if (!api.createOrdersFromSuggestion || selected.size === 0) return;
1276
+ setIsSaving(true);
1277
+ setFeedback(void 0);
1278
+ try {
1279
+ const orders = await api.createOrdersFromSuggestion({ supplierIds: [...selected] });
1280
+ setFeedback({ kind: "success", message: format("ordersCreated", { count: orders.length }) });
1281
+ setSelected(/* @__PURE__ */ new Set());
1282
+ setVersion((value) => value + 1);
1283
+ onOrdersCreated?.(orders);
1284
+ } catch {
1285
+ setFeedback({ kind: "error", message: messages.genericError });
1286
+ } finally {
1287
+ setIsSaving(false);
1288
+ }
1289
+ }
1290
+ return /* @__PURE__ */ jsxs8("section", { className: "arc-root arc-workspace", "aria-labelledby": "apu-suggestion-title", children: [
1291
+ /* @__PURE__ */ jsx9("h1", { className: "arc-title", id: "apu-suggestion-title", children: messages.suggestionTitle }),
1292
+ /* @__PURE__ */ jsx9("p", { className: "arc-hint", children: messages.suggestionHint }),
1293
+ /* @__PURE__ */ jsx9(Feedback, { feedback }),
1294
+ suggestion.error ? /* @__PURE__ */ jsxs8("div", { className: "arc-empty", role: "alert", children: [
1295
+ /* @__PURE__ */ jsx9("p", { children: messages.loadError }),
1296
+ /* @__PURE__ */ jsx9("button", { type: "button", className: "arc-button arc-button--ghost", onClick: suggestion.reload, children: messages.retry })
1297
+ ] }) : groups.length === 0 ? /* @__PURE__ */ jsx9("p", { className: "arc-empty", children: suggestion.isLoading ? messages.loading : messages.suggestionEmpty }) : groups.map((group) => /* @__PURE__ */ jsxs8("article", { className: "apu-group", children: [
1298
+ /* @__PURE__ */ jsxs8("header", { className: "apu-group-head", children: [
1299
+ group.supplierId && api.createOrdersFromSuggestion ? /* @__PURE__ */ jsxs8("label", { className: "apu-check", children: [
1300
+ /* @__PURE__ */ jsx9("input", { type: "checkbox", checked: selected.has(group.supplierId), onChange: () => toggle(group.supplierId) }),
1301
+ /* @__PURE__ */ jsx9("span", { className: "arc-subtitle", children: group.supplierName })
1302
+ ] }) : /* @__PURE__ */ jsx9("span", { className: "arc-subtitle", children: group.supplierName ?? messages.noSupplier }),
1303
+ /* @__PURE__ */ jsx9("span", { className: "arc-number", children: `${messages.estimated}: ${money(group.estimatedTotal, text)}` }),
1304
+ group.belowMinimumOrder ? /* @__PURE__ */ jsx9("span", { className: "arc-chip apu-status--late", children: messages.belowMinimumOrder }) : null
1305
+ ] }),
1306
+ /* @__PURE__ */ jsx9("div", { className: "arc-table-wrap", children: /* @__PURE__ */ jsxs8("table", { className: "arc-table arc-table--cards", children: [
1307
+ /* @__PURE__ */ jsx9("thead", { children: /* @__PURE__ */ jsxs8("tr", { children: [
1308
+ /* @__PURE__ */ jsx9("th", { scope: "col", children: messages.columnItem }),
1309
+ /* @__PURE__ */ jsx9("th", { scope: "col", children: messages.columnNeeded }),
1310
+ /* @__PURE__ */ jsx9("th", { scope: "col", children: messages.columnOnHand }),
1311
+ /* @__PURE__ */ jsx9("th", { scope: "col", children: messages.columnIncoming }),
1312
+ /* @__PURE__ */ jsx9("th", { scope: "col", children: messages.columnSuggested }),
1313
+ /* @__PURE__ */ jsx9("th", { scope: "col", children: messages.estimated })
1314
+ ] }) }),
1315
+ /* @__PURE__ */ jsx9("tbody", { children: group.lines.map((line) => /* @__PURE__ */ jsxs8("tr", { children: [
1316
+ /* @__PURE__ */ jsx9("td", { "data-label": messages.columnItem, children: line.itemName }),
1317
+ /* @__PURE__ */ jsx9("td", { "data-label": messages.columnNeeded, className: "arc-number", children: quantity(line.shortageQuantity, unitLabel(line.stockUnit)) }),
1318
+ /* @__PURE__ */ jsx9("td", { "data-label": messages.columnOnHand, className: "arc-number", children: quantity(line.onHandQuantity, unitLabel(line.stockUnit)) }),
1319
+ /* @__PURE__ */ jsx9("td", { "data-label": messages.columnIncoming, className: "arc-number", children: quantity(line.incomingQuantity, unitLabel(line.stockUnit)) }),
1320
+ /* @__PURE__ */ jsx9("td", { "data-label": messages.columnSuggested, className: "arc-number", children: quantity(line.suggestedQuantity, line.purchaseUnit ?? "") }),
1321
+ /* @__PURE__ */ jsx9("td", { "data-label": messages.estimated, className: "arc-number", children: line.estimatedTotal ? money(line.estimatedTotal, text) : "\u2014" })
1322
+ ] }, line.itemRef)) })
1323
+ ] }) })
1324
+ ] }, group.supplierId ?? "none")),
1325
+ api.createOrdersFromSuggestion && groups.some((group) => group.supplierId) ? /* @__PURE__ */ jsx9("div", { className: "arc-form-actions", children: /* @__PURE__ */ jsx9("button", { type: "button", className: "arc-button", disabled: isSaving || selected.size === 0, onClick: () => void createOrders(), children: messages.createOrders }) }) : null
1326
+ ] });
1327
+ }
1328
+
1329
+ // src/components/PurchaseSuppliersWorkspace.tsx
1330
+ import { ListToolbar as ListToolbar2, Pagination as Pagination2, useAsyncResource as useAsyncResource6, useDebouncedValue as useDebouncedValue2 } from "@adatechnology/recipes-ui";
1331
+ import { formatPaymentTerms as formatPaymentTerms2 } from "@adatechnology/purchase-contracts";
1332
+ import { Pencil, Plus as Plus3 } from "lucide-react";
1333
+ import { useState as useState9 } from "react";
1334
+
1335
+ // src/components/PurchaseSupplierDialog.tsx
1336
+ import { Field as Field4, SelectField as SelectField2, fromInputDecimal as fromInputDecimal3, readErrorCode as readErrorCode4, toInputDecimal as toInputDecimal5 } from "@adatechnology/recipes-ui";
1337
+ import {
1338
+ PURCHASE_ERROR_CODES as PURCHASE_ERROR_CODES4,
1339
+ createSupplierSchema,
1340
+ formatPaymentTerms,
1341
+ parsePaymentTerms
1342
+ } from "@adatechnology/purchase-contracts";
1343
+ import { useState as useState8 } from "react";
1344
+ import { jsx as jsx10, jsxs as jsxs9 } from "react/jsx-runtime";
1345
+ function PurchaseSupplierDialog({ supplier, onSaved, onCancel }) {
1346
+ const api = usePurchaseApi();
1347
+ const { messages, locale } = usePurchaseText();
1348
+ const [form, setForm] = useState8(() => ({
1349
+ name: supplier?.name ?? "",
1350
+ document: supplier?.document ?? "",
1351
+ contactName: supplier?.contactName ?? "",
1352
+ email: supplier?.email ?? "",
1353
+ phone: supplier?.phone ?? "",
1354
+ whatsapp: supplier?.whatsapp ?? "",
1355
+ paymentTerms: supplier ? formatPaymentTerms(supplier.paymentTermDays) : "0",
1356
+ leadTimeDays: supplier?.leadTimeDays === null || supplier?.leadTimeDays === void 0 ? "" : String(supplier.leadTimeDays),
1357
+ minimumOrderAmount: supplier?.minimumOrderAmount ? toInputDecimal5({ value: supplier.minimumOrderAmount, locale }) : "",
1358
+ notes: supplier?.notes ?? "",
1359
+ isActive: supplier?.isActive === false ? "false" : "true"
1360
+ }));
1361
+ const [errors, setErrors] = useState8({});
1362
+ const [submitError, setSubmitError] = useState8();
1363
+ const [isSaving, setIsSaving] = useState8(false);
1364
+ function change(field, value) {
1365
+ setForm((current) => ({ ...current, [field]: value }));
1366
+ setErrors((current) => ({ ...current, [field]: void 0 }));
1367
+ }
1368
+ function build() {
1369
+ const terms = parsePaymentTerms(form.paymentTerms);
1370
+ const minimum = form.minimumOrderAmount.trim() === "" ? null : fromInputDecimal3(form.minimumOrderAmount);
1371
+ const lead = form.leadTimeDays.trim() === "" ? null : Number(form.leadTimeDays);
1372
+ const next = {};
1373
+ if (terms === null) next.paymentTerms = messages.paymentTermsHint;
1374
+ if (minimum === void 0) next.minimumOrderAmount = messages.invalidNumber;
1375
+ if (lead !== null && (!Number.isInteger(lead) || lead < 0)) next.leadTimeDays = messages.invalidNumber;
1376
+ const input = {
1377
+ name: form.name,
1378
+ document: form.document,
1379
+ contactName: form.contactName,
1380
+ email: form.email,
1381
+ phone: form.phone,
1382
+ whatsapp: form.whatsapp,
1383
+ paymentTermDays: terms ?? [],
1384
+ leadTimeDays: lead,
1385
+ minimumOrderAmount: minimum ?? null,
1386
+ notes: form.notes,
1387
+ isActive: form.isActive === "true"
1388
+ };
1389
+ const result = createSupplierSchema.safeParse(input);
1390
+ if (!result.success) {
1391
+ for (const issue of result.error.issues) {
1392
+ const field = issue.path[0];
1393
+ next[field] ??= field === "name" ? messages.requiredField : messages.invalidNumber;
1394
+ }
1395
+ }
1396
+ if (Object.keys(next).length > 0) {
1397
+ setErrors(next);
1398
+ return void 0;
1399
+ }
1400
+ return input;
1401
+ }
1402
+ async function handleSubmit(event) {
1403
+ event.preventDefault();
1404
+ const input = build();
1405
+ if (!input) return;
1406
+ setIsSaving(true);
1407
+ setSubmitError(void 0);
1408
+ try {
1409
+ const saved = supplier ? await api.updateSupplier?.(supplier.id, input) : await api.createSupplier?.(input);
1410
+ if (saved) onSaved(saved);
1411
+ } catch (error) {
1412
+ if (readErrorCode4(error) === PURCHASE_ERROR_CODES4.SUPPLIER_DOCUMENT_TAKEN) {
1413
+ setErrors((current) => ({ ...current, document: messages.documentTaken }));
1414
+ } else setSubmitError(messages.genericError);
1415
+ } finally {
1416
+ setIsSaving(false);
1417
+ }
1418
+ }
1419
+ const text = (field, label, extra) => /* @__PURE__ */ jsx10(Field4, { id: `apu-supplier-${field}`, label, ...extra.hint ? { hint: extra.hint } : {}, ...errors[field] ? { error: errors[field] } : {}, children: (aria) => /* @__PURE__ */ jsx10("input", { id: `apu-supplier-${field}`, className: "arc-input", value: form[field], maxLength: extra.maxLength, inputMode: extra.inputMode ?? "text", onChange: (event) => change(field, event.target.value), ...aria }) });
1420
+ return /* @__PURE__ */ jsx10("div", { className: "arc-root arc-scrim", onClick: (event) => event.target === event.currentTarget && onCancel(), children: /* @__PURE__ */ jsxs9("form", { className: "arc-dialog apu-dialog", role: "dialog", "aria-modal": "true", "aria-labelledby": "apu-supplier-title", onSubmit: handleSubmit, noValidate: true, children: [
1421
+ /* @__PURE__ */ jsx10("h2", { className: "arc-title", id: "apu-supplier-title", children: supplier ? messages.editSupplier : messages.newSupplier }),
1422
+ /* @__PURE__ */ jsxs9("div", { className: "arc-grid", children: [
1423
+ text("name", messages.supplierName, { maxLength: 160 }),
1424
+ text("document", messages.supplierDocument, { maxLength: 30 }),
1425
+ text("contactName", messages.supplierContact, { maxLength: 120 }),
1426
+ text("email", messages.supplierEmail, { maxLength: 254, inputMode: "email" }),
1427
+ text("phone", messages.supplierPhone, { maxLength: 30, inputMode: "tel" }),
1428
+ text("whatsapp", messages.supplierWhatsapp, { maxLength: 30, inputMode: "tel" }),
1429
+ text("paymentTerms", messages.paymentTerms, { maxLength: 60, hint: messages.paymentTermsHint }),
1430
+ text("leadTimeDays", messages.supplierLeadTime, { maxLength: 3, inputMode: "numeric" }),
1431
+ text("minimumOrderAmount", messages.supplierMinimumOrder, { maxLength: 16, inputMode: "decimal" }),
1432
+ /* @__PURE__ */ jsx10(
1433
+ SelectField2,
1434
+ {
1435
+ id: "apu-supplier-active",
1436
+ label: messages.columnStatus,
1437
+ value: form.isActive,
1438
+ options: [
1439
+ { id: "true", label: messages.supplierActive },
1440
+ { id: "false", label: messages.supplierInactive }
1441
+ ],
1442
+ onChange: (value) => change("isActive", value)
1443
+ }
1444
+ )
1445
+ ] }),
1446
+ /* @__PURE__ */ jsx10(Field4, { id: "apu-supplier-notes", label: messages.notes, children: (aria) => /* @__PURE__ */ jsx10("textarea", { id: "apu-supplier-notes", className: "arc-input arc-textarea", value: form.notes, maxLength: 1e3, onChange: (event) => change("notes", event.target.value), ...aria }) }),
1447
+ submitError ? /* @__PURE__ */ jsx10("p", { className: "arc-error", role: "alert", children: submitError }) : null,
1448
+ /* @__PURE__ */ jsxs9("div", { className: "arc-form-actions", children: [
1449
+ /* @__PURE__ */ jsx10("button", { type: "button", className: "arc-button arc-button--ghost", onClick: onCancel, children: messages.cancel }),
1450
+ /* @__PURE__ */ jsx10("button", { type: "submit", className: "arc-button", disabled: isSaving, children: messages.save })
1451
+ ] })
1452
+ ] }) });
1453
+ }
1454
+
1455
+ // src/components/PurchaseSuppliersWorkspace.tsx
1456
+ import { jsx as jsx11, jsxs as jsxs10 } from "react/jsx-runtime";
1457
+ function PurchaseSuppliersWorkspace() {
1458
+ const api = usePurchaseApi();
1459
+ const { messages } = usePurchaseText();
1460
+ const [search, setSearch] = useState9("");
1461
+ const debounced = useDebouncedValue2(search, 300);
1462
+ const [onlyActive, setOnlyActive] = useState9(true);
1463
+ const [page, setPage] = useState9(1);
1464
+ const [pageSize, setPageSize] = useState9(20);
1465
+ const [editing, setEditing] = useState9();
1466
+ const [version, setVersion] = useState9(0);
1467
+ const suppliers = useAsyncResource6(
1468
+ () => api.listSuppliers({
1469
+ page,
1470
+ pageSize,
1471
+ ...onlyActive ? { isActive: true } : {},
1472
+ ...debounced.trim() ? { search: debounced.trim() } : {}
1473
+ }),
1474
+ `${page}:${pageSize}:${onlyActive}:${debounced}:${version}`
1475
+ );
1476
+ const rows = suppliers.data?.data ?? [];
1477
+ return /* @__PURE__ */ jsxs10("section", { className: "arc-root arc-workspace", "aria-labelledby": "apu-suppliers-title", children: [
1478
+ /* @__PURE__ */ jsx11("h1", { className: "arc-title", id: "apu-suppliers-title", children: messages.suppliersTitle }),
1479
+ /* @__PURE__ */ jsx11(
1480
+ ListToolbar2,
1481
+ {
1482
+ id: "apu-suppliers",
1483
+ search,
1484
+ searchPlaceholder: messages.searchSuppliers,
1485
+ onSearchChange: (value) => {
1486
+ setSearch(value);
1487
+ setPage(1);
1488
+ },
1489
+ total: suppliers.data?.pagination.total,
1490
+ hasFilters: !onlyActive,
1491
+ onClearFilters: () => setOnlyActive(true),
1492
+ filters: /* @__PURE__ */ jsx11(
1493
+ "button",
1494
+ {
1495
+ type: "button",
1496
+ className: `arc-filter-chip${onlyActive ? " arc-filter-chip--on" : ""}`,
1497
+ "aria-pressed": onlyActive,
1498
+ onClick: () => {
1499
+ setOnlyActive((value) => !value);
1500
+ setPage(1);
1501
+ },
1502
+ children: messages.supplierActive
1503
+ }
1504
+ ),
1505
+ actions: api.createSupplier ? /* @__PURE__ */ jsxs10("button", { type: "button", className: "arc-button", onClick: () => setEditing("new"), children: [
1506
+ /* @__PURE__ */ jsx11(Plus3, { "aria-hidden": true, size: 16 }),
1507
+ " ",
1508
+ messages.newSupplier
1509
+ ] }) : null
1510
+ }
1511
+ ),
1512
+ suppliers.error ? /* @__PURE__ */ jsxs10("div", { className: "arc-empty", role: "alert", children: [
1513
+ /* @__PURE__ */ jsx11("p", { children: messages.loadError }),
1514
+ /* @__PURE__ */ jsx11("button", { type: "button", className: "arc-button arc-button--ghost", onClick: suppliers.reload, children: messages.retry })
1515
+ ] }) : rows.length === 0 ? /* @__PURE__ */ jsx11("p", { className: "arc-empty", children: suppliers.isLoading ? messages.loading : messages.emptySuppliers }) : /* @__PURE__ */ jsx11("div", { className: "arc-table-wrap", children: /* @__PURE__ */ jsxs10("table", { className: "arc-table arc-table--cards", children: [
1516
+ /* @__PURE__ */ jsx11("thead", { children: /* @__PURE__ */ jsxs10("tr", { children: [
1517
+ /* @__PURE__ */ jsx11("th", { scope: "col", children: messages.supplierName }),
1518
+ /* @__PURE__ */ jsx11("th", { scope: "col", children: messages.supplierDocument }),
1519
+ /* @__PURE__ */ jsx11("th", { scope: "col", children: messages.supplierWhatsapp }),
1520
+ /* @__PURE__ */ jsx11("th", { scope: "col", children: messages.paymentTerms }),
1521
+ /* @__PURE__ */ jsx11("th", { scope: "col", children: messages.supplierLeadTime }),
1522
+ /* @__PURE__ */ jsx11("th", { scope: "col", children: messages.columnStatus }),
1523
+ /* @__PURE__ */ jsx11("th", { scope: "col", children: /* @__PURE__ */ jsx11("span", { className: "arc-visually-hidden", children: messages.edit }) })
1524
+ ] }) }),
1525
+ /* @__PURE__ */ jsx11("tbody", { children: rows.map((supplier) => /* @__PURE__ */ jsxs10("tr", { children: [
1526
+ /* @__PURE__ */ jsx11("td", { "data-label": messages.supplierName, children: supplier.name }),
1527
+ /* @__PURE__ */ jsx11("td", { "data-label": messages.supplierDocument, children: supplier.document ?? "\u2014" }),
1528
+ /* @__PURE__ */ jsx11("td", { "data-label": messages.supplierWhatsapp, children: supplier.whatsapp ?? "\u2014" }),
1529
+ /* @__PURE__ */ jsx11("td", { "data-label": messages.paymentTerms, children: formatPaymentTerms2(supplier.paymentTermDays) }),
1530
+ /* @__PURE__ */ jsx11("td", { "data-label": messages.supplierLeadTime, className: "arc-number", children: supplier.leadTimeDays ?? "\u2014" }),
1531
+ /* @__PURE__ */ jsx11("td", { "data-label": messages.columnStatus, children: supplier.isActive ? messages.supplierActive : messages.supplierInactive }),
1532
+ /* @__PURE__ */ jsx11("td", { children: api.updateSupplier ? /* @__PURE__ */ jsx11("button", { type: "button", className: "arc-button arc-button--ghost", "aria-label": `${messages.edit} ${supplier.name}`, onClick: () => setEditing(supplier), children: /* @__PURE__ */ jsx11(Pencil, { "aria-hidden": true, size: 16 }) }) : null })
1533
+ ] }, supplier.id)) })
1534
+ ] }) }),
1535
+ /* @__PURE__ */ jsx11(
1536
+ Pagination2,
1537
+ {
1538
+ id: "apu-suppliers-pagination",
1539
+ page,
1540
+ totalPages: suppliers.data?.pagination.totalPages ?? 1,
1541
+ pageSize,
1542
+ onPageChange: setPage,
1543
+ onPageSizeChange: (size) => {
1544
+ setPageSize(size);
1545
+ setPage(1);
1546
+ }
1547
+ }
1548
+ ),
1549
+ editing ? /* @__PURE__ */ jsx11(
1550
+ PurchaseSupplierDialog,
1551
+ {
1552
+ ...editing === "new" ? {} : { supplier: editing },
1553
+ onSaved: () => {
1554
+ setEditing(void 0);
1555
+ setVersion((value) => value + 1);
1556
+ },
1557
+ onCancel: () => setEditing(void 0)
1558
+ }
1559
+ ) : null
1560
+ ] });
1561
+ }
1562
+
1563
+ // src/components/PurchaseReportsWorkspace.tsx
1564
+ import { Field as Field5, SelectField as SelectField3, useAsyncResource as useAsyncResource7 } from "@adatechnology/recipes-ui";
1565
+ import { REPORT_GROUPS } from "@adatechnology/purchase-contracts";
1566
+ import { useState as useState10 } from "react";
1567
+ import { Fragment as Fragment5, jsx as jsx12, jsxs as jsxs11 } from "react/jsx-runtime";
1568
+ function PurchaseReportsWorkspace() {
1569
+ const api = usePurchaseApi();
1570
+ const text = usePurchaseText();
1571
+ const { messages, format } = text;
1572
+ const [period, setPeriod] = useState10(() => monthToDate());
1573
+ const [groupBy, setGroupBy] = useState10("supplier");
1574
+ const valid = period.from !== "" && period.to !== "" && period.from <= period.to;
1575
+ const spend = useAsyncResource7(
1576
+ () => api.getSpendReport && valid ? api.getSpendReport({ ...period, groupBy }) : Promise.resolve(void 0),
1577
+ `${period.from}:${period.to}:${groupBy}`
1578
+ );
1579
+ const performance = useAsyncResource7(
1580
+ () => api.getSupplierPerformance && valid ? api.getSupplierPerformance(period) : Promise.resolve(void 0),
1581
+ `${period.from}:${period.to}`
1582
+ );
1583
+ return /* @__PURE__ */ jsxs11("section", { className: "arc-root arc-workspace", "aria-labelledby": "apu-reports-title", children: [
1584
+ /* @__PURE__ */ jsx12("h1", { className: "arc-title", id: "apu-reports-title", children: messages.reportsTitle }),
1585
+ /* @__PURE__ */ jsxs11("div", { className: "arc-grid", children: [
1586
+ /* @__PURE__ */ jsx12(Field5, { id: "apu-report-from", label: messages.periodFrom, children: (aria) => /* @__PURE__ */ jsx12("input", { id: "apu-report-from", type: "date", className: "arc-input", value: period.from, onChange: (event) => setPeriod((current) => ({ ...current, from: event.target.value })), ...aria }) }),
1587
+ /* @__PURE__ */ jsx12(Field5, { id: "apu-report-to", label: messages.periodTo, children: (aria) => /* @__PURE__ */ jsx12("input", { id: "apu-report-to", type: "date", className: "arc-input", value: period.to, onChange: (event) => setPeriod((current) => ({ ...current, to: event.target.value })), ...aria }) }),
1588
+ /* @__PURE__ */ jsx12(
1589
+ SelectField3,
1590
+ {
1591
+ id: "apu-report-group",
1592
+ label: messages.groupBy,
1593
+ value: groupBy,
1594
+ options: REPORT_GROUPS.map((group) => ({ id: group, label: messages[`group_${group}`] })),
1595
+ onChange: (value) => setGroupBy(value)
1596
+ }
1597
+ )
1598
+ ] }),
1599
+ api.getSpendReport ? spend.error ? /* @__PURE__ */ jsx12("p", { className: "arc-empty", role: "alert", children: messages.loadError }) : !spend.data || spend.data.rows.length === 0 ? /* @__PURE__ */ jsx12("p", { className: "arc-empty", children: spend.isLoading ? messages.loading : messages.emptyReport }) : /* @__PURE__ */ jsxs11(Fragment5, { children: [
1600
+ /* @__PURE__ */ jsx12("p", { className: "arc-total", children: format("spendTotal", { total: money(spend.data.total, text), count: spend.data.receiptCount }) }),
1601
+ /* @__PURE__ */ jsx12("div", { className: "arc-table-wrap", children: /* @__PURE__ */ jsxs11("table", { className: "arc-table arc-table--cards", children: [
1602
+ /* @__PURE__ */ jsx12("thead", { children: /* @__PURE__ */ jsxs11("tr", { children: [
1603
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages[`group_${groupBy}`] }),
1604
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages.columnReceipts }),
1605
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages.columnTotal })
1606
+ ] }) }),
1607
+ /* @__PURE__ */ jsx12("tbody", { children: spend.data.rows.map((row) => /* @__PURE__ */ jsxs11("tr", { children: [
1608
+ /* @__PURE__ */ jsx12("td", { "data-label": messages[`group_${groupBy}`], children: row.label }),
1609
+ /* @__PURE__ */ jsx12("td", { "data-label": messages.columnReceipts, className: "arc-number", children: row.receiptCount }),
1610
+ /* @__PURE__ */ jsx12("td", { "data-label": messages.columnTotal, className: "arc-number", children: money(row.total, text) })
1611
+ ] }, row.key)) })
1612
+ ] }) })
1613
+ ] }) : null,
1614
+ api.getSupplierPerformance ? /* @__PURE__ */ jsxs11(Fragment5, { children: [
1615
+ /* @__PURE__ */ jsx12("h2", { className: "arc-subtitle", children: messages.performanceTitle }),
1616
+ !performance.data || performance.data.rows.length === 0 ? /* @__PURE__ */ jsx12("p", { className: "arc-empty", children: performance.isLoading ? messages.loading : messages.emptyReport }) : /* @__PURE__ */ jsx12("div", { className: "arc-table-wrap", children: /* @__PURE__ */ jsxs11("table", { className: "arc-table arc-table--cards", children: [
1617
+ /* @__PURE__ */ jsx12("thead", { children: /* @__PURE__ */ jsxs11("tr", { children: [
1618
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages.columnSupplier }),
1619
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages.columnOrders }),
1620
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages.columnOnTime }),
1621
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages.columnLate }),
1622
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages.columnAverageLate }),
1623
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages.columnDivergent }),
1624
+ /* @__PURE__ */ jsx12("th", { scope: "col", children: messages.columnTotal })
1625
+ ] }) }),
1626
+ /* @__PURE__ */ jsx12("tbody", { children: performance.data.rows.map((row) => /* @__PURE__ */ jsxs11("tr", { children: [
1627
+ /* @__PURE__ */ jsx12("td", { "data-label": messages.columnSupplier, children: row.supplierName }),
1628
+ /* @__PURE__ */ jsx12("td", { "data-label": messages.columnOrders, className: "arc-number", children: row.orderCount }),
1629
+ /* @__PURE__ */ jsx12("td", { "data-label": messages.columnOnTime, className: "arc-number", children: row.onTimeCount }),
1630
+ /* @__PURE__ */ jsx12("td", { "data-label": messages.columnLate, className: "arc-number", children: row.lateCount }),
1631
+ /* @__PURE__ */ jsx12("td", { "data-label": messages.columnAverageLate, className: "arc-number", children: row.averageDaysLate ?? "\u2014" }),
1632
+ /* @__PURE__ */ jsx12("td", { "data-label": messages.columnDivergent, className: "arc-number", children: `${row.divergentLineCount}/${row.receivedLineCount}` }),
1633
+ /* @__PURE__ */ jsx12("td", { "data-label": messages.columnTotal, className: "arc-number", children: money(row.total, text) })
1634
+ ] }, row.supplierId)) })
1635
+ ] }) })
1636
+ ] }) : null
1637
+ ] });
1638
+ }
1639
+ export {
1640
+ NewOrderDialog,
1641
+ OrderStatusChip,
1642
+ PurchaseOrderPanel,
1643
+ PurchaseOrdersWorkspace,
1644
+ PurchaseProvider,
1645
+ PurchaseReportsWorkspace,
1646
+ PurchaseSuggestionWorkspace,
1647
+ PurchaseSupplierDialog,
1648
+ PurchaseSuppliersWorkspace,
1649
+ ReasonDialog,
1650
+ ReceiveOrderForm,
1651
+ SendOrderDialog,
1652
+ applyNfePreview,
1653
+ buildReceiveRows,
1654
+ formatCivilDate,
1655
+ monthToDate,
1656
+ resolvePurchaseMessages,
1657
+ rowDivergence,
1658
+ toReceiveInput,
1659
+ usePurchaseApi,
1660
+ usePurchaseText
1661
+ };
1662
+ //# sourceMappingURL=index.js.map