admin-lib-cms 1.2.16 → 1.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -35,9 +35,13 @@ import {
35
35
  Switch,
36
36
  Button,
37
37
  Image,
38
- App
38
+ App,
39
+ Tag,
40
+ Progress,
41
+ Radio,
42
+ Segmented
39
43
  } from "antd";
40
- import dayjs from "dayjs";
44
+ import dayjs2 from "dayjs";
41
45
  import {
42
46
  FileText,
43
47
  Boxes,
@@ -68,9 +72,226 @@ import {
68
72
  Check,
69
73
  GripVertical,
70
74
  AlertTriangle,
71
- FileDown
75
+ FileDown,
76
+ FileUp,
77
+ FileSpreadsheet
72
78
  } from "lucide-react";
73
79
 
80
+ // src/admin/excel.ts
81
+ import * as XLSX from "xlsx";
82
+ import dayjs from "dayjs";
83
+ function filterEntriesByDateRange(entries, fieldId, startDate, endDate) {
84
+ if (!startDate && !endDate) return entries;
85
+ const startDayjs = startDate ? dayjs(startDate).startOf("day") : null;
86
+ const endDayjs = endDate ? dayjs(endDate).endOf("day") : null;
87
+ return entries.filter((e) => {
88
+ const val = e[fieldId];
89
+ if (!val) return false;
90
+ const d = dayjs(String(val));
91
+ if (!d.isValid()) return false;
92
+ if (startDayjs && d.isBefore(startDayjs)) return false;
93
+ if (endDayjs && d.isAfter(endDayjs)) return false;
94
+ return true;
95
+ });
96
+ }
97
+ function findExistingEntry(item, existingEntries, collection) {
98
+ if (item.id && !item.id.startsWith("item_")) {
99
+ const cleanId = String(item.id).trim().toLowerCase();
100
+ const matchById = existingEntries.find(
101
+ (e) => e.id && String(e.id).trim().toLowerCase() === cleanId || e._id && String(e._id).trim().toLowerCase() === cleanId
102
+ );
103
+ if (matchById) return matchById;
104
+ }
105
+ const uniqueFieldIds = [];
106
+ (collection.fields || []).forEach((f) => {
107
+ if (f.unique && !uniqueFieldIds.includes(f.id)) {
108
+ uniqueFieldIds.push(f.id);
109
+ }
110
+ });
111
+ (collection.uniqueFields || []).forEach((uf) => {
112
+ if (!uniqueFieldIds.includes(uf)) {
113
+ uniqueFieldIds.push(uf);
114
+ }
115
+ });
116
+ for (const ufId of uniqueFieldIds) {
117
+ const itemVal = item[ufId];
118
+ if (itemVal !== void 0 && itemVal !== null && String(itemVal).trim() !== "") {
119
+ const cleanVal = String(itemVal).trim().toLowerCase();
120
+ const match = existingEntries.find((e) => {
121
+ const eVal = e[ufId];
122
+ return eVal !== void 0 && eVal !== null && String(eVal).trim().toLowerCase() === cleanVal;
123
+ });
124
+ if (match) return match;
125
+ }
126
+ }
127
+ return null;
128
+ }
129
+ function formatValueForExport(val, field) {
130
+ if (val === void 0 || val === null) return "";
131
+ if (typeof val === "number" || typeof val === "boolean") return val;
132
+ if (Array.isArray(val)) {
133
+ return val.map((item) => typeof item === "object" && item !== null ? JSON.stringify(item) : String(item)).join(", ");
134
+ }
135
+ if (typeof val === "object") {
136
+ try {
137
+ return JSON.stringify(val);
138
+ } catch {
139
+ return String(val);
140
+ }
141
+ }
142
+ return String(val);
143
+ }
144
+ function exportCollectionToExcel(collection, entries, fileNamePrefix) {
145
+ const columns = [
146
+ { key: "id", label: "ID" }
147
+ ];
148
+ (collection.fields || []).forEach((f) => {
149
+ columns.push({
150
+ key: f.id,
151
+ label: f.label || f.id,
152
+ field: f
153
+ });
154
+ });
155
+ const rows = entries.map((entry) => {
156
+ const rowObj = {};
157
+ columns.forEach((col) => {
158
+ const rawVal = entry[col.key];
159
+ rowObj[col.label] = formatValueForExport(rawVal, col.field);
160
+ });
161
+ return rowObj;
162
+ });
163
+ const worksheet = XLSX.utils.json_to_sheet(rows);
164
+ const colWidths = columns.map((col) => {
165
+ let maxLen = col.label.length;
166
+ for (let i = 0; i < Math.min(rows.length, 100); i++) {
167
+ const cellVal = String(rows[i]?.[col.label] ?? "");
168
+ if (cellVal.length > maxLen) {
169
+ maxLen = Math.min(cellVal.length, 45);
170
+ }
171
+ }
172
+ return { wch: Math.max(maxLen + 3, 12) };
173
+ });
174
+ worksheet["!cols"] = colWidths;
175
+ const workbook = XLSX.utils.book_new();
176
+ const safeSheetName = (collection.name || collection.id).replace(/[\\/?*[\]:]/g, "").slice(0, 31) || "Datos";
177
+ XLSX.utils.book_append_sheet(workbook, worksheet, safeSheetName);
178
+ const dateStr = dayjs().format("YYYY-MM-DD");
179
+ const baseName = fileNamePrefix || (collection.name || collection.id).toLowerCase().replace(/[^a-z0-9_-]+/g, "_");
180
+ const fileName = `${baseName}_${dateStr}.xlsx`;
181
+ XLSX.writeFile(workbook, fileName);
182
+ }
183
+ async function parseExcelForCollection(file, collection, existingEntries = []) {
184
+ const data = await file.arrayBuffer();
185
+ const workbook = XLSX.read(data, { type: "array" });
186
+ const firstSheetName = workbook.SheetNames[0];
187
+ if (!firstSheetName) {
188
+ throw new Error("El archivo no contiene ninguna hoja de c\xE1lculo.");
189
+ }
190
+ const worksheet = workbook.Sheets[firstSheetName];
191
+ const rawRows = XLSX.utils.sheet_to_json(worksheet, { defval: "" });
192
+ if (!rawRows.length) {
193
+ return {
194
+ records: [],
195
+ totalRows: 0,
196
+ matchedFields: [],
197
+ unmatchedHeaders: [],
198
+ samplePreview: [],
199
+ errors: ["El archivo no contiene filas con datos."]
200
+ };
201
+ }
202
+ const headers = Object.keys(rawRows[0] || {});
203
+ const matchedFields = [];
204
+ const unmatchedHeaders = [];
205
+ const headerToFieldMap = /* @__PURE__ */ new Map();
206
+ headers.forEach((header) => {
207
+ const cleanHeader = header.trim().toLowerCase();
208
+ if (cleanHeader === "id" || cleanHeader === "_id" || cleanHeader === "identificador") {
209
+ headerToFieldMap.set(header, "id");
210
+ matchedFields.push({ label: header, fieldId: "id" });
211
+ return;
212
+ }
213
+ const matched = (collection.fields || []).find((f) => {
214
+ const fieldLabel = (f.label || "").trim().toLowerCase();
215
+ const fieldId = f.id.trim().toLowerCase();
216
+ return fieldLabel === cleanHeader || fieldId === cleanHeader;
217
+ });
218
+ if (matched) {
219
+ headerToFieldMap.set(header, matched);
220
+ matchedFields.push({ label: header, fieldId: matched.id });
221
+ } else {
222
+ unmatchedHeaders.push(header);
223
+ }
224
+ });
225
+ const records = [];
226
+ const errors = [];
227
+ rawRows.forEach((row, idx) => {
228
+ const entry = { id: "" };
229
+ (collection.fields || []).forEach((f) => {
230
+ if (f.defaultValue !== void 0) {
231
+ entry[f.id] = f.defaultValue;
232
+ }
233
+ });
234
+ headers.forEach((header) => {
235
+ const mapping = headerToFieldMap.get(header);
236
+ const rawVal = row[header];
237
+ if (rawVal === void 0 || rawVal === "") return;
238
+ if (mapping === "id") {
239
+ entry.id = String(rawVal).trim();
240
+ return;
241
+ }
242
+ if (!mapping) return;
243
+ const field = mapping;
244
+ if (field.type === "number") {
245
+ const num = Number(String(rawVal).replace(/[^0-9.-]/g, ""));
246
+ entry[field.id] = isNaN(num) ? rawVal : num;
247
+ } else if (field.type === "boolean") {
248
+ const str = String(rawVal).trim().toLowerCase();
249
+ entry[field.id] = str === "true" || str === "si" || str === "s\xED" || str === "yes" || str === "1" || str === "verdadero";
250
+ } else if (field.multiple || field.type === "list") {
251
+ if (typeof rawVal === "string") {
252
+ entry[field.id] = rawVal.split(/[,;\n]/).map((s) => s.trim()).filter(Boolean);
253
+ } else if (Array.isArray(rawVal)) {
254
+ entry[field.id] = rawVal;
255
+ } else {
256
+ entry[field.id] = [String(rawVal)];
257
+ }
258
+ } else if (typeof rawVal === "string" && (rawVal.startsWith("{") || rawVal.startsWith("["))) {
259
+ try {
260
+ entry[field.id] = JSON.parse(rawVal);
261
+ } catch {
262
+ entry[field.id] = rawVal;
263
+ }
264
+ } else {
265
+ entry[field.id] = rawVal;
266
+ }
267
+ });
268
+ if (!entry.id) {
269
+ entry.id = typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `item_${Date.now()}_${idx}`;
270
+ }
271
+ records.push(entry);
272
+ });
273
+ let existingCount = 0;
274
+ let newCount = 0;
275
+ records.forEach((rec) => {
276
+ const existing = findExistingEntry(rec, existingEntries, collection);
277
+ if (existing) {
278
+ existingCount++;
279
+ } else {
280
+ newCount++;
281
+ }
282
+ });
283
+ return {
284
+ records,
285
+ totalRows: records.length,
286
+ matchedFields,
287
+ unmatchedHeaders,
288
+ samplePreview: records.slice(0, 5),
289
+ existingRecordsCount: existingCount,
290
+ newRecordsCount: newCount,
291
+ errors
292
+ };
293
+ }
294
+
74
295
  // src/admin/i18n.ts
75
296
  var translations = {
76
297
  es: {
@@ -126,8 +347,11 @@ var translations = {
126
347
  saveSignature: "Guardar Firma",
127
348
  selectOption: "-- Selecciona una opci\xF3n --",
128
349
  loadingOptions: "Cargando opciones...",
129
- cantFindClient: "\xBFNo encuentras el cliente?",
130
- createClient: "Crear cliente",
350
+ cantFindOption: "\xBFNo encuentras la opci\xF3n?",
351
+ createNewOption: "Crear nuevo",
352
+ recordCreatedSuccess: "Registro creado y seleccionado exitosamente.",
353
+ cantFindClient: "\xBFNo encuentras la opci\xF3n?",
354
+ createClient: "Crear nuevo",
131
355
  newBtn: "Nuevo",
132
356
  basicDetails: "Datos b\xE1sicos",
133
357
  clientType: "Tipo",
@@ -152,6 +376,29 @@ var translations = {
152
376
  submissions: "Mensajes y Formularios",
153
377
  noSubmissions: "No hay env\xEDos registrados",
154
378
  exportCsv: "Exportar CSV",
379
+ exportExcel: "Exportar Excel",
380
+ importExcel: "Importar Excel",
381
+ exportSuccess: "Archivo Excel exportado con \xE9xito.",
382
+ importSuccess: "registros procesados exitosamente.",
383
+ exportModalTitle: "Exportar a Excel",
384
+ exportAllRecords: "Todos los registros",
385
+ exportFilterByDate: "Filtrar por rango de fechas",
386
+ exportDateFieldLabel: "Campo de fecha",
387
+ exportDateRangeLabel: "Rango de fechas",
388
+ exportDownloadBtn: "Descargar Excel",
389
+ exportNoRecordsInRange: "No se encontraron registros en el rango seleccionado.",
390
+ importModalTitle: "Importar datos desde Excel / CSV",
391
+ importModalDesc: "Carga un archivo .xlsx, .xls o .csv para agregar o actualizar registros autom\xE1ticamente.",
392
+ importDropzone: "Haz clic o arrastra un archivo Excel aqu\xED",
393
+ importDropzoneSub: "Formatos compatibles: .xlsx, .xls, .csv. La primera fila debe contener los encabezados.",
394
+ importPreviewTitle: "Vista previa de importaci\xF3n",
395
+ importConfirmBtn: "Importar registros",
396
+ importOverwritesWarning: "Tratamiento de registros ya existentes:",
397
+ importingProgress: "Importando registros...",
398
+ importExistingOmit: "Omitir existentes (no volver a crear ni duplicar)",
399
+ importExistingUpdate: "Actualizar existentes con datos del archivo",
400
+ importExistingDetected: "ya existentes",
401
+ importNewDetected: "nuevos a crear",
155
402
  markRead: "Marcar como le\xEDdo",
156
403
  settingsTitle: "Ajustes del sitio",
157
404
  entries: "registros"
@@ -209,8 +456,11 @@ var translations = {
209
456
  saveSignature: "Save Signature",
210
457
  selectOption: "-- Select an option --",
211
458
  loadingOptions: "Loading options...",
212
- cantFindClient: "Can't find the client?",
213
- createClient: "Create client",
459
+ cantFindOption: "Can't find the option?",
460
+ createNewOption: "Create new",
461
+ recordCreatedSuccess: "Record created and selected successfully.",
462
+ cantFindClient: "Can't find the option?",
463
+ createClient: "Create new",
214
464
  newBtn: "New",
215
465
  basicDetails: "Basic details",
216
466
  clientType: "Type",
@@ -235,6 +485,29 @@ var translations = {
235
485
  submissions: "Form Submissions",
236
486
  noSubmissions: "No submissions yet",
237
487
  exportCsv: "Export CSV",
488
+ exportExcel: "Export Excel",
489
+ importExcel: "Import Excel",
490
+ exportSuccess: "Excel file exported successfully.",
491
+ importSuccess: "records processed successfully.",
492
+ exportModalTitle: "Export to Excel",
493
+ exportAllRecords: "All records",
494
+ exportFilterByDate: "Filter by date range",
495
+ exportDateFieldLabel: "Date field",
496
+ exportDateRangeLabel: "Date range",
497
+ exportDownloadBtn: "Download Excel",
498
+ exportNoRecordsInRange: "No records found in the selected date range.",
499
+ importModalTitle: "Import data from Excel / CSV",
500
+ importModalDesc: "Upload a .xlsx, .xls or .csv file to automatically create or update records.",
501
+ importDropzone: "Click or drag an Excel file here",
502
+ importDropzoneSub: "Supported formats: .xlsx, .xls, .csv. The first row must contain column headers.",
503
+ importPreviewTitle: "Import Preview",
504
+ importConfirmBtn: "Import records",
505
+ importOverwritesWarning: "Handling of existing records:",
506
+ importingProgress: "Importing records...",
507
+ importExistingOmit: "Skip existing (do not recreate or duplicate)",
508
+ importExistingUpdate: "Update existing with file data",
509
+ importExistingDetected: "existing records",
510
+ importNewDetected: "new to create",
238
511
  markRead: "Mark as read",
239
512
  settingsTitle: "Site Settings",
240
513
  entries: "entries"
@@ -305,13 +578,13 @@ function toDayjsTime(value) {
305
578
  const isPm = match12[3].toLowerCase().startsWith("p");
306
579
  if (isPm && h < 12) h += 12;
307
580
  if (!isPm && h === 12) h = 0;
308
- return dayjs().hour(h).minute(m).second(0).millisecond(0);
581
+ return dayjs2().hour(h).minute(m).second(0).millisecond(0);
309
582
  }
310
583
  const match24 = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(str);
311
584
  if (match24) {
312
- return dayjs().hour(Number(match24[1])).minute(Number(match24[2])).second(0).millisecond(0);
585
+ return dayjs2().hour(Number(match24[1])).minute(Number(match24[2])).second(0).millisecond(0);
313
586
  }
314
- const parsed = dayjs(str, ["h:mm a", "h:mm A", "hh:mm a", "hh:mm A", "HH:mm"]);
587
+ const parsed = dayjs2(str, ["h:mm a", "h:mm A", "hh:mm a", "hh:mm A", "HH:mm"]);
315
588
  return parsed.isValid() ? parsed : null;
316
589
  }
317
590
  function toStoredTime(value) {
@@ -1691,37 +1964,37 @@ function CollectionsSection() {
1691
1964
  });
1692
1965
  }, [ctx.adapter, colIds, ctx.collectionChangedAt]);
1693
1966
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col md:flex-row h-full bg-slate-50", children: [
1694
- /* @__PURE__ */ jsxs("div", { className: "w-full md:w-72 shrink-0 border-b md:border-b-0 md:border-r border-slate-200 bg-white/50 p-4", children: [
1695
- /* @__PURE__ */ jsx("div", { className: "mb-3 px-2 text-xs font-bold uppercase tracking-widest text-slate-500", children: "Collections" }),
1696
- /* @__PURE__ */ jsxs("ul", { className: "flex overflow-x-auto gap-2 pb-2 md:block md:space-x-0 md:space-y-1 md:pb-0 md:overflow-visible", children: [
1967
+ /* @__PURE__ */ jsxs("div", { className: "w-full md:w-72 shrink-0 border-b md:border-b-0 md:border-r border-slate-200 bg-white/50 p-2 sm:p-3 md:p-4", children: [
1968
+ /* @__PURE__ */ jsx("div", { className: "hidden md:block mb-3 px-2 text-xs font-bold uppercase tracking-widest text-slate-500", children: "Collections" }),
1969
+ /* @__PURE__ */ jsxs("ul", { className: "flex items-center md:items-stretch overflow-x-auto gap-1.5 p-1 md:p-0 md:block md:space-x-0 md:space-y-1 md:overflow-visible", children: [
1697
1970
  collections.map((c, idx) => {
1698
1971
  if (c.isSeparator) {
1699
1972
  return /* @__PURE__ */ jsx(
1700
1973
  "li",
1701
1974
  {
1702
- className: "my-3 border-t border-slate-200/80 pt-2 px-1 list-none",
1703
- children: c.name && /* @__PURE__ */ jsx("span", { className: "text-[10px] font-bold uppercase tracking-wider text-slate-400", children: c.name })
1975
+ className: "self-center shrink-0 h-6 w-px bg-slate-200 mx-1 md:h-auto md:w-auto md:mx-0 md:my-3 md:border-t md:border-slate-200/80 md:pt-2 md:px-1 list-none",
1976
+ children: c.name && /* @__PURE__ */ jsx("span", { className: "hidden md:block text-[10px] font-bold uppercase tracking-wider text-slate-400", children: c.name })
1704
1977
  },
1705
1978
  c.id || `sep-${idx}`
1706
1979
  );
1707
1980
  }
1708
- return /* @__PURE__ */ jsx("li", { className: "shrink-0 min-w-[140px] md:w-full md:min-w-0", children: /* @__PURE__ */ jsxs(
1981
+ return /* @__PURE__ */ jsx("li", { className: "shrink-0 md:w-full md:min-w-0", children: /* @__PURE__ */ jsxs(
1709
1982
  "button",
1710
1983
  {
1711
1984
  onClick: () => setSelected(c),
1712
- className: `w-full rounded-lg px-3 py-2.5 text-left text-sm transition-all duration-200 ${selected?.id === c.id ? "bg-white shadow-sm ring-1 ring-slate-200 font-semibold" : "hover:bg-slate-100"}`,
1985
+ className: `rounded-xl px-3.5 py-2 md:w-full md:px-3 md:py-2.5 text-left text-xs md:text-sm transition-all duration-200 ${selected?.id === c.id ? "bg-white border border-slate-200/90 shadow-2xs font-semibold" : "text-slate-600 hover:text-slate-900 hover:bg-slate-100/70 border border-transparent"}`,
1713
1986
  children: [
1714
1987
  /* @__PURE__ */ jsx(
1715
1988
  "div",
1716
1989
  {
1717
- className: selected?.id === c.id ? "text-slate-900" : "text-slate-700",
1990
+ className: selected?.id === c.id ? "text-slate-900 font-bold" : "text-slate-700 font-medium",
1718
1991
  children: c.name
1719
1992
  }
1720
1993
  ),
1721
1994
  /* @__PURE__ */ jsxs(
1722
1995
  "div",
1723
1996
  {
1724
- className: `text-xs mt-0.5 ${selected?.id === c.id ? "text-indigo-500" : "text-slate-400"}`,
1997
+ className: `text-[10px] md:text-xs mt-0.5 ${selected?.id === c.id ? "text-indigo-600 font-medium" : "text-slate-400"}`,
1725
1998
  children: [
1726
1999
  counts[c.id] ?? 0,
1727
2000
  " items"
@@ -1735,7 +2008,7 @@ function CollectionsSection() {
1735
2008
  collections.length === 0 && /* @__PURE__ */ jsx("li", { className: "px-3 py-6 text-center text-sm text-slate-500 bg-slate-50 rounded-lg border border-dashed border-slate-200", children: "No collections registered." })
1736
2009
  ] })
1737
2010
  ] }),
1738
- /* @__PURE__ */ jsxs("div", { className: "flex-1 overflow-auto p-4 md:p-8 relative", children: [
2011
+ /* @__PURE__ */ jsxs("div", { className: "flex-1 overflow-auto p-2 sm:p-4 md:p-8 relative", children: [
1739
2012
  /* @__PURE__ */ jsx("div", { className: "absolute inset-0 bg-grid-slate-100 [mask-image:linear-gradient(0deg,white,rgba(255,255,255,0.6))] -z-10 pointer-events-none" }),
1740
2013
  selected ? /* @__PURE__ */ jsx(CollectionEditor, { collection: selected }, selected.id) : /* @__PURE__ */ jsx("div", { className: "grid h-full place-items-center text-sm text-slate-500", children: "Select a collection to manage its entries." })
1741
2014
  ] })
@@ -1751,6 +2024,16 @@ function CollectionEditor({ collection }) {
1751
2024
  const [duplicateErrors, setDuplicateErrors] = useState({});
1752
2025
  const [isCreatingManual, setIsCreatingManual] = useState(false);
1753
2026
  const [isViewingDetail, setIsViewingDetail] = useState(false);
2027
+ const [customViewingRecord, setCustomViewingRecord] = useState(null);
2028
+ const [isCustomEditing, setIsCustomEditing] = useState(false);
2029
+ const [customActiveView, setCustomActiveView] = useState(null);
2030
+ const [isCustomCreating, setIsCustomCreating] = useState(false);
2031
+ useEffect(() => {
2032
+ setCustomViewingRecord(null);
2033
+ setIsCustomEditing(false);
2034
+ setCustomActiveView(null);
2035
+ setIsCustomCreating(false);
2036
+ }, [collection.id]);
1754
2037
  const [saving, setSaving] = useState(false);
1755
2038
  const [deletingId, setDeletingId] = useState(null);
1756
2039
  const [loadingEntries, setLoadingEntries] = useState(true);
@@ -1760,13 +2043,74 @@ function CollectionEditor({ collection }) {
1760
2043
  const [filters, setFilters] = useState({});
1761
2044
  const [page, setPage] = useState(1);
1762
2045
  const itemsPerPage = 10;
2046
+ const dateFields = useMemo(() => {
2047
+ const list = [];
2048
+ (collection.fields || []).forEach((f) => {
2049
+ if (f.type === "date" || f.type === "datetime" || f.id === "fecha" || f.id.toLowerCase().includes("fecha") || f.id.toLowerCase().includes("date")) {
2050
+ list.push({ id: f.id, label: f.label || f.id });
2051
+ }
2052
+ });
2053
+ const hasCreatedAt = entries.some((e) => e._createdAt);
2054
+ if (hasCreatedAt && !list.some((f) => f.id === "_createdAt")) {
2055
+ list.push({ id: "_createdAt", label: "Fecha de creaci\xF3n (_createdAt)" });
2056
+ }
2057
+ return list;
2058
+ }, [collection.fields, entries]);
2059
+ const [isExportModalOpen, setIsExportModalOpen] = useState(false);
2060
+ const [exportMode, setExportMode] = useState("all");
2061
+ const [exportDateField, setExportDateField] = useState("");
2062
+ const [exportDateRange, setExportDateRange] = useState(null);
2063
+ useEffect(() => {
2064
+ if (dateFields.length > 0 && !exportDateField) {
2065
+ setExportDateField(dateFields[0].id);
2066
+ }
2067
+ }, [dateFields, exportDateField]);
2068
+ const exportTargetEntries = useMemo(() => {
2069
+ if (exportMode === "all" || !exportDateField || !exportDateRange || !exportDateRange[0] || !exportDateRange[1]) {
2070
+ return entries;
2071
+ }
2072
+ return filterEntriesByDateRange(
2073
+ entries,
2074
+ exportDateField,
2075
+ exportDateRange[0].format("YYYY-MM-DD"),
2076
+ exportDateRange[1].format("YYYY-MM-DD")
2077
+ );
2078
+ }, [entries, exportMode, exportDateField, exportDateRange]);
2079
+ const [isImportModalOpen, setIsImportModalOpen] = useState(false);
2080
+ const [importFile, setImportFile] = useState(null);
2081
+ const [importResult, setImportResult] = useState(null);
2082
+ const [isParsingImport, setIsParsingImport] = useState(false);
2083
+ const [isImporting, setIsImporting] = useState(false);
2084
+ const [importExistingAction, setImportExistingAction] = useState("omit");
2085
+ const [importProgress, setImportProgress] = useState({ current: 0, total: 0 });
2086
+ const fileInputRef = useRef(null);
1763
2087
  const load = useCallback(() => {
1764
2088
  setLoadingEntries(true);
1765
2089
  ctx.adapter.listEntries(collection.id).then((res) => {
1766
2090
  const sorted = [...res].sort((a, b) => {
1767
- const orderA = Number(a.order) || 0;
1768
- const orderB = Number(b.order) || 0;
1769
- return orderA - orderB;
2091
+ if (collection.defaultSort) {
2092
+ if (typeof collection.defaultSort === "function") {
2093
+ return collection.defaultSort(a, b);
2094
+ }
2095
+ const field = collection.defaultSort.field;
2096
+ const valA = a[field];
2097
+ const valB = b[field];
2098
+ const dir = collection.defaultSort.direction === "desc" ? -1 : 1;
2099
+ if (valA === valB) return 0;
2100
+ if (valA === void 0 || valA === null) return 1;
2101
+ if (valB === void 0 || valB === null) return -1;
2102
+ if (typeof valA === "number" && typeof valB === "number") {
2103
+ return (valA - valB) * dir;
2104
+ }
2105
+ return String(valA).localeCompare(String(valB)) * dir;
2106
+ }
2107
+ const hasOrderField = collection.fields.some((f) => f.id === "order");
2108
+ if (hasOrderField) {
2109
+ const orderA = Number(a.order) || 0;
2110
+ const orderB = Number(b.order) || 0;
2111
+ if (orderA !== orderB) return orderA - orderB;
2112
+ }
2113
+ return 0;
1770
2114
  });
1771
2115
  setEntries(sorted);
1772
2116
  setLoadingEntries(false);
@@ -1775,7 +2119,111 @@ function CollectionEditor({ collection }) {
1775
2119
  useEffect(() => {
1776
2120
  load();
1777
2121
  }, [load]);
2122
+ const handleOpenExportModal = () => {
2123
+ if (dateFields.length === 0) {
2124
+ try {
2125
+ exportCollectionToExcel(collection, entries);
2126
+ message.success(t.exportSuccess);
2127
+ } catch (err) {
2128
+ console.error("Error exportando a Excel:", err);
2129
+ message.error("No se pudo exportar a Excel.");
2130
+ }
2131
+ return;
2132
+ }
2133
+ setIsExportModalOpen(true);
2134
+ };
2135
+ const handleConfirmExport = () => {
2136
+ try {
2137
+ let suffix = "";
2138
+ if (exportMode === "byDate" && exportDateRange?.[0] && exportDateRange?.[1]) {
2139
+ suffix = `${(collection.name || collection.id).toLowerCase()}_${exportDateRange[0].format("YYYYMMDD")}_al_${exportDateRange[1].format("YYYYMMDD")}`;
2140
+ }
2141
+ exportCollectionToExcel(collection, exportTargetEntries, suffix);
2142
+ message.success(t.exportSuccess);
2143
+ setIsExportModalOpen(false);
2144
+ } catch (err) {
2145
+ console.error("Error exportando a Excel:", err);
2146
+ message.error("No se pudo exportar a Excel.");
2147
+ }
2148
+ };
2149
+ const handleProcessImportFile = async (file) => {
2150
+ setIsParsingImport(true);
2151
+ setImportFile(file);
2152
+ try {
2153
+ const res = await parseExcelForCollection(file, collection, entries);
2154
+ setImportResult(res);
2155
+ if (res.errors.length > 0) {
2156
+ message.warning(res.errors[0]);
2157
+ }
2158
+ } catch (err) {
2159
+ console.error("Error parseando archivo Excel:", err);
2160
+ message.error(err?.message || "Error al leer el archivo Excel.");
2161
+ setImportResult(null);
2162
+ setImportFile(null);
2163
+ } finally {
2164
+ setIsParsingImport(false);
2165
+ }
2166
+ };
2167
+ const handleExecuteImport = async () => {
2168
+ if (!importResult || !importResult.records.length) return;
2169
+ setIsImporting(true);
2170
+ const total = importResult.records.length;
2171
+ setImportProgress({ current: 0, total });
2172
+ try {
2173
+ let createdCount = 0;
2174
+ let updatedCount = 0;
2175
+ let omittedCount = 0;
2176
+ for (let i = 0; i < total; i++) {
2177
+ const item = { ...importResult.records[i] };
2178
+ const existing = findExistingEntry(item, entries, collection);
2179
+ if (existing) {
2180
+ if (importExistingAction === "omit") {
2181
+ omittedCount++;
2182
+ } else {
2183
+ const merged = { ...existing, ...item, id: existing.id };
2184
+ if (existing._id) merged._id = existing._id;
2185
+ await ctx.adapter.putEntry(collection.id, merged);
2186
+ updatedCount++;
2187
+ }
2188
+ } else {
2189
+ await ctx.adapter.putEntry(collection.id, item);
2190
+ createdCount++;
2191
+ }
2192
+ setImportProgress({ current: i + 1, total });
2193
+ }
2194
+ if (createdCount > 0 && omittedCount > 0) {
2195
+ message.success(
2196
+ `Se importaron ${createdCount} registros nuevos. Se omitieron ${omittedCount} registros ya existentes.`
2197
+ );
2198
+ } else if (createdCount > 0 && updatedCount > 0) {
2199
+ message.success(
2200
+ `Se crearon ${createdCount} registros y se actualizaron ${updatedCount} existentes.`
2201
+ );
2202
+ } else if (createdCount > 0) {
2203
+ message.success(`Se importaron ${createdCount} registros exitosamente.`);
2204
+ } else if (omittedCount > 0) {
2205
+ message.info(
2206
+ `Los ${omittedCount} registros ya se encontraban creados. No se duplic\xF3 ning\xFAn dato.`
2207
+ );
2208
+ } else if (updatedCount > 0) {
2209
+ message.success(`Se actualizaron ${updatedCount} registros existentes.`);
2210
+ }
2211
+ load();
2212
+ setIsImportModalOpen(false);
2213
+ setImportResult(null);
2214
+ setImportFile(null);
2215
+ } catch (err) {
2216
+ console.error("Error importando registros:", err);
2217
+ message.error("Ocurri\xF3 un error al guardar los registros importados.");
2218
+ } finally {
2219
+ setIsImporting(false);
2220
+ }
2221
+ };
1778
2222
  const startNew = () => {
2223
+ if (collection.customCreateView) {
2224
+ setIsCustomCreating(true);
2225
+ return;
2226
+ }
1779
2227
  setIsCreatingManual(true);
1780
2228
  setOriginalId(null);
1781
2229
  setDuplicateErrors({});
@@ -1830,18 +2278,35 @@ function CollectionEditor({ collection }) {
1830
2278
  let val = String(finalEditing[sourceField] || finalEditing.id || "");
1831
2279
  val = val.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)+/g, "");
1832
2280
  finalEditing[f.id] = val;
1833
- } else if (f.type === "list") {
2281
+ } else if (f.type === "list" || f.multiple) {
1834
2282
  if (Array.isArray(finalEditing[f.id])) {
1835
2283
  finalEditing[f.id] = finalEditing[f.id].filter(
1836
2284
  (item) => item !== void 0 && item !== null && String(item).trim() !== ""
1837
2285
  );
1838
- } else if (typeof finalEditing[f.id] === "string") {
1839
- finalEditing[f.id] = String(finalEditing[f.id]).split("\n").map((s) => s.trim()).filter(Boolean);
2286
+ } else if (typeof finalEditing[f.id] === "string" && finalEditing[f.id]) {
2287
+ finalEditing[f.id] = [String(finalEditing[f.id]).trim()];
1840
2288
  }
1841
2289
  }
1842
2290
  });
1843
- const isClientOrEmployee = collection.id === "clients" || collection.id === "employees";
1844
- const uniqueFields = collection.fields.filter((f) => f.unique || isClientOrEmployee && f.id === "id");
2291
+ for (const f of collection.fields) {
2292
+ if (f.required) {
2293
+ if (isCreatingEntry && f.hideOnCreate) continue;
2294
+ if (f.dependsOn && finalEditing[f.dependsOn.field] !== void 0) {
2295
+ const targetVal = f.dependsOn.value;
2296
+ const currentVal = finalEditing[f.dependsOn.field];
2297
+ const match = Array.isArray(targetVal) ? targetVal.includes(currentVal) : currentVal === targetVal;
2298
+ if (!match) continue;
2299
+ }
2300
+ const rawVal = finalEditing[f.id];
2301
+ const isEmpty = rawVal === void 0 || rawVal === null || typeof rawVal === "string" && rawVal.trim() === "" || Array.isArray(rawVal) && rawVal.length === 0;
2302
+ if (isEmpty) {
2303
+ message.error(`El campo "${f.label || f.id}" es obligatorio.`);
2304
+ setSaving(false);
2305
+ return;
2306
+ }
2307
+ }
2308
+ }
2309
+ const uniqueFields = collection.fields.filter((f) => f.unique);
1845
2310
  for (const f of uniqueFields) {
1846
2311
  const val = String(finalEditing[f.id] || "").trim().toLowerCase();
1847
2312
  if (!val) {
@@ -1874,6 +2339,18 @@ function CollectionEditor({ collection }) {
1874
2339
  await ctx.adapter.putEntry(collection.id, finalEditing);
1875
2340
  message.success(originalId ? "Guardado correctamente" : "Creado correctamente");
1876
2341
  ctx.notifyCollectionChanged();
2342
+ setEntries((prev) => {
2343
+ const next = [...prev];
2344
+ const matchIdx = next.findIndex(
2345
+ (e) => originalId && String(e.id || "").trim().toLowerCase() === String(originalId).trim().toLowerCase() || String(e.id || "").trim().toLowerCase() === String(finalEditing.id || "").trim().toLowerCase()
2346
+ );
2347
+ if (matchIdx >= 0) {
2348
+ next[matchIdx] = { ...next[matchIdx], ...finalEditing };
2349
+ } else {
2350
+ next.unshift(finalEditing);
2351
+ }
2352
+ return next;
2353
+ });
1877
2354
  setEditing(null);
1878
2355
  setOriginalId(null);
1879
2356
  setIsCreatingManual(false);
@@ -1887,6 +2364,9 @@ function CollectionEditor({ collection }) {
1887
2364
  setDeletingId(id);
1888
2365
  try {
1889
2366
  await ctx.adapter.deleteEntry(collection.id, id);
2367
+ setEntries(
2368
+ (prev) => prev.filter((e) => String(e.id || "").trim().toLowerCase() !== String(id).trim().toLowerCase())
2369
+ );
1890
2370
  ctx.notifyCollectionChanged();
1891
2371
  load();
1892
2372
  } finally {
@@ -1930,23 +2410,80 @@ function CollectionEditor({ collection }) {
1930
2410
  };
1931
2411
  const visibleFields = collection.tableFields?.length ? collection.tableFields.map((tf) => collection.fields.find((f) => f.id === tf)).filter(Boolean) : collection.fields.filter((f) => !["richtext", "list", "password"].includes(f.type) && f.id !== "order" && !f.hidden).slice(0, 6);
1932
2412
  const isCreatingEntry = isCreatingManual || (editing ? !entries.some((entry) => entry.id && entry.id === editing.id || entry._id && entry._id === (editing._id || editing.id)) : false);
2413
+ if (isCustomCreating && collection.customCreateView) {
2414
+ return /* @__PURE__ */ jsx("div", { className: "w-full", children: collection.customCreateView({
2415
+ onBack: () => setIsCustomCreating(false),
2416
+ reload: () => {
2417
+ load();
2418
+ }
2419
+ }) });
2420
+ }
2421
+ if (customActiveView) {
2422
+ return /* @__PURE__ */ jsx("div", { className: "w-full", children: customActiveView({
2423
+ onBack: () => setCustomActiveView(null),
2424
+ reload: () => {
2425
+ load();
2426
+ }
2427
+ }) });
2428
+ }
2429
+ if (customViewingRecord && (collection.customDetailView || collection.renderCustomDetail || collection.customEditView)) {
2430
+ const renderFn = isCustomEditing && collection.customEditView ? collection.customEditView : collection.customDetailView || collection.renderCustomDetail;
2431
+ if (renderFn) {
2432
+ return /* @__PURE__ */ jsx("div", { className: "w-full", children: renderFn({
2433
+ record: customViewingRecord,
2434
+ isEditing: isCustomEditing,
2435
+ onBack: () => {
2436
+ setCustomViewingRecord(null);
2437
+ setIsCustomEditing(false);
2438
+ },
2439
+ reload: () => {
2440
+ load();
2441
+ }
2442
+ }) });
2443
+ }
2444
+ }
1933
2445
  return /* @__PURE__ */ jsxs("div", { className: "mx-auto max-w-5xl", children: [
1934
- /* @__PURE__ */ jsxs("div", { className: "mb-8 flex items-center justify-between", children: [
2446
+ /* @__PURE__ */ jsxs("div", { className: "mb-8 flex flex-col sm:flex-row sm:items-center justify-between gap-4", children: [
1935
2447
  /* @__PURE__ */ jsxs("div", { children: [
1936
2448
  /* @__PURE__ */ jsx("h2", { className: "text-2xl font-bold text-slate-900 tracking-tight", children: collection.name }),
1937
2449
  collection.description && /* @__PURE__ */ jsx("p", { className: "text-sm text-slate-500 mt-1", children: collection.description })
1938
2450
  ] }),
1939
- /* @__PURE__ */ jsx(
1940
- Button,
1941
- {
1942
- type: "primary",
1943
- size: "large",
1944
- icon: /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4" }),
1945
- onClick: startNew,
1946
- className: "rounded-xl font-bold shadow-sm",
1947
- children: t.newEntry
1948
- }
1949
- )
2451
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
2452
+ !collection.disableExport && /* @__PURE__ */ jsx(
2453
+ Button,
2454
+ {
2455
+ size: "large",
2456
+ icon: /* @__PURE__ */ jsx(FileDown, { className: "h-4 w-4 text-emerald-600" }),
2457
+ onClick: handleOpenExportModal,
2458
+ disabled: loadingEntries || entries.length === 0,
2459
+ className: "rounded-xl font-medium border-slate-200 hover:border-emerald-500 hover:text-emerald-600 shadow-sm",
2460
+ title: "Descargar registros en formato Excel (soporta filtro por fechas)",
2461
+ children: t.exportExcel
2462
+ }
2463
+ ),
2464
+ !collection.disableImport && /* @__PURE__ */ jsx(
2465
+ Button,
2466
+ {
2467
+ size: "large",
2468
+ icon: /* @__PURE__ */ jsx(FileUp, { className: "h-4 w-4 text-sky-600" }),
2469
+ onClick: () => setIsImportModalOpen(true),
2470
+ className: "rounded-xl font-medium border-slate-200 hover:border-sky-500 hover:text-sky-600 shadow-sm",
2471
+ title: "Cargar registros desde un archivo Excel o CSV",
2472
+ children: t.importExcel
2473
+ }
2474
+ ),
2475
+ /* @__PURE__ */ jsx(
2476
+ Button,
2477
+ {
2478
+ type: "primary",
2479
+ size: "large",
2480
+ icon: /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4" }),
2481
+ onClick: startNew,
2482
+ className: "rounded-xl font-bold shadow-sm",
2483
+ children: t.newEntry
2484
+ }
2485
+ )
2486
+ ] })
1950
2487
  ] }),
1951
2488
  !editing && (collection.searchBy?.length || collection.filterBy?.length) && /* @__PURE__ */ jsxs("div", { className: "mb-6 flex flex-wrap gap-4 items-center p-4 bg-white rounded-2xl border border-slate-200 shadow-sm animate-in fade-in slide-in-from-top-2", children: [
1952
2489
  collection.searchBy?.length ? /* @__PURE__ */ jsx("div", { className: "relative flex-1 min-w-[220px]", children: /* @__PURE__ */ jsx(
@@ -1954,7 +2491,10 @@ function CollectionEditor({ collection }) {
1954
2491
  {
1955
2492
  size: "large",
1956
2493
  prefix: /* @__PURE__ */ jsx(Search, { className: "h-4 w-4 text-slate-400" }),
1957
- placeholder: `Buscar por ${collection.searchBy.map((s) => s === "numero" ? "n\xFAmero" : s === "clienteNombre" ? "cliente" : s === "clienteId" ? "identificaci\xF3n" : s === "fecha" ? "fecha" : s).join(", ")}...`,
2494
+ placeholder: `Buscar por ${collection.searchBy.map((s) => {
2495
+ const f = collection.fields.find((field) => field.id === s);
2496
+ return f?.label ? f.label.toLowerCase() : s;
2497
+ }).join(", ")}...`,
1958
2498
  value: search,
1959
2499
  allowClear: true,
1960
2500
  onChange: (e) => {
@@ -1968,7 +2508,7 @@ function CollectionEditor({ collection }) {
1968
2508
  const fieldDef = collection.fields.find((cf) => cf.id === f);
1969
2509
  if (!fieldDef) return null;
1970
2510
  if (fieldDef.type === "date") {
1971
- const dateVal = filters[f] ? dayjs(filters[f], ["YYYY/MM/DD", "YYYY-MM-DD", "YYYY-M-D"]).isValid() ? dayjs(filters[f], ["YYYY/MM/DD", "YYYY-MM-DD", "YYYY-M-D"]) : null : null;
2511
+ const dateVal = filters[f] ? dayjs2(filters[f], ["YYYY/MM/DD", "YYYY-MM-DD", "YYYY-M-D"]).isValid() ? dayjs2(filters[f], ["YYYY/MM/DD", "YYYY-MM-DD", "YYYY-M-D"]) : null : null;
1972
2512
  return /* @__PURE__ */ jsx("div", { className: "min-w-[180px]", children: /* @__PURE__ */ jsx(
1973
2513
  DatePicker,
1974
2514
  {
@@ -2084,7 +2624,7 @@ function CollectionEditor({ collection }) {
2084
2624
  }
2085
2625
  return true;
2086
2626
  }).map((f) => {
2087
- const isFullWidth = f.colSpan === 2 || f.colSpan === 12 || f.type === "signature" || f.type === "date" || f.type === "datetime" || f.type === "richtext" || f.type === "textarea" || f.type === "list" || f.type === "branch-settings" || f.type === "time-range";
2627
+ const isFullWidth = f.colSpan === 2 || f.colSpan === 12 || f.multiple || f.type === "signature" || f.type === "date" || f.type === "datetime" || f.type === "richtext" || f.type === "textarea" || f.type === "list" || f.type === "branch-settings" || f.type === "time-range";
2088
2628
  const colSpanClass = isFullWidth ? "lg:col-span-2 col-span-1" : "col-span-1";
2089
2629
  if (isViewingDetail) {
2090
2630
  return /* @__PURE__ */ jsxs("div", { className: `block ${colSpanClass}`, children: [
@@ -2094,7 +2634,9 @@ function CollectionEditor({ collection }) {
2094
2634
  record: editing,
2095
2635
  onChange: () => {
2096
2636
  },
2097
- isCreatingEntry: false
2637
+ isCreatingEntry: false,
2638
+ isViewingDetail: true,
2639
+ readOnly: true
2098
2640
  }) : f.type === "signature" ? editing[f.id] ? /* @__PURE__ */ jsx("div", { className: "rounded-xl border border-slate-200 bg-white p-3 flex items-center justify-center shadow-sm", children: /* @__PURE__ */ jsx(
2099
2641
  "img",
2100
2642
  {
@@ -2102,14 +2644,14 @@ function CollectionEditor({ collection }) {
2102
2644
  alt: f.label,
2103
2645
  className: "h-28 w-auto max-w-full object-contain"
2104
2646
  }
2105
- ) }) : /* @__PURE__ */ jsx("p", { className: "text-xs text-slate-400 italic py-1", children: "Sin firma registrada" }) : f.type === "list" ? Array.isArray(editing[f.id]) && editing[f.id].length > 0 ? /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5 pt-0.5", children: editing[f.id].map((item, idx) => /* @__PURE__ */ jsx(
2647
+ ) }) : /* @__PURE__ */ jsx("p", { className: "text-xs text-slate-400 italic py-1", children: "Sin firma registrada" }) : f.type === "list" || f.multiple ? Array.isArray(editing[f.id]) && editing[f.id].length > 0 ? /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5 pt-0.5", children: editing[f.id].map((item, idx) => /* @__PURE__ */ jsx(
2106
2648
  "span",
2107
2649
  {
2108
- className: "rounded-full bg-slate-100 text-slate-700 px-3 py-1 text-xs font-medium border border-slate-200",
2650
+ className: "rounded-xl bg-slate-100 text-slate-700 px-3 py-1 text-xs font-medium border border-slate-200",
2109
2651
  children: String(item)
2110
2652
  },
2111
2653
  idx
2112
- )) }) : /* @__PURE__ */ jsx("p", { className: "text-xs text-slate-400 italic py-1", children: "Ninguno" }) : f.type === "link" ? Boolean(editing[f.id]) ? /* @__PURE__ */ jsxs(
2654
+ )) }) : typeof editing[f.id] === "string" && editing[f.id] ? /* @__PURE__ */ jsx("div", { className: "rounded-xl bg-slate-50 border border-slate-200 px-3.5 py-2 text-sm text-slate-800 font-medium", children: String(editing[f.id]) }) : /* @__PURE__ */ jsx("p", { className: "text-xs text-slate-400 italic py-1", children: "Ninguno" }) : f.type === "link" ? Boolean(editing[f.id]) ? /* @__PURE__ */ jsxs(
2113
2655
  "a",
2114
2656
  {
2115
2657
  href: String(editing[f.id]),
@@ -2121,19 +2663,24 @@ function CollectionEditor({ collection }) {
2121
2663
  String(editing[f.id]).includes("maps") ? "Ver en Google Maps" : String(editing[f.id])
2122
2664
  ]
2123
2665
  }
2124
- ) : /* @__PURE__ */ jsx("span", { className: "text-xs text-slate-400 py-1 block", children: "\u2014" }) : f.type === "textarea" ? /* @__PURE__ */ jsx("div", { className: "rounded-xl bg-slate-50 border border-slate-200 px-3.5 py-2.5 text-sm text-slate-800 whitespace-pre-line leading-relaxed", children: String(editing[f.id] || "\u2014") }) : f.type === "time" || f.id.toLowerCase().includes("hora") || f.id === "inicioServicio" || f.id === "finServicio" ? /* @__PURE__ */ jsx("div", { className: "rounded-xl bg-slate-50 border border-slate-200 px-3.5 py-2 text-sm text-slate-800 font-medium", children: formatTo12Hour(editing[f.id]) || String(editing[f.id] ?? "\u2014") }) : /* @__PURE__ */ jsx("div", { className: "rounded-xl bg-slate-50 border border-slate-200 px-3.5 py-2 text-sm text-slate-800 font-medium", children: String(editing[f.id] ?? "\u2014") })
2666
+ ) : /* @__PURE__ */ jsx("span", { className: "text-xs text-slate-400 py-1 block", children: "\u2014" }) : f.type === "textarea" ? /* @__PURE__ */ jsx("div", { className: "rounded-xl bg-slate-50 border border-slate-200 px-3.5 py-2.5 text-sm text-slate-800 whitespace-pre-line leading-relaxed", children: String(editing[f.id] || "\u2014") }) : f.type === "time" || f.id.toLowerCase().includes("hora") || f.id === "inicioServicio" || f.id === "finServicio" ? /* @__PURE__ */ jsx("div", { className: "rounded-xl bg-slate-50 border border-slate-200 px-3.5 py-2 text-sm text-slate-800 font-medium", children: formatTo12Hour(editing[f.id]) || String(editing[f.id] ?? "\u2014") }) : f.renderCell ? /* @__PURE__ */ jsx("div", { className: "rounded-xl bg-slate-50 border border-slate-200 px-3.5 py-2 text-sm text-slate-800 font-medium", children: f.renderCell(editing[f.id], editing) }) : /* @__PURE__ */ jsx("div", { className: "rounded-xl bg-slate-50 border border-slate-200 px-3.5 py-2 text-sm text-slate-800 font-medium", children: String(editing[f.id] ?? "\u2014") })
2125
2667
  ] }, f.id);
2126
2668
  }
2127
2669
  return /* @__PURE__ */ jsxs("div", { className: `block ${colSpanClass}`, children: [
2128
2670
  /* @__PURE__ */ jsxs("span", { className: "text-xs font-bold text-slate-500 uppercase tracking-wide flex items-center justify-between mb-1.5", children: [
2129
- f.label,
2671
+ /* @__PURE__ */ jsxs("span", { children: [
2672
+ f.label,
2673
+ (f.required || f.unique) && /* @__PURE__ */ jsx("span", { className: "text-rose-500 ml-1 font-bold", title: "Campo obligatorio", children: "*" })
2674
+ ] }),
2130
2675
  /* @__PURE__ */ jsx("span", { className: "text-[10px] font-mono text-slate-300 bg-slate-50 px-1.5 py-0.5 rounded", children: f.type })
2131
2676
  ] }),
2132
2677
  f.customRender ? f.customRender({
2133
2678
  value: editing[f.id],
2134
2679
  record: editing,
2135
2680
  onChange: (val) => setEditing({ ...editing, [f.id]: val }),
2136
- isCreatingEntry
2681
+ isCreatingEntry,
2682
+ isViewingDetail: false,
2683
+ readOnly: false
2137
2684
  }) : f.type === "branch-settings" ? /* @__PURE__ */ jsx(
2138
2685
  BranchSettingsEditor,
2139
2686
  {
@@ -2167,7 +2714,7 @@ function CollectionEditor({ collection }) {
2167
2714
  DatePicker,
2168
2715
  {
2169
2716
  size: "large",
2170
- value: editing[f.id] ? dayjs(String(editing[f.id])).isValid() ? dayjs(String(editing[f.id])) : null : null,
2717
+ value: editing[f.id] ? dayjs2(String(editing[f.id])).isValid() ? dayjs2(String(editing[f.id])) : null : null,
2171
2718
  onChange: (date, dateString) => setEditing({ ...editing, [f.id]: (Array.isArray(dateString) ? dateString[0] : dateString) || (date ? date.format("YYYY/MM/DD") : "") }),
2172
2719
  format: "YYYY/MM/DD",
2173
2720
  placeholder: `Seleccionar ${f.label.toLowerCase()}...`,
@@ -2267,21 +2814,8 @@ function CollectionEditor({ collection }) {
2267
2814
  value: editing[f.id],
2268
2815
  onChange: (val) => setEditing({ ...editing, [f.id]: val }),
2269
2816
  onSelectRecord: (rec) => {
2270
- if (f.id === "clienteId" && rec) {
2271
- setEditing((prev) => prev ? {
2272
- ...prev,
2273
- clienteId: rec.id || prev.clienteId,
2274
- clienteNombre: rec.nombre || rec.name || prev.clienteNombre,
2275
- ciudad: rec.ciudad || prev.ciudad,
2276
- direccion: rec.direccion || prev.direccion,
2277
- telefono: rec.telefono || prev.telefono
2278
- } : prev);
2279
- } else if (f.id === "empleadoId" && rec) {
2280
- setEditing((prev) => prev ? {
2281
- ...prev,
2282
- empleadoId: rec.id || prev.empleadoId,
2283
- empleadoNombre: rec.apellido ? `${rec.nombre || rec.name || ""} ${rec.apellido}`.trim() : rec.nombre || rec.name || prev.empleadoNombre
2284
- } : prev);
2817
+ if (f.onSelectRecord) {
2818
+ setEditing((prev) => prev ? { ...prev, ...f.onSelectRecord(rec, prev) } : prev);
2285
2819
  }
2286
2820
  }
2287
2821
  }
@@ -2537,63 +3071,61 @@ function CollectionEditor({ collection }) {
2537
3071
  ]
2538
3072
  }
2539
3073
  )
2540
- ] }) : f.type === "list" ? /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
2541
- (Array.isArray(editing[f.id]) ? editing[f.id] : typeof editing[f.id] === "string" ? String(editing[f.id]).split("\n").filter(Boolean) : []).map((item, idx) => {
2542
- const isFeatures = f.id === "features" || f.label.toLowerCase().includes("caracter\xEDstica") || f.label.toLowerCase().includes("beneficio");
2543
- const placeholder = isFeatures ? `Caracter\xEDstica o beneficio ${idx + 1}...` : `Entregable o punto clave ${idx + 1}...`;
2544
- return /* @__PURE__ */ jsxs("div", { className: "flex gap-2 items-center", children: [
2545
- /* @__PURE__ */ jsxs("span", { className: "text-xs font-mono font-bold text-slate-400 w-6 text-right shrink-0", children: [
2546
- idx + 1,
2547
- "."
3074
+ ] }) : f.type === "list" || f.multiple ? /* @__PURE__ */ jsx("div", { className: "space-y-3", children: (() => {
3075
+ const currentArr = Array.isArray(editing[f.id]) ? editing[f.id] : typeof editing[f.id] === "string" && editing[f.id] ? [editing[f.id]] : [""];
3076
+ const displayArr = currentArr.length > 0 ? currentArr : [""];
3077
+ const singularLabel = f.label.endsWith("es") ? f.label.slice(0, -2) : f.label.endsWith("s") ? f.label.slice(0, -1) : f.label;
3078
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-2.5", children: [
3079
+ displayArr.map((item, idx) => /* @__PURE__ */ jsxs("div", { className: "flex gap-2 items-center", children: [
3080
+ /* @__PURE__ */ jsxs("span", { className: "text-xs font-mono font-bold text-slate-400 w-7 text-right shrink-0", children: [
3081
+ "#",
3082
+ idx + 1
2548
3083
  ] }),
2549
3084
  /* @__PURE__ */ jsx(
2550
3085
  "input",
2551
3086
  {
2552
3087
  type: "text",
2553
3088
  value: String(item ?? ""),
2554
- placeholder,
3089
+ placeholder: `${singularLabel} #${idx + 1}...`,
2555
3090
  onChange: (e) => {
2556
- let arr = Array.isArray(editing[f.id]) ? [...editing[f.id]] : typeof editing[f.id] === "string" ? String(editing[f.id]).split("\n").filter(Boolean) : [];
3091
+ const arr = [...displayArr];
2557
3092
  arr[idx] = e.target.value;
2558
3093
  setEditing({ ...editing, [f.id]: arr });
2559
3094
  },
2560
3095
  className: "flex-1 rounded-xl border border-slate-200 px-4 py-2.5 text-sm text-slate-800 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-4 focus:ring-indigo-500/10 transition-all bg-white"
2561
3096
  }
2562
3097
  ),
2563
- /* @__PURE__ */ jsx(
3098
+ displayArr.length > 1 && /* @__PURE__ */ jsx(
2564
3099
  "button",
2565
3100
  {
2566
3101
  type: "button",
2567
3102
  onClick: () => {
2568
- let arr = Array.isArray(editing[f.id]) ? [...editing[f.id]] : typeof editing[f.id] === "string" ? String(editing[f.id]).split("\n").filter(Boolean) : [];
2569
- arr.splice(idx, 1);
2570
- setEditing({ ...editing, [f.id]: arr });
3103
+ const arr = displayArr.filter((_, i) => i !== idx);
3104
+ setEditing({ ...editing, [f.id]: arr.length > 0 ? arr : [""] });
2571
3105
  },
2572
- className: "p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors cursor-pointer",
3106
+ className: "p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors cursor-pointer shrink-0",
2573
3107
  title: "Eliminar elemento",
2574
3108
  children: /* @__PURE__ */ jsx(Trash2, { className: "w-4 h-4" })
2575
3109
  }
2576
3110
  )
2577
- ] }, idx);
2578
- }),
2579
- /* @__PURE__ */ jsxs(
2580
- "button",
2581
- {
2582
- type: "button",
2583
- onClick: () => {
2584
- let arr = Array.isArray(editing[f.id]) ? [...editing[f.id]] : typeof editing[f.id] === "string" ? String(editing[f.id]).split("\n").filter(Boolean) : [];
2585
- arr.push("");
2586
- setEditing({ ...editing, [f.id]: arr });
2587
- },
2588
- className: "inline-flex items-center gap-1.5 px-3.5 py-2 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 text-xs font-bold rounded-xl border border-indigo-100 transition-colors cursor-pointer",
2589
- children: [
2590
- /* @__PURE__ */ jsx(Plus, { className: "w-3.5 h-3.5" }),
2591
- " ",
2592
- f.id === "features" || f.label.toLowerCase().includes("caracter\xEDstica") ? "Agregar caracter\xEDstica uno a uno" : "Agregar entregable / punto uno a uno"
2593
- ]
2594
- }
2595
- )
2596
- ] }) : f.type === "link" ? /* @__PURE__ */ jsxs("div", { className: "flex gap-2 items-center", children: [
3111
+ ] }, idx)),
3112
+ /* @__PURE__ */ jsxs(
3113
+ "button",
3114
+ {
3115
+ type: "button",
3116
+ onClick: () => {
3117
+ setEditing({ ...editing, [f.id]: [...displayArr, ""] });
3118
+ },
3119
+ className: "inline-flex items-center gap-1.5 px-3.5 py-2 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 text-xs font-bold rounded-xl border border-indigo-100 transition-colors cursor-pointer",
3120
+ children: [
3121
+ /* @__PURE__ */ jsx(Plus, { className: "w-3.5 h-3.5" }),
3122
+ " Agregar ",
3123
+ singularLabel.toLowerCase()
3124
+ ]
3125
+ }
3126
+ )
3127
+ ] });
3128
+ })() }) : f.type === "link" ? /* @__PURE__ */ jsxs("div", { className: "flex gap-2 items-center", children: [
2597
3129
  /* @__PURE__ */ jsx(
2598
3130
  Input,
2599
3131
  {
@@ -2640,7 +3172,7 @@ function CollectionEditor({ collection }) {
2640
3172
  }
2641
3173
  },
2642
3174
  onBlur: (e) => {
2643
- const isUniqueField = f.unique || (collection.id === "clients" || collection.id === "employees") && f.id === "id";
3175
+ const isUniqueField = Boolean(f.unique);
2644
3176
  if (isUniqueField) {
2645
3177
  const val = (e.target.value || "").trim().toLowerCase();
2646
3178
  if (val) {
@@ -2722,6 +3254,304 @@ function CollectionEditor({ collection }) {
2722
3254
  ] }) })
2723
3255
  }
2724
3256
  ),
3257
+ /* @__PURE__ */ jsx(
3258
+ Modal,
3259
+ {
3260
+ open: isExportModalOpen,
3261
+ title: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-slate-900 font-bold text-lg", children: [
3262
+ /* @__PURE__ */ jsx(FileDown, { className: "h-5 w-5 text-emerald-600" }),
3263
+ /* @__PURE__ */ jsxs("span", { children: [
3264
+ t.exportModalTitle,
3265
+ " - ",
3266
+ collection.name
3267
+ ] })
3268
+ ] }),
3269
+ onCancel: () => setIsExportModalOpen(false),
3270
+ footer: null,
3271
+ centered: true,
3272
+ width: "min(560px, calc(100vw - 32px))",
3273
+ mask: { blur: true },
3274
+ children: /* @__PURE__ */ jsxs("div", { className: "py-2 space-y-4", children: [
3275
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-slate-500", children: "Descarga los registros en formato Excel estructurado (.xlsx)." }),
3276
+ /* @__PURE__ */ jsx(
3277
+ Segmented,
3278
+ {
3279
+ size: "large",
3280
+ block: true,
3281
+ value: exportMode,
3282
+ onChange: (val) => setExportMode(val),
3283
+ options: [
3284
+ { label: `${t.exportAllRecords} (${entries.length})`, value: "all" },
3285
+ { label: t.exportFilterByDate, value: "byDate" }
3286
+ ]
3287
+ }
3288
+ ),
3289
+ exportMode === "byDate" && /* @__PURE__ */ jsxs("div", { className: "p-4 bg-slate-50 border border-slate-200 rounded-xl space-y-3 animate-in fade-in", children: [
3290
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
3291
+ /* @__PURE__ */ jsxs("label", { className: "text-xs font-semibold text-slate-600", children: [
3292
+ t.exportDateRangeLabel,
3293
+ ":"
3294
+ ] }),
3295
+ /* @__PURE__ */ jsx(
3296
+ DatePicker.RangePicker,
3297
+ {
3298
+ size: "large",
3299
+ className: "w-full rounded-xl",
3300
+ value: exportDateRange,
3301
+ onChange: (dates) => setExportDateRange(dates),
3302
+ presets: [
3303
+ { label: "Hoy", value: [dayjs2().startOf("day"), dayjs2().endOf("day")] },
3304
+ { label: "Esta semana", value: [dayjs2().startOf("week"), dayjs2().endOf("week")] },
3305
+ { label: "Este mes", value: [dayjs2().startOf("month"), dayjs2().endOf("month")] },
3306
+ { label: "\xDAltimos 30 d\xEDas", value: [dayjs2().subtract(30, "day"), dayjs2()] },
3307
+ { label: "Este a\xF1o", value: [dayjs2().startOf("year"), dayjs2().endOf("year")] }
3308
+ ]
3309
+ }
3310
+ )
3311
+ ] }),
3312
+ /* @__PURE__ */ jsxs("div", { className: "pt-1 flex items-center justify-between text-xs", children: [
3313
+ /* @__PURE__ */ jsx("span", { className: "text-slate-500 font-medium", children: "Registros coincidentes:" }),
3314
+ /* @__PURE__ */ jsxs(
3315
+ "span",
3316
+ {
3317
+ className: `font-bold ${exportTargetEntries.length > 0 ? "text-emerald-600" : "text-amber-600"}`,
3318
+ children: [
3319
+ exportTargetEntries.length,
3320
+ " de ",
3321
+ entries.length,
3322
+ " registros"
3323
+ ]
3324
+ }
3325
+ )
3326
+ ] })
3327
+ ] }),
3328
+ /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2 pt-2", children: [
3329
+ /* @__PURE__ */ jsx(Button, { size: "large", onClick: () => setIsExportModalOpen(false), children: t.cancel }),
3330
+ /* @__PURE__ */ jsxs(
3331
+ Button,
3332
+ {
3333
+ type: "primary",
3334
+ size: "large",
3335
+ icon: /* @__PURE__ */ jsx(FileDown, { className: "h-4 w-4" }),
3336
+ onClick: handleConfirmExport,
3337
+ disabled: exportTargetEntries.length === 0,
3338
+ className: "rounded-xl font-bold bg-emerald-600 hover:bg-emerald-500",
3339
+ children: [
3340
+ t.exportDownloadBtn,
3341
+ " (",
3342
+ exportTargetEntries.length,
3343
+ ")"
3344
+ ]
3345
+ }
3346
+ )
3347
+ ] })
3348
+ ] })
3349
+ }
3350
+ ),
3351
+ /* @__PURE__ */ jsx(
3352
+ Modal,
3353
+ {
3354
+ open: isImportModalOpen,
3355
+ title: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-slate-900 font-bold text-lg", children: [
3356
+ /* @__PURE__ */ jsx(FileSpreadsheet, { className: "h-5 w-5 text-emerald-600" }),
3357
+ /* @__PURE__ */ jsxs("span", { children: [
3358
+ t.importModalTitle,
3359
+ " - ",
3360
+ collection.name
3361
+ ] })
3362
+ ] }),
3363
+ onCancel: () => {
3364
+ if (!isImporting) {
3365
+ setIsImportModalOpen(false);
3366
+ setImportResult(null);
3367
+ setImportFile(null);
3368
+ }
3369
+ },
3370
+ footer: null,
3371
+ centered: true,
3372
+ width: "min(800px, calc(100vw - 32px))",
3373
+ mask: { blur: true },
3374
+ children: /* @__PURE__ */ jsxs("div", { className: "py-2 space-y-4", children: [
3375
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-slate-500", children: t.importModalDesc }),
3376
+ !importResult ? /* @__PURE__ */ jsxs(
3377
+ "div",
3378
+ {
3379
+ onDragOver: (e) => {
3380
+ e.preventDefault();
3381
+ e.stopPropagation();
3382
+ },
3383
+ onDrop: (e) => {
3384
+ e.preventDefault();
3385
+ e.stopPropagation();
3386
+ const file = e.dataTransfer.files?.[0];
3387
+ if (file) handleProcessImportFile(file);
3388
+ },
3389
+ onClick: () => fileInputRef.current?.click(),
3390
+ className: "border-2 border-dashed border-slate-300 hover:border-emerald-500 rounded-2xl p-8 text-center cursor-pointer bg-slate-50 hover:bg-emerald-50/30 transition-all flex flex-col items-center justify-center gap-3",
3391
+ children: [
3392
+ /* @__PURE__ */ jsx(
3393
+ "input",
3394
+ {
3395
+ ref: fileInputRef,
3396
+ type: "file",
3397
+ accept: ".xlsx,.xls,.csv",
3398
+ className: "hidden",
3399
+ onChange: (e) => {
3400
+ const file = e.target.files?.[0];
3401
+ if (file) handleProcessImportFile(file);
3402
+ }
3403
+ }
3404
+ ),
3405
+ /* @__PURE__ */ jsx("div", { className: "size-14 rounded-full bg-emerald-100 flex items-center justify-center text-emerald-600 shadow-sm", children: /* @__PURE__ */ jsx(FileSpreadsheet, { className: "size-7" }) }),
3406
+ /* @__PURE__ */ jsxs("div", { children: [
3407
+ /* @__PURE__ */ jsx("p", { className: "font-semibold text-sm text-slate-700", children: t.importDropzone }),
3408
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-slate-400 mt-1", children: t.importDropzoneSub })
3409
+ ] }),
3410
+ /* @__PURE__ */ jsx(Button, { size: "middle", loading: isParsingImport, className: "mt-2 rounded-lg font-medium", children: isParsingImport ? "Leyendo archivo..." : "Seleccionar archivo" })
3411
+ ]
3412
+ }
3413
+ ) : /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
3414
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between p-3.5 bg-emerald-50/60 border border-emerald-200 rounded-xl", children: [
3415
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
3416
+ /* @__PURE__ */ jsx("div", { className: "size-9 rounded-lg bg-emerald-100 text-emerald-700 flex items-center justify-center font-bold", children: /* @__PURE__ */ jsx(FileSpreadsheet, { className: "size-5" }) }),
3417
+ /* @__PURE__ */ jsxs("div", { children: [
3418
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-bold text-slate-900", children: importFile?.name }),
3419
+ /* @__PURE__ */ jsxs("p", { className: "text-xs text-emerald-700 font-medium", children: [
3420
+ importResult.totalRows,
3421
+ " registros encontrados en el archivo"
3422
+ ] })
3423
+ ] })
3424
+ ] }),
3425
+ /* @__PURE__ */ jsx(
3426
+ Button,
3427
+ {
3428
+ size: "small",
3429
+ onClick: () => {
3430
+ setImportResult(null);
3431
+ setImportFile(null);
3432
+ },
3433
+ disabled: isImporting,
3434
+ children: "Cambiar archivo"
3435
+ }
3436
+ )
3437
+ ] }),
3438
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2 p-3 bg-slate-50 border border-slate-200 rounded-xl", children: [
3439
+ /* @__PURE__ */ jsx("span", { className: "text-xs font-semibold text-slate-700", children: "Estado de los registros:" }),
3440
+ /* @__PURE__ */ jsxs(Tag, { color: "green", className: "text-xs font-medium", children: [
3441
+ "\u2713 ",
3442
+ importResult.newRecordsCount,
3443
+ " ",
3444
+ t.importNewDetected
3445
+ ] }),
3446
+ importResult.existingRecordsCount > 0 && /* @__PURE__ */ jsxs(Tag, { color: "gold", className: "text-xs font-medium", children: [
3447
+ "\u2139\uFE0F ",
3448
+ importResult.existingRecordsCount,
3449
+ " ",
3450
+ t.importExistingDetected
3451
+ ] })
3452
+ ] }),
3453
+ importResult.existingRecordsCount > 0 && /* @__PURE__ */ jsxs("div", { className: "p-3.5 bg-slate-50/90 rounded-xl border border-slate-200 space-y-2", children: [
3454
+ /* @__PURE__ */ jsx("span", { className: "text-xs font-bold text-slate-700 block", children: t.importOverwritesWarning }),
3455
+ /* @__PURE__ */ jsxs(
3456
+ Radio.Group,
3457
+ {
3458
+ value: importExistingAction,
3459
+ onChange: (e) => setImportExistingAction(e.target.value),
3460
+ disabled: isImporting,
3461
+ className: "flex flex-col gap-2.5",
3462
+ children: [
3463
+ /* @__PURE__ */ jsxs(Radio, { value: "omit", className: "text-xs text-slate-700", children: [
3464
+ /* @__PURE__ */ jsx("span", { className: "font-semibold text-emerald-700 block", children: t.importExistingOmit }),
3465
+ /* @__PURE__ */ jsx("span", { className: "text-[11px] text-slate-500 block", children: "Si ya existe por ID o campo \xFAnico, no se vuelve a crear ni duplicar en la base de datos." })
3466
+ ] }),
3467
+ /* @__PURE__ */ jsxs(Radio, { value: "update", className: "text-xs text-slate-700", children: [
3468
+ /* @__PURE__ */ jsx("span", { className: "font-semibold text-sky-700 block", children: t.importExistingUpdate }),
3469
+ /* @__PURE__ */ jsx("span", { className: "text-[11px] text-slate-500 block", children: "Actualiza los campos de los registros ya existentes con los datos del archivo." })
3470
+ ] })
3471
+ ]
3472
+ }
3473
+ )
3474
+ ] }),
3475
+ /* @__PURE__ */ jsxs("div", { children: [
3476
+ /* @__PURE__ */ jsxs("span", { className: "text-xs font-bold text-slate-600 uppercase tracking-wider block mb-1.5", children: [
3477
+ "Campos reconocidos (",
3478
+ importResult.matchedFields.length,
3479
+ "):"
3480
+ ] }),
3481
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-1.5", children: [
3482
+ importResult.matchedFields.map((m, idx) => /* @__PURE__ */ jsxs(Tag, { color: "green", className: "text-xs py-0.5", children: [
3483
+ "\u2713 ",
3484
+ m.label
3485
+ ] }, idx)),
3486
+ importResult.unmatchedHeaders.map((u, idx) => /* @__PURE__ */ jsxs(Tag, { color: "orange", className: "text-xs py-0.5", children: [
3487
+ "\u26A0\uFE0F ",
3488
+ u,
3489
+ " (omitido)"
3490
+ ] }, idx))
3491
+ ] })
3492
+ ] }),
3493
+ /* @__PURE__ */ jsxs("div", { children: [
3494
+ /* @__PURE__ */ jsxs("span", { className: "text-xs font-bold text-slate-600 uppercase tracking-wider block mb-1.5", children: [
3495
+ t.importPreviewTitle,
3496
+ " (",
3497
+ Math.min(5, importResult.samplePreview.length),
3498
+ " de ",
3499
+ importResult.totalRows,
3500
+ "):"
3501
+ ] }),
3502
+ /* @__PURE__ */ jsx("div", { className: "overflow-x-auto border border-slate-200 rounded-xl max-h-48 text-xs", children: /* @__PURE__ */ jsxs("table", { className: "w-full text-left", children: [
3503
+ /* @__PURE__ */ jsx("thead", { className: "bg-slate-100/80 text-slate-700 font-semibold border-b border-slate-200", children: /* @__PURE__ */ jsx("tr", { children: importResult.matchedFields.slice(0, 6).map((m, idx) => /* @__PURE__ */ jsx("th", { className: "p-2 whitespace-nowrap", children: m.label }, idx)) }) }),
3504
+ /* @__PURE__ */ jsx("tbody", { className: "divide-y divide-slate-100", children: importResult.samplePreview.map((row, rIdx) => /* @__PURE__ */ jsx("tr", { className: "hover:bg-slate-50/60", children: importResult.matchedFields.slice(0, 6).map((m, cIdx) => /* @__PURE__ */ jsx("td", { className: "p-2 whitespace-nowrap max-w-[160px] truncate text-slate-600", children: String(row[m.fieldId] ?? "") }, cIdx)) }, rIdx)) })
3505
+ ] }) })
3506
+ ] }),
3507
+ isImporting && /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
3508
+ /* @__PURE__ */ jsxs("div", { className: "flex justify-between text-xs text-slate-600 font-medium", children: [
3509
+ /* @__PURE__ */ jsx("span", { children: t.importingProgress }),
3510
+ /* @__PURE__ */ jsxs("span", { children: [
3511
+ importProgress.current,
3512
+ " / ",
3513
+ importProgress.total
3514
+ ] })
3515
+ ] }),
3516
+ /* @__PURE__ */ jsx(
3517
+ Progress,
3518
+ {
3519
+ percent: Math.round(importProgress.current / (importProgress.total || 1) * 100),
3520
+ status: "active"
3521
+ }
3522
+ )
3523
+ ] }),
3524
+ /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2 pt-2", children: [
3525
+ /* @__PURE__ */ jsx(
3526
+ Button,
3527
+ {
3528
+ size: "large",
3529
+ onClick: () => setIsImportModalOpen(false),
3530
+ disabled: isImporting,
3531
+ children: t.cancel
3532
+ }
3533
+ ),
3534
+ /* @__PURE__ */ jsxs(
3535
+ Button,
3536
+ {
3537
+ type: "primary",
3538
+ size: "large",
3539
+ loading: isImporting,
3540
+ onClick: handleExecuteImport,
3541
+ className: "rounded-xl font-bold bg-emerald-600 hover:bg-emerald-500",
3542
+ children: [
3543
+ t.importConfirmBtn,
3544
+ " (",
3545
+ importExistingAction === "omit" && importResult.existingRecordsCount > 0 ? importResult.newRecordsCount : importResult.totalRows,
3546
+ ")"
3547
+ ]
3548
+ }
3549
+ )
3550
+ ] })
3551
+ ] })
3552
+ ] })
3553
+ }
3554
+ ),
2725
3555
  /* @__PURE__ */ jsx("div", { className: "overflow-x-auto rounded-2xl border border-slate-200 bg-white shadow-sm", children: /* @__PURE__ */ jsxs("table", { className: "w-full text-sm text-left", children: [
2726
3556
  /* @__PURE__ */ jsx("thead", { className: "bg-slate-50/80 border-b border-slate-200", children: /* @__PURE__ */ jsxs("tr", { children: [
2727
3557
  visibleFields.map((f) => /* @__PURE__ */ jsx("th", { className: "px-6 py-4 text-xs font-bold text-slate-500 uppercase tracking-wider", children: f.label }, f.id)),
@@ -2775,7 +3605,30 @@ function CollectionEditor({ collection }) {
2775
3605
  onDragEnd,
2776
3606
  className: `hover:bg-slate-50/50 transition-colors group cursor-grab active:cursor-grabbing ${deletingId === e.id ? "opacity-50" : ""} ${dragOverIdx === idx ? "border-t-2 border-t-indigo-500" : ""}`,
2777
3607
  children: [
2778
- visibleFields.map((f) => /* @__PURE__ */ jsx("td", { className: "px-6 py-4 text-slate-700 max-w-[200px] truncate", children: f.type === "branch-settings" ? /* @__PURE__ */ jsx(BranchSettingsSummary, { value: e[f.id] }) : f.type === "boolean" ? e[f.id] ? /* @__PURE__ */ jsx("span", { className: "inline-flex px-2 py-1 rounded bg-green-100 text-green-700 text-xs font-bold", children: "Yes" }) : /* @__PURE__ */ jsx("span", { className: "inline-flex px-2 py-1 rounded bg-slate-100 text-slate-500 text-xs font-bold", children: "No" }) : f.type === "image" && (Array.isArray(e[f.id]) ? e[f.id].length > 0 : !!e[f.id]) ? /* @__PURE__ */ jsx("img", { src: Array.isArray(e[f.id]) ? String(e[f.id][0]) : String(e[f.id]), alt: "", className: "h-8 w-8 object-cover rounded shadow-sm ring-1 ring-slate-200" }) : f.type === "image" ? /* @__PURE__ */ jsx("div", { className: "h-8 w-8 rounded bg-slate-100 ring-1 ring-slate-200/50 flex items-center justify-center text-slate-300", children: /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: "2", d: "M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" }) }) }) : (f.id === "status" || f.id === "estado") && e[f.id] ? /* @__PURE__ */ jsx("span", { className: `inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold ${String(e[f.id]) === "Terminado" || String(e[f.id]) === "Terminada" || String(e[f.id]).includes("Entregado") ? "bg-emerald-50 text-emerald-700 border border-emerald-200" : String(e[f.id]) === "Proceso" || String(e[f.id]).includes("Preparaci\xF3n") ? "bg-amber-50 text-amber-700 border border-amber-200" : String(e[f.id]) === "Cancelado" || String(e[f.id]).includes("Cancelado") ? "bg-slate-100 text-slate-700 border border-slate-200" : String(e[f.id]) === "Vencido" || String(e[f.id]).toLowerCase().includes("vencid") ? "bg-rose-50 text-rose-700 border border-rose-200" : "bg-blue-50 text-blue-700 border border-blue-200"}`, children: String(e[f.id]) }) : (f.type === "reference" || f.type === "select" && f.collection) && e[f.id] ? e.clienteNombre && f.id === "clienteId" ? /* @__PURE__ */ jsx("span", { className: "font-medium text-slate-800", children: String(e.clienteNombre) }) : e.empleadoNombre && f.id === "empleadoId" ? /* @__PURE__ */ jsx("span", { className: "font-medium text-slate-800", children: String(e.empleadoNombre) }) : /* @__PURE__ */ jsx(ReferenceTableCell, { collectionId: f.collection, entryId: e[f.id], displayField: f.displayField, valueField: f.valueField, multiple: f.multiple }) : f.type === "signature" && e[f.id] ? /* @__PURE__ */ jsx(Image, { src: String(e[f.id]), alt: "Firma", className: "h-7 max-w-[80px] object-contain rounded bg-white border border-slate-200 p-0.5 inline-block shadow-xs cursor-pointer", preview: { mask: "Ver" } }) : f.type === "number" && e[f.id] !== void 0 && e[f.id] !== null && String(e[f.id]) !== "" ? f.id.toLowerCase().includes("price") || f.id.toLowerCase().includes("precio") || f.label.toLowerCase().includes("precio") || f.label.includes("$") || f.id.toLowerCase().includes("amount") || f.id.toLowerCase().includes("total") ? /* @__PURE__ */ jsxs("span", { className: "font-semibold text-slate-800", children: [
3608
+ visibleFields.map((f) => /* @__PURE__ */ jsx("td", { className: "px-6 py-4 text-slate-700 max-w-[200px] truncate", children: f.renderCell ? f.renderCell(e[f.id], e) : f.type === "branch-settings" ? /* @__PURE__ */ jsx(BranchSettingsSummary, { value: e[f.id] }) : f.type === "boolean" ? e[f.id] ? /* @__PURE__ */ jsx("span", { className: "inline-flex px-2 py-1 rounded bg-green-100 text-green-700 text-xs font-bold", children: "Yes" }) : /* @__PURE__ */ jsx("span", { className: "inline-flex px-2 py-1 rounded bg-slate-100 text-slate-500 text-xs font-bold", children: "No" }) : f.type === "image" && (Array.isArray(e[f.id]) ? e[f.id].length > 0 : !!e[f.id]) ? /* @__PURE__ */ jsx("img", { src: Array.isArray(e[f.id]) ? String(e[f.id][0]) : String(e[f.id]), alt: "", className: "h-8 w-8 object-cover rounded shadow-sm ring-1 ring-slate-200" }) : f.type === "image" ? /* @__PURE__ */ jsx("div", { className: "h-8 w-8 rounded bg-slate-100 ring-1 ring-slate-200/50 flex items-center justify-center text-slate-300", children: /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: "2", d: "M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" }) }) }) : (f.id === "status" || f.id === "estado") && e[f.id] ? /* @__PURE__ */ jsx("span", { className: `inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold ${String(e[f.id]) === "Terminado" || String(e[f.id]) === "Terminada" || String(e[f.id]).includes("Entregado") ? "bg-emerald-50 text-emerald-700 border border-emerald-200" : String(e[f.id]) === "Proceso" || String(e[f.id]).includes("Preparaci\xF3n") ? "bg-amber-50 text-amber-700 border border-amber-200" : String(e[f.id]) === "Cancelado" || String(e[f.id]).includes("Cancelado") ? "bg-slate-100 text-slate-700 border border-slate-200" : String(e[f.id]) === "Vencido" || String(e[f.id]).toLowerCase().includes("vencid") ? "bg-rose-50 text-rose-700 border border-rose-200" : "bg-blue-50 text-blue-700 border border-blue-200"}`, children: String(e[f.id]) }) : (f.type === "reference" || f.type === "select" && f.collection) && e[f.id] ? f.onCellClick ? /* @__PURE__ */ jsx(
3609
+ "button",
3610
+ {
3611
+ type: "button",
3612
+ onClick: () => f.onCellClick(e[f.id], e),
3613
+ className: "font-medium text-indigo-600 hover:text-indigo-800 hover:underline cursor-pointer text-left truncate block max-w-full",
3614
+ children: /* @__PURE__ */ jsx(ReferenceTableCell, { collectionId: f.collection, entryId: e[f.id], displayField: f.displayField, valueField: f.valueField, multiple: f.multiple })
3615
+ }
3616
+ ) : /* @__PURE__ */ jsx(ReferenceTableCell, { collectionId: f.collection, entryId: e[f.id], displayField: f.displayField, valueField: f.valueField, multiple: f.multiple }) : (f.type === "list" || f.multiple) && e[f.id] ? Array.isArray(e[f.id]) ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
3617
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: String(e[f.id][0] || "") }),
3618
+ e[f.id].length > 1 && /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center px-1.5 py-0.2 rounded text-[10px] font-bold bg-indigo-50 text-indigo-700 border border-indigo-100 shrink-0", children: [
3619
+ "+",
3620
+ e[f.id].length - 1,
3621
+ " m\xE1s"
3622
+ ] })
3623
+ ] }) : /* @__PURE__ */ jsx("span", { children: String(e[f.id]) }) : f.onCellClick ? /* @__PURE__ */ jsx(
3624
+ "button",
3625
+ {
3626
+ type: "button",
3627
+ onClick: () => f.onCellClick(e[f.id], e),
3628
+ className: "font-medium text-indigo-600 hover:text-indigo-800 hover:underline cursor-pointer text-left truncate block w-full",
3629
+ children: String(e[f.id] ?? "")
3630
+ }
3631
+ ) : f.type === "signature" && e[f.id] ? /* @__PURE__ */ jsx(Image, { src: String(e[f.id]), alt: "Firma", className: "h-7 max-w-[80px] object-contain rounded bg-white border border-slate-200 p-0.5 inline-block shadow-xs cursor-pointer", preview: { mask: "Ver" } }) : f.type === "number" && e[f.id] !== void 0 && e[f.id] !== null && String(e[f.id]) !== "" ? f.id.toLowerCase().includes("price") || f.id.toLowerCase().includes("precio") || f.label.toLowerCase().includes("precio") || f.label.includes("$") || f.id.toLowerCase().includes("amount") || f.id.toLowerCase().includes("total") ? /* @__PURE__ */ jsxs("span", { className: "font-semibold text-slate-800", children: [
2779
3632
  "$ ",
2780
3633
  Number(e[f.id]).toLocaleString("es-CO")
2781
3634
  ] }) : /* @__PURE__ */ jsx("span", { children: Number(e[f.id]).toLocaleString("es-CO") }) : f.type === "link" || typeof e[f.id] === "string" && String(e[f.id]).startsWith("http") ? /* @__PURE__ */ jsxs(
@@ -2792,18 +3645,64 @@ function CollectionEditor({ collection }) {
2792
3645
  }
2793
3646
  ) : f.type === "time" || f.id.toLowerCase().includes("hora") || f.id === "inicioServicio" || f.id === "finServicio" ? formatTo12Hour(e[f.id]) || String(e[f.id] ?? "") : String(e[f.id] ?? "") }, f.id)),
2794
3647
  /* @__PURE__ */ jsx("td", { className: "px-6 py-4 text-right sticky right-0 bg-white border-l border-slate-100 group-hover:bg-slate-50/50 transition-colors", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-1.5", children: [
2795
- collection.enableDetailView && /* @__PURE__ */ jsx(
3648
+ collection.customRowActions && collection.customRowActions({
3649
+ record: e,
3650
+ openDetail: () => {
3651
+ if (collection.customDetailView || collection.renderCustomDetail) {
3652
+ setCustomViewingRecord(e);
3653
+ setIsCustomEditing(false);
3654
+ return;
3655
+ }
3656
+ if (collection.onViewRecord) {
3657
+ collection.onViewRecord(e);
3658
+ return;
3659
+ }
3660
+ setIsCreatingManual(false);
3661
+ setIsViewingDetail(true);
3662
+ setOriginalId(String(e.id || ""));
3663
+ setDuplicateErrors({});
3664
+ setEditing({ ...e });
3665
+ },
3666
+ openEdit: () => {
3667
+ if (collection.customEditView) {
3668
+ setCustomViewingRecord(e);
3669
+ setIsCustomEditing(true);
3670
+ return;
3671
+ }
3672
+ setIsCreatingManual(false);
3673
+ setIsViewingDetail(false);
3674
+ setOriginalId(String(e.id || ""));
3675
+ setDuplicateErrors({});
3676
+ setEditing({ ...e });
3677
+ },
3678
+ openCustomView: (renderFn) => {
3679
+ setCustomActiveView(() => renderFn);
3680
+ },
3681
+ reload: () => {
3682
+ load();
3683
+ }
3684
+ }),
3685
+ (collection.enableDetailView || collection.onViewRecord || collection.customDetailView || collection.renderCustomDetail) && /* @__PURE__ */ jsx(
2796
3686
  "button",
2797
3687
  {
2798
3688
  onClick: () => {
3689
+ if (collection.customDetailView || collection.renderCustomDetail) {
3690
+ setCustomViewingRecord(e);
3691
+ setIsCustomEditing(false);
3692
+ return;
3693
+ }
3694
+ if (collection.onViewRecord) {
3695
+ collection.onViewRecord(e);
3696
+ return;
3697
+ }
2799
3698
  setIsCreatingManual(false);
2800
3699
  setIsViewingDetail(true);
2801
3700
  setOriginalId(String(e.id || ""));
2802
3701
  setDuplicateErrors({});
2803
3702
  setEditing({ ...e });
2804
3703
  },
2805
- className: "p-2 rounded-lg text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 transition-colors",
2806
- title: "Ver detalle",
3704
+ className: "p-2 rounded-lg text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 transition-colors cursor-pointer",
3705
+ title: collection.viewRecordTitle || "Ver detalle",
2807
3706
  children: /* @__PURE__ */ jsx(Eye, { className: "h-4 w-4" })
2808
3707
  }
2809
3708
  ),
@@ -2820,6 +3719,11 @@ function CollectionEditor({ collection }) {
2820
3719
  "button",
2821
3720
  {
2822
3721
  onClick: () => {
3722
+ if (collection.customEditView) {
3723
+ setCustomViewingRecord(e);
3724
+ setIsCustomEditing(true);
3725
+ return;
3726
+ }
2823
3727
  setIsCreatingManual(false);
2824
3728
  setIsViewingDetail(false);
2825
3729
  setOriginalId(String(e.id || ""));
@@ -2831,7 +3735,7 @@ function CollectionEditor({ collection }) {
2831
3735
  children: /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" })
2832
3736
  }
2833
3737
  ),
2834
- !collection.disableDelete && /* @__PURE__ */ jsx(
3738
+ !collection.disableDelete && !collection.hideDelete && (!collection.canDelete || collection.canDelete(e)) && /* @__PURE__ */ jsx(
2835
3739
  "button",
2836
3740
  {
2837
3741
  onClick: () => remove(e.id),
@@ -4397,9 +5301,9 @@ function ReferenceSelect({
4397
5301
  displayField = "name",
4398
5302
  valueField = "name",
4399
5303
  fallbackOptions,
4400
- multiple = false,
5304
+ multiple: _multiple = false,
4401
5305
  searchable = false,
4402
- max,
5306
+ max: _max,
4403
5307
  value,
4404
5308
  onChange,
4405
5309
  onSelectRecord
@@ -4409,45 +5313,46 @@ function ReferenceSelect({
4409
5313
  const { message } = App.useApp();
4410
5314
  const [options, setOptions] = useState([]);
4411
5315
  const [loading, setLoading] = useState(true);
4412
- const [clientModalOpen, setClientModalOpen] = useState(false);
4413
- const [creatingClient, setCreatingClient] = useState(false);
4414
- const [clientError, setClientError] = useState("");
4415
- const [newClient, setNewClient] = useState({
4416
- tipo: "Persona",
4417
- tipoDocumento: "C\xE9dula de ciudadan\xEDa",
4418
- id: "",
4419
- sucursal: "",
4420
- nombre: "",
4421
- email: "",
4422
- telefono: "",
4423
- ciudad: "",
4424
- direccion: ""
4425
- });
4426
- const handleSaveClient = async () => {
4427
- setClientError("");
4428
- if (!newClient.id.trim()) {
4429
- setClientError(t.idRequired);
4430
- return;
4431
- }
4432
- if (!newClient.nombre.trim()) {
4433
- setClientError(t.nameRequired);
4434
- return;
4435
- }
4436
- const cleanId = newClient.id.trim().toLowerCase();
4437
- const isDuplicate = options.some((opt) => String(opt.value || "").trim().toLowerCase() === cleanId);
4438
- if (isDuplicate) {
4439
- setClientError("Ya existe un cliente con este NIT o C\xE9dula. No se pueden repetir.");
4440
- return;
5316
+ const [modalOpen, setModalOpen] = useState(false);
5317
+ const [saving, setSaving] = useState(false);
5318
+ const [formError, setFormError] = useState("");
5319
+ const [newRecord, setNewRecord] = useState({});
5320
+ const targetCol = ctx.config.collections?.find((c) => c.id === collectionId);
5321
+ const handleSaveRecord = async () => {
5322
+ setFormError("");
5323
+ if (!targetCol) return;
5324
+ const uniqueFields = targetCol.fields.filter((f) => f.unique || f.id === "id" && !f.hideOnCreate);
5325
+ for (const uf of uniqueFields) {
5326
+ const val = String(newRecord[uf.id] || "").trim();
5327
+ if (!val) {
5328
+ setFormError(`El campo "${uf.label || uf.id}" es obligatorio.`);
5329
+ return;
5330
+ }
5331
+ const isDup = options.some((opt) => String(opt.value || "").trim().toLowerCase() === val.toLowerCase());
5332
+ if (isDup) {
5333
+ setFormError(`Ya existe un registro con este ${uf.label.toLowerCase()} (\xAB${val}\xBB).`);
5334
+ return;
5335
+ }
4441
5336
  }
4442
- setCreatingClient(true);
5337
+ setSaving(true);
4443
5338
  try {
4444
- const entry = {
4445
- ...newClient,
4446
- id: newClient.id.trim(),
4447
- nombre: newClient.nombre.trim()
5339
+ const entryToSave = {
5340
+ id: String(newRecord.id || Date.now()).trim(),
5341
+ ...newRecord
4448
5342
  };
4449
- await ctx.adapter.putEntry("clients", entry);
4450
- const res = await ctx.adapter.listEntries("clients");
5343
+ targetCol.fields.forEach((f) => {
5344
+ if (f.type === "list" || f.multiple) {
5345
+ if (Array.isArray(entryToSave[f.id])) {
5346
+ entryToSave[f.id] = entryToSave[f.id].filter(
5347
+ (item) => item !== void 0 && item !== null && String(item).trim() !== ""
5348
+ );
5349
+ } else if (typeof entryToSave[f.id] === "string" && entryToSave[f.id]) {
5350
+ entryToSave[f.id] = [String(entryToSave[f.id]).trim()];
5351
+ }
5352
+ }
5353
+ });
5354
+ await ctx.adapter.putEntry(collectionId, entryToSave);
5355
+ const res = await ctx.adapter.listEntries(collectionId);
4451
5356
  const fromCollection = (res || []).map((r) => {
4452
5357
  const val = valueField && r[valueField] !== void 0 ? String(r[valueField]) : r.name ? String(r.name) : r.id;
4453
5358
  const fullName = r.apellido ? `${r.nombre || r.name || ""} ${r.apellido}`.trim() : "";
@@ -4459,27 +5364,18 @@ function ReferenceSelect({
4459
5364
  };
4460
5365
  });
4461
5366
  setOptions(fromCollection);
4462
- onChange(entry.id);
5367
+ const selectedVal = valueField && entryToSave[valueField] !== void 0 ? String(entryToSave[valueField]) : entryToSave.id;
5368
+ onChange(selectedVal);
4463
5369
  if (onSelectRecord) {
4464
- onSelectRecord(entry);
5370
+ onSelectRecord(entryToSave);
4465
5371
  }
4466
- setClientModalOpen(false);
4467
- setNewClient({
4468
- tipo: "Persona",
4469
- tipoDocumento: "C\xE9dula de ciudadan\xEDa",
4470
- id: "",
4471
- sucursal: "",
4472
- nombre: "",
4473
- email: "",
4474
- telefono: "",
4475
- ciudad: "",
4476
- direccion: ""
4477
- });
4478
- message.success(t.clientCreatedSuccess);
5372
+ setModalOpen(false);
5373
+ setNewRecord({});
5374
+ message.success(t.recordCreatedSuccess || "Registro creado y seleccionado exitosamente.");
4479
5375
  } catch (err) {
4480
- setClientError(err?.message || "Error al crear cliente.");
5376
+ setFormError(err?.message || "Error al crear registro.");
4481
5377
  } finally {
4482
- setCreatingClient(false);
5378
+ setSaving(false);
4483
5379
  }
4484
5380
  };
4485
5381
  useEffect(() => {
@@ -4504,41 +5400,24 @@ function ReferenceSelect({
4504
5400
  });
4505
5401
  setOptions(fromCollection);
4506
5402
  setLoading(false);
4507
- }).catch(() => {
4508
- setOptions([]);
5403
+ }).catch((err) => {
5404
+ console.error(`Failed to load reference entries for ${collectionId}:`, err);
5405
+ if (fallbackOptions && fallbackOptions.length > 0) {
5406
+ setOptions(fallbackOptions.map((opt) => typeof opt === "string" ? { value: opt, label: opt } : opt));
5407
+ }
4509
5408
  setLoading(false);
4510
5409
  });
4511
- }, [collectionId, displayField, valueField, fallbackOptions, ctx.adapter, ctx.collectionChangedAt]);
4512
- if (multiple) {
4513
- const selectedList = Array.isArray(value) ? value.map(String) : typeof value === "string" && value.trim() ? value.split(",").map((s) => s.trim()).filter(Boolean) : [];
4514
- return /* @__PURE__ */ jsx(
4515
- Select,
4516
- {
4517
- size: "large",
4518
- mode: "multiple",
4519
- loading,
4520
- showSearch: searchable,
4521
- placeholder: "Seleccionar opciones...",
4522
- filterOption: (input, option) => {
4523
- if (!input) return true;
4524
- const q = input.toLowerCase();
4525
- const label = String(option?.label ?? "").toLowerCase();
4526
- const val = String(option?.value ?? "").toLowerCase();
4527
- return label.includes(q) || val.includes(q);
4528
- },
4529
- maxCount: max,
4530
- value: selectedList,
4531
- onChange,
4532
- options,
4533
- className: "w-full"
4534
- }
4535
- );
4536
- }
4537
- const singleVal = value !== void 0 && value !== null && value !== "" ? String(value) : void 0;
4538
- const displayOptions = [...options];
4539
- if (singleVal && !displayOptions.some((o) => o.value === singleVal)) {
4540
- displayOptions.unshift({ value: singleVal, label: singleVal });
4541
- }
5410
+ }, [collectionId, displayField, valueField, fallbackOptions, ctx.adapter]);
5411
+ const rawVal = Array.isArray(value) ? value : value !== void 0 && value !== null && value !== "" ? [value] : [];
5412
+ const singleVal = rawVal[0] !== void 0 ? String(rawVal[0]) : void 0;
5413
+ const displayOptions = useMemo(() => {
5414
+ const list = [...options];
5415
+ if (singleVal && !list.some((o) => o.value === singleVal)) {
5416
+ list.unshift({ value: singleVal, label: `${singleVal} (actual)` });
5417
+ }
5418
+ return list;
5419
+ }, [options, singleVal]);
5420
+ const canQuickCreate = Boolean(targetCol && targetCol.enableQuickCreate !== false);
4542
5421
  return /* @__PURE__ */ jsxs(Fragment, { children: [
4543
5422
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
4544
5423
  /* @__PURE__ */ jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsx(
@@ -4567,8 +5446,8 @@ function ReferenceSelect({
4567
5446
  options: displayOptions,
4568
5447
  dropdownRender: (menu) => /* @__PURE__ */ jsxs("div", { children: [
4569
5448
  menu,
4570
- collectionId === "clients" && /* @__PURE__ */ jsxs("div", { className: "p-2 border-t border-slate-100 flex items-center justify-between bg-slate-50", children: [
4571
- /* @__PURE__ */ jsx("span", { className: "text-xs text-slate-500 font-medium", children: t.cantFindClient }),
5449
+ canQuickCreate && /* @__PURE__ */ jsxs("div", { className: "p-2 border-t border-slate-100 flex items-center justify-between bg-slate-50", children: [
5450
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-slate-500 font-medium", children: t.cantFindOption || "\xBFNo encuentras la opci\xF3n?" }),
4572
5451
  /* @__PURE__ */ jsx(
4573
5452
  Button,
4574
5453
  {
@@ -4576,11 +5455,18 @@ function ReferenceSelect({
4576
5455
  size: "small",
4577
5456
  icon: /* @__PURE__ */ jsx(Plus, { className: "w-3.5 h-3.5" }),
4578
5457
  onClick: () => {
4579
- setClientError("");
4580
- setClientModalOpen(true);
5458
+ setFormError("");
5459
+ const init = {};
5460
+ targetCol.fields.forEach((f) => {
5461
+ if (f.defaultValue !== void 0) init[f.id] = f.defaultValue;
5462
+ else if (f.type === "list" || f.multiple) init[f.id] = [""];
5463
+ else init[f.id] = "";
5464
+ });
5465
+ setNewRecord(init);
5466
+ setModalOpen(true);
4581
5467
  },
4582
5468
  className: "bg-blue-600 hover:bg-blue-700 text-xs font-semibold rounded-lg shadow-sm",
4583
- children: t.createClient
5469
+ children: t.createNewOption || `Crear ${targetCol.name}`
4584
5470
  }
4585
5471
  )
4586
5472
  ] })
@@ -4588,192 +5474,191 @@ function ReferenceSelect({
4588
5474
  className: "w-full"
4589
5475
  }
4590
5476
  ) }),
4591
- collectionId === "clients" && /* @__PURE__ */ jsx(
5477
+ canQuickCreate && /* @__PURE__ */ jsx(
4592
5478
  Button,
4593
5479
  {
4594
5480
  type: "primary",
4595
5481
  size: "large",
4596
5482
  icon: /* @__PURE__ */ jsx(Plus, { className: "w-4 h-4" }),
4597
5483
  onClick: () => {
4598
- setClientError("");
4599
- setClientModalOpen(true);
5484
+ setFormError("");
5485
+ const init = {};
5486
+ targetCol.fields.forEach((f) => {
5487
+ if (f.defaultValue !== void 0) init[f.id] = f.defaultValue;
5488
+ else if (f.type === "list" || f.multiple) init[f.id] = [""];
5489
+ else init[f.id] = "";
5490
+ });
5491
+ setNewRecord(init);
5492
+ setModalOpen(true);
4600
5493
  },
4601
5494
  className: "bg-blue-600 hover:bg-blue-700 font-bold rounded-xl shrink-0 h-10 px-4 text-xs uppercase tracking-wider",
4602
- children: t.newBtn
5495
+ children: targetCol.submitLabel || t.newBtn
4603
5496
  }
4604
5497
  )
4605
5498
  ] }),
4606
- collectionId === "clients" && /* @__PURE__ */ jsx(
5499
+ canQuickCreate && /* @__PURE__ */ jsx(
4607
5500
  Modal,
4608
5501
  {
4609
- open: clientModalOpen,
4610
- title: /* @__PURE__ */ jsx("span", { className: "text-xl font-bold text-slate-900 font-display", children: t.basicDetails }),
4611
- onCancel: () => setClientModalOpen(false),
5502
+ open: modalOpen,
5503
+ title: /* @__PURE__ */ jsx("span", { className: "text-xl font-bold text-slate-900 font-display", children: targetCol.createTitle || `${t.newBtn} ${targetCol.name}` }),
5504
+ onCancel: () => setModalOpen(false),
4612
5505
  centered: true,
4613
5506
  width: 650,
4614
5507
  footer: null,
4615
5508
  children: /* @__PURE__ */ jsxs("div", { className: "pt-2 space-y-4", children: [
4616
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-3", children: [
4617
- /* @__PURE__ */ jsxs("div", { children: [
4618
- /* @__PURE__ */ jsx("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientType }),
4619
- /* @__PURE__ */ jsx(
4620
- Select,
4621
- {
4622
- size: "large",
4623
- value: newClient.tipo,
4624
- onChange: (val) => {
4625
- setNewClient((prev) => ({
4626
- ...prev,
4627
- tipo: val,
4628
- tipoDocumento: val === "Empresa" ? "Nit" : "C\xE9dula de ciudadan\xEDa"
4629
- }));
4630
- },
4631
- options: [
4632
- { label: "Persona", value: "Persona" },
4633
- { label: "Empresa", value: "Empresa" }
4634
- ],
4635
- className: "w-full"
4636
- }
4637
- )
4638
- ] }),
4639
- /* @__PURE__ */ jsxs("div", { children: [
4640
- /* @__PURE__ */ jsx("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientDocType }),
4641
- /* @__PURE__ */ jsx(
4642
- Select,
4643
- {
4644
- size: "large",
4645
- value: newClient.tipoDocumento,
4646
- onChange: (val) => setNewClient((prev) => ({ ...prev, tipoDocumento: val })),
4647
- options: newClient.tipo === "Persona" ? [
4648
- { label: "C\xE9dula de ciudadan\xEDa", value: "C\xE9dula de ciudadan\xEDa" },
4649
- { label: "C\xE9dula de extranjer\xEDa", value: "C\xE9dula de extranjer\xEDa" },
4650
- { label: "Pasaporte", value: "Pasaporte" }
4651
- ] : [{ label: "Nit", value: "Nit" }],
4652
- className: "w-full"
4653
- }
4654
- )
4655
- ] })
4656
- ] }),
4657
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-3", children: [
4658
- /* @__PURE__ */ jsxs("div", { children: [
5509
+ /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-3", children: targetCol.fields.filter((f) => !f.hideOnCreate && !f.readOnly && f.type !== "signature").map((f) => {
5510
+ if (f.dependsOn && newRecord[f.dependsOn.field] !== void 0) {
5511
+ const targetVal = f.dependsOn.value;
5512
+ const currentVal = newRecord[f.dependsOn.field];
5513
+ const match = Array.isArray(targetVal) ? targetVal.includes(currentVal) : currentVal === targetVal;
5514
+ if (!match) return null;
5515
+ }
5516
+ const isFullWidth = f.colSpan === 2 || f.colSpan === 12 || f.multiple || f.type === "list" || f.type === "textarea";
5517
+ const colSpanClass = isFullWidth ? "col-span-1 sm:col-span-2" : "col-span-1";
5518
+ if (f.type === "list" || f.multiple) {
5519
+ const currentList = Array.isArray(newRecord[f.id]) ? newRecord[f.id] : newRecord[f.id] ? [String(newRecord[f.id])] : [""];
5520
+ const singularLabel = f.label.endsWith("es") ? f.label.slice(0, -2) : f.label.endsWith("s") ? f.label.slice(0, -1) : f.label;
5521
+ return /* @__PURE__ */ jsxs("div", { className: colSpanClass, children: [
5522
+ /* @__PURE__ */ jsx("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: f.label }),
5523
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
5524
+ currentList.map((item, idx) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
5525
+ /* @__PURE__ */ jsxs("span", { className: "text-xs font-mono font-bold text-slate-400 w-6 text-right shrink-0", children: [
5526
+ "#",
5527
+ idx + 1
5528
+ ] }),
5529
+ /* @__PURE__ */ jsx(
5530
+ Input,
5531
+ {
5532
+ size: "large",
5533
+ value: item,
5534
+ placeholder: `${singularLabel} #${idx + 1}...`,
5535
+ onChange: (e) => {
5536
+ const updated = [...currentList];
5537
+ updated[idx] = e.target.value;
5538
+ setNewRecord((prev) => ({ ...prev, [f.id]: updated }));
5539
+ }
5540
+ }
5541
+ ),
5542
+ currentList.length > 1 && /* @__PURE__ */ jsx(
5543
+ "button",
5544
+ {
5545
+ type: "button",
5546
+ onClick: () => {
5547
+ const updated = currentList.filter((_, i) => i !== idx);
5548
+ setNewRecord((prev) => ({
5549
+ ...prev,
5550
+ [f.id]: updated.length > 0 ? updated : [""]
5551
+ }));
5552
+ },
5553
+ className: "p-2 text-rose-500 hover:text-rose-700 hover:bg-rose-50 rounded-lg cursor-pointer shrink-0",
5554
+ children: /* @__PURE__ */ jsx(Trash2, { className: "size-4" })
5555
+ }
5556
+ )
5557
+ ] }, idx)),
5558
+ /* @__PURE__ */ jsxs(
5559
+ Button,
5560
+ {
5561
+ type: "dashed",
5562
+ size: "small",
5563
+ icon: /* @__PURE__ */ jsx(Plus, { className: "size-3.5" }),
5564
+ onClick: () => setNewRecord((prev) => ({
5565
+ ...prev,
5566
+ [f.id]: [...currentList, ""]
5567
+ })),
5568
+ className: "w-full text-xs font-semibold",
5569
+ children: [
5570
+ "+ Agregar ",
5571
+ singularLabel.toLowerCase()
5572
+ ]
5573
+ }
5574
+ )
5575
+ ] })
5576
+ ] }, f.id);
5577
+ }
5578
+ if (f.type === "select") {
5579
+ const opts = f.optionsMap && f.dependsOnField ? f.optionsMap[String(newRecord[f.dependsOnField] || "")] || f.options || [] : f.options || [];
5580
+ const formattedOpts = opts.map((o) => typeof o === "string" ? { label: o, value: o } : o);
5581
+ return /* @__PURE__ */ jsxs("div", { className: colSpanClass, children: [
5582
+ /* @__PURE__ */ jsx("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: f.label }),
5583
+ /* @__PURE__ */ jsx(
5584
+ Select,
5585
+ {
5586
+ size: "large",
5587
+ value: newRecord[f.id] || void 0,
5588
+ onChange: (val) => {
5589
+ setNewRecord((prev) => {
5590
+ const next = { ...prev, [f.id]: val };
5591
+ targetCol.fields.forEach((dep) => {
5592
+ if (dep.dependsOnField === f.id && dep.optionsMap) {
5593
+ const nextOpts = dep.optionsMap[val] || dep.options || [];
5594
+ const firstVal = typeof nextOpts[0] === "string" ? nextOpts[0] : nextOpts[0]?.value;
5595
+ next[dep.id] = firstVal || "";
5596
+ }
5597
+ });
5598
+ return next;
5599
+ });
5600
+ },
5601
+ options: formattedOpts,
5602
+ className: "w-full"
5603
+ }
5604
+ )
5605
+ ] }, f.id);
5606
+ }
5607
+ if (f.type === "textarea") {
5608
+ return /* @__PURE__ */ jsxs("div", { className: colSpanClass, children: [
5609
+ /* @__PURE__ */ jsx("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: f.label }),
5610
+ /* @__PURE__ */ jsx(
5611
+ Input.TextArea,
5612
+ {
5613
+ rows: 3,
5614
+ value: newRecord[f.id] || "",
5615
+ onChange: (e) => setNewRecord((prev) => ({ ...prev, [f.id]: e.target.value }))
5616
+ }
5617
+ )
5618
+ ] }, f.id);
5619
+ }
5620
+ return /* @__PURE__ */ jsxs("div", { className: colSpanClass, children: [
4659
5621
  /* @__PURE__ */ jsxs("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: [
4660
- t.clientIdentification,
4661
- " *"
5622
+ f.label,
5623
+ " ",
5624
+ f.unique ? "*" : ""
4662
5625
  ] }),
4663
5626
  /* @__PURE__ */ jsx(
4664
5627
  Input,
4665
5628
  {
4666
5629
  size: "large",
4667
- status: clientError && clientError.includes("identificaci\xF3n") ? "error" : void 0,
4668
- placeholder: t.clientIdentification,
4669
- value: newClient.id,
5630
+ value: newRecord[f.id] || "",
5631
+ placeholder: f.label,
4670
5632
  onChange: (e) => {
4671
- setNewClient((prev) => ({ ...prev, id: e.target.value }));
4672
- if (clientError) setClientError("");
5633
+ setNewRecord((prev) => ({ ...prev, [f.id]: e.target.value }));
5634
+ if (formError) setFormError("");
4673
5635
  },
4674
5636
  onBlur: (e) => {
4675
- const clean = (e.target.value || "").trim().toLowerCase();
4676
- if (clean) {
4677
- const dup = options.find((opt) => String(opt.value || "").trim().toLowerCase() === clean);
4678
- if (dup) {
4679
- setClientError(`Ya existe un cliente con esta identificaci\xF3n (\xAB${dup.label || clean}\xBB).`);
4680
- message.warning(`\u26A0\uFE0F Ya existe un cliente con esta identificaci\xF3n: ${clean}.`);
5637
+ if (f.unique) {
5638
+ const clean = (e.target.value || "").trim().toLowerCase();
5639
+ if (clean) {
5640
+ const dup = options.find((opt) => String(opt.value || "").trim().toLowerCase() === clean);
5641
+ if (dup) {
5642
+ setFormError(`Ya existe un registro con este ${f.label.toLowerCase()} (\xAB${dup.label || clean}\xBB).`);
5643
+ message.warning(`\u26A0\uFE0F Ya existe un registro con este ${f.label.toLowerCase()}: ${clean}.`);
5644
+ }
4681
5645
  }
4682
5646
  }
4683
5647
  }
4684
5648
  }
4685
5649
  )
4686
- ] }),
4687
- /* @__PURE__ */ jsxs("div", { children: [
4688
- /* @__PURE__ */ jsx("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientBranch }),
4689
- /* @__PURE__ */ jsx(
4690
- Input,
4691
- {
4692
- size: "large",
4693
- placeholder: t.clientBranch,
4694
- value: newClient.sucursal,
4695
- onChange: (e) => setNewClient((prev) => ({ ...prev, sucursal: e.target.value }))
4696
- }
4697
- )
4698
- ] })
4699
- ] }),
4700
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-3", children: [
4701
- /* @__PURE__ */ jsxs("div", { children: [
4702
- /* @__PURE__ */ jsxs("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: [
4703
- t.clientName,
4704
- " *"
4705
- ] }),
4706
- /* @__PURE__ */ jsx(
4707
- Input,
4708
- {
4709
- size: "large",
4710
- placeholder: t.clientName,
4711
- value: newClient.nombre,
4712
- onChange: (e) => setNewClient((prev) => ({ ...prev, nombre: e.target.value }))
4713
- }
4714
- )
4715
- ] }),
4716
- /* @__PURE__ */ jsxs("div", { children: [
4717
- /* @__PURE__ */ jsx("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientEmail }),
4718
- /* @__PURE__ */ jsx(
4719
- Input,
4720
- {
4721
- size: "large",
4722
- placeholder: t.clientEmail,
4723
- value: newClient.email,
4724
- onChange: (e) => setNewClient((prev) => ({ ...prev, email: e.target.value }))
4725
- }
4726
- )
4727
- ] })
4728
- ] }),
4729
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-3", children: [
4730
- /* @__PURE__ */ jsxs("div", { children: [
4731
- /* @__PURE__ */ jsx("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientPhone }),
4732
- /* @__PURE__ */ jsx(
4733
- Input,
4734
- {
4735
- size: "large",
4736
- placeholder: t.clientPhone,
4737
- value: newClient.telefono,
4738
- onChange: (e) => setNewClient((prev) => ({ ...prev, telefono: e.target.value }))
4739
- }
4740
- )
4741
- ] }),
4742
- /* @__PURE__ */ jsxs("div", { children: [
4743
- /* @__PURE__ */ jsx("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientCity }),
4744
- /* @__PURE__ */ jsx(
4745
- Input,
4746
- {
4747
- size: "large",
4748
- placeholder: t.clientCity,
4749
- value: newClient.ciudad,
4750
- onChange: (e) => setNewClient((prev) => ({ ...prev, ciudad: e.target.value }))
4751
- }
4752
- )
4753
- ] })
4754
- ] }),
4755
- /* @__PURE__ */ jsxs("div", { children: [
4756
- /* @__PURE__ */ jsx("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientAddress }),
4757
- /* @__PURE__ */ jsx(
4758
- Input,
4759
- {
4760
- size: "large",
4761
- placeholder: t.clientAddress,
4762
- value: newClient.direccion,
4763
- onChange: (e) => setNewClient((prev) => ({ ...prev, direccion: e.target.value }))
4764
- }
4765
- )
4766
- ] }),
4767
- clientError && /* @__PURE__ */ jsx("p", { className: "text-xs font-semibold text-red-600 bg-red-50 p-2.5 rounded-lg border border-red-200", children: clientError }),
5650
+ ] }, f.id);
5651
+ }) }),
5652
+ formError && /* @__PURE__ */ jsx("p", { className: "text-xs font-semibold text-red-600 bg-red-50 p-2.5 rounded-lg border border-red-200", children: formError }),
4768
5653
  /* @__PURE__ */ jsx(
4769
5654
  Button,
4770
5655
  {
4771
5656
  type: "primary",
4772
5657
  size: "large",
4773
- loading: creatingClient,
4774
- onClick: handleSaveClient,
5658
+ loading: saving,
5659
+ onClick: handleSaveRecord,
4775
5660
  className: "w-full bg-blue-600 hover:bg-blue-700 font-bold uppercase rounded-xl h-11 text-xs tracking-wider shadow-sm mt-2",
4776
- children: t.create.toUpperCase()
5661
+ children: (targetCol.submitLabel || t.create).toUpperCase()
4777
5662
  }
4778
5663
  )
4779
5664
  ] })