@firecms/data_import_export 3.0.0-canary.8 → 3.0.0-canary.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/LICENSE +113 -21
  2. package/README.md +1 -1
  3. package/dist/components/DataNewPropertiesMapping.d.ts +3 -5
  4. package/dist/components/ImportFileUpload.d.ts +1 -1
  5. package/dist/export_import/BasicExportAction.d.ts +7 -0
  6. package/dist/export_import/ExportCollectionAction.d.ts +1 -1
  7. package/dist/export_import/export.d.ts +15 -4
  8. package/dist/export_import/index.d.ts +4 -0
  9. package/dist/index.d.ts +1 -0
  10. package/dist/index.es.js +940 -570
  11. package/dist/index.es.js.map +1 -1
  12. package/dist/index.umd.js +2 -2
  13. package/dist/index.umd.js.map +1 -1
  14. package/dist/types/column_mapping.d.ts +5 -7
  15. package/dist/useImportExportPlugin.d.ts +1 -1
  16. package/dist/utils/data.d.ts +3 -10
  17. package/dist/utils/file_headers.d.ts +1 -0
  18. package/dist/utils/file_to_json.d.ts +6 -1
  19. package/dist/utils/get_properties_mapping.d.ts +0 -3
  20. package/dist/utils/index.d.ts +0 -1
  21. package/package.json +20 -34
  22. package/src/components/DataNewPropertiesMapping.tsx +153 -40
  23. package/src/components/ImportFileUpload.tsx +12 -4
  24. package/src/components/ImportNewPropertyFieldPreview.tsx +7 -2
  25. package/src/export_import/BasicExportAction.tsx +147 -0
  26. package/src/export_import/ExportCollectionAction.tsx +45 -9
  27. package/src/export_import/ImportCollectionAction.tsx +22 -22
  28. package/src/export_import/export.ts +63 -29
  29. package/src/export_import/index.ts +4 -0
  30. package/src/hooks/useImportConfig.tsx +6 -0
  31. package/src/index.ts +1 -0
  32. package/src/types/column_mapping.ts +6 -6
  33. package/src/useImportExportPlugin.tsx +2 -2
  34. package/src/utils/data.ts +36 -126
  35. package/src/utils/file_headers.ts +90 -0
  36. package/src/utils/file_to_json.ts +33 -15
  37. package/src/utils/get_properties_mapping.ts +63 -59
  38. package/src/utils/index.ts +0 -1
package/dist/index.umd.js CHANGED
@@ -1,3 +1,3 @@
1
- (function(m,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("react"),require("react/jsx-runtime"),require("@firecms/core"),require("@firecms/ui"),require("@firecms/schema_inference"),require("xlsx")):typeof define=="function"&&define.amd?define(["exports","react","react/jsx-runtime","@firecms/core","@firecms/ui","@firecms/schema_inference","xlsx"],g):(m=typeof globalThis<"u"?globalThis:m||self,g(m["FireCMS data import/export"]={},m.React,m.jsxRuntime,m.core,m.ui,m.schema_inference,m.XLSX))})(this,function(m,g,r,h,l,pe,fe){"use strict";function ge(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const a in e)if(a!=="default"){const t=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(n,a,t.get?t:{enumerable:!0,get:()=>e[a]})}}return n.default=e,Object.freeze(n)}const G=ge(fe),Q=()=>{const[e,n]=g.useState(!1),[a,t]=g.useState(),[s,o]=g.useState([]),[i,p]=g.useState([]),[d,c]=g.useState({}),[f,y]=g.useState({});return{inUse:e,setInUse:n,idColumn:a,setIdColumn:t,entities:i,setEntities:p,importData:s,setImportData:o,headersMapping:d,setHeadersMapping:c,originProperties:f,setOriginProperties:y}};function Y(e){return new Promise((n,a)=>{if(e.type==="application/json"){console.debug("Converting JSON file to JSON",e.name);const t=new FileReader;t.onload=function(s){const o=s.target?.result,i=JSON.parse(o);Array.isArray(i)||a(new Error("JSON file should contain an array of objects")),n(i)},t.readAsText(e)}else{console.debug("Converting Excel file to JSON",e.name);const t=new FileReader;t.onload=function(s){const o=new Uint8Array(s.target?.result),i=G.read(o,{type:"array",codepage:65001,cellDates:!0}),p=i.SheetNames[0],d=i.Sheets[p],y=G.utils.sheet_to_json(d).map(he).map(H);n(y)},t.readAsArrayBuffer(e)}})}function he(e){return Object.keys(e).reduce((n,a)=>{try{n[a]=JSON.parse(e[a])}catch{n[a]=e[a]}return n},{})}function H(e){return Object.keys(e).reduce((n,a)=>{let t=n;const s=a.split(".");return s.forEach((o,i)=>{if(/^[\w]+\[\d+\]$/.test(o)){const p=o.slice(0,o.indexOf("[")),d=parseInt(o.slice(o.indexOf("[")+1,o.indexOf("]")));t[p]||(t[p]=[]),i!==s.length-1?(t[p][d]=t[p][d]||{},t=t[p][d]):t[p][d]=e[a]}else i!==s.length-1?(t[o]=t[o]||{},t=t[o]):t[o]=e[a]}),n},{})}function Z(e,n,a,t,s,o){const i=U(e);n&&delete i[n];const p=Object.entries(i).map(([f,y])=>{const b=a[f]??f;if(!h.getPropertyInPath(t,b))return{};const I=s[b];let O=y;return I&&(O=_(y,I)),{[b]:O}}).reduce((f,y)=>({...f,...y}),{}),d=H(p);let c=n?e[n]:void 0;return typeof c=="string"?c=c.trim():typeof c=="number"||typeof c=="boolean"?c=c.toString():c instanceof Date?c=c.toISOString():c&&"toString"in c&&(c=c.toString()),{id:c,values:d,path:o}}function U(e,n=""){return Object.keys(e).reduce((a,t)=>{const s=n?`${n}.${t}`:t;return typeof e[t]=="object"&&e[t]!==null&&!Array.isArray(e[t])?Object.assign(a,U(e[t],s)):a[s]=e[t],a},{})}function _(e,n){if(n===void 0)return e;const{from:a,to:t}=n;if(a==="array"&&t==="array"&&n.fromSubtype&&n.toSubtype&&Array.isArray(e))return e.map(s=>_(s,{from:n.fromSubtype,to:n.toSubtype}));if(a==="string"&&t==="number"&&typeof e=="string")return Number(e);if(a==="string"&&t==="array"&&n.toSubtype&&typeof e=="string")return e.split(",").map(s=>_(s,{from:"string",to:n.toSubtype}));if(a==="string"&&t==="boolean")return e==="true";if(a==="number"&&t==="boolean")return e===1;if(a==="boolean"&&t==="number")return e?1:0;if(a==="boolean"&&t==="string")return e?"true":"false";if(a==="number"&&t==="string"&&typeof e=="number")return e.toString();if(a==="string"&&t==="array"&&typeof e=="string")return e.split(",").map(s=>s.trim());if(a==="string"&&t==="date"&&typeof e=="string")try{return new Date(e)}catch{return e}else{if(a==="date"&&t==="string")return e instanceof Date&&e.toISOString();if(a==="number"&&t==="date"&&typeof e=="number")try{return new Date(e)}catch{return e}else if(a==="string"&&t==="reference"&&typeof e=="string"){const s=e.split("/").slice(0,-1).join("/"),o=e.split("/").slice(-1)[0];return new h.EntityReference(o,s)}else{if(a===t)return e;if(a==="array"&&t==="string"&&Array.isArray(e))return e.join(",")}}return e}function K(e){return typeof e=="number"?"number":typeof e=="string"?"string":typeof e=="boolean"?"boolean":e instanceof Date?"date":Array.isArray(e)?"array":"map"}function R(e,n){function a(t,s){const o={};return Object.keys(t).forEach(i=>{const p=s?`${s}.${i}`:i,d=h.getPropertyInPath(t,i),c=h.getPropertyInPath(e,p);if(d){if(d.dataType==="map"&&d.properties){const f=a(d.properties,p);Object.keys(f).forEach(y=>{o[`${p}.${y}`]=f[y]});return}if(c){const f=c.dataType,y=d.dataType;let b,u;d.dataType==="array"&&d.of&&(u=d.of.dataType),c?.dataType==="array"&&c?.of&&(b=c.of.dataType),(f!==y||b!==u)&&(o[i]={from:f,to:y,fromSubtype:b,toSubtype:u})}}}),o}return a(n)}function ee({idColumn:e,headersMapping:n,originProperties:a,destinationProperties:t,onIdPropertyChanged:s,buildPropertyView:o}){return r.jsxs(r.Fragment,{children:[r.jsx(ye,{idColumn:e,headersMapping:n,onChange:s}),r.jsxs(l.Table,{style:{tableLayout:"fixed"},children:[r.jsxs(l.TableHeader,{children:[r.jsx(l.TableCell,{header:!0,style:{width:"20%"},children:"Column in file"}),r.jsx(l.TableCell,{header:!0}),r.jsx(l.TableCell,{header:!0,style:{width:"75%"},children:"Property"})]}),r.jsx(l.TableBody,{children:t&&Object.entries(n).map(([i,p])=>{const d=n[i],c=p?h.getPropertyInPath(t,p):null,f=h.getPropertyInPath(a,i),y=f?f.dataType==="array"&&typeof f.of=="object"?`${f.dataType} - ${f.of.dataType}`:f.dataType:void 0;return r.jsxs(l.TableRow,{style:{height:"90px"},children:[r.jsxs(l.TableCell,{style:{width:"20%"},children:[r.jsx(l.Typography,{variant:"body2",children:i}),f&&r.jsx(l.Typography,{variant:"caption",color:"secondary",children:y})]}),r.jsx(l.TableCell,{children:r.jsx(l.ChevronRightIcon,{})}),r.jsx(l.TableCell,{className:i===e?"text-center":void 0,style:{width:"75%"},children:o?.({isIdColumn:i===e,property:c,propertyKey:d,importKey:i})})]},i)})})]})]})}function ye({idColumn:e,headersMapping:n,onChange:a}){return r.jsx("div",{children:r.jsxs(l.Select,{size:"small",value:e??"",onChange:t=>{const s=t.target.value;a(s==="none"?null:s)},renderValue:t=>r.jsx(l.Typography,{variant:"body2",children:t!==""?t:"Autogenerate ID"}),label:"Column that will be used as ID for each document",children:[r.jsx(l.SelectItem,{value:"none",children:"Autogenerate ID"}),Object.entries(n).map(([t,s])=>r.jsx(l.SelectItem,{value:t,children:t},t))]})})}function re({onDataAdded:e}){const n=h.useSnackbarController();return r.jsx(l.FileUpload,{accept:{"text/*":[".csv",".xls",".xlsx"],"application/vnd.ms-excel":[".xls",".xlsx"],"application/msexcel":[".xls",".xlsx"],"application/vnd.ms-office":[".xls",".xlsx"],"application/xls":[".xls",".xlsx"],"application/x-xls":[".xls",".xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":[".xls",".xlsx"],"application/json":[".json"]},preventDropOnDocument:!0,size:"small",maxFiles:1,uploadDescription:r.jsxs(r.Fragment,{children:[r.jsx(l.UploadIcon,{}),"Drag and drop a file here or click to upload"]}),onFilesAdded:a=>{a.length>0&&Y(a[0]).then(t=>{e(t)}).catch(t=>{console.error("Error parsing file",t),n.open({type:"error",message:t.message})})}})}function me({propertyKey:e,property:n,onEditClick:a,includeName:t=!0,onPropertyNameChanged:s,propertyTypeView:o}){const{propertyConfigs:i}=h.useCustomizationController(),p=n?h.getFieldConfig(n,i):null;return r.jsx(h.ErrorBoundary,{children:r.jsxs("div",{className:"flex flex-row w-full items-center",children:[r.jsx("div",{className:"mx-4",children:o??r.jsx(h.PropertyConfigBadge,{propertyConfig:p??void 0})}),r.jsx("div",{className:"w-full flex flex-col grow",children:r.jsxs("div",{className:"flex flex-row items-center gap-2",children:[t&&r.jsx(l.TextField,{size:"small",className:"text-base grow",value:n?.name??"",onChange:d=>{s&&e&&s(e,d.target.value)}}),r.jsx(l.IconButton,{onClick:a,size:"small",children:r.jsx(l.EditIcon,{size:"small"})})]})})]})})}function te({path:e,importConfig:n,collection:a,onImportSuccess:t}){const[s,o]=g.useState(void 0),i=h.useDataSource(),p=g.useRef(!1),[d,c]=g.useState(0);function f(){p.current||(p.current=!0,ne(i,a,e,n.entities,0,25,c).then(()=>{t(a),p.current=!1}).catch(y=>{o(y),p.current=!1}))}return g.useEffect(()=>{f()},[]),s?r.jsxs(l.CenteredView,{className:"flex flex-col gap-4 items-center",children:[r.jsx(l.Typography,{variant:"h6",children:"Error saving data"}),r.jsx(l.Typography,{variant:"body2",color:"error",children:s.message}),r.jsx(l.Button,{onClick:f,variant:"outlined",children:"Retry"})]}):r.jsxs(l.CenteredView,{className:"flex flex-col gap-4 items-center",children:[r.jsx(l.CircularProgress,{}),r.jsx(l.Typography,{variant:"h6",children:"Saving data"}),r.jsxs(l.Typography,{variant:"body2",children:[d,"/",n.entities.length," entities saved"]}),r.jsx(l.Typography,{variant:"caption",children:"Do not close this tab or the import will be interrupted."})]})}function ne(e,n,a,t,s=0,o=25,i){console.debug("Saving imported data",s,o);const p=t.slice(s,s+o);return Promise.all(p.map(d=>e.saveEntity({path:a,values:d.values,entityId:d.id,collection:n,status:"new"}))).then(()=>s+o<t.length?(i(s+o),ne(e,n,a,t,s+o,o,i)):(i(t.length),Promise.resolve()))}function be({collection:e,path:n,collectionEntitiesCount:a,onAnalyticsEvent:t}){const s=h.useCustomizationController(),o=h.useSnackbarController(),[i,p]=g.useState(!1),[d,c]=g.useState("initial"),f=Q(),y=g.useCallback(()=>{p(!0),c("initial")},[p]),b=g.useCallback(()=>{p(!1)},[p]),u=g.useCallback(()=>{c("preview")},[]),I=g.useCallback(()=>{c("import_data_saving")},[]),O=async x=>{if(f.setImportData(x),x.length>0){const N=await pe.buildEntityPropertiesFromData(x,K);f.setOriginProperties(N);const k=oe(x,e?.properties);f.setHeadersMapping(k);const S=Object.keys(k)?.[0];(S?.includes("id")||S?.includes("key"))&&f.setIdColumn(S)}setTimeout(()=>{c("mapping")},100)},F=h.resolveCollection({collection:e,path:n,fields:s.propertyConfigs}),C=h.getPropertiesWithPropertiesOrder(F.properties,F.propertiesOrder),L=Object.entries(C).flatMap(([x,N])=>ae(x,N,0)),j=F.propertiesOrder??Object.keys(F.properties);return e.collectionGroup?null:r.jsxs(r.Fragment,{children:[r.jsx(l.Tooltip,{title:"Import",children:r.jsx(l.IconButton,{color:"primary",onClick:y,children:r.jsx(l.FileUploadIcon,{})})}),r.jsxs(l.Dialog,{open:i,fullWidth:d==="preview",fullHeight:d==="preview",maxWidth:d==="initial"?"lg":"7xl",children:[r.jsxs(l.DialogContent,{className:"flex flex-col gap-4 my-4",fullHeight:d==="preview",children:[d==="initial"&&r.jsxs(r.Fragment,{children:[r.jsx(l.Typography,{variant:"h6",children:"Import data"}),r.jsx(l.Typography,{variant:"body2",children:"Upload a CSV, Excel or JSON file and map it to your existing schema"}),r.jsx(re,{onDataAdded:O})]}),d==="mapping"&&r.jsxs(r.Fragment,{children:[r.jsx(l.Typography,{variant:"h6",children:"Map fields"}),r.jsx(ee,{headersMapping:f.headersMapping,idColumn:f.idColumn,originProperties:f.originProperties,destinationProperties:C,onIdPropertyChanged:x=>f.setIdColumn(x??void 0),buildPropertyView:({isIdColumn:x,property:N,propertyKey:k,importKey:S})=>r.jsx(ue,{selectedPropertyKey:k??"",properties:C,propertiesAndLevel:L,isIdColumn:x,onIdSelected:()=>{f.setIdColumn(S)},onPropertySelected:M=>{const E=Object.entries(f.headersMapping).map(([w,T])=>T===M?{[w]:null}:w===S?{[w]:M}:{[w]:T}).reduce((w,T)=>({...w,...T}),{});f.setHeadersMapping(E),M===f.idColumn&&f.setIdColumn(void 0)}})})]}),d==="preview"&&r.jsx(xe,{importConfig:f,properties:C,propertiesOrder:j}),d==="import_data_saving"&&f&&r.jsx(te,{importConfig:f,collection:e,path:n,onImportSuccess:x=>{b(),o.open({type:"info",message:"Data imported successfully"})}})]}),r.jsxs(l.DialogActions,{children:[d==="mapping"&&r.jsx(l.Button,{onClick:()=>c("initial"),variant:"text",children:"Back"}),d==="preview"&&r.jsx(l.Button,{onClick:()=>c("mapping"),variant:"text",children:"Back"}),r.jsx(l.Button,{onClick:b,variant:"text",children:"Cancel"}),d==="mapping"&&r.jsx(l.Button,{variant:"filled",onClick:u,children:"Next"}),d==="preview"&&r.jsx(l.Button,{variant:"filled",onClick:I,children:"Save data"})]})]})]})}const B="__internal_id__";function ue({selectedPropertyKey:e,properties:n,onPropertySelected:a,onIdSelected:t,propertiesAndLevel:s,isIdColumn:o}){const i=e?h.getPropertyInPath(n,e):null,p=g.useCallback(c=>c===B?r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"}):!c||!i?r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Do not import this property"}):r.jsx(se,{propertyKey:c,property:i}),[i]),d=g.useCallback(c=>{c===B?(t(),a(null)):a(c==="__do_not_import"?null:c)},[]);return r.jsxs(l.Select,{value:o?B:e??void 0,onValueChange:d,renderValue:p,children:[r.jsx(l.SelectItem,{value:"__do_not_import",children:r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Do not import this property"})}),r.jsx(l.SelectItem,{value:B,children:r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"})}),s.map(({property:c,level:f,propertyKey:y})=>r.jsx(l.SelectItem,{value:y,disabled:c.dataType==="map",children:r.jsx(se,{propertyKey:y,property:c,level:f})},y))]})}function ae(e,n,a){const t=[];return t.push({property:n,level:a,propertyKey:e}),n.dataType==="map"&&n.properties&&Object.entries(n.properties).forEach(([s,o])=>{t.push(...ae(`${e}.${s}`,o,a+1))}),t}function se({propertyKey:e,property:n,level:a=0}){const{propertyConfigs:t}=h.useCustomizationController(),s=h.getFieldConfig(n,t);return r.jsxs("div",{className:"flex flex-row w-full text-start items-center h-full",children:[new Array(a).fill(0).map((o,i)=>r.jsx("div",{className:l.cn(l.defaultBorderMixin,"ml-8 border-l h-12")},i)),r.jsx("div",{className:"m-4",children:r.jsx(l.Tooltip,{title:s?.name,children:r.jsx(h.PropertyConfigBadge,{propertyConfig:s})})}),r.jsxs("div",{className:"flex flex-col flex-grow p-2 pl-2",children:[r.jsx(l.Typography,{variant:"body1",component:"span",className:"flex-grow pr-2",children:n.name?n.name:" "}),r.jsx(l.Typography,{className:" pr-2",variant:"body2",component:"span",color:"secondary",children:e})]})]})}function xe({importConfig:e,properties:n,propertiesOrder:a}){g.useEffect(()=>{const s=R(e.originProperties,n),o=e.importData.map(i=>Z(i,e.idColumn,e.headersMapping,n,s,"TEMP_PATH"));e.setEntities(o)},[]);const t=h.useSelectionController();return r.jsx(h.EntityCollectionTable,{title:r.jsxs("div",{children:[r.jsx(l.Typography,{variant:"subtitle2",children:"Imported data preview"}),r.jsx(l.Typography,{variant:"caption",children:"Entities with the same id will be overwritten"})]}),tableController:{data:e.entities,dataLoading:!1,noMoreToLoad:!1},endAdornment:r.jsx("div",{className:"h-12"}),filterable:!1,sortable:!1,selectionController:t,displayedColumnIds:a.map(s=>({key:s,disabled:!1})),properties:n})}function oe(e,n){const a={};return e.filter(Boolean).forEach(t=>{Object.keys(t).forEach(s=>{const o=t[s];if(typeof o=="object"&&!Array.isArray(o)){const i=n?.[s],p=i&&"properties"in i?i.properties:void 0,d=oe([o],p);Object.entries(d).forEach(([c,f])=>{a[`${s}.${c}`]=`${s}.${f}`})}if(!n)a[s]=s;else if(s in n)a[s]=s;else{const i=h.slugify(s);i in n?a[s]=i:a[s]=s}})}),a}function Ce(e,n,a,t,s,o,i){console.debug("Downloading export",{dataLength:e.length,collection:a,exportType:o,dateExportType:i});const p=a.properties;if(o==="csv"){const d=t?h.getArrayValuesCount(e.map(u=>u.values)):{},c=we(p,s,d),f=ve(e,n,p,c,i),y=le(c.map(u=>u.label)),b=f.map(u=>le(u));ie([y,...b],`${a.name}.csv`,"text/csv")}else{const d=Se(e,n,p,i),c=JSON.stringify(d,null,2);ie([c],`${a.name}.json`,"application/json")}}function ve(e,n,a,t,s){const o=e.map(i=>({id:i.id,...V(i.values,a,"csv",s)}));return n&&n.forEach((i,p)=>{o[p]={...o[p],...i}}),o&&o.map(i=>t.map(p=>h.getValueInPath(i,p.key)))}function Se(e,n,a,t){const s=e.map(o=>({id:o.id,...V(o.values,a,"json",t)}));return n&&n.forEach((o,i)=>{s[i]={...s[i],...o}}),s}function we(e,n,a){const t=[{label:"id",key:"id"},...Object.entries(e).flatMap(([s,o])=>a&&a[s]>1?Array.from({length:a[s]},(i,p)=>z(o,`${s}[${p}]`,"")).flat():z(o,s,""))];return n&&t.push(...n.map(s=>({label:s,key:s}))),t}function z(e,n,a=""){const t=a?`${a}.${n}`:n;return e.dataType==="map"&&e.properties?Object.entries(e.properties).map(([s,o])=>z(o,s,t)).flat():[{label:t,key:t}]}function $(e,n,a,t){let s;if(n.dataType==="map"&&n.properties)s=V(e,n.properties,a,t);else if(n.dataType==="array")n.of&&Array.isArray(e)?Array.isArray(n.of)?s=n.of.map((o,i)=>$(e[i],o,a,t)):n.of.dataType==="map"?s=a==="csv"?e.map(o=>JSON.stringify(o)):e.map(o=>$(o,n.of,a,t)):s=e.map(o=>$(o,n.of,a,t)):s=e;else if(n.dataType==="reference"&&e&&e.isEntityReference&&e.isEntityReference()){const o=e||void 0;s=o?o.pathWithId:null}else n.dataType==="date"&&e instanceof Date?s=e?t==="timestamp"?e.getTime():e.toISOString():null:s=e;return s}function V(e,n,a,t){const s=Object.entries(n).map(([o,i])=>{const p=e&&e[o],d=$(p,i,a,t);return d===void 0?{}:{[o]:d}}).reduce((o,i)=>({...o,...i}),{});return{...e,...s}}function le(e){return e.map(n=>n==null?"":Array.isArray(n)?'"'+JSON.stringify(n).replaceAll('"','\\"')+'"':'"'+String(n).replaceAll('"','""')+'"').join(",")+`\r
2
- `}function ie(e,n,a){const t=new Blob(e,{type:a}),s=URL.createObjectURL(t),o=document.createElement("a");o.href=s,o.setAttribute("download",n),o.click()}const Te=500;function De({collection:e,path:n,collectionEntitiesCount:a,exportAllowed:t,notAllowedView:s}){const o=h.useCustomizationController(),i=typeof e.exportable=="object"?e.exportable:void 0,p=g.useRef(new Date),[d,c]=g.useState(!0),[f,y]=g.useState("csv"),[b,u]=g.useState("string"),I=h.useFireCMSContext(),O=h.useDataSource(),C=h.useNavigationController().resolveAliasesFrom(n),L=!t||t({collectionEntitiesCount:a,path:C,collection:e}),j=g.useMemo(()=>h.resolveCollection({collection:e,path:C,fields:o.propertyConfigs}),[e,C]),[x,N]=g.useState(!1),[k,S]=g.useState(),[M,E]=g.useState(!1),w=g.useCallback(()=>{E(!0)},[E]),T=g.useCallback(()=>{E(!1)},[E]),ce=g.useCallback(async A=>{const J=i?.additionalFields,D=j.additionalFields,q=J?await Promise.all(A.map(async P=>(await Promise.all(J.map(async v=>({[v.key]:await v.builder({entity:P,context:I})})))).reduce((v,X)=>({...v,...X}),{}))):[],W=D?await Promise.all(A.map(async P=>(await Promise.all(D.map(async v=>v.value?{[v.key]:await v.value({entity:P,context:I})}:{}))).reduce((v,X)=>({...v,...X}),{}))):[];return[...q,...W]},[i?.additionalFields]),de=g.useCallback(async(A,J)=>{N(!0),O.fetchCollection({path:C,collection:A}).then(async D=>{S(void 0);const q=await ce(D),W=[...J?.additionalFields?.map(P=>P.key)??[],...A.additionalFields?.map(P=>P.key)??[]];Ce(D,q,A,d,W,f,b)}).catch(D=>{console.error("Error loading export data",D),S(D)}).finally(()=>N(!1))},[O,C,ce,d,f,b]),Oe=g.useCallback(()=>{de(j,i),T()},[de,j,i,T]);return r.jsxs(r.Fragment,{children:[r.jsx(l.Tooltip,{title:"Export",children:r.jsx(l.IconButton,{color:"primary",onClick:w,children:r.jsx(l.GetAppIcon,{})})}),r.jsxs(l.Dialog,{open:M,onOpenChange:E,maxWidth:"xl",children:[r.jsxs(l.DialogContent,{className:"flex flex-col gap-4 my-4",children:[r.jsx(l.Typography,{variant:"h6",children:"Export data"}),r.jsx("div",{children:"Download the the content of this table as a CSV"}),a>Te&&r.jsx(l.Alert,{color:"warning",children:r.jsxs("div",{children:["This collections has a large number of documents (",a,")."]})}),r.jsxs("div",{className:"flex flex-row gap-4",children:[r.jsxs("div",{className:"p-4 flex flex-col",children:[r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-csv",type:"radio",value:"csv",name:"exportType",checked:f==="csv",onChange:()=>y("csv"),className:l.cn(l.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsx("label",{htmlFor:"radio-csv",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:"CSV"})]}),r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-json",type:"radio",value:"json",name:"exportType",checked:f==="json",onChange:()=>y("json"),className:l.cn(l.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsx("label",{htmlFor:"radio-json",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:"JSON"})]})]}),r.jsxs("div",{className:"p-4 flex flex-col",children:[r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-timestamp",type:"radio",value:"timestamp",name:"dateExportType",checked:b==="timestamp",onChange:()=>u("timestamp"),className:l.cn(l.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsxs("label",{htmlFor:"radio-timestamp",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:["Dates as timestamps (",p.current.getTime(),")"]})]}),r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-string",type:"radio",value:"string",name:"dateExportType",checked:b==="string",onChange:()=>u("string"),className:l.cn(l.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsxs("label",{htmlFor:"radio-string",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:["Dates as strings (",p.current.toISOString(),")"]})]})]})]}),r.jsx(l.BooleanSwitchWithLabel,{size:"small",disabled:f!=="csv",value:d,onValueChange:c,label:"Flatten arrays"}),!L&&s]}),r.jsxs(l.DialogActions,{children:[x&&r.jsx(l.CircularProgress,{size:"small"}),r.jsx(l.Button,{onClick:T,variant:"text",children:"Cancel"}),r.jsx(l.Button,{variant:"filled",onClick:Oe,disabled:x||!L,children:"Download"})]})]})]})}function Ie(e){return g.useMemo(()=>({name:"Import/Export",collectionView:{CollectionActions:[be,De],collectionActionsProps:e}}),[e])}m.DataNewPropertiesMapping=ee,m.ImportFileUpload=re,m.ImportNewPropertyFieldPreview=me,m.ImportSaveInProgress=te,m.convertDataToEntity=Z,m.convertFileToJson=Y,m.flattenEntry=U,m.getInferenceType=K,m.getPropertiesMapping=R,m.processValueMapping=_,m.unflattenObject=H,m.useImportConfig=Q,m.useImportExportPlugin=Ie,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
1
+ (function(m,f){typeof exports=="object"&&typeof module<"u"?f(exports,require("react"),require("react/jsx-runtime"),require("@firecms/core"),require("@firecms/ui"),require("@firecms/schema_inference"),require("xlsx"),require("@firecms/formex")):typeof define=="function"&&define.amd?define(["exports","react","react/jsx-runtime","@firecms/core","@firecms/ui","@firecms/schema_inference","xlsx","@firecms/formex"],f):(m=typeof globalThis<"u"?globalThis:m||self,f(m["FireCMS data import/export"]={},m.React,m.jsxRuntime,m.core,m.ui,m.schema_inference,m.XLSX,m.formex))})(this,function(m,f,r,g,o,R,we,H){"use strict";function Se(e){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const t=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(a,n,t.get?t:{enumerable:!0,get:()=>e[n]})}}return a.default=e,Object.freeze(a)}const F=Se(we),ee=()=>{const[e,a]=f.useState(!1),[n,t]=f.useState({}),[s,l]=f.useState(),[i,c]=f.useState([]),[d,p]=f.useState([]),[h,y]=f.useState({}),[b,u]=f.useState([]),[v,N]=f.useState({});return{inUse:e,setInUse:a,idColumn:s,setIdColumn:l,entities:d,setEntities:p,importData:i,setImportData:c,headingsOrder:(b??[]).length>0?b:Object.keys(h),setHeadingsOrder:u,headersMapping:h,setHeadersMapping:y,originProperties:v,setOriginProperties:N,defaultValues:n,setDefaultValues:t}};function Te(e){let a=0;const n=[],t={};if(e==null||e["!ref"]==null)return[];const s=t.range!==void 0?t.range:e["!ref"];let l;switch(t.header===1?a=1:t.header==="A"?a=2:Array.isArray(t.header)&&(a=3),typeof s){case"string":l=re(s);break;case"number":l=re(e["!ref"]),l.s.r=s;break;default:l=s}const i=F.utils.encode_row(l.s.r),c=new Array(l.e.c-l.s.c+1);for(let d=l.s.c;d<=l.e.c;++d){c[d]=F.utils.encode_col(d);const p=e[c[d]+i];switch(a){case 1:n.push(d);break;case 2:n.push(c[d]);break;case 3:n.push(t.header[d-l.s.c]);break;default:if(p===void 0)continue;n.push(F.utils.format_cell(p))}}return n}function re(e){const a={s:{c:0,r:0},e:{c:0,r:0}};let n=0,t=0,s=0;const l=e.length;for(n=0;t<l&&!((s=e.charCodeAt(t)-64)<1||s>26);++t)n=26*n+s;for(a.s.c=--n,n=0;t<l&&!((s=e.charCodeAt(t)-48)<0||s>9);++t)n=10*n+s;if(a.s.r=--n,t===l||e.charCodeAt(++t)===58)return a.e.c=a.s.c,a.e.r=a.s.r,a;for(n=0;t!==l&&!((s=e.charCodeAt(t)-64)<1||s>26);++t)n=26*n+s;for(a.e.c=--n,n=0;t!==l&&!((s=e.charCodeAt(t)-48)<0||s>9);++t)n=10*n+s;return a.e.r=--n,a}function te(e){return new Promise((a,n)=>{if(e.type==="application/json"){console.debug("Converting JSON file to JSON",e.name);const t=new FileReader;t.onload=function(s){try{const l=s.target?.result,i=JSON.parse(l);if(!Array.isArray(i))n(new Error("JSON file should contain an array of objects"));else{const c=i.length>0?Object.keys(i[0]):[];a({data:i,propertiesOrder:c})}}catch(l){console.error("Error parsing JSON file",l),n(l)}},t.readAsText(e)}else{console.debug("Converting Excel file to JSON",e.name);const t=new FileReader;t.onload=function(s){const l=new Uint8Array(s.target?.result),i=F.read(l,{type:"array",codepage:65001,cellDates:!0}),c=i.SheetNames[0],d=i.Sheets[c],p=F.utils.sheet_to_json(d),h=Te(d),b=p.map(De).map(z);a({data:b,propertiesOrder:h})},t.readAsArrayBuffer(e)}})}function De(e){return Object.keys(e).reduce((a,n)=>{try{a[n]=JSON.parse(e[n])}catch{a[n]=e[n]}return a},{})}function z(e){return Object.keys(e).reduce((a,n)=>{let t=a;const s=n.split(".");return s.forEach((l,i)=>{if(/^[\w]+\[\d+\]$/.test(l)){const c=l.slice(0,l.indexOf("[")),d=parseInt(l.slice(l.indexOf("[")+1,l.indexOf("]")));t[c]||(t[c]=[]),i!==s.length-1?(t[c][d]=t[c][d]||{},t=t[c][d]):t[c][d]=e[n]}else i!==s.length-1?(t[l]=t[l]||{},t=t[l]):t[l]=e[n]}),a},{})}function ae(e,a,n,t,s,l){const i=U(e);a&&delete i[a];const c=Object.entries(i).map(([h,y])=>{const b=H.getIn(n,h)??h,u=g.getPropertyInPath(t,b);if(!u)return{};const v=B(y,u);return{[b]:v}}).reduce((h,y)=>({...h,...y}),{}),d=g.mergeDeep(l??{},z(c));let p=a?e[a]:void 0;return typeof p=="string"?p=p.trim():typeof p=="number"||typeof p=="boolean"?p=p.toString():p instanceof Date?p=p.toISOString():p&&"toString"in p&&(p=p.toString()),{id:p,values:d,path:s}}function U(e,a=""){return Object.keys(e).reduce((n,t)=>{const s=a?`${a}.${t}`:t;return typeof e[t]=="object"&&!(e[t]instanceof Date)&&e[t]!==null&&!Array.isArray(e[t])?Object.assign(n,U(e[t],s)):n[s]=e[t],n},{})}function B(e,a){if(e===null)return null;if(a===void 0)return e;const n=g.resolveProperty({propertyOrBuilder:a});if(n===null)return e;const t=R.inferTypeFromValue(e),s=n.dataType;if(t==="array"&&s==="array"&&Array.isArray(e)&&n.of&&!g.isPropertyBuilder(n.of))return e.map(l=>B(l,n.of));if(t==="string"&&s==="number"&&typeof e=="string")return Number(e);if(t==="string"&&s==="array"&&typeof e=="string"&&n.of&&!g.isPropertyBuilder(n.of))return e.split(",").map(l=>B(l,n.of));if(t==="string"&&s==="boolean")return e==="true";if(t==="number"&&s==="boolean")return e===1;if(t==="boolean"&&s==="number")return e?1:0;if(t==="boolean"&&s==="string")return e?"true":"false";if(t==="number"&&s==="string"&&typeof e=="number")return e.toString();if(t==="string"&&s==="array"&&typeof e=="string")return e.split(",").map(l=>l.trim());if(t==="string"&&s==="date"&&typeof e=="string")try{return new Date(e)}catch{return e}else{if(t==="date"&&s==="string")return e instanceof Date&&e.toISOString();if(t==="number"&&s==="date"&&typeof e=="number")try{return new Date(e)}catch{return e}else if(t==="string"&&s==="reference"&&typeof e=="string"){const l=e.split("/").slice(0,-1).join("/"),i=e.split("/").slice(-1)[0];return new g.EntityReference(i,l)}else{if(t===s)return e;if(t==="array"&&s==="string"&&Array.isArray(e))return e.join(",")}}return e}function se(e){return typeof e=="number"?"number":typeof e=="string"?"string":typeof e=="boolean"?"boolean":e instanceof Date?"date":Array.isArray(e)?"array":"map"}function ne({importConfig:e,destinationProperties:a,buildPropertyView:n}){const t=e.headersMapping,s=e.headingsOrder,l=e.idColumn,i=e.originProperties;return r.jsxs(r.Fragment,{children:[r.jsx(Ne,{idColumn:l,headersMapping:t,onChange:c=>e.setIdColumn(c??void 0)}),r.jsx("div",{className:"h-4"}),r.jsxs(o.Table,{style:{tableLayout:"fixed"},children:[r.jsxs(o.TableHeader,{children:[r.jsx(o.TableCell,{header:!0,style:{width:"20%"},children:"Column in file"}),r.jsx(o.TableCell,{header:!0}),r.jsx(o.TableCell,{header:!0,style:{width:"75%"},children:"Map to Property"})]}),r.jsx(o.TableBody,{children:a&&s.map(c=>{const d=t[c],p=t[c],h=d?g.getPropertyInPath(a,d):null,y=g.getPropertyInPath(i,c),b=y?y.dataType==="array"&&typeof y.of=="object"?`${y.dataType} - ${y.of.dataType}`:y.dataType:void 0;return r.jsxs(o.TableRow,{style:{height:"90px"},children:[r.jsxs(o.TableCell,{style:{width:"20%"},children:[r.jsx(o.Typography,{variant:"body2",children:c}),y&&r.jsx(o.Typography,{variant:"caption",color:"secondary",children:b})]}),r.jsx(o.TableCell,{children:r.jsx(o.ChevronRightIcon,{})}),r.jsx(o.TableCell,{className:c===l?"text-center":void 0,style:{width:"75%"},children:n?.({isIdColumn:c===l,property:h,propertyKey:p,importKey:c})})]},c)})})]}),r.jsxs(o.ExpandablePanel,{title:"Default values",initiallyExpanded:!1,className:"p-4 mt-4",children:[r.jsx("div",{className:"text-sm text-slate-500 dark:text-slate-300 font-medium ml-3.5 mb-1",children:"You can select a default value for unmapped columns and empty values:"}),r.jsxs(o.Table,{style:{tableLayout:"fixed"},children:[r.jsxs(o.TableHeader,{children:[r.jsx(o.TableCell,{header:!0,style:{width:"30%"},children:"Property"}),r.jsx(o.TableCell,{header:!0}),r.jsx(o.TableCell,{header:!0,style:{width:"65%"},children:"Default value"})]}),r.jsx(o.TableBody,{children:a&&le(a).map(c=>{const d=g.getPropertyInPath(a,c);return typeof d!="object"||d===null||!["number","string","boolean","map"].includes(d.dataType)?null:r.jsxs(o.TableRow,{style:{height:"70px"},children:[r.jsx(o.TableCell,{style:{width:"20%"},children:r.jsx(o.Typography,{variant:"body2",children:c})}),r.jsx(o.TableCell,{children:r.jsx(o.ChevronRightIcon,{})}),r.jsx(o.TableCell,{className:c===l?"text-center":void 0,style:{width:"75%"},children:r.jsx(Oe,{property:d,defaultValue:H.getIn(e.defaultValues,c),onValueChange:p=>{const h=H.setIn(e.defaultValues,c,p);e.setDefaultValues(h)}})})]},c)})})]})]})]})}function le(e,a){return Object.entries(e).reduce((n,[t,s])=>{const l=a?`${a}.${t}`:t;if(typeof s!="function"&&s.dataType==="map"&&s.properties){const i=le(s.properties,l);return[...n,...i]}return[...n,l]},[])}function Ne({idColumn:e,headersMapping:a,onChange:n}){return r.jsx("div",{children:r.jsxs(o.Select,{size:"small",value:e??"",onChange:t=>{const s=t.target.value;n(s==="__none__"?null:s)},placeholder:"Autogenerate ID",renderValue:t=>r.jsx(o.Typography,{variant:"body2",children:t!=="__none__"?t:"Autogenerate ID"}),label:"Column that will be used as ID for each document",children:[r.jsx(o.SelectItem,{value:"__none__",children:"Autogenerate ID"}),Object.entries(a).map(([t,s])=>r.jsx(o.SelectItem,{value:t,children:t},t))]})})}function Oe({property:e,onValueChange:a,defaultValue:n}){return e.dataType==="string"?r.jsx(o.TextField,{size:"small",placeholder:"Default value",value:n??"",onChange:t=>a(t.target.value)}):e.dataType==="number"?r.jsx(o.TextField,{size:"small",type:"number",value:n??"",placeholder:"Default value",onChange:t=>a(t.target.value)}):e.dataType==="boolean"?r.jsx(o.BooleanSwitchWithLabel,{value:n??null,allowIndeterminate:!0,size:"small",onValueChange:t=>a(t===null?void 0:t),label:n===void 0?"Do not set value":n===!0?"Set value to true":"Set value to false"}):e.dataType==="date"?r.jsx(o.DateTimeField,{mode:e.mode??"date",size:"small",value:n??void 0,onChange:t=>{a(t)},clearable:!0}):null}function oe({onDataAdded:e}){const a=g.useSnackbarController();return r.jsx(o.FileUpload,{accept:{"text/*":[".csv",".xls",".xlsx"],"application/vnd.ms-excel":[".xls",".xlsx"],"application/msexcel":[".xls",".xlsx"],"application/vnd.ms-office":[".xls",".xlsx"],"application/xls":[".xls",".xlsx"],"application/x-xls":[".xls",".xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":[".xls",".xlsx"],"application/json":[".json"]},preventDropOnDocument:!0,size:"small",maxFiles:1,uploadDescription:r.jsxs(r.Fragment,{children:[r.jsx(o.UploadIcon,{}),"Drag and drop a file here or click to upload"]}),onFilesAdded:n=>{n.length>0&&te(n[0]).then(({data:t,propertiesOrder:s})=>{e(t,s)}).catch(t=>{console.error("Error parsing file",t),a.open({type:"error",message:t.message})})}})}function Ie({propertyKey:e,property:a,onEditClick:n,includeName:t=!0,onPropertyNameChanged:s,propertyTypeView:l}){const{propertyConfigs:i}=g.useCustomizationController(),c=a?g.getFieldConfig(a,i):null;return r.jsx(g.ErrorBoundary,{children:r.jsxs("div",{className:"flex flex-row w-full items-center",children:[r.jsx("div",{className:"mx-4",children:l??r.jsx(g.PropertyConfigBadge,{propertyConfig:c??void 0})}),r.jsx("div",{className:"w-full flex flex-col grow",children:r.jsxs("div",{className:"flex flex-row items-center gap-2",children:[t&&r.jsx(o.TextField,{size:"small",className:"text-base grow",value:a?.name??"",onChange:d=>{s&&e&&s(e,d.target.value)}}),r.jsx(o.IconButton,{onClick:n,size:"small",children:r.jsx(o.EditIcon,{size:"small"})})]})})]})})}function ie({path:e,importConfig:a,collection:n,onImportSuccess:t}){const[s,l]=f.useState(void 0),i=g.useDataSource(),c=f.useRef(!1),[d,p]=f.useState(0);function h(){c.current||(c.current=!0,ce(i,n,e,a.entities,0,25,p).then(()=>{t(n),c.current=!1}).catch(y=>{l(y),c.current=!1}))}return f.useEffect(()=>{h()},[]),s?r.jsxs(o.CenteredView,{className:"flex flex-col gap-4 items-center",children:[r.jsx(o.Typography,{variant:"h6",children:"Error saving data"}),r.jsx(o.Typography,{variant:"body2",color:"error",children:s.message}),r.jsx(o.Button,{onClick:h,variant:"outlined",children:"Retry"})]}):r.jsxs(o.CenteredView,{className:"flex flex-col gap-4 items-center",children:[r.jsx(o.CircularProgress,{}),r.jsx(o.Typography,{variant:"h6",children:"Saving data"}),r.jsxs(o.Typography,{variant:"body2",children:[d,"/",a.entities.length," entities saved"]}),r.jsx(o.Typography,{variant:"caption",children:"Do not close this tab or the import will be interrupted."})]})}function ce(e,a,n,t,s=0,l=25,i){console.debug("Saving imported data",s,l);const c=t.slice(s,s+l);return Promise.all(c.map(d=>e.saveEntity({path:n,values:d.values,entityId:d.id,collection:a,status:"new"}))).then(()=>s+l<t.length?(i(s+l),ce(e,a,n,t,s+l,l,i)):(i(t.length),Promise.resolve()))}function de({collection:e,path:a,collectionEntitiesCount:n,onAnalyticsEvent:t}){const s=g.useCustomizationController(),l=g.useSnackbarController(),[i,c]=f.useState(!1),[d,p]=f.useState("initial"),h=ee(),y=f.useCallback(()=>{c(!0),t?.("import_open"),p("initial")},[t]),b=f.useCallback(()=>{c(!1)},[c]),u=f.useCallback(()=>{t?.("import_mapping_complete"),p("preview")},[t]),v=f.useCallback(()=>{t?.("import_data_save"),p("import_data_saving")},[t]),N=async C=>{if(h.setImportData(C),C.length>0){const E=await R.buildEntityPropertiesFromData(C,se);h.setOriginProperties(E);const O=he(C,e?.properties);h.setHeadersMapping(O);const S=Object.keys(O)?.[0];(S?.includes("id")||S?.includes("key"))&&h.setIdColumn(S)}setTimeout(()=>{t?.("import_data_added"),p("mapping")},100)},I=g.resolveCollection({collection:e,path:a,fields:s.propertyConfigs}),k=g.getPropertiesWithPropertiesOrder(I.properties,I.propertiesOrder),$=Object.entries(k).flatMap(([C,E])=>pe(C,E,0)),ue=I.propertiesOrder??Object.keys(I.properties);return e.collectionGroup?null:r.jsxs(r.Fragment,{children:[r.jsx(o.Tooltip,{title:"Import",children:r.jsx(o.IconButton,{color:"primary",onClick:y,children:r.jsx(o.FileUploadIcon,{})})}),r.jsxs(o.Dialog,{open:i,fullWidth:d==="preview",fullHeight:d==="preview",maxWidth:d==="initial"?"lg":"7xl",children:[r.jsxs(o.DialogContent,{className:"flex flex-col gap-4 my-4",fullHeight:d==="preview",children:[d==="initial"&&r.jsxs(r.Fragment,{children:[r.jsx(o.Typography,{variant:"h6",children:"Import data"}),r.jsx(o.Typography,{variant:"body2",children:"Upload a CSV, Excel or JSON file and map it to your existing schema"}),r.jsx(oe,{onDataAdded:N})]}),d==="mapping"&&r.jsxs(r.Fragment,{children:[r.jsx(o.Typography,{variant:"h6",className:"ml-3.5",children:"Map fields"}),r.jsx(ne,{importConfig:h,destinationProperties:k,buildPropertyView:({isIdColumn:C,property:E,propertyKey:O,importKey:S})=>r.jsx(ke,{selectedPropertyKey:O??"",properties:k,propertiesAndLevel:$,isIdColumn:C,onIdSelected:()=>{h.setIdColumn(S)},onPropertySelected:A=>{t?.("import_mapping_field_updated");const xe=Object.entries(h.headersMapping).map(([T,_])=>_===A?{[T]:null}:T===S?{[T]:A}:{[T]:_}).reduce((T,_)=>({...T,..._}),{});h.setHeadersMapping(xe),A===h.idColumn&&h.setIdColumn(void 0)}})})]}),d==="preview"&&r.jsx(fe,{importConfig:h,properties:k,propertiesOrder:ue}),d==="import_data_saving"&&h&&r.jsx(ie,{importConfig:h,collection:e,path:a,onImportSuccess:C=>{b(),l.open({type:"info",message:"Data imported successfully"})}})]}),r.jsxs(o.DialogActions,{children:[d==="mapping"&&r.jsx(o.Button,{onClick:()=>p("initial"),variant:"text",children:"Back"}),d==="preview"&&r.jsx(o.Button,{onClick:()=>p("mapping"),variant:"text",children:"Back"}),r.jsx(o.Button,{onClick:b,variant:"text",children:"Cancel"}),d==="mapping"&&r.jsx(o.Button,{variant:"filled",onClick:u,children:"Next"}),d==="preview"&&r.jsx(o.Button,{variant:"filled",onClick:v,children:"Save data"})]})]})]})}const L="__internal_id__";function ke({selectedPropertyKey:e,properties:a,onPropertySelected:n,onIdSelected:t,propertiesAndLevel:s,isIdColumn:l}){const i=e?g.getPropertyInPath(a,e):null,c=f.useCallback(p=>p===L?r.jsx(o.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"}):!p||!i?r.jsx(o.Typography,{variant:"body2",color:"disabled",className:"p-4",children:"Do not import this property"}):r.jsx(W,{propertyKey:p,property:i}),[i]),d=p=>{p===L?(t(),n(null)):n(p==="__do_not_import"?null:p)};return r.jsxs(o.Select,{value:l?L:e??void 0,onValueChange:d,renderValue:c,children:[r.jsx(o.SelectItem,{value:"__do_not_import",children:r.jsx(o.Typography,{variant:"body2",color:"disabled",className:"p-4",children:"Do not import this property"})}),r.jsx(o.SelectItem,{value:L,children:r.jsx(o.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"})}),s.map(({property:p,level:h,propertyKey:y})=>r.jsx(o.SelectItem,{value:y,disabled:p.dataType==="map",children:r.jsx(W,{propertyKey:y,property:p,level:h})},y))]})}function pe(e,a,n){const t=[];return t.push({property:a,level:n,propertyKey:e}),a.dataType==="map"&&a.properties&&Object.entries(a.properties).forEach(([s,l])=>{t.push(...pe(`${e}.${s}`,l,n+1))}),t}function W({propertyKey:e,property:a,level:n=0}){const{propertyConfigs:t}=g.useCustomizationController(),s=g.getFieldConfig(a,t);return r.jsxs("div",{className:"flex flex-row w-full text-start items-center h-full",children:[new Array(n).fill(0).map((l,i)=>r.jsx("div",{className:o.cls(o.defaultBorderMixin,"ml-8 border-l h-12")},i)),r.jsx("div",{className:"m-4",children:r.jsx(o.Tooltip,{title:s?.name,children:r.jsx(g.PropertyConfigBadge,{propertyConfig:s})})}),r.jsxs("div",{className:"flex flex-col flex-grow p-2 pl-2",children:[r.jsx(o.Typography,{variant:"body1",component:"span",className:"flex-grow pr-2",children:a.name?a.name:" "}),r.jsx(o.Typography,{className:" pr-2",variant:"body2",component:"span",color:"secondary",children:e})]})]})}function fe({importConfig:e,properties:a,propertiesOrder:n}){f.useEffect(()=>{const s=e.importData.map(l=>ae(l,e.idColumn,e.headersMapping,a,"TEMP_PATH",e.defaultValues));e.setEntities(s)},[]);const t=g.useSelectionController();return r.jsx(g.EntityCollectionTable,{title:r.jsxs("div",{children:[r.jsx(o.Typography,{variant:"subtitle2",children:"Imported data preview"}),r.jsx(o.Typography,{variant:"caption",children:"Entities with the same id will be overwritten"})]}),tableController:{data:e.entities,dataLoading:!1,noMoreToLoad:!1},enablePopupIcon:!1,endAdornment:r.jsx("div",{className:"h-12"}),filterable:!1,sortable:!1,selectionController:t,properties:a})}function he(e,a){const n={};return e.filter(Boolean).forEach(t=>{Object.keys(t).forEach(s=>{const l=t[s];if(typeof l=="object"&&!Array.isArray(l)){const i=a?.[s],c=i&&"properties"in i?i.properties:void 0,d=he([l],c);Object.entries(d).forEach(([p,h])=>{n[`${s}.${p}`]=`${s}.${h}`})}if(!a)n[s]=s;else if(s in a)n[s]=s;else{const i=g.slugify(s);i in a?n[s]=i:n[s]=s}})}),n}function q({data:e,additionalData:a,properties:n,propertiesOrder:t,name:s,flattenArrays:l,additionalHeaders:i,exportType:c,dateExportType:d}){if(console.debug("Downloading export",{dataLength:e.length,properties:n,exportType:c,dateExportType:d}),c==="csv"){const p=l?g.getArrayValuesCount(e.map(v=>v.values)):{},h=Ee(n,t,i,p),y=ge(e,a,n,h,d),b=me(h.map(v=>v.label)),u=y.map(v=>me(v));Y([b,...u],`${s}.csv`,"text/csv")}else{const p=ye(e,a,n,d),h=JSON.stringify(p,null,2);Y([h],`${s}.json`,"application/json")}}function ge(e,a,n,t,s){const l=e.map(i=>({id:i.id,...G(i.values,n,"csv",s)}));return a&&a.forEach((i,c)=>{l[c]={...l[c],...i}}),l&&l.map(i=>t.map(c=>g.getValueInPath(i,c.key)))}function ye(e,a,n,t){const s=e.map(l=>({id:l.id,...G(l.values,n,"json",t)}));return a&&a.forEach((l,i)=>{s[i]={...s[i],...l}}),s}function Ee(e,a,n,t){const s=[{label:"id",key:"id"},...(a??Object.keys(e)).flatMap(l=>{const i=e[l];return i?t&&t[l]>1?Array.from({length:t[l]},(c,d)=>X(i,`${l}[${d}]`,"")).flat():X(i,l,""):(console.warn("Property not found",l,e),[])})];return n&&s.push(...n.map(l=>({label:l,key:l}))),s}function X(e,a,n=""){const t=n?`${n}.${a}`:a;return e.dataType==="map"&&e.properties?Object.entries(e.properties).map(([s,l])=>X(l,s,t)).flat():[{label:t,key:t}]}function V(e,a,n,t){let s;if(a.dataType==="map"&&a.properties)s=G(e,a.properties,n,t);else if(a.dataType==="array")a.of&&Array.isArray(e)?Array.isArray(a.of)?s=a.of.map((l,i)=>V(e[i],l,n,t)):a.of.dataType==="map"?s=n==="csv"?e.map(l=>JSON.stringify(l)):e.map(l=>V(l,a.of,n,t)):s=e.map(l=>V(l,a.of,n,t)):s=e;else if(a.dataType==="reference"&&e&&e.isEntityReference&&e.isEntityReference()){const l=e||void 0;s=l?l.pathWithId:null}else a.dataType==="date"&&e instanceof Date?s=e?t==="timestamp"?e.getTime():e.toISOString():null:s=e;return s}function G(e,a,n,t){const s=Object.entries(a).map(([l,i])=>{const c=e&&e[l],d=V(c,i,n,t);return d===void 0?{}:{[l]:d}}).reduce((l,i)=>({...l,...i}),{});return{...e,...s}}function me(e){return e.map(a=>a==null?"":Array.isArray(a)?'"'+JSON.stringify(a).replaceAll('"','\\"')+'"':'"'+String(a).replaceAll('"','""')+'"').join(",")+`\r
2
+ `}function Y(e,a,n){const t=new Blob(e,{type:n}),s=URL.createObjectURL(t),l=document.createElement("a");l.href=s,l.setAttribute("download",a),l.click()}const Ae=500;function be({collection:e,path:a,collectionEntitiesCount:n,onAnalyticsEvent:t,exportAllowed:s,notAllowedView:l}){const i=g.useCustomizationController(),c=typeof e.exportable=="object"?e.exportable:void 0,d=f.useRef(new Date),[p,h]=f.useState(!1),[y,b]=f.useState(!0),[u,v]=f.useState("csv"),[N,I]=f.useState("string"),k=g.useFireCMSContext(),$=g.useDataSource(),C=g.useNavigationController().resolveAliasesFrom(a),E=!s||s({collectionEntitiesCount:n,path:C,collection:e}),O=f.useMemo(()=>g.resolveCollection({collection:e,path:C,fields:i.propertyConfigs}),[e,C]),[S,A]=f.useState(!1),[xe,T]=f.useState(),[_,P]=f.useState(!1),Pe=f.useCallback(()=>{P(!0)},[P]),Q=f.useCallback(()=>{P(!1)},[P]),ve=f.useCallback(async w=>{const J=c?.additionalFields,D=O.additionalFields,Z=J?await Promise.all(w.map(async j=>(await Promise.all(J.map(async x=>({[x.key]:await x.builder({entity:j,context:k})})))).reduce((x,M)=>({...x,...M}),{}))):[],K=D?await Promise.all(w.map(async j=>(await Promise.all(D.map(async x=>x.value?{[x.key]:await x.value({entity:j,context:k})}:{}))).reduce((x,M)=>({...x,...M}),{}))):[];return[...Z,...K]},[c?.additionalFields]),Ce=f.useCallback(async(w,J)=>{t?.("export_collection",{collection:w.path}),A(!0),$.fetchCollection({path:C,collection:w}).then(async D=>{T(void 0);const Z=await ve(D),K=[...J?.additionalFields?.map(x=>x.key)??[],...w.additionalFields?.map(x=>x.key)??[]],j=p?D.map(x=>{const M=g.getDefaultValuesFor(w.properties);return{...x,values:{...M,...x.values}}}):D;q({data:j,additionalData:Z,properties:w.properties,propertiesOrder:w.propertiesOrder,name:w.name,flattenArrays:y,additionalHeaders:K,exportType:u,dateExportType:N}),t?.("export_collection_success",{collection:w.path})}).catch(D=>{console.error("Error loading export data",D),T(D)}).finally(()=>A(!1))},[t,$,C,ve,p,y,u,N]),je=f.useCallback(()=>{Ce(O,c),Q()},[Ce,O,c,Q]);return r.jsxs(r.Fragment,{children:[r.jsx(o.Tooltip,{title:"Export",children:r.jsx(o.IconButton,{color:"primary",onClick:Pe,children:r.jsx(o.GetAppIcon,{})})}),r.jsxs(o.Dialog,{open:_,onOpenChange:P,maxWidth:"xl",children:[r.jsxs(o.DialogContent,{className:"flex flex-col gap-4 my-4",children:[r.jsx(o.Typography,{variant:"h6",children:"Export data"}),r.jsx("div",{children:"Download the the content of this table as a CSV"}),n>Ae&&r.jsx(o.Alert,{color:"warning",children:r.jsxs("div",{children:["This collections has a large number of documents (",n,")."]})}),r.jsxs("div",{className:"flex flex-row gap-4",children:[r.jsxs("div",{className:"p-4 flex flex-col",children:[r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-csv",type:"radio",value:"csv",name:"exportType",checked:u==="csv",onChange:()=>v("csv"),className:o.cls(o.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsx("label",{htmlFor:"radio-csv",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:"CSV"})]}),r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-json",type:"radio",value:"json",name:"exportType",checked:u==="json",onChange:()=>v("json"),className:o.cls(o.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsx("label",{htmlFor:"radio-json",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:"JSON"})]})]}),r.jsxs("div",{className:"p-4 flex flex-col",children:[r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-timestamp",type:"radio",value:"timestamp",name:"dateExportType",checked:N==="timestamp",onChange:()=>I("timestamp"),className:o.cls(o.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsxs("label",{htmlFor:"radio-timestamp",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:["Dates as timestamps (",d.current.getTime(),")"]})]}),r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-string",type:"radio",value:"string",name:"dateExportType",checked:N==="string",onChange:()=>I("string"),className:o.cls(o.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsxs("label",{htmlFor:"radio-string",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:["Dates as strings (",d.current.toISOString(),")"]})]})]})]}),r.jsx(o.BooleanSwitchWithLabel,{size:"small",disabled:u!=="csv",value:y,onValueChange:b,label:"Flatten arrays"}),r.jsx(o.BooleanSwitchWithLabel,{size:"small",value:p,onValueChange:h,label:"Include undefined values"}),!E&&l]}),r.jsxs(o.DialogActions,{children:[S&&r.jsx(o.CircularProgress,{size:"small"}),r.jsx(o.Button,{onClick:Q,variant:"text",children:"Cancel"}),r.jsx(o.Button,{variant:"filled",onClick:je,disabled:S||!E,children:"Download"})]})]})]})}function _e(e){return f.useMemo(()=>({key:"import_export",collectionView:{CollectionActions:[de,be],collectionActionsProps:e}}),[e])}function Fe({data:e,properties:a,propertiesOrder:n}){const t=f.useRef(new Date),[s,l]=f.useState(!0),[i,c]=f.useState("csv"),[d,p]=f.useState("string"),[h,y]=f.useState(!1),b=f.useCallback(()=>{y(!0)},[y]),u=f.useCallback(()=>{y(!1)},[y]),v=f.useCallback(()=>{q({data:e,additionalData:[],properties:a,propertiesOrder:n,name:"export.csv",flattenArrays:s,additionalHeaders:[],exportType:i,dateExportType:d}),u()},[]);return r.jsxs(r.Fragment,{children:[r.jsx(o.Tooltip,{title:"Export",children:r.jsx(o.IconButton,{color:"primary",onClick:b,children:r.jsx(o.GetAppIcon,{})})}),r.jsxs(o.Dialog,{open:h,onOpenChange:y,maxWidth:"xl",children:[r.jsxs(o.DialogContent,{className:"flex flex-col gap-4 my-4",children:[r.jsx(o.Typography,{variant:"h6",children:"Export data"}),r.jsx("div",{children:"Download the the content of this table as a CSV"}),r.jsxs("div",{className:"flex flex-row gap-4",children:[r.jsxs("div",{className:"p-4 flex flex-col",children:[r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-csv",type:"radio",value:"csv",name:"exportType",checked:i==="csv",onChange:()=>c("csv"),className:o.cls(o.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsx("label",{htmlFor:"radio-csv",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:"CSV"})]}),r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-json",type:"radio",value:"json",name:"exportType",checked:i==="json",onChange:()=>c("json"),className:o.cls(o.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsx("label",{htmlFor:"radio-json",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:"JSON"})]})]}),r.jsxs("div",{className:"p-4 flex flex-col",children:[r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-timestamp",type:"radio",value:"timestamp",name:"dateExportType",checked:d==="timestamp",onChange:()=>p("timestamp"),className:o.cls(o.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsxs("label",{htmlFor:"radio-timestamp",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:["Dates as timestamps (",t.current.getTime(),")"]})]}),r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-string",type:"radio",value:"string",name:"dateExportType",checked:d==="string",onChange:()=>p("string"),className:o.cls(o.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsxs("label",{htmlFor:"radio-string",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:["Dates as strings (",t.current.toISOString(),")"]})]})]})]}),r.jsx(o.BooleanSwitchWithLabel,{size:"small",disabled:i!=="csv",value:s,onValueChange:l,label:"Flatten arrays"})]}),r.jsxs(o.DialogActions,{children:[r.jsx(o.Button,{onClick:u,variant:"text",children:"Cancel"}),r.jsx(o.Button,{variant:"filled",onClick:v,children:"Download"})]})]})]})}m.BasicExportAction=Fe,m.DataNewPropertiesMapping=ne,m.ExportCollectionAction=be,m.ImportCollectionAction=de,m.ImportDataPreview=fe,m.ImportFileUpload=oe,m.ImportNewPropertyFieldPreview=Ie,m.ImportSaveInProgress=ie,m.PropertySelectEntry=W,m.convertDataToEntity=ae,m.convertFileToJson=te,m.downloadBlob=Y,m.downloadEntitiesExport=q,m.flattenEntry=U,m.getEntityCSVExportableData=ge,m.getEntityJsonExportableData=ye,m.getInferenceType=se,m.processValueMapping=B,m.unflattenObject=z,m.useImportConfig=ee,m.useImportExportPlugin=_e,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
3
3
  //# sourceMappingURL=index.umd.js.map