@firecms/data_import_export 3.0.0-beta.2-pre.1 → 3.0.0-beta.2-pre.3
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,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")):typeof define=="function"&&define.amd?define(["exports","react","react/jsx-runtime","@firecms/core","@firecms/ui","@firecms/schema_inference","xlsx"],f):(m=typeof globalThis<"u"?globalThis:m||self,f(m.FireCMS={},m.React,m.jsxRuntime,m.core,m.ui,m.schema_inference,m.XLSX))})(this,function(m,f,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]=f.useState(!1),[a,t]=f.useState(),[s,o]=f.useState([]),[i,c]=f.useState([]),[p,d]=f.useState({}),[g,y]=f.useState({});return{inUse:e,setInUse:n,idColumn:a,setIdColumn:t,entities:i,setEntities:c,importData:s,setImportData:o,headersMapping:p,setHeadersMapping:d,originProperties:g,setOriginProperties:y}};function Y(e){return new Promise((n,a)=>{if(e.type==="application/json"){const t=new FileReader;t.onload=function(s){const o=s.target?.result,i=JSON.parse(o);n(i)},t.readAsText(e)}else{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}),c=i.SheetNames[0],p=i.Sheets[c],y=G.utils.sheet_to_json(p).map(he).map(L);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 L(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 c=o.slice(0,o.indexOf("[")),p=parseInt(o.slice(o.indexOf("[")+1,o.indexOf("]")));t[c]||(t[c]=[]),i!==s.length-1?(t[c][p]=t[c][p]||{},t=t[c][p]):t[c][p]=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=H(e);n&&delete i[n];const c=Object.entries(i).map(([d,g])=>{const y=a[d]??d;if(!h.getPropertyInPath(t,y))return{};const b=s[y];let T=g;return b&&(T=j(g,b)),{[y]:T}}).reduce((d,g)=>({...d,...g}),{}),p=L(c);return{id:n?e[n]:void 0,values:p,path:o}}function H(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,H(e[t],s)):a[s]=e[t],a},{})}function j(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=>j(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=>j(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 c=s?`${s}.${i}`:i,p=h.getPropertyInPath(t,i),d=h.getPropertyInPath(e,c);if(p){if(p.dataType==="map"&&p.properties){const g=a(p.properties,c);Object.keys(g).forEach(y=>{o[`${c}.${y}`]=g[y]});return}if(d){const g=d.dataType,y=p.dataType;let x,b;p.dataType==="array"&&p.of&&(b=p.of.dataType),d?.dataType==="array"&&d?.of&&(x=d.of.dataType),(g!==y||x!==b)&&(o[i]={from:g,to:y,fromSubtype:x,toSubtype:b})}}}),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,c])=>{const p=n[i],d=c?h.getPropertyInPath(t,c):null,g=h.getPropertyInPath(a,i),y=g?g.dataType==="array"&&typeof g.of=="object"?`${g.dataType} - ${g.of.dataType}`:g.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}),g&&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:d,propertyKey:p,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=>{a(t.target.value)},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:"",children:"Autogenerate ID"}),Object.entries(n).map(([t,s])=>r.jsx(l.SelectItem,{value:t,children:t},t))]})})}function te({onDataAdded:e}){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:n=>{n.length>0&&Y(n[0]).then(a=>{e(a)})}})}function me({propertyKey:e,property:n,onEditClick:a,includeName:t=!0,onPropertyNameChanged:s,propertyTypeView:o}){const{propertyConfigs:i}=h.useCustomizationController(),c=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: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(l.TextField,{size:"small",className:"text-base grow",value:n?.name??"",onChange:p=>{s&&e&&s(e,p.target.value)}}),r.jsx(l.IconButton,{onClick:a,size:"small",children:r.jsx(l.EditIcon,{size:"small"})})]})})]})})}function re({importConfig:e,collection:n,onImportSuccess:a}){const t=h.useDataSource(),s=f.useRef(!1),[o,i]=f.useState(0);function c(){s.current||(s.current=!0,ne(t,n,e.entities,0,25,i).then(()=>{a(n),s.current=!1}))}return f.useEffect(()=>{c()},[]),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:[o,"/",e.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=0,s=25,o){console.debug("Saving imported data",t,s);const i=a.slice(t,t+s);return Promise.all(i.map(c=>e.saveEntity({path:n.path,values:c.values,entityId:c.id,collection:n,status:"new"}))).then(()=>t+s<a.length?(o(t+s),ne(e,n,a,t+s,s,o)):(o(a.length),Promise.resolve()))}function be({collection:e,path:n,collectionEntitiesCount:a}){const t=h.useCustomizationController(),s=h.useSnackbarController(),[o,i]=f.useState(!1),[c,p]=f.useState("initial"),d=Q(),g=f.useCallback(()=>{i(!0),p("initial")},[i]),y=f.useCallback(()=>{i(!1)},[i]),x=f.useCallback(()=>{p("preview")},[]),b=f.useCallback(()=>{p("import_data_saving")},[]),T=async u=>{if(d.setImportData(u),u.length>0){const O=await pe.buildEntityPropertiesFromData(u,K);d.setOriginProperties(O);const N=oe(u);d.setHeadersMapping(N);const P=Object.keys(N)?.[0];if(P?.includes("id")||P?.includes("key")){const w=P;d.setIdColumn(w)}}setTimeout(()=>{p("mapping")},100)},D=h.resolveCollection({collection:e,path:n,fields:t.propertyConfigs}),F=h.getPropertiesWithPropertiesOrder(D.properties,D.propertiesOrder),I=Object.entries(F).flatMap(([u,O])=>ae(u,O,0)),_=D.propertiesOrder??Object.keys(D.properties);return e.collectionGroup?null:r.jsxs(r.Fragment,{children:[r.jsx(l.Tooltip,{title:"Import",children:r.jsx(l.IconButton,{color:"primary",onClick:g,children:r.jsx(l.FileUploadIcon,{})})}),r.jsxs(l.Dialog,{open:o,fullWidth:c==="preview",fullHeight:c==="preview",maxWidth:c==="initial"?"lg":"7xl",children:[r.jsxs(l.DialogContent,{className:"flex flex-col gap-4 my-4",fullHeight:c==="preview",children:[c==="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(te,{onDataAdded:T})]}),c==="mapping"&&r.jsxs(r.Fragment,{children:[r.jsx(l.Typography,{variant:"h6",children:"Map fields"}),r.jsx(ee,{headersMapping:d.headersMapping,idColumn:d.idColumn,originProperties:d.originProperties,destinationProperties:F,onIdPropertyChanged:u=>d.setIdColumn(u),buildPropertyView:({isIdColumn:u,property:O,propertyKey:N,importKey:P})=>r.jsx(ue,{selectedPropertyKey:N??"",properties:F,propertiesAndLevel:I,isIdColumn:u,onIdSelected:()=>{d.setIdColumn(P)},onPropertySelected:w=>{const z=Object.entries(d.headersMapping).map(([C,A])=>A===w?{[C]:null}:C===P?{[C]:w}:{[C]:A}).reduce((C,A)=>({...C,...A}),{});d.setHeadersMapping(z),w===d.idColumn&&d.setIdColumn(void 0)}})})]}),c==="preview"&&r.jsx(xe,{importConfig:d,properties:F,propertiesOrder:_}),c==="import_data_saving"&&d&&r.jsx(re,{importConfig:d,collection:e,onImportSuccess:u=>{y(),s.open({type:"info",message:"Data imported successfully"})}})]}),r.jsxs(l.DialogActions,{children:[c==="mapping"&&r.jsx(l.Button,{onClick:()=>p("initial"),variant:"text",children:"Back"}),c==="preview"&&r.jsx(l.Button,{onClick:()=>p("mapping"),variant:"text",children:"Back"}),r.jsx(l.Button,{onClick:y,variant:"text",children:"Cancel"}),c==="mapping"&&r.jsx(l.Button,{variant:"filled",onClick:x,children:"Next"}),c==="preview"&&r.jsx(l.Button,{variant:"filled",onClick:b,children:"Save data"})]})]})]})}const M="__internal_id__";function ue({selectedPropertyKey:e,properties:n,onPropertySelected:a,onIdSelected:t,propertiesAndLevel:s,isIdColumn:o}){const i=e?h.getPropertyInPath(n,e):null,c=f.useCallback(d=>d===M?r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"}):!d||!i?r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Do not import this property"}):r.jsx(se,{propertyKey:d,property:i}),[i]),p=f.useCallback(d=>{d===M?(t(),a(null)):a(d===""?null:d)},[]);return r.jsxs(l.Select,{value:o?M:e??void 0,onValueChange:p,renderValue:c,children:[r.jsx(l.SelectItem,{value:"",children:r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Do not import this property"})}),r.jsx(l.SelectItem,{value:M,children:r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"})}),s.map(({property:d,level:g,propertyKey:y})=>r.jsx(l.SelectItem,{value:y,disabled:d.dataType==="map",children:r.jsx(se,{propertyKey:y,property:d,level:g})},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}){f.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){const n={};return e.filter(Boolean).forEach(a=>{Object.keys(a).forEach(t=>{const s=a[t];typeof s=="object"&&!Array.isArray(s)&&Object.entries(oe([s])).forEach(([o,i])=>{n[`${t}.${o}`]=`${t}.${i}`}),n[t]=t})}),n}function Ce(e,n,a,t,s,o,i){console.debug("Downloading export",{dataLength:e.length,collection:a,exportType:o,dateExportType:i});const c=a.properties;if(o==="csv"){const p=t?h.getArrayValuesCount(e.map(b=>b.values)):{},d=Se(c,s,p),g=ve(e,n,c,d,i),y=le(d.map(b=>b.label)),x=g.map(b=>le(b));ie([y,...x],`${a.name}.csv`,"text/csv")}else{const p=we(e,n,c,i),d=JSON.stringify(p,null,2);ie([d],`${a.name}.json`,"application/json")}}function ve(e,n,a,t,s){const o=e.map(i=>({id:i.id,...U(i.values,a,"csv",s)}));return n&&n.forEach((i,c)=>{o[c]={...o[c],...i}}),o&&o.map(i=>t.map(c=>h.getValueInPath(i,c.key)))}function we(e,n,a,t){const s=e.map(o=>({id:o.id,...U(o.values,a,"json",t)}));return n&&n.forEach((o,i)=>{s[i]={...s[i],...o}}),s}function Se(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,c)=>J(o,`${s}[${c}]`,"")).flat():J(o,s,""))];return n&&t.push(...n.map(s=>({label:s,key:s}))),t}function J(e,n,a=""){const t=a?`${a}.${n}`:n;return e.dataType==="map"&&e.properties?Object.entries(e.properties).map(([s,o])=>J(o,s,t)).flat():[{label:t,key:t}]}function B(e,n,a,t){let s;if(n.dataType==="map"&&n.properties)s=U(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)=>B(e[i],o,a,t)):n.of.dataType==="map"?s=a==="csv"?e.map(o=>JSON.stringify(o)):e.map(o=>B(o,n.of,a,t)):s=e.map(o=>B(o,n.of,a,t)):s=e;else if(n.dataType==="reference"&&e instanceof h.EntityReference){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 U(e,n,a,t){const s=Object.entries(n).map(([o,i])=>{const c=e&&e[o],p=B(c,i,a,t);return p===void 0?{}:{[o]:p}}).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
|
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")):typeof define=="function"&&define.amd?define(["exports","react","react/jsx-runtime","@firecms/core","@firecms/ui","@firecms/schema_inference","xlsx"],f):(m=typeof globalThis<"u"?globalThis:m||self,f(m.FireCMS={},m.React,m.jsxRuntime,m.core,m.ui,m.schema_inference,m.XLSX))})(this,function(m,f,t,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 r=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>e[a]})}}return n.default=e,Object.freeze(n)}const G=ge(fe),Q=()=>{const[e,n]=f.useState(!1),[a,r]=f.useState(),[s,o]=f.useState([]),[i,c]=f.useState([]),[p,d]=f.useState({}),[g,y]=f.useState({});return{inUse:e,setInUse:n,idColumn:a,setIdColumn:r,entities:i,setEntities:c,importData:s,setImportData:o,headersMapping:p,setHeadersMapping:d,originProperties:g,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 r=new FileReader;r.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)},r.readAsText(e)}else{console.debug("Converting Excel file to JSON",e.name);const r=new FileReader;r.onload=function(s){const o=new Uint8Array(s.target?.result),i=G.read(o,{type:"array",codepage:65001,cellDates:!0}),c=i.SheetNames[0],p=i.Sheets[c],y=G.utils.sheet_to_json(p).map(he).map(L);n(y)},r.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 L(e){return Object.keys(e).reduce((n,a)=>{let r=n;const s=a.split(".");return s.forEach((o,i)=>{if(/^[\w]+\[\d+\]$/.test(o)){const c=o.slice(0,o.indexOf("[")),p=parseInt(o.slice(o.indexOf("[")+1,o.indexOf("]")));r[c]||(r[c]=[]),i!==s.length-1?(r[c][p]=r[c][p]||{},r=r[c][p]):r[c][p]=e[a]}else i!==s.length-1?(r[o]=r[o]||{},r=r[o]):r[o]=e[a]}),n},{})}function Z(e,n,a,r,s,o){const i=J(e);n&&delete i[n];const c=Object.entries(i).map(([d,g])=>{const y=a[d]??d;if(!h.getPropertyInPath(r,y))return{};const b=s[y];let T=g;return b&&(T=j(g,b)),{[y]:T}}).reduce((d,g)=>({...d,...g}),{}),p=L(c);return{id:n?e[n]:void 0,values:p,path:o}}function J(e,n=""){return Object.keys(e).reduce((a,r)=>{const s=n?`${n}.${r}`:r;return typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])?Object.assign(a,J(e[r],s)):a[s]=e[r],a},{})}function j(e,n){if(n===void 0)return e;const{from:a,to:r}=n;if(a==="array"&&r==="array"&&n.fromSubtype&&n.toSubtype&&Array.isArray(e))return e.map(s=>j(s,{from:n.fromSubtype,to:n.toSubtype}));if(a==="string"&&r==="number"&&typeof e=="string")return Number(e);if(a==="string"&&r==="array"&&n.toSubtype&&typeof e=="string")return e.split(",").map(s=>j(s,{from:"string",to:n.toSubtype}));if(a==="string"&&r==="boolean")return e==="true";if(a==="number"&&r==="boolean")return e===1;if(a==="boolean"&&r==="number")return e?1:0;if(a==="boolean"&&r==="string")return e?"true":"false";if(a==="number"&&r==="string"&&typeof e=="number")return e.toString();if(a==="string"&&r==="array"&&typeof e=="string")return e.split(",").map(s=>s.trim());if(a==="string"&&r==="date"&&typeof e=="string")try{return new Date(e)}catch{return e}else{if(a==="date"&&r==="string")return e instanceof Date&&e.toISOString();if(a==="number"&&r==="date"&&typeof e=="number")try{return new Date(e)}catch{return e}else if(a==="string"&&r==="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===r)return e;if(a==="array"&&r==="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(r,s){const o={};return Object.keys(r).forEach(i=>{const c=s?`${s}.${i}`:i,p=h.getPropertyInPath(r,i),d=h.getPropertyInPath(e,c);if(p){if(p.dataType==="map"&&p.properties){const g=a(p.properties,c);Object.keys(g).forEach(y=>{o[`${c}.${y}`]=g[y]});return}if(d){const g=d.dataType,y=p.dataType;let x,b;p.dataType==="array"&&p.of&&(b=p.of.dataType),d?.dataType==="array"&&d?.of&&(x=d.of.dataType),(g!==y||x!==b)&&(o[i]={from:g,to:y,fromSubtype:x,toSubtype:b})}}}),o}return a(n)}function ee({idColumn:e,headersMapping:n,originProperties:a,destinationProperties:r,onIdPropertyChanged:s,buildPropertyView:o}){return t.jsxs(t.Fragment,{children:[t.jsx(ye,{idColumn:e,headersMapping:n,onChange:s}),t.jsxs(l.Table,{style:{tableLayout:"fixed"},children:[t.jsxs(l.TableHeader,{children:[t.jsx(l.TableCell,{header:!0,style:{width:"20%"},children:"Column in file"}),t.jsx(l.TableCell,{header:!0}),t.jsx(l.TableCell,{header:!0,style:{width:"75%"},children:"Property"})]}),t.jsx(l.TableBody,{children:r&&Object.entries(n).map(([i,c])=>{const p=n[i],d=c?h.getPropertyInPath(r,c):null,g=h.getPropertyInPath(a,i),y=g?g.dataType==="array"&&typeof g.of=="object"?`${g.dataType} - ${g.of.dataType}`:g.dataType:void 0;return t.jsxs(l.TableRow,{style:{height:"90px"},children:[t.jsxs(l.TableCell,{style:{width:"20%"},children:[t.jsx(l.Typography,{variant:"body2",children:i}),g&&t.jsx(l.Typography,{variant:"caption",color:"secondary",children:y})]}),t.jsx(l.TableCell,{children:t.jsx(l.ChevronRightIcon,{})}),t.jsx(l.TableCell,{className:i===e?"text-center":void 0,style:{width:"75%"},children:o?.({isIdColumn:i===e,property:d,propertyKey:p,importKey:i})})]},i)})})]})]})}function ye({idColumn:e,headersMapping:n,onChange:a}){return t.jsx("div",{children:t.jsxs(l.Select,{size:"small",value:e??"",onChange:r=>{a(r.target.value)},renderValue:r=>t.jsx(l.Typography,{variant:"body2",children:r!==""?r:"Autogenerate ID"}),label:"Column that will be used as ID for each document",children:[t.jsx(l.SelectItem,{value:"",children:"Autogenerate ID"}),Object.entries(n).map(([r,s])=>t.jsx(l.SelectItem,{value:r,children:r},r))]})})}function re({onDataAdded:e}){const n=h.useSnackbarController();return t.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:t.jsxs(t.Fragment,{children:[t.jsx(l.UploadIcon,{}),"Drag and drop a file here or click to upload"]}),onFilesAdded:a=>{a.length>0&&Y(a[0]).then(r=>{e(r)}).catch(r=>{console.error("Error parsing file",r),n.open({type:"error",message:r.message})})}})}function me({propertyKey:e,property:n,onEditClick:a,includeName:r=!0,onPropertyNameChanged:s,propertyTypeView:o}){const{propertyConfigs:i}=h.useCustomizationController(),c=n?h.getFieldConfig(n,i):null;return t.jsx(h.ErrorBoundary,{children:t.jsxs("div",{className:"flex flex-row w-full items-center",children:[t.jsx("div",{className:"mx-4",children:o??t.jsx(h.PropertyConfigBadge,{propertyConfig:c??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(l.TextField,{size:"small",className:"text-base grow",value:n?.name??"",onChange:p=>{s&&e&&s(e,p.target.value)}}),t.jsx(l.IconButton,{onClick:a,size:"small",children:t.jsx(l.EditIcon,{size:"small"})})]})})]})})}function te({importConfig:e,collection:n,onImportSuccess:a}){const r=h.useDataSource(),s=f.useRef(!1),[o,i]=f.useState(0);function c(){s.current||(s.current=!0,ne(r,n,e.entities,0,25,i).then(()=>{a(n),s.current=!1}))}return f.useEffect(()=>{c()},[]),t.jsxs(l.CenteredView,{className:"flex flex-col gap-4 items-center",children:[t.jsx(l.CircularProgress,{}),t.jsx(l.Typography,{variant:"h6",children:"Saving data"}),t.jsxs(l.Typography,{variant:"body2",children:[o,"/",e.entities.length," entities saved"]}),t.jsx(l.Typography,{variant:"caption",children:"Do not close this tab or the import will be interrupted."})]})}function ne(e,n,a,r=0,s=25,o){console.debug("Saving imported data",r,s);const i=a.slice(r,r+s);return Promise.all(i.map(c=>e.saveEntity({path:n.path,values:c.values,entityId:c.id,collection:n,status:"new"}))).then(()=>r+s<a.length?(o(r+s),ne(e,n,a,r+s,s,o)):(o(a.length),Promise.resolve()))}function be({collection:e,path:n,collectionEntitiesCount:a}){const r=h.useCustomizationController(),s=h.useSnackbarController(),[o,i]=f.useState(!1),[c,p]=f.useState("initial"),d=Q(),g=f.useCallback(()=>{i(!0),p("initial")},[i]),y=f.useCallback(()=>{i(!1)},[i]),x=f.useCallback(()=>{p("preview")},[]),b=f.useCallback(()=>{p("import_data_saving")},[]),T=async u=>{if(d.setImportData(u),u.length>0){const O=await pe.buildEntityPropertiesFromData(u,K);d.setOriginProperties(O);const N=oe(u);d.setHeadersMapping(N);const E=Object.keys(N)?.[0];if(E?.includes("id")||E?.includes("key")){const w=E;d.setIdColumn(w)}}setTimeout(()=>{p("mapping")},100)},D=h.resolveCollection({collection:e,path:n,fields:r.propertyConfigs}),F=h.getPropertiesWithPropertiesOrder(D.properties,D.propertiesOrder),I=Object.entries(F).flatMap(([u,O])=>ae(u,O,0)),_=D.propertiesOrder??Object.keys(D.properties);return e.collectionGroup?null:t.jsxs(t.Fragment,{children:[t.jsx(l.Tooltip,{title:"Import",children:t.jsx(l.IconButton,{color:"primary",onClick:g,children:t.jsx(l.FileUploadIcon,{})})}),t.jsxs(l.Dialog,{open:o,fullWidth:c==="preview",fullHeight:c==="preview",maxWidth:c==="initial"?"lg":"7xl",children:[t.jsxs(l.DialogContent,{className:"flex flex-col gap-4 my-4",fullHeight:c==="preview",children:[c==="initial"&&t.jsxs(t.Fragment,{children:[t.jsx(l.Typography,{variant:"h6",children:"Import data"}),t.jsx(l.Typography,{variant:"body2",children:"Upload a CSV, Excel or JSON file and map it to your existing schema"}),t.jsx(re,{onDataAdded:T})]}),c==="mapping"&&t.jsxs(t.Fragment,{children:[t.jsx(l.Typography,{variant:"h6",children:"Map fields"}),t.jsx(ee,{headersMapping:d.headersMapping,idColumn:d.idColumn,originProperties:d.originProperties,destinationProperties:F,onIdPropertyChanged:u=>d.setIdColumn(u),buildPropertyView:({isIdColumn:u,property:O,propertyKey:N,importKey:E})=>t.jsx(ue,{selectedPropertyKey:N??"",properties:F,propertiesAndLevel:I,isIdColumn:u,onIdSelected:()=>{d.setIdColumn(E)},onPropertySelected:w=>{const z=Object.entries(d.headersMapping).map(([C,A])=>A===w?{[C]:null}:C===E?{[C]:w}:{[C]:A}).reduce((C,A)=>({...C,...A}),{});d.setHeadersMapping(z),w===d.idColumn&&d.setIdColumn(void 0)}})})]}),c==="preview"&&t.jsx(xe,{importConfig:d,properties:F,propertiesOrder:_}),c==="import_data_saving"&&d&&t.jsx(te,{importConfig:d,collection:e,onImportSuccess:u=>{y(),s.open({type:"info",message:"Data imported successfully"})}})]}),t.jsxs(l.DialogActions,{children:[c==="mapping"&&t.jsx(l.Button,{onClick:()=>p("initial"),variant:"text",children:"Back"}),c==="preview"&&t.jsx(l.Button,{onClick:()=>p("mapping"),variant:"text",children:"Back"}),t.jsx(l.Button,{onClick:y,variant:"text",children:"Cancel"}),c==="mapping"&&t.jsx(l.Button,{variant:"filled",onClick:x,children:"Next"}),c==="preview"&&t.jsx(l.Button,{variant:"filled",onClick:b,children:"Save data"})]})]})]})}const M="__internal_id__";function ue({selectedPropertyKey:e,properties:n,onPropertySelected:a,onIdSelected:r,propertiesAndLevel:s,isIdColumn:o}){const i=e?h.getPropertyInPath(n,e):null,c=f.useCallback(d=>d===M?t.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"}):!d||!i?t.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Do not import this property"}):t.jsx(se,{propertyKey:d,property:i}),[i]),p=f.useCallback(d=>{d===M?(r(),a(null)):a(d===""?null:d)},[]);return t.jsxs(l.Select,{value:o?M:e??void 0,onValueChange:p,renderValue:c,children:[t.jsx(l.SelectItem,{value:"",children:t.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Do not import this property"})}),t.jsx(l.SelectItem,{value:M,children:t.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"})}),s.map(({property:d,level:g,propertyKey:y})=>t.jsx(l.SelectItem,{value:y,disabled:d.dataType==="map",children:t.jsx(se,{propertyKey:y,property:d,level:g})},y))]})}function ae(e,n,a){const r=[];return r.push({property:n,level:a,propertyKey:e}),n.dataType==="map"&&n.properties&&Object.entries(n.properties).forEach(([s,o])=>{r.push(...ae(`${e}.${s}`,o,a+1))}),r}function se({propertyKey:e,property:n,level:a=0}){const{propertyConfigs:r}=h.useCustomizationController(),s=h.getFieldConfig(n,r);return t.jsxs("div",{className:"flex flex-row w-full text-start items-center h-full",children:[new Array(a).fill(0).map((o,i)=>t.jsx("div",{className:l.cn(l.defaultBorderMixin,"ml-8 border-l h-12")},i)),t.jsx("div",{className:"m-4",children:t.jsx(l.Tooltip,{title:s?.name,children:t.jsx(h.PropertyConfigBadge,{propertyConfig:s})})}),t.jsxs("div",{className:"flex flex-col flex-grow p-2 pl-2",children:[t.jsx(l.Typography,{variant:"body1",component:"span",className:"flex-grow pr-2",children:n.name?n.name:" "}),t.jsx(l.Typography,{className:" pr-2",variant:"body2",component:"span",color:"secondary",children:e})]})]})}function xe({importConfig:e,properties:n,propertiesOrder:a}){f.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 r=h.useSelectionController();return t.jsx(h.EntityCollectionTable,{title:t.jsxs("div",{children:[t.jsx(l.Typography,{variant:"subtitle2",children:"Imported data preview"}),t.jsx(l.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,displayedColumnIds:a.map(s=>({key:s,disabled:!1})),properties:n})}function oe(e){const n={};return e.filter(Boolean).forEach(a=>{Object.keys(a).forEach(r=>{const s=a[r];typeof s=="object"&&!Array.isArray(s)&&Object.entries(oe([s])).forEach(([o,i])=>{n[`${r}.${o}`]=`${r}.${i}`}),n[r]=r})}),n}function Ce(e,n,a,r,s,o,i){console.debug("Downloading export",{dataLength:e.length,collection:a,exportType:o,dateExportType:i});const c=a.properties;if(o==="csv"){const p=r?h.getArrayValuesCount(e.map(b=>b.values)):{},d=Se(c,s,p),g=ve(e,n,c,d,i),y=le(d.map(b=>b.label)),x=g.map(b=>le(b));ie([y,...x],`${a.name}.csv`,"text/csv")}else{const p=we(e,n,c,i),d=JSON.stringify(p,null,2);ie([d],`${a.name}.json`,"application/json")}}function ve(e,n,a,r,s){const o=e.map(i=>({id:i.id,...U(i.values,a,"csv",s)}));return n&&n.forEach((i,c)=>{o[c]={...o[c],...i}}),o&&o.map(i=>r.map(c=>h.getValueInPath(i,c.key)))}function we(e,n,a,r){const s=e.map(o=>({id:o.id,...U(o.values,a,"json",r)}));return n&&n.forEach((o,i)=>{s[i]={...s[i],...o}}),s}function Se(e,n,a){const r=[{label:"id",key:"id"},...Object.entries(e).flatMap(([s,o])=>a&&a[s]>1?Array.from({length:a[s]},(i,c)=>H(o,`${s}[${c}]`,"")).flat():H(o,s,""))];return n&&r.push(...n.map(s=>({label:s,key:s}))),r}function H(e,n,a=""){const r=a?`${a}.${n}`:n;return e.dataType==="map"&&e.properties?Object.entries(e.properties).map(([s,o])=>H(o,s,r)).flat():[{label:r,key:r}]}function B(e,n,a,r){let s;if(n.dataType==="map"&&n.properties)s=U(e,n.properties,a,r);else if(n.dataType==="array")n.of&&Array.isArray(e)?Array.isArray(n.of)?s=n.of.map((o,i)=>B(e[i],o,a,r)):n.of.dataType==="map"?s=a==="csv"?e.map(o=>JSON.stringify(o)):e.map(o=>B(o,n.of,a,r)):s=e.map(o=>B(o,n.of,a,r)):s=e;else if(n.dataType==="reference"&&e instanceof h.EntityReference){const o=e||void 0;s=o?o.pathWithId:null}else n.dataType==="date"&&e instanceof Date?s=e?r==="timestamp"?e.getTime():e.toISOString():null:s=e;return s}function U(e,n,a,r){const s=Object.entries(n).map(([o,i])=>{const c=e&&e[o],p=B(c,i,a,r);return p===void 0?{}:{[o]:p}}).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 r=new Blob(e,{type:a}),s=URL.createObjectURL(r),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:r,notAllowedView:s}){const o=h.useCustomizationController(),i=typeof e.exportable=="object"?e.exportable:void 0,c=f.useRef(new Date),[p,d]=f.useState(!0),[g,y]=f.useState("csv"),[x,b]=f.useState("string"),T=h.useFireCMSContext(),D=h.useDataSource(),I=h.useNavigationController().resolveAliasesFrom(n),_=!r||r({collectionEntitiesCount:a,path:I,collection:e}),u=f.useMemo(()=>h.resolveCollection({collection:e,path:I,fields:o.propertyConfigs}),[e,I]),[O,N]=f.useState(!1),[E,w]=f.useState(),[z,C]=f.useState(!1),A=f.useCallback(()=>{C(!0)},[C]),V=f.useCallback(()=>{C(!1)},[C]),ce=f.useCallback(async k=>{const $=i?.additionalFields,S=u.additionalFields,q=$?await Promise.all(k.map(async P=>(await Promise.all($.map(async v=>({[v.key]:await v.builder({entity:P,context:T})})))).reduce((v,X)=>({...v,...X}),{}))):[],W=S?await Promise.all(k.map(async P=>(await Promise.all(S.map(async v=>v.value?{[v.key]:await v.value({entity:P,context:T})}:{}))).reduce((v,X)=>({...v,...X}),{}))):[];return[...q,...W]},[i?.additionalFields]),de=f.useCallback(async(k,$)=>{N(!0),D.fetchCollection({path:I,collection:k}).then(async S=>{w(void 0);const q=await ce(S),W=[...$?.additionalFields?.map(P=>P.key)??[],...k.additionalFields?.map(P=>P.key)??[]];Ce(S,q,k,p,W,g,x)}).catch(S=>{console.error("Error loading export data",S),w(S)}).finally(()=>N(!1))},[D,I,ce,p,g,x]),Oe=f.useCallback(()=>{de(u,i),V()},[de,u,i,V]);return t.jsxs(t.Fragment,{children:[t.jsx(l.Tooltip,{title:"Export",children:t.jsx(l.IconButton,{color:"primary",onClick:A,children:t.jsx(l.GetAppIcon,{})})}),t.jsxs(l.Dialog,{open:z,onOpenChange:C,maxWidth:"xl",children:[t.jsxs(l.DialogContent,{className:"flex flex-col gap-4 my-4",children:[t.jsx(l.Typography,{variant:"h6",children:"Export data"}),t.jsx("div",{children:"Download the the content of this table as a CSV"}),a>Te&&t.jsx(l.Alert,{color:"warning",children:t.jsxs("div",{children:["This collections has a large number of documents (",a,")."]})}),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:g==="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")}),t.jsx("label",{htmlFor:"radio-csv",className:"p-2 text-sm font-medium text-gray-900 dark:text-gray-300",children:"CSV"})]}),t.jsxs("div",{className:"flex items-center",children:[t.jsx("input",{id:"radio-json",type:"radio",value:"json",name:"exportType",checked:g==="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")}),t.jsx("label",{htmlFor:"radio-json",className:"p-2 text-sm font-medium text-gray-900 dark:text-gray-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:x==="timestamp",onChange:()=>b("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")}),t.jsxs("label",{htmlFor:"radio-timestamp",className:"p-2 text-sm font-medium text-gray-900 dark:text-gray-300",children:["Dates as timestamps (",c.current.getTime(),")"]})]}),t.jsxs("div",{className:"flex items-center",children:[t.jsx("input",{id:"radio-string",type:"radio",value:"string",name:"dateExportType",checked:x==="string",onChange:()=>b("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")}),t.jsxs("label",{htmlFor:"radio-string",className:"p-2 text-sm font-medium text-gray-900 dark:text-gray-300",children:["Dates as strings (",c.current.toISOString(),")"]})]})]})]}),t.jsx(l.BooleanSwitchWithLabel,{size:"small",disabled:g!=="csv",value:p,onValueChange:d,label:"Flatten arrays"}),!_&&s]}),t.jsxs(l.DialogActions,{children:[O&&t.jsx(l.CircularProgress,{size:"small"}),t.jsx(l.Button,{onClick:V,variant:"text",children:"Cancel"}),t.jsx(l.Button,{variant:"filled",onClick:Oe,disabled:O||!_,children:"Download"})]})]})]})}function Ie(e){return f.useMemo(()=>({name:"Import/Export",collections:{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=J,m.getInferenceType=K,m.getPropertiesMapping=R,m.processValueMapping=j,m.unflattenObject=L,m.useImportConfig=Q,m.useImportExportPlugin=Ie,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
|
3
3
|
//# sourceMappingURL=index.umd.js.map
|