@firecms/data_import_export 3.0.0-canary.42 → 3.0.0-canary.43

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