@firecms/data_import_export 3.0.0-alpha.78 → 3.0.0-alpha.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.
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,y,l,de,pe){"use strict";function fe(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 z=fe(pe),G=()=>{const[e,n]=f.useState(!1),[a,t]=f.useState(),[s,o]=f.useState([]),[i,c]=f.useState([]),[p,d]=f.useState({}),[h,g]=f.useState({});return{inUse:e,setInUse:n,idColumn:a,setIdColumn:t,entities:i,setEntities:c,importData:s,setImportData:o,headersMapping:p,setHeadersMapping:d,originProperties:h,setOriginProperties:g}};function Q(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=z.read(o,{type:"array",codepage:65001,cellDates:!0}),c=i.SheetNames[0],p=i.Sheets[c],g=z.utils.sheet_to_json(p).map(he).map(H);n(g)},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 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 Y(e,n,a,t,s,o){const i=J(e);n&&delete i[n];const c=Object.entries(i).map(([d,h])=>{const g=a[d]??d;if(!y.getPropertyInPath(t,g))return{};const b=s[g];let D=h;return b&&(D=M(h,b)),{[g]:D}}).reduce((d,h)=>({...d,...h}),{}),p=H(c);return{id:n?e[n]:void 0,values:p,path:o}}function J(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,J(e[t],s)):a[s]=e[t],a},{})}function M(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=>M(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=>M(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 y.EntityReference(o,s)}else{if(a===t)return e;if(a==="array"&&t==="string"&&Array.isArray(e))return e.join(",")}}return e}function Z(e){return typeof e=="number"?"number":typeof e=="string"?"string":typeof e=="boolean"?"boolean":e instanceof Date?"date":Array.isArray(e)?"array":"map"}function K(e,n){function a(t,s){const o={};return Object.keys(t).forEach(i=>{const c=s?`${s}.${i}`:i,p=y.getPropertyInPath(t,i),d=y.getPropertyInPath(e,c);if(p){if(p.dataType==="map"&&p.properties){const h=a(p.properties,c);Object.keys(h).forEach(g=>{o[`${c}.${g}`]=h[g]});return}if(d){const h=d.dataType,g=p.dataType;let x,b;p.dataType==="array"&&p.of&&(b=p.of.dataType),d?.dataType==="array"&&d?.of&&(x=d.of.dataType),(h!==g||x!==b)&&(o[i]={from:h,to:g,fromSubtype:x,toSubtype:b})}}}),o}return a(n)}function R({idColumn:e,headersMapping:n,originProperties:a,destinationProperties:t,onIdPropertyChanged:s,buildPropertyView:o}){return r.jsxs(r.Fragment,{children:[r.jsx(ge,{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?y.getPropertyInPath(t,c):null,h=y.getPropertyInPath(a,i),g=h?h.dataType==="array"&&typeof h.of=="object"?`${h.dataType} - ${h.of.dataType}`:h.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}),h&&r.jsx(l.Typography,{variant:"caption",color:"secondary",children:g})]}),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 ge({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 ee({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&&Q(n[0]).then(a=>{e(a)})}})}function ye({propertyKey:e,property:n,onEditClick:a,includeName:t=!0,onPropertyNameChanged:s,propertyTypeView:o}){const{propertyConfigs:i}=y.useFireCMSContext(),c=n?y.getFieldConfig(n,i):null;return r.jsx(y.ErrorBoundary,{children:r.jsxs("div",{className:"flex flex-row w-full items-center",children:[r.jsx("div",{className:"mx-4",children:o??r.jsx(y.FieldConfigBadge,{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 te({importConfig:e,collection:n,onImportSuccess:a}){const t=y.useDataSource(),s=f.useRef(!1),[o,i]=f.useState(0);function c(){s.current||(s.current=!0,re(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 re(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),re(e,n,a,t+s,s,o)):(o(a.length),Promise.resolve()))}function me({collection:e,path:n,collectionEntitiesCount:a}){const t=y.useFireCMSContext(),s=y.useSnackbarController(),[o,i]=f.useState(!1),[c,p]=f.useState("initial"),d=G(),h=f.useCallback(()=>{i(!0),p("initial")},[i]),g=f.useCallback(()=>{i(!1)},[i]),x=f.useCallback(()=>{p("preview")},[]),b=f.useCallback(()=>{p("import_data_saving")},[]),D=async u=>{if(d.setImportData(u),u.length>0){const I=await de.buildEntityPropertiesFromData(u,Z);d.setOriginProperties(I);const j=se(u);d.setHeadersMapping(j);const w=Object.keys(j)?.[0];if(w?.includes("id")||w?.includes("key")){const O=w;d.setIdColumn(O)}}setTimeout(()=>{p("mapping")},100)},E=y.resolveCollection({collection:e,path:n,fields:t.propertyConfigs}),C=y.getPropertiesWithPropertiesOrder(E.properties,E.propertiesOrder),$=Object.entries(C).flatMap(([u,I])=>ne(u,I,0)),A=E.propertiesOrder??Object.keys(E.properties);return e.collectionGroup?null:r.jsxs(r.Fragment,{children:[r.jsx(l.Tooltip,{title:"Import",children:r.jsx(l.IconButton,{color:"primary",onClick:h,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(ee,{onDataAdded:D})]}),c==="mapping"&&r.jsxs(r.Fragment,{children:[r.jsx(l.Typography,{variant:"h6",children:"Map fields"}),r.jsx(R,{headersMapping:d.headersMapping,idColumn:d.idColumn,originProperties:d.originProperties,destinationProperties:C,onIdPropertyChanged:u=>d.setIdColumn(u),buildPropertyView:({isIdColumn:u,property:I,propertyKey:j,importKey:w})=>r.jsx(be,{selectedPropertyKey:j??"",properties:C,propertiesAndLevel:$,isIdColumn:u,onIdSelected:()=>{d.setIdColumn(w)},onPropertySelected:O=>{const N=Object.entries(d.headersMapping).map(([S,T])=>T===O?{[S]:null}:S===w?{[S]:O}:{[S]:T}).reduce((S,T)=>({...S,...T}),{});d.setHeadersMapping(N),O===d.idColumn&&d.setIdColumn(void 0)}})})]}),c==="preview"&&r.jsx(ue,{importConfig:d,properties:C,propertiesOrder:A}),c==="import_data_saving"&&d&&r.jsx(te,{importConfig:d,collection:e,onImportSuccess:u=>{g(),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:g,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 B="__internal_id__";function be({selectedPropertyKey:e,properties:n,onPropertySelected:a,onIdSelected:t,propertiesAndLevel:s,isIdColumn:o}){const i=e?y.getPropertyInPath(n,e):null,c=f.useCallback(d=>d===B?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(ae,{propertyKey:d,property:i}),[i]),p=f.useCallback(d=>{d===B?(t(),a(null)):a(d===""?null:d)},[]);return r.jsxs(l.Select,{value:o?B: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:B,children:r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"})}),s.map(({property:d,level:h,propertyKey:g})=>r.jsx(l.SelectItem,{value:g,disabled:d.dataType==="map",children:r.jsx(ae,{propertyKey:g,property:d,level:h})},g))]})}function ne(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(...ne(`${e}.${s}`,o,a+1))}),t}function ae({propertyKey:e,property:n,level:a=0}){const{propertyConfigs:t}=y.useFireCMSContext(),s=y.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(y.FieldConfigBadge,{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 ue({importConfig:e,properties:n,propertiesOrder:a}){f.useEffect(()=>{const s=K(e.originProperties,n),o=e.importData.map(i=>Y(i,e.idColumn,e.headersMapping,n,s,"TEMP_PATH"));e.setEntities(o)},[]);const t=y.useSelectionController();return r.jsx(y.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 se(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(se([s])).forEach(([o,i])=>{n[`${t}.${o}`]=`${t}.${i}`}),n[t]=t})}),n}function xe(e,n,a,t,s,o,i){const c=a.properties;if(o==="csv"){const p=t?y.getArrayValuesCount(e.map(b=>b.values)):{},d=we(c,s,p),h=Ce(e,n,c,d,i),g=oe(d.map(b=>b.label)),x=h.map(b=>oe(b));le([g,...x],`${a.name}.csv`,"text/csv")}else{const p=ve(e,n,c,i),d=JSON.stringify(p,null,2);le([d],`${a.name}.json`,"application/json")}}function Ce(e,n,a,t,s){const o=e.map(i=>({id:i.id,...V(i.values,a,"csv",s)}));return n&&n.forEach((i,c)=>{o[c]={...o[c],...i}}),o&&o.map(i=>t.map(c=>y.getValueInPath(i,c.key)))}function ve(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,c)=>U(o,`${s}[${c}]`,"")).flat():U(o,s,""))];return n&&t.push(...n.map(s=>({label:s,key:s}))),t}function U(e,n,a=""){const t=a?`${a}.${n}`:n;return e.dataType==="map"&&e.properties?Object.entries(e.properties).map(([s,o])=>U(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 instanceof y.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 V(e,n,a,t){const s=Object.entries(n).map(([o,i])=>{const c=e&&e[o],p=_(c,i,a,t);return p===void 0?{}:{[o]:p}}).reduce((o,i)=>({...o,...i}),{});return{...e,...s}}function oe(e){return e.map(n=>n==null?"":Array.isArray(n)?'"'+JSON.stringify(n).replaceAll('"','\\"')+'"':'"'+String(n).replaceAll('"','""')+'"').join(",")+`\r
|
|
2
|
-
`}function le(e,n
|
|
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,y,l,de,pe){"use strict";function fe(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 z=fe(pe),G=()=>{const[e,a]=f.useState(!1),[n,t]=f.useState(),[s,o]=f.useState([]),[i,c]=f.useState([]),[p,d]=f.useState({}),[h,g]=f.useState({});return{inUse:e,setInUse:a,idColumn:n,setIdColumn:t,entities:i,setEntities:c,importData:s,setImportData:o,headersMapping:p,setHeadersMapping:d,originProperties:h,setOriginProperties:g}};function Q(e){return new Promise((a,n)=>{if(e.type==="application/json"){const t=new FileReader;t.onload=function(s){const o=s.target?.result,i=JSON.parse(o);a(i)},t.readAsText(e)}else{const t=new FileReader;t.onload=function(s){const o=new Uint8Array(s.target?.result),i=z.read(o,{type:"array",codepage:65001,cellDates:!0}),c=i.SheetNames[0],p=i.Sheets[c],g=z.utils.sheet_to_json(p).map(he).map(H);a(g)},t.readAsArrayBuffer(e)}})}function he(e){return Object.keys(e).reduce((a,n)=>{try{a[n]=JSON.parse(e[n])}catch{a[n]=e[n]}return a},{})}function H(e){return Object.keys(e).reduce((a,n)=>{let t=a;const s=n.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[n]}else i!==s.length-1?(t[o]=t[o]||{},t=t[o]):t[o]=e[n]}),a},{})}function Y(e,a,n,t,s,o){const i=J(e);a&&delete i[a];const c=Object.entries(i).map(([d,h])=>{const g=n[d]??d;if(!y.getPropertyInPath(t,g))return{};const b=s[g];let D=h;return b&&(D=M(h,b)),{[g]:D}}).reduce((d,h)=>({...d,...h}),{}),p=H(c);return{id:a?e[a]:void 0,values:p,path:o}}function J(e,a=""){return Object.keys(e).reduce((n,t)=>{const s=a?`${a}.${t}`:t;return typeof e[t]=="object"&&e[t]!==null&&!Array.isArray(e[t])?Object.assign(n,J(e[t],s)):n[s]=e[t],n},{})}function M(e,a){if(a===void 0)return e;const{from:n,to:t}=a;if(n==="array"&&t==="array"&&a.fromSubtype&&a.toSubtype&&Array.isArray(e))return e.map(s=>M(s,{from:a.fromSubtype,to:a.toSubtype}));if(n==="string"&&t==="number"&&typeof e=="string")return Number(e);if(n==="string"&&t==="array"&&a.toSubtype&&typeof e=="string")return e.split(",").map(s=>M(s,{from:"string",to:a.toSubtype}));if(n==="string"&&t==="boolean")return e==="true";if(n==="number"&&t==="boolean")return e===1;if(n==="boolean"&&t==="number")return e?1:0;if(n==="boolean"&&t==="string")return e?"true":"false";if(n==="number"&&t==="string"&&typeof e=="number")return e.toString();if(n==="string"&&t==="array"&&typeof e=="string")return e.split(",").map(s=>s.trim());if(n==="string"&&t==="date"&&typeof e=="string")try{return new Date(e)}catch{return e}else{if(n==="date"&&t==="string")return e instanceof Date&&e.toISOString();if(n==="number"&&t==="date"&&typeof e=="number")try{return new Date(e)}catch{return e}else if(n==="string"&&t==="reference"&&typeof e=="string"){const s=e.split("/").slice(0,-1).join("/"),o=e.split("/").slice(-1)[0];return new y.EntityReference(o,s)}else{if(n===t)return e;if(n==="array"&&t==="string"&&Array.isArray(e))return e.join(",")}}return e}function Z(e){return typeof e=="number"?"number":typeof e=="string"?"string":typeof e=="boolean"?"boolean":e instanceof Date?"date":Array.isArray(e)?"array":"map"}function K(e,a){function n(t,s){const o={};return Object.keys(t).forEach(i=>{const c=s?`${s}.${i}`:i,p=y.getPropertyInPath(t,i),d=y.getPropertyInPath(e,c);if(p){if(p.dataType==="map"&&p.properties){const h=n(p.properties,c);Object.keys(h).forEach(g=>{o[`${c}.${g}`]=h[g]});return}if(d){const h=d.dataType,g=p.dataType;let x,b;p.dataType==="array"&&p.of&&(b=p.of.dataType),d?.dataType==="array"&&d?.of&&(x=d.of.dataType),(h!==g||x!==b)&&(o[i]={from:h,to:g,fromSubtype:x,toSubtype:b})}}}),o}return n(a)}function R({idColumn:e,headersMapping:a,originProperties:n,destinationProperties:t,onIdPropertyChanged:s,buildPropertyView:o}){return r.jsxs(r.Fragment,{children:[r.jsx(ge,{idColumn:e,headersMapping:a,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(a).map(([i,c])=>{const p=a[i],d=c?y.getPropertyInPath(t,c):null,h=y.getPropertyInPath(n,i),g=h?h.dataType==="array"&&typeof h.of=="object"?`${h.dataType} - ${h.of.dataType}`:h.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}),h&&r.jsx(l.Typography,{variant:"caption",color:"secondary",children:g})]}),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 ge({idColumn:e,headersMapping:a,onChange:n}){return r.jsx("div",{children:r.jsxs(l.Select,{size:"small",value:e??"",onChange:t=>{n(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(a).map(([t,s])=>r.jsx(l.SelectItem,{value:t,children:t},t))]})})}function ee({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:a=>{a.length>0&&Q(a[0]).then(n=>{e(n)})}})}function ye({propertyKey:e,property:a,onEditClick:n,includeName:t=!0,onPropertyNameChanged:s,propertyTypeView:o}){const{propertyConfigs:i}=y.useFireCMSContext(),c=a?y.getFieldConfig(a,i):null;return r.jsx(y.ErrorBoundary,{children:r.jsxs("div",{className:"flex flex-row w-full items-center",children:[r.jsx("div",{className:"mx-4",children:o??r.jsx(y.FieldConfigBadge,{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:a?.name??"",onChange:p=>{s&&e&&s(e,p.target.value)}}),r.jsx(l.IconButton,{onClick:n,size:"small",children:r.jsx(l.EditIcon,{size:"small"})})]})})]})})}function te({importConfig:e,collection:a,onImportSuccess:n}){const t=y.useDataSource(),s=f.useRef(!1),[o,i]=f.useState(0);function c(){s.current||(s.current=!0,re(t,a,e.entities,0,25,i).then(()=>{n(a),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 re(e,a,n,t=0,s=25,o){console.debug("Saving imported data",t,s);const i=n.slice(t,t+s);return Promise.all(i.map(c=>e.saveEntity({path:a.path,values:c.values,entityId:c.id,collection:a,status:"new"}))).then(()=>t+s<n.length?(o(t+s),re(e,a,n,t+s,s,o)):(o(n.length),Promise.resolve()))}function me({collection:e,path:a,collectionEntitiesCount:n}){const t=y.useFireCMSContext(),s=y.useSnackbarController(),[o,i]=f.useState(!1),[c,p]=f.useState("initial"),d=G(),h=f.useCallback(()=>{i(!0),p("initial")},[i]),g=f.useCallback(()=>{i(!1)},[i]),x=f.useCallback(()=>{p("preview")},[]),b=f.useCallback(()=>{p("import_data_saving")},[]),D=async u=>{if(d.setImportData(u),u.length>0){const I=await de.buildEntityPropertiesFromData(u,Z);d.setOriginProperties(I);const k=se(u);d.setHeadersMapping(k);const w=Object.keys(k)?.[0];if(w?.includes("id")||w?.includes("key")){const O=w;d.setIdColumn(O)}}setTimeout(()=>{p("mapping")},100)},E=y.resolveCollection({collection:e,path:a,fields:t.propertyConfigs}),C=y.getPropertiesWithPropertiesOrder(E.properties,E.propertiesOrder),$=Object.entries(C).flatMap(([u,I])=>ae(u,I,0)),A=E.propertiesOrder??Object.keys(E.properties);return e.collectionGroup?null:r.jsxs(r.Fragment,{children:[r.jsx(l.Tooltip,{title:"Import",children:r.jsx(l.IconButton,{color:"primary",onClick:h,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(ee,{onDataAdded:D})]}),c==="mapping"&&r.jsxs(r.Fragment,{children:[r.jsx(l.Typography,{variant:"h6",children:"Map fields"}),r.jsx(R,{headersMapping:d.headersMapping,idColumn:d.idColumn,originProperties:d.originProperties,destinationProperties:C,onIdPropertyChanged:u=>d.setIdColumn(u),buildPropertyView:({isIdColumn:u,property:I,propertyKey:k,importKey:w})=>r.jsx(be,{selectedPropertyKey:k??"",properties:C,propertiesAndLevel:$,isIdColumn:u,onIdSelected:()=>{d.setIdColumn(w)},onPropertySelected:O=>{const N=Object.entries(d.headersMapping).map(([S,T])=>T===O?{[S]:null}:S===w?{[S]:O}:{[S]:T}).reduce((S,T)=>({...S,...T}),{});d.setHeadersMapping(N),O===d.idColumn&&d.setIdColumn(void 0)}})})]}),c==="preview"&&r.jsx(ue,{importConfig:d,properties:C,propertiesOrder:A}),c==="import_data_saving"&&d&&r.jsx(te,{importConfig:d,collection:e,onImportSuccess:u=>{g(),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:g,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 B="__internal_id__";function be({selectedPropertyKey:e,properties:a,onPropertySelected:n,onIdSelected:t,propertiesAndLevel:s,isIdColumn:o}){const i=e?y.getPropertyInPath(a,e):null,c=f.useCallback(d=>d===B?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(ne,{propertyKey:d,property:i}),[i]),p=f.useCallback(d=>{d===B?(t(),n(null)):n(d===""?null:d)},[]);return r.jsxs(l.Select,{value:o?B: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:B,children:r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"})}),s.map(({property:d,level:h,propertyKey:g})=>r.jsx(l.SelectItem,{value:g,disabled:d.dataType==="map",children:r.jsx(ne,{propertyKey:g,property:d,level:h})},g))]})}function ae(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,o])=>{t.push(...ae(`${e}.${s}`,o,n+1))}),t}function ne({propertyKey:e,property:a,level:n=0}){const{propertyConfigs:t}=y.useFireCMSContext(),s=y.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((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(y.FieldConfigBadge,{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:a.name?a.name:" "}),r.jsx(l.Typography,{className:" pr-2",variant:"body2",component:"span",color:"secondary",children:e})]})]})}function ue({importConfig:e,properties:a,propertiesOrder:n}){f.useEffect(()=>{const s=K(e.originProperties,a),o=e.importData.map(i=>Y(i,e.idColumn,e.headersMapping,a,s,"TEMP_PATH"));e.setEntities(o)},[]);const t=y.useSelectionController();return r.jsx(y.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:n.map(s=>({key:s,disabled:!1})),properties:a})}function se(e){const a={};return e.filter(Boolean).forEach(n=>{Object.keys(n).forEach(t=>{const s=n[t];typeof s=="object"&&!Array.isArray(s)&&Object.entries(se([s])).forEach(([o,i])=>{a[`${t}.${o}`]=`${t}.${i}`}),a[t]=t})}),a}function xe(e,a,n,t,s,o,i){const c=n.properties;if(o==="csv"){const p=t?y.getArrayValuesCount(e.map(b=>b.values)):{},d=we(c,s,p),h=Ce(e,a,c,d,i),g=oe(d.map(b=>b.label)),x=h.map(b=>oe(b));le([g,...x],`${n.name}.csv`,"text/csv")}else{const p=ve(e,a,c,i),d=JSON.stringify(p,null,2);le([d],`${n.name}.json`,"application/json")}}function Ce(e,a,n,t,s){const o=e.map(i=>({id:i.id,...V(i.values,n,"csv",s)}));return a&&a.forEach((i,c)=>{o[c]={...o[c],...i}}),o&&o.map(i=>t.map(c=>y.getValueInPath(i,c.key)))}function ve(e,a,n,t){const s=e.map(o=>({id:o.id,...V(o.values,n,"json",t)}));return a&&a.forEach((o,i)=>{s[i]={...s[i],...o}}),s}function we(e,a,n){const t=[{label:"id",key:"id"},...Object.entries(e).flatMap(([s,o])=>n&&n[s]>1?Array.from({length:n[s]},(i,c)=>U(o,`${s}[${c}]`,"")).flat():U(o,s,""))];return a&&t.push(...a.map(s=>({label:s,key:s}))),t}function U(e,a,n=""){const t=n?`${n}.${a}`:a;return e.dataType==="map"&&e.properties?Object.entries(e.properties).map(([s,o])=>U(o,s,t)).flat():[{label:t,key:t}]}function _(e,a,n,t){let s;if(a.dataType==="map"&&a.properties)s=V(e,a.properties,n,t);else if(a.dataType==="array")a.of&&Array.isArray(e)?Array.isArray(a.of)?s=a.of.map((o,i)=>_(e[i],o,n,t)):a.of.dataType==="map"?s=n==="csv"?e.map(o=>JSON.stringify(o)):e.map(o=>_(o,a.of,n,t)):s=e.map(o=>_(o,a.of,n,t)):s=e;else if(a.dataType==="reference"&&e instanceof y.EntityReference){const o=e||void 0;s=o?o.pathWithId:null}else a.dataType==="date"&&e instanceof Date?s=e?t==="timestamp"?e.getTime():e.toISOString():null:s=e;return s}function V(e,a,n,t){const s=Object.entries(a).map(([o,i])=>{const c=e&&e[o],p=_(c,i,n,t);return p===void 0?{}:{[o]:p}}).reduce((o,i)=>({...o,...i}),{});return{...e,...s}}function oe(e){return e.map(a=>a==null?"":Array.isArray(a)?'"'+JSON.stringify(a).replaceAll('"','\\"')+'"':'"'+String(a).replaceAll('"','""')+'"').join(",")+`\r
|
|
2
|
+
`}function le(e,a,n){const t=new Blob(e,{type:n}),s=URL.createObjectURL(t),o=document.createElement("a");o.href=s,o.setAttribute("download",a),o.click()}const Se=500;function Te({collection:e,path:a,collectionEntitiesCount:n,exportAllowed:t,notAllowedView:s}){const o=typeof e.exportable=="object"?e.exportable:void 0,i=f.useRef(new Date),[c,p]=f.useState(!0),[d,h]=f.useState("csv"),[g,x]=f.useState("string"),b=y.useFireCMSContext(),D=y.useDataSource(),C=y.useNavigationController().resolveAliasesFrom(a),$=!t||t({collectionEntitiesCount:n,path:C,collection:e}),A=f.useMemo(()=>y.resolveCollection({collection:e,path:C,fields:b.propertyConfigs}),[e,C]),[u,I]=f.useState(!1),[k,w]=f.useState(),[O,N]=f.useState(!1),S=f.useCallback(()=>{N(!0)},[N]),T=f.useCallback(()=>{N(!1)},[N]),ie=f.useCallback(async P=>{const L=o?.additionalFields,j=A.additionalFields,q=L?await Promise.all(P.map(async F=>(await Promise.all(L.map(async v=>({[v.key]:await v.builder({entity:F,context:b})})))).reduce((v,X)=>({...v,...X}),{}))):[],W=j?await Promise.all(P.map(async F=>(await Promise.all(j.map(async v=>v.value?{[v.key]:await v.value({entity:F,context:b})}:{}))).reduce((v,X)=>({...v,...X}),{}))):[];return[...q,...W]},[o?.additionalFields]),ce=f.useCallback(async(P,L)=>{I(!0),D.fetchCollection({path:C,collection:P}).then(async j=>{w(void 0);const q=await ie(j),W=[...L?.additionalFields?.map(F=>F.key)??[],...P.additionalFields?.map(F=>F.key)??[]];xe(j,q,P,c,W,d,g)}).catch(w).finally(()=>I(!1))},[D,C,ie,c,d,g]),Ie=f.useCallback(()=>{ce(A,o),T()},[ce,A,o,T]);return r.jsxs(r.Fragment,{children:[r.jsx(l.Tooltip,{title:"Export",children:r.jsx(l.IconButton,{color:"primary",onClick:S,children:r.jsx(l.GetAppIcon,{})})}),r.jsxs(l.Dialog,{open:O,onOpenChange:N,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"}),n>Se&&r.jsx(l.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:d==="csv",onChange:()=>h("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-gray-300",children:"CSV"})]}),r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-json",type:"radio",value:"json",name:"exportType",checked:d==="json",onChange:()=>h("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-gray-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:g==="timestamp",onChange:()=>x("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-gray-300",children:["Dates as timestamps (",i.current.getTime(),")"]})]}),r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-string",type:"radio",value:"string",name:"dateExportType",checked:g==="string",onChange:()=>x("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-gray-300",children:["Dates as strings (",i.current.toISOString(),")"]})]})]})]}),r.jsx(l.BooleanSwitchWithLabel,{size:"small",disabled:d!=="csv",value:c,onValueChange:p,label:"Flatten arrays"}),!$&&s]}),r.jsxs(l.DialogActions,{children:[u&&r.jsx(l.CircularProgress,{size:"small"}),r.jsx(l.Button,{onClick:T,variant:"text",children:"Cancel"}),r.jsx(l.Button,{variant:"filled",onClick:Ie,disabled:u||!$,children:"Download"})]})]})]})}function De(e){return f.useMemo(()=>({name:"Import/Export",collections:{CollectionActions:[me,Te],collectionActionsProps:e}}),[e])}m.DataNewPropertiesMapping=R,m.ImportFileUpload=ee,m.ImportNewPropertyFieldPreview=ye,m.ImportSaveInProgress=te,m.convertDataToEntity=Y,m.convertFileToJson=Q,m.flattenEntry=J,m.getInferenceType=Z,m.getPropertiesMapping=K,m.processValueMapping=M,m.unflattenObject=H,m.useImportConfig=G,m.useImportExportPlugin=De,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
|
|
3
3
|
//# sourceMappingURL=index.umd.js.map
|