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.js CHANGED
@@ -829,9 +829,224 @@ function EditableReference({
829
829
  var import_react5 = __toESM(require("react"));
830
830
  var import_react_dom = require("react-dom");
831
831
  var import_antd = require("antd");
832
- var import_dayjs = __toESM(require("dayjs"));
832
+ var import_dayjs2 = __toESM(require("dayjs"));
833
833
  var import_lucide_react2 = require("lucide-react");
834
834
 
835
+ // src/admin/excel.ts
836
+ var XLSX = __toESM(require("xlsx"));
837
+ var import_dayjs = __toESM(require("dayjs"));
838
+ function filterEntriesByDateRange(entries, fieldId, startDate, endDate) {
839
+ if (!startDate && !endDate) return entries;
840
+ const startDayjs = startDate ? (0, import_dayjs.default)(startDate).startOf("day") : null;
841
+ const endDayjs = endDate ? (0, import_dayjs.default)(endDate).endOf("day") : null;
842
+ return entries.filter((e) => {
843
+ const val = e[fieldId];
844
+ if (!val) return false;
845
+ const d = (0, import_dayjs.default)(String(val));
846
+ if (!d.isValid()) return false;
847
+ if (startDayjs && d.isBefore(startDayjs)) return false;
848
+ if (endDayjs && d.isAfter(endDayjs)) return false;
849
+ return true;
850
+ });
851
+ }
852
+ function findExistingEntry(item, existingEntries, collection) {
853
+ if (item.id && !item.id.startsWith("item_")) {
854
+ const cleanId = String(item.id).trim().toLowerCase();
855
+ const matchById = existingEntries.find(
856
+ (e) => e.id && String(e.id).trim().toLowerCase() === cleanId || e._id && String(e._id).trim().toLowerCase() === cleanId
857
+ );
858
+ if (matchById) return matchById;
859
+ }
860
+ const uniqueFieldIds = [];
861
+ (collection.fields || []).forEach((f) => {
862
+ if (f.unique && !uniqueFieldIds.includes(f.id)) {
863
+ uniqueFieldIds.push(f.id);
864
+ }
865
+ });
866
+ (collection.uniqueFields || []).forEach((uf) => {
867
+ if (!uniqueFieldIds.includes(uf)) {
868
+ uniqueFieldIds.push(uf);
869
+ }
870
+ });
871
+ for (const ufId of uniqueFieldIds) {
872
+ const itemVal = item[ufId];
873
+ if (itemVal !== void 0 && itemVal !== null && String(itemVal).trim() !== "") {
874
+ const cleanVal = String(itemVal).trim().toLowerCase();
875
+ const match = existingEntries.find((e) => {
876
+ const eVal = e[ufId];
877
+ return eVal !== void 0 && eVal !== null && String(eVal).trim().toLowerCase() === cleanVal;
878
+ });
879
+ if (match) return match;
880
+ }
881
+ }
882
+ return null;
883
+ }
884
+ function formatValueForExport(val, field) {
885
+ if (val === void 0 || val === null) return "";
886
+ if (typeof val === "number" || typeof val === "boolean") return val;
887
+ if (Array.isArray(val)) {
888
+ return val.map((item) => typeof item === "object" && item !== null ? JSON.stringify(item) : String(item)).join(", ");
889
+ }
890
+ if (typeof val === "object") {
891
+ try {
892
+ return JSON.stringify(val);
893
+ } catch {
894
+ return String(val);
895
+ }
896
+ }
897
+ return String(val);
898
+ }
899
+ function exportCollectionToExcel(collection, entries, fileNamePrefix) {
900
+ const columns = [
901
+ { key: "id", label: "ID" }
902
+ ];
903
+ (collection.fields || []).forEach((f) => {
904
+ columns.push({
905
+ key: f.id,
906
+ label: f.label || f.id,
907
+ field: f
908
+ });
909
+ });
910
+ const rows = entries.map((entry) => {
911
+ const rowObj = {};
912
+ columns.forEach((col) => {
913
+ const rawVal = entry[col.key];
914
+ rowObj[col.label] = formatValueForExport(rawVal, col.field);
915
+ });
916
+ return rowObj;
917
+ });
918
+ const worksheet = XLSX.utils.json_to_sheet(rows);
919
+ const colWidths = columns.map((col) => {
920
+ let maxLen = col.label.length;
921
+ for (let i = 0; i < Math.min(rows.length, 100); i++) {
922
+ const cellVal = String(rows[i]?.[col.label] ?? "");
923
+ if (cellVal.length > maxLen) {
924
+ maxLen = Math.min(cellVal.length, 45);
925
+ }
926
+ }
927
+ return { wch: Math.max(maxLen + 3, 12) };
928
+ });
929
+ worksheet["!cols"] = colWidths;
930
+ const workbook = XLSX.utils.book_new();
931
+ const safeSheetName = (collection.name || collection.id).replace(/[\\/?*[\]:]/g, "").slice(0, 31) || "Datos";
932
+ XLSX.utils.book_append_sheet(workbook, worksheet, safeSheetName);
933
+ const dateStr = (0, import_dayjs.default)().format("YYYY-MM-DD");
934
+ const baseName = fileNamePrefix || (collection.name || collection.id).toLowerCase().replace(/[^a-z0-9_-]+/g, "_");
935
+ const fileName = `${baseName}_${dateStr}.xlsx`;
936
+ XLSX.writeFile(workbook, fileName);
937
+ }
938
+ async function parseExcelForCollection(file, collection, existingEntries = []) {
939
+ const data = await file.arrayBuffer();
940
+ const workbook = XLSX.read(data, { type: "array" });
941
+ const firstSheetName = workbook.SheetNames[0];
942
+ if (!firstSheetName) {
943
+ throw new Error("El archivo no contiene ninguna hoja de c\xE1lculo.");
944
+ }
945
+ const worksheet = workbook.Sheets[firstSheetName];
946
+ const rawRows = XLSX.utils.sheet_to_json(worksheet, { defval: "" });
947
+ if (!rawRows.length) {
948
+ return {
949
+ records: [],
950
+ totalRows: 0,
951
+ matchedFields: [],
952
+ unmatchedHeaders: [],
953
+ samplePreview: [],
954
+ errors: ["El archivo no contiene filas con datos."]
955
+ };
956
+ }
957
+ const headers = Object.keys(rawRows[0] || {});
958
+ const matchedFields = [];
959
+ const unmatchedHeaders = [];
960
+ const headerToFieldMap = /* @__PURE__ */ new Map();
961
+ headers.forEach((header) => {
962
+ const cleanHeader = header.trim().toLowerCase();
963
+ if (cleanHeader === "id" || cleanHeader === "_id" || cleanHeader === "identificador") {
964
+ headerToFieldMap.set(header, "id");
965
+ matchedFields.push({ label: header, fieldId: "id" });
966
+ return;
967
+ }
968
+ const matched = (collection.fields || []).find((f) => {
969
+ const fieldLabel = (f.label || "").trim().toLowerCase();
970
+ const fieldId = f.id.trim().toLowerCase();
971
+ return fieldLabel === cleanHeader || fieldId === cleanHeader;
972
+ });
973
+ if (matched) {
974
+ headerToFieldMap.set(header, matched);
975
+ matchedFields.push({ label: header, fieldId: matched.id });
976
+ } else {
977
+ unmatchedHeaders.push(header);
978
+ }
979
+ });
980
+ const records = [];
981
+ const errors = [];
982
+ rawRows.forEach((row, idx) => {
983
+ const entry = { id: "" };
984
+ (collection.fields || []).forEach((f) => {
985
+ if (f.defaultValue !== void 0) {
986
+ entry[f.id] = f.defaultValue;
987
+ }
988
+ });
989
+ headers.forEach((header) => {
990
+ const mapping = headerToFieldMap.get(header);
991
+ const rawVal = row[header];
992
+ if (rawVal === void 0 || rawVal === "") return;
993
+ if (mapping === "id") {
994
+ entry.id = String(rawVal).trim();
995
+ return;
996
+ }
997
+ if (!mapping) return;
998
+ const field = mapping;
999
+ if (field.type === "number") {
1000
+ const num = Number(String(rawVal).replace(/[^0-9.-]/g, ""));
1001
+ entry[field.id] = isNaN(num) ? rawVal : num;
1002
+ } else if (field.type === "boolean") {
1003
+ const str = String(rawVal).trim().toLowerCase();
1004
+ entry[field.id] = str === "true" || str === "si" || str === "s\xED" || str === "yes" || str === "1" || str === "verdadero";
1005
+ } else if (field.multiple || field.type === "list") {
1006
+ if (typeof rawVal === "string") {
1007
+ entry[field.id] = rawVal.split(/[,;\n]/).map((s) => s.trim()).filter(Boolean);
1008
+ } else if (Array.isArray(rawVal)) {
1009
+ entry[field.id] = rawVal;
1010
+ } else {
1011
+ entry[field.id] = [String(rawVal)];
1012
+ }
1013
+ } else if (typeof rawVal === "string" && (rawVal.startsWith("{") || rawVal.startsWith("["))) {
1014
+ try {
1015
+ entry[field.id] = JSON.parse(rawVal);
1016
+ } catch {
1017
+ entry[field.id] = rawVal;
1018
+ }
1019
+ } else {
1020
+ entry[field.id] = rawVal;
1021
+ }
1022
+ });
1023
+ if (!entry.id) {
1024
+ entry.id = typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `item_${Date.now()}_${idx}`;
1025
+ }
1026
+ records.push(entry);
1027
+ });
1028
+ let existingCount = 0;
1029
+ let newCount = 0;
1030
+ records.forEach((rec) => {
1031
+ const existing = findExistingEntry(rec, existingEntries, collection);
1032
+ if (existing) {
1033
+ existingCount++;
1034
+ } else {
1035
+ newCount++;
1036
+ }
1037
+ });
1038
+ return {
1039
+ records,
1040
+ totalRows: records.length,
1041
+ matchedFields,
1042
+ unmatchedHeaders,
1043
+ samplePreview: records.slice(0, 5),
1044
+ existingRecordsCount: existingCount,
1045
+ newRecordsCount: newCount,
1046
+ errors
1047
+ };
1048
+ }
1049
+
835
1050
  // src/admin/i18n.ts
836
1051
  var translations = {
837
1052
  es: {
@@ -887,8 +1102,11 @@ var translations = {
887
1102
  saveSignature: "Guardar Firma",
888
1103
  selectOption: "-- Selecciona una opci\xF3n --",
889
1104
  loadingOptions: "Cargando opciones...",
890
- cantFindClient: "\xBFNo encuentras el cliente?",
891
- createClient: "Crear cliente",
1105
+ cantFindOption: "\xBFNo encuentras la opci\xF3n?",
1106
+ createNewOption: "Crear nuevo",
1107
+ recordCreatedSuccess: "Registro creado y seleccionado exitosamente.",
1108
+ cantFindClient: "\xBFNo encuentras la opci\xF3n?",
1109
+ createClient: "Crear nuevo",
892
1110
  newBtn: "Nuevo",
893
1111
  basicDetails: "Datos b\xE1sicos",
894
1112
  clientType: "Tipo",
@@ -913,6 +1131,29 @@ var translations = {
913
1131
  submissions: "Mensajes y Formularios",
914
1132
  noSubmissions: "No hay env\xEDos registrados",
915
1133
  exportCsv: "Exportar CSV",
1134
+ exportExcel: "Exportar Excel",
1135
+ importExcel: "Importar Excel",
1136
+ exportSuccess: "Archivo Excel exportado con \xE9xito.",
1137
+ importSuccess: "registros procesados exitosamente.",
1138
+ exportModalTitle: "Exportar a Excel",
1139
+ exportAllRecords: "Todos los registros",
1140
+ exportFilterByDate: "Filtrar por rango de fechas",
1141
+ exportDateFieldLabel: "Campo de fecha",
1142
+ exportDateRangeLabel: "Rango de fechas",
1143
+ exportDownloadBtn: "Descargar Excel",
1144
+ exportNoRecordsInRange: "No se encontraron registros en el rango seleccionado.",
1145
+ importModalTitle: "Importar datos desde Excel / CSV",
1146
+ importModalDesc: "Carga un archivo .xlsx, .xls o .csv para agregar o actualizar registros autom\xE1ticamente.",
1147
+ importDropzone: "Haz clic o arrastra un archivo Excel aqu\xED",
1148
+ importDropzoneSub: "Formatos compatibles: .xlsx, .xls, .csv. La primera fila debe contener los encabezados.",
1149
+ importPreviewTitle: "Vista previa de importaci\xF3n",
1150
+ importConfirmBtn: "Importar registros",
1151
+ importOverwritesWarning: "Tratamiento de registros ya existentes:",
1152
+ importingProgress: "Importando registros...",
1153
+ importExistingOmit: "Omitir existentes (no volver a crear ni duplicar)",
1154
+ importExistingUpdate: "Actualizar existentes con datos del archivo",
1155
+ importExistingDetected: "ya existentes",
1156
+ importNewDetected: "nuevos a crear",
916
1157
  markRead: "Marcar como le\xEDdo",
917
1158
  settingsTitle: "Ajustes del sitio",
918
1159
  entries: "registros"
@@ -970,8 +1211,11 @@ var translations = {
970
1211
  saveSignature: "Save Signature",
971
1212
  selectOption: "-- Select an option --",
972
1213
  loadingOptions: "Loading options...",
973
- cantFindClient: "Can't find the client?",
974
- createClient: "Create client",
1214
+ cantFindOption: "Can't find the option?",
1215
+ createNewOption: "Create new",
1216
+ recordCreatedSuccess: "Record created and selected successfully.",
1217
+ cantFindClient: "Can't find the option?",
1218
+ createClient: "Create new",
975
1219
  newBtn: "New",
976
1220
  basicDetails: "Basic details",
977
1221
  clientType: "Type",
@@ -996,6 +1240,29 @@ var translations = {
996
1240
  submissions: "Form Submissions",
997
1241
  noSubmissions: "No submissions yet",
998
1242
  exportCsv: "Export CSV",
1243
+ exportExcel: "Export Excel",
1244
+ importExcel: "Import Excel",
1245
+ exportSuccess: "Excel file exported successfully.",
1246
+ importSuccess: "records processed successfully.",
1247
+ exportModalTitle: "Export to Excel",
1248
+ exportAllRecords: "All records",
1249
+ exportFilterByDate: "Filter by date range",
1250
+ exportDateFieldLabel: "Date field",
1251
+ exportDateRangeLabel: "Date range",
1252
+ exportDownloadBtn: "Download Excel",
1253
+ exportNoRecordsInRange: "No records found in the selected date range.",
1254
+ importModalTitle: "Import data from Excel / CSV",
1255
+ importModalDesc: "Upload a .xlsx, .xls or .csv file to automatically create or update records.",
1256
+ importDropzone: "Click or drag an Excel file here",
1257
+ importDropzoneSub: "Supported formats: .xlsx, .xls, .csv. The first row must contain column headers.",
1258
+ importPreviewTitle: "Import Preview",
1259
+ importConfirmBtn: "Import records",
1260
+ importOverwritesWarning: "Handling of existing records:",
1261
+ importingProgress: "Importing records...",
1262
+ importExistingOmit: "Skip existing (do not recreate or duplicate)",
1263
+ importExistingUpdate: "Update existing with file data",
1264
+ importExistingDetected: "existing records",
1265
+ importNewDetected: "new to create",
999
1266
  markRead: "Mark as read",
1000
1267
  settingsTitle: "Site Settings",
1001
1268
  entries: "entries"
@@ -1066,13 +1333,13 @@ function toDayjsTime(value) {
1066
1333
  const isPm = match12[3].toLowerCase().startsWith("p");
1067
1334
  if (isPm && h < 12) h += 12;
1068
1335
  if (!isPm && h === 12) h = 0;
1069
- return (0, import_dayjs.default)().hour(h).minute(m).second(0).millisecond(0);
1336
+ return (0, import_dayjs2.default)().hour(h).minute(m).second(0).millisecond(0);
1070
1337
  }
1071
1338
  const match24 = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(str);
1072
1339
  if (match24) {
1073
- return (0, import_dayjs.default)().hour(Number(match24[1])).minute(Number(match24[2])).second(0).millisecond(0);
1340
+ return (0, import_dayjs2.default)().hour(Number(match24[1])).minute(Number(match24[2])).second(0).millisecond(0);
1074
1341
  }
1075
- const parsed = (0, import_dayjs.default)(str, ["h:mm a", "h:mm A", "hh:mm a", "hh:mm A", "HH:mm"]);
1342
+ const parsed = (0, import_dayjs2.default)(str, ["h:mm a", "h:mm A", "hh:mm a", "hh:mm A", "HH:mm"]);
1076
1343
  return parsed.isValid() ? parsed : null;
1077
1344
  }
1078
1345
  function toStoredTime(value) {
@@ -2452,37 +2719,37 @@ function CollectionsSection() {
2452
2719
  });
2453
2720
  }, [ctx.adapter, colIds, ctx.collectionChangedAt]);
2454
2721
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex flex-col md:flex-row h-full bg-slate-50", children: [
2455
- /* @__PURE__ */ (0, import_jsx_runtime5.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: [
2456
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "mb-3 px-2 text-xs font-bold uppercase tracking-widest text-slate-500", children: "Collections" }),
2457
- /* @__PURE__ */ (0, import_jsx_runtime5.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: [
2722
+ /* @__PURE__ */ (0, import_jsx_runtime5.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: [
2723
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "hidden md:block mb-3 px-2 text-xs font-bold uppercase tracking-widest text-slate-500", children: "Collections" }),
2724
+ /* @__PURE__ */ (0, import_jsx_runtime5.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: [
2458
2725
  collections.map((c, idx) => {
2459
2726
  if (c.isSeparator) {
2460
2727
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2461
2728
  "li",
2462
2729
  {
2463
- className: "my-3 border-t border-slate-200/80 pt-2 px-1 list-none",
2464
- children: c.name && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "text-[10px] font-bold uppercase tracking-wider text-slate-400", children: c.name })
2730
+ 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",
2731
+ children: c.name && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "hidden md:block text-[10px] font-bold uppercase tracking-wider text-slate-400", children: c.name })
2465
2732
  },
2466
2733
  c.id || `sep-${idx}`
2467
2734
  );
2468
2735
  }
2469
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("li", { className: "shrink-0 min-w-[140px] md:w-full md:min-w-0", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
2736
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("li", { className: "shrink-0 md:w-full md:min-w-0", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
2470
2737
  "button",
2471
2738
  {
2472
2739
  onClick: () => setSelected(c),
2473
- 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"}`,
2740
+ 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"}`,
2474
2741
  children: [
2475
2742
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2476
2743
  "div",
2477
2744
  {
2478
- className: selected?.id === c.id ? "text-slate-900" : "text-slate-700",
2745
+ className: selected?.id === c.id ? "text-slate-900 font-bold" : "text-slate-700 font-medium",
2479
2746
  children: c.name
2480
2747
  }
2481
2748
  ),
2482
2749
  /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
2483
2750
  "div",
2484
2751
  {
2485
- className: `text-xs mt-0.5 ${selected?.id === c.id ? "text-indigo-500" : "text-slate-400"}`,
2752
+ className: `text-[10px] md:text-xs mt-0.5 ${selected?.id === c.id ? "text-indigo-600 font-medium" : "text-slate-400"}`,
2486
2753
  children: [
2487
2754
  counts[c.id] ?? 0,
2488
2755
  " items"
@@ -2496,7 +2763,7 @@ function CollectionsSection() {
2496
2763
  collections.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime5.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." })
2497
2764
  ] })
2498
2765
  ] }),
2499
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex-1 overflow-auto p-4 md:p-8 relative", children: [
2766
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex-1 overflow-auto p-2 sm:p-4 md:p-8 relative", children: [
2500
2767
  /* @__PURE__ */ (0, import_jsx_runtime5.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" }),
2501
2768
  selected ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(CollectionEditor, { collection: selected }, selected.id) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "grid h-full place-items-center text-sm text-slate-500", children: "Select a collection to manage its entries." })
2502
2769
  ] })
@@ -2512,6 +2779,16 @@ function CollectionEditor({ collection }) {
2512
2779
  const [duplicateErrors, setDuplicateErrors] = (0, import_react5.useState)({});
2513
2780
  const [isCreatingManual, setIsCreatingManual] = (0, import_react5.useState)(false);
2514
2781
  const [isViewingDetail, setIsViewingDetail] = (0, import_react5.useState)(false);
2782
+ const [customViewingRecord, setCustomViewingRecord] = (0, import_react5.useState)(null);
2783
+ const [isCustomEditing, setIsCustomEditing] = (0, import_react5.useState)(false);
2784
+ const [customActiveView, setCustomActiveView] = (0, import_react5.useState)(null);
2785
+ const [isCustomCreating, setIsCustomCreating] = (0, import_react5.useState)(false);
2786
+ (0, import_react5.useEffect)(() => {
2787
+ setCustomViewingRecord(null);
2788
+ setIsCustomEditing(false);
2789
+ setCustomActiveView(null);
2790
+ setIsCustomCreating(false);
2791
+ }, [collection.id]);
2515
2792
  const [saving, setSaving] = (0, import_react5.useState)(false);
2516
2793
  const [deletingId, setDeletingId] = (0, import_react5.useState)(null);
2517
2794
  const [loadingEntries, setLoadingEntries] = (0, import_react5.useState)(true);
@@ -2521,13 +2798,74 @@ function CollectionEditor({ collection }) {
2521
2798
  const [filters, setFilters] = (0, import_react5.useState)({});
2522
2799
  const [page, setPage] = (0, import_react5.useState)(1);
2523
2800
  const itemsPerPage = 10;
2801
+ const dateFields = (0, import_react5.useMemo)(() => {
2802
+ const list = [];
2803
+ (collection.fields || []).forEach((f) => {
2804
+ if (f.type === "date" || f.type === "datetime" || f.id === "fecha" || f.id.toLowerCase().includes("fecha") || f.id.toLowerCase().includes("date")) {
2805
+ list.push({ id: f.id, label: f.label || f.id });
2806
+ }
2807
+ });
2808
+ const hasCreatedAt = entries.some((e) => e._createdAt);
2809
+ if (hasCreatedAt && !list.some((f) => f.id === "_createdAt")) {
2810
+ list.push({ id: "_createdAt", label: "Fecha de creaci\xF3n (_createdAt)" });
2811
+ }
2812
+ return list;
2813
+ }, [collection.fields, entries]);
2814
+ const [isExportModalOpen, setIsExportModalOpen] = (0, import_react5.useState)(false);
2815
+ const [exportMode, setExportMode] = (0, import_react5.useState)("all");
2816
+ const [exportDateField, setExportDateField] = (0, import_react5.useState)("");
2817
+ const [exportDateRange, setExportDateRange] = (0, import_react5.useState)(null);
2818
+ (0, import_react5.useEffect)(() => {
2819
+ if (dateFields.length > 0 && !exportDateField) {
2820
+ setExportDateField(dateFields[0].id);
2821
+ }
2822
+ }, [dateFields, exportDateField]);
2823
+ const exportTargetEntries = (0, import_react5.useMemo)(() => {
2824
+ if (exportMode === "all" || !exportDateField || !exportDateRange || !exportDateRange[0] || !exportDateRange[1]) {
2825
+ return entries;
2826
+ }
2827
+ return filterEntriesByDateRange(
2828
+ entries,
2829
+ exportDateField,
2830
+ exportDateRange[0].format("YYYY-MM-DD"),
2831
+ exportDateRange[1].format("YYYY-MM-DD")
2832
+ );
2833
+ }, [entries, exportMode, exportDateField, exportDateRange]);
2834
+ const [isImportModalOpen, setIsImportModalOpen] = (0, import_react5.useState)(false);
2835
+ const [importFile, setImportFile] = (0, import_react5.useState)(null);
2836
+ const [importResult, setImportResult] = (0, import_react5.useState)(null);
2837
+ const [isParsingImport, setIsParsingImport] = (0, import_react5.useState)(false);
2838
+ const [isImporting, setIsImporting] = (0, import_react5.useState)(false);
2839
+ const [importExistingAction, setImportExistingAction] = (0, import_react5.useState)("omit");
2840
+ const [importProgress, setImportProgress] = (0, import_react5.useState)({ current: 0, total: 0 });
2841
+ const fileInputRef = (0, import_react5.useRef)(null);
2524
2842
  const load = (0, import_react5.useCallback)(() => {
2525
2843
  setLoadingEntries(true);
2526
2844
  ctx.adapter.listEntries(collection.id).then((res) => {
2527
2845
  const sorted = [...res].sort((a, b) => {
2528
- const orderA = Number(a.order) || 0;
2529
- const orderB = Number(b.order) || 0;
2530
- return orderA - orderB;
2846
+ if (collection.defaultSort) {
2847
+ if (typeof collection.defaultSort === "function") {
2848
+ return collection.defaultSort(a, b);
2849
+ }
2850
+ const field = collection.defaultSort.field;
2851
+ const valA = a[field];
2852
+ const valB = b[field];
2853
+ const dir = collection.defaultSort.direction === "desc" ? -1 : 1;
2854
+ if (valA === valB) return 0;
2855
+ if (valA === void 0 || valA === null) return 1;
2856
+ if (valB === void 0 || valB === null) return -1;
2857
+ if (typeof valA === "number" && typeof valB === "number") {
2858
+ return (valA - valB) * dir;
2859
+ }
2860
+ return String(valA).localeCompare(String(valB)) * dir;
2861
+ }
2862
+ const hasOrderField = collection.fields.some((f) => f.id === "order");
2863
+ if (hasOrderField) {
2864
+ const orderA = Number(a.order) || 0;
2865
+ const orderB = Number(b.order) || 0;
2866
+ if (orderA !== orderB) return orderA - orderB;
2867
+ }
2868
+ return 0;
2531
2869
  });
2532
2870
  setEntries(sorted);
2533
2871
  setLoadingEntries(false);
@@ -2536,7 +2874,111 @@ function CollectionEditor({ collection }) {
2536
2874
  (0, import_react5.useEffect)(() => {
2537
2875
  load();
2538
2876
  }, [load]);
2877
+ const handleOpenExportModal = () => {
2878
+ if (dateFields.length === 0) {
2879
+ try {
2880
+ exportCollectionToExcel(collection, entries);
2881
+ message.success(t.exportSuccess);
2882
+ } catch (err) {
2883
+ console.error("Error exportando a Excel:", err);
2884
+ message.error("No se pudo exportar a Excel.");
2885
+ }
2886
+ return;
2887
+ }
2888
+ setIsExportModalOpen(true);
2889
+ };
2890
+ const handleConfirmExport = () => {
2891
+ try {
2892
+ let suffix = "";
2893
+ if (exportMode === "byDate" && exportDateRange?.[0] && exportDateRange?.[1]) {
2894
+ suffix = `${(collection.name || collection.id).toLowerCase()}_${exportDateRange[0].format("YYYYMMDD")}_al_${exportDateRange[1].format("YYYYMMDD")}`;
2895
+ }
2896
+ exportCollectionToExcel(collection, exportTargetEntries, suffix);
2897
+ message.success(t.exportSuccess);
2898
+ setIsExportModalOpen(false);
2899
+ } catch (err) {
2900
+ console.error("Error exportando a Excel:", err);
2901
+ message.error("No se pudo exportar a Excel.");
2902
+ }
2903
+ };
2904
+ const handleProcessImportFile = async (file) => {
2905
+ setIsParsingImport(true);
2906
+ setImportFile(file);
2907
+ try {
2908
+ const res = await parseExcelForCollection(file, collection, entries);
2909
+ setImportResult(res);
2910
+ if (res.errors.length > 0) {
2911
+ message.warning(res.errors[0]);
2912
+ }
2913
+ } catch (err) {
2914
+ console.error("Error parseando archivo Excel:", err);
2915
+ message.error(err?.message || "Error al leer el archivo Excel.");
2916
+ setImportResult(null);
2917
+ setImportFile(null);
2918
+ } finally {
2919
+ setIsParsingImport(false);
2920
+ }
2921
+ };
2922
+ const handleExecuteImport = async () => {
2923
+ if (!importResult || !importResult.records.length) return;
2924
+ setIsImporting(true);
2925
+ const total = importResult.records.length;
2926
+ setImportProgress({ current: 0, total });
2927
+ try {
2928
+ let createdCount = 0;
2929
+ let updatedCount = 0;
2930
+ let omittedCount = 0;
2931
+ for (let i = 0; i < total; i++) {
2932
+ const item = { ...importResult.records[i] };
2933
+ const existing = findExistingEntry(item, entries, collection);
2934
+ if (existing) {
2935
+ if (importExistingAction === "omit") {
2936
+ omittedCount++;
2937
+ } else {
2938
+ const merged = { ...existing, ...item, id: existing.id };
2939
+ if (existing._id) merged._id = existing._id;
2940
+ await ctx.adapter.putEntry(collection.id, merged);
2941
+ updatedCount++;
2942
+ }
2943
+ } else {
2944
+ await ctx.adapter.putEntry(collection.id, item);
2945
+ createdCount++;
2946
+ }
2947
+ setImportProgress({ current: i + 1, total });
2948
+ }
2949
+ if (createdCount > 0 && omittedCount > 0) {
2950
+ message.success(
2951
+ `Se importaron ${createdCount} registros nuevos. Se omitieron ${omittedCount} registros ya existentes.`
2952
+ );
2953
+ } else if (createdCount > 0 && updatedCount > 0) {
2954
+ message.success(
2955
+ `Se crearon ${createdCount} registros y se actualizaron ${updatedCount} existentes.`
2956
+ );
2957
+ } else if (createdCount > 0) {
2958
+ message.success(`Se importaron ${createdCount} registros exitosamente.`);
2959
+ } else if (omittedCount > 0) {
2960
+ message.info(
2961
+ `Los ${omittedCount} registros ya se encontraban creados. No se duplic\xF3 ning\xFAn dato.`
2962
+ );
2963
+ } else if (updatedCount > 0) {
2964
+ message.success(`Se actualizaron ${updatedCount} registros existentes.`);
2965
+ }
2966
+ load();
2967
+ setIsImportModalOpen(false);
2968
+ setImportResult(null);
2969
+ setImportFile(null);
2970
+ } catch (err) {
2971
+ console.error("Error importando registros:", err);
2972
+ message.error("Ocurri\xF3 un error al guardar los registros importados.");
2973
+ } finally {
2974
+ setIsImporting(false);
2975
+ }
2976
+ };
2539
2977
  const startNew = () => {
2978
+ if (collection.customCreateView) {
2979
+ setIsCustomCreating(true);
2980
+ return;
2981
+ }
2540
2982
  setIsCreatingManual(true);
2541
2983
  setOriginalId(null);
2542
2984
  setDuplicateErrors({});
@@ -2591,18 +3033,35 @@ function CollectionEditor({ collection }) {
2591
3033
  let val = String(finalEditing[sourceField] || finalEditing.id || "");
2592
3034
  val = val.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)+/g, "");
2593
3035
  finalEditing[f.id] = val;
2594
- } else if (f.type === "list") {
3036
+ } else if (f.type === "list" || f.multiple) {
2595
3037
  if (Array.isArray(finalEditing[f.id])) {
2596
3038
  finalEditing[f.id] = finalEditing[f.id].filter(
2597
3039
  (item) => item !== void 0 && item !== null && String(item).trim() !== ""
2598
3040
  );
2599
- } else if (typeof finalEditing[f.id] === "string") {
2600
- finalEditing[f.id] = String(finalEditing[f.id]).split("\n").map((s) => s.trim()).filter(Boolean);
3041
+ } else if (typeof finalEditing[f.id] === "string" && finalEditing[f.id]) {
3042
+ finalEditing[f.id] = [String(finalEditing[f.id]).trim()];
2601
3043
  }
2602
3044
  }
2603
3045
  });
2604
- const isClientOrEmployee = collection.id === "clients" || collection.id === "employees";
2605
- const uniqueFields = collection.fields.filter((f) => f.unique || isClientOrEmployee && f.id === "id");
3046
+ for (const f of collection.fields) {
3047
+ if (f.required) {
3048
+ if (isCreatingEntry && f.hideOnCreate) continue;
3049
+ if (f.dependsOn && finalEditing[f.dependsOn.field] !== void 0) {
3050
+ const targetVal = f.dependsOn.value;
3051
+ const currentVal = finalEditing[f.dependsOn.field];
3052
+ const match = Array.isArray(targetVal) ? targetVal.includes(currentVal) : currentVal === targetVal;
3053
+ if (!match) continue;
3054
+ }
3055
+ const rawVal = finalEditing[f.id];
3056
+ const isEmpty = rawVal === void 0 || rawVal === null || typeof rawVal === "string" && rawVal.trim() === "" || Array.isArray(rawVal) && rawVal.length === 0;
3057
+ if (isEmpty) {
3058
+ message.error(`El campo "${f.label || f.id}" es obligatorio.`);
3059
+ setSaving(false);
3060
+ return;
3061
+ }
3062
+ }
3063
+ }
3064
+ const uniqueFields = collection.fields.filter((f) => f.unique);
2606
3065
  for (const f of uniqueFields) {
2607
3066
  const val = String(finalEditing[f.id] || "").trim().toLowerCase();
2608
3067
  if (!val) {
@@ -2635,6 +3094,18 @@ function CollectionEditor({ collection }) {
2635
3094
  await ctx.adapter.putEntry(collection.id, finalEditing);
2636
3095
  message.success(originalId ? "Guardado correctamente" : "Creado correctamente");
2637
3096
  ctx.notifyCollectionChanged();
3097
+ setEntries((prev) => {
3098
+ const next = [...prev];
3099
+ const matchIdx = next.findIndex(
3100
+ (e) => originalId && String(e.id || "").trim().toLowerCase() === String(originalId).trim().toLowerCase() || String(e.id || "").trim().toLowerCase() === String(finalEditing.id || "").trim().toLowerCase()
3101
+ );
3102
+ if (matchIdx >= 0) {
3103
+ next[matchIdx] = { ...next[matchIdx], ...finalEditing };
3104
+ } else {
3105
+ next.unshift(finalEditing);
3106
+ }
3107
+ return next;
3108
+ });
2638
3109
  setEditing(null);
2639
3110
  setOriginalId(null);
2640
3111
  setIsCreatingManual(false);
@@ -2648,6 +3119,9 @@ function CollectionEditor({ collection }) {
2648
3119
  setDeletingId(id);
2649
3120
  try {
2650
3121
  await ctx.adapter.deleteEntry(collection.id, id);
3122
+ setEntries(
3123
+ (prev) => prev.filter((e) => String(e.id || "").trim().toLowerCase() !== String(id).trim().toLowerCase())
3124
+ );
2651
3125
  ctx.notifyCollectionChanged();
2652
3126
  load();
2653
3127
  } finally {
@@ -2691,23 +3165,80 @@ function CollectionEditor({ collection }) {
2691
3165
  };
2692
3166
  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);
2693
3167
  const isCreatingEntry = isCreatingManual || (editing ? !entries.some((entry) => entry.id && entry.id === editing.id || entry._id && entry._id === (editing._id || editing.id)) : false);
3168
+ if (isCustomCreating && collection.customCreateView) {
3169
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "w-full", children: collection.customCreateView({
3170
+ onBack: () => setIsCustomCreating(false),
3171
+ reload: () => {
3172
+ load();
3173
+ }
3174
+ }) });
3175
+ }
3176
+ if (customActiveView) {
3177
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "w-full", children: customActiveView({
3178
+ onBack: () => setCustomActiveView(null),
3179
+ reload: () => {
3180
+ load();
3181
+ }
3182
+ }) });
3183
+ }
3184
+ if (customViewingRecord && (collection.customDetailView || collection.renderCustomDetail || collection.customEditView)) {
3185
+ const renderFn = isCustomEditing && collection.customEditView ? collection.customEditView : collection.customDetailView || collection.renderCustomDetail;
3186
+ if (renderFn) {
3187
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "w-full", children: renderFn({
3188
+ record: customViewingRecord,
3189
+ isEditing: isCustomEditing,
3190
+ onBack: () => {
3191
+ setCustomViewingRecord(null);
3192
+ setIsCustomEditing(false);
3193
+ },
3194
+ reload: () => {
3195
+ load();
3196
+ }
3197
+ }) });
3198
+ }
3199
+ }
2694
3200
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "mx-auto max-w-5xl", children: [
2695
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "mb-8 flex items-center justify-between", children: [
3201
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "mb-8 flex flex-col sm:flex-row sm:items-center justify-between gap-4", children: [
2696
3202
  /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
2697
3203
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("h2", { className: "text-2xl font-bold text-slate-900 tracking-tight", children: collection.name }),
2698
3204
  collection.description && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "text-sm text-slate-500 mt-1", children: collection.description })
2699
3205
  ] }),
2700
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2701
- import_antd.Button,
2702
- {
2703
- type: "primary",
2704
- size: "large",
2705
- icon: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.Plus, { className: "h-4 w-4" }),
2706
- onClick: startNew,
2707
- className: "rounded-xl font-bold shadow-sm",
2708
- children: t.newEntry
2709
- }
2710
- )
3206
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex flex-wrap items-center gap-2", children: [
3207
+ !collection.disableExport && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3208
+ import_antd.Button,
3209
+ {
3210
+ size: "large",
3211
+ icon: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.FileDown, { className: "h-4 w-4 text-emerald-600" }),
3212
+ onClick: handleOpenExportModal,
3213
+ disabled: loadingEntries || entries.length === 0,
3214
+ className: "rounded-xl font-medium border-slate-200 hover:border-emerald-500 hover:text-emerald-600 shadow-sm",
3215
+ title: "Descargar registros en formato Excel (soporta filtro por fechas)",
3216
+ children: t.exportExcel
3217
+ }
3218
+ ),
3219
+ !collection.disableImport && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3220
+ import_antd.Button,
3221
+ {
3222
+ size: "large",
3223
+ icon: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.FileUp, { className: "h-4 w-4 text-sky-600" }),
3224
+ onClick: () => setIsImportModalOpen(true),
3225
+ className: "rounded-xl font-medium border-slate-200 hover:border-sky-500 hover:text-sky-600 shadow-sm",
3226
+ title: "Cargar registros desde un archivo Excel o CSV",
3227
+ children: t.importExcel
3228
+ }
3229
+ ),
3230
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3231
+ import_antd.Button,
3232
+ {
3233
+ type: "primary",
3234
+ size: "large",
3235
+ icon: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.Plus, { className: "h-4 w-4" }),
3236
+ onClick: startNew,
3237
+ className: "rounded-xl font-bold shadow-sm",
3238
+ children: t.newEntry
3239
+ }
3240
+ )
3241
+ ] })
2711
3242
  ] }),
2712
3243
  !editing && (collection.searchBy?.length || collection.filterBy?.length) && /* @__PURE__ */ (0, import_jsx_runtime5.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: [
2713
3244
  collection.searchBy?.length ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "relative flex-1 min-w-[220px]", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
@@ -2715,7 +3246,10 @@ function CollectionEditor({ collection }) {
2715
3246
  {
2716
3247
  size: "large",
2717
3248
  prefix: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.Search, { className: "h-4 w-4 text-slate-400" }),
2718
- placeholder: `Buscar por ${collection.searchBy.map((s) => s === "numero" ? "n\xFAmero" : s === "clienteNombre" ? "cliente" : s === "clienteId" ? "identificaci\xF3n" : s === "fecha" ? "fecha" : s).join(", ")}...`,
3249
+ placeholder: `Buscar por ${collection.searchBy.map((s) => {
3250
+ const f = collection.fields.find((field) => field.id === s);
3251
+ return f?.label ? f.label.toLowerCase() : s;
3252
+ }).join(", ")}...`,
2719
3253
  value: search,
2720
3254
  allowClear: true,
2721
3255
  onChange: (e) => {
@@ -2729,7 +3263,7 @@ function CollectionEditor({ collection }) {
2729
3263
  const fieldDef = collection.fields.find((cf) => cf.id === f);
2730
3264
  if (!fieldDef) return null;
2731
3265
  if (fieldDef.type === "date") {
2732
- const dateVal = filters[f] ? (0, import_dayjs.default)(filters[f], ["YYYY/MM/DD", "YYYY-MM-DD", "YYYY-M-D"]).isValid() ? (0, import_dayjs.default)(filters[f], ["YYYY/MM/DD", "YYYY-MM-DD", "YYYY-M-D"]) : null : null;
3266
+ const dateVal = filters[f] ? (0, import_dayjs2.default)(filters[f], ["YYYY/MM/DD", "YYYY-MM-DD", "YYYY-M-D"]).isValid() ? (0, import_dayjs2.default)(filters[f], ["YYYY/MM/DD", "YYYY-MM-DD", "YYYY-M-D"]) : null : null;
2733
3267
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "min-w-[180px]", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2734
3268
  import_antd.DatePicker,
2735
3269
  {
@@ -2845,7 +3379,7 @@ function CollectionEditor({ collection }) {
2845
3379
  }
2846
3380
  return true;
2847
3381
  }).map((f) => {
2848
- 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";
3382
+ 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";
2849
3383
  const colSpanClass = isFullWidth ? "lg:col-span-2 col-span-1" : "col-span-1";
2850
3384
  if (isViewingDetail) {
2851
3385
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: `block ${colSpanClass}`, children: [
@@ -2855,7 +3389,9 @@ function CollectionEditor({ collection }) {
2855
3389
  record: editing,
2856
3390
  onChange: () => {
2857
3391
  },
2858
- isCreatingEntry: false
3392
+ isCreatingEntry: false,
3393
+ isViewingDetail: true,
3394
+ readOnly: true
2859
3395
  }) : f.type === "signature" ? editing[f.id] ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "rounded-xl border border-slate-200 bg-white p-3 flex items-center justify-center shadow-sm", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2860
3396
  "img",
2861
3397
  {
@@ -2863,14 +3399,14 @@ function CollectionEditor({ collection }) {
2863
3399
  alt: f.label,
2864
3400
  className: "h-28 w-auto max-w-full object-contain"
2865
3401
  }
2866
- ) }) : /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.jsx)("div", { className: "flex flex-wrap gap-1.5 pt-0.5", children: editing[f.id].map((item, idx) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3402
+ ) }) : /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.jsx)("div", { className: "flex flex-wrap gap-1.5 pt-0.5", children: editing[f.id].map((item, idx) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2867
3403
  "span",
2868
3404
  {
2869
- className: "rounded-full bg-slate-100 text-slate-700 px-3 py-1 text-xs font-medium border border-slate-200",
3405
+ className: "rounded-xl bg-slate-100 text-slate-700 px-3 py-1 text-xs font-medium border border-slate-200",
2870
3406
  children: String(item)
2871
3407
  },
2872
3408
  idx
2873
- )) }) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "text-xs text-slate-400 italic py-1", children: "Ninguno" }) : f.type === "link" ? Boolean(editing[f.id]) ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
3409
+ )) }) : typeof editing[f.id] === "string" && editing[f.id] ? /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.jsx)("p", { className: "text-xs text-slate-400 italic py-1", children: "Ninguno" }) : f.type === "link" ? Boolean(editing[f.id]) ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
2874
3410
  "a",
2875
3411
  {
2876
3412
  href: String(editing[f.id]),
@@ -2882,19 +3418,24 @@ function CollectionEditor({ collection }) {
2882
3418
  String(editing[f.id]).includes("maps") ? "Ver en Google Maps" : String(editing[f.id])
2883
3419
  ]
2884
3420
  }
2885
- ) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "text-xs text-slate-400 py-1 block", children: "\u2014" }) : f.type === "textarea" ? /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.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") })
3421
+ ) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "text-xs text-slate-400 py-1 block", children: "\u2014" }) : f.type === "textarea" ? /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.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") })
2886
3422
  ] }, f.id);
2887
3423
  }
2888
3424
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: `block ${colSpanClass}`, children: [
2889
3425
  /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { className: "text-xs font-bold text-slate-500 uppercase tracking-wide flex items-center justify-between mb-1.5", children: [
2890
- f.label,
3426
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { children: [
3427
+ f.label,
3428
+ (f.required || f.unique) && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "text-rose-500 ml-1 font-bold", title: "Campo obligatorio", children: "*" })
3429
+ ] }),
2891
3430
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "text-[10px] font-mono text-slate-300 bg-slate-50 px-1.5 py-0.5 rounded", children: f.type })
2892
3431
  ] }),
2893
3432
  f.customRender ? f.customRender({
2894
3433
  value: editing[f.id],
2895
3434
  record: editing,
2896
3435
  onChange: (val) => setEditing({ ...editing, [f.id]: val }),
2897
- isCreatingEntry
3436
+ isCreatingEntry,
3437
+ isViewingDetail: false,
3438
+ readOnly: false
2898
3439
  }) : f.type === "branch-settings" ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2899
3440
  BranchSettingsEditor,
2900
3441
  {
@@ -2928,7 +3469,7 @@ function CollectionEditor({ collection }) {
2928
3469
  import_antd.DatePicker,
2929
3470
  {
2930
3471
  size: "large",
2931
- value: editing[f.id] ? (0, import_dayjs.default)(String(editing[f.id])).isValid() ? (0, import_dayjs.default)(String(editing[f.id])) : null : null,
3472
+ value: editing[f.id] ? (0, import_dayjs2.default)(String(editing[f.id])).isValid() ? (0, import_dayjs2.default)(String(editing[f.id])) : null : null,
2932
3473
  onChange: (date, dateString) => setEditing({ ...editing, [f.id]: (Array.isArray(dateString) ? dateString[0] : dateString) || (date ? date.format("YYYY/MM/DD") : "") }),
2933
3474
  format: "YYYY/MM/DD",
2934
3475
  placeholder: `Seleccionar ${f.label.toLowerCase()}...`,
@@ -3028,21 +3569,8 @@ function CollectionEditor({ collection }) {
3028
3569
  value: editing[f.id],
3029
3570
  onChange: (val) => setEditing({ ...editing, [f.id]: val }),
3030
3571
  onSelectRecord: (rec) => {
3031
- if (f.id === "clienteId" && rec) {
3032
- setEditing((prev) => prev ? {
3033
- ...prev,
3034
- clienteId: rec.id || prev.clienteId,
3035
- clienteNombre: rec.nombre || rec.name || prev.clienteNombre,
3036
- ciudad: rec.ciudad || prev.ciudad,
3037
- direccion: rec.direccion || prev.direccion,
3038
- telefono: rec.telefono || prev.telefono
3039
- } : prev);
3040
- } else if (f.id === "empleadoId" && rec) {
3041
- setEditing((prev) => prev ? {
3042
- ...prev,
3043
- empleadoId: rec.id || prev.empleadoId,
3044
- empleadoNombre: rec.apellido ? `${rec.nombre || rec.name || ""} ${rec.apellido}`.trim() : rec.nombre || rec.name || prev.empleadoNombre
3045
- } : prev);
3572
+ if (f.onSelectRecord) {
3573
+ setEditing((prev) => prev ? { ...prev, ...f.onSelectRecord(rec, prev) } : prev);
3046
3574
  }
3047
3575
  }
3048
3576
  }
@@ -3298,63 +3826,61 @@ function CollectionEditor({ collection }) {
3298
3826
  ]
3299
3827
  }
3300
3828
  )
3301
- ] }) : f.type === "list" ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "space-y-3", children: [
3302
- (Array.isArray(editing[f.id]) ? editing[f.id] : typeof editing[f.id] === "string" ? String(editing[f.id]).split("\n").filter(Boolean) : []).map((item, idx) => {
3303
- const isFeatures = f.id === "features" || f.label.toLowerCase().includes("caracter\xEDstica") || f.label.toLowerCase().includes("beneficio");
3304
- const placeholder = isFeatures ? `Caracter\xEDstica o beneficio ${idx + 1}...` : `Entregable o punto clave ${idx + 1}...`;
3305
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex gap-2 items-center", children: [
3306
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { className: "text-xs font-mono font-bold text-slate-400 w-6 text-right shrink-0", children: [
3307
- idx + 1,
3308
- "."
3829
+ ] }) : f.type === "list" || f.multiple ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "space-y-3", children: (() => {
3830
+ const currentArr = Array.isArray(editing[f.id]) ? editing[f.id] : typeof editing[f.id] === "string" && editing[f.id] ? [editing[f.id]] : [""];
3831
+ const displayArr = currentArr.length > 0 ? currentArr : [""];
3832
+ const singularLabel = f.label.endsWith("es") ? f.label.slice(0, -2) : f.label.endsWith("s") ? f.label.slice(0, -1) : f.label;
3833
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "space-y-2.5", children: [
3834
+ displayArr.map((item, idx) => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex gap-2 items-center", children: [
3835
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { className: "text-xs font-mono font-bold text-slate-400 w-7 text-right shrink-0", children: [
3836
+ "#",
3837
+ idx + 1
3309
3838
  ] }),
3310
3839
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3311
3840
  "input",
3312
3841
  {
3313
3842
  type: "text",
3314
3843
  value: String(item ?? ""),
3315
- placeholder,
3844
+ placeholder: `${singularLabel} #${idx + 1}...`,
3316
3845
  onChange: (e) => {
3317
- let arr = Array.isArray(editing[f.id]) ? [...editing[f.id]] : typeof editing[f.id] === "string" ? String(editing[f.id]).split("\n").filter(Boolean) : [];
3846
+ const arr = [...displayArr];
3318
3847
  arr[idx] = e.target.value;
3319
3848
  setEditing({ ...editing, [f.id]: arr });
3320
3849
  },
3321
3850
  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"
3322
3851
  }
3323
3852
  ),
3324
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3853
+ displayArr.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3325
3854
  "button",
3326
3855
  {
3327
3856
  type: "button",
3328
3857
  onClick: () => {
3329
- let arr = Array.isArray(editing[f.id]) ? [...editing[f.id]] : typeof editing[f.id] === "string" ? String(editing[f.id]).split("\n").filter(Boolean) : [];
3330
- arr.splice(idx, 1);
3331
- setEditing({ ...editing, [f.id]: arr });
3858
+ const arr = displayArr.filter((_, i) => i !== idx);
3859
+ setEditing({ ...editing, [f.id]: arr.length > 0 ? arr : [""] });
3332
3860
  },
3333
- className: "p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors cursor-pointer",
3861
+ className: "p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors cursor-pointer shrink-0",
3334
3862
  title: "Eliminar elemento",
3335
3863
  children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.Trash2, { className: "w-4 h-4" })
3336
3864
  }
3337
3865
  )
3338
- ] }, idx);
3339
- }),
3340
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
3341
- "button",
3342
- {
3343
- type: "button",
3344
- onClick: () => {
3345
- let arr = Array.isArray(editing[f.id]) ? [...editing[f.id]] : typeof editing[f.id] === "string" ? String(editing[f.id]).split("\n").filter(Boolean) : [];
3346
- arr.push("");
3347
- setEditing({ ...editing, [f.id]: arr });
3348
- },
3349
- 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",
3350
- children: [
3351
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.Plus, { className: "w-3.5 h-3.5" }),
3352
- " ",
3353
- f.id === "features" || f.label.toLowerCase().includes("caracter\xEDstica") ? "Agregar caracter\xEDstica uno a uno" : "Agregar entregable / punto uno a uno"
3354
- ]
3355
- }
3356
- )
3357
- ] }) : f.type === "link" ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex gap-2 items-center", children: [
3866
+ ] }, idx)),
3867
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
3868
+ "button",
3869
+ {
3870
+ type: "button",
3871
+ onClick: () => {
3872
+ setEditing({ ...editing, [f.id]: [...displayArr, ""] });
3873
+ },
3874
+ 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",
3875
+ children: [
3876
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.Plus, { className: "w-3.5 h-3.5" }),
3877
+ " Agregar ",
3878
+ singularLabel.toLowerCase()
3879
+ ]
3880
+ }
3881
+ )
3882
+ ] });
3883
+ })() }) : f.type === "link" ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex gap-2 items-center", children: [
3358
3884
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3359
3885
  import_antd.Input,
3360
3886
  {
@@ -3401,7 +3927,7 @@ function CollectionEditor({ collection }) {
3401
3927
  }
3402
3928
  },
3403
3929
  onBlur: (e) => {
3404
- const isUniqueField = f.unique || (collection.id === "clients" || collection.id === "employees") && f.id === "id";
3930
+ const isUniqueField = Boolean(f.unique);
3405
3931
  if (isUniqueField) {
3406
3932
  const val = (e.target.value || "").trim().toLowerCase();
3407
3933
  if (val) {
@@ -3483,6 +4009,304 @@ function CollectionEditor({ collection }) {
3483
4009
  ] }) })
3484
4010
  }
3485
4011
  ),
4012
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4013
+ import_antd.Modal,
4014
+ {
4015
+ open: isExportModalOpen,
4016
+ title: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex items-center gap-2 text-slate-900 font-bold text-lg", children: [
4017
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.FileDown, { className: "h-5 w-5 text-emerald-600" }),
4018
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { children: [
4019
+ t.exportModalTitle,
4020
+ " - ",
4021
+ collection.name
4022
+ ] })
4023
+ ] }),
4024
+ onCancel: () => setIsExportModalOpen(false),
4025
+ footer: null,
4026
+ centered: true,
4027
+ width: "min(560px, calc(100vw - 32px))",
4028
+ mask: { blur: true },
4029
+ children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "py-2 space-y-4", children: [
4030
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "text-xs text-slate-500", children: "Descarga los registros en formato Excel estructurado (.xlsx)." }),
4031
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4032
+ import_antd.Segmented,
4033
+ {
4034
+ size: "large",
4035
+ block: true,
4036
+ value: exportMode,
4037
+ onChange: (val) => setExportMode(val),
4038
+ options: [
4039
+ { label: `${t.exportAllRecords} (${entries.length})`, value: "all" },
4040
+ { label: t.exportFilterByDate, value: "byDate" }
4041
+ ]
4042
+ }
4043
+ ),
4044
+ exportMode === "byDate" && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "p-4 bg-slate-50 border border-slate-200 rounded-xl space-y-3 animate-in fade-in", children: [
4045
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "space-y-1", children: [
4046
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("label", { className: "text-xs font-semibold text-slate-600", children: [
4047
+ t.exportDateRangeLabel,
4048
+ ":"
4049
+ ] }),
4050
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4051
+ import_antd.DatePicker.RangePicker,
4052
+ {
4053
+ size: "large",
4054
+ className: "w-full rounded-xl",
4055
+ value: exportDateRange,
4056
+ onChange: (dates) => setExportDateRange(dates),
4057
+ presets: [
4058
+ { label: "Hoy", value: [(0, import_dayjs2.default)().startOf("day"), (0, import_dayjs2.default)().endOf("day")] },
4059
+ { label: "Esta semana", value: [(0, import_dayjs2.default)().startOf("week"), (0, import_dayjs2.default)().endOf("week")] },
4060
+ { label: "Este mes", value: [(0, import_dayjs2.default)().startOf("month"), (0, import_dayjs2.default)().endOf("month")] },
4061
+ { label: "\xDAltimos 30 d\xEDas", value: [(0, import_dayjs2.default)().subtract(30, "day"), (0, import_dayjs2.default)()] },
4062
+ { label: "Este a\xF1o", value: [(0, import_dayjs2.default)().startOf("year"), (0, import_dayjs2.default)().endOf("year")] }
4063
+ ]
4064
+ }
4065
+ )
4066
+ ] }),
4067
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "pt-1 flex items-center justify-between text-xs", children: [
4068
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "text-slate-500 font-medium", children: "Registros coincidentes:" }),
4069
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
4070
+ "span",
4071
+ {
4072
+ className: `font-bold ${exportTargetEntries.length > 0 ? "text-emerald-600" : "text-amber-600"}`,
4073
+ children: [
4074
+ exportTargetEntries.length,
4075
+ " de ",
4076
+ entries.length,
4077
+ " registros"
4078
+ ]
4079
+ }
4080
+ )
4081
+ ] })
4082
+ ] }),
4083
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex justify-end gap-2 pt-2", children: [
4084
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_antd.Button, { size: "large", onClick: () => setIsExportModalOpen(false), children: t.cancel }),
4085
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
4086
+ import_antd.Button,
4087
+ {
4088
+ type: "primary",
4089
+ size: "large",
4090
+ icon: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.FileDown, { className: "h-4 w-4" }),
4091
+ onClick: handleConfirmExport,
4092
+ disabled: exportTargetEntries.length === 0,
4093
+ className: "rounded-xl font-bold bg-emerald-600 hover:bg-emerald-500",
4094
+ children: [
4095
+ t.exportDownloadBtn,
4096
+ " (",
4097
+ exportTargetEntries.length,
4098
+ ")"
4099
+ ]
4100
+ }
4101
+ )
4102
+ ] })
4103
+ ] })
4104
+ }
4105
+ ),
4106
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4107
+ import_antd.Modal,
4108
+ {
4109
+ open: isImportModalOpen,
4110
+ title: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex items-center gap-2 text-slate-900 font-bold text-lg", children: [
4111
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.FileSpreadsheet, { className: "h-5 w-5 text-emerald-600" }),
4112
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { children: [
4113
+ t.importModalTitle,
4114
+ " - ",
4115
+ collection.name
4116
+ ] })
4117
+ ] }),
4118
+ onCancel: () => {
4119
+ if (!isImporting) {
4120
+ setIsImportModalOpen(false);
4121
+ setImportResult(null);
4122
+ setImportFile(null);
4123
+ }
4124
+ },
4125
+ footer: null,
4126
+ centered: true,
4127
+ width: "min(800px, calc(100vw - 32px))",
4128
+ mask: { blur: true },
4129
+ children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "py-2 space-y-4", children: [
4130
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "text-xs text-slate-500", children: t.importModalDesc }),
4131
+ !importResult ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
4132
+ "div",
4133
+ {
4134
+ onDragOver: (e) => {
4135
+ e.preventDefault();
4136
+ e.stopPropagation();
4137
+ },
4138
+ onDrop: (e) => {
4139
+ e.preventDefault();
4140
+ e.stopPropagation();
4141
+ const file = e.dataTransfer.files?.[0];
4142
+ if (file) handleProcessImportFile(file);
4143
+ },
4144
+ onClick: () => fileInputRef.current?.click(),
4145
+ 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",
4146
+ children: [
4147
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4148
+ "input",
4149
+ {
4150
+ ref: fileInputRef,
4151
+ type: "file",
4152
+ accept: ".xlsx,.xls,.csv",
4153
+ className: "hidden",
4154
+ onChange: (e) => {
4155
+ const file = e.target.files?.[0];
4156
+ if (file) handleProcessImportFile(file);
4157
+ }
4158
+ }
4159
+ ),
4160
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "size-14 rounded-full bg-emerald-100 flex items-center justify-center text-emerald-600 shadow-sm", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.FileSpreadsheet, { className: "size-7" }) }),
4161
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
4162
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "font-semibold text-sm text-slate-700", children: t.importDropzone }),
4163
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "text-xs text-slate-400 mt-1", children: t.importDropzoneSub })
4164
+ ] }),
4165
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_antd.Button, { size: "middle", loading: isParsingImport, className: "mt-2 rounded-lg font-medium", children: isParsingImport ? "Leyendo archivo..." : "Seleccionar archivo" })
4166
+ ]
4167
+ }
4168
+ ) : /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "space-y-4", children: [
4169
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex items-center justify-between p-3.5 bg-emerald-50/60 border border-emerald-200 rounded-xl", children: [
4170
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex items-center gap-3", children: [
4171
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "size-9 rounded-lg bg-emerald-100 text-emerald-700 flex items-center justify-center font-bold", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.FileSpreadsheet, { className: "size-5" }) }),
4172
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
4173
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "text-sm font-bold text-slate-900", children: importFile?.name }),
4174
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("p", { className: "text-xs text-emerald-700 font-medium", children: [
4175
+ importResult.totalRows,
4176
+ " registros encontrados en el archivo"
4177
+ ] })
4178
+ ] })
4179
+ ] }),
4180
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4181
+ import_antd.Button,
4182
+ {
4183
+ size: "small",
4184
+ onClick: () => {
4185
+ setImportResult(null);
4186
+ setImportFile(null);
4187
+ },
4188
+ disabled: isImporting,
4189
+ children: "Cambiar archivo"
4190
+ }
4191
+ )
4192
+ ] }),
4193
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex flex-wrap items-center gap-2 p-3 bg-slate-50 border border-slate-200 rounded-xl", children: [
4194
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "text-xs font-semibold text-slate-700", children: "Estado de los registros:" }),
4195
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_antd.Tag, { color: "green", className: "text-xs font-medium", children: [
4196
+ "\u2713 ",
4197
+ importResult.newRecordsCount,
4198
+ " ",
4199
+ t.importNewDetected
4200
+ ] }),
4201
+ importResult.existingRecordsCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_antd.Tag, { color: "gold", className: "text-xs font-medium", children: [
4202
+ "\u2139\uFE0F ",
4203
+ importResult.existingRecordsCount,
4204
+ " ",
4205
+ t.importExistingDetected
4206
+ ] })
4207
+ ] }),
4208
+ importResult.existingRecordsCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "p-3.5 bg-slate-50/90 rounded-xl border border-slate-200 space-y-2", children: [
4209
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "text-xs font-bold text-slate-700 block", children: t.importOverwritesWarning }),
4210
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
4211
+ import_antd.Radio.Group,
4212
+ {
4213
+ value: importExistingAction,
4214
+ onChange: (e) => setImportExistingAction(e.target.value),
4215
+ disabled: isImporting,
4216
+ className: "flex flex-col gap-2.5",
4217
+ children: [
4218
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_antd.Radio, { value: "omit", className: "text-xs text-slate-700", children: [
4219
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "font-semibold text-emerald-700 block", children: t.importExistingOmit }),
4220
+ /* @__PURE__ */ (0, import_jsx_runtime5.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." })
4221
+ ] }),
4222
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_antd.Radio, { value: "update", className: "text-xs text-slate-700", children: [
4223
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "font-semibold text-sky-700 block", children: t.importExistingUpdate }),
4224
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "text-[11px] text-slate-500 block", children: "Actualiza los campos de los registros ya existentes con los datos del archivo." })
4225
+ ] })
4226
+ ]
4227
+ }
4228
+ )
4229
+ ] }),
4230
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
4231
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { className: "text-xs font-bold text-slate-600 uppercase tracking-wider block mb-1.5", children: [
4232
+ "Campos reconocidos (",
4233
+ importResult.matchedFields.length,
4234
+ "):"
4235
+ ] }),
4236
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex flex-wrap gap-1.5", children: [
4237
+ importResult.matchedFields.map((m, idx) => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_antd.Tag, { color: "green", className: "text-xs py-0.5", children: [
4238
+ "\u2713 ",
4239
+ m.label
4240
+ ] }, idx)),
4241
+ importResult.unmatchedHeaders.map((u, idx) => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_antd.Tag, { color: "orange", className: "text-xs py-0.5", children: [
4242
+ "\u26A0\uFE0F ",
4243
+ u,
4244
+ " (omitido)"
4245
+ ] }, idx))
4246
+ ] })
4247
+ ] }),
4248
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
4249
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { className: "text-xs font-bold text-slate-600 uppercase tracking-wider block mb-1.5", children: [
4250
+ t.importPreviewTitle,
4251
+ " (",
4252
+ Math.min(5, importResult.samplePreview.length),
4253
+ " de ",
4254
+ importResult.totalRows,
4255
+ "):"
4256
+ ] }),
4257
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "overflow-x-auto border border-slate-200 rounded-xl max-h-48 text-xs", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("table", { className: "w-full text-left", children: [
4258
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("thead", { className: "bg-slate-100/80 text-slate-700 font-semibold border-b border-slate-200", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("tr", { children: importResult.matchedFields.slice(0, 6).map((m, idx) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("th", { className: "p-2 whitespace-nowrap", children: m.label }, idx)) }) }),
4259
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("tbody", { className: "divide-y divide-slate-100", children: importResult.samplePreview.map((row, rIdx) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("tr", { className: "hover:bg-slate-50/60", children: importResult.matchedFields.slice(0, 6).map((m, cIdx) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("td", { className: "p-2 whitespace-nowrap max-w-[160px] truncate text-slate-600", children: String(row[m.fieldId] ?? "") }, cIdx)) }, rIdx)) })
4260
+ ] }) })
4261
+ ] }),
4262
+ isImporting && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "space-y-1", children: [
4263
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex justify-between text-xs text-slate-600 font-medium", children: [
4264
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { children: t.importingProgress }),
4265
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { children: [
4266
+ importProgress.current,
4267
+ " / ",
4268
+ importProgress.total
4269
+ ] })
4270
+ ] }),
4271
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4272
+ import_antd.Progress,
4273
+ {
4274
+ percent: Math.round(importProgress.current / (importProgress.total || 1) * 100),
4275
+ status: "active"
4276
+ }
4277
+ )
4278
+ ] }),
4279
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex justify-end gap-2 pt-2", children: [
4280
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4281
+ import_antd.Button,
4282
+ {
4283
+ size: "large",
4284
+ onClick: () => setIsImportModalOpen(false),
4285
+ disabled: isImporting,
4286
+ children: t.cancel
4287
+ }
4288
+ ),
4289
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
4290
+ import_antd.Button,
4291
+ {
4292
+ type: "primary",
4293
+ size: "large",
4294
+ loading: isImporting,
4295
+ onClick: handleExecuteImport,
4296
+ className: "rounded-xl font-bold bg-emerald-600 hover:bg-emerald-500",
4297
+ children: [
4298
+ t.importConfirmBtn,
4299
+ " (",
4300
+ importExistingAction === "omit" && importResult.existingRecordsCount > 0 ? importResult.newRecordsCount : importResult.totalRows,
4301
+ ")"
4302
+ ]
4303
+ }
4304
+ )
4305
+ ] })
4306
+ ] })
4307
+ ] })
4308
+ }
4309
+ ),
3486
4310
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "overflow-x-auto rounded-2xl border border-slate-200 bg-white shadow-sm", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("table", { className: "w-full text-sm text-left", children: [
3487
4311
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("thead", { className: "bg-slate-50/80 border-b border-slate-200", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("tr", { children: [
3488
4312
  visibleFields.map((f) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("th", { className: "px-6 py-4 text-xs font-bold text-slate-500 uppercase tracking-wider", children: f.label }, f.id)),
@@ -3536,7 +4360,30 @@ function CollectionEditor({ collection }) {
3536
4360
  onDragEnd,
3537
4361
  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" : ""}`,
3538
4362
  children: [
3539
- visibleFields.map((f) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("td", { className: "px-6 py-4 text-slate-700 max-w-[200px] truncate", children: f.type === "branch-settings" ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(BranchSettingsSummary, { value: e[f.id] }) : f.type === "boolean" ? e[f.id] ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "inline-flex px-2 py-1 rounded bg-green-100 text-green-700 text-xs font-bold", children: "Yes" }) : /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.jsx)("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.jsx)("span", { className: "font-medium text-slate-800", children: String(e.clienteNombre) }) : e.empleadoNombre && f.id === "empleadoId" ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "font-medium text-slate-800", children: String(e.empleadoNombre) }) : /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.jsx)(import_antd.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__ */ (0, import_jsx_runtime5.jsxs)("span", { className: "font-semibold text-slate-800", children: [
4363
+ visibleFields.map((f) => /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.jsx)(BranchSettingsSummary, { value: e[f.id] }) : f.type === "boolean" ? e[f.id] ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "inline-flex px-2 py-1 rounded bg-green-100 text-green-700 text-xs font-bold", children: "Yes" }) : /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.jsx)("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.jsx)(
4364
+ "button",
4365
+ {
4366
+ type: "button",
4367
+ onClick: () => f.onCellClick(e[f.id], e),
4368
+ className: "font-medium text-indigo-600 hover:text-indigo-800 hover:underline cursor-pointer text-left truncate block max-w-full",
4369
+ children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(ReferenceTableCell, { collectionId: f.collection, entryId: e[f.id], displayField: f.displayField, valueField: f.valueField, multiple: f.multiple })
4370
+ }
4371
+ ) : /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex items-center gap-1", children: [
4372
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "truncate", children: String(e[f.id][0] || "") }),
4373
+ e[f.id].length > 1 && /* @__PURE__ */ (0, import_jsx_runtime5.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: [
4374
+ "+",
4375
+ e[f.id].length - 1,
4376
+ " m\xE1s"
4377
+ ] })
4378
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { children: String(e[f.id]) }) : f.onCellClick ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4379
+ "button",
4380
+ {
4381
+ type: "button",
4382
+ onClick: () => f.onCellClick(e[f.id], e),
4383
+ className: "font-medium text-indigo-600 hover:text-indigo-800 hover:underline cursor-pointer text-left truncate block w-full",
4384
+ children: String(e[f.id] ?? "")
4385
+ }
4386
+ ) : f.type === "signature" && e[f.id] ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_antd.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__ */ (0, import_jsx_runtime5.jsxs)("span", { className: "font-semibold text-slate-800", children: [
3540
4387
  "$ ",
3541
4388
  Number(e[f.id]).toLocaleString("es-CO")
3542
4389
  ] }) : /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.jsxs)(
@@ -3553,18 +4400,64 @@ function CollectionEditor({ collection }) {
3553
4400
  }
3554
4401
  ) : 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)),
3555
4402
  /* @__PURE__ */ (0, import_jsx_runtime5.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__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex items-center justify-end gap-1.5", children: [
3556
- collection.enableDetailView && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4403
+ collection.customRowActions && collection.customRowActions({
4404
+ record: e,
4405
+ openDetail: () => {
4406
+ if (collection.customDetailView || collection.renderCustomDetail) {
4407
+ setCustomViewingRecord(e);
4408
+ setIsCustomEditing(false);
4409
+ return;
4410
+ }
4411
+ if (collection.onViewRecord) {
4412
+ collection.onViewRecord(e);
4413
+ return;
4414
+ }
4415
+ setIsCreatingManual(false);
4416
+ setIsViewingDetail(true);
4417
+ setOriginalId(String(e.id || ""));
4418
+ setDuplicateErrors({});
4419
+ setEditing({ ...e });
4420
+ },
4421
+ openEdit: () => {
4422
+ if (collection.customEditView) {
4423
+ setCustomViewingRecord(e);
4424
+ setIsCustomEditing(true);
4425
+ return;
4426
+ }
4427
+ setIsCreatingManual(false);
4428
+ setIsViewingDetail(false);
4429
+ setOriginalId(String(e.id || ""));
4430
+ setDuplicateErrors({});
4431
+ setEditing({ ...e });
4432
+ },
4433
+ openCustomView: (renderFn) => {
4434
+ setCustomActiveView(() => renderFn);
4435
+ },
4436
+ reload: () => {
4437
+ load();
4438
+ }
4439
+ }),
4440
+ (collection.enableDetailView || collection.onViewRecord || collection.customDetailView || collection.renderCustomDetail) && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3557
4441
  "button",
3558
4442
  {
3559
4443
  onClick: () => {
4444
+ if (collection.customDetailView || collection.renderCustomDetail) {
4445
+ setCustomViewingRecord(e);
4446
+ setIsCustomEditing(false);
4447
+ return;
4448
+ }
4449
+ if (collection.onViewRecord) {
4450
+ collection.onViewRecord(e);
4451
+ return;
4452
+ }
3560
4453
  setIsCreatingManual(false);
3561
4454
  setIsViewingDetail(true);
3562
4455
  setOriginalId(String(e.id || ""));
3563
4456
  setDuplicateErrors({});
3564
4457
  setEditing({ ...e });
3565
4458
  },
3566
- className: "p-2 rounded-lg text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 transition-colors",
3567
- title: "Ver detalle",
4459
+ className: "p-2 rounded-lg text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 transition-colors cursor-pointer",
4460
+ title: collection.viewRecordTitle || "Ver detalle",
3568
4461
  children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.Eye, { className: "h-4 w-4" })
3569
4462
  }
3570
4463
  ),
@@ -3581,6 +4474,11 @@ function CollectionEditor({ collection }) {
3581
4474
  "button",
3582
4475
  {
3583
4476
  onClick: () => {
4477
+ if (collection.customEditView) {
4478
+ setCustomViewingRecord(e);
4479
+ setIsCustomEditing(true);
4480
+ return;
4481
+ }
3584
4482
  setIsCreatingManual(false);
3585
4483
  setIsViewingDetail(false);
3586
4484
  setOriginalId(String(e.id || ""));
@@ -3592,7 +4490,7 @@ function CollectionEditor({ collection }) {
3592
4490
  children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.Pencil, { className: "h-4 w-4" })
3593
4491
  }
3594
4492
  ),
3595
- !collection.disableDelete && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4493
+ !collection.disableDelete && !collection.hideDelete && (!collection.canDelete || collection.canDelete(e)) && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3596
4494
  "button",
3597
4495
  {
3598
4496
  onClick: () => remove(e.id),
@@ -5158,9 +6056,9 @@ function ReferenceSelect({
5158
6056
  displayField = "name",
5159
6057
  valueField = "name",
5160
6058
  fallbackOptions,
5161
- multiple = false,
6059
+ multiple: _multiple = false,
5162
6060
  searchable = false,
5163
- max,
6061
+ max: _max,
5164
6062
  value,
5165
6063
  onChange,
5166
6064
  onSelectRecord
@@ -5170,45 +6068,46 @@ function ReferenceSelect({
5170
6068
  const { message } = import_antd.App.useApp();
5171
6069
  const [options, setOptions] = (0, import_react5.useState)([]);
5172
6070
  const [loading, setLoading] = (0, import_react5.useState)(true);
5173
- const [clientModalOpen, setClientModalOpen] = (0, import_react5.useState)(false);
5174
- const [creatingClient, setCreatingClient] = (0, import_react5.useState)(false);
5175
- const [clientError, setClientError] = (0, import_react5.useState)("");
5176
- const [newClient, setNewClient] = (0, import_react5.useState)({
5177
- tipo: "Persona",
5178
- tipoDocumento: "C\xE9dula de ciudadan\xEDa",
5179
- id: "",
5180
- sucursal: "",
5181
- nombre: "",
5182
- email: "",
5183
- telefono: "",
5184
- ciudad: "",
5185
- direccion: ""
5186
- });
5187
- const handleSaveClient = async () => {
5188
- setClientError("");
5189
- if (!newClient.id.trim()) {
5190
- setClientError(t.idRequired);
5191
- return;
5192
- }
5193
- if (!newClient.nombre.trim()) {
5194
- setClientError(t.nameRequired);
5195
- return;
5196
- }
5197
- const cleanId = newClient.id.trim().toLowerCase();
5198
- const isDuplicate = options.some((opt) => String(opt.value || "").trim().toLowerCase() === cleanId);
5199
- if (isDuplicate) {
5200
- setClientError("Ya existe un cliente con este NIT o C\xE9dula. No se pueden repetir.");
5201
- return;
6071
+ const [modalOpen, setModalOpen] = (0, import_react5.useState)(false);
6072
+ const [saving, setSaving] = (0, import_react5.useState)(false);
6073
+ const [formError, setFormError] = (0, import_react5.useState)("");
6074
+ const [newRecord, setNewRecord] = (0, import_react5.useState)({});
6075
+ const targetCol = ctx.config.collections?.find((c) => c.id === collectionId);
6076
+ const handleSaveRecord = async () => {
6077
+ setFormError("");
6078
+ if (!targetCol) return;
6079
+ const uniqueFields = targetCol.fields.filter((f) => f.unique || f.id === "id" && !f.hideOnCreate);
6080
+ for (const uf of uniqueFields) {
6081
+ const val = String(newRecord[uf.id] || "").trim();
6082
+ if (!val) {
6083
+ setFormError(`El campo "${uf.label || uf.id}" es obligatorio.`);
6084
+ return;
6085
+ }
6086
+ const isDup = options.some((opt) => String(opt.value || "").trim().toLowerCase() === val.toLowerCase());
6087
+ if (isDup) {
6088
+ setFormError(`Ya existe un registro con este ${uf.label.toLowerCase()} (\xAB${val}\xBB).`);
6089
+ return;
6090
+ }
5202
6091
  }
5203
- setCreatingClient(true);
6092
+ setSaving(true);
5204
6093
  try {
5205
- const entry = {
5206
- ...newClient,
5207
- id: newClient.id.trim(),
5208
- nombre: newClient.nombre.trim()
6094
+ const entryToSave = {
6095
+ id: String(newRecord.id || Date.now()).trim(),
6096
+ ...newRecord
5209
6097
  };
5210
- await ctx.adapter.putEntry("clients", entry);
5211
- const res = await ctx.adapter.listEntries("clients");
6098
+ targetCol.fields.forEach((f) => {
6099
+ if (f.type === "list" || f.multiple) {
6100
+ if (Array.isArray(entryToSave[f.id])) {
6101
+ entryToSave[f.id] = entryToSave[f.id].filter(
6102
+ (item) => item !== void 0 && item !== null && String(item).trim() !== ""
6103
+ );
6104
+ } else if (typeof entryToSave[f.id] === "string" && entryToSave[f.id]) {
6105
+ entryToSave[f.id] = [String(entryToSave[f.id]).trim()];
6106
+ }
6107
+ }
6108
+ });
6109
+ await ctx.adapter.putEntry(collectionId, entryToSave);
6110
+ const res = await ctx.adapter.listEntries(collectionId);
5212
6111
  const fromCollection = (res || []).map((r) => {
5213
6112
  const val = valueField && r[valueField] !== void 0 ? String(r[valueField]) : r.name ? String(r.name) : r.id;
5214
6113
  const fullName = r.apellido ? `${r.nombre || r.name || ""} ${r.apellido}`.trim() : "";
@@ -5220,27 +6119,18 @@ function ReferenceSelect({
5220
6119
  };
5221
6120
  });
5222
6121
  setOptions(fromCollection);
5223
- onChange(entry.id);
6122
+ const selectedVal = valueField && entryToSave[valueField] !== void 0 ? String(entryToSave[valueField]) : entryToSave.id;
6123
+ onChange(selectedVal);
5224
6124
  if (onSelectRecord) {
5225
- onSelectRecord(entry);
6125
+ onSelectRecord(entryToSave);
5226
6126
  }
5227
- setClientModalOpen(false);
5228
- setNewClient({
5229
- tipo: "Persona",
5230
- tipoDocumento: "C\xE9dula de ciudadan\xEDa",
5231
- id: "",
5232
- sucursal: "",
5233
- nombre: "",
5234
- email: "",
5235
- telefono: "",
5236
- ciudad: "",
5237
- direccion: ""
5238
- });
5239
- message.success(t.clientCreatedSuccess);
6127
+ setModalOpen(false);
6128
+ setNewRecord({});
6129
+ message.success(t.recordCreatedSuccess || "Registro creado y seleccionado exitosamente.");
5240
6130
  } catch (err) {
5241
- setClientError(err?.message || "Error al crear cliente.");
6131
+ setFormError(err?.message || "Error al crear registro.");
5242
6132
  } finally {
5243
- setCreatingClient(false);
6133
+ setSaving(false);
5244
6134
  }
5245
6135
  };
5246
6136
  (0, import_react5.useEffect)(() => {
@@ -5265,41 +6155,24 @@ function ReferenceSelect({
5265
6155
  });
5266
6156
  setOptions(fromCollection);
5267
6157
  setLoading(false);
5268
- }).catch(() => {
5269
- setOptions([]);
6158
+ }).catch((err) => {
6159
+ console.error(`Failed to load reference entries for ${collectionId}:`, err);
6160
+ if (fallbackOptions && fallbackOptions.length > 0) {
6161
+ setOptions(fallbackOptions.map((opt) => typeof opt === "string" ? { value: opt, label: opt } : opt));
6162
+ }
5270
6163
  setLoading(false);
5271
6164
  });
5272
- }, [collectionId, displayField, valueField, fallbackOptions, ctx.adapter, ctx.collectionChangedAt]);
5273
- if (multiple) {
5274
- const selectedList = Array.isArray(value) ? value.map(String) : typeof value === "string" && value.trim() ? value.split(",").map((s) => s.trim()).filter(Boolean) : [];
5275
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5276
- import_antd.Select,
5277
- {
5278
- size: "large",
5279
- mode: "multiple",
5280
- loading,
5281
- showSearch: searchable,
5282
- placeholder: "Seleccionar opciones...",
5283
- filterOption: (input, option) => {
5284
- if (!input) return true;
5285
- const q = input.toLowerCase();
5286
- const label = String(option?.label ?? "").toLowerCase();
5287
- const val = String(option?.value ?? "").toLowerCase();
5288
- return label.includes(q) || val.includes(q);
5289
- },
5290
- maxCount: max,
5291
- value: selectedList,
5292
- onChange,
5293
- options,
5294
- className: "w-full"
5295
- }
5296
- );
5297
- }
5298
- const singleVal = value !== void 0 && value !== null && value !== "" ? String(value) : void 0;
5299
- const displayOptions = [...options];
5300
- if (singleVal && !displayOptions.some((o) => o.value === singleVal)) {
5301
- displayOptions.unshift({ value: singleVal, label: singleVal });
5302
- }
6165
+ }, [collectionId, displayField, valueField, fallbackOptions, ctx.adapter]);
6166
+ const rawVal = Array.isArray(value) ? value : value !== void 0 && value !== null && value !== "" ? [value] : [];
6167
+ const singleVal = rawVal[0] !== void 0 ? String(rawVal[0]) : void 0;
6168
+ const displayOptions = (0, import_react5.useMemo)(() => {
6169
+ const list = [...options];
6170
+ if (singleVal && !list.some((o) => o.value === singleVal)) {
6171
+ list.unshift({ value: singleVal, label: `${singleVal} (actual)` });
6172
+ }
6173
+ return list;
6174
+ }, [options, singleVal]);
6175
+ const canQuickCreate = Boolean(targetCol && targetCol.enableQuickCreate !== false);
5303
6176
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_jsx_runtime5.Fragment, { children: [
5304
6177
  /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex items-center gap-2", children: [
5305
6178
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "flex-1", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
@@ -5328,8 +6201,8 @@ function ReferenceSelect({
5328
6201
  options: displayOptions,
5329
6202
  dropdownRender: (menu) => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
5330
6203
  menu,
5331
- collectionId === "clients" && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "p-2 border-t border-slate-100 flex items-center justify-between bg-slate-50", children: [
5332
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "text-xs text-slate-500 font-medium", children: t.cantFindClient }),
6204
+ canQuickCreate && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "p-2 border-t border-slate-100 flex items-center justify-between bg-slate-50", children: [
6205
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "text-xs text-slate-500 font-medium", children: t.cantFindOption || "\xBFNo encuentras la opci\xF3n?" }),
5333
6206
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5334
6207
  import_antd.Button,
5335
6208
  {
@@ -5337,11 +6210,18 @@ function ReferenceSelect({
5337
6210
  size: "small",
5338
6211
  icon: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.Plus, { className: "w-3.5 h-3.5" }),
5339
6212
  onClick: () => {
5340
- setClientError("");
5341
- setClientModalOpen(true);
6213
+ setFormError("");
6214
+ const init = {};
6215
+ targetCol.fields.forEach((f) => {
6216
+ if (f.defaultValue !== void 0) init[f.id] = f.defaultValue;
6217
+ else if (f.type === "list" || f.multiple) init[f.id] = [""];
6218
+ else init[f.id] = "";
6219
+ });
6220
+ setNewRecord(init);
6221
+ setModalOpen(true);
5342
6222
  },
5343
6223
  className: "bg-blue-600 hover:bg-blue-700 text-xs font-semibold rounded-lg shadow-sm",
5344
- children: t.createClient
6224
+ children: t.createNewOption || `Crear ${targetCol.name}`
5345
6225
  }
5346
6226
  )
5347
6227
  ] })
@@ -5349,192 +6229,191 @@ function ReferenceSelect({
5349
6229
  className: "w-full"
5350
6230
  }
5351
6231
  ) }),
5352
- collectionId === "clients" && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
6232
+ canQuickCreate && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5353
6233
  import_antd.Button,
5354
6234
  {
5355
6235
  type: "primary",
5356
6236
  size: "large",
5357
6237
  icon: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.Plus, { className: "w-4 h-4" }),
5358
6238
  onClick: () => {
5359
- setClientError("");
5360
- setClientModalOpen(true);
6239
+ setFormError("");
6240
+ const init = {};
6241
+ targetCol.fields.forEach((f) => {
6242
+ if (f.defaultValue !== void 0) init[f.id] = f.defaultValue;
6243
+ else if (f.type === "list" || f.multiple) init[f.id] = [""];
6244
+ else init[f.id] = "";
6245
+ });
6246
+ setNewRecord(init);
6247
+ setModalOpen(true);
5361
6248
  },
5362
6249
  className: "bg-blue-600 hover:bg-blue-700 font-bold rounded-xl shrink-0 h-10 px-4 text-xs uppercase tracking-wider",
5363
- children: t.newBtn
6250
+ children: targetCol.submitLabel || t.newBtn
5364
6251
  }
5365
6252
  )
5366
6253
  ] }),
5367
- collectionId === "clients" && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
6254
+ canQuickCreate && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5368
6255
  import_antd.Modal,
5369
6256
  {
5370
- open: clientModalOpen,
5371
- title: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "text-xl font-bold text-slate-900 font-display", children: t.basicDetails }),
5372
- onCancel: () => setClientModalOpen(false),
6257
+ open: modalOpen,
6258
+ title: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "text-xl font-bold text-slate-900 font-display", children: targetCol.createTitle || `${t.newBtn} ${targetCol.name}` }),
6259
+ onCancel: () => setModalOpen(false),
5373
6260
  centered: true,
5374
6261
  width: 650,
5375
6262
  footer: null,
5376
6263
  children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "pt-2 space-y-4", children: [
5377
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-3", children: [
5378
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
5379
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientType }),
5380
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5381
- import_antd.Select,
5382
- {
5383
- size: "large",
5384
- value: newClient.tipo,
5385
- onChange: (val) => {
5386
- setNewClient((prev) => ({
5387
- ...prev,
5388
- tipo: val,
5389
- tipoDocumento: val === "Empresa" ? "Nit" : "C\xE9dula de ciudadan\xEDa"
5390
- }));
5391
- },
5392
- options: [
5393
- { label: "Persona", value: "Persona" },
5394
- { label: "Empresa", value: "Empresa" }
5395
- ],
5396
- className: "w-full"
5397
- }
5398
- )
5399
- ] }),
5400
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
5401
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientDocType }),
5402
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5403
- import_antd.Select,
5404
- {
5405
- size: "large",
5406
- value: newClient.tipoDocumento,
5407
- onChange: (val) => setNewClient((prev) => ({ ...prev, tipoDocumento: val })),
5408
- options: newClient.tipo === "Persona" ? [
5409
- { label: "C\xE9dula de ciudadan\xEDa", value: "C\xE9dula de ciudadan\xEDa" },
5410
- { label: "C\xE9dula de extranjer\xEDa", value: "C\xE9dula de extranjer\xEDa" },
5411
- { label: "Pasaporte", value: "Pasaporte" }
5412
- ] : [{ label: "Nit", value: "Nit" }],
5413
- className: "w-full"
5414
- }
5415
- )
5416
- ] })
5417
- ] }),
5418
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-3", children: [
5419
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
6264
+ /* @__PURE__ */ (0, import_jsx_runtime5.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) => {
6265
+ if (f.dependsOn && newRecord[f.dependsOn.field] !== void 0) {
6266
+ const targetVal = f.dependsOn.value;
6267
+ const currentVal = newRecord[f.dependsOn.field];
6268
+ const match = Array.isArray(targetVal) ? targetVal.includes(currentVal) : currentVal === targetVal;
6269
+ if (!match) return null;
6270
+ }
6271
+ const isFullWidth = f.colSpan === 2 || f.colSpan === 12 || f.multiple || f.type === "list" || f.type === "textarea";
6272
+ const colSpanClass = isFullWidth ? "col-span-1 sm:col-span-2" : "col-span-1";
6273
+ if (f.type === "list" || f.multiple) {
6274
+ const currentList = Array.isArray(newRecord[f.id]) ? newRecord[f.id] : newRecord[f.id] ? [String(newRecord[f.id])] : [""];
6275
+ const singularLabel = f.label.endsWith("es") ? f.label.slice(0, -2) : f.label.endsWith("s") ? f.label.slice(0, -1) : f.label;
6276
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: colSpanClass, children: [
6277
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: f.label }),
6278
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "space-y-2", children: [
6279
+ currentList.map((item, idx) => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "flex items-center gap-2", children: [
6280
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { className: "text-xs font-mono font-bold text-slate-400 w-6 text-right shrink-0", children: [
6281
+ "#",
6282
+ idx + 1
6283
+ ] }),
6284
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
6285
+ import_antd.Input,
6286
+ {
6287
+ size: "large",
6288
+ value: item,
6289
+ placeholder: `${singularLabel} #${idx + 1}...`,
6290
+ onChange: (e) => {
6291
+ const updated = [...currentList];
6292
+ updated[idx] = e.target.value;
6293
+ setNewRecord((prev) => ({ ...prev, [f.id]: updated }));
6294
+ }
6295
+ }
6296
+ ),
6297
+ currentList.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
6298
+ "button",
6299
+ {
6300
+ type: "button",
6301
+ onClick: () => {
6302
+ const updated = currentList.filter((_, i) => i !== idx);
6303
+ setNewRecord((prev) => ({
6304
+ ...prev,
6305
+ [f.id]: updated.length > 0 ? updated : [""]
6306
+ }));
6307
+ },
6308
+ className: "p-2 text-rose-500 hover:text-rose-700 hover:bg-rose-50 rounded-lg cursor-pointer shrink-0",
6309
+ children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.Trash2, { className: "size-4" })
6310
+ }
6311
+ )
6312
+ ] }, idx)),
6313
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
6314
+ import_antd.Button,
6315
+ {
6316
+ type: "dashed",
6317
+ size: "small",
6318
+ icon: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.Plus, { className: "size-3.5" }),
6319
+ onClick: () => setNewRecord((prev) => ({
6320
+ ...prev,
6321
+ [f.id]: [...currentList, ""]
6322
+ })),
6323
+ className: "w-full text-xs font-semibold",
6324
+ children: [
6325
+ "+ Agregar ",
6326
+ singularLabel.toLowerCase()
6327
+ ]
6328
+ }
6329
+ )
6330
+ ] })
6331
+ ] }, f.id);
6332
+ }
6333
+ if (f.type === "select") {
6334
+ const opts = f.optionsMap && f.dependsOnField ? f.optionsMap[String(newRecord[f.dependsOnField] || "")] || f.options || [] : f.options || [];
6335
+ const formattedOpts = opts.map((o) => typeof o === "string" ? { label: o, value: o } : o);
6336
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: colSpanClass, children: [
6337
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: f.label }),
6338
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
6339
+ import_antd.Select,
6340
+ {
6341
+ size: "large",
6342
+ value: newRecord[f.id] || void 0,
6343
+ onChange: (val) => {
6344
+ setNewRecord((prev) => {
6345
+ const next = { ...prev, [f.id]: val };
6346
+ targetCol.fields.forEach((dep) => {
6347
+ if (dep.dependsOnField === f.id && dep.optionsMap) {
6348
+ const nextOpts = dep.optionsMap[val] || dep.options || [];
6349
+ const firstVal = typeof nextOpts[0] === "string" ? nextOpts[0] : nextOpts[0]?.value;
6350
+ next[dep.id] = firstVal || "";
6351
+ }
6352
+ });
6353
+ return next;
6354
+ });
6355
+ },
6356
+ options: formattedOpts,
6357
+ className: "w-full"
6358
+ }
6359
+ )
6360
+ ] }, f.id);
6361
+ }
6362
+ if (f.type === "textarea") {
6363
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: colSpanClass, children: [
6364
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: f.label }),
6365
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
6366
+ import_antd.Input.TextArea,
6367
+ {
6368
+ rows: 3,
6369
+ value: newRecord[f.id] || "",
6370
+ onChange: (e) => setNewRecord((prev) => ({ ...prev, [f.id]: e.target.value }))
6371
+ }
6372
+ )
6373
+ ] }, f.id);
6374
+ }
6375
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: colSpanClass, children: [
5420
6376
  /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: [
5421
- t.clientIdentification,
5422
- " *"
6377
+ f.label,
6378
+ " ",
6379
+ f.unique ? "*" : ""
5423
6380
  ] }),
5424
6381
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5425
6382
  import_antd.Input,
5426
6383
  {
5427
6384
  size: "large",
5428
- status: clientError && clientError.includes("identificaci\xF3n") ? "error" : void 0,
5429
- placeholder: t.clientIdentification,
5430
- value: newClient.id,
6385
+ value: newRecord[f.id] || "",
6386
+ placeholder: f.label,
5431
6387
  onChange: (e) => {
5432
- setNewClient((prev) => ({ ...prev, id: e.target.value }));
5433
- if (clientError) setClientError("");
6388
+ setNewRecord((prev) => ({ ...prev, [f.id]: e.target.value }));
6389
+ if (formError) setFormError("");
5434
6390
  },
5435
6391
  onBlur: (e) => {
5436
- const clean = (e.target.value || "").trim().toLowerCase();
5437
- if (clean) {
5438
- const dup = options.find((opt) => String(opt.value || "").trim().toLowerCase() === clean);
5439
- if (dup) {
5440
- setClientError(`Ya existe un cliente con esta identificaci\xF3n (\xAB${dup.label || clean}\xBB).`);
5441
- message.warning(`\u26A0\uFE0F Ya existe un cliente con esta identificaci\xF3n: ${clean}.`);
6392
+ if (f.unique) {
6393
+ const clean = (e.target.value || "").trim().toLowerCase();
6394
+ if (clean) {
6395
+ const dup = options.find((opt) => String(opt.value || "").trim().toLowerCase() === clean);
6396
+ if (dup) {
6397
+ setFormError(`Ya existe un registro con este ${f.label.toLowerCase()} (\xAB${dup.label || clean}\xBB).`);
6398
+ message.warning(`\u26A0\uFE0F Ya existe un registro con este ${f.label.toLowerCase()}: ${clean}.`);
6399
+ }
5442
6400
  }
5443
6401
  }
5444
6402
  }
5445
6403
  }
5446
6404
  )
5447
- ] }),
5448
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
5449
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientBranch }),
5450
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5451
- import_antd.Input,
5452
- {
5453
- size: "large",
5454
- placeholder: t.clientBranch,
5455
- value: newClient.sucursal,
5456
- onChange: (e) => setNewClient((prev) => ({ ...prev, sucursal: e.target.value }))
5457
- }
5458
- )
5459
- ] })
5460
- ] }),
5461
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-3", children: [
5462
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
5463
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: [
5464
- t.clientName,
5465
- " *"
5466
- ] }),
5467
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5468
- import_antd.Input,
5469
- {
5470
- size: "large",
5471
- placeholder: t.clientName,
5472
- value: newClient.nombre,
5473
- onChange: (e) => setNewClient((prev) => ({ ...prev, nombre: e.target.value }))
5474
- }
5475
- )
5476
- ] }),
5477
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
5478
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientEmail }),
5479
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5480
- import_antd.Input,
5481
- {
5482
- size: "large",
5483
- placeholder: t.clientEmail,
5484
- value: newClient.email,
5485
- onChange: (e) => setNewClient((prev) => ({ ...prev, email: e.target.value }))
5486
- }
5487
- )
5488
- ] })
5489
- ] }),
5490
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-3", children: [
5491
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
5492
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientPhone }),
5493
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5494
- import_antd.Input,
5495
- {
5496
- size: "large",
5497
- placeholder: t.clientPhone,
5498
- value: newClient.telefono,
5499
- onChange: (e) => setNewClient((prev) => ({ ...prev, telefono: e.target.value }))
5500
- }
5501
- )
5502
- ] }),
5503
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
5504
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientCity }),
5505
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5506
- import_antd.Input,
5507
- {
5508
- size: "large",
5509
- placeholder: t.clientCity,
5510
- value: newClient.ciudad,
5511
- onChange: (e) => setNewClient((prev) => ({ ...prev, ciudad: e.target.value }))
5512
- }
5513
- )
5514
- ] })
5515
- ] }),
5516
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { children: [
5517
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("label", { className: "block text-xs font-bold text-slate-700 mb-1", children: t.clientAddress }),
5518
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5519
- import_antd.Input,
5520
- {
5521
- size: "large",
5522
- placeholder: t.clientAddress,
5523
- value: newClient.direccion,
5524
- onChange: (e) => setNewClient((prev) => ({ ...prev, direccion: e.target.value }))
5525
- }
5526
- )
5527
- ] }),
5528
- clientError && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "text-xs font-semibold text-red-600 bg-red-50 p-2.5 rounded-lg border border-red-200", children: clientError }),
6405
+ ] }, f.id);
6406
+ }) }),
6407
+ formError && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "text-xs font-semibold text-red-600 bg-red-50 p-2.5 rounded-lg border border-red-200", children: formError }),
5529
6408
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5530
6409
  import_antd.Button,
5531
6410
  {
5532
6411
  type: "primary",
5533
6412
  size: "large",
5534
- loading: creatingClient,
5535
- onClick: handleSaveClient,
6413
+ loading: saving,
6414
+ onClick: handleSaveRecord,
5536
6415
  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",
5537
- children: t.create.toUpperCase()
6416
+ children: (targetCol.submitLabel || t.create).toUpperCase()
5538
6417
  }
5539
6418
  )
5540
6419
  ] })