@fayz-ai/plugin-fiscal-br 0.13.6 → 0.14.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/InvoiceNotesButton-SC3G7FUR.js +5 -0
- package/dist/{InvoiceNotesButton-3SMNHWMQ.js.map → InvoiceNotesButton-SC3G7FUR.js.map} +1 -1
- package/dist/OrderNoteCard-PDSK2AS3.js +5 -0
- package/dist/{OrderNoteCard-H6P66R4J.js.map → OrderNoteCard-PDSK2AS3.js.map} +1 -1
- package/dist/{UnitFiscalWidgets-KCHSISBS.js → UnitFiscalWidgets-K4PX3HWG.js} +3 -3
- package/dist/{UnitFiscalWidgets-KCHSISBS.js.map → UnitFiscalWidgets-K4PX3HWG.js.map} +1 -1
- package/dist/{chunk-WID54RUV.js → chunk-F325US5P.js} +4 -115
- package/dist/chunk-F325US5P.js.map +1 -0
- package/dist/chunk-ODMEESFD.js +222 -0
- package/dist/chunk-ODMEESFD.js.map +1 -0
- package/dist/{chunk-G7T5YMNY.js → chunk-SSPDH22E.js} +78 -41
- package/dist/chunk-SSPDH22E.js.map +1 -0
- package/dist/{chunk-7NW3EBOQ.js → chunk-ZJGXUJKM.js} +5 -3
- package/dist/chunk-ZJGXUJKM.js.map +1 -0
- package/dist/index.js +41 -10
- package/dist/index.js.map +1 -1
- package/dist/lib/emitters.d.ts +7 -0
- package/dist/lib/emitters.d.ts.map +1 -1
- package/dist/lib/notes.d.ts +19 -3
- package/dist/lib/notes.d.ts.map +1 -1
- package/dist/migrations/index.d.ts +1 -0
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/migrations/main.browser.js +2 -1
- package/dist/migrations/main.browser.js.map +1 -1
- package/dist/migrations/main.js +240 -2
- package/dist/migrations/main.js.map +1 -1
- package/dist/views/OrderNoteCard.d.ts.map +1 -1
- package/package.json +5 -5
- package/dist/InvoiceNotesButton-3SMNHWMQ.js +0 -5
- package/dist/OrderNoteCard-H6P66R4J.js +0 -5
- package/dist/chunk-7NW3EBOQ.js.map +0 -1
- package/dist/chunk-G7T5YMNY.js.map +0 -1
- package/dist/chunk-RZT2BO6E.js +0 -64
- package/dist/chunk-RZT2BO6E.js.map +0 -1
- package/dist/chunk-WID54RUV.js.map +0 -1
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { EmitterError, requestFile, request } from './chunk-2GHTB3Z2.js';
|
|
2
|
+
import { tl } from '@fayz-ai/core';
|
|
3
|
+
|
|
4
|
+
var CANCEL_MIN_JUSTIFICATION = 15;
|
|
5
|
+
var SENTENCES = {
|
|
6
|
+
no_client: "O servi\xE7o de integra\xE7\xF5es n\xE3o est\xE1 configurado neste app.",
|
|
7
|
+
not_configured: "A emiss\xE3o fiscal ainda n\xE3o est\xE1 ligada no servidor.",
|
|
8
|
+
unauthorized: "Sua sess\xE3o expirou. Entre de novo.",
|
|
9
|
+
not_allowed: "Seu acesso n\xE3o permite emitir ou cancelar notas.",
|
|
10
|
+
unavailable: "N\xE3o foi poss\xEDvel falar com o servi\xE7o fiscal. Tente de novo em instantes.",
|
|
11
|
+
unknown_order: "Este pedido n\xE3o foi encontrado.",
|
|
12
|
+
unknown_note: "Esta nota n\xE3o foi encontrada.",
|
|
13
|
+
not_a_sale: "S\xF3 uma venda recebe nota fiscal.",
|
|
14
|
+
order_not_closed: "Este pedido ainda n\xE3o pode receber nota.",
|
|
15
|
+
no_emitter: "A unidade deste pedido n\xE3o tem empresa (CNPJ) cadastrada para emitir.",
|
|
16
|
+
emitter_not_owned: "Esta empresa ainda emite pelo sistema anterior. Configure em Integra\xE7\xF5es \u2192 PlugNotas.",
|
|
17
|
+
emitter_not_ready: "Falta configurar a empresa para emitir esta nota (Integra\xE7\xF5es \u2192 PlugNotas).",
|
|
18
|
+
interstate: "Este pedido vai para outro estado: n\xE3o cabe NFC-e, e NF-e interestadual ainda n\xE3o \xE9 emitida por aqui.",
|
|
19
|
+
no_series: "A empresa n\xE3o tem s\xE9rie de NFC-e configurada.",
|
|
20
|
+
no_items: "O pedido n\xE3o tem produtos para a nota.",
|
|
21
|
+
products_without_ncm: "H\xE1 produtos sem cadastro fiscal (NCM).",
|
|
22
|
+
icms_code_mismatch: "H\xE1 produtos com c\xF3digo de ICMS que n\xE3o combina com o regime da empresa.",
|
|
23
|
+
not_paid: "O pedido n\xE3o tem pagamento recebido para a nota.",
|
|
24
|
+
totals_differ: "Os itens e os pagamentos do pedido n\xE3o fecham no mesmo total.",
|
|
25
|
+
invalid_text: "Um produto tem um nome que a SEFAZ n\xE3o aceita (s\xF3 emojis ou caracteres especiais).",
|
|
26
|
+
note_exists: "Este pedido j\xE1 tem uma nota emitida ou em processamento. Para trocar de modelo, cancele a nota atual primeiro.",
|
|
27
|
+
not_authorized: "S\xF3 uma nota autorizada pode ser cancelada ou baixada.",
|
|
28
|
+
justification_too_short: `A justificativa precisa ter pelo menos ${CANCEL_MIN_JUSTIFICATION} caracteres.`,
|
|
29
|
+
cancel_deadline_passed: "O prazo de cancelamento desta nota j\xE1 passou.",
|
|
30
|
+
cancel_refused: "A SEFAZ recusou o cancelamento.",
|
|
31
|
+
plugnotas_refused: "A PlugNotas recusou o envio.",
|
|
32
|
+
marketplace_intermediary: "Pedidos de marketplace (iFood, 99Food, Keeta) ainda n\xE3o emitem NFC-e por aqui.",
|
|
33
|
+
not_ours: "Esta nota foi emitida pelo sistema anterior; cancele por l\xE1."
|
|
34
|
+
};
|
|
35
|
+
var NFE_SENTENCES = {
|
|
36
|
+
nfe_needs_company: () => tl(
|
|
37
|
+
"NF-e is for a sale to a company: this order's customer has no CNPJ.",
|
|
38
|
+
"A NF-e \xE9 para venda a empresa: o cliente deste pedido n\xE3o tem CNPJ."
|
|
39
|
+
),
|
|
40
|
+
nfe_not_enabled: () => tl(
|
|
41
|
+
"The company does not issue NF-e yet. Turn it on and choose its series in Integrations \u2192 PlugNotas.",
|
|
42
|
+
"A empresa ainda n\xE3o emite NF-e. Ative e escolha a s\xE9rie em Integra\xE7\xF5es \u2192 PlugNotas."
|
|
43
|
+
),
|
|
44
|
+
nfe_not_set_up: () => tl(
|
|
45
|
+
"NF-e issuing is not set up for this company yet (Integrations \u2192 PlugNotas: NF-e series).",
|
|
46
|
+
"A emiss\xE3o de NF-e por aqui ainda n\xE3o foi configurada para esta empresa (Integra\xE7\xF5es \u2192 PlugNotas: s\xE9rie da NF-e)."
|
|
47
|
+
),
|
|
48
|
+
no_nfe_series: () => tl("The company has no NF-e series set.", "A empresa n\xE3o tem s\xE9rie de NF-e configurada."),
|
|
49
|
+
recipient_no_name: () => tl("The customer's record has no legal name.", "O cadastro do cliente n\xE3o tem raz\xE3o social."),
|
|
50
|
+
recipient_state_registration_unknown: () => tl(
|
|
51
|
+
"The customer's state registration (IE) is not recorded: enter the number, ISENTO or N\xC3O CONTRIBUINTE on the customer's record.",
|
|
52
|
+
"A inscri\xE7\xE3o estadual do cliente n\xE3o est\xE1 cadastrada: informe o n\xFAmero, ISENTO ou N\xC3O CONTRIBUINTE no cadastro do cliente."
|
|
53
|
+
),
|
|
54
|
+
recipient_address_incomplete: () => tl("The customer's address is incomplete", "O endere\xE7o do cliente est\xE1 incompleto"),
|
|
55
|
+
nfe_interstate: () => tl(
|
|
56
|
+
"The customer is in another state: interstate NF-e is not issued here yet.",
|
|
57
|
+
"O cliente \xE9 de outro estado: NF-e interestadual ainda n\xE3o \xE9 emitida por aqui."
|
|
58
|
+
)
|
|
59
|
+
};
|
|
60
|
+
var ADDRESS_PART = {
|
|
61
|
+
street: () => tl("street", "rua"),
|
|
62
|
+
city: () => tl("city", "cidade"),
|
|
63
|
+
state: () => tl("state", "UF"),
|
|
64
|
+
"postal code": () => tl("postal code", "CEP"),
|
|
65
|
+
"IBGE city code": () => tl("city code (IBGE), not found for this postal code", "c\xF3digo do munic\xEDpio (IBGE), n\xE3o encontrado pelo CEP")
|
|
66
|
+
};
|
|
67
|
+
function refusalSentence(code, message) {
|
|
68
|
+
const nfe = NFE_SENTENCES[code];
|
|
69
|
+
if (nfe) {
|
|
70
|
+
if (code !== "recipient_address_incomplete") return nfe();
|
|
71
|
+
const parts = (message.split("missing ")[1] ?? "").split(", ").map((p) => ADDRESS_PART[p.trim()]?.() ?? p.trim()).filter(Boolean);
|
|
72
|
+
return parts.length ? `${nfe()}: ${tl("missing", "falta")} ${parts.join(", ")}.` : `${nfe()}.`;
|
|
73
|
+
}
|
|
74
|
+
const base = SENTENCES[code] ?? message;
|
|
75
|
+
return code === "products_without_ncm" || code === "icms_code_mismatch" ? `${base} ${message.split(": ").slice(1).join(": ")}`.trim() : base;
|
|
76
|
+
}
|
|
77
|
+
function noteErrorSentence(error) {
|
|
78
|
+
if (error instanceof EmitterError) return refusalSentence(error.code, error.message);
|
|
79
|
+
return error instanceof Error ? error.message : String(error);
|
|
80
|
+
}
|
|
81
|
+
function optionSentence(option) {
|
|
82
|
+
if (!option || option.available) return null;
|
|
83
|
+
return refusalSentence(option.reason ?? "unavailable", option.message ?? "");
|
|
84
|
+
}
|
|
85
|
+
var order = (orderId) => `/v1/fiscal/orders/${encodeURIComponent(orderId)}/notes`;
|
|
86
|
+
var one = (documentId, rest = "") => `/v1/fiscal/notes/${encodeURIComponent(documentId)}${rest}`;
|
|
87
|
+
var orderNotes = {
|
|
88
|
+
/** The order's notes, newest first, and which models the service would issue on it. */
|
|
89
|
+
list: async (orderId) => {
|
|
90
|
+
const r = await request("GET", order(orderId));
|
|
91
|
+
return { notes: r.notes, options: r.options ?? null };
|
|
92
|
+
},
|
|
93
|
+
issue: (orderId, model) => request("POST", order(orderId), { model }),
|
|
94
|
+
/** Reads PlugNotas again while the note is processing. */
|
|
95
|
+
read: (documentId) => request("GET", one(documentId)),
|
|
96
|
+
cancel: (documentId, justification) => request("PUT", one(documentId, "/cancellation"), { justification }),
|
|
97
|
+
pdf: (documentId) => requestFile(one(documentId, "/pdf")),
|
|
98
|
+
xml: (documentId) => requestFile(one(documentId, "/xml"))
|
|
99
|
+
};
|
|
100
|
+
var NOTE_STATUS_LABEL = {
|
|
101
|
+
processing: "Processando",
|
|
102
|
+
authorized: "Autorizada",
|
|
103
|
+
rejected: "Rejeitada",
|
|
104
|
+
error: "Erro",
|
|
105
|
+
cancelled: "Cancelada",
|
|
106
|
+
substituted: "Substitu\xEDda"
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
// src/lib/issued-note.ts
|
|
110
|
+
var MODEL_LABEL = { nfse: "NFS-e", nfce: "NFC-e", nfe: "NF-e" };
|
|
111
|
+
var STATUS_META = {
|
|
112
|
+
authorized: { label: "Autorizada", tone: "success" },
|
|
113
|
+
draft: { label: "Enviando", tone: "warning" },
|
|
114
|
+
processing: { label: "Processando", tone: "warning" },
|
|
115
|
+
rejected: { label: "Rejeitada", tone: "danger" },
|
|
116
|
+
denied: { label: "Denegada", tone: "danger" },
|
|
117
|
+
error: { label: "Erro", tone: "danger" },
|
|
118
|
+
cancelled: { label: "Cancelada", tone: "muted" },
|
|
119
|
+
substituted: { label: "Substitu\xEDda", tone: "muted" }
|
|
120
|
+
};
|
|
121
|
+
var EVENT_LABEL = {
|
|
122
|
+
emissao: "Emiss\xE3o enviada",
|
|
123
|
+
consulta: "Consulta de status",
|
|
124
|
+
cancelamento: "Cancelamento",
|
|
125
|
+
substituicao: "Substitui\xE7\xE3o",
|
|
126
|
+
cce: "Carta de corre\xE7\xE3o",
|
|
127
|
+
inutilizacao: "Inutiliza\xE7\xE3o",
|
|
128
|
+
webhook: "Notifica\xE7\xE3o do emissor fiscal",
|
|
129
|
+
erro: "Erro"
|
|
130
|
+
};
|
|
131
|
+
var EVENT_STATUS_LABEL = {
|
|
132
|
+
CRIADO: "Enviando",
|
|
133
|
+
PROCESSANDO: "Processando",
|
|
134
|
+
CONCLUIDO: "Autorizada",
|
|
135
|
+
REJEITADO: "Rejeitada",
|
|
136
|
+
DENEGADO: "Denegada",
|
|
137
|
+
CANCELADO: "Cancelada",
|
|
138
|
+
SUBSTITUIDO: "Substitu\xEDda",
|
|
139
|
+
SOLICITADO: "Solicitado",
|
|
140
|
+
ERRO: "Erro"
|
|
141
|
+
};
|
|
142
|
+
function eventStatusLabel(status) {
|
|
143
|
+
return status ? EVENT_STATUS_LABEL[status.toUpperCase()] ?? null : null;
|
|
144
|
+
}
|
|
145
|
+
var IN_FLIGHT = ["draft", "processing"];
|
|
146
|
+
var WITHOUT_EFFECT = ["rejected", "denied", "error", "cancelled", "substituted"];
|
|
147
|
+
function isWithoutEffect(status) {
|
|
148
|
+
return WITHOUT_EFFECT.includes(status);
|
|
149
|
+
}
|
|
150
|
+
function statusLabel(note) {
|
|
151
|
+
if (IN_FLIGHT.includes(note.status) && note.cancelledAt) return "Cancelamento solicitado";
|
|
152
|
+
return (STATUS_META[note.status] ?? STATUS_META.error).label;
|
|
153
|
+
}
|
|
154
|
+
function summarizeNotes(notes) {
|
|
155
|
+
const s = { hasValid: false, withoutEffect: 0, inFlight: 0, validIsTest: false };
|
|
156
|
+
for (const n of notes) {
|
|
157
|
+
if (n.status === "authorized") {
|
|
158
|
+
s.hasValid = true;
|
|
159
|
+
if (n.environment === "homologacao") s.validIsTest = true;
|
|
160
|
+
} else if (IN_FLIGHT.includes(n.status)) s.inFlight += 1;
|
|
161
|
+
else if (WITHOUT_EFFECT.includes(n.status)) s.withoutEffect += 1;
|
|
162
|
+
}
|
|
163
|
+
return s;
|
|
164
|
+
}
|
|
165
|
+
function notesButtonState(s) {
|
|
166
|
+
if (s.hasValid) return "authorized";
|
|
167
|
+
if (s.inFlight > 0) return "processing";
|
|
168
|
+
if (s.withoutEffect > 0) return "failed-only";
|
|
169
|
+
return "none";
|
|
170
|
+
}
|
|
171
|
+
var SEFAZ_HINTS = [
|
|
172
|
+
["E0120", "no padr\xE3o nacional a Inscri\xE7\xE3o Municipal \xE9 opcional (a nota identifica pelo CNPJ). Apague a IM na configura\xE7\xE3o fiscal da unidade e emita de novo."],
|
|
173
|
+
["E0312", "geralmente falta o C\xD3DIGO DE TRIBUTA\xC7\xC3O DO MUNIC\xCDPIO (3 d\xEDgitos) na configura\xE7\xE3o fiscal da unidade \u2014 n\xE3o o nacional. Cada prefeitura tem a sua tabela; confirme o c\xF3digo com a contabilidade."],
|
|
174
|
+
["E0314", "o c\xF3digo de tributa\xE7\xE3o do munic\xEDpio n\xE3o existe na tabela daquela prefeitura. Confirme o valor com a contabilidade da unidade \u2014 ele n\xE3o \xE9 o mesmo em todo munic\xEDpio. Fora do Rio de Janeiro, o normal \xE9 deixar esse campo VAZIO."],
|
|
175
|
+
["E0084", "o CNPJ n\xE3o consta como estabelecido nesse munic\xEDpio no cadastro nacional. Isso se resolve FORA do sistema: a empresa precisa ter inscri\xE7\xE3o municipal ativa na prefeitura e o endere\xE7o do CNPJ na Receita Federal apontando para o mesmo munic\xEDpio. Fale com a contabilidade \u2014 n\xE3o h\xE1 o que ajustar aqui."]
|
|
176
|
+
];
|
|
177
|
+
var FIELD_LABELS = {
|
|
178
|
+
"prestador.cpfCnpj": "CNPJ do emitente",
|
|
179
|
+
"tomador.cpfCnpj": "CPF/CNPJ do cliente",
|
|
180
|
+
"tomador.razaoSocial": "Nome do cliente",
|
|
181
|
+
"tomador.endereco.cep": "CEP do cliente",
|
|
182
|
+
"tomador.endereco.codigoCidade": "Munic\xEDpio do cliente",
|
|
183
|
+
"servico.codigo": "C\xF3digo de tributa\xE7\xE3o do servi\xE7o",
|
|
184
|
+
"servico.iss.aliquota": "Al\xEDquota de ISS",
|
|
185
|
+
"itens.ncm": "NCM do produto",
|
|
186
|
+
"itens.cfop": "CFOP do produto",
|
|
187
|
+
"pagamentos.meio": "Forma de pagamento (tPag)",
|
|
188
|
+
"emitente.inscricaoMunicipal": "Inscri\xE7\xE3o municipal",
|
|
189
|
+
"emitente.inscricaoEstadual": "Inscri\xE7\xE3o estadual"
|
|
190
|
+
};
|
|
191
|
+
function explainRejection(rejection) {
|
|
192
|
+
if (!rejection) return { summary: "Nota rejeitada sem detalhe do motivo.", fields: [] };
|
|
193
|
+
const r = Array.isArray(rejection) ? rejection[0] : rejection;
|
|
194
|
+
const err = r?.error ?? r;
|
|
195
|
+
let message = String(err?.message || r?.mensagem || r?.motivo || "Nota rejeitada.");
|
|
196
|
+
const embedded = message.match(/\[\s*\{[\s\S]*\}\s*\]/);
|
|
197
|
+
if (embedded) {
|
|
198
|
+
try {
|
|
199
|
+
const arr = JSON.parse(embedded[0]);
|
|
200
|
+
const parts = (Array.isArray(arr) ? arr : [arr]).map((e) => [e.Codigo ?? e.codigo, e.Descricao ?? e.descricao ?? e.Mensagem ?? e.mensagem].filter(Boolean).join(" \u2014 ")).filter(Boolean);
|
|
201
|
+
if (parts.length) message = parts.join("; ");
|
|
202
|
+
} catch {
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const hint = SEFAZ_HINTS.find(([code]) => message.includes(code));
|
|
206
|
+
if (hint) message = `${message} \u2014 ${hint[1]}`;
|
|
207
|
+
const fieldsObj = err?.data?.fields ?? {};
|
|
208
|
+
const fields = Object.entries(fieldsObj).map(([field, msg]) => {
|
|
209
|
+
const normalized = field.replace(/\[\d+\]/g, "").replace(/\.\d+\./g, ".");
|
|
210
|
+
return { field, label: FIELD_LABELS[normalized] ?? field, message: String(msg) };
|
|
211
|
+
});
|
|
212
|
+
return { summary: message, fields };
|
|
213
|
+
}
|
|
214
|
+
function recipientLabel(recipient) {
|
|
215
|
+
if (!recipient) return "Consumidor final";
|
|
216
|
+
if (recipient.consumidor) return "Consumidor final";
|
|
217
|
+
return String(recipient.razaoSocial ?? recipient.nome ?? recipient.cpfCnpj ?? "Consumidor final");
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export { CANCEL_MIN_JUSTIFICATION, EVENT_LABEL, MODEL_LABEL, NOTE_STATUS_LABEL, STATUS_META, eventStatusLabel, explainRejection, isWithoutEffect, noteErrorSentence, notesButtonState, optionSentence, orderNotes, recipientLabel, refusalSentence, statusLabel, summarizeNotes };
|
|
221
|
+
//# sourceMappingURL=chunk-ODMEESFD.js.map
|
|
222
|
+
//# sourceMappingURL=chunk-ODMEESFD.js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,OAAO,EAAE,OAAA,EAAS,OAAA,EAAS,MAAA,EAAO;AACpC;AAEO,SAAS,eAAe,SAAA,EAAmD;AAChF,EAAA,IAAI,CAAC,WAAW,OAAO,kBAAA;AACvB,EAAA,IAAI,SAAA,CAAU,YAAY,OAAO,kBAAA;AACjC,EAAA,OAAO,OAAO,SAAA,CAAU,WAAA,IAAe,UAAU,IAAA,IAAQ,SAAA,CAAU,WAAW,kBAAkB,CAAA;AAClG","file":"chunk-ODMEESFD.js","sourcesContent":["// An order's fiscal notes as the integration service issues them\n// (control-sdk-backend ADR 0008, step 2). The service builds the note with the\n// V1's rules, talks to PlugNotas and records the answer; this file only sends\n// and turns a refusal code into the sentence the screen shows.\nimport { tl } from '@fayz-ai/core'\nimport { EmitterError, request, requestFile } from './service'\n\nexport type NoteModel = 'nfce' | 'nfe'\n\n/** Whether the order can take a model of note, as the service answers it; `reason` is its refusal code. */\nexport interface IssueOption {\n available: boolean\n reason: string | null\n message: string | null\n}\n\nexport type IssueOptions = Record<NoteModel, IssueOption>\n\nexport type NoteStatus = 'processing' | 'authorized' | 'rejected' | 'error' | 'cancelled' | 'substituted'\n\nexport interface OrderNote {\n documentId: string\n orderId: string | null\n model: NoteModel\n status: NoteStatus\n environment: string | null\n series: string | null\n number: string | null\n accessKey: string | null\n protocol: string | null\n total: number | null\n rejection: { message?: string | null; fields?: Array<{ field: string; message: string }>; raw?: unknown } | null\n authorizedAt: string | null\n cancelledAt: string | null\n cancelReason: string | null\n /** processing while a cancellation waits on the SEFAZ. */\n cancellation: string | null\n /** The send got no answer; the service is looking for the note by its id. */\n uncertain: boolean\n createdAt: string\n}\n\nexport const CANCEL_MIN_JUSTIFICATION = 15\n\nconst SENTENCES: Record<string, string> = {\n no_client: 'O serviço de integrações não está configurado neste app.',\n not_configured: 'A emissão fiscal ainda não está ligada no servidor.',\n unauthorized: 'Sua sessão expirou. Entre de novo.',\n not_allowed: 'Seu acesso não permite emitir ou cancelar notas.',\n unavailable: 'Não foi possível falar com o serviço fiscal. Tente de novo em instantes.',\n unknown_order: 'Este pedido não foi encontrado.',\n unknown_note: 'Esta nota não foi encontrada.',\n not_a_sale: 'Só uma venda recebe nota fiscal.',\n order_not_closed: 'Este pedido ainda não pode receber nota.',\n no_emitter: 'A unidade deste pedido não tem empresa (CNPJ) cadastrada para emitir.',\n emitter_not_owned: 'Esta empresa ainda emite pelo sistema anterior. Configure em Integrações → PlugNotas.',\n emitter_not_ready: 'Falta configurar a empresa para emitir esta nota (Integrações → PlugNotas).',\n interstate: 'Este pedido vai para outro estado: não cabe NFC-e, e NF-e interestadual ainda não é emitida por aqui.',\n no_series: 'A empresa não tem série de NFC-e configurada.',\n no_items: 'O pedido não tem produtos para a nota.',\n products_without_ncm: 'Há produtos sem cadastro fiscal (NCM).',\n icms_code_mismatch: 'Há produtos com código de ICMS que não combina com o regime da empresa.',\n not_paid: 'O pedido não tem pagamento recebido para a nota.',\n totals_differ: 'Os itens e os pagamentos do pedido não fecham no mesmo total.',\n invalid_text: 'Um produto tem um nome que a SEFAZ não aceita (só emojis ou caracteres especiais).',\n note_exists: 'Este pedido já tem uma nota emitida ou em processamento. Para trocar de modelo, cancele a nota atual primeiro.',\n not_authorized: 'Só uma nota autorizada pode ser cancelada ou baixada.',\n justification_too_short: `A justificativa precisa ter pelo menos ${CANCEL_MIN_JUSTIFICATION} caracteres.`,\n cancel_deadline_passed: 'O prazo de cancelamento desta nota já passou.',\n cancel_refused: 'A SEFAZ recusou o cancelamento.',\n plugnotas_refused: 'A PlugNotas recusou o envio.',\n marketplace_intermediary: 'Pedidos de marketplace (iFood, 99Food, Keeta) ainda não emitem NFC-e por aqui.',\n not_ours: 'Esta nota foi emitida pelo sistema anterior; cancele por lá.',\n}\n\n/** The NF-e's own refusals (control-sdk-backend ADR 0008, decisions 15 to 23), in both locales. */\nconst NFE_SENTENCES: Record<string, () => string> = {\n nfe_needs_company: () => tl(\n \"NF-e is for a sale to a company: this order's customer has no CNPJ.\",\n 'A NF-e é para venda a empresa: o cliente deste pedido não tem CNPJ.'),\n nfe_not_enabled: () => tl(\n 'The company does not issue NF-e yet. Turn it on and choose its series in Integrations → PlugNotas.',\n 'A empresa ainda não emite NF-e. Ative e escolha a série em Integrações → PlugNotas.'),\n nfe_not_set_up: () => tl(\n 'NF-e issuing is not set up for this company yet (Integrations → PlugNotas: NF-e series).',\n 'A emissão de NF-e por aqui ainda não foi configurada para esta empresa (Integrações → PlugNotas: série da NF-e).'),\n no_nfe_series: () => tl('The company has no NF-e series set.', 'A empresa não tem série de NF-e configurada.'),\n recipient_no_name: () => tl(\"The customer's record has no legal name.\", 'O cadastro do cliente não tem razão social.'),\n recipient_state_registration_unknown: () => tl(\n \"The customer's state registration (IE) is not recorded: enter the number, ISENTO or NÃO CONTRIBUINTE on the customer's record.\",\n 'A inscrição estadual do cliente não está cadastrada: informe o número, ISENTO ou NÃO CONTRIBUINTE no cadastro do cliente.'),\n recipient_address_incomplete: () => tl(\"The customer's address is incomplete\", 'O endereço do cliente está incompleto'),\n nfe_interstate: () => tl(\n 'The customer is in another state: interstate NF-e is not issued here yet.',\n 'O cliente é de outro estado: NF-e interestadual ainda não é emitida por aqui.'),\n}\n\n/** What the address lacks, as the service names it, in the screen's words. */\nconst ADDRESS_PART: Record<string, () => string> = {\n street: () => tl('street', 'rua'),\n city: () => tl('city', 'cidade'),\n state: () => tl('state', 'UF'),\n 'postal code': () => tl('postal code', 'CEP'),\n 'IBGE city code': () => tl('city code (IBGE), not found for this postal code', 'código do município (IBGE), não encontrado pelo CEP'),\n}\n\n/** The sentence for a refusal code; `message` is the service's, used for the parts it names. */\nexport function refusalSentence(code: string, message: string): string {\n const nfe = NFE_SENTENCES[code]\n if (nfe) {\n if (code !== 'recipient_address_incomplete') return nfe()\n const parts = (message.split('missing ')[1] ?? '').split(', ').map((p) => ADDRESS_PART[p.trim()]?.() ?? p.trim()).filter(Boolean)\n return parts.length ? `${nfe()}: ${tl('missing', 'falta')} ${parts.join(', ')}.` : `${nfe()}.`\n }\n const base = SENTENCES[code] ?? message\n // The products to fix come by name: they are what the store acts on.\n return code === 'products_without_ncm' || code === 'icms_code_mismatch'\n ? `${base} ${message.split(': ').slice(1).join(': ')}`.trim()\n : base\n}\n\nexport function noteErrorSentence(error: unknown): string {\n if (error instanceof EmitterError) return refusalSentence(error.code, error.message)\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Why the model is not offered on this order, as a sentence; null when it is. */\nexport function optionSentence(option: IssueOption | undefined): string | null {\n if (!option || option.available) return null\n return refusalSentence(option.reason ?? 'unavailable', option.message ?? '')\n}\n\nconst order = (orderId: string) => `/v1/fiscal/orders/${encodeURIComponent(orderId)}/notes`\nconst one = (documentId: string, rest = '') => `/v1/fiscal/notes/${encodeURIComponent(documentId)}${rest}`\n\nexport const orderNotes = {\n /** The order's notes, newest first, and which models the service would issue on it. */\n list: async (orderId: string): Promise<{ notes: OrderNote[]; options: IssueOptions | null }> => {\n const r = await request<{ notes: OrderNote[]; options?: IssueOptions }>('GET', order(orderId))\n return { notes: r.notes, options: r.options ?? null }\n },\n issue: (orderId: string, model: NoteModel) => request<OrderNote>('POST', order(orderId), { model }),\n /** Reads PlugNotas again while the note is processing. */\n read: (documentId: string) => request<OrderNote>('GET', one(documentId)),\n cancel: (documentId: string, justification: string) => request<OrderNote>('PUT', one(documentId, '/cancellation'), { justification }),\n pdf: (documentId: string) => requestFile(one(documentId, '/pdf')),\n xml: (documentId: string) => requestFile(one(documentId, '/xml')),\n}\n\nexport const NOTE_STATUS_LABEL: Record<NoteStatus, string> = {\n processing: 'Processando',\n authorized: 'Autorizada',\n rejected: 'Rejeitada',\n error: 'Erro',\n cancelled: 'Cancelada',\n substituted: 'Substituída',\n}\n","// Vocabulary and reading rules for an issued note (plg_fiscalbr_documents),\n// shared by every screen that shows one.\n\nexport type IssuedNoteModel = 'nfse' | 'nfce' | 'nfe'\nexport type IssuedNoteStatus =\n | 'draft' | 'processing' | 'authorized' | 'rejected' | 'error' | 'cancelled' | 'substituted' | 'denied'\n\nexport interface IssuedNote {\n documentId: string\n model: IssuedNoteModel\n status: IssuedNoteStatus\n environment: 'producao' | 'homologacao' | null\n number: string | null\n series: string | null\n accessKey: string | null\n verificationCode: string | null\n integrationId: string | null\n totalValue: number | null\n recipient: Record<string, unknown> | null\n rejection: unknown\n createdAt: string\n authorizedAt: string | null\n cancelledAt: string | null\n cancelReason: string | null\n}\n\nexport interface IssuedNoteEvent {\n id: string\n eventType: string\n status: string | null\n justification: string | null\n createdAt: string\n}\n\nexport const MODEL_LABEL: Record<IssuedNoteModel, string> = { nfse: 'NFS-e', nfce: 'NFC-e', nfe: 'NF-e' }\n\nexport type StatusTone = 'success' | 'warning' | 'danger' | 'muted'\n\nexport const STATUS_META: Record<IssuedNoteStatus, { label: string; tone: StatusTone }> = {\n authorized: { label: 'Autorizada', tone: 'success' },\n draft: { label: 'Enviando', tone: 'warning' },\n processing: { label: 'Processando', tone: 'warning' },\n rejected: { label: 'Rejeitada', tone: 'danger' },\n denied: { label: 'Denegada', tone: 'danger' },\n error: { label: 'Erro', tone: 'danger' },\n cancelled: { label: 'Cancelada', tone: 'muted' },\n substituted: { label: 'Substituída', tone: 'muted' },\n}\n\nexport const EVENT_LABEL: Record<string, string> = {\n emissao: 'Emissão enviada',\n consulta: 'Consulta de status',\n cancelamento: 'Cancelamento',\n substituicao: 'Substituição',\n cce: 'Carta de correção',\n inutilizacao: 'Inutilização',\n webhook: 'Notificação do emissor fiscal',\n erro: 'Erro',\n}\n\n// Provider/V1 words on the trail. Internal steps (nfce_start…) have no\n// translation on purpose: they show nothing rather than the raw code.\nconst EVENT_STATUS_LABEL: Record<string, string> = {\n CRIADO: 'Enviando', PROCESSANDO: 'Processando', CONCLUIDO: 'Autorizada', REJEITADO: 'Rejeitada',\n DENEGADO: 'Denegada', CANCELADO: 'Cancelada', SUBSTITUIDO: 'Substituída', SOLICITADO: 'Solicitado', ERRO: 'Erro',\n}\n\nexport function eventStatusLabel(status: string | null): string | null {\n return status ? EVENT_STATUS_LABEL[status.toUpperCase()] ?? null : null\n}\n\nconst IN_FLIGHT: IssuedNoteStatus[] = ['draft', 'processing']\nconst WITHOUT_EFFECT: IssuedNoteStatus[] = ['rejected', 'denied', 'error', 'cancelled', 'substituted']\n\nexport function isWithoutEffect(status: IssuedNoteStatus): boolean {\n return WITHOUT_EFFECT.includes(status)\n}\n\n/** A cancellation in progress sits in `processing` exactly like an issue in progress. */\nexport function statusLabel(note: Pick<IssuedNote, 'status' | 'cancelledAt'>): string {\n if (IN_FLIGHT.includes(note.status) && note.cancelledAt) return 'Cancelamento solicitado'\n return (STATUS_META[note.status] ?? STATUS_META.error).label\n}\n\nexport interface NotesSummary {\n hasValid: boolean\n withoutEffect: number\n inFlight: number\n /** Only an AUTHORIZED test note misleads; a rejected one in homologação fools nobody. */\n validIsTest: boolean\n}\n\nexport function summarizeNotes(notes: Pick<IssuedNote, 'status' | 'environment'>[]): NotesSummary {\n const s: NotesSummary = { hasValid: false, withoutEffect: 0, inFlight: 0, validIsTest: false }\n for (const n of notes) {\n if (n.status === 'authorized') {\n s.hasValid = true\n if (n.environment === 'homologacao') s.validIsTest = true\n } else if (IN_FLIGHT.includes(n.status)) s.inFlight += 1\n else if (WITHOUT_EFFECT.includes(n.status)) s.withoutEffect += 1\n }\n return s\n}\n\nexport type NotesButtonState = 'none' | 'authorized' | 'processing' | 'failed-only'\n\nexport function notesButtonState(s: NotesSummary): NotesButtonState {\n if (s.hasValid) return 'authorized'\n if (s.inFlight > 0) return 'processing'\n if (s.withoutEffect > 0) return 'failed-only'\n return 'none'\n}\n\n// The SEFAZ message says what is wrong, never what to do. These codes each cost\n// a full diagnosis in the V1 (measured on tenant 1, 23-09-2026), so the hint\n// travels with the message.\nconst SEFAZ_HINTS: Array<[string, string]> = [\n ['E0120', 'no padrão nacional a Inscrição Municipal é opcional (a nota identifica pelo CNPJ). '\n + 'Apague a IM na configuração fiscal da unidade e emita de novo.'],\n ['E0312', 'geralmente falta o CÓDIGO DE TRIBUTAÇÃO DO MUNICÍPIO (3 dígitos) na configuração '\n + 'fiscal da unidade — não o nacional. Cada prefeitura tem a sua tabela; confirme o código '\n + 'com a contabilidade.'],\n ['E0314', 'o código de tributação do município não existe na tabela daquela prefeitura. '\n + 'Confirme o valor com a contabilidade da unidade — ele não é o mesmo em todo município. '\n + 'Fora do Rio de Janeiro, o normal é deixar esse campo VAZIO.'],\n ['E0084', 'o CNPJ não consta como estabelecido nesse município no cadastro nacional. '\n + 'Isso se resolve FORA do sistema: a empresa precisa ter inscrição municipal ativa na '\n + 'prefeitura e o endereço do CNPJ na Receita Federal apontando para o mesmo município. '\n + 'Fale com a contabilidade — não há o que ajustar aqui.'],\n]\n\nconst FIELD_LABELS: Record<string, string> = {\n 'prestador.cpfCnpj': 'CNPJ do emitente',\n 'tomador.cpfCnpj': 'CPF/CNPJ do cliente',\n 'tomador.razaoSocial': 'Nome do cliente',\n 'tomador.endereco.cep': 'CEP do cliente',\n 'tomador.endereco.codigoCidade': 'Município do cliente',\n 'servico.codigo': 'Código de tributação do serviço',\n 'servico.iss.aliquota': 'Alíquota de ISS',\n 'itens.ncm': 'NCM do produto',\n 'itens.cfop': 'CFOP do produto',\n 'pagamentos.meio': 'Forma de pagamento (tPag)',\n 'emitente.inscricaoMunicipal': 'Inscrição municipal',\n 'emitente.inscricaoEstadual': 'Inscrição estadual',\n}\n\nexport interface RejectionField { field: string; label: string; message: string }\n\n/** PlugNotas rejection payload ({error:{message,data:{fields}}}) → something a person can act on. */\nexport function explainRejection(rejection: unknown): { summary: string; fields: RejectionField[] } {\n if (!rejection) return { summary: 'Nota rejeitada sem detalhe do motivo.', fields: [] }\n const r = (Array.isArray(rejection) ? rejection[0] : rejection) as Record<string, any>\n const err = r?.error ?? r\n let message: string = String(err?.message || r?.mensagem || r?.motivo || 'Nota rejeitada.')\n // The national issuer embeds the reason as JSON inside the string.\n const embedded = message.match(/\\[\\s*\\{[\\s\\S]*\\}\\s*\\]/)\n if (embedded) {\n try {\n const arr = JSON.parse(embedded[0])\n const parts = (Array.isArray(arr) ? arr : [arr])\n .map((e: any) => [e.Codigo ?? e.codigo, e.Descricao ?? e.descricao ?? e.Mensagem ?? e.mensagem]\n .filter(Boolean).join(' — '))\n .filter(Boolean)\n if (parts.length) message = parts.join('; ')\n } catch { /* keep the raw message */ }\n }\n const hint = SEFAZ_HINTS.find(([code]) => message.includes(code))\n if (hint) message = `${message} — ${hint[1]}`\n\n const fieldsObj: Record<string, unknown> = err?.data?.fields ?? {}\n const fields = Object.entries(fieldsObj).map(([field, msg]) => {\n const normalized = field.replace(/\\[\\d+\\]/g, '').replace(/\\.\\d+\\./g, '.')\n return { field, label: FIELD_LABELS[normalized] ?? field, message: String(msg) }\n })\n return { summary: message, fields }\n}\n\nexport function recipientLabel(recipient: Record<string, unknown> | null): string {\n if (!recipient) return 'Consumidor final'\n if (recipient.consumidor) return 'Consumidor final'\n return String(recipient.razaoSocial ?? recipient.nome ?? recipient.cpfCnpj ?? 'Consumidor final')\n}\n"]}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { orderNotes, noteErrorSentence, NOTE_STATUS_LABEL, CANCEL_MIN_JUSTIFICATION } from './chunk-
|
|
1
|
+
import { orderNotes, noteErrorSentence, optionSentence, MODEL_LABEL, NOTE_STATUS_LABEL, CANCEL_MIN_JUSTIFICATION } from './chunk-ODMEESFD.js';
|
|
2
2
|
import React from 'react';
|
|
3
3
|
import { Button, Skeleton, Badge, toast, Modal, ModalContent, ModalHeader, ModalTitle, ModalDescription, Textarea, ModalFooter } from '@fayz-ai/ui';
|
|
4
4
|
import { OrderDetailBlock } from '@fayz-ai/admin';
|
|
5
|
-
import {
|
|
5
|
+
import { tl } from '@fayz-ai/core';
|
|
6
|
+
import { Info, RefreshCw, Loader2, AlertCircle, FileText, Download } from 'lucide-react';
|
|
6
7
|
import { jsxs, jsx } from 'react/jsx-runtime';
|
|
7
8
|
|
|
8
9
|
var POLL_DELAYS = [3, 5, 8, 12, 20, 20];
|
|
@@ -21,13 +22,16 @@ async function openFile(blob, fileName, download) {
|
|
|
21
22
|
}
|
|
22
23
|
function OrderNoteCard({ orderId }) {
|
|
23
24
|
const [notes, setNotes] = React.useState(null);
|
|
25
|
+
const [options, setOptions] = React.useState(null);
|
|
24
26
|
const [error, setError] = React.useState(null);
|
|
25
|
-
const [issuing, setIssuing] = React.useState(
|
|
27
|
+
const [issuing, setIssuing] = React.useState(null);
|
|
26
28
|
const [cancelling, setCancelling] = React.useState(null);
|
|
27
29
|
const load = React.useCallback(async () => {
|
|
28
30
|
if (!orderId) return;
|
|
29
31
|
try {
|
|
30
|
-
|
|
32
|
+
const r = await orderNotes.list(orderId);
|
|
33
|
+
setNotes(r.notes);
|
|
34
|
+
setOptions(r.options);
|
|
31
35
|
setError(null);
|
|
32
36
|
} catch (e) {
|
|
33
37
|
setError(noteErrorSentence(e));
|
|
@@ -50,9 +54,10 @@ function OrderNoteCard({ orderId }) {
|
|
|
50
54
|
const fresh = await orderNotes.read(processing.documentId);
|
|
51
55
|
if (!alive) return;
|
|
52
56
|
setNotes((list) => list?.map((n) => n.documentId === fresh.documentId ? fresh : n) ?? null);
|
|
57
|
+
const label = MODEL_LABEL[fresh.model];
|
|
53
58
|
if (fresh.status === "processing" || fresh.cancellation === "processing") void tick();
|
|
54
|
-
else if (fresh.status === "authorized" && !fresh.cancellation) toast.success(
|
|
55
|
-
else if (fresh.status === "rejected") toast.error(
|
|
59
|
+
else if (fresh.status === "authorized" && !fresh.cancellation) toast.success(tl(`${label} no. ${fresh.number ?? ""} authorized`, `${label} n\xBA ${fresh.number ?? ""} autorizada`));
|
|
60
|
+
else if (fresh.status === "rejected") toast.error(tl(`The SEFAZ rejected the ${label}`, `A SEFAZ rejeitou a ${label}`), { description: fresh.rejection?.message ?? void 0 });
|
|
56
61
|
} catch {
|
|
57
62
|
void tick();
|
|
58
63
|
}
|
|
@@ -69,64 +74,88 @@ function OrderNoteCard({ orderId }) {
|
|
|
69
74
|
const earlier = notes?.slice(1) ?? [];
|
|
70
75
|
const failed = current?.status === "rejected" || current?.status === "error";
|
|
71
76
|
const canIssue = notes !== null && !error && (!current || failed || current.status === "cancelled");
|
|
72
|
-
const
|
|
73
|
-
|
|
77
|
+
const nfeWhyNot = optionSentence(options?.nfe);
|
|
78
|
+
const nfeFirst = options?.nfe.available === true;
|
|
79
|
+
const issue = async (model) => {
|
|
80
|
+
const label = MODEL_LABEL[model];
|
|
81
|
+
setIssuing(model);
|
|
74
82
|
try {
|
|
75
|
-
const note = await orderNotes.
|
|
83
|
+
const note = await orderNotes.issue(orderId, model);
|
|
76
84
|
setNotes((list) => [note, ...list ?? []]);
|
|
77
|
-
if (note.status === "rejected") toast.error(
|
|
78
|
-
else toast.success(
|
|
85
|
+
if (note.status === "rejected") toast.error(tl(`The ${label} was refused`, `A ${label} foi recusada`), { description: reasonOf(note) ?? void 0 });
|
|
86
|
+
else toast.success(tl(`${label} sent. Waiting for the SEFAZ\u2026`, `${label} enviada. Aguardando a SEFAZ\u2026`));
|
|
79
87
|
} catch (e) {
|
|
80
|
-
toast.error(
|
|
88
|
+
toast.error(tl(`Could not issue the ${label}`, `N\xE3o foi poss\xEDvel emitir a ${label}`), { description: noteErrorSentence(e) });
|
|
81
89
|
} finally {
|
|
82
|
-
setIssuing(
|
|
90
|
+
setIssuing(null);
|
|
83
91
|
}
|
|
84
92
|
};
|
|
93
|
+
const button = (model, primary) => {
|
|
94
|
+
const label = MODEL_LABEL[model];
|
|
95
|
+
const blocked = model === "nfe" && options?.nfe.available === false;
|
|
96
|
+
return /* @__PURE__ */ jsxs(
|
|
97
|
+
Button,
|
|
98
|
+
{
|
|
99
|
+
size: "sm",
|
|
100
|
+
variant: primary ? "default" : "outline",
|
|
101
|
+
onClick: () => void issue(model),
|
|
102
|
+
disabled: issuing !== null || blocked,
|
|
103
|
+
title: blocked ? nfeWhyNot ?? void 0 : void 0,
|
|
104
|
+
children: [
|
|
105
|
+
/* @__PURE__ */ jsx(FileText, { className: "mr-1.5 h-4 w-4" }),
|
|
106
|
+
issuing === model ? tl("Issuing\u2026", "Emitindo\u2026") : tl(`Issue ${label}`, `Emitir ${label}`)
|
|
107
|
+
]
|
|
108
|
+
},
|
|
109
|
+
model
|
|
110
|
+
);
|
|
111
|
+
};
|
|
85
112
|
return /* @__PURE__ */ jsxs(
|
|
86
113
|
OrderDetailBlock,
|
|
87
114
|
{
|
|
88
|
-
title: "Nota fiscal",
|
|
89
|
-
actions: canIssue
|
|
90
|
-
/* @__PURE__ */ jsx(FileText, { className: "mr-1.5 h-4 w-4" }),
|
|
91
|
-
issuing ? "Emitindo\u2026" : "Emitir NFC-e"
|
|
92
|
-
] }) : void 0,
|
|
115
|
+
title: tl("Invoice", "Nota fiscal"),
|
|
116
|
+
actions: canIssue ? /* @__PURE__ */ jsx("div", { className: "flex flex-wrap justify-end gap-2", children: nfeFirst ? [button("nfe", true), button("nfce", false)] : [button("nfce", true), button("nfe", false)] }) : void 0,
|
|
93
117
|
children: [
|
|
118
|
+
canIssue && nfeWhyNot && /* @__PURE__ */ jsxs("p", { className: "mb-2 flex items-start gap-1.5 text-xs text-muted-foreground", children: [
|
|
119
|
+
/* @__PURE__ */ jsx(Info, { className: "mt-0.5 h-3.5 w-3.5 shrink-0" }),
|
|
120
|
+
/* @__PURE__ */ jsx("span", { children: nfeWhyNot })
|
|
121
|
+
] }),
|
|
94
122
|
error && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 text-sm", children: [
|
|
95
123
|
/* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: error }),
|
|
96
124
|
/* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", onClick: () => void load(), children: /* @__PURE__ */ jsx(RefreshCw, { className: "h-4 w-4" }) })
|
|
97
125
|
] }),
|
|
98
126
|
!error && notes === null && /* @__PURE__ */ jsx(Skeleton, { className: "h-10 w-full" }),
|
|
99
|
-
!error && current === null && notes !== null && /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Nenhuma nota emitida para este pedido." }),
|
|
127
|
+
!error && current === null && notes !== null && /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: tl("No invoice issued for this order.", "Nenhuma nota emitida para este pedido.") }),
|
|
100
128
|
!error && current && current.status === "processing" && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
|
|
101
129
|
/* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }),
|
|
102
|
-
current.uncertain ? "Aguardando a resposta da SEFAZ\u2026" :
|
|
130
|
+
current.uncertain ? tl("Waiting for the SEFAZ answer\u2026", "Aguardando a resposta da SEFAZ\u2026") : tl(`Sending the ${MODEL_LABEL[current.model]} to the SEFAZ\u2026`, `Enviando a ${MODEL_LABEL[current.model]} \xE0 SEFAZ\u2026`)
|
|
103
131
|
] }),
|
|
104
132
|
!error && current && failed && /* @__PURE__ */ jsxs("div", { className: "space-y-2 rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm", children: [
|
|
105
133
|
/* @__PURE__ */ jsxs("p", { className: "flex items-center gap-1.5 font-medium text-destructive", children: [
|
|
106
134
|
/* @__PURE__ */ jsx(AlertCircle, { className: "h-4 w-4" }),
|
|
107
|
-
current.status === "rejected" ?
|
|
135
|
+
current.status === "rejected" ? tl(`The SEFAZ refused the ${MODEL_LABEL[current.model]}`, `A SEFAZ recusou a ${MODEL_LABEL[current.model]}`) : tl(`Could not issue the ${MODEL_LABEL[current.model]}`, `N\xE3o foi poss\xEDvel emitir a ${MODEL_LABEL[current.model]}`)
|
|
108
136
|
] }),
|
|
109
137
|
reasonOf(current) && /* @__PURE__ */ jsx("p", { children: reasonOf(current) }),
|
|
110
|
-
/* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children:
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
] }) })
|
|
138
|
+
/* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: tl(
|
|
139
|
+
"No invoice was issued, so there is nothing to cancel. Fix the reason and issue again above.",
|
|
140
|
+
"Nenhuma nota foi emitida: n\xE3o h\xE1 o que cancelar. Corrija o motivo e emita de novo acima."
|
|
141
|
+
) })
|
|
115
142
|
] }),
|
|
116
143
|
!error && current && (current.status === "authorized" || current.status === "cancelled" || current.status === "substituted") && /* @__PURE__ */ jsx(NoteDetails, { note: current, onCancel: () => setCancelling(current) }),
|
|
117
144
|
!error && earlier.length > 0 && /* @__PURE__ */ jsxs("details", { className: "mt-3 text-xs text-muted-foreground", children: [
|
|
118
|
-
/* @__PURE__ */
|
|
119
|
-
"Tentativas anteriores (",
|
|
120
|
-
earlier.length,
|
|
121
|
-
")"
|
|
122
|
-
] }),
|
|
145
|
+
/* @__PURE__ */ jsx("summary", { className: "cursor-pointer select-none", children: tl(`Earlier attempts (${earlier.length})`, `Tentativas anteriores (${earlier.length})`) }),
|
|
123
146
|
/* @__PURE__ */ jsx("ul", { className: "mt-2 space-y-1.5", children: earlier.map((n) => /* @__PURE__ */ jsxs("li", { className: "flex flex-wrap items-baseline gap-x-2", children: [
|
|
124
147
|
/* @__PURE__ */ jsx("span", { children: new Date(n.createdAt).toLocaleString("pt-BR", { dateStyle: "short", timeStyle: "short" }) }),
|
|
125
|
-
/* @__PURE__ */
|
|
148
|
+
/* @__PURE__ */ jsxs("span", { className: "font-medium", children: [
|
|
149
|
+
MODEL_LABEL[n.model],
|
|
150
|
+
" \xB7 ",
|
|
151
|
+
NOTE_STATUS_LABEL[n.status]
|
|
152
|
+
] }),
|
|
126
153
|
n.status === "authorized" || n.status === "cancelled" ? /* @__PURE__ */ jsxs("span", { children: [
|
|
127
154
|
"n\xBA ",
|
|
128
155
|
n.number,
|
|
129
|
-
" \xB7
|
|
156
|
+
" \xB7 ",
|
|
157
|
+
tl("series", "s\xE9rie"),
|
|
158
|
+
" ",
|
|
130
159
|
n.series
|
|
131
160
|
] }) : null,
|
|
132
161
|
reasonOf(n) && /* @__PURE__ */ jsx("span", { className: "basis-full", children: reasonOf(n) })
|
|
@@ -158,10 +187,12 @@ function NoteDetails({ note, onCancel }) {
|
|
|
158
187
|
return /* @__PURE__ */ jsxs("div", { className: "space-y-1.5 text-sm", children: [
|
|
159
188
|
/* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
|
|
160
189
|
/* @__PURE__ */ jsxs("span", { className: "font-medium", children: [
|
|
161
|
-
note.model
|
|
190
|
+
MODEL_LABEL[note.model],
|
|
162
191
|
" n\xBA ",
|
|
163
192
|
note.number,
|
|
164
|
-
" \xB7
|
|
193
|
+
" \xB7 ",
|
|
194
|
+
tl("series", "s\xE9rie"),
|
|
195
|
+
" ",
|
|
165
196
|
note.series
|
|
166
197
|
] }),
|
|
167
198
|
/* @__PURE__ */ jsx(Badge, { variant: "outline", className: tone(note.status), children: note.cancellation === "processing" ? "Cancelando\u2026" : NOTE_STATUS_LABEL[note.status] }),
|
|
@@ -177,11 +208,11 @@ function NoteDetails({ note, onCancel }) {
|
|
|
177
208
|
note.cancelReason
|
|
178
209
|
] }),
|
|
179
210
|
/* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-2 pt-1", children: [
|
|
180
|
-
/* @__PURE__ */ jsxs(Button, { variant: "outline", size: "sm", onClick: () => void orderNotes.pdf(note.documentId).then((b) => openFile(b,
|
|
211
|
+
/* @__PURE__ */ jsxs(Button, { variant: "outline", size: "sm", onClick: () => void orderNotes.pdf(note.documentId).then((b) => openFile(b, `${note.model}-${note.number ?? note.documentId}.pdf`, false)).catch((e) => toast.error("N\xE3o foi poss\xEDvel abrir o DANFE", { description: noteErrorSentence(e) })), children: [
|
|
181
212
|
/* @__PURE__ */ jsx(FileText, { className: "mr-1.5 h-4 w-4" }),
|
|
182
213
|
"DANFE"
|
|
183
214
|
] }),
|
|
184
|
-
/* @__PURE__ */ jsxs(Button, { variant: "outline", size: "sm", onClick: () => void orderNotes.xml(note.documentId).then((b) => openFile(b,
|
|
215
|
+
/* @__PURE__ */ jsxs(Button, { variant: "outline", size: "sm", onClick: () => void orderNotes.xml(note.documentId).then((b) => openFile(b, `${note.model}-${note.number ?? note.documentId}.xml`, true)).catch((e) => toast.error("N\xE3o foi poss\xEDvel baixar o XML", { description: noteErrorSentence(e) })), children: [
|
|
185
216
|
/* @__PURE__ */ jsx(Download, { className: "mr-1.5 h-4 w-4" }),
|
|
186
217
|
"XML"
|
|
187
218
|
] }),
|
|
@@ -210,10 +241,16 @@ function CancelDialog({ note, onClose, onDone }) {
|
|
|
210
241
|
}, children: /* @__PURE__ */ jsxs(ModalContent, { children: [
|
|
211
242
|
/* @__PURE__ */ jsxs(ModalHeader, { children: [
|
|
212
243
|
/* @__PURE__ */ jsxs(ModalTitle, { children: [
|
|
213
|
-
|
|
244
|
+
tl(`Cancel ${MODEL_LABEL[note.model]}`, `Cancelar ${MODEL_LABEL[note.model]}`),
|
|
214
245
|
note.number ? ` n\xBA ${note.number}` : ""
|
|
215
246
|
] }),
|
|
216
|
-
/* @__PURE__ */ jsx(ModalDescription, { children:
|
|
247
|
+
/* @__PURE__ */ jsx(ModalDescription, { children: note.model === "nfe" ? tl(
|
|
248
|
+
"The SEFAZ accepts cancelling an NF-e within 24 hours of its authorization. To issue an NFC-e instead, cancel this one first.",
|
|
249
|
+
"A SEFAZ aceita o cancelamento de uma NF-e em at\xE9 24 horas da autoriza\xE7\xE3o. Para emitir uma NFC-e no lugar, cancele primeiro esta nota."
|
|
250
|
+
) : tl(
|
|
251
|
+
"The SEFAZ only accepts cancelling an NFC-e right after it is issued (usually 30 minutes). To issue an NF-e instead, cancel this one first.",
|
|
252
|
+
"A SEFAZ s\xF3 aceita o cancelamento de uma NFC-e logo depois da emiss\xE3o (em geral, 30 minutos). Para emitir uma NF-e no lugar, cancele primeiro esta nota."
|
|
253
|
+
) })
|
|
217
254
|
] }),
|
|
218
255
|
/* @__PURE__ */ jsx(
|
|
219
256
|
Textarea,
|
|
@@ -237,5 +274,5 @@ function CancelDialog({ note, onClose, onDone }) {
|
|
|
237
274
|
}
|
|
238
275
|
|
|
239
276
|
export { OrderNoteCard };
|
|
240
|
-
//# sourceMappingURL=chunk-
|
|
241
|
-
//# sourceMappingURL=chunk-
|
|
277
|
+
//# sourceMappingURL=chunk-SSPDH22E.js.map
|
|
278
|
+
//# sourceMappingURL=chunk-SSPDH22E.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/views/OrderNoteCard.tsx"],"names":[],"mappings":";;;;;;;;AA0BA,IAAM,cAAc,CAAC,CAAA,EAAG,GAAG,CAAA,EAAG,EAAA,EAAI,IAAI,EAAE,CAAA;AAExC,IAAM,IAAA,GAAO,CAAC,MAAA,KACZ,MAAA,KAAW,YAAA,GAAe,mFACtB,MAAA,KAAW,UAAA,IAAc,MAAA,KAAW,OAAA,GAAU,0DAAA,GAC5C,uBAAA;AAER,eAAe,QAAA,CAAS,IAAA,EAAY,QAAA,EAAkB,QAAA,EAAmB;AACvE,EAAA,MAAM,GAAA,GAAM,GAAA,CAAI,eAAA,CAAgB,IAAI,CAAA;AACpC,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,MAAM,CAAA,GAAI,QAAA,CAAS,aAAA,CAAc,GAAG,CAAA;AACpC,IAAA,CAAA,CAAE,IAAA,GAAO,GAAA;AACT,IAAA,CAAA,CAAE,QAAA,GAAW,QAAA;AACb,IAAA,CAAA,CAAE,KAAA,EAAM;AAAA,EACV,CAAA,MAAO;AACL,IAAA,MAAA,CAAO,IAAA,CAAK,GAAA,EAAK,QAAA,EAAU,UAAU,CAAA;AAAA,EACvC;AACA,EAAA,UAAA,CAAW,MAAM,GAAA,CAAI,eAAA,CAAgB,GAAG,GAAG,GAAM,CAAA;AACnD;AAEO,SAAS,aAAA,CAAc,EAAE,OAAA,EAAQ,EAAyB;AAC/D,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAI,KAAA,CAAM,SAA6B,IAAI,CAAA;AACjE,EAAA,MAAM,CAAC,OAAA,EAAS,UAAU,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AAC,gBAAA,EAAA,EACE,QAAA,EAAA,IAAA,CAAK,KAAA,KAAU,KAAA,GACZ,EAAA;AAAA,QAAG,8HAAA;AAAA,QACH;AAAA,OAAuI,GACvI,EAAA;AAAA,QAAG,4IAAA;AAAA,QACH;AAAA,OAAyJ,EAC/J;AAAA,KAAA,EACF,CAAA;AAAA,oBACA,GAAA;AAAA,MAAC,QAAA;AAAA,MAAA;AAAA,QACC,KAAA,EAAO,IAAA;AAAA,QACP,UAAU,CAAC,CAAA,KAA8C,OAAA,CAAQ,CAAA,CAAE,OAAO,KAAK,CAAA;AAAA,QAC/E,WAAA,EAAY,qDAAA;AAAA,QACZ,IAAA,EAAM;AAAA;AAAA,KACR;AAAA,oBACA,IAAA,CAAC,GAAA,EAAA,EAAE,SAAA,EAAU,+BAAA,EAAgC,QAAA,EAAA;AAAA,MAAA,aAAA;AAAA,MAAY,wBAAA;AAAA,MAAyB;AAAA,KAAA,EAAY,CAAA;AAAA,yBAC7F,WAAA,EAAA,EACC,QAAA,EAAA;AAAA,sBAAA,GAAA,CAAC,UAAO,OAAA,EAAQ,SAAA,EAAU,SAAS,OAAA,EAAS,QAAA,EAAU,SAAS,QAAA,EAAA,QAAA,EAAM,CAAA;AAAA,sBACrE,GAAA,CAAC,MAAA,EAAA,EAAO,OAAA,EAAQ,aAAA,EAAc,SAAS,MAAM,KAAK,IAAA,EAAK,EAAG,UAAU,CAAC,EAAA,IAAM,OAAA,EAAU,QAAA,EAAA,OAAA,GAAU,qBAAgB,eAAA,EAAgB;AAAA,KAAA,EACjI;AAAA,GAAA,EACF,CAAA,EACF,CAAA;AAEJ","file":"chunk-SSPDH22E.js","sourcesContent":["import React from 'react'\nimport {\n Badge, Button, Modal, ModalContent, ModalDescription, ModalFooter, ModalHeader, ModalTitle, Skeleton, Textarea, toast,\n} from '@fayz-ai/ui'\nimport { OrderDetailBlock } from '@fayz-ai/admin'\nimport { tl } from '@fayz-ai/core'\nimport { AlertCircle, Download, FileText, Info, Loader2, RefreshCw } from 'lucide-react'\nimport {\n CANCEL_MIN_JUSTIFICATION, NOTE_STATUS_LABEL, noteErrorSentence, optionSentence, orderNotes,\n type IssueOptions, type NoteModel, type OrderNote,\n} from '../lib/notes'\nimport { MODEL_LABEL } from '../lib/issued-note'\n\n/**\n * The order's fiscal note (control-sdk-backend ADR 0008), drawn in the order\n * screens' `order.detail.fiscal` slot. Issuing is a click, never automatic\n * (V1), and the operator picks the model: \"Emitir NF-e\" for a company buyer\n * (model 55, the DANFE it books), \"Emitir NFC-e\" for a consumer. The\n * integration service builds the note and answers what is missing when it\n * cannot; it also says, before the click, when the order cannot take an NF-e\n * (a customer without a CNPJ), and the card shows that reason under a greyed\n * button. While a note is processing the card reads it again at the V1's\n * intervals.\n */\n\n/** Seconds between reads while a note is processing (V1, fiscalIssuance.ts). */\nconst POLL_DELAYS = [3, 5, 8, 12, 20, 20]\n\nconst tone = (status: OrderNote['status']) =>\n status === 'authorized' ? 'border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400'\n : status === 'rejected' || status === 'error' ? 'border-destructive/40 bg-destructive/10 text-destructive'\n : 'text-muted-foreground'\n\nasync function openFile(blob: Blob, fileName: string, download: boolean) {\n const url = URL.createObjectURL(blob)\n if (download) {\n const a = document.createElement('a')\n a.href = url\n a.download = fileName\n a.click()\n } else {\n window.open(url, '_blank', 'noopener')\n }\n setTimeout(() => URL.revokeObjectURL(url), 60_000)\n}\n\nexport function OrderNoteCard({ orderId }: { orderId?: string }) {\n const [notes, setNotes] = React.useState<OrderNote[] | null>(null)\n const [options, setOptions] = React.useState<IssueOptions | null>(null)\n const [error, setError] = React.useState<string | null>(null)\n const [issuing, setIssuing] = React.useState<NoteModel | null>(null)\n const [cancelling, setCancelling] = React.useState<OrderNote | null>(null)\n\n const load = React.useCallback(async () => {\n if (!orderId) return\n try {\n const r = await orderNotes.list(orderId)\n setNotes(r.notes)\n setOptions(r.options)\n setError(null)\n } catch (e) {\n setError(noteErrorSentence(e))\n }\n }, [orderId])\n React.useEffect(() => { void load() }, [load])\n\n // Read a processing note again until PlugNotas settles it, or the delays run out.\n const processing = notes?.find((n) => n.status === 'processing' || n.cancellation === 'processing')\n React.useEffect(() => {\n if (!processing) return\n let alive = true\n let step = 0\n let timer: ReturnType<typeof setTimeout>\n const tick = async () => {\n if (!alive || step >= POLL_DELAYS.length) return\n timer = setTimeout(async () => {\n step++\n try {\n const fresh = await orderNotes.read(processing.documentId)\n if (!alive) return\n setNotes((list) => list?.map((n) => (n.documentId === fresh.documentId ? fresh : n)) ?? null)\n const label = MODEL_LABEL[fresh.model]\n if (fresh.status === 'processing' || fresh.cancellation === 'processing') void tick()\n else if (fresh.status === 'authorized' && !fresh.cancellation) toast.success(tl(`${label} no. ${fresh.number ?? ''} authorized`, `${label} nº ${fresh.number ?? ''} autorizada`))\n else if (fresh.status === 'rejected') toast.error(tl(`The SEFAZ rejected the ${label}`, `A SEFAZ rejeitou a ${label}`), { description: fresh.rejection?.message ?? undefined })\n } catch {\n void tick()\n }\n }, POLL_DELAYS[step]! * 1000)\n }\n void tick()\n return () => { alive = false; clearTimeout(timer) }\n }, [processing?.documentId, processing?.status, processing?.cancellation])\n\n if (!orderId) return null\n\n // The newest attempt is what the order's note IS; the older ones are history.\n const current = notes?.[0] ?? null\n const earlier = notes?.slice(1) ?? []\n const failed = current?.status === 'rejected' || current?.status === 'error'\n // One sale, one note: a new one only when there is none, or the last failed or was cancelled.\n const canIssue = notes !== null && !error && (!current || failed || current.status === 'cancelled')\n const nfeWhyNot = optionSentence(options?.nfe)\n // A company buyer is what NF-e is for: then it is the main button.\n const nfeFirst = options?.nfe.available === true\n\n const issue = async (model: NoteModel) => {\n const label = MODEL_LABEL[model]\n setIssuing(model)\n try {\n const note = await orderNotes.issue(orderId, model)\n setNotes((list) => [note, ...(list ?? [])])\n if (note.status === 'rejected') toast.error(tl(`The ${label} was refused`, `A ${label} foi recusada`), { description: reasonOf(note) ?? undefined })\n else toast.success(tl(`${label} sent. Waiting for the SEFAZ…`, `${label} enviada. Aguardando a SEFAZ…`))\n } catch (e) {\n toast.error(tl(`Could not issue the ${label}`, `Não foi possível emitir a ${label}`), { description: noteErrorSentence(e) })\n } finally {\n setIssuing(null)\n }\n }\n\n const button = (model: NoteModel, primary: boolean) => {\n const label = MODEL_LABEL[model]\n const blocked = model === 'nfe' && options?.nfe.available === false\n return (\n <Button key={model} size=\"sm\" variant={primary ? 'default' : 'outline'} onClick={() => void issue(model)}\n disabled={issuing !== null || blocked} title={blocked ? nfeWhyNot ?? undefined : undefined}>\n <FileText className=\"mr-1.5 h-4 w-4\" />\n {issuing === model ? tl('Issuing…', 'Emitindo…') : tl(`Issue ${label}`, `Emitir ${label}`)}\n </Button>\n )\n }\n\n return (\n <OrderDetailBlock\n title={tl('Invoice', 'Nota fiscal')}\n actions={canIssue ? (\n <div className=\"flex flex-wrap justify-end gap-2\">\n {nfeFirst ? [button('nfe', true), button('nfce', false)] : [button('nfce', true), button('nfe', false)]}\n </div>\n ) : undefined}\n >\n {canIssue && nfeWhyNot && (\n <p className=\"mb-2 flex items-start gap-1.5 text-xs text-muted-foreground\">\n <Info className=\"mt-0.5 h-3.5 w-3.5 shrink-0\" />\n <span>{nfeWhyNot}</span>\n </p>\n )}\n {error && (\n <div className=\"flex items-center justify-between gap-3 text-sm\">\n <span className=\"text-muted-foreground\">{error}</span>\n <Button variant=\"ghost\" size=\"sm\" onClick={() => void load()}><RefreshCw className=\"h-4 w-4\" /></Button>\n </div>\n )}\n {!error && notes === null && <Skeleton className=\"h-10 w-full\" />}\n {!error && current === null && notes !== null && <p className=\"text-sm text-muted-foreground\">{tl('No invoice issued for this order.', 'Nenhuma nota emitida para este pedido.')}</p>}\n\n {!error && current && (current.status === 'processing') && (\n <div className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <Loader2 className=\"h-4 w-4 animate-spin\" />\n {current.uncertain ? tl('Waiting for the SEFAZ answer…', 'Aguardando a resposta da SEFAZ…') : tl(`Sending the ${MODEL_LABEL[current.model]} to the SEFAZ…`, `Enviando a ${MODEL_LABEL[current.model]} à SEFAZ…`)}\n </div>\n )}\n\n {!error && current && failed && (\n <div className=\"space-y-2 rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm\">\n <p className=\"flex items-center gap-1.5 font-medium text-destructive\">\n <AlertCircle className=\"h-4 w-4\" />\n {current.status === 'rejected'\n ? tl(`The SEFAZ refused the ${MODEL_LABEL[current.model]}`, `A SEFAZ recusou a ${MODEL_LABEL[current.model]}`)\n : tl(`Could not issue the ${MODEL_LABEL[current.model]}`, `Não foi possível emitir a ${MODEL_LABEL[current.model]}`)}\n </p>\n {reasonOf(current) && <p>{reasonOf(current)}</p>}\n <p className=\"text-xs text-muted-foreground\">\n {tl('No invoice was issued, so there is nothing to cancel. Fix the reason and issue again above.',\n 'Nenhuma nota foi emitida: não há o que cancelar. Corrija o motivo e emita de novo acima.')}\n </p>\n </div>\n )}\n\n {!error && current && (current.status === 'authorized' || current.status === 'cancelled' || current.status === 'substituted') && (\n <NoteDetails note={current} onCancel={() => setCancelling(current)} />\n )}\n\n {!error && earlier.length > 0 && (\n <details className=\"mt-3 text-xs text-muted-foreground\">\n <summary className=\"cursor-pointer select-none\">{tl(`Earlier attempts (${earlier.length})`, `Tentativas anteriores (${earlier.length})`)}</summary>\n <ul className=\"mt-2 space-y-1.5\">\n {earlier.map((n) => (\n <li key={n.documentId} className=\"flex flex-wrap items-baseline gap-x-2\">\n <span>{new Date(n.createdAt).toLocaleString('pt-BR', { dateStyle: 'short', timeStyle: 'short' })}</span>\n <span className=\"font-medium\">{MODEL_LABEL[n.model]} · {NOTE_STATUS_LABEL[n.status]}</span>\n {n.status === 'authorized' || n.status === 'cancelled' ? <span>nº {n.number} · {tl('series', 'série')} {n.series}</span> : null}\n {reasonOf(n) && <span className=\"basis-full\">{reasonOf(n)}</span>}\n </li>\n ))}\n </ul>\n </details>\n )}\n\n {cancelling && (\n <CancelDialog\n note={cancelling}\n onClose={() => setCancelling(null)}\n onDone={(fresh) => { setNotes((list) => list?.map((x) => (x.documentId === fresh.documentId ? fresh : x)) ?? null); setCancelling(null) }}\n />\n )}\n </OrderDetailBlock>\n )\n}\n\n/** The SEFAZ reason as a sentence: without its \"Rejeição:\" prefix, first letter up. */\nfunction reasonOf(n: OrderNote): string | null {\n const raw = n.rejection?.message?.trim()\n if (!raw) return null\n const text = raw.replace(/^rejei[cç][aã]o\\s*:?\\s*/i, '').trim()\n return text ? text.charAt(0).toUpperCase() + text.slice(1) : null\n}\n\n/** An issued note: number, key, when, and what can be done with it. */\nfunction NoteDetails({ note, onCancel }: { note: OrderNote; onCancel: () => void }) {\n const at = note.authorizedAt ? new Date(note.authorizedAt).toLocaleString('pt-BR', { dateStyle: 'short', timeStyle: 'short' }) : null\n return (\n <div className=\"space-y-1.5 text-sm\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <span className=\"font-medium\">{MODEL_LABEL[note.model]} nº {note.number} · {tl('series', 'série')} {note.series}</span>\n <Badge variant=\"outline\" className={tone(note.status)}>{note.cancellation === 'processing' ? 'Cancelando…' : NOTE_STATUS_LABEL[note.status]}</Badge>\n {note.environment === 'homologation' && <Badge variant=\"outline\" className=\"text-muted-foreground\">Homologação</Badge>}\n </div>\n {at && <p className=\"text-xs text-muted-foreground\">Autorizada em {at}</p>}\n {note.accessKey && <p className=\"break-all font-mono text-xs text-muted-foreground\">{note.accessKey.replace(/(\\d{4})(?=\\d)/g, '$1 ')}</p>}\n {note.status === 'cancelled' && note.cancelReason && <p className=\"text-xs text-muted-foreground\">Cancelada: {note.cancelReason}</p>}\n <div className=\"flex flex-wrap gap-2 pt-1\">\n <Button variant=\"outline\" size=\"sm\" onClick={() => void orderNotes.pdf(note.documentId).then((b) => openFile(b, `${note.model}-${note.number ?? note.documentId}.pdf`, false)).catch((e) => toast.error('Não foi possível abrir o DANFE', { description: noteErrorSentence(e) }))}>\n <FileText className=\"mr-1.5 h-4 w-4\" />DANFE\n </Button>\n <Button variant=\"outline\" size=\"sm\" onClick={() => void orderNotes.xml(note.documentId).then((b) => openFile(b, `${note.model}-${note.number ?? note.documentId}.xml`, true)).catch((e) => toast.error('Não foi possível baixar o XML', { description: noteErrorSentence(e) }))}>\n <Download className=\"mr-1.5 h-4 w-4\" />XML\n </Button>\n {note.status === 'authorized' && !note.cancellation && (\n <Button variant=\"ghost\" size=\"sm\" className=\"text-destructive\" onClick={onCancel}>Cancelar nota</Button>\n )}\n </div>\n </div>\n )\n}\n\nfunction CancelDialog({ note, onClose, onDone }: { note: OrderNote; onClose: () => void; onDone: (n: OrderNote) => void }) {\n const [text, setText] = React.useState('')\n const [sending, setSending] = React.useState(false)\n const ok = text.trim().length >= CANCEL_MIN_JUSTIFICATION\n const send = async () => {\n setSending(true)\n try {\n const fresh = await orderNotes.cancel(note.documentId, text.trim())\n toast.success('Cancelamento enviado. Aguardando a SEFAZ…')\n onDone(fresh)\n } catch (e) {\n toast.error('Não foi possível cancelar a nota', { description: noteErrorSentence(e) })\n } finally {\n setSending(false)\n }\n }\n return (\n <Modal open onOpenChange={(open) => { if (!open) onClose() }}>\n <ModalContent>\n <ModalHeader>\n <ModalTitle>{tl(`Cancel ${MODEL_LABEL[note.model]}`, `Cancelar ${MODEL_LABEL[note.model]}`)}{note.number ? ` nº ${note.number}` : ''}</ModalTitle>\n <ModalDescription>\n {note.model === 'nfe'\n ? tl('The SEFAZ accepts cancelling an NF-e within 24 hours of its authorization. To issue an NFC-e instead, cancel this one first.',\n 'A SEFAZ aceita o cancelamento de uma NF-e em até 24 horas da autorização. Para emitir uma NFC-e no lugar, cancele primeiro esta nota.')\n : tl('The SEFAZ only accepts cancelling an NFC-e right after it is issued (usually 30 minutes). To issue an NF-e instead, cancel this one first.',\n 'A SEFAZ só aceita o cancelamento de uma NFC-e logo depois da emissão (em geral, 30 minutos). Para emitir uma NF-e no lugar, cancele primeiro esta nota.')}\n </ModalDescription>\n </ModalHeader>\n <Textarea\n value={text}\n onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setText(e.target.value)}\n placeholder=\"Ex.: Emissão em duplicidade por erro operacional\"\n rows={3}\n />\n <p className=\"text-xs text-muted-foreground\">Pelo menos {CANCEL_MIN_JUSTIFICATION} caracteres.</p>\n <ModalFooter>\n <Button variant=\"outline\" onClick={onClose} disabled={sending}>Voltar</Button>\n <Button variant=\"destructive\" onClick={() => void send()} disabled={!ok || sending}>{sending ? 'Cancelando…' : 'Cancelar nota'}</Button>\n </ModalFooter>\n </ModalContent>\n </Modal>\n )\n}\n"]}
|
|
@@ -72,7 +72,9 @@ var emitters = {
|
|
|
72
72
|
certificate: async (legalEntityId, file, password) => request("PUT", one(legalEntityId, "/certificate"), { pfxBase64: await base64Of(file), password, fileName: file.name }),
|
|
73
73
|
register: (legalEntityId) => request("PUT", one(legalEntityId, "/registration")),
|
|
74
74
|
/** Issue in parallel with the previous system: adds this app's own NFC-e series, nothing else. */
|
|
75
|
-
addOwnSeries: (legalEntityId) => request("PUT", one(legalEntityId, "/nfce-series"))
|
|
75
|
+
addOwnSeries: (legalEntityId) => request("PUT", one(legalEntityId, "/nfce-series")),
|
|
76
|
+
/** NF-e on a company the previous system manages: the emitter's NF-e series becomes this app's. */
|
|
77
|
+
claimNfeSeries: (legalEntityId) => request("PUT", one(legalEntityId, "/nfe-series"))
|
|
76
78
|
};
|
|
77
79
|
var TAX_REGIMES = [
|
|
78
80
|
{ value: 1, label: "Simples Nacional" },
|
|
@@ -97,5 +99,5 @@ var SPECIAL_TAX_REGIMES = [
|
|
|
97
99
|
];
|
|
98
100
|
|
|
99
101
|
export { GATE_LABELS, SPECIAL_TAX_REGIMES, TAX_REGIMES, emitterErrorSentence, emitters };
|
|
100
|
-
//# sourceMappingURL=chunk-
|
|
101
|
-
//# sourceMappingURL=chunk-
|
|
102
|
+
//# sourceMappingURL=chunk-ZJGXUJKM.js.map
|
|
103
|
+
//# sourceMappingURL=chunk-ZJGXUJKM.js.map
|