@asteby/metacore-runtime-react 47.1.0 → 48.0.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/CHANGELOG.md +29 -0
- package/dist/action-modal-dispatcher.d.ts.map +1 -1
- package/dist/action-modal-dispatcher.js +24 -4
- package/dist/business/catalog-product-search.d.ts +25 -0
- package/dist/business/catalog-product-search.d.ts.map +1 -0
- package/dist/business/catalog-product-search.js +57 -0
- package/dist/business/catalog.d.ts.map +1 -1
- package/dist/business/catalog.js +2 -0
- package/dist/business/document-editor-model.d.ts +107 -0
- package/dist/business/document-editor-model.d.ts.map +1 -0
- package/dist/business/document-editor-model.js +279 -0
- package/dist/business/document-editor-panels.d.ts +64 -0
- package/dist/business/document-editor-panels.d.ts.map +1 -0
- package/dist/business/document-editor-panels.js +58 -0
- package/dist/business/document-editor.d.ts +27 -0
- package/dist/business/document-editor.d.ts.map +1 -0
- package/dist/business/document-editor.js +445 -0
- package/dist/business/document-lines.d.ts.map +1 -1
- package/dist/business/document-lines.js +5 -1
- package/dist/business/index.d.ts +5 -0
- package/dist/business/index.d.ts.map +1 -1
- package/dist/business/index.js +5 -0
- package/dist/business/line-items.d.ts +7 -0
- package/dist/business/line-items.d.ts.map +1 -1
- package/dist/business/line-items.js +6 -1
- package/dist/business/payment-allocator.d.ts +19 -0
- package/dist/business/payment-allocator.d.ts.map +1 -0
- package/dist/business/payment-allocator.js +31 -0
- package/dist/business/product-search.d.ts +4 -0
- package/dist/business/product-search.d.ts.map +1 -1
- package/dist/dialogs/dynamic-record.d.ts.map +1 -1
- package/dist/dialogs/dynamic-record.js +14 -7
- package/dist/document-form-dialog.d.ts +31 -2
- package/dist/document-form-dialog.d.ts.map +1 -1
- package/dist/document-form-dialog.js +43 -11
- package/dist/dynamic-columns-helpers.d.ts +9 -0
- package/dist/dynamic-columns-helpers.d.ts.map +1 -1
- package/dist/dynamic-columns-helpers.js +19 -0
- package/dist/dynamic-columns.d.ts +8 -2
- package/dist/dynamic-columns.d.ts.map +1 -1
- package/dist/dynamic-columns.js +21 -5
- package/dist/dynamic-crud-page.d.ts +6 -0
- package/dist/dynamic-crud-page.d.ts.map +1 -1
- package/dist/dynamic-crud-page.js +14 -5
- package/dist/dynamic-form-schema.d.ts.map +1 -1
- package/dist/dynamic-form-schema.js +15 -3
- package/dist/dynamic-form.d.ts +16 -1
- package/dist/dynamic-form.d.ts.map +1 -1
- package/dist/dynamic-form.js +78 -20
- package/dist/dynamic-kanban.d.ts +9 -3
- package/dist/dynamic-kanban.d.ts.map +1 -1
- package/dist/dynamic-kanban.js +31 -12
- package/dist/dynamic-relation-helpers.d.ts.map +1 -1
- package/dist/dynamic-relation-helpers.js +8 -0
- package/dist/dynamic-relation.js +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -2
- package/dist/installed-addons-context.d.ts +15 -0
- package/dist/installed-addons-context.d.ts.map +1 -0
- package/dist/installed-addons-context.js +39 -0
- package/dist/org-runtime-context.d.ts +8 -0
- package/dist/org-runtime-context.d.ts.map +1 -1
- package/dist/org-runtime-context.js +8 -0
- package/dist/org-runtime-provider.d.ts +3 -1
- package/dist/org-runtime-provider.d.ts.map +1 -1
- package/dist/org-runtime-provider.js +3 -3
- package/dist/primitives/aging.d.ts +34 -0
- package/dist/primitives/aging.d.ts.map +1 -0
- package/dist/primitives/aging.js +48 -0
- package/dist/primitives/allocation.d.ts +42 -0
- package/dist/primitives/allocation.d.ts.map +1 -0
- package/dist/primitives/allocation.js +59 -0
- package/dist/primitives/approvals.d.ts +71 -0
- package/dist/primitives/approvals.d.ts.map +1 -0
- package/dist/primitives/approvals.js +48 -0
- package/dist/primitives/contributions.d.ts +82 -0
- package/dist/primitives/contributions.d.ts.map +1 -0
- package/dist/primitives/contributions.js +126 -0
- package/dist/primitives/document-kinds.d.ts +25 -0
- package/dist/primitives/document-kinds.d.ts.map +1 -0
- package/dist/primitives/document-kinds.js +26 -0
- package/dist/primitives/index.d.ts +8 -0
- package/dist/primitives/index.d.ts.map +1 -0
- package/dist/primitives/index.js +23 -0
- package/dist/primitives/panels.d.ts +68 -0
- package/dist/primitives/panels.d.ts.map +1 -0
- package/dist/primitives/panels.js +3 -0
- package/dist/primitives/use-contributions.d.ts +15 -0
- package/dist/primitives/use-contributions.d.ts.map +1 -0
- package/dist/primitives/use-contributions.js +30 -0
- package/dist/record-prefill-bar.d.ts +11 -0
- package/dist/record-prefill-bar.d.ts.map +1 -0
- package/dist/record-prefill-bar.js +33 -0
- package/dist/types.d.ts +102 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/__tests__/catalog-product-search.test.ts +61 -0
- package/src/__tests__/document-editor-model.test.ts +167 -0
- package/src/__tests__/document-editor.test.tsx +261 -0
- package/src/__tests__/document-form-dialog.test.tsx +118 -3
- package/src/__tests__/dynamic-form-select-edit.test.tsx +155 -0
- package/src/__tests__/dynamic-kanban.test.tsx +24 -3
- package/src/__tests__/dynamic-record-extension-label.test.tsx +88 -0
- package/src/__tests__/installed-addons-context.test.tsx +50 -0
- package/src/__tests__/line-item-totals.test.ts +28 -0
- package/src/__tests__/primitives-federated.test.tsx +156 -0
- package/src/__tests__/primitives.test.ts +224 -0
- package/src/__tests__/record-prefill-bar.test.tsx +50 -0
- package/src/action-modal-dispatcher.tsx +47 -4
- package/src/business/catalog-product-search.ts +87 -0
- package/src/business/catalog.ts +2 -0
- package/src/business/document-editor-model.ts +325 -0
- package/src/business/document-editor-panels.tsx +164 -0
- package/src/business/document-editor.tsx +727 -0
- package/src/business/document-lines.ts +5 -1
- package/src/business/index.ts +5 -0
- package/src/business/line-items.ts +15 -1
- package/src/business/payment-allocator.tsx +110 -0
- package/src/business/product-search.ts +4 -0
- package/src/dialogs/dynamic-record.tsx +29 -6
- package/src/document-form-dialog.tsx +92 -12
- package/src/dynamic-columns-helpers.ts +22 -0
- package/src/dynamic-columns.tsx +23 -6
- package/src/dynamic-crud-page.tsx +22 -3
- package/src/dynamic-form-schema.ts +15 -2
- package/src/dynamic-form.tsx +117 -39
- package/src/dynamic-kanban.tsx +34 -7
- package/src/dynamic-relation-helpers.ts +9 -0
- package/src/dynamic-relation.tsx +7 -2
- package/src/index.ts +21 -1
- package/src/installed-addons-context.tsx +58 -0
- package/src/org-runtime-context.ts +10 -0
- package/src/org-runtime-provider.tsx +7 -2
- package/src/primitives/aging.ts +76 -0
- package/src/primitives/allocation.ts +104 -0
- package/src/primitives/approvals.ts +103 -0
- package/src/primitives/contributions.ts +208 -0
- package/src/primitives/document-kinds.ts +62 -0
- package/src/primitives/index.ts +23 -0
- package/src/primitives/panels.ts +59 -0
- package/src/primitives/use-contributions.ts +42 -0
- package/src/record-prefill-bar.tsx +62 -0
- package/src/row-action-stage-gate.test.ts +33 -0
- package/src/types.ts +101 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { type ReactNode } from 'react';
|
|
2
|
+
import type { CreditStatus, EditorIssue } from './document-editor-model';
|
|
3
|
+
import type { Formatter } from './format';
|
|
4
|
+
/** Bloque con título discreto y espaciado generoso (sin bordes pesados). */
|
|
5
|
+
export declare function EditorSection({ title, hint, children, slot }: {
|
|
6
|
+
title?: ReactNode;
|
|
7
|
+
hint?: ReactNode;
|
|
8
|
+
children: ReactNode;
|
|
9
|
+
slot?: string;
|
|
10
|
+
}): import("react").JSX.Element;
|
|
11
|
+
export interface CollapsibleSectionProps {
|
|
12
|
+
title: ReactNode;
|
|
13
|
+
/** Resumen de una línea cuando está cerrada (p. ej. «G03 · PUE»). */
|
|
14
|
+
summary?: ReactNode;
|
|
15
|
+
open?: boolean;
|
|
16
|
+
defaultOpen?: boolean;
|
|
17
|
+
onOpenChange?: (open: boolean) => void;
|
|
18
|
+
children: ReactNode;
|
|
19
|
+
slot?: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Sección plegable. El contenido queda MONTADO aunque esté cerrada (`hidden`):
|
|
23
|
+
* las contribuciones de otros addons siguen aplicando defaults y reportando
|
|
24
|
+
* revisiones sin que el usuario abra la sección.
|
|
25
|
+
*/
|
|
26
|
+
export declare function CollapsibleSection({ title, summary, open, defaultOpen, onOpenChange, children, slot }: CollapsibleSectionProps): import("react").JSX.Element;
|
|
27
|
+
export interface PartyCardProps {
|
|
28
|
+
name?: string;
|
|
29
|
+
rows: Array<{
|
|
30
|
+
key: string;
|
|
31
|
+
label: string;
|
|
32
|
+
value: string;
|
|
33
|
+
}>;
|
|
34
|
+
credit?: CreditStatus | null;
|
|
35
|
+
fmt: Formatter;
|
|
36
|
+
children?: ReactNode;
|
|
37
|
+
}
|
|
38
|
+
/** Tarjeta compacta de la contraparte: nombre, 3-6 datos clave y estado de crédito. */
|
|
39
|
+
export declare function PartyCard({ name, rows, credit, fmt, children }: PartyCardProps): import("react").JSX.Element;
|
|
40
|
+
export interface TotalsRow {
|
|
41
|
+
label: string;
|
|
42
|
+
value: string;
|
|
43
|
+
emphasis?: boolean;
|
|
44
|
+
}
|
|
45
|
+
/** Totales alineados a la derecha; la última fila con `emphasis` es el total. */
|
|
46
|
+
export declare function TotalsPanel({ rows }: {
|
|
47
|
+
rows: TotalsRow[];
|
|
48
|
+
}): import("react").JSX.Element;
|
|
49
|
+
/** Lista de revisión: errores (rojo) y avisos (ámbar). Vacía → no pinta nada. */
|
|
50
|
+
export declare function ValidationChecklist({ issues, title }: {
|
|
51
|
+
issues: EditorIssue[];
|
|
52
|
+
title?: string;
|
|
53
|
+
}): import("react").JSX.Element | null;
|
|
54
|
+
export interface PreviewContent {
|
|
55
|
+
xml?: string;
|
|
56
|
+
html?: string;
|
|
57
|
+
pdf_url?: string;
|
|
58
|
+
pdf_base64?: string;
|
|
59
|
+
}
|
|
60
|
+
/** Contenido de la vista previa (PDF, HTML o XML, en ese orden de preferencia). */
|
|
61
|
+
export declare function PreviewPanel({ preview }: {
|
|
62
|
+
preview: PreviewContent | null;
|
|
63
|
+
}): import("react").JSX.Element | null;
|
|
64
|
+
//# sourceMappingURL=document-editor-panels.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"document-editor-panels.d.ts","sourceRoot":"","sources":["../../src/business/document-editor-panels.tsx"],"names":[],"mappings":"AAIA,OAAO,EAAmB,KAAK,SAAS,EAAE,MAAM,OAAO,CAAA;AAGvD,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AACxE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AAEzC,4EAA4E;AAC5E,wBAAgB,aAAa,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE;IAAE,KAAK,CAAC,EAAE,SAAS,CAAC;IAAC,IAAI,CAAC,EAAE,SAAS,CAAC;IAAC,QAAQ,EAAE,SAAS,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,+BAYzI;AAED,MAAM,WAAW,uBAAuB;IACpC,KAAK,EAAE,SAAS,CAAA;IAChB,qEAAqE;IACrE,OAAO,CAAC,EAAE,SAAS,CAAA;IACnB,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,CAAA;IACtC,QAAQ,EAAE,SAAS,CAAA;IACnB,IAAI,CAAC,EAAE,MAAM,CAAA;CAChB;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,WAAmB,EAAE,YAAY,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,uBAAuB,+BA4BtI;AAED,MAAM,WAAW,cAAc;IAC3B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,KAAK,CAAC;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IAC1D,MAAM,CAAC,EAAE,YAAY,GAAG,IAAI,CAAA;IAC5B,GAAG,EAAE,SAAS,CAAA;IACd,QAAQ,CAAC,EAAE,SAAS,CAAA;CACvB;AAED,uFAAuF;AACvF,wBAAgB,SAAS,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,EAAE,cAAc,+BA4B9E;AAED,MAAM,WAAW,SAAS;IACtB,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,OAAO,CAAA;CACrB;AAED,iFAAiF;AACjF,wBAAgB,WAAW,CAAC,EAAE,IAAI,EAAE,EAAE;IAAE,IAAI,EAAE,SAAS,EAAE,CAAA;CAAE,+BAW1D;AAED,iFAAiF;AACjF,wBAAgB,mBAAmB,CAAC,EAAE,MAAM,EAAE,KAAiC,EAAE,EAAE;IAAE,MAAM,EAAE,WAAW,EAAE,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,sCAe3H;AAED,MAAM,WAAW,cAAc;IAC3B,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,UAAU,CAAC,EAAE,MAAM,CAAA;CACtB;AAED,mFAAmF;AACnF,wBAAgB,YAAY,CAAC,EAAE,OAAO,EAAE,EAAE;IAAE,OAAO,EAAE,cAAc,GAAG,IAAI,CAAA;CAAE,sCAO3E"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
// Piezas visuales del DocumentEditor: secciones, sección plegable, tarjeta de
|
|
3
|
+
// contraparte, totales, revisión y vista previa. Sin estado de negocio: el
|
|
4
|
+
// editor (o un remote federado) les pasa los datos ya calculados. Los contratos
|
|
5
|
+
// de datos viven en primitives/panels.ts.
|
|
6
|
+
import { useId, useState } from 'react';
|
|
7
|
+
import { Badge } from '@asteby/metacore-ui/primitives';
|
|
8
|
+
import { AlertTriangle, ChevronDown, XCircle } from 'lucide-react';
|
|
9
|
+
/** Bloque con título discreto y espaciado generoso (sin bordes pesados). */
|
|
10
|
+
export function EditorSection({ title, hint, children, slot }) {
|
|
11
|
+
return (_jsxs("section", { className: "space-y-3", "data-slot": slot, children: [(title || hint) && (_jsxs("header", { className: "flex items-baseline justify-between gap-3", children: [title && _jsx("h3", { className: "text-sm font-semibold", children: title }), hint && _jsx("span", { className: "text-xs text-muted-foreground", children: hint })] })), children] }));
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Sección plegable. El contenido queda MONTADO aunque esté cerrada (`hidden`):
|
|
15
|
+
* las contribuciones de otros addons siguen aplicando defaults y reportando
|
|
16
|
+
* revisiones sin que el usuario abra la sección.
|
|
17
|
+
*/
|
|
18
|
+
export function CollapsibleSection({ title, summary, open, defaultOpen = false, onOpenChange, children, slot }) {
|
|
19
|
+
const [inner, setInner] = useState(defaultOpen);
|
|
20
|
+
const isOpen = open ?? inner;
|
|
21
|
+
const id = useId();
|
|
22
|
+
const toggle = () => {
|
|
23
|
+
setInner(!isOpen);
|
|
24
|
+
onOpenChange?.(!isOpen);
|
|
25
|
+
};
|
|
26
|
+
return (_jsxs("section", { className: "rounded-lg border border-dashed", "data-slot": slot, "data-state": isOpen ? 'open' : 'closed', children: [_jsxs("button", { type: "button", "aria-expanded": isOpen, "aria-controls": id, onClick: toggle, className: "flex w-full items-center justify-between gap-3 px-4 py-3 text-left text-sm", children: [_jsx("span", { className: "font-medium", children: title }), _jsxs("span", { className: "flex min-w-0 items-center gap-2 text-xs text-muted-foreground", children: [!isOpen && summary && _jsx("span", { className: "truncate", children: summary }), _jsx(ChevronDown, { className: `size-4 shrink-0 transition-transform ${isOpen ? 'rotate-180' : ''}`, "aria-hidden": true })] })] }), _jsx("div", { id: id, hidden: !isOpen, className: "space-y-4 px-4 pb-4", children: children })] }));
|
|
27
|
+
}
|
|
28
|
+
/** Tarjeta compacta de la contraparte: nombre, 3-6 datos clave y estado de crédito. */
|
|
29
|
+
export function PartyCard({ name, rows, credit, fmt, children }) {
|
|
30
|
+
return (_jsxs("div", { className: "rounded-md bg-muted/40 px-4 py-3 text-sm", "data-slot": "party-card", children: [_jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [name && _jsx("span", { className: "font-medium", children: name }), credit && (_jsx(Badge, { variant: credit.level === 'block' ? 'destructive' : credit.level === 'warn' ? 'secondary' : 'outline', "data-slot": "party-credit", children: credit.holdReason
|
|
31
|
+
? credit.holdReason
|
|
32
|
+
: credit.available != null
|
|
33
|
+
? `Crédito disponible ${fmt.money(credit.available)}`
|
|
34
|
+
: `Saldo ${fmt.money(credit.balance ?? 0)}` }))] }), rows.length > 0 && (_jsx("dl", { className: "mt-2 grid grid-cols-2 gap-x-6 gap-y-1 sm:grid-cols-3", children: rows.map((r) => (_jsxs("div", { className: "min-w-0", children: [_jsx("dt", { className: "text-xs text-muted-foreground", children: r.label }), _jsx("dd", { className: "truncate", children: r.value })] }, r.key))) })), children] }));
|
|
35
|
+
}
|
|
36
|
+
/** Totales alineados a la derecha; la última fila con `emphasis` es el total. */
|
|
37
|
+
export function TotalsPanel({ rows }) {
|
|
38
|
+
return (_jsx("dl", { className: "ml-auto w-full max-w-xs space-y-1 text-sm tabular-nums", "data-slot": "totals", children: rows.map((r) => (_jsxs("div", { className: `flex justify-between gap-6 ${r.emphasis ? 'border-t pt-2 text-base font-semibold' : ''}`, children: [_jsx("dt", { className: r.emphasis ? '' : 'text-muted-foreground', children: r.label }), _jsx("dd", { children: r.value })] }, r.label))) }));
|
|
39
|
+
}
|
|
40
|
+
/** Lista de revisión: errores (rojo) y avisos (ámbar). Vacía → no pinta nada. */
|
|
41
|
+
export function ValidationChecklist({ issues, title = 'Revisa antes de guardar' }) {
|
|
42
|
+
if (issues.length === 0)
|
|
43
|
+
return null;
|
|
44
|
+
return (_jsxs("div", { className: "rounded-md bg-muted/30 px-4 py-3", "data-slot": "validation-checklist", role: "status", children: [_jsx("p", { className: "mb-1 text-xs font-medium text-muted-foreground", children: title }), _jsx("ul", { className: "space-y-1 text-sm", children: issues.map((i, k) => (_jsxs("li", { className: `flex items-start gap-2 ${i.severity === 'error' ? 'text-destructive' : 'text-amber-700'}`, children: [i.severity === 'error' ? _jsx(XCircle, { className: "mt-0.5 size-4 shrink-0", "aria-hidden": true }) : _jsx(AlertTriangle, { className: "mt-0.5 size-4 shrink-0", "aria-hidden": true }), i.message] }, `${i.field ?? ''}:${k}`))) })] }));
|
|
45
|
+
}
|
|
46
|
+
/** Contenido de la vista previa (PDF, HTML o XML, en ese orden de preferencia). */
|
|
47
|
+
export function PreviewPanel({ preview }) {
|
|
48
|
+
if (!preview)
|
|
49
|
+
return null;
|
|
50
|
+
const pdf = preview.pdf_url ?? (preview.pdf_base64 ? `data:application/pdf;base64,${preview.pdf_base64}` : undefined);
|
|
51
|
+
if (pdf)
|
|
52
|
+
return _jsx("iframe", { title: "Vista previa", src: pdf, className: "h-96 w-full rounded border", "data-slot": "preview-pdf" });
|
|
53
|
+
if (preview.html)
|
|
54
|
+
return _jsx("iframe", { title: "Vista previa", srcDoc: preview.html, className: "h-96 w-full rounded border", "data-slot": "preview-html" });
|
|
55
|
+
if (preview.xml)
|
|
56
|
+
return _jsx("pre", { className: "max-h-96 overflow-auto rounded bg-muted p-3 text-[11px] leading-tight", "data-slot": "preview-xml", children: preview.xml });
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type DocumentLinesGridProps } from './line-items-editor';
|
|
2
|
+
import type { DocumentFormType, DocumentFormsManifest } from '../types';
|
|
3
|
+
export interface DocumentEditorProps {
|
|
4
|
+
model: string;
|
|
5
|
+
/** Endpoint de alta del modelo. Default `/dynamic/<model>`. */
|
|
6
|
+
endpoint?: string;
|
|
7
|
+
forms: DocumentFormsManifest;
|
|
8
|
+
type: DocumentFormType;
|
|
9
|
+
/** Registro desde el que se abrió (acción de fila): siembra `default_from_record`. */
|
|
10
|
+
record?: Record<string, any>;
|
|
11
|
+
/** Documento origen a precargar al abrir (`sources[].key` + id). */
|
|
12
|
+
initialSource?: {
|
|
13
|
+
key: string;
|
|
14
|
+
id: string;
|
|
15
|
+
};
|
|
16
|
+
onSaved?: (record?: unknown) => void;
|
|
17
|
+
onCancel: () => void;
|
|
18
|
+
searchProducts?: DocumentLinesGridProps['search'];
|
|
19
|
+
/** Modelo de catálogo del buscador por defecto. Default `products.Product`. */
|
|
20
|
+
productModel?: string;
|
|
21
|
+
defaultTaxRate?: number;
|
|
22
|
+
currency?: string;
|
|
23
|
+
/** Hoy (días de atraso del reparto; inyectable en tests). */
|
|
24
|
+
today?: Date;
|
|
25
|
+
}
|
|
26
|
+
export declare function DocumentEditor({ model, endpoint, forms, type, record, initialSource, onSaved, onCancel, searchProducts, productModel, defaultTaxRate, currency, today, }: DocumentEditorProps): import("react").JSX.Element;
|
|
27
|
+
//# sourceMappingURL=document-editor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"document-editor.d.ts","sourceRoot":"","sources":["../../src/business/document-editor.tsx"],"names":[],"mappings":"AA4BA,OAAO,EAAqB,KAAK,sBAAsB,EAAwB,MAAM,qBAAqB,CAAA;AAwC1G,OAAO,KAAK,EAAsC,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAA;AAE3G,MAAM,WAAW,mBAAmB;IAChC,KAAK,EAAE,MAAM,CAAA;IACb,+DAA+D;IAC/D,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,KAAK,EAAE,qBAAqB,CAAA;IAC5B,IAAI,EAAE,gBAAgB,CAAA;IACtB,sFAAsF;IACtF,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC5B,oEAAoE;IACpE,aAAa,CAAC,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAA;IAC3C,OAAO,CAAC,EAAE,CAAC,MAAM,CAAC,EAAE,OAAO,KAAK,IAAI,CAAA;IACpC,QAAQ,EAAE,MAAM,IAAI,CAAA;IACpB,cAAc,CAAC,EAAE,sBAAsB,CAAC,QAAQ,CAAC,CAAA;IACjD,+EAA+E;IAC/E,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,6DAA6D;IAC7D,KAAK,CAAC,EAAE,IAAI,CAAA;CACf;AAID,wBAAgB,cAAc,CAAC,EAC3B,KAAK,EACL,QAAQ,EACR,KAAK,EACL,IAAI,EACJ,MAAM,EACN,aAAa,EACb,OAAO,EACP,QAAQ,EACR,cAAc,EACd,YAAY,EACZ,cAAc,EACd,QAAQ,EACR,KAAK,GACR,EAAE,mBAAmB,+BA2kBrB"}
|
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
// DocumentEditor — alta de un documento comercial en UNA pantalla por
|
|
3
|
+
// secciones: factura, NC, cobro/REP, cotización, OC… Sustituye al wizard
|
|
4
|
+
// «Datos → Siguiente → Renglones» de DocumentFormDialog cuando el tipo declara
|
|
5
|
+
// `layout: "editor"` en `document_forms` (lo sirve el kernel ≥ v0.190.0).
|
|
6
|
+
//
|
|
7
|
+
// Contraparte + lo esencial (PartyCard: datos clave y crédito)
|
|
8
|
+
// Cargar desde… (sources: el renglón/encabezado se precarga)
|
|
9
|
+
// Renglones | Reparto del pago (DocumentLinesGrid con catálogo | PaymentAllocator)
|
|
10
|
+
// Totales
|
|
11
|
+
// ▸ Opciones fiscales (plegada: extensiones fiscal_data.*, catálogos
|
|
12
|
+
// con default y contribuciones header.fields)
|
|
13
|
+
// Secciones de otros addons (body.sections / side.panels)
|
|
14
|
+
// ▸ Vista previa (plegada; acción `preview` con analyze: true)
|
|
15
|
+
// [Cancelar] [Acción primaria única]
|
|
16
|
+
//
|
|
17
|
+
// Pensado para quien hace varios roles: a la vista solo lo que hay que decidir;
|
|
18
|
+
// lo fiscal trae defaults (de la contraparte y del manifest) y se revisa solo si
|
|
19
|
+
// hace falta. Genérico y sin país: fiscal_mexico aporta sus campos como
|
|
20
|
+
// extensiones o contribuciones; otra localización hace lo mismo.
|
|
21
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
22
|
+
import { useTranslation } from 'react-i18next';
|
|
23
|
+
import { Button } from '@asteby/metacore-ui/primitives';
|
|
24
|
+
import { Loader2 } from 'lucide-react';
|
|
25
|
+
import { toast } from 'sonner';
|
|
26
|
+
import { useApi } from '../api-context';
|
|
27
|
+
import { useOrgTaxRate } from '../org-runtime-context';
|
|
28
|
+
import { FieldCell, FieldGrid, FieldLabel } from '../field-grid';
|
|
29
|
+
import { FormErrorBanner } from './feedback';
|
|
30
|
+
import { DocumentLinesGrid } from './line-items-editor';
|
|
31
|
+
import { computeTotals, serializeLineItems, taxBreakdown } from './line-items';
|
|
32
|
+
import { roundMoney, toAmount, useFormatter } from './format';
|
|
33
|
+
import { createCatalogProductSearch } from './catalog-product-search';
|
|
34
|
+
import { allocationAmountField, allocationIssueMessages, allocationPayload, creditStatus, editorLinesConfig, linesFromSource, localIssues, partyDefaults, partySummaryRows, splitEditorFields, toOpenDocuments, withFriendlyOptions, } from './document-editor-model';
|
|
35
|
+
import { CollapsibleSection, EditorSection, PartyCard, PreviewPanel, TotalsPanel, ValidationChecklist, } from './document-editor-panels';
|
|
36
|
+
import { PaymentAllocator } from './payment-allocator';
|
|
37
|
+
import { actionErrorBannerMessage, buildFieldDefaults, prefillFromFieldRelationRequest, renderField } from '../action-modal-dispatcher';
|
|
38
|
+
import { extractFieldErrors, localizeFieldErrorMap } from '../server-error';
|
|
39
|
+
import { validateValues, bagHasErrors } from '../validator';
|
|
40
|
+
import { clearFieldErrorTree } from '../field-validation-ui';
|
|
41
|
+
import { emitRecordMutation } from '../record-mutation-events';
|
|
42
|
+
import { evaluateVisibleWhen, getVisibleWhen } from '../dynamic-form-schema';
|
|
43
|
+
import { useInstalledAddons } from '../installed-addons-context';
|
|
44
|
+
import { allocatePayment, validateAllocation } from '../primitives/allocation';
|
|
45
|
+
import { useDocumentContributions } from '../primitives/use-contributions';
|
|
46
|
+
export function DocumentEditor({ model, endpoint, forms, type, record, initialSource, onSaved, onCancel, searchProducts, productModel, defaultTaxRate, currency, today, }) {
|
|
47
|
+
const { t, i18n } = useTranslation();
|
|
48
|
+
const lang = i18n?.language;
|
|
49
|
+
const api = useApi();
|
|
50
|
+
const fmt = useFormatter({ currency });
|
|
51
|
+
const installed = useInstalledAddons();
|
|
52
|
+
const orgTaxRate = useOrgTaxRate();
|
|
53
|
+
const tl = useCallback((s) => t(s, { defaultValue: s }), [t]);
|
|
54
|
+
const lineCfg = useMemo(() => editorLinesConfig(type, forms), [type, forms]);
|
|
55
|
+
const kind = lineCfg?.kind ?? 'sale';
|
|
56
|
+
const isAllocation = kind === 'allocation' && !!lineCfg?.open_documents;
|
|
57
|
+
const amountKey = isAllocation ? allocationAmountField(type.fields) : undefined;
|
|
58
|
+
const [header, setHeader] = useState(() => ({
|
|
59
|
+
...buildFieldDefaults(type.fields, record),
|
|
60
|
+
...(type.defaults ?? {}),
|
|
61
|
+
}));
|
|
62
|
+
const [lines, setLines] = useState([]);
|
|
63
|
+
const [linesFromSourceDoc, setLinesFromSourceDoc] = useState(false);
|
|
64
|
+
const [extFields, setExtFields] = useState([]);
|
|
65
|
+
const [party, setParty] = useState(null);
|
|
66
|
+
const [openDocs, setOpenDocs] = useState([]);
|
|
67
|
+
const [docsLoading, setDocsLoading] = useState(false);
|
|
68
|
+
const [alloc, setAlloc] = useState({ strategy: 'oldest_due_first', manual: {} });
|
|
69
|
+
const [draftId, setDraftId] = useState(null);
|
|
70
|
+
const [serverIssues, setServerIssues] = useState([]);
|
|
71
|
+
const [contributed, setContributed] = useState({});
|
|
72
|
+
const [preview, setPreview] = useState(null);
|
|
73
|
+
const [previewOpen, setPreviewOpen] = useState(false);
|
|
74
|
+
const [advancedOpen, setAdvancedOpen] = useState(false);
|
|
75
|
+
const [busy, setBusy] = useState(null);
|
|
76
|
+
const [formError, setFormError] = useState();
|
|
77
|
+
const [fieldErrors, setFieldErrors] = useState({});
|
|
78
|
+
const [attempted, setAttempted] = useState(false);
|
|
79
|
+
const [sourceKey, setSourceKey] = useState(initialSource?.key ?? '');
|
|
80
|
+
const [sourceId, setSourceId] = useState(initialSource?.id ?? '');
|
|
81
|
+
const relCache = useRef(new Map());
|
|
82
|
+
const taxRate = defaultTaxRate ?? orgTaxRate;
|
|
83
|
+
const search = useMemo(() => searchProducts ?? createCatalogProductSearch(api, { model: productModel, defaultTaxRate: taxRate }), [searchProducts, api, productModel, taxRate]);
|
|
84
|
+
const isInstalled = useCallback((k) => !k || !installed || installed.addons.has(k), [installed]);
|
|
85
|
+
const sources = useMemo(() => (type.sources ?? []).filter((s) => isInstalled(s.requires_addon)), [type.sources, isInstalled]);
|
|
86
|
+
const previewEnabled = !!type.preview && !type.submit_action && isInstalled(type.preview.requires_addon);
|
|
87
|
+
// Campos de extensión del modelo (fiscal_data.* que declaran otros addons): van plegados.
|
|
88
|
+
useEffect(() => {
|
|
89
|
+
let cancelled = false;
|
|
90
|
+
api.get(`/metadata/modal/${model}`)
|
|
91
|
+
.then((res) => {
|
|
92
|
+
const fields = res?.data?.data?.fields ?? res?.data?.fields ?? [];
|
|
93
|
+
const declared = new Set(type.fields.map((f) => f.key));
|
|
94
|
+
const ext = fields.filter((f) => typeof f?.key === 'string' && f.key.startsWith('fiscal_data.') && !declared.has(f.key) && !f.readonly && !f.readOnly);
|
|
95
|
+
if (!cancelled)
|
|
96
|
+
setExtFields(ext);
|
|
97
|
+
})
|
|
98
|
+
.catch(() => { });
|
|
99
|
+
return () => {
|
|
100
|
+
cancelled = true;
|
|
101
|
+
};
|
|
102
|
+
}, [api, model, type.fields]);
|
|
103
|
+
const groups = useMemo(() => splitEditorFields(type.fields, {
|
|
104
|
+
partyField: type.party?.field,
|
|
105
|
+
essentialKeys: [amountKey, ...sources.map((s) => s.link_field)].filter((k) => !!k),
|
|
106
|
+
extensionFields: extFields,
|
|
107
|
+
}), [type.fields, type.party?.field, amountKey, sources, extFields]);
|
|
108
|
+
const visible = useCallback((f) => evaluateVisibleWhen(getVisibleWhen(f), header), [header]);
|
|
109
|
+
const allFields = useMemo(() => [...(groups.party ? [groups.party] : []), ...groups.essential, ...groups.advanced, ...groups.notes], [groups]);
|
|
110
|
+
const fieldKeys = useRef([]);
|
|
111
|
+
fieldKeys.current = allFields.map((f) => f.key);
|
|
112
|
+
// Contraparte: tarjeta + defaults de las extensiones con la misma clave.
|
|
113
|
+
const partyId = type.party ? header[type.party.field] : undefined;
|
|
114
|
+
useEffect(() => {
|
|
115
|
+
if (!type.party || !partyId) {
|
|
116
|
+
setParty(null);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
let cancelled = false;
|
|
120
|
+
const ep = type.party.endpoint ?? `/data/${type.party.model}`;
|
|
121
|
+
api.get(ep, { params: { f_id: `eq:${partyId}`, per_page: 1 } })
|
|
122
|
+
.then((res) => {
|
|
123
|
+
const rows = res?.data?.data ?? [];
|
|
124
|
+
const rec = Array.isArray(rows) ? rows[0] ?? null : rows ?? null;
|
|
125
|
+
if (cancelled)
|
|
126
|
+
return;
|
|
127
|
+
setParty(rec);
|
|
128
|
+
setHeader((h) => ({ ...h, ...partyDefaults(rec, fieldKeys.current, h) }));
|
|
129
|
+
})
|
|
130
|
+
.catch(() => !cancelled && setParty(null));
|
|
131
|
+
return () => {
|
|
132
|
+
cancelled = true;
|
|
133
|
+
};
|
|
134
|
+
}, [api, type.party, partyId]);
|
|
135
|
+
// Cobro: documentos abiertos de la contraparte.
|
|
136
|
+
const openCfg = lineCfg?.open_documents;
|
|
137
|
+
const allocPartyId = openCfg ? header[openCfg.party_field] ?? partyId : undefined;
|
|
138
|
+
useEffect(() => {
|
|
139
|
+
if (!isAllocation || !openCfg || !allocPartyId) {
|
|
140
|
+
setOpenDocs([]);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
let cancelled = false;
|
|
144
|
+
setDocsLoading(true);
|
|
145
|
+
api.get(`/data/${openCfg.model}`, { params: { [`f_${openCfg.party_field}`]: `eq:${allocPartyId}`, per_page: 200 } })
|
|
146
|
+
.then((res) => {
|
|
147
|
+
if (!cancelled)
|
|
148
|
+
setOpenDocs(toOpenDocuments(res?.data?.data, openCfg, fmt.currency));
|
|
149
|
+
})
|
|
150
|
+
.catch(() => !cancelled && setOpenDocs([]))
|
|
151
|
+
.finally(() => !cancelled && setDocsLoading(false));
|
|
152
|
+
return () => {
|
|
153
|
+
cancelled = true;
|
|
154
|
+
};
|
|
155
|
+
}, [api, isAllocation, openCfg, allocPartyId, fmt.currency]);
|
|
156
|
+
const amount = amountKey ? toAmount(header[amountKey]) : 0;
|
|
157
|
+
const allocation = useMemo(() => allocatePayment(amount, openDocs, alloc.strategy, alloc.manual), [amount, openDocs, alloc]);
|
|
158
|
+
const openBalance = useMemo(() => roundMoney(openDocs.reduce((s, d) => s + d.balance, 0)), [openDocs]);
|
|
159
|
+
const totals = useMemo(() => computeTotals(lines), [lines]);
|
|
160
|
+
const taxes = useMemo(() => taxBreakdown(lines), [lines]);
|
|
161
|
+
const documentTotal = isAllocation ? amount : totals.total;
|
|
162
|
+
const credit = useMemo(() => (isAllocation ? null : creditStatus(party, type.party?.credit, documentTotal)), [isAllocation, party, type.party?.credit, documentTotal]);
|
|
163
|
+
const issues = useMemo(() => {
|
|
164
|
+
const out = [];
|
|
165
|
+
if (isAllocation && openCfg) {
|
|
166
|
+
const found = validateAllocation(amount, fmt.currency, openDocs, allocation.allocations, { allowUnapplied: true });
|
|
167
|
+
out.push(...allocationIssueMessages(found, openDocs));
|
|
168
|
+
}
|
|
169
|
+
else if (lineCfg) {
|
|
170
|
+
out.push(...localIssues(lines, { requireLines: lineCfg.required ?? true }));
|
|
171
|
+
}
|
|
172
|
+
if (credit?.level === 'block') {
|
|
173
|
+
out.push({
|
|
174
|
+
field: type.party?.field,
|
|
175
|
+
severity: 'error',
|
|
176
|
+
message: credit.holdReason
|
|
177
|
+
? `${t('documentEditor.credit_hold', { defaultValue: 'Crédito retenido' })}: ${credit.holdReason}`
|
|
178
|
+
: t('documentEditor.credit_exceeded', { defaultValue: 'El total supera el crédito disponible.' }),
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
out.push(...Object.values(contributed), ...serverIssues);
|
|
182
|
+
return out;
|
|
183
|
+
}, [isAllocation, openCfg, amount, fmt.currency, openDocs, allocation, lineCfg, lines, credit, type.party?.field, contributed, serverIssues, t]);
|
|
184
|
+
const blocking = issues.some((i) => i.severity === 'error');
|
|
185
|
+
const shownIssues = attempted ? issues : issues.filter((i) => i.severity === 'warning');
|
|
186
|
+
const payload = useCallback(() => {
|
|
187
|
+
const p = { ...(type.defaults ?? {}), ...header };
|
|
188
|
+
if (forms.type_field && !type.submit_action)
|
|
189
|
+
p[forms.type_field] = type.value ?? type.key;
|
|
190
|
+
if (lineCfg) {
|
|
191
|
+
p[lineCfg.field] = isAllocation && openCfg ? allocationPayload(allocation.allocations, openCfg) : serializeLineItems(lines);
|
|
192
|
+
}
|
|
193
|
+
return p;
|
|
194
|
+
}, [type, header, forms.type_field, lineCfg, isAllocation, openCfg, allocation, lines]);
|
|
195
|
+
const baseUrl = type.endpoint ?? endpoint ?? `/dynamic/${model}`;
|
|
196
|
+
/** Crea o actualiza el BORRADOR (idempotente por draftId). La vista previa lo necesita. */
|
|
197
|
+
const saveDraft = useCallback(async () => {
|
|
198
|
+
const res = draftId ? await api.put(`${baseUrl}/${draftId}`, payload()) : await api.post(baseUrl, payload());
|
|
199
|
+
if (res.data?.success === false)
|
|
200
|
+
throw { response: { data: res.data } };
|
|
201
|
+
const rec = (res.data?.data ?? res.data ?? {});
|
|
202
|
+
const id = draftId ?? (rec.id != null ? String(rec.id) : null);
|
|
203
|
+
if (id)
|
|
204
|
+
setDraftId(id);
|
|
205
|
+
emitRecordMutation(model, draftId ? 'update' : 'create');
|
|
206
|
+
return { ...rec, id: id ?? rec.id };
|
|
207
|
+
}, [api, baseUrl, draftId, model, payload]);
|
|
208
|
+
const handleError = (err) => {
|
|
209
|
+
setFormError(actionErrorBannerMessage(err, allFields, t, lang));
|
|
210
|
+
const map = extractFieldErrors(err);
|
|
211
|
+
if (map) {
|
|
212
|
+
const labels = {};
|
|
213
|
+
for (const f of allFields)
|
|
214
|
+
labels[f.key] = tl(f.label);
|
|
215
|
+
const localized = localizeFieldErrorMap(map, t, { labels, language: lang });
|
|
216
|
+
setFieldErrors(localized);
|
|
217
|
+
if (groups.advanced.some((f) => localized[f.key]))
|
|
218
|
+
setAdvancedOpen(true);
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
// ---- Cargar desde… --------------------------------------------------------
|
|
222
|
+
const loadFromSource = useCallback(async (src, id) => {
|
|
223
|
+
if (!lineCfg || !id)
|
|
224
|
+
return;
|
|
225
|
+
setBusy('source');
|
|
226
|
+
try {
|
|
227
|
+
if (!isAllocation) {
|
|
228
|
+
let rels = relCache.current.get(src.model);
|
|
229
|
+
if (!rels) {
|
|
230
|
+
rels = api
|
|
231
|
+
.get(`/metadata/table/${src.model}`)
|
|
232
|
+
.then((r) => r?.data?.data?.relations ?? r?.data?.relations ?? []);
|
|
233
|
+
relCache.current.set(src.model, rels);
|
|
234
|
+
}
|
|
235
|
+
const call = prefillFromFieldRelationRequest({ fieldKey: lineCfg.field, refModel: src.model, refId: id, spec: { $prefillFromRecord: src.lines } }, await rels);
|
|
236
|
+
if (!call)
|
|
237
|
+
throw new Error(`${src.model}: falta la relación «${src.lines}»`);
|
|
238
|
+
const res = await api.get(call.endpoint, { params: call.params });
|
|
239
|
+
setLines(linesFromSource(res?.data?.data ?? [], src.map, { kind }));
|
|
240
|
+
setLinesFromSourceDoc(kind === 'credit');
|
|
241
|
+
}
|
|
242
|
+
if (src.header || src.link_field) {
|
|
243
|
+
const h = await api.get(`/data/${src.model}`, { params: { f_id: `eq:${id}`, per_page: 1 } });
|
|
244
|
+
const rec = ((h?.data?.data ?? [])[0] ?? {});
|
|
245
|
+
setHeader((prev) => {
|
|
246
|
+
const next = { ...prev };
|
|
247
|
+
for (const [to, from] of Object.entries(src.header ?? {}))
|
|
248
|
+
if (rec[from] != null)
|
|
249
|
+
next[to] = rec[from];
|
|
250
|
+
if (src.link_field)
|
|
251
|
+
next[src.link_field] = id;
|
|
252
|
+
return next;
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
setServerIssues([]);
|
|
256
|
+
}
|
|
257
|
+
catch (err) {
|
|
258
|
+
toast.error(t('documentEditor.source_failed', { defaultValue: 'No se pudo cargar el documento' }), {
|
|
259
|
+
description: err instanceof Error ? err.message : undefined,
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
finally {
|
|
263
|
+
setBusy(null);
|
|
264
|
+
}
|
|
265
|
+
}, [api, lineCfg, isAllocation, kind, t]);
|
|
266
|
+
// Prefill al abrir desde un documento origen (acción de fila «Crear NC», «Facturar venta»…).
|
|
267
|
+
const autoLoaded = useRef(false);
|
|
268
|
+
useEffect(() => {
|
|
269
|
+
if (autoLoaded.current || !initialSource)
|
|
270
|
+
return;
|
|
271
|
+
const src = sources.find((s) => s.key === initialSource.key);
|
|
272
|
+
if (!src)
|
|
273
|
+
return;
|
|
274
|
+
autoLoaded.current = true;
|
|
275
|
+
void loadFromSource(src, initialSource.id);
|
|
276
|
+
}, [initialSource, sources, loadFromSource]);
|
|
277
|
+
// ---- Vista previa -----------------------------------------------------------
|
|
278
|
+
const runPreview = async () => {
|
|
279
|
+
if (!type.preview)
|
|
280
|
+
return;
|
|
281
|
+
setBusy('preview');
|
|
282
|
+
setFormError(undefined);
|
|
283
|
+
try {
|
|
284
|
+
const rec = await saveDraft();
|
|
285
|
+
if (!rec.id)
|
|
286
|
+
return;
|
|
287
|
+
const res = await api.post(`${baseUrl}/${rec.id}/action/${type.preview.action}`, { analyze: true });
|
|
288
|
+
const d = res.data?.data ?? res.data ?? {};
|
|
289
|
+
const checks = Array.isArray(d.checks) ? d.checks : Array.isArray(d.issues) ? d.issues : [];
|
|
290
|
+
setServerIssues(checks
|
|
291
|
+
.filter((c) => c && c.severity !== 'ok' && c.message)
|
|
292
|
+
.map((c) => ({ field: c.field, severity: c.severity === 'error' ? 'error' : 'warning', message: String(c.message) })));
|
|
293
|
+
setPreview({ xml: d.xml, html: d.html, pdf_url: d.pdf_url, pdf_base64: d.pdf_base64 });
|
|
294
|
+
}
|
|
295
|
+
catch (err) {
|
|
296
|
+
handleError(err);
|
|
297
|
+
}
|
|
298
|
+
finally {
|
|
299
|
+
setBusy(null);
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
const togglePreview = (open) => {
|
|
303
|
+
setPreviewOpen(open);
|
|
304
|
+
if (open && !preview && busy === null)
|
|
305
|
+
void runPreview();
|
|
306
|
+
};
|
|
307
|
+
// ---- Guardar (acción primaria única) ----------------------------------------
|
|
308
|
+
const validateHeader = () => {
|
|
309
|
+
const fields = allFields.filter(visible);
|
|
310
|
+
const bag = validateValues(fields, header);
|
|
311
|
+
if (!bagHasErrors(bag)) {
|
|
312
|
+
setFieldErrors({});
|
|
313
|
+
return true;
|
|
314
|
+
}
|
|
315
|
+
const labels = {};
|
|
316
|
+
for (const f of fields)
|
|
317
|
+
labels[f.key] = tl(f.label);
|
|
318
|
+
const localized = localizeFieldErrorMap(bag, t, { labels, language: lang });
|
|
319
|
+
setFieldErrors(localized);
|
|
320
|
+
if (groups.advanced.some((f) => localized[f.key]))
|
|
321
|
+
setAdvancedOpen(true);
|
|
322
|
+
return false;
|
|
323
|
+
};
|
|
324
|
+
const submit = async () => {
|
|
325
|
+
setAttempted(true);
|
|
326
|
+
const headerOk = validateHeader();
|
|
327
|
+
if (!headerOk || blocking) {
|
|
328
|
+
setFormError(t('documentEditor.fix_issues', { defaultValue: 'Corrige los puntos marcados antes de guardar.' }));
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
setBusy('save');
|
|
332
|
+
setFormError(undefined);
|
|
333
|
+
try {
|
|
334
|
+
let saved;
|
|
335
|
+
if (type.submit_action) {
|
|
336
|
+
const res = await api.post(`${baseUrl}/action/${type.submit_action}`, payload());
|
|
337
|
+
if (res.data?.success === false)
|
|
338
|
+
throw { response: { data: res.data } };
|
|
339
|
+
saved = res.data?.data ?? res.data ?? undefined;
|
|
340
|
+
emitRecordMutation(model, 'create');
|
|
341
|
+
}
|
|
342
|
+
else {
|
|
343
|
+
saved = await saveDraft();
|
|
344
|
+
}
|
|
345
|
+
toast.success(t('dynamic.create_success', { defaultValue: 'Registro creado correctamente' }));
|
|
346
|
+
onSaved?.(saved);
|
|
347
|
+
}
|
|
348
|
+
catch (err) {
|
|
349
|
+
handleError(err);
|
|
350
|
+
}
|
|
351
|
+
finally {
|
|
352
|
+
setBusy(null);
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
// ---- Contribuciones de otros addons -----------------------------------------
|
|
356
|
+
const ctx = useMemo(() => ({ kind: type.key, model, values: header, mode: 'create' }), [type.key, model, header]);
|
|
357
|
+
const setValue = useCallback((key, value) => setHeader((h) => (h[key] === value ? h : { ...h, [key]: value })), []);
|
|
358
|
+
const report = useCallback((key, issue) => {
|
|
359
|
+
setContributed((prev) => {
|
|
360
|
+
const cur = prev[key];
|
|
361
|
+
if (!issue) {
|
|
362
|
+
if (!cur)
|
|
363
|
+
return prev;
|
|
364
|
+
const { [key]: _drop, ...rest } = prev;
|
|
365
|
+
return rest;
|
|
366
|
+
}
|
|
367
|
+
if (cur && cur.severity === issue.severity && cur.message === issue.message)
|
|
368
|
+
return prev;
|
|
369
|
+
return { ...prev, [key]: { ...issue, field: key } };
|
|
370
|
+
});
|
|
371
|
+
}, []);
|
|
372
|
+
const contribProps = useMemo(() => ({ ctx, setValue, issues: { report: report } }), [ctx, setValue, report]);
|
|
373
|
+
const headerContribs = useDocumentContributions(ctx, 'header.fields');
|
|
374
|
+
const partyContribs = useDocumentContributions(ctx, 'party.card');
|
|
375
|
+
const bodyContribs = useDocumentContributions(ctx, 'body.sections');
|
|
376
|
+
const sideContribs = useDocumentContributions(ctx, 'side.panels');
|
|
377
|
+
const footerContribs = useDocumentContributions(ctx, 'footer.actions');
|
|
378
|
+
// ---- Render -------------------------------------------------------------------
|
|
379
|
+
const updateField = (key, value) => {
|
|
380
|
+
setHeader((h) => ({ ...h, [key]: value }));
|
|
381
|
+
setFieldErrors((prev) => clearFieldErrorTree(prev, key));
|
|
382
|
+
};
|
|
383
|
+
const fieldCell = (field, fullWidth = false) => visible(field) ? (_jsxs(FieldCell, { fullWidth: fullWidth, children: [_jsx(FieldLabel, { htmlFor: field.key, required: field.required, children: tl(field.label) }), renderField(withFriendlyOptions(field), header[field.key], (v) => updateField(field.key, v), header, undefined, fieldErrors), fieldErrors[field.key] && _jsx("p", { className: "mt-1 text-xs text-destructive", children: fieldErrors[field.key] })] }, field.key)) : null;
|
|
384
|
+
const summaryRows = partySummaryRows(party, type.party?.summary, Object.fromEntries(allFields.map((f) => [f.key, tl(f.label)])));
|
|
385
|
+
const advancedSummary = groups.advanced
|
|
386
|
+
.filter(visible)
|
|
387
|
+
.map((f) => {
|
|
388
|
+
const v = header[f.key];
|
|
389
|
+
if (v == null || v === '')
|
|
390
|
+
return null;
|
|
391
|
+
const opt = f.options?.find((o) => String(o.value) === String(v));
|
|
392
|
+
return opt ? String(opt.value) : String(v);
|
|
393
|
+
})
|
|
394
|
+
.filter(Boolean)
|
|
395
|
+
.slice(0, 4)
|
|
396
|
+
.join(' · ');
|
|
397
|
+
const totalsRows = isAllocation
|
|
398
|
+
? [
|
|
399
|
+
{ label: t('documentEditor.received', { defaultValue: 'Recibido' }), value: fmt.money(amount) },
|
|
400
|
+
{ label: t('documentEditor.applied', { defaultValue: 'Aplicado' }), value: fmt.money(allocation.applied) },
|
|
401
|
+
...(allocation.unapplied > 0
|
|
402
|
+
? [{ label: t('documentEditor.unapplied', { defaultValue: 'Sin aplicar (saldo a favor)' }), value: fmt.money(allocation.unapplied) }]
|
|
403
|
+
: []),
|
|
404
|
+
]
|
|
405
|
+
: [
|
|
406
|
+
{ label: t('documentEditor.subtotal', { defaultValue: 'Subtotal' }), value: fmt.money(totals.subtotal) },
|
|
407
|
+
...(totals.discount > 0 ? [{ label: t('documentEditor.discount', { defaultValue: 'Descuento' }), value: `− ${fmt.money(totals.discount)}` }] : []),
|
|
408
|
+
...taxes.map((x) => ({
|
|
409
|
+
label: `${t('documentEditor.tax', { defaultValue: 'Impuesto' })} ${roundMoney(x.rate * 100)} %`,
|
|
410
|
+
value: fmt.money(x.tax),
|
|
411
|
+
})),
|
|
412
|
+
{ label: t('documentEditor.total', { defaultValue: 'Total' }), value: fmt.money(totals.total), emphasis: true },
|
|
413
|
+
];
|
|
414
|
+
const activeSource = sources.find((s) => s.key === sourceKey);
|
|
415
|
+
const linesTitle = lineCfg?.title
|
|
416
|
+
? tl(lineCfg.title)
|
|
417
|
+
: isAllocation
|
|
418
|
+
? t('documentEditor.allocation_title', { defaultValue: 'Documentos a pagar' })
|
|
419
|
+
: t('documentEditor.lines_title', { defaultValue: 'Conceptos' });
|
|
420
|
+
return (_jsxs("div", { className: "flex min-h-0 flex-1 flex-col", "data-slot": "document-editor", "data-kind": kind, children: [_jsxs("div", { className: "-mx-1 min-h-0 flex-1 space-y-8 overflow-y-auto px-1 py-2", children: [_jsx(FormErrorBanner, { message: formError }), _jsxs(EditorSection, { slot: "editor-essentials", children: [_jsxs(FieldGrid, { children: [groups.party && fieldCell(groups.party), groups.essential.map((f) => fieldCell(f))] }), party && (_jsx(PartyCard, { name: party.name ?? party.legal_name, rows: summaryRows, credit: credit, fmt: fmt, children: partyContribs.map(({ id, component: C }) => (_jsx(C, { ...contribProps }, id))) }))] }), sources.length > 0 && !isAllocation && (_jsx(EditorSection, { slot: "load-from-source", title: t('documentEditor.load_from', { defaultValue: 'Cargar desde…' }), hint: busy === 'source' ? t('documentEditor.loading_source', { defaultValue: 'Cargando…' }) : undefined, children: _jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [sources.length > 1 && (_jsxs("select", { "aria-label": t('documentEditor.source_kind', { defaultValue: 'Tipo de documento origen' }), className: "h-9 rounded-md border bg-background px-2 text-sm", value: sourceKey, onChange: (e) => {
|
|
421
|
+
setSourceKey(e.target.value);
|
|
422
|
+
setSourceId('');
|
|
423
|
+
}, children: [_jsx("option", { value: "", children: t('documentEditor.choose_source', { defaultValue: 'Elige…' }) }), sources.map((s) => (_jsx("option", { value: s.key, children: tl(s.label) }, s.key)))] })), (activeSource ?? (sources.length === 1 ? sources[0] : undefined)) && (_jsx(SourcePicker, { source: (activeSource ?? sources[0]), value: sourceId, header: header, label: tl((activeSource ?? sources[0]).label), onPick: (id) => {
|
|
424
|
+
if (!activeSource)
|
|
425
|
+
setSourceKey(sources[0].key);
|
|
426
|
+
setSourceId(id);
|
|
427
|
+
const src = activeSource ?? sources[0];
|
|
428
|
+
if (id)
|
|
429
|
+
void loadFromSource(src, id);
|
|
430
|
+
} }))] }) })), lineCfg && (_jsxs(EditorSection, { slot: isAllocation ? 'editor-allocation' : 'editor-lines', title: linesTitle, hint: isAllocation && openBalance > 0 && amountKey ? (_jsx("button", { type: "button", className: "underline-offset-2 hover:underline", onClick: () => updateField(amountKey, openBalance), children: t('documentEditor.pay_all', { defaultValue: 'Cobrar todo ({{amount}})', amount: fmt.money(openBalance) }) })) : undefined, children: [isAllocation ? (allocPartyId ? (_jsx(PaymentAllocator, { documents: openDocs, result: allocation, value: alloc, onChange: setAlloc, currency: currency, loading: docsLoading, today: today })) : (_jsx("p", { className: "text-sm text-muted-foreground", children: t('documentEditor.pick_party_first', { defaultValue: 'Elige el cliente para ver sus documentos con saldo.' }) }))) : (_jsx(DocumentLinesGrid, { value: lines, onChange: (next) => {
|
|
431
|
+
setLines(next);
|
|
432
|
+
setServerIssues([]);
|
|
433
|
+
}, columns: lineCfg.columns ?? ['discount', 'tax'], priceSource: lineCfg.price_source ?? (kind === 'purchase' ? 'cost' : 'sale'), discountMode: lineCfg.discount_mode, mode: linesFromSourceDoc ? 'from_source' : 'free', policy: kind === 'credit' ? { allowZeroQuantity: linesFromSourceDoc } : undefined, search: search, currency: currency })), _jsx(TotalsPanel, { rows: totalsRows })] })), (groups.advanced.length > 0 || headerContribs.length > 0) && (_jsxs(CollapsibleSection, { slot: "advanced-options", title: t('documentEditor.advanced', { defaultValue: 'Opciones fiscales' }), summary: advancedSummary || t('documentEditor.advanced_defaults', { defaultValue: 'Valores sugeridos' }), open: advancedOpen, onOpenChange: setAdvancedOpen, children: [groups.advanced.length > 0 && _jsx(FieldGrid, { children: groups.advanced.map((f) => fieldCell(f)) }), headerContribs.map(({ id, component: C }) => (_jsx(C, { ...contribProps }, id)))] })), [...bodyContribs, ...sideContribs].map(({ id, component: C }) => (_jsx("section", { "data-contribution": id, children: _jsx(C, { ...contribProps }) }, id))), groups.notes.length > 0 && _jsx(FieldGrid, { children: groups.notes.map((f) => fieldCell(f, true)) }), previewEnabled && (_jsx(CollapsibleSection, { slot: "preview", title: tl(type.preview.label ?? 'Vista previa'), open: previewOpen, onOpenChange: togglePreview, children: busy === 'preview' ? (_jsxs("p", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [_jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }), t('documentEditor.preview_loading', { defaultValue: 'Generando vista previa…' })] })) : (_jsxs(_Fragment, { children: [_jsx(PreviewPanel, { preview: preview }), _jsx(Button, { type: "button", variant: "ghost", size: "sm", onClick: () => void runPreview(), disabled: busy !== null, children: t('documentEditor.preview_refresh', { defaultValue: 'Actualizar vista previa' }) })] })) })), _jsx(ValidationChecklist, { issues: shownIssues, title: t('documentEditor.review', { defaultValue: 'Revisa antes de guardar' }) })] }), _jsxs("footer", { className: "flex shrink-0 flex-wrap items-center justify-end gap-2 border-t pt-4", "data-slot": "editor-actions", children: [footerContribs.map(({ id, component: C }) => (_jsx(C, { ...contribProps }, id))), _jsx(Button, { type: "button", variant: "ghost", onClick: onCancel, disabled: busy === 'save', children: t('common.cancel', { defaultValue: 'Cancelar' }) }), _jsxs(Button, { type: "button", "data-primary": "true", onClick: () => void submit(), disabled: busy !== null, children: [busy === 'save' && _jsx(Loader2, { className: "mr-2 size-4 animate-spin", "aria-hidden": true }), type.submit_label ? tl(type.submit_label) : t('common.save', { defaultValue: 'Guardar' })] })] })] }));
|
|
434
|
+
}
|
|
435
|
+
/** Selector del documento origen (mismo widget de relación que el resto de formularios). */
|
|
436
|
+
function SourcePicker({ source, value, header, label, onPick, }) {
|
|
437
|
+
const field = useMemo(() => ({
|
|
438
|
+
key: `__source_${source.key}`,
|
|
439
|
+
label,
|
|
440
|
+
type: 'dynamic_select',
|
|
441
|
+
ref: source.model,
|
|
442
|
+
option_filter: source.option_filter,
|
|
443
|
+
}), [source, label]);
|
|
444
|
+
return (_jsx("div", { className: "min-w-[240px] flex-1", "data-source": source.key, children: renderField(field, value, (v) => onPick(v == null || v === '' ? '' : String(v)), header) }));
|
|
445
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document-lines.d.ts","sourceRoot":"","sources":["../../src/business/document-lines.ts"],"names":[],"mappings":"AAGA,OAAO,EAAY,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAA;AACtD,OAAO,EAAkB,KAAK,aAAa,EAAE,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAA;AAE1F,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,MAAM,GAAG,QAAQ,CAAA;AACpD,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,aAAa,CAAA;AAEtD,8DAA8D;AAC9D,wBAAgB,gBAAgB,CAC5B,OAAO,EAAE,aAAa,EACtB,OAAO,EAAE,cAAc,GAAG,SAAS,EACnC,MAAM,EAAE,WAAW,GACpB,MAAM,CAKR;AAED,uGAAuG;AACvG,wBAAgB,kBAAkB,CAC9B,IAAI,EAAE,QAAQ,EACd,OAAO,EAAE,aAAa,EACtB,OAAO,CAAC,EAAE,cAAc,EACxB,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,WAAW,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GAClF,QAAQ,
|
|
1
|
+
{"version":3,"file":"document-lines.d.ts","sourceRoot":"","sources":["../../src/business/document-lines.ts"],"names":[],"mappings":"AAGA,OAAO,EAAY,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAA;AACtD,OAAO,EAAkB,KAAK,aAAa,EAAE,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAA;AAE1F,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,MAAM,GAAG,QAAQ,CAAA;AACpD,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,aAAa,CAAA;AAEtD,8DAA8D;AAC9D,wBAAgB,gBAAgB,CAC5B,OAAO,EAAE,aAAa,EACtB,OAAO,EAAE,cAAc,GAAG,SAAS,EACnC,MAAM,EAAE,WAAW,GACpB,MAAM,CAKR;AAED,uGAAuG;AACvG,wBAAgB,kBAAkB,CAC9B,IAAI,EAAE,QAAQ,EACd,OAAO,EAAE,aAAa,EACtB,OAAO,CAAC,EAAE,cAAc,EACxB,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,WAAW,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GAClF,QAAQ,CAuBV;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC1B,KAAK,EAAE,QAAQ,EAAE,EACjB,OAAO,EAAE,aAAa,EACtB,OAAO,CAAC,EAAE,cAAc,EACxB,IAAI,GAAE;IACF,WAAW,CAAC,EAAE,WAAW,CAAA;IACzB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,gBAAgB,CAAC,EAAE,OAAO,CAAA;CACxB,GACP,QAAQ,EAAE,CAeZ;AAED,MAAM,MAAM,eAAe,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,GAAG,MAAM,CAAA;AAEhE,2GAA2G;AAC3G,wBAAgB,kBAAkB,CAC9B,GAAG,EAAE,MAAM,EACX,IAAI,GAAE;IAAE,eAAe,CAAC,EAAE,OAAO,CAAC;IAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,iBAAiB,CAAA;CAAO,GACxF,eAAe,CAKjB"}
|