PageSourceSearch

https://aidealer360.com/assets/CustomTemplateBuilder-91KF_dQ3.js

js aidealer360.com collected 2026-10-01 15:59:29 UTC 69,534 bytes, 16 lines download raw bytes

1import{j as e}from"./ui-vendor-B12AOeKi.js";import{r as t}from"./react-vendor-DZt7wVAJ.js";import{ai as bs,s as j,i as g,B as k,a6 as ns,ao as Pe,ax as is,X as Bs,g as Ie,D as Ke,m as Ns,k as Se,b as qe,c as We,d as Ge,e as as,n as Qe,P as se,bn as Vs,Y as Us,T as Ye,W as He,av as Hs,bo as zs,am as ts,aw as Ks,C as qs,aj as Ws,ac as _s,q as ie,y as he,v as ve,w as ye,x as _e,l as cs,E as os,L as I,o as Gs,al as Qs,u as Ys,z as Ae,bi as Ze,G as Te,an as Js,a5 as Xs,a as Zs,Q as ea,ak as es,I as ne,p as sa,bh as aa,ab as ta}from"./index-BZo64Z7H.js";import{u as Ee,w as la,r as Oe}from"./xlsx-CwpDMyS9.js";import{g as ra,B as Be,a as na,b as ia,s as ca,c as oa}from"./excelDataSanitizer-CynNAh0h.js";import{A as ws,a as ks,b as Cs,c as Ss,d as Es,e as As,g as Ts,f as Fs}from"./alert-dialog-Diwn5aYx.js";import{U as ds}from"./upload-CzyNu08p.js";import{F as da}from"./file-spreadsheet-BEw0f8A5.js";import{L as ms}from"./layers-BpBqBFzi.js";import{T as Rs,b as Is,c as Fe,a as Re}from"./tabs-BcL48lVI.js";import{H as ze}from"./history-CCcNq537.js";import{S as xe,a as fe,b as ge,c as je,d as H}from"./select-B9Z9mxdV.js";import{S as ma}from"./switch-D_kCiubG.js";import{D as ls}from"./database-DMQ83p2N.js";import{L as ua}from"./lock-BsXOWpo0.js";import{C as ha}from"./circle-check-big-3X4sON1s.js";import{C as pa}from"./circle-stop-DNGZiifn.js";import{u as xa,D as fa}from"./DemoModeIndicator-CrWObcdo.js";import{K as Ve}from"./key-PffLlk2P.js";import{E as us}from"./external-link-B_oQ01HE.js";import{S as ga}from"./save-Cxi2VgTj.js";import{T as hs}from"./textarea-B3uKHHtr.js";import{p as ja}from"./purify.es-DxJI3Wx7.js";import{S as va}from"./square-pen-DOZlbkbu.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const ps=bs("Cloud",[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]]);/**
7 * @license lucide-react v0.462.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const ya=bs("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]]),ss=4*1024*1024,ba=3,xs=1e3;async function fs(n){return new Promise(i=>setTimeout(i,n))}async function gs(n,i,h,w,o=ba){for(let l=0;l<o;l++)try{const{error:x}=await j.storage.from(n).upload(i,h,{contentType:w,upsert:!0});if(!x)return{success:!0};if(l<o-1)console.warn(`Upload attempt ${l+1} failed, retrying...`,x),await fs(xs*(l+1));else return{success:!1,error:x.message}}catch(x){if(l<o-1)console.warn(`Upload attempt ${l+1} threw error, retrying...`,x),await fs(xs*(l+1));else return{success:!1,error:x.message}}return{success:!1,error:"Max retries exceeded"}}async function Na(n,i,h,w,o){const l=n.size,x=Math.ceil(l/ss),c=[],d=i.replace(/\.[^.]+$/,"");console.log(`Starting chunked upload: ${i} (${(l/1024/1024).toFixed(2)}MB) in ${x} chunks`);for(let E=0;E<x;E++){const L=E*ss,ee=Math.min(L+ss,l),F=n.slice(L,ee),p=`chunks/${d}.chunk_${E}`;o==null||o({currentChunk:E+1,totalChunks:x,percent:Math.round((E+1)/x*100)});const v=await gs(h,p,F,w);if(!v.success)return console.error(`Failed to upload chunk ${E}:`,v.error),await js(h,c),{success:!1,error:`Failed to upload chunk ${E+1}/${x}: ${v.error}`};c.push(p)}const N={originalFilename:i,totalSize:l,chunkCount:x,chunks:c,createdAt:new Date().toISOString(),contentType:w},C=`${d}.manifest.json`,m=new Blob([JSON.stringify(N,null,2)],{type:"text/plain"}),_=await gs(h,C,m,"text/plain");return _.success?(console.log(`Chunked upload complete: ${C}`),{success:!0,manifestPath:C}):(console.error("Failed to upload manifest:",_.error),await js(h,c),{success:!1,error:`Failed to upload manifest: ${_.error}`})}async function _a(n,i){try{const{data:h,error:w}=await j.storage.from(i).download(n);if(w)return{success:!1,error:`Failed to download manifest: ${w.message}`};const o=await h.text(),l=JSON.parse(o);console.log(`Reassembling ${l.originalFilename} from ${l.chunkCount} chunks`);const x=[];for(let d=0;d<l.chunks.length;d++){const N=l.chunks[d],{data:C,error:m}=await j.storage.from(i).download(N);if(m)return{success:!1,error:`Failed to download chunk ${d+1}: ${m.message}`};x.push(C)}const c=new Blob(x,{type:l.contentType});return console.log(`Reassembly complete: ${(c.size/1024/1024).toFixed(2)}MB`),{success:!0,blob:c}}catch(h){return console.error("Reassembly error:",h),{success:!1,error:h.message}}}
11async function js(n,i){if(i.length!==0)try{const{error:h}=await j.storage.from(n).remove(i);h&&console.warn("Failed to cleanup chunks:",h)}catch(h){console.warn("Error during chunk cleanup:",h)}}async function wa(n,i){try{const{data:h,error:w}=await j.storage.from(i).download(n);if(w)return{success:!1,error:`Failed to download manifest: ${w.message}`};const o=await h.text(),l=JSON.parse(o);if(l.chunks.length>0){const{error:c}=await j.storage.from(i).remove(l.chunks);c&&console.warn("Failed to delete some chunks:",c)}const{error:x}=await j.storage.from(i).remove([n]);return x?{success:!1,error:`Failed to delete manifest: ${x.message}`}:{success:!0}}catch(h){return{success:!1,error:h.message}}}function vs(n){return n.endsWith(".manifest.json")}function ys(n){return n.replace(".manifest.json",".xlsx")}const ka=5*1024*1024,Ca={Settings:_s,Users:Ws,Car:qs,DollarSign:Ks,Mail:ts,Megaphone:zs,BarChart3:Hs,Wrench:He};function lt(){const[n,i]=t.useState({}),[h,w]=t.useState(!0),[o,l]=t.useState(!0),[x,c]=t.useState(!1),[d,N]=t.useState(!1),[C,m]=t.useState(!1),[_,E]=t.useState(!1),[L,ee]=t.useState([]),[F,p]=t.useState([]),[v,M]=t.useState(!1),[D,q]=t.useState(null),[z,V]=t.useState(!1),[W,ce]=t.useState("backup"),[oe,de]=t.useState(null),[Q,r]=t.useState(null),[X,Y]=t.useState(null),K=t.useRef(null),$=t.useMemo(()=>ra(),[]),ae=t.useMemo(()=>{const a=Object.entries(n).filter(([b,f])=>f).length,u=Object.keys(Be).length;return{selected:a,total:u}},[n]);t.useEffect(()=>{te()},[]);const te=async()=>{m(!0);try{const{data:a,error:u}=await j.storage.from("backups").list("",{limit:100,sortBy:{column:"created_at",order:"desc"}});if(u)throw u;const b=(a||[]).filter(f=>f.name.endsWith(".xlsx")||f.name.endsWith(".csv")||f.name.endsWith(".manifest.json")).map(f=>{var P;return{name:f.name,created_at:f.created_at||"",size:((P=f.metadata)==null?void 0:P.size)||0,isChunked:vs(f.name)}});ee(b)}catch(a){console.error("Error loading backups:",a),g.error("Failed to load available backups")}finally{m(!1)}},be=async()=>{if(confirm("Are you sure you want to delete ALL backup files? This cannot be undone.")){E(!0);try{if(L.length===0){g.info("No backup files to delete");return}let a=0,u=0;for(const b of L)try{if(b.isChunked){const f=await wa(b.name,"backups");f.success?a++:(console.error(`Failed to delete chunked backup ${b.name}:`,f.error),u++)}else{const{error:f}=await j.storage.from("backups").remove([b.name]);f?(console.error(`Failed to delete ${b.name}:`,f),u++):a++}}catch(f){console.error(`Error deleting ${b.name}:`,f),u++}u>0?g.warning(`Deleted ${a} backups, ${u} failed`):g.success(`Deleted ${a} backup files`),await te(),p([])}catch(a){console.error("Error clearing backups:",a),g.error("Failed to clear backups: "+a.message)}finally{E(!1)}}},R=a=>{const u=$[a]||[],b=u.every(P=>n[P.appName]),f={...n};u.forEach(P=>{f[P.appName]=!b}),i(f)},Je=()=>{const a={};Object.keys(Be).forEach(u=>{a[u]=!0}),i(a)},De=()=>{i({})},$e=async()=>{const a=Object.entries(n).filter(([B,y])=>y).map(([B])=>B);if(a.length===0){g.error("Please select at least one application to backup");return}if(!h&&!o){g.error("Please select at least one backup destination");return}c(!0);const u=new Date().toISOString().replace(/[:.]/g,"-").slice(0,-5);let b=0,f=0,P=0,U=0,O=0;const S={};try{for(const B of a){const y=ia(B);if(!y)continue;const T=`${y.appId}__${u}.xlsx`,le=Ee.book_new();let ue=0,Me=0,Ne=0;const Le=[];for(const A of y.tables)try{const re=A.orderBy||"created_at",{data:Ce,error:Xe}=await j.from(A.tableName).select("*").order(re,{ascending:!1});if(Xe){console.error(`Error fetching ${A.tableName}:`,Xe),Le.push(`${A.sheetName}: ${Xe.message}`),Ne++;continue}if(!Ce||Ce.length===0){Ne++;continue}ue+=Ce.length;const $s=A.formatter?A.formatter(Ce):Ce,{sanitizedData:Ms,oversizedFields:Ls,totalTruncated:rs}=ca($s);if(rs>0){const Os=oa(Ls);console.warn(`[${A.sheetName}] ${Os}`),g.warning(`${A.sheetName}: ${rs} fields truncated for Excel compatibility`)}const Ps=Ee.json_to_sheet(Ms);Ee.book_append_sheet(le,Ps,A.sheetName),Me++}catch(re){console.error(`Error processing ${A.tableName}:`,re),Le.push(`${A.sheetName}: ${re.message}`),Ne++}O+=ue;const pe=y.category;if(S[pe]||(S[pe]={records:0,tables:0,tablesBackedUp:0,tablesSkipped:0,errors:[]}),S[pe].records+=ue,S[pe].tables+=y.tables.length,S[pe].tablesBackedUp+=Me,S[pe].tablesSkipped+=Ne,Le.length>0&&(S[pe].errors=[...S[pe].errors||[],...Le]),le.SheetNames.length===0){console.warn(`No data to backup for ${y.displayName} - skipping workbook creation`);continue}const Ds=la(le,{bookType:"xlsx",type:"array"}),ke=new Blob([Ds],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});if(h){const A=window.URL.createObjectURL(ke),re=document.createElement("a");re.href=A,re.download=T,re.click(),window.URL.revokeObjectURL(A),b++}if(o)if(ke.size>ka){console.log(`File ${T} is large (${(ke.size/1024/1024).toFixed(2)}MB). Using chunked upload.`),Y(y.displayName);const A=await Na(ke,T,"backups","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",re=>r(re));Y(null),r(null),A.success?(P++,g.success(`${y.displayName} uploaded in chunks`)):(console.error(`Chunked upload failed for ${T}:`,A.error),U++,g.error(`Failed to upload ${y.displayName}: ${A.error}`))}else try{const{error:A}=await j.storage.from("backups").upload(T,ke,{contentType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",upsert:!0});A?(console.error(`Upload error for ${T}:`,A),U++):f++}catch(A){console.error(`Upload exception for ${T}:`,A),U++}}q({totalRecords:O,downloadedFiles:b,uploadedFiles:f,chunkedFiles:P,failedUploads:U,recordsByCategory:S}),M(!0),o&&await te()}catch(B){console.error("Backup error:",B),g.error("Backup failed: "+B.message)}finally{c(!1),Y(null),r(null)}},s=()=>
11{if(F.length===0){g.error("Please select at least one backup file to restore");return}V(!0)},G=async()=>{V(!1),N(!0);const a=[];try{for(const u of F){const b=vs(u),f=b?ys(u):u,P=f.split("__");if(P.length<2){g.error(`Invalid backup filename format: ${u}`);continue}const U=P[0],O=Object.values(Be).find(y=>y.appId===U);if(!O){g.error(`No configuration found for app ID: ${U}`);continue}let S;if(b){g.info(`Reassembling ${O.displayName} from chunks...`);const y=await _a(u,"backups");if(!y.success||!y.blob){console.error(`Reassembly error for ${u}:`,y.error),g.error(`Failed to reassemble ${O.displayName}: ${y.error}`);continue}S=y.blob}else{const{data:y,error:Z}=await j.storage.from("backups").download(u);if(Z){console.error(`Download error for ${u}:`,Z),g.error(`Failed to download ${u}`);continue}S=y}let B;if(f.endsWith(".csv")){const y=await S.text();B=Oe(y,{type:"string"})}else{const y=await S.arrayBuffer();B=Oe(y,{type:"array"})}for(const y of O.tables)try{const Z=B.Sheets[y.sheetName];if(!Z)continue;const T=Ee.sheet_to_json(Z);if(T.length===0)continue;const le=y.conflictTarget??"id",{error:ue}=await j.from(y.tableName).upsert(T,{onConflict:le});ue&&(console.error(`Upsert error for ${y.tableName}:`,ue),a.push(`${O.displayName} - ${y.sheetName}`))}catch(Z){console.error(`Error restoring ${y.tableName}:`,Z),a.push(`${O.displayName} - ${y.sheetName}`)}}g.success("Restore Complete"),a.length>0&&g.warning(`Some tables failed: ${a.slice(0,3).join(", ")}${a.length>3?` +${a.length-3} more`:""}`,{duration:1e4}),p([])}catch(u){console.error("Restore error:",u),g.error("Restore failed: "+u.message)}finally{N(!1)}},J=async a=>{const u=a.target.files;if(!u||u.length===0)return;N(!0);const b=[];try{for(let f=0;f<u.length;f++){const P=u[f],U=P.name,O=U.split("__");if(O.length<2){g.error(`Invalid filename format: ${U}`);continue}const S=O[0],B=Object.values(Be).find(T=>T.appId===S);if(!B){g.error(`No configuration found for app ID: ${S}`);continue}const y=await P.arrayBuffer();let Z;if(U.endsWith(".csv")){const T=new TextDecoder().decode(y);Z=Oe(T,{type:"string"})}else Z=Oe(y,{type:"array"});for(const T of B.tables)try{const le=Z.Sheets[T.sheetName];if(!le)continue;const ue=Ee.sheet_to_json(le);if(ue.length===0)continue;const Me=T.conflictTarget??"id",{error:Ne}=await j.from(T.tableName).upsert(ue,{onConflict:Me});Ne&&(console.error(`Upsert error for ${T.tableName}:`,Ne),b.push(`${B.displayName} - ${T.sheetName}`))}catch(le){console.error(`Error restoring ${T.tableName}:`,le),b.push(`${B.displayName} - ${T.sheetName}`)}}g.success("Restore Complete"),b.length>0&&g.warning(`Some tables failed: ${b.slice(0,3).join(", ")}${b.length>3?` +${b.length-3} more`:""}`,{duration:1e4})}catch(f){console.error("Restore error:",f),g.error("Restore failed: "+f.message)}finally{N(!1),K.current&&(K.current.value="")}},me=a=>Ca[a]||_s,we=a=>($[a]||[]).filter(b=>n[b.appName]).length;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(k,{variant:W==="backup"?"default":"outline",size:"sm",onClick:()=>ce("backup"),children:[e.jsx(ns,{className:"h-4 w-4 mr-1"}),"Backup"]}),e.jsxs(k,{variant:W==="restore"?"default":"outline",size:"sm",onClick:()=>ce("restore"),children:[e.jsx(ds,{className:"h-4 w-4 mr-1"}),"Restore"]})]}),W==="backup"&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer",children:[e.jsx(Pe,{checked:h,onCheckedChange:a=>w(a)}),e.jsx(da,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"hidden sm:inline",children:"Excel"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer",children:[e.jsx(Pe,{checked:o,onCheckedChange:a=>l(a)}),e.jsx(ps,{className:"h-4 w-4 text-blue-600"}),e.jsx("span",{className:"hidden sm:inline",children:"Cloud"})]})]}),e.jsx("div",{className:"h-4 w-px bg-border"}),e.jsxs(k,{variant:"ghost",size:"sm",onClick:Je,className:"h-7 px-2 text-xs",children:[e.jsx(is,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(k,{variant:"ghost",size:"sm",onClick:De,className:"h-7 px-2 text-xs",children:[e.jsx(Bs,{className:"h-3 w-3 mr-1"}),"None"]}),e.jsxs(Ie,{variant:"secondary",className:"text-xs",children:[ae.selected,"/",ae.total]})]})]}),W==="backup"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-8 gap-2",children:Object.entries(na).sort((a,u)=>a[1].order-u[1].order).map(([a,u])=>{const b=a,f=$[b]||[],P=me(u.icon),U=we(b),O=f.length>0&&f.every(S=>n[S.appName]);return e.jsxs(Ke,{open:oe===b,onOpenChange:S=>de(S?b:null),children:[e.jsx(Ns,{asChild:!0,children:e.jsxs("button",{className:Se("relative flex flex-col items-center p-3 rounded-lg transition-all","hover:bg-muted/80 hover:scale-105","border border-transparent",O&&"bg-primary/10 border-primary/30",U>
110&&!O&&"bg-muted/50 border-muted-foreground/20"),children:[e.jsx(P,{className:Se("h-7 w-7 transition-colors",O?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:"text-[10px] mt-1 text-center leading-tight font-medium truncate w-full",children:u.label}),U>0&&e.jsx(Ie,{variant:O?"default":"secondary",className:"absolute -top-1 -right-1 h-5 min-w-[20px] px-1 text-[10px] justify-center",children:U})]})}),e.jsxs(qe,{className:"",children:[e.jsxs(We,{children:[e.jsxs(Ge,{className:"flex items-center gap-2",children:[e.jsx(P,{className:"h-5 w-5"}),u.label]}),e.jsx(as,{children:"Select apps to backup from this category"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[U," of ",f.length," selected"]}),e.jsx(k,{variant:"ghost",size:"sm",onClick:()=>R(b),className:"h-7 text-xs",children:O?"Deselect All":"Select All"})]}),e.jsx(Qe,{className:"max-h-[300px]",children:e.jsx("div",{className:"space-y-1",children:f.map(S=>e.jsxs("label",{className:Se("flex items-center gap-2 p-2 rounded cursor-pointer hover:bg-muted/50 transition-colors",n[S.appName]&&"bg-primary/10"),children:[e.jsx(Pe,{checked:n[S.appName]||!1,onCheckedChange:B=>i({...n,[S.appName]:B})}),e.jsx("span",{className:"text-sm",children:S.displayName})]},S.appName))})})]})]})]},b)})}),X&&Q&&e.jsxs("div",{className:"p-4 rounded-lg bg-blue-500/10 border border-blue-500/20 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{className:"h-4 w-4 animate-spin text-blue-600"}),e.jsxs("span",{className:"text-sm font-medium text-blue-700 truncate",children:["Uploading ",X]})]}),e.jsxs("span",{className:"text-lg font-bold text-blue-600",children:[Q.percent,"%"]})]}),e.jsx(Vs,{value:Q.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-blue-600/80",children:[e.jsxs("span",{children:["Chunk ",Q.currentChunk," of ",Q.totalChunks]}),e.jsxs("span",{children:[(Q.currentChunk/Q.totalChunks*100).toFixed(0),"% complete"]})]})]}),e.jsx(k,{onClick:$e,disabled:x||ae.selected===0,className:"w-full",children:x?e.jsxs(e.Fragment,{children:[e.jsx(se,{className:"mr-2 h-4 w-4 animate-spin"}),X?"Uploading Large File...":"Creating Backup..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ns,{className:"mr-2 h-4 w-4"}),"Create Backup (",ae.selected," apps)"]})})]}),W==="restore"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[L.length," backups in cloud"]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(k,{variant:"ghost",size:"sm",onClick:te,disabled:C,className:"h-7",children:e.jsx(Us,{className:Se("h-3.5 w-3.5",C&&"animate-spin")})}),e.jsx(k,{variant:"ghost",size:"sm",onClick:be,disabled:L.length===0||_,className:"h-7 text-destructive hover:text-destructive",children:_?e.jsx(se,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ye,{className:"h-3.5 w-3.5"})})]})]}),e.jsx(Qe,{className:"h-[280px] border rounded-md",children:L.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full py-8 text-muted-foreground",children:[e.jsx(ya,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("span",{className:"text-sm",children:"No backups found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:L.map(a=>e.jsxs("label",{className:Se("flex items-center gap-2 p-2 rounded cursor-pointer hover:bg-muted/50",F.includes(a.name)&&"bg-primary/10"),children:[e.jsx(Pe,{checked:F.includes(a.name),onCheckedChange:u=>{p(u?[...F,a.name]:F.filter(b=>b!==a.name))}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm truncate flex items-center gap-1.5",children:[a.isChunked&&e.jsx(ms,{className:"h-3.5 w-3.5 text-blue-600 shrink-0"}),a.isChunked?ys(a.name):a.name]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[new Date(a.created_at).toLocaleDateString()," • ",a.isChunked?"Chunked":`${(a.size/1024).toFixed(0)} KB`]})]})]},a.name))})}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(k,{onClick:s,disabled:d||F.length===0,children:[d?e.jsx(se,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ps,{className:"mr-2 h-4 w-4"}),"Restore (",F.length,")"]}),e.jsx("input",{ref:K,type:"file",accept:".xlsx,.csv",multiple:!0,onChange:J,className:"hidden"}),e.jsxs(k,{variant:"outline",onClick:()=>{var a;return(a=K.current)==null?void 0:a.click()},disabled:d,children:[e.jsx(ds,{className:"mr-2 h-4 w-4"}),"Upload File"]})]})]}),e.jsx(Ke,{open:v,onOpenChange:M,children:e.jsxs(qe,{className:"",children:[e.jsxs(We,{children:[e.jsxs(Ge,{className:"flex items-center gap-2",children:[e.jsx(is,{className:"h-5 w-5 text-green-600"}),"Backup Complete"]}),e.jsx(as,{children:"Summary of backup operation"})]}),D&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"p-3 border rounded-lg text-center",children:[e.jsx("div",{className:"text-xl font-bold",children:D.totalRecords.toLocaleStr
11ing()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Records"})]}),e.jsxs("div",{className:"p-3 border rounded-lg text-center",children:[e.jsx("div",{className:"text-xl font-bold",children:D.downloadedFiles}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Downloaded"})]}),e.jsxs("div",{className:"p-3 border rounded-lg text-center",children:[e.jsx("div",{className:"text-xl font-bold",children:D.uploadedFiles+D.chunkedFiles}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Uploaded"})]}),e.jsx("div",{className:"p-3 border rounded-lg text-center",children:D.failedUploads>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl font-bold text-amber-600",children:D.failedUploads}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Failed"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl font-bold text-green-600",children:"✓"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"All Success"})]})})]}),D.chunkedFiles>0&&e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded bg-blue-500/10 text-blue-700 text-xs",children:[e.jsx(ms,{className:"h-4 w-4"}),e.jsxs("span",{children:[D.chunkedFiles," large file(s) uploaded in chunks"]})]}),e.jsx(k,{onClick:()=>M(!1),className:"w-full",children:"Close"})]})]})}),e.jsx(ws,{open:z,onOpenChange:V,children:e.jsxs(ks,{children:[e.jsxs(Cs,{children:[e.jsx(Ss,{children:"Confirm Restore"}),e.jsxs(Es,{children:["This will restore data from ",F.length," backup file(s). Existing records with matching IDs will be updated. This action cannot be undone."]})]}),e.jsxs(As,{children:[e.jsx(Ts,{children:"Cancel"}),e.jsx(Fs,{onClick:G,children:"Restore"})]})]})})]})}function Sa(){const[n,i]=t.useState([]),[h,w]=t.useState(!0),[o,l]=t.useState(null);t.useEffect(()=>{x()},[]);const x=async()=>{try{const{data:c,error:d}=await j.from("system_cleanup_logs").select("*").order("created_at",{ascending:!1}).limit(50);if(d)throw d;i(c||[]),c&&c.length>0&&l(c[0])}catch(c){console.error("Error loading cleanup logs:",c)}finally{w(!1)}};return h?e.jsx(ie,{children:e.jsx(he,{className:"pt-6 flex items-center justify-center",children:e.jsx(se,{className:"h-8 w-8 animate-spin"})})}):n.length===0?e.jsxs(ie,{children:[e.jsxs(ve,{children:[e.jsxs(ye,{className:"flex items-center gap-2",children:[e.jsx(ze,{className:"h-5 w-5"}),"Cleanup History"]}),e.jsx(_e,{children:"View detailed logs of all system cleanup operations"})]}),e.jsx(he,{children:e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No cleanup logs found. Run a system cleanup to see logs here."})})]}):e.jsxs(ie,{children:[e.jsxs(ve,{children:[e.jsxs(ye,{className:"flex items-center gap-2",children:[e.jsx(ze,{className:"h-5 w-5"}),"Cleanup History"]}),e.jsx(_e,{children:"View detailed logs of all system cleanup operations"})]}),e.jsx(he,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx("div",{className:"col-span-1 border rounded-lg",children:e.jsx(Qe,{className:"h-[600px]",children:e.jsx("div",{className:"space-y-2 p-2",children:n.map(c=>e.jsxs("div",{onClick:()=>l(c),className:`p-3 rounded-lg cursor-pointer transition-colors ${(o==null?void 0:o.id)===c.id?"bg-primary/10 border-2 border-primary":"bg-secondary hover:bg-secondary/80 border-2 border-transparent"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(Ie,{variant:c.issues_found>0?"destructive":"default",children:c.application}),e.jsx("span",{className:"text-xs text-muted-foreground",children:cs(new Date(c.created_at),"MMM d, HH:mm")})]}),e.jsxs("div",{className:"text-sm space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Found:"}),e.jsx("span",{className:"font-medium",children:c.issues_found})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Fixed:"}),e.jsx("span",{className:"font-medium text-green-600",children:c.issues_fixed})]})]})]},c.id))})})}),e.jsx("div",{className:"col-span-2 border rounded-lg p-4",children:o&&e.jsx(Qe,{className:"h-[600px]",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-xl font-semibold",children:o.application}),e.jsx(Ie,{variant:o.issues_found>0?"destructive":"default",children:o.issues_found>0?"Issues Found":"Healthy"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:cs(new Date(o.created_at),"MMMM d, yyyy at h:mm a")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4 bg-secondary rounded-lg",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Issues Found"}),e.jsx("div",{className:"text-2xl font-bold",children:o.issues_found})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Issues Fixed"}),e.jsx("div",{className:"text-2xl font-bold text-green-600",children:o.issues_fixed})]})]}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-semibold mb-2 flex items-center gap-2",children:[e.jsx(ze,{className:"h-4 w-4"}),"Detailed Log"]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg font-mono text-xs space-y-1",children:o.cleanup_log.map((c,d)=>e.jsx("div",{className:c.includes("✓")?"text-green-600":c.includes("⚠️")?"text-yellow-600":c.includes("===")?"font-bold text-primary":c.includes("---")?"font-semibold text-foreground":"",children:c},d))})]}),o.recommendations.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-semibold mb-2 flex items-center gap-2",children:[e.jsx(os,{className:"h-4 w-4"}),"Recommendations"]}),e.jsx("ul",{className:"space-y-2",children:o.recommendations.map((c,d)=>e.jsxs("li",{className:"flex items-start gap-2 p-3 bg-yellow-50 dark:bg-yellow-950/20 border border-yellow-200 dark:border-yellow-800 rounded-lg",children:[e.jsx(os,{className:"h-4 w-4 text-yellow-600 mt-0.5 flex-shrink-0"}),e.jsx("span",{className:"text-sm",children:c})]},d))})]})]})})})]})})]})}const Ea=()=>{const[n,i]=t.useState("daily"),[h,w]=t.useState("02:00"),[o,l]=t.useState(!1),[x,c]=t.useState(!0),[d,N]=t.useState(!1),[C,m]=t.useState(null);t.useEffect(()=>{E(),_()},[]);const _=async()=>{try{const{data:p,error:v}=await j.from("cleanup_logs").select("created_at").order("created_at",{ascending:!1}).limit(1).maybeSingle();if(v)throw v;p&&m(new Date(p.created_at))}catch(p){console.error("Error loading last run info:",p)}},E=async()=>{try{const{data:p,error:v}=await j.from("system_config").select("config_value").eq("config_key","cleanup_schedule").maybeSingle();if(v)throw v;const{data:M,error:D}=await j.from("system_config").select("config_value").eq("config_key","cleanup_time").maybeSingle();if(D)throw D;const{data:q,error:z}=await j.from("system_config").select("config_value").eq("config_key","cleanup_enabled").maybeSingle();if(z)throw z;p!=null&&p.config_value&&i(p.config_value),M!=null&&M.config_value&&w(M.c
11onfig_value),(q==null?void 0:q.config_value)!==void 0&&l(q.config_value==="true")}catch(p){console.error("Error loading schedule:",p)}finally{c(!1)}},L=()=>{const[p,v]=h.split(":");switch(n){case"daily":return`${v} ${p} * * *`;case"weekly":return`${v} ${p} * * 0`;case"monthly":return`${v} ${p} 1 * *`;default:return`${v} ${p} * * *`}},ee=async()=>{N(!0);try{const{error:p}=await j.from("system_config").upsert({config_key:"cleanup_schedule",config_value:n,description:"Automated cleanup schedule frequency"},{onConflict:"config_key"});if(p)throw p;const{error:v}=await j.from("system_config").upsert({config_key:"cleanup_time",config_value:h,description:"Automated cleanup scheduled time (24h format)"},{onConflict:"config_key"});if(v)throw v;const{error:M}=await j.from("system_config").upsert({config_key:"cleanup_enabled",config_value:o.toString(),description:"Whether automated cleanup is enabled"},{onConflict:"config_key"});if(M)throw M;o&&await F(),g.success("Cleanup schedule saved successfully"),await _()}catch(p){console.error("Error saving schedule:",p),g.error("Failed to save cleanup schedule")}finally{N(!1)}},F=async()=>{try{const p=L(),v=void 0,M=void 0;console.log("Cron expression:",p),console.log("Setup instructions displayed to admin"),g.info("Cron Job Setup Required",{description:"Please contact your administrator to enable the pg_cron extension and set up the scheduled job.",duration:1e4})}catch(p){throw console.error("Error setting up cron job:",p),p}};return x?e.jsx(ie,{children:e.jsxs(ve,{children:[e.jsxs(ye,{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"h-5 w-5"}),"Automated Cleanup Schedule"]}),e.jsx(_e,{children:"Loading configuration..."})]})}):e.jsxs(ie,{children:[e.jsx(ve,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs(ye,{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"h-5 w-5"}),"Automated Cleanup Schedule"]}),e.jsx(_e,{children:"Configure automated system cleanup to run on a schedule"})]}),C&&e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx(Ie,{variant:"outline",className:"text-xs",children:"Last Run"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:C.toLocaleString()})]})]})}),e.jsxs(he,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(I,{htmlFor:"enabled",className:"text-base",children:"Enable Automated Cleanup"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically run system cleanup on a schedule"})]}),e.jsx(ma,{id:"enabled",checked:o,onCheckedChange:l})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(I,{htmlFor:"schedule",className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-4 w-4"}),"Cleanup Frequency"]}),e.jsxs(xe,{value:n,onValueChange:i,disabled:!o,children:[e.jsx(fe,{id:"schedule",children:e.jsx(ge,{})}),e.jsxs(je,{children:[e.jsx(H,{value:"daily",children:"Daily"}),e.jsx(H,{value:"weekly",children:"Weekly (Sunday)"}),e.jsx(H,{value:"monthly",children:"Monthly (1st of month)"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Cleanup will run ",n," at the specified time"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(I,{htmlFor:"time",className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"h-4 w-4"}),"Cleanup Time (24h format)"]}),e.jsxs(xe,{value:h,onValueChange:w,disabled:!o,children:[e.jsx(fe,{id:"time",children:e.jsx(ge,{})}),e.jsxs(je,{children:[e.jsx(H,{value:"00:00",children:"00:00 (Midnight)"}),e.jsx(H,{value:"02:00",children:"02:00 (2 AM)"}),e.jsx(H,{value:"04:00",children:"04:00 (4 AM)"}),e.jsx(H,{value:"06:00",children:"06:00 (6 AM)"}),e.jsx(H,{value:"12:00",children:"12:00 (Noon)"}),e.jsx(H,{value:"18:00",children:"18:00 (6 PM)"}),e.jsx(H,{value:"22:00",children:"22:00 (10 PM)"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Cleanup will run at ",h," (server time)"]})]}),o&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx(I,{className:"text-sm font-medium mb-2 block",children:"Cron Expression"}),e.jsx("code",{className:"text-xs bg-muted px-2 py-1 rounded",children:L()})]}),e.jsx(k,{onClick:ee,disabled:d,className:"w-full",children:d?"Saving...":"Save Schedule"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Note: Automated cleanup will clean old audit logs, maintenance events, email logs, and archived records based on retention policies."})]})]})};function rt(){const{isPlatformAdmin:n}=Ys(),[i,h]=t.useState(!1),[w,o]=t.useState(!1),[l,x]=t.useState(null),[c,d]=t.useState(!1),N=async m=>{d(!1),h(!0),o(!0),x(null);try{g.info("Starting System Cleanup",{description:`Analyzing ${m==="ALL"?"all applications":m}...`});const{data:_,error:E}=await j.functions.invoke("system-cleanup",{body:{application:m}});if(E)throw E;x(_),g.success("System Cleanup Complete",{description:`Fixed ${_.issues_fixed} issues. Email report sent.`})}catch(_){console.error("Cleanup error:",_),g.error("Cleanup Failed",{description:_ instanceof Error?_.message:"An error occurred during cleanup"})}finally{h(!1),o(!1)}},C=async()=>{o(!1);const{error:m}=await j.from("system_maintenance").delete().eq("status","running");m?(console.error("Error stopping cleanup:",m),g.error("Failed to stop cleanup")):(h(!1),g.info("Cleanup stopped by administrator"))};return e.jsx("div",{className:"space-y-6",children:n?e.jsxs(e.Fragment,{children:[e.jsx(Ea,{}),e.jsxs(Rs,{defaultValue:"cleanup",className:"w-full",children:[e.jsxs(Is,{children:[e.jsxs(Fe,{value:"cleanup",className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-4 w-4"}),"Run Cleanup"]}),e.jsxs(Fe,{value:"logs",className:"flex items-center gap-2",children:[e.jsx(ze,{className:"h-4 w-4"}),"Cleanup Logs"]})]}),e.jsx(Re,{value:"cleanup",children:e.jsxs(ie,{children:[e.jsxs(ve,{children:[e.jsxs(ye,{className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-5 w-5"}),"System Cleanup"]}),e.jsx(_e,{children:"Automatically scan and repair issues across all applications"})]}),e.jsxs(he,{className:"space-y-6 max-w-4xl",children:[e.jsxs(Ae,{children:[e.jsx(Js,{className:"h-4 w-4"}),e.jsx(Ze,{children:"What does System Cleanup do?"}),e.jsxs(Te,{className:"mt-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm mt-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-primary mb-1",children:"🔍 Data Integrity Checks"}),e.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-muted-foreground",children:[e.jsx("li",{children:"Orphaned user access records"}),e.jsx("li",{children:"Vehicle notes without vehicles"}),e.jsx("li",{children:"SOP notes without parts"}),e.jsx("li",{children:"Registration orphaned documents"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-primary mb-1",children:"🧹 Orphan Cleanup"}),e.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-muted-foreground",children:[e.jsx("li",{children:"Deletes orphaned records safely"}),e.jsx("li",{children:"Cleans broken foreign key refs"}),e.jsx("li",{children:"Vehicle photos are NEVER deleted"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-primary mb-1",children:"⚡ Stuck Process Clearing"}),e.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-muted-foreground",children:[e.jsx("li",{children:"Scrape jobs stuck >20 min"}),e.jsx("li",{children:"Maintenance stuck >30 min"}),e.jsx("li",{children:"Inventory imports stuck >1 hr"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-primary mb-1",children:"📋 Log Cleanup"}),e.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-muted-foreground",children:[e.jsx("li",{children:"Audit logs >90 days"}),e.jsx("li",{children:"Email logs >60 days"}),e.jsx("li",{children:"Archived prewrite >180 days"})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-3 border-t pt-2",children:"📧 A detailed HTML email report is sent after each cleanup run"})]})]}),l&&e.jsxs(Ae,{className:l.issues_fixed>0?"border-green-500 bg-green-50/50":"border-blue-500 bg-blue-50/50",children:[e.jsx(ha,{className:"h-4 w-4"}),e.jsx(Ze,{className:"text-lg",children:"Cleanup Results"}),e.jsx(Te,{className:"mt-3",children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-3 text-center",children:[e.jsxs("div",{className:"bg-background p-3 rounded-lg border",children:[e.jsx("p",{className:"text-2xl font-bold text-primary",children:l.application}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Application"})]}),e.jsxs("div",{className:"bg-background p-3 rounded-lg border",children:[e.jsx("p",{className:"text-2xl font-bold text-amber-600",children:l.issues_found}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Issues Found"})]}),e.jsxs("div",{className:"bg-background p-3 rounded-lg border",children:[e.jsx("p",{className:"text-2xl font-bold text-green-600",children:l.issues_fixed}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Issues Fixed"})]}),e.jsxs("div",{className:"bg-background p-3 rounded-lg border",children:[e.jsx("p",{className:"text-2xl font-bold text-purple-600",children:l.stuck_processes_cleared||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Stuck Cleared"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Duration: ",l.duration_seconds,"s |",l.email_sent?" ✅ Email report sent":" ⚠️ Email not configured"]}
11),l.integrity_checks&&l.integrity_checks.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold mb-2 text-primary",children:"🔍 Data Integrity Checks"}),e.jsx("div",{className:"bg-background rounded-lg border overflow-hidden",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-2",children:"Category"}),e.jsx("th",{className:"text-left p-2",children:"Check"}),e.jsx("th",{className:"text-center p-2",children:"Found"}),e.jsx("th",{className:"text-center p-2",children:"Status"})]})}),e.jsx("tbody",{children:l.integrity_checks.slice(0,8).map((m,_)=>e.jsxs("tr",{className:"border-t",children:[e.jsx("td",{className:"p-2 font-medium",children:m.category}),e.jsx("td",{className:"p-2",children:m.description}),e.jsx("td",{className:"p-2 text-center",children:m.found}),e.jsx("td",{className:"p-2 text-center",children:m.status==="success"?"✅":"❌"})]},_))})]})})]}),l.stuck_processes&&l.stuck_processes.some(m=>m.found>0)&&e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold mb-2 text-primary",children:"⚡ Stuck Processes Cleared"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.stuck_processes.filter(m=>m.found>0).map((m,_)=>e.jsxs("span",{className:"bg-purple-100 text-purple-800 px-2 py-1 rounded text-xs",children:[m.category,": ",m.fixed," cleared"]},_))})]}),l.log_cleanup&&l.log_cleanup.some(m=>m.fixed>0)&&e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold mb-2 text-primary",children:"📋 Logs Cleaned"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.log_cleanup.filter(m=>m.fixed>0).map((m,_)=>e.jsxs("span",{className:"bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs",children:[m.category,": ",m.fixed," deleted"]},_))})]}),l.recommendations&&l.recommendations.length>0&&e.jsxs("div",{className:"bg-muted p-3 rounded-md",children:[e.jsx("p",{className:"font-semibold mb-2",children:"💡 Recommendations:"}),e.jsx("ul",{className:"space-y-1.5",children:l.recommendations.map((m,_)=>e.jsx("li",{className:"text-sm",children:m},_))})]})]})})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(k,{onClick:()=>d(!0),disabled:i,className:"flex-1",size:"lg",children:i?e.jsxs(e.Fragment,{children:[e.jsx(se,{className:"h-5 w-5 animate-spin mr-2"}),"Running System Cleanup..."]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-5 w-5 mr-2"}),"Run System Cleanup"]})}),w&&e.jsxs(k,{onClick:C,variant:"destructive",size:"lg",children:[e.jsx(pa,{className:"h-5 w-5 mr-2"}),"Force Stop"]})]}),e.jsx(Ke,{open:c,onOpenChange:d,children:e.jsxs(qe,{children:[e.jsxs(We,{children:[e.jsx(Ge,{children:"Select Application to Clean"}),e.jsx(as,{children:"Choose which application to run cleanup on, or select ALL for a comprehensive system-wide cleanup."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 mt-4",children:[e.jsx(k,{onClick:()=>N("Lot Manager"),variant:"outline",className:"h-20",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-semibold",children:"Lot Manager"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Inventory Management"})]})}),e.jsx(k,{onClick:()=>N("Pre-Write"),variant:"outline",className:"h-20",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-semibold",children:"Pre-Write"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Service Estimates"})]})}),e.jsx(k,{onClick:()=>N("Registration Tracker"),variant:"outline",className:"h-20",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-semibold",children:"Registration Tracker"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Vehicle Registration"})]})}),e.jsx(k,{onClick:()=>N("Special Order Parts"),variant:"outline",className:"h-20",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-semibold",children:"Special Order Parts"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Parts Management"})]})}),e.jsx(k,{onClick:()=>N("Quote Builder"),variant:"outline",className:"h-20",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-semibold",children:"Quote Builder"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Customer Quotes"})]})}),e.jsx(k,{onClick:()=>N("ALL"),variant:"default",className:"col-span-2 h-20",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-semibold text-lg",children:"ALL APPLICATIONS"}),e.jsx("p",{className:"text-xs",children:"Comprehensive system-wide cleanup"})]})})]})]})})]})]})}),e.jsx(Re,{value:"logs",children:e.jsx(Sa,{})})]})]}):e.jsxs(Ae,{children:[e.jsx(ua,{className:"h-4 w-4"}),e.jsx(Ze,{children:"System Cleanup is platform-wide"}),e.jsx(Te,{children:"System cleanup mutates data across all organizations and is restricted to platform administrators. Org-scoped cleanup is coming soon."})]})})}function nt(){const n=Xs(),[i,h]=t.useState(""),[w,o]=t.useState(""),[l,x]=t.useState(""),[c,d]=t.useState(""),[N,C]=t.useState(""),[m,_]=t.useState(!1),[E,L]=t.useState(!1),[ee,F]=t.useState(""),[p,v]=t.useState(""),[M,D]=t.useState(""),{guardMutation:q,isDemoUser:z}=xa(),{selectedDealership:V}
11=Zs(),{data:W,isLoading:ce}=ea({queryKey:["email-settings",V==null?void 0:V.code],queryFn:async()=>{const{data:r,error:X}=await j.from("system_config").select("config_key, config_value").in("config_key",["from_email_address","global_notification_email","maintenance_summary_email","resend_api_key","openai_api_key","crm_email"]);if(X)throw X;const Y=r==null?void 0:r.find(R=>R.config_key==="from_email_address"),K=r==null?void 0:r.find(R=>R.config_key==="global_notification_email"),$=r==null?void 0:r.find(R=>R.config_key==="maintenance_summary_email"),ae=r==null?void 0:r.find(R=>R.config_key==="resend_api_key"),te=r==null?void 0:r.find(R=>R.config_key==="openai_api_key"),be=r==null?void 0:r.find(R=>R.config_key==="crm_email");if(h((Y==null?void 0:Y.config_value)||""),o((K==null?void 0:K.config_value)||""),x(($==null?void 0:$.config_value)||""),D((be==null?void 0:be.config_value)||""),_(!!(ae!=null&&ae.config_value)),L(!!(te!=null&&te.config_value)),V){const{data:R}=await j.from("crm_configuration").select("*").eq("dealership_code",V.code).maybeSingle();R&&(F(R.crm_endpoint_url||""),v(R.crm_provider||""))}return r}}),oe=es({mutationFn:q(async()=>{const{error:r}=await j.from("system_config").upsert({config_key:"from_email_address",config_value:i,description:"Email address used as sender for all system emails"},{onConflict:"config_key"});if(r)throw r;const{error:X}=await j.from("system_config").upsert({config_key:"global_notification_email",config_value:w,description:"Email address to receive system notifications and reports"},{onConflict:"config_key"});if(X)throw X;const{error:Y}=await j.from("system_config").upsert({config_key:"maintenance_summary_email",config_value:l,description:"Email address to receive automated maintenance summary reports"},{onConflict:"config_key"});if(Y)throw Y;const{error:K}=await j.from("system_config").upsert({config_key:"crm_email",config_value:M,description:"Email address to receive CRM lead notifications from chat"},{onConflict:"config_key"});if(K)throw K;if(c.trim()){const{error:$}=await j.from("system_config").upsert({config_key:"resend_api_key",config_value:c,description:"Resend API key for sending emails"},{onConflict:"config_key"});if($)throw $;d(""),_(!0)}if(N.trim()){const{error:$}=await j.from("system_config").upsert({config_key:"openai_api_key",config_value:N,description:"OpenAI API key for AI features"},{onConflict:"config_key"});if($)throw $;C(""),L(!0)}if(V&&ee.trim()){const{error:$}=await j.from("crm_configuration").upsert({dealership_code:V.code,crm_endpoint_url:ee,crm_provider:p,is_active:!0});if($)throw $}},"Cannot save email settings in demo mode"),onSuccess:()=>{n.invalidateQueries({queryKey:["email-settings"]}),g.success("Email settings saved successfully")},onError:r=>{console.error("Error saving email settings:",r),g.error("Failed to save email settings")}}),de=es({mutationFn:q(async()=>{const{error:r}=await j.from("system_config").delete().eq("config_key","resend_api_key");if(r)throw r},"Cannot delete API key in demo mode"),onSuccess:()=>{_(!1),d(""),n.invalidateQueries({queryKey:["email-settings"]}),g.success("API key deleted successfully")},onError:r=>{console.error("Error deleting API key:",r),g.error("Failed to delete API key")}}),Q=es({mutationFn:q(async()=>{const{error:r}=await j.from("system_config").delete().eq("config_key","openai_api_key");if(r)throw r},"Cannot delete OpenAI API key in demo mode"),onSuccess:()=>{L(!1),C(""),n.invalidateQueries({queryKey:["email-settings"]}),g.success("OpenAI API key deleted successfully")},onError:r=>{console.error("Error deleting OpenAI API key:",r),g.error("Failed to delete OpenAI API key")}});return ce?e.jsxs(ie,{children:[e.jsx(ve,{children:e.jsxs(ye,{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"h-5 w-5"}),"Email Configuration"]})}),e.jsx(he,{children:e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(se,{className:"h-6 w-6 animate-spin"})})})]}):e.jsxs(ie,{children:[e.jsxs(ve,{children:[e.jsxs(ye,{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"h-5 w-5"}),"Email Configuration"]}),e.jsx(_e,{children:"Configure email addresses used throughout the system"})]}),e.jsxs(he,{className:"space-y-6 max-w-2xl",children:[e.jsx(fa,{}),e.jsxs("div",{className:"space-y-2 max-w-lg",children:[e.jsx(I,{htmlFor:"from-email",children:"From Email Address"}),e.jsx(ne,{id:"from-email",type:"email",placeholder:"[email protected]",value:i,onChange:r=>h(r.target.value)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This email address will be used as the sender for all system emails (must be verified in your Resend account)"})]}),e.jsxs("div",{className:"space-y-2 max-w-lg",children:[e.jsx(I,{htmlFor:"notification-email",children:"Recipient Email (for notifications)"}),e.jsx(ne,{id:"notification-email",type:"email",placeholder:"[email protected]",value:w,onChange:r=>o(r.target.value)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This email will receive automated reports, alerts, and system notifications"})]}),e.jsxs("div",{className:"space-y-2 max-w-lg",children:[e.jsx(I,{htmlFor:"maintenance-email",children:"Maintenance Summary Email"}),e.jsx(ne,{id:"maintenance-email",type:"email",placeholder:"[email protected]",value:l,onCh
11ange:r=>x(r.target.value)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This email will receive automated maintenance completion reports"})]}),e.jsxs("div",{className:"space-y-2 max-w-lg",children:[e.jsx(I,{htmlFor:"crm-email",children:"CRM Lead Email"}),e.jsx(ne,{id:"crm-email",type:"email",placeholder:"[email protected]",value:M,onChange:r=>D(r.target.value)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This email will receive chat lead information when sent to CRM"})]}),V&&e.jsx(e.Fragment,{children:e.jsxs("div",{className:"border-t pt-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"h-5 w-5"}),e.jsx("h3",{className:"text-lg font-semibold",children:"CRM Integration (ADF/XML)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure CRM endpoint for pushing chat leads"}),e.jsxs("div",{className:"space-y-2 max-w-lg",children:[e.jsx(I,{htmlFor:"crm-endpoint",children:"CRM Endpoint URL"}),e.jsx(ne,{id:"crm-endpoint",type:"url",placeholder:"https://crm.yourdealership.com/adf/leads",value:ee,onChange:r=>F(r.target.value)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Enter the ADF/XML endpoint URL provided by your CRM vendor"})]}),e.jsxs("div",{className:"space-y-2 max-w-lg",children:[e.jsx(I,{htmlFor:"crm-provider",children:"CRM Provider (Optional)"}),e.jsx(ne,{id:"crm-provider",type:"text",placeholder:"e.g., DealerSocket, VinSolutions, Eleads",value:p,onChange:r=>v(r.target.value)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Name of your CRM provider for reference"})]})]})}),e.jsxs("div",{className:"space-y-2 max-w-lg border-t pt-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(I,{htmlFor:"resend-api-key",className:"flex items-center gap-2",children:[e.jsx(Ve,{className:"h-4 w-4"}),"Resend API Key"]}),m&&e.jsx(k,{variant:"ghost",size:"sm",onClick:()=>de.mutate(),disabled:de.isPending,className:"text-destructive hover:text-destructive",children:de.isPending?e.jsx(se,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ye,{className:"h-4 w-4 mr-1"}),"Delete Key"]})})]}),m?e.jsxs(Ae,{children:[e.jsx(Ve,{className:"h-4 w-4"}),e.jsx(Te,{children:"API key is configured and hidden for security. Delete to add a new one."})]}):e.jsxs(e.Fragment,{children:[e.jsx(ne,{id:"resend-api-key",type:"password",placeholder:"re_••••••••••••••••••••",value:c,onChange:r=>d(r.target.value)}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:["Get your API key from"," ",e.jsxs("a",{href:"https://resend.com/api-keys",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["resend.com/api-keys",e.jsx(us,{className:"h-3 w-3"})]})]})]})]}),e.jsxs("div",{className:"space-y-2 max-w-lg",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(I,{htmlFor:"openai-api-key",className:"flex items-center gap-2",children:[e.jsx(Ve,{className:"h-4 w-4"}),"OpenAI API Key"]}),E&&e.jsx(k,{variant:"ghost",size:"sm",onClick:()=>Q.mutate(),disabled:Q.isPending,className:"text-destructive hover:text-destructive",children:Q.isPending?e.jsx(se,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ye,{className:"h-4 w-4 mr-1"}),"Delete Key"]})})]}),E?e.jsxs(Ae,{children:[e.jsx(Ve,{className:"h-4 w-4"}),e.jsx(Te,{children:"OpenAI API key is configured and hidden for security. Delete to add a new one."})]}):e.jsxs(e.Fragment,{children:[e.jsx(ne,{id:"openai-api-key",type:"password",placeholder:"sk-••••••••••••••••••••",value:N,onChange:r=>C(r.target.value)}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:["Get your API key from"," ",e.jsxs("a",{href:"https://platform.openai.com/api-keys",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["platform.openai.com/api-keys",e.jsx(us,{className:"h-3 w-3"})]})]})]})]}),e.jsx(k,{onClick:()=>oe.mutate(),disabled:oe.isPending||z,children:oe.isPending?e.jsxs(e.Fragment,{children:[e.jsx(se,{className:"mr-2 h-4 w-4 animate-spin"}),"Saving..."]}):z?"Demo Mode - View Only":e.jsxs(e.Fragment,{children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),"Save Email Settings"]})})]})]})}const Aa={"Lot Manager":[{label:"Vehicle is added",value:"vehicle_added"},{label:"Vehicle is deleted",value:"vehicle_deleted"},{label:"Vehicle status changes",value:"status_changed"},{label:"Vehicle status changes to 'Ready'",value:"status_ready"},{label:"Vehicle status changes to 'Sold'",value:"status_sold"},{label:"Photos are uploaded",value:"photos_uploaded"},{label:"Price is changed",value:"price_changed"},{label:"Vehicle exceeds 30 days in inventory",value:"days_30_plus"},{label:"Vehicle exceeds 60 days in inventory",value:"days_60_plus"}],"SOP Manager":[{label:"New SOP is created",value:"sop_created"},{label:"SOP is deleted",value:"sop_deleted"},{label:"Advisor is assigned",value:"advisor_assigned"},{label:"Parts status changes to 'Here'",value:"parts_here"},{label:"Appointment is set",value:"appointment_set"},{label:"Call outcome is recorded",value:"call_outcome"},{label:"SOP status changes to 'Contacted'",value:"status_contacted"},{label:"SOP status changes to 'Completed'",value:"status_completed"},{label:"SOP exceeds 7 days without contact",value:"no_contact_7_days"}],"Registration Tracker":[{label:"New registration is created",value:"registration_created"},{label:"Registration status changes",value:"status_changed"},{label:"Salesperson is assigned",value:"salesperson_assigned"},{label:"Documents are uploaded",value:"documents_uploaded"},{label:"Issue is reported",value:"issue_reported"},{label:"Registration is completed",value:"registration_completed"},{label:"Registration exceeds 5 days pending",value:"pending_5_days"}],"Missed Opportunities":[{label:"New campaign vehicle is added",value:"campaign_created"},{label:"Advisor is assigned",value:"advisor_assigned"},{label:"Appointment is scheduled",value:"appointment_scheduled"},{label:"Campaign status changes",value:"status_changed"},{label:"Note is added",value:"note_added"}],PreWrite:[{label:"New record is created",value:"record_created"},{label:"Service is selected",value:"service_selected"},{label:"Appointment status changes",value:"appointment_status_changed"},{label:"Record is archived",value:"record_archived"}],Recon:[{label:"New issue is created",value:"issue_created"},{label:"Issue is resolved",value:"issue_resolved"},{label:"User is assigned",value:"user_assigned"},{label:"Priority is changed",value:"priority_changed"},{label:"Recon status changes",value:"status_changed"}]},Ta=["Ready for Service","IN PROCESS","ISSUE","DONE"],Fa=["RECON","ISSUE","DONE"];function Ra({appName:n,trigger:i,onChange:h}){var x,c;const w=Aa[n]||[],o=d=>{console.log("Selected event:",d);const N=w.find(C=>C.value===d);if(console.log("Found event:",N),N){const C={event:N.value,label:N.label};N.value==="status_changed"&&(C.conditions={}),console.log("Calling onChange with:",C),h(C)}else h(null)},l=d=>{if(i){const N={...i,conditions:{...i.conditions,status:d}};h(N)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(I,{children:"Trigger Event (WHEN/THEN)"}),w.length===0?e.jsx("div",{className:"border border-dashed rounded-lg p-6 text-center",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Please select an ",e.jsx("strong",{children:"Application"})," above to see available trigger events"]})}):e.jsxs("div",{className:"border rounded-lg p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{className:"text-sm font-medium",children:"WHEN"}),e.jsxs(xe,{value:(i==null?void 0:i.event)||"",onValueChange:o,children:[e.jsx(fe,{children:e.jsx(ge,{placeholder:"Select a trigger event"})}),e.jsx(je,{className:"z-[100] bg-popover",children:w.map(d=>e.jsx(H,{value:d.value,children:d.label},d.value))})]})]}),(i==null?void 0:i.event)==="status_changed"&&(n==="Lot Manager"||n==="Recon")&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{className:"text-sm font-medium",children:"Specific Status"}
11),e.jsxs(xe,{value:((x=i.conditions)==null?void 0:x.status)||"",onValueChange:l,children:[e.jsx(fe,{children:e.jsx(ge,{placeholder:"Select a status"})}),e.jsx(je,{className:"z-[100] bg-popover",children:(n==="Lot Manager"?Ta:Fa).map(d=>e.jsx(H,{value:d,children:d},d))})]})]}),i&&e.jsxs("div",{className:"text-sm bg-primary/10 text-primary rounded p-3 border border-primary/20",children:[e.jsx("strong",{children:"WHEN:"})," ",i.label," in ",n,((c=i.conditions)==null?void 0:c.status)&&e.jsxs("span",{children:[" to ",e.jsx("strong",{children:i.conditions.status})]}),e.jsx("br",{}),e.jsx("strong",{children:"THEN:"})," Send this email template to subscribers"]}),!i&&e.jsx("div",{className:"text-xs text-muted-foreground bg-muted/50 rounded p-3",children:"Select a trigger event to define when this template will be sent"})]})]})}const Ia=[{label:"Notification",value:"notification"},{label:"Summary",value:"summary"}],Ue={"Lot Manager":[{label:"Year Make Model",value:"{{vehicle_year}} {{vehicle_make}} {{vehicle_model}}"},{label:"Vehicle Year",value:"{{vehicle_year}}"},{label:"Vehicle Make",value:"{{vehicle_make}}"},{label:"Vehicle Model",value:"{{vehicle_model}}"},{label:"Stock Number",value:"{{stock_number}}"},{label:"VIN",value:"{{vin}}"},{label:"Last 8 (VIN)",value:"{{last_8_vin}}"},{label:"Status",value:"{{status}}"},{label:"Location",value:"{{location}}"},{label:"Work Type",value:"{{work_type}}"},{label:"New/Used",value:"{{vehicle_type}}"},{label:"Issue Details",value:"{{issue_note}}"}],"SOP Manager":[{label:"Customer Name",value:"{{customer_name}}"},{label:"Customer Phone",value:"{{customer_phone}}"},{label:"Customer Email",value:"{{email_address}}"},{label:"RO Number",value:"{{ro_number}}"},{label:"Customer Type",value:"{{customer_type}}"},{label:"Vehicle Location",value:"{{vehicle_location}}"},{label:"Parts Status",value:"{{parts_status}}"},{label:"Appointment Date",value:"{{appointment_date}}"},{label:"Appointment Time",value:"{{appointment_time}}"},{label:"Appointment Status",value:"{{appointment_status}}"},{label:"Advisor Name",value:"{{advisor_name}}"},{label:"VIN",value:"{{vin}}"},{label:"Arrival Date",value:"{{arrival_date}}"},{label:"Work Completed",value:"{{work_completed}}"}],"Registration Tracker":[{label:"Customer Name",value:"{{customer_name}}"},{label:"Year Make Model",value:"{{vehicle_year}} {{vehicle_make}} {{vehicle_model}}"},{label:"Vehicle Make",value:"{{vehicle_make}}"},{label:"Vehicle Model",value:"{{vehicle_model}}"},{label:"Registration Status",value:"{{registration_status}}"}],"Missed Opportunities":[{label:"Customer Name",value:"{{customer_name}}"},{label:"Customer Phone",value:"{{customer_phone}}"},{label:"Vehicle VIN",value:"{{vin}}"},{label:"Advisor Name",value:"{{advisor_name}}"}],PreWrite:[{label:"Customer Name",value:"{{customer_name}}"},{label:"Year Make Model",value:"{{vehicle_year}} {{vehicle_make}} {{vehicle_model}}"},{label:"Vehicle Make",value:"{{vehicle_make}}"},{label:"Vehicle Model",value:"{{vehicle_model}}"},{label:"Mileage",value:"{{mileage}}"}],Recon:[{label:"Stock Number",value:"{{stock_number}}"},{label:"Year Make Model",value:"{{year_make_model}}"},{label:"VIN (Last 8)",value:"{{vin_last_8}}"},{label:"Recon Status",value:"{{status}}"},{label:"Cleaned By",value:"{{cleaned_by}}"},{label:"Photos By",value:"{{photos_by}}"},{label:"Recon Completed Date",value:"{{recon_completed_at}}"},{label:"Work Type",value:"{{work_type}}"},{label:"Issue Details",value:"{{issue_note}}"},{label:"Issue Resolution",value:"{{issue_resolution_note}}"},{label:"New/Used",value:"{{vehicle_type}}"},{label:"Color",value:"{{color}}"},{label:"Mileage",value:"{{miles}}"}],"Quote Builder":[{label:"Customer Name",value:"{{customer_name}}"},{label:"Quote Amount",value:"{{quote_amount}}"},{label:"Quote Date",value:"{{quote_date}}"}],Calendar:[{label:"Event Title",value:"{{event_title}}"},{label:"Event Date",value:"{{event_date}}"},{label:"Event Time",value:"{{event_time}}"}],Mail:[{label:"Sender Name",value:"{{sender_name}}"},{label:"Subject",value:"{{email_subject}}"},{label:"Date",value:"{{email_date}}"}]};function it(){const{toast:n}=sa(),[i,h]=t.useState([]),[w,o]=t.useState(!0),[l,x]=t.useState(!1),[c,d]=t.useState(!1),[N,C]=t.useState(null),[m,_]=t.useState(null),{data:E,isLoading:L}=aa(),ee=(E==null?void 0:E.map(s=>s.app_name))||[],[F,p]=t.useState(""),[v,M]=t.useState(""),[D,q]=t.useState(""),[z,V]=t.useState(""),[W,ce]=t.useState(""),[oe,de]=t.useState(null),[Q,r]=t.useState("plain"),X=t.useRef(null),Y=t.useRef(null);t.useEffect(()=>{K()},[]);const K=async()=>{try{const{data:s,error:G}=await j.from("custom_email_templates").select("*").order("created_at",{ascending:!1});if(G)throw G;h(s||[])}catch(s){console.error("Error fetching templates:",s),n({title:"Error",description:"Failed to load templates",variant:"destructive"})}finally{o(!1)}},$=s=>s.split(`
12
13`).map(G=>`<p>${G.replace(/\n/g,"<br>")}</p>`).join(""),ae=s=>s.replace(/<p>/g,"").replace(/<\/p>/g,`
14
15`).replace(/<br>/g,`
16`).trim(),te=async()=>
16{if(!F||!v||!D||!z||!W){n({title:"Validation Error",description:"Please fill in all required fields",variant:"destructive"});return}try{const s=$(W);if(m){const{error:G}=await j.from("custom_email_templates").update({app_name:v,template_name:F,template_type:D,subject_template:z,body_template:s,trigger_conditions:oe,updated_at:new Date().toISOString()}).eq("id",m.id);if(G)throw G;n({title:"Success",description:"Template updated successfully"})}else{const{error:G}=await j.from("custom_email_templates").insert({app_name:v,template_name:F,template_type:D,subject_template:z,body_template:s,trigger_conditions:oe,is_active:!0});if(G)throw G;n({title:"Success",description:"Template created successfully"})}R(),x(!1),_(null),K()}catch(s){console.error("Error saving template:",s),n({title:"Error",description:"Failed to save template",variant:"destructive"})}},be=async()=>{if(N)try{const{error:s}=await j.from("custom_email_templates").delete().eq("id",N);if(s)throw s;n({title:"Success",description:"Template deleted successfully"}),d(!1),C(null),K()}catch(s){console.error("Error deleting template:",s),n({title:"Error",description:"Failed to delete template",variant:"destructive"})}},R=()=>{p(""),M(""),q(""),V(""),ce(""),de(null),r("plain"),_(null)},Je=s=>{_(s),p(s.template_name),M(s.app_name),q(s.template_type),V(s.subject_template),ce(ae(s.body_template)),de(s.trigger_conditions),r("plain"),x(!0)},De=(s,G)=>{if(G==="subject"){const J=X.current;if(J){const me=J.selectionStart||0,we=J.selectionEnd||0,a=z.substring(0,me)+s+z.substring(we);V(a),setTimeout(()=>{J.focus(),J.setSelectionRange(me+s.length,me+s.length)},0)}}else{const J=Y.current;if(J){const me=J.selectionStart||0,we=J.selectionEnd||0,a=W.substring(0,me)+s+W.substring(we);ce(a),setTimeout(()=>{J.focus(),J.setSelectionRange(me+s.length,me+s.length)},0)}}},$e=s=>e.jsx("div",{dangerouslySetInnerHTML:{__html:ja.sanitize(s)}});return w?e.jsx("div",{className:"text-center py-8",children:"Loading templates..."}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Email Template Builder"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create custom email templates with trigger conditions"})]}),e.jsxs(Ke,{open:l,onOpenChange:s=>{x(s),s||R()},children:[e.jsx(Ns,{asChild:!0,children:e.jsxs(k,{children:[e.jsx(ta,{className:"h-4 w-4 mr-2"}),"Create Template"]})}),e.jsxs(qe,{className:"overflow-y-auto",children:[e.jsx(We,{children:e.jsx(Ge,{children:m?"Edit Template":"Create New Template"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(I,{children:"Template Name"}),e.jsx(ne,{value:F,onChange:s=>p(s.target.value),placeholder:"e.g., Vehicle Ready Notification"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(I,{children:"Application"}),e.jsxs(xe,{value:v,onValueChange:M,children:[e.jsx(fe,{children:L?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:"Loading..."})]}):e.jsx(ge,{placeholder:"Select app"})}),e.jsx(je,{children:ee.map(s=>e.jsx(H,{value:s,children:s},s))})]})]}),e.jsxs("div",{children:[e.jsx(I,{children:"Template Type"}),e.jsxs(xe,{value:D,onValueChange:q,children:[e.jsx(fe,{children:e.jsx(ge,{placeholder:"Select type"})}),e.jsx(je,{children:Ia.map(s=>e.jsx(H,{value:s.value,children:s.label},s.value))})]})]})]})]}),v&&e.jsx(Ra,{appName:v,trigger:oe,onChange:s=>{console.log("TriggerBuilder onChange called with:",s),de(s)}}),e.jsxs(Rs,{value:Q,onValueChange:r,children:[e.jsxs(Is,{className:"grid w-full grid-cols-3",children:[e.jsx(Fe,{value:"plain",children:"Plain Text"}),e.jsx(Fe,{value:"html",children:"HTML"}),e.jsx(Fe,{value:"preview",children:"Preview"})]}),e.jsxs(Re,{value:"plain",className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(I,{children:"Subject Line"}),v&&Ue[v]&&e.jsxs(xe,{onValueChange:s=>De(s,"subject"),children:[e.jsx(fe,{className:"w-[200px] h-8",children:e.jsx(ge,{placeholder:"Insert Field"})}),e.jsx(je,{children:Ue[v].map(s=>e.jsx(H,{value:s.value,children:s.label},s.value))})]})]}),e.jsx(ne,{ref:X,value:z,onChange:s=>V(s.target.value),placeholder:"Enter email subject"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(I,{children:"Message Body"}),v&&Ue[v]&&e.jsxs(xe,{onValueChange:s=>De(s,"body"),children:[e.jsx(fe,{className:"w-[200px] h-8",children:e.jsx(ge,{placeholder:"Insert Field"})}),e.jsx(je,{children:Ue[v].map(s=>e.jsx(H,{value:s.value,children:s.label},s.value))})]})]}),e.jsx(hs,{ref:Y,value:W,onChange:s=>ce(s.target.value),rows:8,placeholder:"Enter your message here. Use double line breaks for paragraphs."})]})]}),e.jsx(Re,{value:"html",children:e.jsxs("div",{children:[e.jsx(I,{className:"text-xs text-muted-foreground mb-2 block",children:"HTML Version (auto-generated from plain text)"}),e.jsx(hs,{value:$(W),readOnly:!0,rows:8,className:"font-mono text-sm bg-muted"})]})}),e.jsxs(Re,{value:"preview",className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Subject Line Preview"}),e.jsx("div",{className:"border rounded-lg p-3 bg-background min-h-[40px]",children:$e(z)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Email Body Preview"}),e.jsx("div",{className:"border rounded-lg p-4 bg-background min-h-[120px]",children:$e($(W))})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(k,{variant:"outline",onClick:()=>{x(!1),R()},children:"Cancel"}),e.jsx(k,{onClick:te,children:m?"Update Template":"Save Template"})]})]})]})]})]}),e.jsx("div",{className:"grid gap-4",children:i.length===0?e.jsx(ie,{children:e.jsx(he,{className:"py-12 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:'No templates created yet. Click "Create Template" to get started.'})})}):i.map(s=>e.jsxs(ie,{children:[e.jsx(ve,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(ye,{className:"text-lg",children:s.template_name}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx("span",{className:"text-xs bg-primary/10 text-primary px-2 py-1 rounded",children:s.app_name}),e.jsx("span",{className:"text-xs bg-secondary/10 text-secondary-foreground px-2 py-1 rounded",children:s.template_type}),s.trigger_conditions&&e.jsxs("span",{className:"text-xs bg-accent/10 text-accent-foreground px-2 py-1 rounded",children:["Trigger: ",s.trigger_conditions.label]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(k,{variant:"ghost",size:"icon",onClick:()=>Je(s),children:e.jsx(va,{className:"h-4 w-4"})}),e.jsx(k,{variant:"ghost",size:"icon",onClick:()=>{C(s.id),d(!0)},children:e.jsx(Ye,{className:"h-4 w-4 text-destructive"})})]})]})}),e.jsxs(he,{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Subject:"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s.subject_template})]}),s.trigger_conditions&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Trigger:"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[e.jsx("span",{className:"font-medium",children:"WHEN:"})," ",s.trigger_conditions.label,e.jsx("br",{}),e.jsx("span",{className:"font-medium",children:"THEN:"})," Send this template to subscribers"]}
16)]})]})]},s.id))}),e.jsx(ws,{open:c,onOpenChange:d,children:e.jsxs(ks,{children:[e.jsxs(Cs,{children:[e.jsx(Ss,{children:"Delete Template"}),e.jsx(Es,{children:"Are you sure you want to delete this template? This action cannot be undone."})]}),e.jsxs(As,{children:[e.jsx(Ts,{onClick:()=>C(null),children:"Cancel"}),e.jsx(Fs,{onClick:be,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}export{it as C,lt as D,nt as E,ya as H,rt as S};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.