PageSourceSearch

https://swus-erp.lovable.app/assets/erp.settings-DgZlXxzm.js

js swus-erp.lovable.app collected 2026-10-03 03:40:04 UTC 113,616 bytes, 2 lines download raw bytes

1import{c as oe,h as K,r as f,s as q,j as e,i as Z,a as ae}from"./index-EB60i8_b.js";import{u as me}from"./brand-context-jy_uMzVx.js";import{u as L}from"./useQuery-CD633ads.js";import{u as M}from"./useMutation-B66l_5Oh.js";import{t as _}from"./index-B1qPRzBi.js";import{I as b}from"./input-D8MgPrVN.js";import{L as k}from"./label-B_revbFK.js";import{B as w}from"./button-vMBgSq5N.js";import{T as Y}from"./textarea-BXC_JKsL.js";import{S as J}from"./skeleton-C6LproLv.js";import{I as Ns}from"./image-BngFkn6a.js";import{L as I}from"./loader-circle-D9lJnZUL.js";import{U as ws}from"./upload-mWfFtcXq.js";import{T as ge}from"./trash-2-BZTVKg0m.js";import{F as os}from"./file-text-Ae3gmFrk.js";import{S as $}from"./save-ckH3rmbb.js";import{T as ms}from"./tag-50b3fwqu.js";import{X as Ge}from"./x-rtEj0dnA.js";import{P as Se}from"./plus-erq3DUUs.js";import{c as ee,r as se,u as C}from"./auth-middleware-BXg-s9l0.js";import{S as U}from"./switch-DeZ_rl-2.js";import{B as W}from"./badge-CppVMURX.js";import{D as Re,e as us,a as Oe,b as Ie,c as $e,d as ze}from"./dialog-CQs09mcw.js";import{S as T,a as E,b as F,c as D,d as y}from"./select-DhyoRdYW.js";import{g as ue,s as te}from"./app-settings.functions-CbWZNLzq.js";import{u as V}from"./use-current-role-DMhO4RNJ.js";import{S as ks}from"./star-DQnot0sh.js";import{S as Cs}from"./slider-Bb3nbZ28.js";import{T as Ue,a as Ke,b as Q,c as G}from"./tabs-pw5N1qnz.js";import{D as Ss,P as As,m as Ps}from"./order-invoice-xtOuGmit.js";import{E as xs}from"./eye-DVEKRmYm.js";import{P as Ts}from"./printer-C-lnHn_Q.js";import{O as De,s as fe}from"./orders-CrZOz2l8.js";import{P as Es,S as Fs}from"./steadfast-settings-Dug0V5Ay.js";import{R as Ds}from"./rotate-ccw-DJov7mhM.js";import{W as Ve}from"./wallet-BPFjTZVM.js";import{C as qe,a as qs,b as Ms,d as Ls,c as Me}from"./card-CKGYtlGw.js";import{P as Bs}from"./progress-D1IQu-Oq.js";import{b as Rs,f as Os}from"./courier-history.functions-DAsvJw-T.js";import{A as de,a as ce}from"./alert-C6r40Ny8.js";import{L as hs}from"./lock-nUgCQ_2j.js";import{E as Is}from"./eye-off-Bw3QVCeU.js";import{S as We}from"./sparkles-C26fop8P.js";import{D as be}from"./download-CXyrNcW9.js";import{R as Le}from"./refresh-cw-9OwAwMhX.js";import{I as $s}from"./info-mmY8q_3n.js";import{D as Xe}from"./database-CRDj3YHk.js";import{T as je}from"./triangle-alert-BXBiVDuy.js";import{E as ps}from"./external-link-DspSNfde.js";import{C as Ye}from"./checkbox-B1zH9sEA.js";import{l as zs,c as Us,u as Ks,d as Vs}from"./admin.functions-CpOT66FZ.js";import{G as Xs}from"./grip-vertical-Cdnu32HF.js";import{C as gs}from"./chart-column-BSk_nild.js";import{A as js}from"./activity-BnJFWnQQ.js";import{F as He}from"./facebook-CB8jsepv.js";import{F as Je}from"./flask-conical-BRI3kiPi.js";import{K as Hs}from"./key-round-DxEWGyEw.js";import{S as we}from"./send-BzSNGFOT.js";import{G as Qs}from"./globe-IlyhFCCI.js";import{S as Gs}from"./shield-check-D6GzMyjO.js";import{C as fs}from"./circle-check-BadlvWHx.js";import{C as bs}from"./circle-x-DV4ULbUq.js";import{g as Ws,c as Ys,s as Js,l as Zs}from"./sms.functions-BTE1rRNC.js";import{S as Ae,s as ea,a as Ze,b as sa,c as es}from"./templates-Cv4S6hC6.js";import{M as vs}from"./message-square-CMAa3Kz5.js";import{R as aa}from"./refresh-ccw-C5m6FBda.js";import{H as ta}from"./history-C5lMW8rV.js";import{B as _s}from"./building-2-Dts8MA6J.js";import{T as na}from"./truck-zATajgQD.js";import{P as ra}from"./plug-DNc-pciU.js";import"./use-my-access-profile-eX8ffDWv.js";import"./index-DPrYYZ34.js";import"./index-CJtd0Bml.js";import"./index-Dl9hlz3A.js";import"./index-BGNpujc9.js";import"./index-BdQq_4o_.js";import"./index-ix3cE_J2.js";import"./index--KVnfuxa.js";import"./index-BuMx1jGY.js";import"./chevron-down-BpeL8prt.js";import"./check-BfMNAkIe.js";import"./chevron-up-WDwjygZr.js";import"./index-B3GWG_Ui.js";import"./format-CdF6Rsce.js";import"./en-US-IVrGvTxk.js";import"./pathao.functions-Co1EwgyV.js";import"./plug-zap-DmmMKJ1M.js";import"./steadfast.functions-CawnXtU8.js";const ia=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],la=oe("bell",ia);const da=[["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M16 6h.01",key:"1x0f13"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M8 6h.01",key:"1dz90k"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3",key:"cabbwy"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2",key:"1uxh74"}]],ca=oe("building",da);const oa=[["path",{d:"M16 2v2",key:"scm5qe"}],["path",{d:"M17.915 22a6 6 0 0 0-12 0",key:"suqz9p"}
1],["path",{d:"M8 2v2",key:"pbkmx"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["rect",{x:"3",y:"4",width:"18",height:"18",rx:"2",key:"12vinp"}]],ma=oe("contact-round",oa);const ua=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}],["path",{d:"M3.22 13H9.5l.5-1 2 4.5 2-7 1.5 3.5h5.27",key:"auskq0"}]],xa=oe("heart-pulse",ua);const ha=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],pa=oe("link-2",ha);const ga=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],ja=oe("webhook",ga),fa={business_name:"",business_mobile:"",invoice_prefix:"",business_address:"",default_delivery_cost:"0",logo_url:"",hotline:"",whatsapp:"",email:"",website:"",facebook:"",instagram:"",bin:"",trade_license:"",footer_thank_you:"",order_sources:[]},ba=["Facebook","Instagram","WhatsApp","Messenger","TikTok","Phone Call","Website","Walk-in","Referral","Others"],va=/^[A-Za-z0-9_]+-?$/;function _a({brandIdOverride:a}={}){const{activeBrand:s}=me(),i=a??s?.id,d=K(),{data:m,isLoading:r}=L({queryKey:["brand-settings",i],enabled:!!i,queryFn:async()=>{const[o,N]=await Promise.all([q.from("brands").select("id,name,logo_url,settings").eq("id",i).single(),q.from("erp_settings").select("invoice_prefix,invoice_seq,invoice_pad").eq("brand_id",i).maybeSingle()]);if(o.error)throw o.error;const A=o.data?.settings??{};return{brand:o.data,bsettings:A,erp:N.data}}}),[c,p]=f.useState(fa),t=(o,N)=>p(A=>({...A,[o]:N}));f.useEffect(()=>{m&&p({business_name:m.brand?.name??"",business_mobile:m.bsettings.business_mobile??"",invoice_prefix:m.erp?.invoice_prefix??"INV-",business_address:m.bsettings.business_address??"",default_delivery_cost:String(m.bsettings.default_delivery_cost??0),logo_url:m.brand?.logo_url??"",hotline:m.bsettings.hotline??"",whatsapp:m.bsettings.whatsapp??"",email:m.bsettings.email??"",website:m.bsettings.website??"",facebook:m.bsettings.facebook??"",instagram:m.bsettings.instagram??"",bin:m.bsettings.bin??"",trade_license:m.bsettings.trade_license??"",footer_thank_you:m.bsettings.footer_thank_you??"",order_sources:Array.isArray(m.bsettings.order_sources)&&m.bsettings.order_sources.length>0?m.bsettings.order_sources:ba})},[m]);const x=!!c.invoice_prefix&&!va.test(c.invoice_prefix),j=c.invoice_prefix?c.invoice_prefix+String((m?.erp?.invoice_seq??0)+1).padStart(m?.erp?.invoice_pad??7,"0"):"—",u=M({mutationFn:async()=>{if(!i)throw new Error("No active brand");if(x)throw new Error("Invalid invoice slug");const o={...m?.bsettings??{},business_mobile:c.business_mobile||void 0,business_address:c.business_address||void 0,default_delivery_cost:Number(c.default_delivery_cost)||0,hotline:c.hotline||void 0,whatsapp:c.whatsapp||void 0,email:c.email||void 0,website:c.website||void 0,facebook:c.facebook||void 0,instagram:c.instagram||void 0,bin:c.bin||void 0,trade_license:c.trade_license||void 0,footer_thank_you:c.footer_thank_you||void 0,order_sources:c.order_sources.filter(h=>h.trim().length>0)},{error:N}=await q.from("brands").update({name:c.business_name,logo_url:c.logo_url||null,settings:o}).eq("id",i);if(N)throw N;const A=m?.erp?.invoice_prefix??"INV-",R=c.invoice_prefix||"INV-",{error:X}=await q.from("erp_settings").upsert({brand_id:i,invoice_prefix:R},{onConflict:"brand_id"});if(X)throw X;let H=0;if(R!==A){const{data:h,error:O}=await q.rpc("reapply_invoice_prefix",{_brand_id:i});if(O)throw O;H=Number(h??0)}return{updated:H,changed:R!==A}},onSuccess:o=>{o?.changed?_.success(`Settings saved. ${o.updated} invoice${o.updated===1?"":"s"} re-prefixed.`):_.success("Business settings updated"),d.invalidateQueries({queryKey:["brand-settings",i]}),d.invalidateQueries({queryKey:["brands"]}),d.invalidateQueries({queryKey:["orders"]}),d.invalidateQueries({queryKey:["orders-status-counts"]})},onError:o=>_.error(o.message)}),l=f.useRef(null),[g,n]=f.useState(!1);async function v(o){if(i){if(!o.type.startsWith("image/")){_.error("Please select an image file");return}if(o.size>4*1024*1024){_.error("Logo must be under 4 MB");return}n(!0);try{const N=o.name.split(".").pop()?.toLowerCase()||"png",A=`brands/${i}/logo-${Date.now()}.${N}`,{error:R}=await q.storage.from("product-images").upload(A,o,{cacheControl:"3600",upsert:!0,contentType:o.type});if(R)throw R;const{data:X}=q.storage.from("product-images").getPublicUrl(A);t("logo_url",X.publicUrl),_.success("Logo uploaded — click Update to save")}catch(N){_.error(N.message)}finally{n(!1)}}}return i?r?e.jsx("div",{className:"rounded-xl border bg-card p-6 space-y-4 max-w-3xl",children:Array.from({length:5}).map((o,N)=>e.jsx(J,{className:"h-16 w-full"},N))}):e.jsxs("form",{onSubmit:o=>{o.preventDefault(),u.mutate()},className:"rounded-xl border bg-card shadow-sm max-w-4xl overflow-hidden",children:[e.jsxs("header",{className:"px-5 py-3 border-b bg-muted/30",children:[e.jsxs("h2",{className:"font-bold text-base",children:["Business Setting — ",m?.brand?.name]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"These values auto-fill invoices, stickers and order documents."})]}),e.jsxs("div",{className:"p-5 space-y-6",children:[e.jsx(ne,{title:"Brand Logo",desc:"Used on invoices, stickers and the storefront header.",children:e.jsxs("div",{className:"flex gap-4 items-start",children:[e.jsx("div",{className:"h-24 w-24 rounded-md border bg-muted/30 flex items-center justify-center overflow-hidden shrink-0",children:c.logo_url?e.jsx("img",{src:c.logo_url,alt:"Logo",className:"max-h-full max-w-full object-contain"}
1):e.jsx(Ns,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("input",{ref:l,type:"file",accept:"image/png,image/jpeg,image/webp,image/svg+xml",className:"hidden",onChange:o=>{const N=o.target.files?.[0];N&&v(N),o.currentTarget.value=""}}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(w,{type:"button",variant:"outline",size:"sm",onClick:()=>l.current?.click(),disabled:g,children:[g?e.jsx(I,{className:"h-4 w-4 animate-spin"}):e.jsx(ws,{className:"h-4 w-4"}),g?"Uploading…":"Upload Logo"]}),c.logo_url&&e.jsxs(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>t("logo_url",""),children:[e.jsx(ge,{className:"h-4 w-4"})," Remove"]})]}),e.jsx(b,{value:c.logo_url,onChange:o=>t("logo_url",o.target.value),placeholder:"…or paste a URL",className:"text-xs"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"PNG, JPG, WebP or SVG. Max 4 MB. Transparent PNG recommended."})]})]})}),e.jsxs(ne,{title:"Identity",children:[e.jsx(z,{label:"Business Name",hint:"Shown as the brand name on every printed document.",children:e.jsx(b,{value:c.business_name,onChange:o=>t("business_name",o.target.value),required:!0})}),e.jsxs(z,{label:"Invoice Slug",hint:"This slug is added before the invoice number. Use English letters, digits or underscores, with an optional trailing hyphen.",error:x?"Only A–Z, a–z, 0–9, _ allowed, optional trailing -":null,children:[e.jsx(b,{value:c.invoice_prefix,onChange:o=>t("invoice_prefix",o.target.value),placeholder:"HBS-",className:x?"border-destructive focus-visible:ring-destructive":""}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(os,{className:"h-3.5 w-3.5"}),"Next invoice will be"," ",e.jsx("span",{className:"font-mono font-semibold text-foreground",children:j})]})]})]}),e.jsx(ne,{title:"Contact",desc:"Customer-facing contact channels.",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(z,{label:"Business Mobile",hint:"Primary phone — appears as the default sender on invoices.",children:e.jsx(b,{value:c.business_mobile,onChange:o=>t("business_mobile",o.target.value),inputMode:"tel",placeholder:"01711-223344"})}),e.jsx(z,{label:"Hotline",hint:"Customer support number.",children:e.jsx(b,{value:c.hotline,onChange:o=>t("hotline",o.target.value),inputMode:"tel",placeholder:"16263"})}),e.jsx(z,{label:"WhatsApp",children:e.jsx(b,{value:c.whatsapp,onChange:o=>t("whatsapp",o.target.value),inputMode:"tel",placeholder:"+8801XXXXXXXXX"})}),e.jsx(z,{label:"Email",children:e.jsx(b,{type:"email",value:c.email,onChange:o=>t("email",o.target.value),placeholder:"[email protected]"})}),e.jsx(z,{label:"Website",children:e.jsx(b,{value:c.website,onChange:o=>t("website",o.target.value),placeholder:"https://brand.com"})}),e.jsx(z,{label:"Address",className:"md:col-span-2",children:e.jsx(Y,{value:c.business_address,onChange:o=>t("business_address",o.target.value),rows:2,placeholder:"Shop 12, Road 5, Block C, Bashundhara R/A, Dhaka"})})]})}),e.jsx(ne,{title:"Social",desc:"Shown in the invoice footer & order notifications.",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(z,{label:"Facebook",children:e.jsx(b,{value:c.facebook,onChange:o=>t("facebook",o.target.value),placeholder:"fb.com/brand"})}),e.jsx(z,{label:"Instagram",children:e.jsx(b,{value:c.instagram,onChange:o=>t("instagram",o.target.value),placeholder:"@brand"})})]})}),e.jsx(ne,{title:"Legal & Tax",desc:"Government-issued numbers for compliance.",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(z,{label:"BIN / VAT Registration",children:e.jsx(b,{value:c.bin,onChange:o=>t("bin",o.target.value),placeholder:"0001234-5678"})}),e.jsx(z,{label:"Trade License",children:e.jsx(b,{value:c.trade_license,onChange:o=>t("trade_license",o.target.value),placeholder:"TL-2024-12345"})})]})}),e.jsx(ne,{title:"Defaults & Footer",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(z,{label:"Default Delivery Cost",hint:"Pre-filled in the new-order form.",children:e.jsx(b,{type:"number",min:"0",step:"1",value:c.default_delivery_cost,onChange:o=>t("default_delivery_cost",o.target.value)})}),e.jsx(z,{label:"Footer / Thank-you Message",hint:"Shown at the bottom of invoices.",className:"md:col-span-2",children:e.jsx(Y,{value:c.footer_thank_you,onCh
1ange:o=>t("footer_thank_you",o.target.value),rows:2,placeholder:"Thank you for shopping with us!"})})]})}),e.jsx(ne,{title:"Order Sources",desc:"Manage where orders come from — shown as dropdown in New Order form.",children:e.jsx(ya,{sources:c.order_sources,onChange:o=>t("order_sources",o)})})]}),e.jsx("footer",{className:"px-5 py-3 border-t bg-muted/20 flex justify-end",children:e.jsxs(w,{type:"submit",disabled:u.isPending||x,children:[u.isPending?e.jsx(I,{className:"h-4 w-4 animate-spin"}):e.jsx($,{className:"h-4 w-4"}),"Update Business"]})})]}):e.jsx("div",{className:"rounded-xl border bg-card p-6 text-sm text-muted-foreground",children:"Select a brand to edit its settings."})}function ne({title:a,desc:s,children:i}){return e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"border-b pb-1.5",children:[e.jsx("h3",{className:"text-sm font-bold",children:a}),s&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:s})]}),e.jsx("div",{className:"space-y-4",children:i})]})}function z({label:a,hint:s,error:i,children:d,className:m}){return e.jsxs("div",{className:"space-y-1.5 "+(m??""),children:[e.jsx(k,{className:"text-sm font-bold",children:a}),d,i?e.jsx("p",{className:"text-xs text-destructive font-medium",children:i}):s?e.jsx("p",{className:"text-xs text-muted-foreground",children:s}):null]})}function ya({sources:a,onChange:s}){const[i,d]=f.useState(""),m=()=>{const c=i.trim();if(c){if(a.some(p=>p.toLowerCase()===c.toLowerCase())){_.error("Already added");return}s([...a,c]),d("")}},r=c=>s(a.filter((p,t)=>t!==c));return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No sources yet — add one below."}),a.map((c,p)=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border bg-muted/40 pl-3 pr-1 py-1 text-xs font-medium",children:[e.jsx(ms,{className:"h-3 w-3 text-muted-foreground"}),c,e.jsx("button",{type:"button",onClick:()=>r(p),className:"rounded-full p-0.5 text-muted-foreground hover:bg-rose-100 hover:text-rose-600","aria-label":`Remove ${c}`,children:e.jsx(Ge,{className:"h-3 w-3"})})]},`${c}-${p}`))]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{value:i,onChange:c=>d(c.target.value),onKeyDown:c=>{c.key==="Enter"&&(c.preventDefault(),m())},placeholder:"e.g. Telegram, Live Chat, YouTube…",className:"max-w-xs",maxLength:40}),e.jsxs(w,{type:"button",variant:"outline",size:"sm",onClick:m,disabled:!i.trim(),children:[e.jsx(Se,{className:"h-4 w-4"})," Add Source"]})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Click ",e.jsx(Ge,{className:"inline h-3 w-3 -mt-0.5"})," to remove. Don't forget to press ",e.jsx("b",{children:"Update Business"})," below to save."]})]})}const Na=ee({method:"POST"}).middleware([se]).handler(Z("75abf12fc797263b5fb8841968c27cb8c5e58b55ec48b783fc7442bc29429057")),wa=ee({method:"POST"}).middleware([se]).handler(Z("15090e8e947c43dfc90f02ddf476c349ad47b621a789c6aa2407ad977d55c384")),ka=["Asia/Dhaka","Asia/Kolkata","Asia/Dubai","UTC","America/New_York"],Ca=["BDT","USD","EUR","INR","AED"],Sa=["en","bn"],Pe={name:"",slug:"",logo_url:"",primary_color:"#3B82F6",timezone:"Asia/Dhaka",currency:"BDT",language:"en",is_active:!0};function Aa(){const{brands:a}=me(),{isAdmin:s}=V(),i=K(),[d,m]=f.useState(!1),[r,c]=f.useState(Pe),p=C(ue),t=C(te),x=C(Na),j=C(wa),l=L({queryKey:["app-setting","default_brand_id"],queryFn:()=>p({data:{key:"default_brand_id"}})}).data?.value??null,g=M({mutationFn:o=>t({data:{key:"default_brand_id",value:o}}),onSuccess:()=>{_.success("Default brand updated"),i.invalidateQueries({queryKey:["app-setting","default_brand_id"]})},onError:o=>_.error(o.message)}),n=M({mutationFn:async()=>{r.id?await j({data:{id:r.id,name:r.name,slug:r.slug,logo_url:r.logo_url||null,primary_color:r.primary_color,timezone:r.timezone,currency:r.currency,language:r.language,is_active:r.is_active}}):await x({data:{name:r.name,slug:r.slug,logo_url:r.logo_url||null,primary_color:r.primary_color,timezone:r.timezone,currency:r.currency,language:r.language,is_active:r.is_active}})},onSuccess:()=>{_.success(r.id?"Brand updated":"Brand created"),i.invalidateQueries({queryKey:["brands"]}),m(!1),c(Pe)},onError:o=>_.error(o.message)});function v(o){const N=o.settings??{};c({id:o.id,name:o.name,slug:o.slug,logo_url:o.logo_url??"",primary_color:N.primary_color??"#3B82F6",timezone:N.timezone??"Asia/Dhaka",currency:N.currency??"BDT",language:N.language??"en",is_active:o.is_active}),m(!0)}return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Brands"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add, edit, set defaults. Per-brand timezone & currency."})]}),s&&e.jsxs(Re,{open:d,onOpenChange:m,children:[e.jsx(us,{asChild:!0,children:e.jsxs(w,{size:"sm",onClick:()=>c(Pe),children:[e.jsx(Se,{className:"h-4 w-4"})," Add brand"]})}),e.jsx(Pa,{form:r,setForm:c,onSave:()=>n.mutate(),saving:n.isPending})]})]}),e.jsxs("div",{className:"rounded-xl border bg-card divide-y",children:[a.length===0&&e.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"No brands yet."}),a.map(o=>{const N=o.settings??{},A=o.id===l;return e.jsxs("div",{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-lg border bg-muted/30 overflow-hidden flex items-center justify-center shrink-0",children:o.logo_url?e.jsx("img",{src:o.logo_url,alt:o.name,className:"max-h-full max-w-full object-contain"}):e.jsx("span",{className:"text-xs font-bold text-muted-foreground",children:o.name.slice(0,2).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold",children:o.name}),A&&e.jsxs(W,{variant:"secondary",className:"text-[10px]",children:[e.jsx(ks,{className:"h-3 w-3 mr-1"}),"Default"]}),!o.is_active&&e.jsx(W,{variant:"outline",className:"text-[10px]",children:"Inactive"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-0.5",children:["/",o.slug," • ",N.currency??"BDT"," • ",N.timezone??"Asia/Dhaka"," • ",N.language??"en"]})]}),N.primary_color&&e.jsx("div",{className:"h-5 w-5 rounded-full border",style:{backgroundColor:N.primary_color},title:N.primary_color}),s&&e.jsxs(e.Fragment,{children:[!A&&e.jsx(w,{size:"sm",variant:"ghost",onClick:()=>g.mutate(o.id),disabled:g.isPending,children:"Set default"}),e.jsx(w,{size:"sm",variant:"outline",onClick:()=>v(o),children:"Edit"})]})]},o.id)})]}),!s&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"View-only. Admin role required to create or edit brands."})]})}function Pa({form:a,setForm:s,onSave:i,saving:d}){const m=(r,c)=>s({...a,[r]:c});return e.jsxs(Oe,{className:"max-w-lg",children:[e.jsx(Ie,{children:e.jsx($e,{children:a.id?"Edit brand":"New brand"})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(k,{children:"Name"}),e.jsx(b,{value:a.name,onChange:r=>m("name",r.target.value)})]}),e.jsxs("div",{children:[e.jsx(k,{children:"Slug"}),e.jsx(b,{value:a.slug,onChange:r=>m("slug",r.target.value.toLowerCase()),placeholder:"hobbyshop"})]}),e.jsxs("div",{children:[e.jsx(k,{children:"Primary color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{type:"color",value:a.primary_color,onChange:r=>m("primary_color",r.target.value),className:"w-12 p-1 h-10"}),e.jsx(b,{value:a.primary_color,onChange:r=>m("primary_color",r.target.value),className:"flex-1 font-mono text-xs"})]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(k,{children:"Logo URL"}),e.jsx(b,{value:a.logo_url,onChange:r=>m("logo_url",r.target.value),placeholder:"https://…"})]}),e.jsxs("div",{children:[e.jsx(k,{children:"Timezone"}),e.jsxs(T,{value:a.timezone,onValueChange:r=>m("timezone",r),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsx(D,{children:ka.map(r=>e.jsx(y,{value:r,children:r},r))})]})]}),e.jsxs("div",{children:[e.jsx(k,{children:"Currency"}),e.jsxs(T,{value:a.currency,onValueChange:r=>m("currency",r),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsx(D,{children:Ca.map(r=>e.jsx(y,{value:r,children:r},r))})]})]}),e.jsxs("div",{children:[e.jsx(k,{children:"Language"}),e.jsxs(T,{value:a.language,onValueChange:r=>m("language",r),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsx(D,{children:Sa.map(r=>e.jsx(y,{value:r,children:r},r))})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(U,{checked:a.is_active,onCheckedChange:r=>m("is_active",r),id:"brand-active"}),e.jsx(k,{htmlFor:"brand-active",children:"Active"})]})]}),e.jsx(ze,{children:e.jsxs(w,{onClick:i,disabled:d||!a.name||!a.slug,children:[d?e.jsx(I,{className:"h-4 w-4 animate-spin"}):e.jsx($,{className:"h-4 w-4"}),a.id?"Save changes":"Create brand"]})})]})}const Ta={id:"00000000-0000-0000-0000-000000000000",invoice_no:"INV-0000123",created_at:new Date().toISOString(),status:"confirmed",total:2450,subtotal:2200,shipping_fee:120,discount_amount:0,advance_amount:500,payment_method:"Cash on Delivery",courier_name:"Pathao",tracking_number:"PT123456789",shipping_name:"Rakib Hasan",shipping_phone:"01711-223344",shipping_address:"House 12, Road 5, Block C, Bashundhara R/A",shipping_city:"Dhaka",shipping_district:"Dhaka",shipping_thana:"Vatara",
1shipping_note:"Please call before delivery.",customer_note:"Gift wrap please.",guest_name:null,guest_phone:null},Ea=[{name:"Premium Cotton T-Shirt",quantity:2,unit_price:750,price:750,variant_label:"Size: L, Color: Black",line_total:1500,sku:"TS-PRM-001",image:null},{name:"Sports Cap",quantity:1,unit_price:700,price:700,variant_label:null,line_total:700,sku:"CAP-001",image:null}];function Fa({brandIdOverride:a}={}){const{activeBrand:s,brands:i}=me(),d=a??s?.id,m=i.find(n=>n.id===d)?.name??s?.name??"",r=K(),{data:c,isLoading:p}=L({queryKey:["invoice-config-edit",d],enabled:!!d,queryFn:async()=>{const{data:n,error:v}=await q.from("erp_settings").select("config").eq("brand_id",d).maybeSingle();if(v)throw v;return Ps(n?.config?.invoice)}}),[t,x]=f.useState(Ss);f.useEffect(()=>{c&&x(c)},[c]);const j=(n,v)=>x(o=>({...o,[n]:v})),u=(n,v)=>x(o=>{const N=structuredClone(o);let A=N;for(let R=0;R<n.length-1;R++)A=A[n[R]];return A[n[n.length-1]]=v,N}),l=M({mutationFn:async()=>{if(!d)throw new Error("No brand");const{data:n}=await q.from("erp_settings").select("config").eq("brand_id",d).maybeSingle(),v={...n?.config??{},invoice:t},{error:o}=await q.from("erp_settings").upsert({brand_id:d,config:v},{onConflict:"brand_id"});if(o)throw o},onSuccess:()=>{_.success("Invoice settings saved"),r.invalidateQueries({queryKey:["invoice-config",d]}),r.invalidateQueries({queryKey:["invoice-config-edit",d]})},onError:n=>_.error(n.message)}),g=f.useMemo(()=>JSON.stringify(t),[t]);return d?p?e.jsxs("div",{className:"rounded-xl border bg-card p-6 space-y-3",children:[e.jsx(J,{className:"h-8 w-full"}),e.jsx(J,{className:"h-64 w-full"})]}):e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)] gap-5",children:[e.jsxs("div",{className:"rounded-xl border bg-card shadow-sm overflow-hidden",children:[e.jsxs("header",{className:"px-5 py-3 border-b bg-muted/30 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"font-bold text-base",children:["Invoice — ",m]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Per-brand invoice design & content"})]}),e.jsxs(w,{onClick:()=>l.mutate(),disabled:l.isPending,children:[l.isPending?e.jsx(I,{className:"h-4 w-4 animate-spin"}):e.jsx($,{className:"h-4 w-4"})," Save"]})]}),e.jsxs(Ue,{defaultValue:"design",className:"p-4",children:[e.jsxs(Ke,{className:"grid grid-cols-6 w-full",children:[e.jsx(Q,{value:"design",children:"Design"}),e.jsx(Q,{value:"business",children:"Business"}),e.jsx(Q,{value:"meta",children:"Meta"}),e.jsx(Q,{value:"items",children:"Items"}),e.jsx(Q,{value:"totals",children:"Totals"}),e.jsx(Q,{value:"footer",children:"Footer"})]}),e.jsxs(G,{value:"design",className:"space-y-4 mt-4",children:[e.jsx(S,{label:"Theme",children:e.jsxs(T,{value:t.theme,onValueChange:n=>j("theme",n),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"template",children:"HobbyShop Template (recommended)"}),e.jsx(y,{value:"modern",children:"Modern (colored band)"}),e.jsx(y,{value:"classic",children:"Classic (B&W)"}),e.jsx(y,{value:"minimal",children:"Minimal"}),e.jsx(y,{value:"pos",children:"POS / Thermal"})]})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(S,{label:"Paper",children:e.jsxs(T,{value:t.paper,onValueChange:n=>j("paper",n),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"A4",children:"A4"}),e.jsx(y,{value:"A5",children:"A5"}),e.jsx(y,{value:"80mm",children:"80mm POS"}),e.jsx(y,{value:"58mm",children:"58mm POS"})]})]})}),e.jsx(S,{label:"Orientation",children:e.jsxs(T,{value:t.orientation,onValueChange:n=>j("orientation",n),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"portrait",children:"Portrait"}),e.jsx(y,{value:"landscape",children:"Landscape"})]})]})}),e.jsx(S,{label:"Margin",children:e.jsxs(T,{value:t.margin,onValueChange:n=>j("margin",n),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"compact",children:"Compact"}),e.jsx(y,{value:"normal",children:"Normal"}),e.jsx(y,{value:"wide",children:"Wide"})]})]})}),e.jsx(S,{label:"Font size",children:e.jsxs(T,{value:t.font.size,onValueChange:n=>u(["font","size"],n),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"sm",children:"Small"}),e.jsx(y,{value:"md",children:"Medium"}),e.jsx(y,{value:"lg",children:"Large"})]})]})}),e.jsx(S,{label:"Font family",children:e.jsxs(T,{value:t.font.family,onValueChange:n=>u(["font","family"],n),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"inter",children:"Inter (Latin)"}
1),e.jsx(y,{value:"hind-siliguri",children:"Hind Siliguri (বাংলা)"}),e.jsx(y,{value:"roboto",children:"Roboto"})]})]})}),e.jsx(S,{label:"Header layout",children:e.jsxs(T,{value:t.header.layout,onValueChange:n=>u(["header","layout"],n),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"logo-left",children:"Logo left"}),e.jsx(y,{value:"logo-center",children:"Logo center"}),e.jsx(y,{value:"logo-right",children:"Logo right"})]})]})})]}),e.jsx(S,{label:`Logo height (${t.header.logoHeight}px)`,children:e.jsx(Cs,{min:32,max:120,step:4,value:[t.header.logoHeight],onValueChange:n=>u(["header","logoHeight"],n[0])})}),e.jsx(S,{label:"Accent color",children:e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"color",value:t.accentColor,onChange:n=>j("accentColor",n.target.value),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(b,{value:t.accentColor,onChange:n=>j("accentColor",n.target.value),className:"font-mono"})]})}),e.jsx(S,{label:"Header tagline",children:e.jsx(b,{value:t.header.tagline,onChange:n=>u(["header","tagline"],n.target.value),placeholder:"Your trusted shop since 2020"})}),e.jsx(B,{label:"Show watermark (PAID / DUE / CANCELLED)",v:t.header.showWatermark,on:n=>u(["header","showWatermark"],n)})]}),e.jsxs(G,{value:"business",className:"space-y-3 mt-4",children:[e.jsx(S,{label:"Address",children:e.jsx(Y,{rows:2,value:t.business.address,onChange:n=>u(["business","address"],n.target.value)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(S,{label:"Hotline",children:e.jsx(b,{value:t.business.hotline,onChange:n=>u(["business","hotline"],n.target.value)})}),e.jsx(S,{label:"WhatsApp",children:e.jsx(b,{value:t.business.whatsapp,onChange:n=>u(["business","whatsapp"],n.target.value)})}),e.jsx(S,{label:"Email",children:e.jsx(b,{value:t.business.email,onChange:n=>u(["business","email"],n.target.value)})}),e.jsx(S,{label:"Website",children:e.jsx(b,{value:t.business.website,onChange:n=>u(["business","website"],n.target.value)})}),e.jsx(S,{label:"Facebook",children:e.jsx(b,{value:t.business.facebook,onChange:n=>u(["business","facebook"],n.target.value)})}),e.jsx(S,{label:"Instagram",children:e.jsx(b,{value:t.business.instagram,onChange:n=>u(["business","instagram"],n.target.value)})}),e.jsx(S,{label:"BIN / VAT reg",children:e.jsx(b,{value:t.business.bin,onChange:n=>u(["business","bin"],n.target.value)})}),e.jsx(S,{label:"Trade license",children:e.jsx(b,{value:t.business.trade_license,onChange:n=>u(["business","trade_license"],n.target.value)})})]})]}),e.jsxs(G,{value:"meta",className:"space-y-3 mt-4",children:[e.jsx(B,{label:"Show order date",v:t.meta.showDate,on:n=>u(["meta","showDate"],n)}),e.jsx(B,{label:"Show courier",v:t.meta.showCourier,on:n=>u(["meta","showCourier"],n)}),e.jsx(B,{label:"Show tracking #",v:t.meta.showTracking,on:n=>u(["meta","showTracking"],n)}),e.jsx(B,{label:"Show payment method",v:t.meta.showPayment,on:n=>u(["meta","showPayment"],n)}),e.jsxs("div",{className:"rounded-md border p-3 space-y-2 bg-muted/20",children:[e.jsx(B,{label:"QR code",v:t.meta.qr.enabled,on:n=>u(["meta","qr","enabled"],n)}),t.meta.qr.enabled&&e.jsxs(e.Fragment,{children:[e.jsx(S,{label:"QR target",children:e.jsxs(T,{value:t.meta.qr.target,onValueChange:n=>u(["meta","qr","target"],n),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"tracking",children:"Tracking link"}),e.jsx(y,{value:"phone",children:"Customer phone"}),e.jsx(y,{value:"website",children:"Business website"}),e.jsx(y,{value:"custom",children:"Custom URL"})]})]})}),t.meta.qr.target==="custom"&&e.jsx(S,{label:"Custom URL",children:e.jsx(b,{value:t.meta.qr.customUrl,onChange:n=>u(["meta","qr","customUrl"],n.target.value)})})]})]})]}),e.jsxs(G,{value:"items",className:"space-y-3 mt-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(S,{label:"Currency",children:e.jsx(b,{value:t.items.currency,onChange:n=>u(["items","currency"],n.target.value)})}),e.jsx(S,{label:"Currency position",children:e.jsxs(T,{value:t.items.currencyPosition,onValueChange:n=>u(["items","currencyPosition"],n),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"before",children:"Before (৳ 100)"}),e.jsx(y,{value:"after",children:"After (100 ৳)"})]})]})}),e.jsx(S,{label:"Number format",children:e.jsxs(T,{value:t.items.numberFormat,onValueChange:n=>u(["items","numberFormat"],n),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"bd",children:"BD (1,23,456)"}),e.jsx(y,{value:"intl",children:"Intl (123,456)"})]})]})})]}),e.jsx(B,{label:"Show SKU column",v:t.items.showSku,on:n=>u(["items","showSku"],n)}),e.jsx(B,{label:"Show variant",v:t.items.showVariant,on:n=>u(["items","showVariant"],n)}),e.jsx(B,{label:"Show product image",v:t.items.showImage,on:n=>u(["items","showImage"],n)}),e.jsx(B,{label:"Show per-item discount column",v:t.items.showDiscount,on:n=>u(["items","showDiscount"],n)}),e.jsx(B,{label:"Zebra row striping",v:t.items.zebra,on:n=>u(["items","zebra"],n)})]}),e.jsxs(G,{value:"totals",className:"space-y-3 mt-4",children:[e.jsx(B,{label:"Show subtotal",v:t.totals.showSubtotal,on:n=>u(["totals","showSubtotal"],n)}),e.jsx(B,{label:"Show discount",v:t.totals.showDiscount,on:n=>u(["totals","showDiscount"],n)}),e.jsx(B,{label:"Show shipping",v:t.totals.showShipping,on:n=>u(["totals","showShipping"],n)}),e.jsx(B,{label:"Show advance paid",v:t.totals.showAdvance,on:n=>u(["totals","showAdvance"],n)}),e.jsx(B,{label:"Show amount due",v:t.totals.showDue,on:n=>u(["totals","showDue"],n)}),e.jsx(B,{label:"Round-off total",v:t.totals.roundOff,on:n=>u(["totals","roundOff"],n)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 pt-2",children:[e.jsx(S,{label:"VAT / Tax %",children:e.jsx(b,{type:"number",min:0,max:100,value:t.totals.tax.rate,onChange:n=>u(["totals","tax","rate"],Number(n.target.value)||0)})}),e.jsx(S,{label:"Tax mode",children:e.jsxs(T,{value:t.totals.tax.inclusive?"inclusive":"exclusive",onValueChange:n=>u(["totals","tax","inclusive"],n==="inclusive"),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"exclusive",children:"Exclusive (add to total)"}),e.jsx(y,{value:"inclusive",children:"Inclusive (already in price)"})]})]})})]}),e.jsx(S,{label:"Amount in words",children:e.jsxs(T,{value:t.totals.amountInWords,onValueChange:n=>u(["totals","amountInWords"],n),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"off",children:"Off"}),e.jsx(y,{value:"en",children:"English"}),e.jsx(y,{value:"bn",children:"বাংলা"})]})]})})]}),e.jsxs(G,{value:"footer",className:"space-y-3 mt-4",children:[e.jsx(S,{label:"Terms & conditions",children:e.jsx(Y,{rows:2,value:t.footer.terms,onChange:n=>u(["footer","terms"],n.target.value)})}),e.jsx(S,{label:"Return / exchange policy",children:e.jsx(Y,{rows:2,value:t.footer.returnPolicy,onChange:n=>u(["footer","returnPolicy"],n.target.value)})}),e.jsx(S,{label:"Thank-you message",children:e.jsx(b,{value:t.footer.thankYou,onChange:n=>u(["footer","thankYou"],n.target.value)})}),e.jsx(S,{label:"Signature label",children:e.jsx(b,{value:t.footer.signatureLabel,onChange:n=>u(["footer","signatureLabel"],n.target.value)})}),e.jsx(S,{label:"Signature image URL",children:e.jsx(b,{value:t.footer.signatureUrl,onChange:n=>u(["footer","signatureUrl"],n.target.value),placeholder:"https://..."})})]})]})]}),e.jsxs("div",{className:"rounded-xl border bg-card shadow-sm overflow-hidden flex flex-col",children:[e.jsxs("header",{className:"px-5 py-3 border-b bg-muted/30 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"h-4 w-4"}),e.jsx("h2",{className:"font-bold text-base",children:"Live preview"})]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>window.print(),children:[e.jsx(Ts,{className:"h-4 w-4"})," Print test"]})]}),e.jsx("div",{className:"bg-zinc-200 dark:bg-zinc-900 p-4 overflow-auto flex-1 min-h-[600px]",children:e.jsx("div",{className:"mx-auto bg-white shadow-2xl rounded",style:{maxWidth:t.paper==="80mm"?320:t.paper==="58mm"?240:720},children:e.jsx(As,{order:Ta,items:Ea,configOverride:t,visible:!0},g)})})]})]}):e.jsx("div",{className:"rounded-xl border bg-card p-6 text-sm text-muted-foreground",children:"Select a brand to configure its invoice."})}function S({label:a,children:s}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(k,{className:"text-xs font-semibold",children:a}),s]})}function B({label:a,v:s,on:i}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md border px-3 py-2 bg-background",children:[e.jsx("span",{className:"text-sm",children:a}),e.jsx(U,{checked:s,onCheckedChange:i})]})}const ss={default_status:"pending",auto_confirm:!1,cod_fee_type:"flat",cod_fee_value:0,return_window_days:7,order_id_format:"{prefix}{seq}",allow_website_oversell:!0};function Da({brandId:a}){const{isAdmin:s}=V(),i=K(),d=`orders:${a}`,m=C(ue),r=C(te),{data:c,isLoading:p}=L({queryKey:["app-setting",d],queryFn:()=>m({data:{key:d}})}),[t,x]=f.useState(ss);f.useEffect(()=>{c?.value&&x({...ss,...c.value})},[c]);const j=M({mutationFn:()=>r({data:{key:d,value:t}}),onSuccess:()=>{_.success("Order settings saved"),i.invalidateQueries({queryKey:["app-setting",d]})},onError:l=>_.error(l.message)}),u=(l,g)=>x({...t,[l]:g});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Invoice & Orders"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Invoice template, numbering, order defaults and COD fees."})]}),e.jsx(Fa,{brandIdOverride:a},a),e.jsxs("section",{className:"rounded-xl border bg-card p-5 space-y-4 max-w-4xl",children:[e.jsx("h3",{className:"font-semibold",children:"Order workflow"}),p?e.jsx("div",{className:"space-y-3",children:Array.from({length:4}).map((l,g)=>e.jsx(J,{className:"h-12 w-full"},g))}):e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(k,{children:"Default status on creation"}),e.jsxs(T,{value:t.default_status,onValueChange:l=>u("default_status",l),disabled:!s,children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsx(D,{children:De.map(l=>e.jsx(y,{value:l,children:l},l))})]})]}),e.jsxs("div",{children:[e.jsx(k,{children:"Return window (days)"}),e.jsx(b,{type:"number",min:0,value:t.return_window_days,onChange:l=>u("return_window_days",Number(l.target.value)),disabled:!s}
1)]}),e.jsxs("div",{children:[e.jsx(k,{children:"COD fee"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(T,{value:t.cod_fee_type,onValueChange:l=>u("cod_fee_type",l),disabled:!s,children:[e.jsx(E,{className:"w-28",children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"flat",children:"Flat (à§³)"}),e.jsx(y,{value:"percent",children:"Percent (%)"})]})]}),e.jsx(b,{type:"number",min:0,value:t.cod_fee_value,onChange:l=>u("cod_fee_value",Number(l.target.value)),disabled:!s})]})]}),e.jsxs("div",{children:[e.jsx(k,{children:"Order ID format"}),e.jsx(b,{value:t.order_id_format,onChange:l=>u("order_id_format",l.target.value),placeholder:"{prefix}{seq}",disabled:!s}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:["Tokens: ","{prefix}"," ","{seq}"," ","{yyyy}"," ","{mm}"]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3 md:col-span-2",children:[e.jsx(k,{children:"Auto-confirm orders on creation"}),e.jsx(U,{checked:t.auto_confirm,onCheckedChange:l=>u("auto_confirm",l),disabled:!s})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3 md:col-span-2",children:[e.jsxs("div",{children:[e.jsx(k,{children:"Allow website orders when out of stock"}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:"Enable to let customers order from the storefront even if ERP stock is 0 (backorder)."})]}),e.jsx(U,{checked:t.allow_website_oversell,onCheckedChange:l=>u("allow_website_oversell",l),disabled:!s})]})]}),s&&e.jsx("div",{className:"flex justify-end",children:e.jsxs(w,{onClick:()=>j.mutate(),disabled:j.isPending,children:[j.isPending?e.jsx(I,{className:"h-4 w-4 animate-spin"}):e.jsx($,{className:"h-4 w-4"}),"Save order settings"]})})]})]})}function qa(a){return(a??"").toString().trim().toLowerCase().replace(/[\s-]+/g,"_")}const ke={pending:"ready_to_ship",pickup_requested:"ready_to_ship",waiting_for_pickup:"ready_to_ship",waiting_for_pick_up:"ready_to_ship",assigned_for_pickup:"ready_to_ship",pickup_rescheduled:"ready_to_ship",pickup_failed:"on_hold",pickup_cancelled:"cancelled",picked:"shipped",pickup:"shipped",picked_up:"shipped",collected:"shipped",at_the_sorting_hub:"in_transit",at_sorting_hub:"in_transit",sorting_hub:"in_transit",in_transit:"in_transit",received_at_last_mile_hub:"in_transit",last_mile_hub:"in_transit",hub_received:"in_transit",at_delivery_hub:"in_transit",on_the_way_to_delivery_hub:"in_transit",forwarded:"in_transit",reached:"in_transit",rider_assigned:"in_transit",assigned_for_delivery:"in_transit",on_delivery:"in_transit",out_for_delivery:"in_transit",delivered:"delivered",delivery_success:"delivered",partial_delivery:"partial_delivered",partial_delivered:"partial_delivered",delivery_failed:"on_hold",delivery_hold:"on_hold",delivery_rescheduled:"on_hold",hold:"on_hold",on_hold:"on_hold",merchant_confirmed:"on_hold",customer_unreachable:"on_hold",lost:"on_hold",damaged:"on_hold",return:"return_in_transit",returning:"return_in_transit",return_processing:"return_in_transit",pending_return:"return_in_transit",return_in_transit:"return_in_transit",return_to_pickup:"return_in_transit",return_to_merchant:"return_in_transit",on_the_way_to_return:"return_in_transit",return_rescheduled:"return_in_transit",returned:"pending_return",return_completed:"pending_return",paid_return:"paid_return",unpaid_return:"unpaid_return",partial_delivered_return:"partial_return",partial_return:"partial_return",exchange:"exchange",exchanged:"exchange",cancelled:"cancelled",canceled:"cancelled",cancelled_by_courier:"cancelled"},Ce={pending:"ready_to_ship",in_review:"ready_to_ship",picked:"shipped",picked_up:"shipped",in_transit:"in_transit",out_for_delivery:"in_transit",delivered:"delivered",partial_delivered:"partial_delivered",hold:"on_hold",on_hold:"on_hold",delivery_failed:"on_hold",lost:"on_hold",damaged:"on_hold",unknown:"on_hold",unknown_approval:"on_hold",delivered_approval_pending:"on_hold",partial_delivered_approval_pending:"on_hold",cancelled_approval_pending:"on_hold",unknown_approval_pending:"on_hold",return_approval_pending:"on_hold",hold_approval_pending:"on_hold",return:"return_in_transit",returning:"return_in_transit",pending_return:"return_in_transit",return_in_transit:"return_in_transit",returned:"pending_return",partial_delivered_return:"partial_return",partial_return:"partial_return",paid_return:"paid_return",unpaid_return:"unpaid_return",exchange:"exchange",exchanged:"exchange",cancelled:"cancelled",canceled:"cancelled"};function Ma(a,s){const i=a==="pathao"?ke:Ce,d=s?.[a]??{},m=new Set([...Object.keys(i),...Object.keys(d)]);return Array.from(m).sort().map(r=>({raw:r,mapped:d[r]??i[r],source:r in d?"override":"default"}))}function La({brandIdOverride:a}={}){const{activeBrand:s}=me(),i=a??s?.id,d=K(),{data:m,isLoading:r}=L({queryKey:["courier-mapping",i],enabled:!!i,queryFn:async()=>{const{data:x,error:j}=await q.from("erp_settings").select("config").eq("brand_id",i).maybeSingle();if(j)throw j;return x?.config?.courier_status_mapping??null}}),[c,p]=f.useState({});f.useEffect(()=>{p(m??{})},[m]);const t=M({mutationFn:async()=>
1{if(!i)throw new Error("Brand select korun");const{data:x}=await q.from("erp_settings").select("config").eq("brand_id",i).maybeSingle(),j={...x?.config??{},courier_status_mapping:c},{error:u}=await q.from("erp_settings").upsert({brand_id:i,config:j},{onConflict:"brand_id"});if(u)throw u},onSuccess:()=>{_.success("Mapping save hoyeche"),d.invalidateQueries({queryKey:["courier-mapping",i]})},onError:x=>_.error(x.message)});return i?r?e.jsx(J,{className:"h-64 w-full"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Courier Status Mapping"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Courier theke ja raw status ashbe, oitar against e amader ERP status set korun. Default mapping built-in, ekhane override korte parben."})]}),e.jsxs(w,{onClick:()=>t.mutate(),disabled:t.isPending,size:"sm",children:[t.isPending?e.jsx(I,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx($,{className:"h-4 w-4 mr-1.5"}),"Save"]})]}),e.jsxs(Ue,{defaultValue:"pathao",children:[e.jsxs(Ke,{children:[e.jsx(Q,{value:"pathao",children:"Pathao"}),e.jsx(Q,{value:"steadfast",children:"Steadfast"})]}),["pathao","steadfast"].map(x=>e.jsx(G,{value:x,className:"mt-3",children:e.jsx(Ba,{provider:x,overrides:c,setOverrides:p})},x))]})]}):e.jsx("div",{className:"text-sm text-muted-foreground",children:"Top theke ekta brand select korun."})}function Ba({provider:a,overrides:s,setOverrides:i}){const d=f.useMemo(()=>Ma(a,s),[a,s]),[m,r]=f.useState(""),[c,p]=f.useState("delivered"),t=(l,g)=>{i(n=>{const v={...n[a]??{}};return(a==="pathao"?ke:Ce)[l]===g?delete v[l]:v[l]=g,{...n,[a]:v}})},x=l=>{i(g=>{const n={...g[a]??{}};return delete n[l],{...g,[a]:n}})},j=l=>{l in(a==="pathao"?ke:Ce)||x(l)},u=()=>{const l=qa(m);l&&(t(l,c),r(""))};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"rounded-lg border bg-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/40 text-xs font-semibold text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2",children:"Courier Raw Status"}),e.jsx("th",{className:"text-left px-3 py-2",children:"→ ERP Status"}),e.jsx("th",{className:"px-3 py-2 w-20"})]})}),e.jsx("tbody",{children:d.map(l=>{const g=fe(l.mapped),n=a==="pathao"?ke:Ce,v=!(l.raw in n);return e.jsxs("tr",{className:"border-t",children:[e.jsxs("td",{className:"px-3 py-2 font-mono text-xs",children:[l.raw,l.source==="override"&&e.jsx(W,{variant:"outline",className:"ml-2 text-[10px]",children:"Custom"})]}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs(T,{value:l.mapped,onValueChange:o=>t(l.raw,o),children:[e.jsx(E,{className:"h-8 w-[180px]",children:e.jsx(F,{children:g.label})}),e.jsx(D,{children:De.map(o=>e.jsx(y,{value:o,children:fe(o).label},o))})]})}),e.jsxs("td",{className:"px-3 py-2 text-right",children:[l.source==="override"&&!v&&e.jsx(w,{size:"icon",variant:"ghost",onClick:()=>x(l.raw),title:"Default e firao",children:e.jsx(Ds,{className:"h-3.5 w-3.5"})}),v&&e.jsx(w,{size:"icon",variant:"ghost",onClick:()=>j(l.raw),title:"Delete",children:e.jsx(ge,{className:"h-3.5 w-3.5 text-destructive"})})]})]},l.raw)})})]})}),e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-3",children:[e.jsx(k,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom status add korun"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(b,{placeholder:"e.g. customer_unreachable",value:m,onChange:l=>r(l.target.value),className:"h-9 font-mono"}),e.jsxs(T,{value:c,onValueChange:l=>p(l),children:[e.jsx(E,{className:"h-9 w-[180px]",children:e.jsx(F,{children:fe(c).label})}),e.jsx(D,{children:De.map(l=>e.jsx(y,{value:l,children:fe(l).label},l))})]}),e.jsxs(w,{size:"sm",onClick:u,disabled:!m.trim(),children:[e.jsx(Se,{className:"h-4 w-4 mr-1"})," Add"]})]})]})]})}const Ra="https://swus-erp.lovable.app/api/public/webhook/pathao";function Oa({brandId:a}){const s=K(),{data:i,isLoading:d}=L({queryKey:["instapay-settings",a],enabled:!!a,queryFn:async()=>{const[{data:p},{data:t}]=await Promise.all([q.from("erp_settings").select("config").eq("brand_id",a).maybeSingle(),q.from("erp_accounts").select("id,name,current_balance").eq("brand_id",a).ilike("name","INSTAPAY PATHAO").maybeSingle()]),x=p?.config??{};return{auto:x.instapay_auto_apply===void 0||x.instapay_auto_apply===null?!0:!!x.instapay_auto_apply,wallet:t??null}}}),[m,r]=f.useState(!0);f.useEffect(()=>{i&&r(i.auto)},[i]);const c=M({mutationFn:async()=>{const{data:p}=await q.from("erp_settings").select("config").eq("brand_id",a).maybeSingle(),t={...p?.config??{},instapay_auto_apply:m},{error:x}=await q.from("erp_settings").upsert({brand_id:a,config:t},{onConflict:"brand_id"});if(x)throw x},onSuccess:()=>{_.success("InstaPay setting save hoyeche"),s.invalidateQueries({queryKey:["instapay-settings",a]})},onError:p=>_.error(p.message)});
1return d?e.jsx(J,{className:"h-48 w-full"}):e.jsxs("div",{className:"rounded-xl border bg-card p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(Ve,{className:"h-4 w-4"})," Pathao InstaPay"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Pathao payment-invoice webhook ashle payout automatic “INSTAPAY PATHAO” wallet-e credit hobe, order settle hobe. Auto off korle run-gulo pending thakbe — Reconciliation page theke manually Apply / CSV upload korte parben."})]}),e.jsxs(w,{size:"sm",onClick:()=>c.mutate(),disabled:c.isPending,children:[c.isPending?e.jsx(I,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx($,{className:"h-4 w-4 mr-1.5"}),"Save"]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(k,{className:"text-sm",children:"Auto-apply invoice"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Webhook theke asha invoice sathe sathe wallet-e post hobe."})]}),e.jsx(U,{checked:m,onCheckedChange:r})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-xs space-y-1",children:[e.jsx("div",{className:"text-muted-foreground",children:"Webhook URL (Pathao merchant panel-e set korun):"}),e.jsx("code",{className:"block break-all rounded bg-muted px-2 py-1",children:Ra})]}),i?.wallet?e.jsxs("div",{className:"rounded-lg border p-3 text-sm flex items-center justify-between",children:[e.jsx("span",{children:i.wallet.name}),e.jsxs("span",{className:"font-semibold",children:["৳",Number(i.wallet.current_balance??0).toLocaleString("en-BD")]})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Wallet ekhono toiri hoyni — prothom invoice ashlei “INSTAPAY PATHAO” account automatic toiri hobe."})]})}function Ia(){const a=K(),s=C(Rs),i=C(te),d=C(Os),[m,r]=f.useState(""),[c,p]=f.useState(""),[t,x]=f.useState(null),{data:j}=L({queryKey:["bdcourier-quota"],queryFn:()=>s({data:{}}),staleTime:3e4}),u=M({mutationFn:async()=>{const v=Number(m);if(!Number.isFinite(v)||v<=0)throw new Error("Valid number din");await i({data:{key:"bdcourier_daily_limit",value:v}})},onSuccess:()=>{_.success("Daily limit save hoyeche"),a.invalidateQueries({queryKey:["bdcourier-quota"]})},onError:v=>_.error(v.message)}),l=M({mutationFn:async()=>{const v=await d({data:{phones:[c],force:!0}});return Object.values(v.results)[0]},onSuccess:v=>{const o=(v?.providers??[]).filter(N=>N.name!=="pathao");x(o.length===0?"Kono data ashe nai":o.map(N=>N.ok?`${N.label}: ${N.success}/${N.total} success`:`${N.label}: ${N.error}`).join(" · ")),a.invalidateQueries({queryKey:["bdcourier-quota"]})},onError:v=>_.error(v.message)}),g=j?.used??0,n=j?.limit??500;return e.jsxs(qe,{children:[e.jsx(qs,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx(Ms,{className:"text-base",children:"BDCourier (non-Pathao couriers)"}),e.jsx(Ls,{children:"Steadfast, RedX, Paperfly, Sundarban ityadi courier-er success rate BDCourier API theke ase. Pathao amader nijer API theke."})]}),e.jsx(W,{variant:j?.configured?"default":"destructive",children:j?.configured?"API key set":"API key nei"})]})}),e.jsxs(Me,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Ajker search use"}),e.jsxs("span",{className:"font-medium tabular-nums",children:[g," / ",n]})]}),e.jsx(Bs,{value:Math.min(100,g/Math.max(1,n)*100)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ekta phone lookup = 1 search (sob courier ekshathe ase). Same phone 24 ghontar cache theke free ashe."})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-[1fr_auto] sm:items-end",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(k,{htmlFor:"bdc-limit",className:"text-xs",children:"Daily search limit"}),e.jsx(b,{id:"bdc-limit",inputMode:"numeric",placeholder:String(n),value:m,onChange:v=>r(v.target.value)})]}),e.jsx(w,{onClick:()=>u.mutate(),disabled:u.isPending||!m,children:"Save"})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-[1fr_auto] sm:items-end",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(k,{htmlFor:"bdc-test",className:"text-xs",children:"Test lookup (phone)"}),e.jsx(b,{id:"bdc-test",placeholder:"01XXXXXXXXX",maxLength:14,value:c,onChange:v=>p(v.target.value)})]}),e.jsx(w,{variant:"outline",onClick:()=>l.mutate(),disabled:l.isPending||c.replace(/\D/g,"").length<11,children:l.isPending?"Checking...":"Test"})]}),t&&e.jsx("p",{className:"rounded-lg border bg-muted/40 p-3 text-xs",children:t})]})]})}function $a({brandId:a}){const{isAdmin:s}=V();return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Courier Settings"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Credentials, store mapping and status overrides per provider."})]}),!s&&e.jsxs(de,{children:[e.jsx(hs,{className:"h-4 w-4"}),e.jsx(ce,{children:"API credentials are admin-only. You can still view status mappings."})]}),e.jsxs(Ue,{defaultValue:"pathao",className:"space-y-4",children:[e.jsxs(Ke,{children:[e.jsx(Q,{value:"pathao",children:"Pathao"}),e.jsx(Q,{value:"steadfast",children:"Steadfast"}),e.jsx(Q,{value:"bdcourier",children:"BDCourier"}),e.jsx(Q,{value:"mapping",children:"Status Mapping"})]}),e.jsx(G,{value:"pathao",children:s?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Es,{},a),e.jsx(Oa,{brandId:a})]}):e.jsx("div",{className:"rounded-xl border bg-card p-6 text-sm text-muted-foreground",children:"Hidden — admin only."})}),e.jsx(G,{value:"steadfast",children:s?e.jsx(Fs,{},a):e.jsx("div",{className:"rounded-xl border bg-card p-6 text-sm text-muted-foreground",children:"Hidden — admin only."})}),e.jsx(G,{value:"bdcourier",children:s?e.jsx(Ia,{}):e.jsx("div",{className:"rounded-xl border bg-card p-6 text-sm text-muted-foreground",children:"Hidden — admin only."})}),e.jsx(G,{value:"mapping",children:e.jsx(La,{brandIdOverride:a},a)})]})]})}const as={currency:"BDT",fiscal_year_start_month:7,double_entry_enabled:!0,default_expense_category:"Operating",auto_reconciliation:!1,low_stock_threshold:5,fx_update_frequency:"manual",default_tax_rate:0},za=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ua({brandId:a}){const{isAdmin:s}=V(),i=K(),d=`finance:${a}`,m=C(ue),r=C(te),{data:c,isLoading:p}=L({queryKey:["app-setting",d],queryFn:()=>m({data:{key:d}})}),[t,x]=f.useState(as);f.useEffect(()=>{c?.value&&x({...as,...c.value})},[c]);const j=M({mutationFn:()=>r({data:{key:d,value:t}}),onSuccess:()=>{_.success("Finance settings saved"),i.invalidateQueries({queryKey:["app-setting",d]})},onError:l=>_.error(l.message)}),u=(l,g)=>x({...t,[l]:g});return p?e.jsx("div",{className:"space-y-3",children:Array.from({length:5}).map((l,g)=>e.jsx(J,{className:"h-12 w-full"},g))}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Finance Settings"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Defaults for accounting, inventory and FX."})]}),e.jsxs("div",{className:"rounded-xl border bg-card p-5 grid grid-cols-1 md:grid-cols-2 gap-4 max-w-3xl",children:[e.jsx(re,{label:"Default currency",children:e.jsxs(T,{value:t.currency,onValueChange:l=>u("currency",l),disabled:!s,children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsx(D,{children:["BDT","USD","EUR","INR"].map(l=>e.jsx(y,{value:l,children:l},l))})]})}),e.jsx(re,{label:"Fiscal year starts",children:e.jsxs(T,{value:String(t.fiscal_year_start_month),onValueChange:l=>u("fiscal_year_start_month",Number(l)),disabled:!s,children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsx(D,{children:za.map((l,g)=>e.jsx(y,{value:String(g+1),children:l},l))})]})}),e.jsx(re,{label:"Default expense category",children:e.jsx(b,{value:t.default_expense_category,onChange:l=>u("default_expense_category",l.target.value),disabled:!s}
1)}),e.jsx(re,{label:"Low stock alert threshold",children:e.jsx(b,{type:"number",min:0,value:t.low_stock_threshold,onChange:l=>u("low_stock_threshold",Number(l.target.value)),disabled:!s})}),e.jsx(re,{label:"Default tax rate (%)",children:e.jsx(b,{type:"number",min:0,max:100,step:.01,value:t.default_tax_rate,onChange:l=>u("default_tax_rate",Number(l.target.value)),disabled:!s})}),e.jsx(re,{label:"FX rate update",children:e.jsxs(T,{value:t.fx_update_frequency,onValueChange:l=>u("fx_update_frequency",l),disabled:!s,children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"manual",children:"Manual"}),e.jsx(y,{value:"daily",children:"Daily (auto)"})]})]})}),e.jsx(ts,{label:"Enable double-entry accounting",checked:t.double_entry_enabled,onCheckedChange:l=>u("double_entry_enabled",l),disabled:!s}),e.jsx(ts,{label:"Auto-reconciliation",checked:t.auto_reconciliation,onCheckedChange:l=>u("auto_reconciliation",l),disabled:!s})]}),s&&e.jsx("div",{className:"flex justify-end max-w-3xl",children:e.jsxs(w,{onClick:()=>j.mutate(),disabled:j.isPending,children:[j.isPending?e.jsx(I,{className:"h-4 w-4 animate-spin"}):e.jsx($,{className:"h-4 w-4"}),"Save changes"]})})]})}function re({label:a,children:s}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(k,{className:"text-sm font-medium",children:a}),s]})}function ts({label:a,checked:s,onCheckedChange:i,disabled:d}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3 md:col-span-1",children:[e.jsx(k,{className:"text-sm",children:a}),e.jsx(U,{checked:s,onCheckedChange:i,disabled:d})]})}const ns={low_stock_email:!0,low_stock_in_app:!0,new_order:!0,cod_reconciliation_reminder:!0,failed_courier_sync:!0,daily_pnl_summary:!1,daily_pnl_time:"09:00",weekly_report:!1,recipient_emails:""};function Ka({brandId:a}){const{isAdmin:s}=V(),i=K(),d=`notifications:${a}`,m=C(ue),r=C(te),{data:c,isLoading:p}=L({queryKey:["app-setting",d],queryFn:()=>m({data:{key:d}})}),[t,x]=f.useState(ns);f.useEffect(()=>{c?.value&&x({...ns,...c.value})},[c]);const j=M({mutationFn:()=>r({data:{key:d,value:t}}),onSuccess:()=>{_.success("Notification settings saved"),i.invalidateQueries({queryKey:["app-setting",d]})},onError:l=>_.error(l.message)}),u=(l,g)=>x({...t,[l]:g});return p?e.jsx("div",{className:"space-y-3",children:Array.from({length:5}).map((l,g)=>e.jsx(J,{className:"h-12 w-full"},g))}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Notifications & Alerts"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose when and how the team gets notified."})]}),e.jsxs("div",{className:"rounded-xl border bg-card p-5 space-y-3 max-w-3xl",children:[e.jsx(ie,{label:"Low stock alert — email",checked:t.low_stock_email,onCheckedChange:l=>u("low_stock_email",l),disabled:!s}),e.jsx(ie,{label:"Low stock alert — in-app",checked:t.low_stock_in_app,onCheckedChange:l=>u("low_stock_in_app",l),disabled:!s}),e.jsx(ie,{label:"New order alert",checked:t.new_order,onCheckedChange:l=>u("new_order",l),disabled:!s}),e.jsx(ie,{label:"COD reconciliation reminder",checked:t.cod_reconciliation_reminder,onCheckedChange:l=>u("cod_reconciliation_reminder",l),disabled:!s}),e.jsx(ie,{label:"Failed courier sync alert",checked:t.failed_courier_sync,onCheckedChange:l=>u("failed_courier_sync",l),disabled:!s}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3 gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(k,{className:"text-sm",children:"Daily P&L summary"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emailed every day at the time below."})]}),e.jsx(b,{type:"time",value:t.daily_pnl_time,onChange:l=>u("daily_pnl_time",l.target.value),className:"w-28",disabled:!t.daily_pnl_summary||!s}),e.jsx(U,{checked:t.daily_pnl_summary,onCheckedChange:l=>u("daily_pnl_summary",l),disabled:!s})]}),e.jsx(ie,{label:"Weekly report (every Monday)",checked:t.weekly_report,onCheckedChange:l=>u("weekly_report",l),disabled:!s}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(k,{className:"text-sm",children:"Recipient emails (comma-separated)"}),e.jsx(Y,{value:t.recipient_emails,onChange:l=>u("recipient_emails",l.target.value),placeholder:"[email protected], [email protected]",rows:2,disabled:!s}
1)]})]}),s&&e.jsx("div",{className:"flex justify-end max-w-3xl",children:e.jsxs(w,{onClick:()=>j.mutate(),disabled:j.isPending,children:[j.isPending?e.jsx(I,{className:"h-4 w-4 animate-spin"}):e.jsx($,{className:"h-4 w-4"}),"Save changes"]})})]})}function ie({label:a,checked:s,onCheckedChange:i,disabled:d}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsx(k,{className:"text-sm",children:a}),e.jsx(U,{checked:s,onCheckedChange:i,disabled:d})]})}function Be({value:a,onChange:s,isAdmin:i,placeholder:d,disabled:m}){const[r,c]=f.useState(!1);return i?e.jsxs("div",{className:"relative",children:[e.jsx(b,{type:r?"text":"password",value:a,onChange:p=>s(p.target.value),placeholder:d,disabled:m,className:"pr-10 font-mono text-xs",autoComplete:"off"}),e.jsx(w,{type:"button",variant:"ghost",size:"icon",className:"absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7",onClick:()=>c(p=>!p),tabIndex:-1,children:r?e.jsx(Is,{className:"h-3.5 w-3.5"}):e.jsx(xs,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center gap-2 rounded-md border bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:[e.jsx(hs,{className:"h-3.5 w-3.5"})," Hidden — admin only"]})}const rs={api_key:"",model:"gemini-1.5-flash",address_parsing:!0},is={secret:""};function Va(){const a=new Uint8Array(24);return crypto.getRandomValues(a),Array.from(a).map(s=>s.toString(16).padStart(2,"0")).join("")}function Xa({brandId:a}){const{isAdmin:s}=V(),i=K(),d=C(ue),m=C(te),r="integration:gemini",c=L({queryKey:["app-setting",r],queryFn:()=>d({data:{key:r}})}),[p,t]=f.useState(rs);f.useEffect(()=>{c.data?.value&&t({...rs,...c.data.value})},[c.data]);const x=`integration:webhook:${a}`,j=L({queryKey:["app-setting",x],queryFn:()=>d({data:{key:x}})}),[u,l]=f.useState(is);f.useEffect(()=>{j.data?.value&&l({...is,...j.data.value})},[j.data]);const g=M({mutationFn:async v=>m({data:v}),onSuccess:(v,o)=>{_.success("Saved"),i.invalidateQueries({queryKey:["app-setting",o.key]})},onError:v=>_.error(v.message)}),n=typeof window<"u"?`${window.location.origin}/api/public/webhooks/${a}`:"(will be available after deploy)";return e.jsxs("div",{className:"space-y-6 max-w-3xl",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Integrations"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Marketing platforms, AI providers, and inbound webhooks."})]}),e.jsx(ve,{title:"Meta Ads (per brand)",icon:e.jsx(pa,{className:"h-4 w-4"}),children:e.jsx(de,{children:e.jsx(ce,{className:"text-xs",children:"Meta Ad Accounts (Pixel ID, Access Token, App ID/Secret) are managed in the Marketing module (currently being rebuilt — settings will move back here shortly)."})})}),e.jsx(ve,{title:"Gemini AI",icon:e.jsx(We,{className:"h-4 w-4"}),children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(_e,{label:"API Key",children:e.jsx(Be,{value:p.api_key,onChange:v=>t({...p,api_key:v}),isAdmin:s,placeholder:"AIza…"})}),e.jsx(_e,{label:"Model",children:e.jsxs(T,{value:p.model,onValueChange:v=>t({...p,model:v}),disabled:!s,children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsxs(D,{children:[e.jsx(y,{value:"gemini-1.5-flash",children:"gemini-1.5-flash (fast)"}),e.jsx(y,{value:"gemini-flash",children:"gemini-flash"}),e.jsx(y,{value:"gemini-pro",children:"gemini-pro"})]})]})}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsx(k,{children:"Enable AI address parsing"}),e.jsx(U,{checked:p.address_parsing,onCheckedChange:v=>t({...p,address_parsing:v}),disabled:!s})]}),s&&e.jsx("div",{className:"flex justify-end",children:e.jsxs(w,{size:"sm",onClick:()=>g.mutate({key:r,value:p}),disabled:g.isPending,children:[e.jsx($,{className:"h-4 w-4"})," Save Gemini"]})})]})}),e.jsx(ve,{title:"Lovable AI Gateway",icon:e.jsx(We,{className:"h-4 w-4"}),children:e.jsx(de,{children:e.jsxs(ce,{className:"text-xs",children:[e.jsx("code",{children:"LOVABLE_API_KEY"})," is managed automatically by Lovable Cloud — no manual entry needed. Rotate it from Project Settings → Secrets."]})})}),e.jsx(ve,{title:"Inbound Webhook",icon:e.jsx(ja,{className:"h-4 w-4"}),children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(_e,{label:"Webhook URL (read-only)",children:e.jsx(b,{readOnly:!0,value:n,className:"font-mono text-xs bg-muted/40"})}),e.jsx(_e,{label:"Secret for HMAC verification",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsx(Be,{value:u.secret,onChange:v=>l({...u,secret:v}),isAdmin:s})}),s&&e.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>l({...u,secret:Va()}),children:"Generate"})]})}),s&&e.jsx("div",{className:"flex justify-end",children:e.jsxs(w,{size:"sm",onClick:()=>g.mutate({key:x,value:u}),disabled:g.isPending,children:[e.jsx($,{className:"h-4 w-4"})," Save webhook"]})})]})})]})}function ve({title:a,icon:s,children:i}){return e.jsxs("section",{className:"rounded-xl border bg-card p-5",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-3",children:[s,a]}),i]})}function _e({label:a,children:s}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(k,{className:"text-sm font-medium",children:a}),s]})}async function Te(a,s){if(!s||s.length===0){_.error("No data to export");return}const i=Object.keys(s[0]),d=[i.join(","),...s.map(p=>i.map(t=>{const x=p[t];if(x==null)return"";const j=typeof x=="object"?JSON.stringify(x):String(x);return/[",\n]/.test(j)?`"${j.replace(/"/g,'""')}"`:j}).join(","))].join(`
2`),m=new Blob([d],{type:"text/csv;charset=utf-8;"}),r=URL.createObjectURL(m),c=document.createElement("a");c.href=r,c.download=a,c.click(),URL.revokeObjectURL(r)}function Ha({brandId:a}){const{brands:s}=me(),{isAdmin:i}=V(),d=s.find(t=>
2t.id===a),m=L({queryKey:["activity-logs-latest"],enabled:i,queryFn:async()=>{const{data:t,error:x}=await q.from("activity_logs").select("id, action, created_at, user_id, note, order_id").order("created_at",{ascending:!1}).limit(100);if(x)throw x;return t??[]}});async function r(){const{data:t,error:x}=await q.from("orders").select("invoice_no, status, payment_method, total, subtotal, shipping_fee, advance_amount, created_at, shipping_name, shipping_phone, shipping_address").eq("brand_id",a).order("created_at",{ascending:!1}).limit(1e4);if(x){_.error(x.message);return}await Te(`orders-${d?.slug??a}-${Date.now()}.csv`,t??[])}async function c(){const{data:t,error:x}=await q.from("products").select("id, name, sku, price, stock, is_active, created_at").eq("brand_id",a).limit(1e4);if(x){_.error(x.message);return}await Te(`products-${d?.slug??a}-${Date.now()}.csv`,t??[])}async function p(){const{data:t,error:x}=await q.from("erp_transactions").select("id, type, amount, currency, description, occurred_at, created_at").eq("brand_id",a).order("occurred_at",{ascending:!1}).limit(1e4);if(x){_.error(x.message);return}await Te(`finance-${d?.slug??a}-${Date.now()}.csv`,t??[])}return e.jsxs("div",{className:"space-y-6 max-w-3xl",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Data & System"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Exports, activity log, system info."})]}),e.jsxs("section",{className:"rounded-xl border bg-card p-5",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(be,{className:"h-4 w-4"}),"Export data — ",d?.name]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(w,{variant:"outline",size:"sm",onClick:r,children:[e.jsx(be,{className:"h-4 w-4"})," Orders CSV"]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:c,children:[e.jsx(be,{className:"h-4 w-4"})," Products CSV"]}),e.jsxs(w,{variant:"outline",size:"sm",onClick:p,children:[e.jsx(be,{className:"h-4 w-4"})," Finance CSV"]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-2",children:"Up to 10,000 rows per export. Brand-scoped."})]}),e.jsxs("section",{className:"rounded-xl border bg-card p-5",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Le,{className:"h-4 w-4"}),"Activity log (latest 100)"]}),i?m.isLoading?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading…"}):(m.data??[]).length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No activity yet."}):e.jsx("div",{className:"max-h-80 overflow-auto rounded border divide-y text-xs",children:(m.data??[]).map(t=>e.jsxs("div",{className:"p-2 flex gap-3",children:[e.jsx(W,{variant:"outline",className:"font-mono shrink-0",children:t.action}),e.jsx("span",{className:"flex-1 truncate text-muted-foreground",children:t.note??t.order_id}),e.jsx("span",{className:"text-muted-foreground shrink-0",children:new Date(t.created_at).toLocaleString()})]},t.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Admin only."})]}),e.jsxs("section",{className:"rounded-xl border bg-card p-5",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"System info"]}),e.jsxs("dl",{className:"text-xs grid grid-cols-2 gap-x-4 gap-y-1.5 font-mono",children:[e.jsx("dt",{className:"text-muted-foreground",children:"Supabase project"}),e.jsx("dd",{children:"bgsspipkjeuceftuatue"}),e.jsx("dt",{className:"text-muted-foreground",children:"Build mode"}),e.jsx("dd",{children:"production"}),e.jsx("dt",{className:"text-muted-foreground",children:"Active brand"}),e.jsx("dd",{children:d?.slug??"—"}),e.jsx("dt",{className:"text-muted-foreground",children:"Brands available"}),e.jsx("dd",{children:s.length})]})]}),e.jsxs("section",{className:"rounded-xl border bg-card p-5",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Xe,{className:"h-4 w-4"}),"Cache"]}
2),e.jsxs(w,{size:"sm",variant:"outline",onClick:()=>{typeof window<"u"&&window.location.reload()},children:[e.jsx(Le,{className:"h-4 w-4"})," Reload app"]})]})]})}const Qa=ee({method:"POST"}).middleware([se]).handler(Z("6bc9f247d30b2c44e730c4e6fc266c88ab1060a482997a14fa8516d58ac28341"));function Ga({brandId:a}){const{isAdmin:s}=V(),[i,d]=f.useState(!1),[m,r]=f.useState(""),c=C(Qa),p=M({mutationFn:()=>c({data:{brandId:a,confirm:"DELETE"}}),onSuccess:x=>{_.success(`Deleted ${x.deleted} test order(s)`),d(!1),r("")},onError:x=>_.error(x.message)});return s?e.jsxs("div",{className:"space-y-4 max-w-3xl",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-destructive flex items-center gap-2",children:[e.jsx(je,{className:"h-5 w-5"}),"Danger Zone"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Destructive actions. Double-check before proceeding."})]}),e.jsxs(de,{variant:"destructive",children:[e.jsx(je,{className:"h-4 w-4"}),e.jsx(ce,{children:"These actions are irreversible. Always run a backup first."})]}),e.jsxs("section",{className:"rounded-xl border-2 border-destructive/40 bg-destructive/5 p-5 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Clear test data"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Deletes orders where ",e.jsx("code",{children:"notes"}),' contains "TEST" (current brand only). Also removes related order items, notes, status history.']})]}),e.jsxs(Re,{open:i,onOpenChange:x=>{d(x),x||r("")},children:[e.jsx(us,{asChild:!0,children:e.jsxs(w,{variant:"destructive",size:"sm",children:[e.jsx(ge,{className:"h-4 w-4"})," Clear test data…"]})}),e.jsxs(Oe,{children:[e.jsx(Ie,{children:e.jsx($e,{className:"text-destructive",children:"Confirm test data deletion"})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Type ",e.jsx("code",{className:"font-mono font-bold text-foreground",children:"DELETE"})," to confirm."]}),e.jsx(k,{className:"sr-only",children:"Confirm"}),e.jsx(b,{value:m,onChange:x=>r(x.target.value),placeholder:"DELETE"}),e.jsxs(ze,{children:[e.jsx(w,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(w,{variant:"destructive",disabled:m!=="DELETE"||p.isPending,onClick:()=>p.mutate(),children:[p.isPending?e.jsx(I,{className:"h-4 w-4 animate-spin"}):e.jsx(ge,{className:"h-4 w-4"}),"Delete forever"]})]})]})]})]}),e.jsxs("section",{className:"rounded-xl border-2 border-destructive/40 bg-destructive/5 p-5 space-y-2",children:[e.jsx("h3",{className:"font-semibold",children:"Full DB backup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supabase manages daily backups automatically. Trigger a manual backup or download from the dashboard."}),e.jsxs("a",{href:"https://supabase.com/dashboard/project/bgsspipkjeuceftuatue/database/backups",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 text-sm text-primary hover:underline",children:["Open Supabase backups ",e.jsx(ps,{className:"h-3.5 w-3.5"})]})]})]}):e.jsx("div",{className:"rounded-xl border bg-card p-6 text-sm text-muted-foreground",children:"Admin only."})}const Wa=["text","number","date","toggle","select","url"];function Ya({brandId:a}){const{isAdmin:s}=V(),i=K(),d=C(zs),m=C(Us),r=C(Ks),c=C(Vs),[p,t]=f.useState(!1),[x,j]=f.useState(""),[u,l]=f.useState("text"),[g,n]=f.useState(""),[v,o]=f.useState(!1),N=L({queryKey:["crm-custom-field-defs",a],enabled:s,queryFn:()=>d({data:{brandId:a}}),staleTime:3e4}),A=M({mutationFn:()=>m({data:{brandId:a,label:x.trim(),fieldType:u,options:u==="select"?g.split(",").map(h=>h.trim()).filter(Boolean):void 0,isRequired:v,sortOrder:(N.data?.length??0)*10}}),onSuccess:()=>{_.success("Field added"),t(!1),j(""),l("text"),n(""),o(!1),i.invalidateQueries({queryKey:["crm-custom-field-defs"]})},onError:h=>_.error(h.message??"Create failed")}),R=M({mutationFn:h=>c({data:{id:h}}),onSuccess:()=>{_.success("Field deleted"),i.invalidateQueries({queryKey:["crm-custom-field-defs"]})},onError:h=>_.error(h.message??"Delete failed")}),X=M({mutationFn:h=>r({data:{id:h.id,patch:{isRequired:h.isRequired}}}),onSuccess:()=>i.invalidateQueries({queryKey:["crm-custom-field-defs"]})});if(!s)return e.jsx(qe,{children:e.jsx(Me,{className:"p-6 text-sm text-muted-foreground",children:"Admin only."})});const H=N.data??[];return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"CRM Custom Fields"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Per-customer extra fields. Customer detail page e form auto-render hobe."})]}),e.jsxs(w,{size:"sm",onClick:()=>t(!0),children:[e.jsx(Se,{className:"h-4 w-4 mr-1.5"})," Add field"]})]}),e.jsx(qe,{children:e.jsx(Me,{className:"p-0",children:N.isLoading?e.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"Loading…"}):H.length?e.jsx("ul",{className:"divide-y",children:H.map(h=>e.jsxs("li",{className:"flex items-center gap-3 px-4 py-3",children:[e.jsx(Xs,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:h.label}),e.jsx(W,{variant:"outline",className:"text-[10px]",children:h.field_type}),e.jsx("span",{className:"text-[11px] text-muted-foreground font-mono truncate",children:h.field_key})]}),h.field_type==="select"&&h.options?.values?.length>0&&e.jsxs("div",{className:"text-[11px] text-muted-foreground mt-0.5 truncate",children:["Options: ",h.options.values.join(", ")
2]})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(Ye,{checked:h.is_required,onCheckedChange:O=>X.mutate({id:h.id,isRequired:!!O})}),"Required"]}),e.jsx(w,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>{confirm(`Delete field "${h.label}"? Existing values stay in JSON.`)&&R.mutate(h.id)},children:e.jsx(ge,{className:"h-4 w-4"})})]},h.id))}):e.jsx("div",{className:"p-8 text-sm text-muted-foreground text-center",children:"No custom fields yet. Add one to start collecting structured data."})})}),e.jsx(Re,{open:p,onOpenChange:t,children:e.jsxs(Oe,{children:[e.jsx(Ie,{children:e.jsx($e,{children:"Add custom field"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(k,{children:"Label"}),e.jsx(b,{value:x,onChange:h=>j(h.target.value),placeholder:"e.g. Preferred size"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(k,{children:"Type"}),e.jsxs(T,{value:u,onValueChange:h=>l(h),children:[e.jsx(E,{children:e.jsx(F,{})}),e.jsx(D,{children:Wa.map(h=>e.jsx(y,{value:h,children:h},h))})]})]}),u==="select"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(k,{children:"Options (comma-separated)"}),e.jsx(b,{value:g,onChange:h=>n(h.target.value),placeholder:"S, M, L, XL"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ye,{checked:v,onCheckedChange:h=>o(!!h)}),"Required field"]})]}),e.jsxs(ze,{children:[e.jsx(w,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(w,{disabled:!x.trim()||A.isPending,onClick:()=>A.mutate(),children:[e.jsx($,{className:"h-4 w-4 mr-1.5"}),A.isPending?"Saving…":"Save"]})]})]})})]})}const ls={ga4_measurement_id:"",clarity_project_id:"",meta_pixel_id:"",gtm_container_id:"",enable_ga4:!1,enable_clarity:!1,enable_meta_pixel:!1,enable_gtm:!1,retention_days:90,track_admin_traffic:!1};function Ja({brandId:a}){const{isAdmin:s}=V(),i=K(),d=C(ue),m=C(te),r=`analytics:tracking:${a}`,c=L({queryKey:["app-setting",r],queryFn:()=>d({data:{key:r}})}),[p,t]=f.useState(ls);f.useEffect(()=>{c.data?.value&&t({...ls,...c.data.value})},[c.data]);const x=M({mutationFn:()=>m({data:{key:r,value:p}}),onSuccess:()=>{_.success("Analytics settings saved"),i.invalidateQueries({queryKey:["app-setting",r]})},onError:g=>_.error(g.message)}),[j,u]=f.useState(!1),l=async()=>{u(!0);try{const{error:g}=await q.from("analytics_events").insert({event_name:"test_event",session_id:`test-${Date.now()}`,path:"/erp/settings",brand_id:a,metadata:{source:"settings_test_button",brand_id:a}});if(g)throw g;_.success("Test event sent — check Live Analytics dashboard")}catch(g){_.error(g.message)}finally{u(!1)}};return e.jsxs("div",{className:"space-y-6 max-w-3xl",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Analytics & Tracking"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Configure tracking pixels, data retention, and test your setup."})]}),e.jsxs(le,{title:"Google Analytics 4",icon:e.jsx(gs,{className:"h-4 w-4 text-blue-600"}),children:[e.jsx(pe,{label:"Enable GA4 tracking",checked:p.enable_ga4,onChange:g=>t({...p,enable_ga4:g}),disabled:!s}),e.jsx(he,{label:"Measurement ID",children:e.jsx(b,{value:p.ga4_measurement_id,onChange:g=>t({...p,ga4_measurement_id:g.target.value}),placeholder:"G-XXXXXXXXXX",disabled:!s,className:"font-mono"})})]}),e.jsxs(le,{title:"Microsoft Clarity",icon:e.jsx(js,{className:"h-4 w-4 text-orange-600"}),children:[e.jsx(pe,{label:"Enable Clarity heatmaps",checked:p.enable_clarity,onChange:g=>t({...p,enable_clarity:g}),disabled:!s}),e.jsx(he,{label:"Project ID",children:e.jsx(b,{value:p.clarity_project_id,onChange:g=>t({...p,clarity_project_id:g.target.value}),placeholder:"abcd1234ef",disabled:!s,className:"font-mono"})})]}),e.jsxs(le,{title:"Meta Pixel",icon:e.jsx(He,{className:"h-4 w-4 text-blue-700"}),children:[e.jsx(pe,{label:"Enable Meta Pixel",checked:p.enable_meta_pixel,onChange:g=>t({...p,enable_meta_pixel:g}),disabled:!s}),e.jsx(he,{label:"Pixel ID",children:e.jsx(b,{value:p.meta_pixel_id,onChange:g=>t({...p,meta_pixel_id:g.target.value}),placeholder:"1234567890123456",disabled:!s,className:"font-mono"})}),e.jsx(de,{children:e.jsx(ce,{className:"text-xs",children:"Server-side Conversions API token is managed in the Marketing module (currently being rebuilt)."})})]}),e.jsxs(le,{title:"Google Tag Manager",icon:e.jsx(ms,{className:"h-4 w-4 text-emerald-600"}),children:[e.jsx(pe,{label:"Enable GTM",checked:p.enable_gtm,onChange:g=>t({...p,enable_gtm:g}),disabled:!s}
2),e.jsx(he,{label:"Container ID",children:e.jsx(b,{value:p.gtm_container_id,onChange:g=>t({...p,gtm_container_id:g.target.value}),placeholder:"GTM-XXXXXXX",disabled:!s,className:"font-mono"})})]}),e.jsxs(le,{title:"Data Retention & Privacy",icon:e.jsx(Xe,{className:"h-4 w-4 text-purple-600"}),children:[e.jsxs(he,{label:"Event retention (days)",children:[e.jsx(b,{type:"number",min:7,max:730,value:p.retention_days,onChange:g=>t({...p,retention_days:Math.max(7,Math.min(730,Number(g.target.value)||90))}),disabled:!s}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Events older than this are eligible for cleanup. Min 7, max 730."})]}),e.jsx(pe,{label:"Track admin/staff traffic",checked:p.track_admin_traffic,onChange:g=>t({...p,track_admin_traffic:g}),disabled:!s})]}),e.jsx(le,{title:"Test Tracking",icon:e.jsx(Je,{className:"h-4 w-4 text-pink-600"}),children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex-1 min-w-[200px]",children:["Sends a synthetic ",e.jsx("code",{className:"text-[11px]",children:"test_event"})," to verify your pipeline. Open Live Analytics to see it arrive in real-time."]}),e.jsxs(w,{size:"sm",variant:"outline",onClick:l,disabled:j,children:[e.jsx(Je,{className:"h-4 w-4"})," ",j?"Sending…":"Send test event"]})]})}),s&&e.jsx("div",{className:"flex justify-end sticky bottom-2",children:e.jsxs(w,{onClick:()=>x.mutate(),disabled:x.isPending,className:"shadow-lg",children:[e.jsx($,{className:"h-4 w-4"})," Save analytics settings"]})})]})}function le({title:a,icon:s,children:i}){return e.jsxs("section",{className:"rounded-xl border bg-card p-5 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[s,a]}),i]})}function he({label:a,children:s}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(k,{className:"text-sm font-medium",children:a}),s]})}function pe({label:a,checked:s,onChange:i,disabled:d}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsx(k,{className:"text-sm",children:a}),e.jsx(U,{checked:s,onCheckedChange:i,disabled:d})]})}const Za=ee({method:"GET"}).middleware([se]).handler(Z("d5b34e8a8a545fc9e72527e1f6b5c75d1763dfa1231b68ec2c7720cbaf90b119")),et=ee({method:"POST"}).middleware([se]).handler(Z("8ba470eb3886a512abaf9c749a157b1719094b53fcc692523c710d1ab689b9eb")),st=ee({method:"POST"}).middleware([se]).handler(Z("981ce196de84e8168f87403c0407167954459cd005fdd58b157f9be28795af08")),at=ee({method:"GET"}).middleware([se]).handler(Z("3786dc96bf74976bc5598154c43dc59a1caf9a9d47ac2c118a91fa42a505dc4a")),tt=ee({method:"GET"}).middleware([se]).handler(Z("6f8dbbafe2d60537bf5d61c945116fe60c14f3fab2e08f8f7d8750736a381d17")),nt=ee({method:"GET"}).middleware([se]).handler(Z("3b3e64a4f06495c76686230d0c4e970a77f8d034954b9ddf431fa9d47a961654")),rt=["PageView","ViewContent","AddToCart","InitiateCheckout","Purchase"];function Qe(a){if(!a)return"—";const s=Date.now()-new Date(a).getTime(),i=Math.floor(s/6e4);if(i<1)return"just now";if(i<60)return`${i}m ago`;const d=Math.floor(i/60);return d<24?`${d}h ago`:`${Math.floor(d/24)}d ago`}function it(){const{isAdmin:a}=V(),s=K(),i=C(Za),d=L({queryKey:["meta-tracking-configs"],queryFn:()=>i(),refetchInterval:3e4});return e.jsxs("div",{className:"space-y-6 max-w-5xl",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(He,{className:"h-5 w-5 text-blue-600"})," Meta Pixel & CAPI"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Per-brand Pixel ID, Conversions API token, event toggles, test sender, and live status."})]})}),d.isLoading&&e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(I,{className:"h-4 w-4 animate-spin"})," Loading brands…"]}),e.jsx(ot,{}),e.jsx("div",{className:"space-y-5",children:(d.data??[]).map(m=>e.jsx(lt,{brand:m.brand,config:m.config,status:m.status,disabled:!a,onSaved:()=>s.invalidateQueries({queryKey:["meta-tracking-configs"]})},m.brand.id))}),e.jsx(dt,{}),e.jsx(ct,{})]})}function lt({brand:a,config:s,status:i,disabled:d,onSaved:m}){const[r,c]=f.useState(s.pixel_id??""),[p,t]=f.useState(s.token_secret_name??`META_CAPI_TOKEN_${(a.slug??a.name).toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`),[x,j]=f.useState(s.test_event_code??""),[u,l]=f.useState(s.capi_enabled),[g,n]=f.useState({...s.enabled_events}),[v,o]=f.useState(""),[N,A]=f.useState(!1),R=C(et),X=C(st),H=M({mutationFn:()=>R({data:{brand_id:a.id,pixel_id:r,capi_enabled:u,test_event_code:x,enabled_events:g,token_secret_name:p,...v.trim()?{capi_access_token:v.trim()}:{}}}),onSuccess:()=>{_.success(`${a.name} tracking saved`),o(""),m()},onError:P=>_.error(P.message)}),h=M({mutationFn:()=>X({data:{brand_id:a.id}}),onSuccess:P=>{P.ok?_.success(`✅ Meta received ${P.events_received??1} event · trace ${P.fbtrace_id??"—"}`):_.error(`❌ ${P.error??"CAPI rejected"}`),m()},onError:P=>_.error(P.message)}),O=i.last_at?i.error>0&&i.error/Math.max(i.total,1)>.3?"bg-red-500":Date.now()-new Date(i.last_at).getTime()<3600*1e3?"bg-emerald-500":"bg-amber-500":"bg-gray-400";return e.jsxs("section",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-5 py-3 border-b bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:ae("h-2.5 w-2.5 rounded-full shrink-0",O)}),e.jsx("h3",{className:"font-semibold truncate",children:a.name}),s.pixel_id&&e.jsxs(W,{variant:"outline",className:"font-mono text-[10px]",children:["PX ",s.pixel_id]}),e.jsxs(W,{variant:s.capi_enabled?"default":"secondary",className:"text-[10px]",children:["CAPI ",s.capi_enabled?"ON":"OFF"]}),s.token_secret_name&&e.jsxs(W,{variant:s.token_present?"default":"destructive",className:"text-[10px] gap-1",children:[e.jsx(Hs,{className:"h-3 w-3"})," ",s.token_present?"token ok":"token missing"]})]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center gap-3 shrink-0",children:[e.jsxs("span",{title:"Last 24h",children:[e.jsx(js,{className:"inline h-3 w-3 mr-0.5"}),i.ok,"/",i.total," ok"]}),e.jsxs("span",{children:["last: ",Qe(i.last_at),i.last_event?` · ${i.last_event}`:""]})]})]}),e.jsxs("div",{className:"p-5 grid md:grid-cols-2 gap-5",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ee,{label:"Meta Pixel ID",children:e.jsx(b,{value:r,onChange:P=>c(P.target.value),placeholder:"123456789012345",disabled:d,className:"font-mono",inputMode:"numeric"})}),e.jsxs(Ee,{label:"CAPI Access Token",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{type:N?"text":"password",value:v,onCh
2ange:P=>o(P.target.value),placeholder:s.token_present?`•••••••• ${s.token_last4??""}`:"Paste your Meta CAPI access token",disabled:d,className:"font-mono text-xs",autoComplete:"off"}),e.jsx(w,{type:"button",variant:"outline",size:"sm",onClick:()=>A(P=>!P),disabled:d,children:N?"Hide":"Show"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:s.token_present?`Token saved (ends ••${s.token_last4??"??"}). Leave blank to keep, paste a new value to replace.`:"Paste your Conversions API access token from Meta Events Manager."})]}),e.jsx(Ee,{label:"Test Event Code (optional)",children:e.jsx(b,{value:x,onChange:P=>j(P.target.value),placeholder:"TEST12345",disabled:d,className:"font-mono"})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border p-3 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(k,{className:"text-sm font-medium",children:"Server-side CAPI enabled"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Master switch. Off = ERP won't fire any CAPI event."})]}),e.jsx(U,{checked:u,onCheckedChange:l,disabled:d})]}),e.jsxs("div",{className:"rounded-md border p-3 space-y-2",children:[e.jsx(k,{className:"text-sm font-medium",children:"Event types"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:rt.map(P=>e.jsxs("label",{className:"flex items-center justify-between gap-2 text-xs px-2 py-1 rounded border bg-background",children:[e.jsx("span",{children:P}),e.jsx(U,{checked:!!g[P],onCheckedChange:xe=>n(ys=>({...ys,[P]:xe})),disabled:d})]},P))})]}),s.pixel_id&&e.jsxs("a",{href:`https://www.facebook.com/events_manager2/list/pixel/${s.pixel_id}/test_events`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 text-xs text-primary hover:underline",children:[e.jsx(ps,{className:"h-3 w-3"})," Open Events Manager Test Events"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 px-5 py-3 border-t bg-muted/20",children:[e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>h.mutate(),disabled:d||h.isPending||!s.pixel_id||!s.token_present,children:[h.isPending?e.jsx(I,{className:"h-4 w-4 animate-spin"}):e.jsx(we,{className:"h-4 w-4"}),"Send test event"]}),e.jsxs(w,{size:"sm",onClick:()=>H.mutate(),disabled:d||H.isPending,children:[e.jsx($,{className:"h-4 w-4"})," Save ",a.name]})]})]})}function dt(){const a=C(nt),[s,i]=f.useState(30),d=L({queryKey:["utm-breakdown",s],queryFn:()=>a({data:{days:s}})}),m=f.useMemo(()=>!d.data||d.data.total_orders===0?0:Math.round(d.data.captured_attribution/d.data.total_orders*100),[d.data]);return e.jsxs("section",{className:"rounded-xl border bg-card",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(Qs,{className:"h-4 w-4 text-emerald-600"})," UTM & Attribution capture"]}),e.jsx("div",{className:"flex gap-1",children:[7,30,90].map(r=>e.jsxs("button",{onClick:()=>i(r),className:ae("px-2 py-0.5 rounded text-xs",s===r?"bg-primary text-primary-foreground":"hover:bg-accent"),children:[r,"d"]},r))})]}),e.jsxs("div",{className:"px-5 py-3 grid grid-cols-3 gap-3 text-sm border-b bg-muted/20",children:[e.jsx(Fe,{label:"Orders",value:d.data?.total_orders??0}),e.jsx(Fe,{label:"UTM captured",value:`${m}%`,hint:`${d.data?.captured_attribution??0} orders`}),e.jsx(Fe,{label:"fbclid/fbc",value:d.data?.captured_fbclid??0,hint:"for FB Ads match"})]}),e.jsx("div",{className:"overflow-auto max-h-72",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-card border-b text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-1.5",children:"Source"}),e.jsx("th",{className:"text-left px-3 py-1.5",children:"Medium"}),e.jsx("th",{className:"text-left px-3 py-1.5",children:"Campaign"}),e.jsx("th",{className:"text-right px-3 py-1.5",children:"Orders"}),e.jsx("th",{className:"text-right px-3 py-1.5",children:"Revenue"}),e.jsx("th",{className:"text-right px-3 py-1.5",children:"fbclid"})]})}),e.jsxs("tbody",{children:[(d.data?.breakdown??[]).slice(0,50).map((r,c)=>e.jsxs("tr",{className:"border-b hover:bg-muted/30",children:[e.jsx("td",{className:"px-3 py-1.5 font-medium",children:r.utm_source}),e.jsx("td",{className:"px-3 py-1.5",children:r.utm_medium}),e.jsx("td",{className:"px-3 py-1.5 truncate max-w-[200px]",children:r.utm_campaign}),e.jsx("td",{className:"px-3 py-1.5 text-right tabular-nums",children:r.orders}),e.jsxs("td",{className:"px-3 py-1.5 text-right tabular-nums",children:["৳",Math.round(r.revenue).toLocaleStr
2ing()]}),e.jsx("td",{className:"px-3 py-1.5 text-right tabular-nums",children:r.has_fbclid})]},c)),(!d.data||d.data.breakdown.length===0)&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-center py-6 text-muted-foreground",children:"No orders in window"})})]})]})})]})}function ct(){const a=C(at),s=L({queryKey:["capi-logs"],queryFn:()=>a({data:{limit:30}}),refetchInterval:15e3});return e.jsxs("section",{className:"rounded-xl border bg-card",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(Gs,{className:"h-4 w-4 text-indigo-600"})," Recent CAPI sends"]}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"auto-refresh 15s"})]}),e.jsx("div",{className:"overflow-auto max-h-64",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-card border-b text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-1.5",children:"When"}),e.jsx("th",{className:"text-left px-3 py-1.5",children:"Event"}),e.jsx("th",{className:"text-left px-3 py-1.5",children:"Source"}),e.jsx("th",{className:"text-left px-3 py-1.5",children:"Status"}),e.jsx("th",{className:"text-left px-3 py-1.5",children:"Details"})]})}),e.jsxs("tbody",{children:[(s.data??[]).map(i=>e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"px-3 py-1.5 text-muted-foreground",children:Qe(i.created_at)}),e.jsx("td",{className:"px-3 py-1.5 font-medium",children:i.event_name}),e.jsx("td",{className:"px-3 py-1.5",children:i.source??"—"}),e.jsx("td",{className:"px-3 py-1.5",children:i.status==="ok"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-600",children:[e.jsx(fs,{className:"h-3 w-3"})," ok"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-red-600",children:[e.jsx(bs,{className:"h-3 w-3"})," error"]})}),e.jsx("td",{className:"px-3 py-1.5 text-muted-foreground truncate max-w-[420px]",children:i.status==="ok"?`received ${i.events_received??1}${i.fbtrace_id?` · ${i.fbtrace_id}`:""}`:i.error??"—"})]},i.id)),(!s.data||s.data.length===0)&&e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"text-center py-6 text-muted-foreground",children:'No CAPI sends yet. Try "Send test event".'})})]})]})}),e.jsxs(de,{className:"m-3",children:[e.jsx(je,{className:"h-4 w-4"}),e.jsx(ce,{className:"text-[11px]",children:"Tokens are read from runtime secrets by the name you set above. Browser pixel events fire from your website code — this panel only shows server-side CAPI sends."})]})]})}function Ee({label:a,children:s}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(k,{className:"text-sm font-medium",children:a}),s]})}function ot(){const a=C(tt),s=L({queryKey:["tracking-health"],queryFn:()=>a(),refetchInterval:3e4}),i=f.useMemo(()=>{const d=s.data??[];return{healthy:d.filter(m=>m.verdict==="healthy").length,warning:d.filter(m=>m.verdict==="warning").length,down:d.filter(m=>m.verdict==="down").length,total:d.length}},[s.data]);return e.jsxs("section",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b bg-gradient-to-r from-emerald-500/5 to-blue-500/5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xa,{className:"h-4 w-4 text-rose-600"}),e.jsx("h3",{className:"font-semibold",children:"Daily Health Check"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"last 24h · auto-refresh 30s"})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-emerald-500"})," ",i.healthy," healthy"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-amber-500"})," ",i.warning," warning"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-red-500"})," ",i.down," down"]}),e.jsx(w,{size:"sm",variant:"ghost",onClick:()=>s.refetch(),disabled:s.isFetching,className:"h-6 px-2",children:e.jsx(Le,{className:ae("h-3 w-3",s.isFetching&&"animate-spin")})})]})]}),e.jsxs("div",{className:"divide-y",children:[(s.data??[]).map(d=>e.jsx(mt,{row:d},d.brand.id)),!s.isLoading&&(s.data?.length??0)===0&&e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"No brands configured."}),s.isLoading&&e.jsxs("div",{className:"text-center text-sm text-muted-foreground py-8",children:[e.jsx(I,{className:"inline h-4 w-4 animate-spin"})," Loading…"]})]})]})}function mt({row:a}){const[s,i]=f.useState(!1),d=a.verdict==="healthy"?"bg-emerald-500":a.verdict==="warning"?"bg-amber-500":"bg-red-500",m=a.verdict==="healthy"?"All systems go":a.verdict==="warning"?"Minor issues":"Needs attention";return e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>i(r=>!r),className:"w-full flex items-center justify-between gap-3 px-5 py-3 hover:bg-muted/40 text-left",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:ae("h-2.5 w-2.5 rounded-full shrink-0",d)}),e.jsx("span",{className:"font-semibold truncate",children:a.brand.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground tabular-nums",children:[e.jsxs("span",{title:"Browser pixel events",children:["PX ",e.jsx("b",{className:"text-foreground",children:a.counts.px_total})]}),e.jsxs("span",{title:"Server CAPI sends",children:["CAPI ",e.jsx("b",{className:"text-foreground",children:a.counts.capi_total}),a.counts.capi_errors>0&&e.jsxs("span",{className:"text-red-600",children:[" (",a.counts.capi_errors," err)"]})]}),e.jsxs("span",{title:"Orders / with UTM",children:["ORD ",e.jsxs("b",{className:"text-foreground",children:[a.counts.orders_with_attribution,"/",a.counts.orders]})]})]})]}),s&&e.jsxs("div",{className:"px-5 pb-4 grid md:grid-cols-2 gap-4 bg-muted/20",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground font-medium",children:"Checks"}),a.checks.map(r=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs px-2 py-1.5 rounded bg-background border",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.ok?e.jsx(fs,{className:"h-3.5 w-3.5 text-emerald-600 shrink-0"}):r.critical?e.jsx(bs,{className:"h-3.5 w-3.5 text-red-600 shrink-0"}):e.jsx(je,{className:"h-3.5 w-3.5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:r.label})]}),r.detail&&e.jsx("span",{className:"text-muted-foreground tabular-nums shrink-0",children:r.detail})]},r.id))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ds,{title:"Browser pixel events (24h)",data:a.px_by_event,lastAt:a.last_px_at}),e.jsx(ds,{title:"Server CAPI sends (24h)",data:a.capi_by_event,errors:a.capi_err_by_event,lastAt:a.last_capi_at})]})]})]})}function ds({title:a,data:s,errors:i,lastAt:d}){const m=Object.entries(s??{}).sort((r,c)=>c[1]-r[1]);return e.jsxs("div",{className:"rounded border bg-background p-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground font-medium",children:a}),e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["last: ",Qe(d)]})]}),m.length===0?e.jsx("div",{className:"text-xs text-muted-foreground py-2",children:"No events."}):e.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:m.map(([r,c])=>{const p=i?.[r]??0;return e.jsxs("div",{className:"flex items-center justify-between text-xs px-2 py-1 rounded border",children:[e.jsx("span",{className:"truncate",children:r}),e.jsxs("span",{className:"tabular-nums font-medium",children:[c,p>0&&e.jsxs("span",{className:"text-red-600 ml-1",children:["(",p,"!)"]})]})]},r)})})]})}function Fe({label:a,value:s,hint:i}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:a}),e.jsx("div",{className:"text-lg font-semibold tabular-nums",children:s}),i&&e.jsx("div",{className:"text-[11px] text-muted-foreground",children:i})]})}function ut({brandId:a}){const{isAdmin:s}
2=V(),i=K(),d=C(Ws),m=C(te),r=C(Ys),c=C(Js),p=C(Zs),t=L({queryKey:["sms-config",a],queryFn:()=>d({data:{brandId:a}}),enabled:!!a}),x=L({queryKey:["sms-logs",a],queryFn:()=>p({data:{brandId:a,limit:30}}),enabled:!!a}),[j,u]=f.useState(Ae);f.useEffect(()=>{if(t.data){const{is_admin:h,...O}=t.data;u({...Ae,...O,templates:{...Ae.templates,...O.templates}})}},[t.data]);const l=M({mutationFn:()=>m({data:{key:ea(a),value:j}}),onSuccess:()=>{_.success("SMS settings save hoyeche"),i.invalidateQueries({queryKey:["sms-config",a]})},onError:h=>_.error(h.message)}),g=M({mutationFn:()=>r({data:{brandId:a}}),onSuccess:h=>_.success(h.balance!==null?`Balance: à§³${h.balance}`:`Response: ${h.raw}`),onError:h=>_.error(h.message)}),[n,v]=f.useState(""),[o,N]=f.useState(""),A=f.useMemo(()=>n.split(/[\s,;\n]+/).map(h=>h.trim()).filter(Boolean),[n]),R=Ze(o),X=M({mutationFn:()=>c({data:{brandId:a,numbers:A,message:o}}),onSuccess:h=>{h.ok?_.success(`${h.sent} ta number e SMS gelo`):_.error(h.message||"SMS pathano jayni"),h.invalid?.length&&_.warning(`Invalid: ${h.invalid.join(", ")}`),N(""),i.invalidateQueries({queryKey:["sms-logs",a]})},onError:h=>_.error(h.message)});if(t.isLoading)return e.jsx("div",{className:"space-y-3",children:Array.from({length:5}).map((h,O)=>e.jsx(J,{className:"h-12 w-full"},O))});const H=(h,O)=>u({...j,[h]:O});return e.jsxs("div",{className:"space-y-6 max-w-3xl",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"SMS (BulkSMSBD)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"bulksmsbd.net diye order 
2confirm, pre-order o custom SMS pathan."})]}),e.jsx(ye,{title:"API credentials",icon:e.jsx(vs,{className:"h-4 w-4"}),children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx(k,{className:"text-sm",children:"SMS enabled"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Off thakle kono automatic SMS jabe na."})]}),e.jsx(U,{checked:j.enabled,onCheckedChange:h=>H("enabled",h),disabled:!s})]}),e.jsx(Ne,{label:"API key",children:e.jsx(Be,{value:j.api_key,onChange:h=>H("api_key",h),isAdmin:s,placeholder:"bulksmsbd API key"})}),e.jsx(Ne,{label:"Sender ID (approved mask / number)",children:e.jsx(b,{value:j.sender_id,onChange:h=>H("sender_id",h.target.value),placeholder:"8809617XXXXXX",className:"font-mono text-xs",disabled:!s})}),e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsxs(w,{variant:"outline",size:"sm",onClick:()=>g.mutate(),disabled:g.isPending,children:[g.isPending?e.jsx(I,{className:"h-4 w-4 animate-spin"}):e.jsx(Ve,{className:"h-4 w-4"})," Check balance"]}),s&&e.jsxs(w,{size:"sm",onClick:()=>l.mutate(),disabled:l.isPending,children:[l.isPending?e.jsx(I,{className:"h-4 w-4 animate-spin"}):e.jsx($,{className:"h-4 w-4"})," Save"]})]})]})}),e.jsxs(ye,{title:"Templates & auto-send",icon:e.jsx(we,{className:"h-4 w-4"}),children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground mb-3",children:["Placeholder: ",sa.join(" ")]}),e.jsxs("div",{className:"space-y-4",children:[Object.keys(es).map(h=>{const O={order_confirm:"auto_order_confirm",preorder_placed:"auto_preorder_placed",preorder_ready:"auto_preorder_ready",preorder_confirmed:"auto_preorder_confirmed"}[h],P=j.templates[h]??"";return e.jsxs("div",{className:"rounded-md border p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(k,{className:"text-sm font-medium",children:es[h]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Auto"}),e.jsx(U,{checked:j[O],onCheckedChange:xe=>u({...j,[O]:xe}),disabled:!s})]})]}),e.jsx(Y,{value:P,onChange:xe=>u({...j,templates:{...j.templates,[h]:xe.target.value}}),rows:3,disabled:!s,className:"text-xs"}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[P.length," chars · ",Ze(P)," SMS"]})]},h)}),s&&e.jsx("div",{className:"flex justify-end",children:e.jsxs(w,{size:"sm",onClick:()=>l.mutate(),disabled:l.isPending,children:[e.jsx($,{className:"h-4 w-4"})," Save templates"]})})]})]}),e.jsx(ye,{title:"Custom SMS pathan",icon:e.jsx(we,{className:"h-4 w-4"}),children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ne,{label:"Number (comma / newline separated)",children:e.jsx(Y,{value:n,onChange:h=>v(h.target.value),rows:2,placeholder:"01712345678, 01898765432",className:"font-mono text-xs"})}),e.jsx(Ne,{label:"Message",children:e.jsx(Y,{value:o,onChange:h=>N(h.target.value),rows:3,placeholder:"Apnar message…"})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[A.length," number · ",o.length," chars · ",R," SMS/number"]}),e.jsxs(w,{size:"sm",onClick:()=>X.mutate(),disabled:X.isPending||A.length===0||!o.trim(),children:[X.isPending?e.jsx(I,{className:"h-4 w-4 animate-spin"}):e.jsx(we,{className:"h-4 w-4"})," Send"]})]})]})}),e.jsxs(ye,{title:"Recent SMS",icon:e.jsx(ta,{className:"h-4 w-4"}),children:[e.jsx("div",{className:"flex justify-end mb-2",children:e.jsxs(w,{variant:"ghost",size:"sm",onClick:()=>x.refetch(),children:[e.jsx(aa,{className:"h-3.5 w-3.5"})," Refresh"]})}),x.data&&x.data.length>0?e.jsx("div",{className:"divide-y rounded-md border",children:x.data.map(h=>e.jsxs("div",{className:"p-2.5 text-xs flex items-start gap-2",children:[e.jsx(W,{variant:h.status==="sent"?"secondary":"destructive",className:"shrink-0",children:h.status}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"font-mono",children:[h.phone," · ",h.template_key]}),e.jsx("div",{className:"text-muted-foreground truncate",children:h.message}),h.status!=="sent"&&h.provider_response&&e.jsx("div",{className:"text-destructive",children:h.provider_response})]}),e.jsx("div",{className:"shrink-0 text-muted-foreground",children:new Date(h.created_at).toLocaleStr
2ing()})]},h.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ekhono kono SMS pathano hoyni."})]})]})}function ye({title:a,icon:s,children:i}){return e.jsxs("section",{className:"rounded-xl border bg-card p-5",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-3",children:[s,a]}),i]})}function Ne({label:a,children:s}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(k,{className:"text-sm font-medium",children:a}),s]})}const cs=[{id:"business",label:"Business Profile",description:"Identity, contact, legal & defaults",icon:ca,perBrand:!0},{id:"brands",label:"Brands",description:"Add, edit, default brand",icon:_s,perBrand:!1},{id:"invoice",label:"Invoice & Orders",description:"Template, numbering, workflow",icon:os,perBrand:!0},{id:"courier",label:"Courier",description:"Pathao, Steadfast, status mapping",icon:na,perBrand:!0},{id:"finance",label:"Finance",description:"Accounting, FX, tax defaults",icon:Ve,perBrand:!0},{id:"notifications",label:"Notifications",description:"Alerts, daily summaries",icon:la,perBrand:!0},{id:"sms",label:"SMS (BulkSMSBD)",description:"Order, pre-order & custom SMS",icon:vs,perBrand:!0},{id:"integrations",label:"Integrations",description:"Meta, Gemini, webhooks",icon:ra,perBrand:!0},{id:"analytics",label:"Analytics & Tracking",description:"GA4, Clarity, Pixel, retention",icon:gs,perBrand:!0},{id:"tracking",label:"Meta Pixel & CAPI",description:"Per-brand Pixel, CAPI, UTM, status",icon:He,perBrand:!1},{id:"crm",label:"CRM Custom Fields",description:"Per-customer custom data fields",icon:ma,perBrand:!0,adminOnly:!0},{id:"data",label:"Data & System",description:"Exports, activity, info",icon:Xe,perBrand:!0},{id:"danger",label:"Danger Zone",description:"Destructive actions",icon:je,perBrand:!0,adminOnly:!0}];function Gn(){const{brands:a,activeBrand:s}=me(),{isAdmin:i}=V(),[d,m]=f.useState("business"),[r,c]=f.useState(()=>s?.id??a[0]?.id??"");f.useEffect(()=>{a.length!==0&&(!r||!a.some(x=>x.id===r))&&c(s?.id??a[0].id)},[a,s?.id,r]);const p=f.useMemo(()=>cs.filter(x=>!x.adminOnly||i),[i]),t=cs.find(x=>x.id===d);return e.jsxs("div",{className:"min-h-screen bg-muted/20",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsxs("div",{className:"px-4 md:px-6 py-4",children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:"Configure brands, finance, integrations and team."})]})}),e.jsxs("div",{className:"flex flex-col lg:flex-row gap-0 min-h-[calc(100vh-90px)]",children:[e.jsx("aside",{className:"lg:w-64 lg:shrink-0 border-r bg-card lg:min-h-[calc(100vh-90px)]",children:e.jsx("nav",{className:"p-2 space-y-0.5",children:p.map(x=>{const j=x.icon,u=x.id===d;return e.jsxs("button",{onClick:()=>m(x.id),className:ae("w-full flex items-start gap-3 px-3 py-2.5 rounded-md text-left transition-colors",u?"bg-primary/10 text-primary":"hover:bg-accent text-foreground/80"),children:[e.jsx(j,{className:ae("h-4 w-4 mt-0.5 shrink-0",x.id==="danger"&&"text-destructive")}
2),e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:ae("block text-sm font-medium",x.id==="danger"&&"text-destructive"),children:x.label}),e.jsx("span",{className:"block text-[11px] text-muted-foreground truncate",children:x.description})]})]},x.id)})})}),e.jsxs("main",{className:"flex-1 p-4 md:p-6 space-y-4 min-w-0",children:[t.perBrand&&a.length>1&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap rounded-lg border bg-card px-3 py-2 shadow-sm",children:[e.jsx(_s,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Editing brand:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map(x=>{const j=x.id===r;return e.jsx("button",{onClick:()=>c(x.id),className:ae("px-3 py-1 rounded-md text-xs font-semibold transition-colors",j?"bg-primary text-primary-foreground":"bg-background border hover:bg-accent"),children:x.name},x.id)})})]}),t.perBrand&&!r?e.jsx("div",{className:"rounded-xl border bg-card p-6 text-sm text-muted-foreground",children:"No brand available — create one in the Brands section."}):e.jsx(xt,{section:d,brandId:r})]})]})]})}function xt({section:a,brandId:s}){switch(a){case"business":return e.jsx(_a,{brandIdOverride:s},s);case"brands":return e.jsx(Aa,{});case"invoice":return e.jsx(Da,{brandId:s},s);case"courier":return e.jsx($a,{brandId:s},s);case"finance":return e.jsx(Ua,{brandId:s},s);case"notifications":return e.jsx(Ka,{brandId:s},s);case"sms":return e.jsx(ut,{brandId:s},s);case"integrations":return e.jsx(Xa,{brandId:s},s);case"analytics":return e.jsx(Ja,{brandId:s},s);case"tracking":return e.jsx(it,{});case"crm":return e.jsx(Ya,{brandId:s},s);case"data":return e.jsx(Ha,{brandId:s},s);case"danger":return e.jsx(Ga,{brandId:s},s);default:return null}}export{Gn as component};

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.