@fayz-ai/plugin-fiscal-br 0.15.13 → 0.16.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.
Files changed (46) hide show
  1. package/dist/InvoiceNotesButton-4L7SLYMA.js +6 -0
  2. package/dist/{InvoiceNotesButton-SC3G7FUR.js.map → InvoiceNotesButton-4L7SLYMA.js.map} +1 -1
  3. package/dist/NotasFiscaisView-LU4A65J7.js +6 -0
  4. package/dist/NotasFiscaisView-LU4A65J7.js.map +1 -0
  5. package/dist/OrderNoteCard-NZOVNTR3.js +5 -0
  6. package/dist/{OrderNoteCard-PDSK2AS3.js.map → OrderNoteCard-NZOVNTR3.js.map} +1 -1
  7. package/dist/UnitFiscalWidgets-XSED3WPQ.js +564 -0
  8. package/dist/UnitFiscalWidgets-XSED3WPQ.js.map +1 -0
  9. package/dist/{chunk-ODMEESFD.js → chunk-CWYTWKXW.js} +23 -3
  10. package/dist/chunk-CWYTWKXW.js.map +1 -0
  11. package/dist/chunk-E5TUJOGT.js +644 -0
  12. package/dist/chunk-E5TUJOGT.js.map +1 -0
  13. package/dist/{chunk-SSPDH22E.js → chunk-ITWWGLEV.js} +3 -3
  14. package/dist/{chunk-SSPDH22E.js.map → chunk-ITWWGLEV.js.map} +1 -1
  15. package/dist/chunk-U4TQSVWI.js +269 -0
  16. package/dist/chunk-U4TQSVWI.js.map +1 -0
  17. package/dist/chunk-YSRG5JQI.js +205 -0
  18. package/dist/chunk-YSRG5JQI.js.map +1 -0
  19. package/dist/data/issued.d.ts +97 -0
  20. package/dist/data/issued.d.ts.map +1 -1
  21. package/dist/data/registries.d.ts.map +1 -1
  22. package/dist/index.d.ts +1 -0
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +52 -20
  25. package/dist/index.js.map +1 -1
  26. package/dist/lib/notes.d.ts +35 -1
  27. package/dist/lib/notes.d.ts.map +1 -1
  28. package/dist/migrations/index.d.ts +4 -0
  29. package/dist/migrations/index.d.ts.map +1 -1
  30. package/dist/migrations/main.browser.js +5 -1
  31. package/dist/migrations/main.browser.js.map +1 -1
  32. package/dist/migrations/main.js +400 -2
  33. package/dist/migrations/main.js.map +1 -1
  34. package/dist/views/InvoiceNotesButton.d.ts.map +1 -1
  35. package/dist/views/NotasFiscaisView.d.ts +4 -0
  36. package/dist/views/NotasFiscaisView.d.ts.map +1 -0
  37. package/dist/views/UnitFiscalWidgets.d.ts +6 -4
  38. package/dist/views/UnitFiscalWidgets.d.ts.map +1 -1
  39. package/package.json +5 -5
  40. package/dist/InvoiceNotesButton-SC3G7FUR.js +0 -5
  41. package/dist/OrderNoteCard-PDSK2AS3.js +0 -5
  42. package/dist/UnitFiscalWidgets-K4PX3HWG.js +0 -503
  43. package/dist/UnitFiscalWidgets-K4PX3HWG.js.map +0 -1
  44. package/dist/chunk-F325US5P.js +0 -387
  45. package/dist/chunk-F325US5P.js.map +0 -1
  46. package/dist/chunk-ODMEESFD.js.map +0 -1
@@ -0,0 +1,6 @@
1
+ export { InvoiceNotesButton } from './chunk-E5TUJOGT.js';
2
+ import './chunk-U4TQSVWI.js';
3
+ import './chunk-CWYTWKXW.js';
4
+ import './chunk-2GHTB3Z2.js';
5
+ //# sourceMappingURL=InvoiceNotesButton-4L7SLYMA.js.map
6
+ //# sourceMappingURL=InvoiceNotesButton-4L7SLYMA.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"InvoiceNotesButton-SC3G7FUR.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"InvoiceNotesButton-4L7SLYMA.js"}
@@ -0,0 +1,6 @@
1
+ export { NotasFiscaisView } from './chunk-YSRG5JQI.js';
2
+ import './chunk-U4TQSVWI.js';
3
+ import './chunk-CWYTWKXW.js';
4
+ import './chunk-2GHTB3Z2.js';
5
+ //# sourceMappingURL=NotasFiscaisView-LU4A65J7.js.map
6
+ //# sourceMappingURL=NotasFiscaisView-LU4A65J7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"NotasFiscaisView-LU4A65J7.js"}
@@ -0,0 +1,5 @@
1
+ export { OrderNoteCard } from './chunk-ITWWGLEV.js';
2
+ import './chunk-CWYTWKXW.js';
3
+ import './chunk-2GHTB3Z2.js';
4
+ //# sourceMappingURL=OrderNoteCard-NZOVNTR3.js.map
5
+ //# sourceMappingURL=OrderNoteCard-NZOVNTR3.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"OrderNoteCard-PDSK2AS3.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"OrderNoteCard-NZOVNTR3.js"}
@@ -0,0 +1,564 @@
1
+ import { emitters, GATE_LABELS, emitterErrorSentence } from './chunk-ZJGXUJKM.js';
2
+ import { EmitterError } from './chunk-2GHTB3Z2.js';
3
+ import React from 'react';
4
+ import { Card, CardHeader, CardTitle, CardDescription, Button, CardContent, Badge, Input, toast, SegmentedControl, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, Skeleton, Switch } from '@fayz-ai/ui';
5
+ import { maskCpfCnpj, getSupabaseClientOptional } from '@fayz-ai/core';
6
+ import { adminNavigateTo } from '@fayz-ai/admin';
7
+ import { ShieldCheck, ChevronUp, ChevronDown, Check, X } from 'lucide-react';
8
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
9
+
10
+ var COLUMNS = [
11
+ "id",
12
+ "legal_entity_id",
13
+ "nfse_enabled",
14
+ "nfse_production",
15
+ "nfse_national",
16
+ "nfse_service_code_national",
17
+ "nfse_service_code_municipal",
18
+ "nfse_nbs_code",
19
+ "nfse_cnae",
20
+ "nfse_iss_rate",
21
+ "nfse_iss_taxation",
22
+ "nfse_ibscbs_cst",
23
+ "nfse_ibscbs_classification",
24
+ "nfse_simples_regime",
25
+ "nfse_net_value",
26
+ "nfse_additional_info",
27
+ "nfce_enabled",
28
+ "nfce_production",
29
+ "nfce_series",
30
+ "nfce_csc_id",
31
+ "nfce_csc_token_set",
32
+ "nfce_generic_item",
33
+ "certificate_cn",
34
+ "certificate_expires_at",
35
+ "certificate_uploaded_at",
36
+ "dfe_sync_enabled",
37
+ "dfe_last_sync_at",
38
+ "dfe_last_error",
39
+ "provider_synced_at"
40
+ ].join(", ");
41
+ var sb = () => getSupabaseClientOptional();
42
+ async function uploadCertificate(legalEntityId, file, password) {
43
+ try {
44
+ const emitter = await emitters.certificate(legalEntityId, file, password);
45
+ return { cn: emitter.certificate?.holder ?? "", expiresAt: emitter.certificate?.expiresAt ?? "", warning: null };
46
+ } catch (error) {
47
+ throw new Error(emitterErrorSentence(error));
48
+ }
49
+ }
50
+ function useResolvedLegalEntityId(item) {
51
+ const direct = item?.legalEntityId || null;
52
+ const unitId = item?.id;
53
+ const [resolved, setResolved] = React.useState(direct || void 0);
54
+ React.useEffect(() => {
55
+ if (direct) {
56
+ setResolved(direct);
57
+ return;
58
+ }
59
+ if (!unitId) {
60
+ setResolved(null);
61
+ return;
62
+ }
63
+ let alive = true;
64
+ void sb()?.from("v_units").select("legal_entity_id").eq("id", unitId).maybeSingle().then(({ data }) => {
65
+ if (alive) setResolved(data?.legal_entity_id ?? null);
66
+ }).catch(() => {
67
+ if (alive) setResolved(null);
68
+ });
69
+ return () => {
70
+ alive = false;
71
+ };
72
+ }, [direct, unitId]);
73
+ return resolved;
74
+ }
75
+ function useCnaeSuggestions(cnpj) {
76
+ const [opts, setOpts] = React.useState([]);
77
+ React.useEffect(() => {
78
+ const d = (cnpj ?? "").replace(/\D/g, "");
79
+ if (d.length !== 14) {
80
+ setOpts([]);
81
+ return;
82
+ }
83
+ const fmt = (c) => {
84
+ const s = String(c).replace(/\D/g, "").padStart(7, "0");
85
+ return `${s.slice(0, 4)}-${s.slice(4, 5)}/${s.slice(5, 7)}`;
86
+ };
87
+ let alive = true;
88
+ void fetch(`https://brasilapi.com.br/api/cnpj/v1/${d}`).then((r) => r.ok ? r.json() : null).then((data) => {
89
+ if (!alive || !data) return;
90
+ const list = [];
91
+ if (data.cnae_fiscal) list.push({ code: fmt(data.cnae_fiscal), label: `${fmt(data.cnae_fiscal)} \u2014 ${data.cnae_fiscal_descricao ?? ""}`.trim() });
92
+ for (const s of data.cnaes_secundarios ?? []) if (s?.codigo) list.push({ code: fmt(s.codigo), label: `${fmt(s.codigo)} \u2014 ${s.descricao ?? ""}`.trim() });
93
+ setOpts(list);
94
+ }).catch(() => {
95
+ });
96
+ return () => {
97
+ alive = false;
98
+ };
99
+ }, [cnpj]);
100
+ return opts;
101
+ }
102
+ function useEmitterSettings(legalEntityId) {
103
+ const [row, setRow] = React.useState(null);
104
+ const [loading, setLoading] = React.useState(true);
105
+ React.useEffect(() => {
106
+ if (!legalEntityId) {
107
+ setLoading(false);
108
+ return;
109
+ }
110
+ let alive = true;
111
+ void sb()?.from("plg_fiscalbr_emitter_settings").select(COLUMNS).eq("legal_entity_id", legalEntityId).maybeSingle().then(({ data, error }) => {
112
+ if (!alive) return;
113
+ if (error) toast.error("N\xE3o foi poss\xEDvel ler a configura\xE7\xE3o fiscal", { description: error.message });
114
+ setRow(data ?? {});
115
+ setLoading(false);
116
+ });
117
+ return () => {
118
+ alive = false;
119
+ };
120
+ }, [legalEntityId]);
121
+ const save = React.useCallback(async (tenantId, patch) => {
122
+ if (!legalEntityId) return false;
123
+ const payload = { ...patch, tenant_id: tenantId, legal_entity_id: legalEntityId, updated_at: (/* @__PURE__ */ new Date()).toISOString() };
124
+ const { data, error } = await sb().from("plg_fiscalbr_emitter_settings").upsert(payload, { onConflict: "legal_entity_id" }).select(COLUMNS).single();
125
+ if (error) {
126
+ toast.error("N\xE3o foi poss\xEDvel salvar", { description: error.message });
127
+ return false;
128
+ }
129
+ setRow(data);
130
+ return true;
131
+ }, [legalEntityId]);
132
+ return { row, loading, save, setRow };
133
+ }
134
+ function NeedsLegalEntity({ item, what }) {
135
+ return /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "flex flex-col items-start gap-3 py-6", children: [
136
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: "Falta o CNPJ desta unidade" }),
137
+ /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
138
+ what,
139
+ " pertence \xE0 pessoa jur\xEDdica. Preencha a raz\xE3o social e o CNPJ em Dados da empresa para configurar aqui."
140
+ ] }),
141
+ /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => adminNavigateTo(`/settings/locations/${item.id}/edit`), children: "Preencher CNPJ" })
142
+ ] }) });
143
+ }
144
+ function LoadingCard() {
145
+ return /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "space-y-3 py-6", children: [
146
+ /* @__PURE__ */ jsx(Skeleton, { className: "h-5 w-48" }),
147
+ /* @__PURE__ */ jsx(Skeleton, { className: "h-10 w-full" }),
148
+ /* @__PURE__ */ jsx(Skeleton, { className: "h-10 w-full" })
149
+ ] }) });
150
+ }
151
+ function ToggleRow({ title, description, checked, onChange, disabled, children }) {
152
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-4", children: [
153
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
154
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: title }),
155
+ description && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: description })
156
+ ] }),
157
+ /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2", children: [
158
+ children,
159
+ /* @__PURE__ */ jsx(Switch, { checked, disabled, onCheckedChange: onChange })
160
+ ] })
161
+ ] });
162
+ }
163
+ function Field({ label, hint, children }) {
164
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
165
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: label }),
166
+ children,
167
+ hint && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: hint })
168
+ ] });
169
+ }
170
+ function SummaryCard({ title, lines, badge, onConfigure }) {
171
+ return /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardHeader, { className: "flex-row items-start justify-between gap-3 space-y-0", children: [
172
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
173
+ /* @__PURE__ */ jsx(CardTitle, { className: "text-base", children: title }),
174
+ /* @__PURE__ */ jsx("dl", { className: "mt-2 grid gap-x-6 gap-y-1 text-sm", style: { gridTemplateColumns: "auto 1fr" }, children: lines.map((l) => /* @__PURE__ */ jsxs(React.Fragment, { children: [
175
+ /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: l.label }),
176
+ /* @__PURE__ */ jsx("dd", { className: "text-foreground", children: l.value })
177
+ ] }, l.label)) })
178
+ ] }),
179
+ /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2", children: [
180
+ badge && /* @__PURE__ */ jsx(
181
+ Badge,
182
+ {
183
+ variant: badge.tone === "bad" ? "destructive" : "outline",
184
+ className: badge.tone === "ok" ? "border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400" : badge.tone === "muted" ? "text-muted-foreground" : void 0,
185
+ children: badge.text
186
+ }
187
+ ),
188
+ /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: onConfigure, children: "Configurar" })
189
+ ] })
190
+ ] }) });
191
+ }
192
+ var ISS_TAXATION = [
193
+ { value: "6", label: "Tribut\xE1vel no munic\xEDpio" },
194
+ { value: "7", label: "Tribut\xE1vel fora do munic\xEDpio" },
195
+ { value: "1", label: "Isento" },
196
+ { value: "2", label: "Imune" }
197
+ ];
198
+ var SIMPLES_REGIME = [
199
+ { value: "auto", label: "Autom\xE1tico (1 \u2014 tudo pelo Simples; excesso \u2192 3)" },
200
+ { value: "1", label: "1 \u2014 Federais e ISS pelo Simples (DAS)" },
201
+ { value: "2", label: "2 \u2014 Federais pelo Simples; ISS pela NFS-e (lei municipal)" },
202
+ { value: "3", label: "3 \u2014 Federais e ISS fora do Simples (sublimite)" }
203
+ ];
204
+ function EnvSelect({ value, onChange, disabled }) {
205
+ return /* @__PURE__ */ jsxs(Select, { value: value ? "prod" : "hom", onValueChange: (v) => onChange(v === "prod"), disabled, children: [
206
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "h-8 w-36", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
207
+ /* @__PURE__ */ jsxs(SelectContent, { children: [
208
+ /* @__PURE__ */ jsx(SelectItem, { value: "hom", children: "Homologa\xE7\xE3o" }),
209
+ /* @__PURE__ */ jsx(SelectItem, { value: "prod", children: "Produ\xE7\xE3o" })
210
+ ] })
211
+ ] });
212
+ }
213
+ function UnitFiscalCard({ item }) {
214
+ const legalEntityId = useResolvedLegalEntityId(item);
215
+ const { row, loading, save, setRow } = useEmitterSettings(legalEntityId ?? null);
216
+ const [open, setOpen] = React.useState(false);
217
+ const [file, setFile] = React.useState(null);
218
+ const [password, setPassword] = React.useState("");
219
+ const [sending, setSending] = React.useState(false);
220
+ const [changingCert, setChangingCert] = React.useState(false);
221
+ const [draft, setDraft] = React.useState({});
222
+ const [cscToken, setCscToken] = React.useState("");
223
+ const [saving, setSaving] = React.useState(false);
224
+ const [registering, setRegistering] = React.useState(false);
225
+ const [missing, setMissing] = React.useState([]);
226
+ const [showEmission, setShowEmission] = React.useState(false);
227
+ const [nfseTab, setNfseTab] = React.useState("servico");
228
+ const cnaeOptions = useCnaeSuggestions(item?.cnpj);
229
+ React.useEffect(() => {
230
+ if (row) setDraft(row);
231
+ }, [row]);
232
+ const expiredNow = !!row?.certificate_expires_at && Date.parse(row.certificate_expires_at) < Date.now();
233
+ React.useEffect(() => {
234
+ if (expiredNow) setOpen(true);
235
+ }, [expiredNow]);
236
+ React.useEffect(() => {
237
+ if (open && (row?.nfse_enabled || row?.nfce_enabled)) setShowEmission(true);
238
+ }, [open, row]);
239
+ if (!item?.id) return null;
240
+ if (legalEntityId === void 0) return /* @__PURE__ */ jsx(LoadingCard, {});
241
+ if (!legalEntityId) return /* @__PURE__ */ jsx(NeedsLegalEntity, { item, what: "A nota fiscal" });
242
+ if (loading || !row) return /* @__PURE__ */ jsx(LoadingCard, {});
243
+ const expires = row.certificate_expires_at ? new Date(row.certificate_expires_at) : null;
244
+ const expired = expires ? expires.getTime() < Date.now() : false;
245
+ const hasCertificate = !!row.certificate_uploaded_at;
246
+ const set = (patch) => setDraft((d) => ({ ...d, ...patch }));
247
+ const generic = draft.nfce_generic_item ?? {};
248
+ const setGeneric = (patch) => set({ nfce_generic_item: { ...generic, ...patch } });
249
+ const isSimples = (item.taxRegime ?? "").startsWith("simples");
250
+ const checks = [
251
+ { ok: !!row.certificate_uploaded_at && !(row.certificate_expires_at && Date.parse(row.certificate_expires_at) < Date.now()), label: "Certificado A1 v\xE1lido" },
252
+ // Only what the switched-on documents need: NFS-e off does not block a restaurant that issues NFC-e.
253
+ ...draft.nfse_enabled ? [
254
+ { ok: !!draft.nfse_service_code_national, label: "C\xF3digo de tributa\xE7\xE3o do servi\xE7o" },
255
+ { ok: draft.nfse_iss_rate != null && draft.nfse_iss_rate !== "", label: "Al\xEDquota de ISS" }
256
+ ] : [],
257
+ ...draft.nfce_enabled ? [
258
+ { ok: !!item.stateRegistration && !!draft.nfce_csc_id && (!!row.nfce_csc_token_set || !!cscToken), label: "IE + CSC (NFC-e)" }
259
+ ] : [],
260
+ { ok: !!row.provider_synced_at, label: "Empresa registrada para emitir" }
261
+ ];
262
+ const ready = (draft.nfse_enabled || draft.nfce_enabled) && checks.every((c) => c.ok);
263
+ const saveNfce = async () => {
264
+ const cscIdDigits = String(draft.nfce_csc_id ?? "").replace(/\D/g, "");
265
+ try {
266
+ await emitters.save(legalEntityId, {
267
+ nfce: {
268
+ enabled: !!draft.nfce_enabled,
269
+ production: !!draft.nfce_production,
270
+ series: draft.nfce_series ? Number(draft.nfce_series) : null,
271
+ ...cscIdDigits ? { cscId: cscIdDigits } : {},
272
+ ...cscToken ? { cscToken } : {}
273
+ }
274
+ });
275
+ return true;
276
+ } catch (error) {
277
+ toast.error("N\xE3o foi poss\xEDvel salvar a NFC-e", { description: emitterErrorSentence(error) });
278
+ return false;
279
+ }
280
+ };
281
+ const onSave = async () => {
282
+ setSaving(true);
283
+ if (!await saveNfce()) {
284
+ setSaving(false);
285
+ return;
286
+ }
287
+ const {
288
+ id: _id,
289
+ legal_entity_id: _le,
290
+ nfce_csc_token_set: _t,
291
+ certificate_cn: _cn,
292
+ certificate_expires_at: _e,
293
+ certificate_uploaded_at: _u,
294
+ dfe_last_sync_at: _d,
295
+ provider_synced_at: _p,
296
+ nfce_enabled: _ne,
297
+ nfce_production: _np,
298
+ nfce_series: _ns,
299
+ nfce_csc_id: _nc,
300
+ ...patch
301
+ } = draft;
302
+ const issRate = patch.nfse_iss_rate === "" || patch.nfse_iss_rate == null ? null : Number(String(patch.nfse_iss_rate).replace(",", "."));
303
+ const ok = await save(item.tenantId, {
304
+ ...patch,
305
+ nfse_iss_rate: Number.isFinite(issRate) ? issRate : null,
306
+ nfse_iss_taxation: patch.nfse_iss_taxation ? Number(patch.nfse_iss_taxation) : null,
307
+ nfse_simples_regime: patch.nfse_simples_regime && patch.nfse_simples_regime !== "auto" ? Number(patch.nfse_simples_regime) : null
308
+ });
309
+ setSaving(false);
310
+ if (ok) {
311
+ setCscToken("");
312
+ setOpen(false);
313
+ toast.success("Configura\xE7\xE3o fiscal salva");
314
+ }
315
+ };
316
+ const onRegister = async () => {
317
+ setRegistering(true);
318
+ setMissing([]);
319
+ try {
320
+ if (!await saveNfce()) return;
321
+ const after = await emitters.register(legalEntityId);
322
+ setRow((r) => ({ ...r ?? {}, provider_synced_at: after.providerSyncedAt }));
323
+ toast.success("Empresa cadastrada na PlugNotas");
324
+ } catch (error) {
325
+ if (error instanceof EmitterError) setMissing(error.gates.filter((g) => !g.ok).map((g) => GATE_LABELS[g.id] ?? g.id));
326
+ toast.error("N\xE3o foi poss\xEDvel cadastrar na PlugNotas", { description: emitterErrorSentence(error) });
327
+ } finally {
328
+ setRegistering(false);
329
+ }
330
+ };
331
+ if (!open) {
332
+ const env = (prod) => prod ? "Produ\xE7\xE3o" : "Homologa\xE7\xE3o";
333
+ const emissionLine = row.nfse_enabled || row.nfce_enabled ? [row.nfse_enabled ? `NFS-e ${env(!!row.nfse_production).toLowerCase()}` : null, row.nfce_enabled ? `NFC-e ${env(!!row.nfce_production).toLowerCase()}` : null].filter(Boolean).join(" \xB7 ") : "Desligada";
334
+ return /* @__PURE__ */ jsx(
335
+ SummaryCard,
336
+ {
337
+ title: "Nota fiscal",
338
+ lines: [
339
+ { label: "Certificado A1", value: hasCertificate ? [row.certificate_cn, expires ? `v\xE1lido at\xE9 ${expires.toLocaleDateString("pt-BR")}` : null].filter(Boolean).join(" \xB7 ") || "Enviado" : "Nenhum certificado enviado" },
340
+ { label: "Emiss\xE3o", value: emissionLine }
341
+ ],
342
+ badge: hasCertificate ? { text: expired ? "Vencido" : "Ativo", tone: expired ? "bad" : "ok" } : { text: "Sem certificado", tone: "muted" },
343
+ onConfigure: () => setOpen(true)
344
+ }
345
+ );
346
+ }
347
+ return /* @__PURE__ */ jsxs(Card, { children: [
348
+ /* @__PURE__ */ jsxs(CardHeader, { className: "flex-row items-start justify-between gap-3 space-y-0", children: [
349
+ /* @__PURE__ */ jsxs("div", { children: [
350
+ /* @__PURE__ */ jsx(CardTitle, { className: "text-base", children: "Nota fiscal" }),
351
+ /* @__PURE__ */ jsxs(CardDescription, { children: [
352
+ item.legalName ?? "Pessoa jur\xEDdica",
353
+ item.cnpj ? ` \xB7 CNPJ ${maskCpfCnpj(item.cnpj)}` : ""
354
+ ] })
355
+ ] }),
356
+ /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", onClick: () => {
357
+ setDraft(row);
358
+ setCscToken("");
359
+ setOpen(false);
360
+ }, children: "Fechar" })
361
+ ] }),
362
+ /* @__PURE__ */ jsxs(CardContent, { className: "space-y-5", children: [
363
+ /* @__PURE__ */ jsxs("section", { className: "space-y-4 rounded-md border p-4", children: [
364
+ /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
365
+ /* @__PURE__ */ jsxs("div", { children: [
366
+ /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-1.5 text-sm font-medium", children: [
367
+ /* @__PURE__ */ jsx(ShieldCheck, { className: "h-4 w-4" }),
368
+ " Certificado digital A1"
369
+ ] }),
370
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: hasCertificate ? [row.certificate_cn, expires ? `v\xE1lido at\xE9 ${expires.toLocaleDateString("pt-BR")}` : null].filter(Boolean).join(" \xB7 ") : "O arquivo .pfx vai direto ao servi\xE7o fiscal e n\xE3o fica guardado aqui." })
371
+ ] }),
372
+ /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2", children: [
373
+ hasCertificate && /* @__PURE__ */ jsx(Badge, { variant: expired ? "destructive" : "secondary", children: expired ? "Vencido" : "Ativo" }),
374
+ hasCertificate && !changingCert && /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: () => setChangingCert(true), children: "Alterar" })
375
+ ] })
376
+ ] }),
377
+ (!hasCertificate || changingCert) && /* @__PURE__ */ jsxs(Fragment, { children: [
378
+ /* @__PURE__ */ jsx("div", { className: "fz-container", children: /* @__PURE__ */ jsxs("div", { className: "fz-fields fz-fields-2 gap-4", children: [
379
+ /* @__PURE__ */ jsx(Field, { label: "Arquivo (.pfx)", children: /* @__PURE__ */ jsx(
380
+ Input,
381
+ {
382
+ type: "file",
383
+ accept: ".pfx,.p12,application/x-pkcs12",
384
+ "data-testid": "certificate-file",
385
+ onChange: (e) => setFile(e.target.files?.[0] ?? null)
386
+ }
387
+ ) }),
388
+ /* @__PURE__ */ jsx(Field, { label: "Senha do certificado", children: /* @__PURE__ */ jsx(
389
+ Input,
390
+ {
391
+ type: "password",
392
+ autoComplete: "new-password",
393
+ name: "pfx-password",
394
+ value: password,
395
+ "data-testid": "certificate-password",
396
+ onChange: (e) => setPassword(e.target.value)
397
+ }
398
+ ) })
399
+ ] }) }),
400
+ /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2", children: [
401
+ hasCertificate && changingCert && /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", onClick: () => {
402
+ setChangingCert(false);
403
+ setFile(null);
404
+ setPassword("");
405
+ }, children: "Cancelar" }),
406
+ /* @__PURE__ */ jsx(
407
+ Button,
408
+ {
409
+ size: "sm",
410
+ "data-testid": "certificate-send",
411
+ disabled: !file || !password || sending,
412
+ onClick: () => {
413
+ if (!file) return;
414
+ setSending(true);
415
+ void uploadCertificate(legalEntityId, file, password).then(async (res) => {
416
+ setRow((r) => ({
417
+ ...r ?? {},
418
+ certificate_cn: res.cn,
419
+ certificate_expires_at: res.expiresAt,
420
+ certificate_uploaded_at: (/* @__PURE__ */ new Date()).toISOString(),
421
+ dfe_last_error: res.warning ?? null
422
+ }));
423
+ setChangingCert(false);
424
+ if (!row.dfe_sync_enabled) await save(item.tenantId, { dfe_sync_enabled: true });
425
+ setFile(null);
426
+ setPassword("");
427
+ if (res.warning) toast.warning("Certificado enviado, com um aviso", { description: res.warning });
428
+ else toast.success(`Certificado enviado \xB7 v\xE1lido at\xE9 ${new Date(res.expiresAt).toLocaleDateString("pt-BR")}`);
429
+ }).catch((e) => toast.error("N\xE3o foi poss\xEDvel enviar o certificado", { description: e.message })).finally(() => setSending(false));
430
+ },
431
+ children: sending ? "Enviando\u2026" : hasCertificate ? "Atualizar certificado" : "Enviar certificado"
432
+ }
433
+ )
434
+ ] }),
435
+ row.dfe_last_error && /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: row.dfe_last_error })
436
+ ] }),
437
+ /* @__PURE__ */ jsx(
438
+ ToggleRow,
439
+ {
440
+ title: "Receber DANFes automaticamente",
441
+ description: "Busca por hora as NF-e emitidas contra o CNPJ desta empresa. Requer o certificado A1 v\xE1lido.",
442
+ checked: !!row.dfe_sync_enabled,
443
+ onChange: (v) => void save(item.tenantId, { dfe_sync_enabled: v }).then((ok) => ok && toast.success(v ? "Recep\xE7\xE3o ligada" : "Recep\xE7\xE3o desligada"))
444
+ }
445
+ )
446
+ ] }),
447
+ /* @__PURE__ */ jsxs(
448
+ "button",
449
+ {
450
+ type: "button",
451
+ className: "flex w-full items-center justify-between rounded-md border px-4 py-3 text-left text-sm font-medium hover:bg-muted/40",
452
+ "aria-expanded": showEmission,
453
+ onClick: () => setShowEmission((v) => !v),
454
+ children: [
455
+ /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-2", children: [
456
+ "Emiss\xE3o de nota (NFS-e / NFC-e)",
457
+ /* @__PURE__ */ jsx(Badge, { variant: "outline", className: ready ? "border-emerald-500/40 text-emerald-700 dark:text-emerald-400" : "text-muted-foreground", children: ready ? "Pronto para emitir" : "Configura\xE7\xE3o incompleta" })
458
+ ] }),
459
+ showEmission ? /* @__PURE__ */ jsx(ChevronUp, { className: "h-4 w-4 text-muted-foreground" }) : /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4 text-muted-foreground" })
460
+ ]
461
+ }
462
+ ),
463
+ showEmission && /* @__PURE__ */ jsxs(Fragment, { children: [
464
+ /* @__PURE__ */ jsxs("section", { className: "space-y-4 rounded-md border p-4", children: [
465
+ /* @__PURE__ */ jsx(
466
+ ToggleRow,
467
+ {
468
+ title: "NFS-e \u2014 Nota de Servi\xE7o",
469
+ description: "Padr\xE3o nacional (RJ, Vit\xF3ria e demais aderentes)",
470
+ checked: !!draft.nfse_enabled,
471
+ onChange: (v) => set({ nfse_enabled: v }),
472
+ children: /* @__PURE__ */ jsx(EnvSelect, { value: !!draft.nfse_production, onChange: (v) => set({ nfse_production: v }), disabled: !draft.nfse_enabled })
473
+ }
474
+ ),
475
+ draft.nfse_enabled && /* @__PURE__ */ jsxs("div", { className: "fz-container space-y-4", children: [
476
+ /* @__PURE__ */ jsx(
477
+ SegmentedControl,
478
+ {
479
+ size: "sm",
480
+ "aria-label": "Se\xE7\xE3o da NFS-e",
481
+ options: [
482
+ { value: "servico", label: "Servi\xE7o" },
483
+ { value: "iss", label: "ISS" },
484
+ { value: "reforma", label: "Reforma" },
485
+ { value: "nota", label: "Nota" }
486
+ ],
487
+ value: nfseTab,
488
+ onChange: (v) => setNfseTab(v)
489
+ }
490
+ ),
491
+ nfseTab === "servico" && /* @__PURE__ */ jsxs("div", { className: "fz-fields fz-fields-2 gap-4", children: [
492
+ /* @__PURE__ */ jsx(Field, { label: "C\xF3d. tributa\xE7\xE3o nacional", children: /* @__PURE__ */ jsx(Input, { value: draft.nfse_service_code_national ?? "", placeholder: "ex.: 06.02.01", onChange: (e) => set({ nfse_service_code_national: e.target.value }) }) }),
493
+ /* @__PURE__ */ jsx(Field, { label: "C\xF3d. tributa\xE7\xE3o municipal", children: /* @__PURE__ */ jsx(Input, { value: draft.nfse_service_code_municipal ?? "", placeholder: "ex.: 001", onChange: (e) => set({ nfse_service_code_municipal: e.target.value }) }) }),
494
+ /* @__PURE__ */ jsx(Field, { label: "C\xF3digo NBS", children: /* @__PURE__ */ jsx(Input, { value: draft.nfse_nbs_code ?? "", placeholder: "ex.: 1.2602.90.00", onChange: (e) => set({ nfse_nbs_code: e.target.value }) }) }),
495
+ /* @__PURE__ */ jsxs(Field, { label: "CNAE do servi\xE7o", hint: cnaeOptions.length ? "Sugest\xF5es do CNPJ \u2014 escolha ou digite outro." : "Digite o CNAE do servi\xE7o.", children: [
496
+ /* @__PURE__ */ jsx(Input, { value: draft.nfse_cnae ?? "", placeholder: "ex.: 9602-5/02", list: `cnae-${legalEntityId}`, onChange: (e) => set({ nfse_cnae: e.target.value }) }),
497
+ cnaeOptions.length > 0 && /* @__PURE__ */ jsx("datalist", { id: `cnae-${legalEntityId}`, children: cnaeOptions.map((o) => /* @__PURE__ */ jsx("option", { value: o.code, children: o.label }, o.code)) })
498
+ ] })
499
+ ] }),
500
+ nfseTab === "iss" && /* @__PURE__ */ jsxs("div", { className: "fz-fields fz-fields-2 gap-4", children: [
501
+ /* @__PURE__ */ jsx(Field, { label: "Al\xEDquota ISS (%)", children: /* @__PURE__ */ jsx(Input, { inputMode: "decimal", value: draft.nfse_iss_rate ?? "", placeholder: "ex.: 5", onChange: (e) => set({ nfse_iss_rate: e.target.value }) }) }),
502
+ /* @__PURE__ */ jsx(Field, { label: "Tributa\xE7\xE3o ISS", children: /* @__PURE__ */ jsxs(Select, { value: draft.nfse_iss_taxation != null ? String(draft.nfse_iss_taxation) : void 0, onValueChange: (v) => set({ nfse_iss_taxation: v }), children: [
503
+ /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Selecione" }) }),
504
+ /* @__PURE__ */ jsx(SelectContent, { children: ISS_TAXATION.map((o) => /* @__PURE__ */ jsx(SelectItem, { value: o.value, children: o.label }, o.value)) })
505
+ ] }) }),
506
+ isSimples && /* @__PURE__ */ jsx(Field, { label: "Apura\xE7\xE3o dos tributos no Simples", children: /* @__PURE__ */ jsxs(Select, { value: draft.nfse_simples_regime != null ? String(draft.nfse_simples_regime) : "auto", onValueChange: (v) => set({ nfse_simples_regime: v }), children: [
507
+ /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
508
+ /* @__PURE__ */ jsx(SelectContent, { children: SIMPLES_REGIME.map((o) => /* @__PURE__ */ jsx(SelectItem, { value: o.value, children: o.label }, o.value)) })
509
+ ] }) })
510
+ ] }),
511
+ nfseTab === "reforma" && /* @__PURE__ */ jsxs("div", { className: "fz-fields fz-fields-2 gap-4", children: [
512
+ /* @__PURE__ */ jsx(Field, { label: "IBS/CBS \u2014 CST", hint: "Reforma tribut\xE1ria (vig\xEAncia progressiva). Confirme com a contabilidade.", children: /* @__PURE__ */ jsx(Input, { value: draft.nfse_ibscbs_cst ?? "", placeholder: "ex.: 000", onChange: (e) => set({ nfse_ibscbs_cst: e.target.value }) }) }),
513
+ /* @__PURE__ */ jsx(Field, { label: "IBS/CBS \u2014 Classifica\xE7\xE3o", children: /* @__PURE__ */ jsx(Input, { value: draft.nfse_ibscbs_classification ?? "", placeholder: "ex.: 000001", onChange: (e) => set({ nfse_ibscbs_classification: e.target.value }) }) })
514
+ ] }),
515
+ nfseTab === "nota" && /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
516
+ /* @__PURE__ */ jsx(ToggleRow, { title: "Emitir pelo valor l\xEDquido", description: "Sai com o valor final, sem destacar desconto.", checked: !!draft.nfse_net_value, onChange: (v) => set({ nfse_net_value: v }) }),
517
+ /* @__PURE__ */ jsx(Field, { label: "Informa\xE7\xF5es complementares da nota", hint: "Sai no rodap\xE9 do DANFSe.", children: /* @__PURE__ */ jsx(Input, { value: draft.nfse_additional_info ?? "", placeholder: "ex.: Totais Aproximados dos Tributos cfe. Lei n\xBA 12.741/2012\u2026", onChange: (e) => set({ nfse_additional_info: e.target.value }) }) })
518
+ ] })
519
+ ] })
520
+ ] }),
521
+ /* @__PURE__ */ jsxs("section", { className: "space-y-4 rounded-md border p-4", children: [
522
+ /* @__PURE__ */ jsx(
523
+ ToggleRow,
524
+ {
525
+ title: "NFC-e \u2014 Cupom do Consumidor",
526
+ description: "Produtos / comanda",
527
+ checked: !!draft.nfce_enabled,
528
+ onChange: (v) => set({ nfce_enabled: v }),
529
+ children: /* @__PURE__ */ jsx(EnvSelect, { value: !!draft.nfce_production, onChange: (v) => set({ nfce_production: v }), disabled: !draft.nfce_enabled })
530
+ }
531
+ ),
532
+ draft.nfce_enabled && /* @__PURE__ */ jsxs("div", { className: "fz-container space-y-4", children: [
533
+ /* @__PURE__ */ jsxs("div", { className: "fz-fields fz-fields-2 gap-4", children: [
534
+ /* @__PURE__ */ jsx(Field, { label: "S\xE9rie", children: /* @__PURE__ */ jsx(Input, { inputMode: "numeric", value: draft.nfce_series ?? "", onChange: (e) => set({ nfce_series: e.target.value.replace(/\D/g, "") }) }) }),
535
+ /* @__PURE__ */ jsx(Field, { label: "CSC \u2014 ID", children: /* @__PURE__ */ jsx(Input, { value: draft.nfce_csc_id ?? "", onChange: (e) => set({ nfce_csc_id: e.target.value }) }) })
536
+ ] }),
537
+ /* @__PURE__ */ jsx(Field, { label: "CSC \u2014 Token", hint: "O CSC (id num\xE9rico + token) \xE9 gerado no portal da SEFAZ do estado \u2014 n\xE3o \xE9 o login de nenhum sistema.", children: /* @__PURE__ */ jsx(Input, { type: "password", value: cscToken, placeholder: row.nfce_csc_token_set ? "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022 (configurado \u2014 digite para trocar)" : "", onChange: (e) => setCscToken(e.target.value) }) }),
538
+ /* @__PURE__ */ jsxs("div", { className: "fz-fields fz-fields-2 gap-4", children: [
539
+ /* @__PURE__ */ jsx(Field, { label: "Item gen\xE9rico \u2014 NCM", children: /* @__PURE__ */ jsx(Input, { value: generic.ncm ?? "", onChange: (e) => setGeneric({ ncm: e.target.value }) }) }),
540
+ /* @__PURE__ */ jsx(Field, { label: "Item gen\xE9rico \u2014 CFOP", children: /* @__PURE__ */ jsx(Input, { value: generic.cfop ?? "", onChange: (e) => setGeneric({ cfop: e.target.value }) }) }),
541
+ /* @__PURE__ */ jsx(Field, { label: "Item gen\xE9rico \u2014 CSOSN/CST", children: /* @__PURE__ */ jsx(Input, { value: generic.csosn ?? "", onChange: (e) => setGeneric({ csosn: e.target.value }) }) })
542
+ ] })
543
+ ] })
544
+ ] }),
545
+ /* @__PURE__ */ jsx("ul", { className: "flex flex-wrap gap-2", children: checks.map((c) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: c.ok ? "gap-1 border-emerald-500/40 text-emerald-700 dark:text-emerald-400" : "gap-1 text-muted-foreground", children: [
546
+ c.ok ? /* @__PURE__ */ jsx(Check, { className: "h-3 w-3" }) : /* @__PURE__ */ jsx(X, { className: "h-3 w-3" }),
547
+ c.label
548
+ ] }) }, c.label)) }),
549
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-end gap-3", children: [
550
+ missing.length > 0 && /* @__PURE__ */ jsxs("p", { className: "mr-auto text-xs text-destructive", children: [
551
+ "Falta: ",
552
+ missing.join(", ")
553
+ ] }),
554
+ /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => void onRegister(), disabled: saving || registering, children: registering ? "Cadastrando\u2026" : row.provider_synced_at ? "Atualizar na PlugNotas" : "Cadastrar na PlugNotas" }),
555
+ /* @__PURE__ */ jsx(Button, { onClick: () => void onSave(), disabled: saving || registering, children: saving ? "Salvando\u2026" : "Salvar configura\xE7\xE3o" })
556
+ ] })
557
+ ] })
558
+ ] })
559
+ ] });
560
+ }
561
+
562
+ export { UnitFiscalCard };
563
+ //# sourceMappingURL=UnitFiscalWidgets-XSED3WPQ.js.map
564
+ //# sourceMappingURL=UnitFiscalWidgets-XSED3WPQ.js.map