PageSourceSearch

https://calabash.app/assets/Suppliers-o8VJHosK.js

js calabash.app collected 2026-10-04 08:03:45 UTC 109,792 bytes, 12 lines download raw bytes

1import{k as Be,m as y,s as c,j as e,C as ue,g as me,d as ve,e as be,f as qe,G as Ys,H as Ws,I as Zs,B as f,J as Js,p as ws,X as ht,K as De,O as Ae,P as Oe,Q as Le,S as Pe,U as Me,a4 as _t,n as Qs,b as Ft,r as Rt,a8 as Tt,bK as It,L as Ts}from"./index-DyMEJKlS.js";import{k as j}from"./syncfusion-charts-DlApThQX.js";import{o as Xs,u as Et,f as Dt,g as At,Z as Is,h as Ot}from"./MainAppPortal-g60tf2rL.js";import{L as Lt}from"./ListFilterChips-B1ITcKop.js";import{p as Es,l as Ds,o as Pt,a as Mt,s as Vt,b as et,h as Kt,d as Bt}from"./enterprise-list-filters-C99lmHtK.js";import{u as _e}from"./useQuery-DhdMI9wy.js";import{u as $}from"./useMutation-BYUHNXk7.js";import{I as H}from"./input-rdMtSQPj.js";import{S as Re}from"./switch-2V3rVV1Z.js";import{L as M}from"./label-ClVmu0SU.js";import{T as gt,a as ft,b as Ns,c as J,d as jt,e as X}from"./table-CFMeC6MK.js";import{T as yt,a as vt,b as Te,c as Ie}from"./tabs-DZILhcmw.js";import{B as T}from"./badge-BtICRtyC.js";import{S as ss,a as ts,b as ns,c as is,d as ye}from"./select-D1rh0o2K.js";import{A as zt,a as Qt,b as $t,c as Ut,d as Ht,e as Gt,f as Yt,g as Wt}from"./alert-dialog-Dh71kj9_.js";import{p as Zt,i as Jt}from"./prefill-kyc-CstbPnqB.js";import{g as Xt}from"./isic-categories-DsnZEQFH.js";import{g as en,u as sn}from"./naics-categories-DWls4RQ0.js";import{T as as}from"./textarea-Ca_8wMoU.js";import{L as ge}from"./loader-circle-Cnqj8Yqk.js";import{F as Ne}from"./file-text-DqknZCbJ.js";import{B as Ee}from"./building-2-DjOoXQ9-.js";import{M as $s}from"./mail-zdOGTIi0.js";import{M as bt}from"./map-pin-CeLPfJds.js";import{C as tn}from"./clock-DmrDXC8z.js";import{C as As}from"./check-CgDD1As6.js";import{S as nn}from"./send-DmonHTDq.js";import{f as zs}from"./formatDistanceToNow-BoLvehOh.js";import{u as Ze,t as Je,C as an}from"./zod-b95m8XBl.js";import{A as wt,b as Nt,a as rn}from"./alert-52ui5p84.js";import{e as on,f as ln,h as Ct,i as st,j as dn,k as cn,g as un}from"./connect-compliance-assignment-Cyp4mtZv.js";import{S as St}from"./settings-DDUyMw7s.js";import{P as Xe}from"./plus-VuC2i9Rc.js";import{S as Cs}from"./square-pen-DWagjp49.js";import{T as Ss}from"./trash-2-B13y5ojF.js";import{S as tt}from"./save-DZG9Vvav.js";import{I as mn}from"./info-Tkicboe7.js";import{S as es}from"./shield-check-B9FDnLYj.js";import{C as pn}from"./calendar-clock-CA_4uZgm.js";import{S as fs}from"./separator-HhslObZx.js";import{F as Os}from"./form-section-CwklOX0u.js";import{P as xn}from"./progress-DRrumFGZ.js";import{g as Ls}from"./compliance-validity-BzYrBLNi.js";import{B as hn}from"./BusinessCategorySelector-DIIezgeR.js";import{o as qt,a as _n,s as ae,l as gn,e as fn}from"./types-BBV31Xxv.js";import{E as Us}from"./eye-B6bBOq2L.js";import{B as nt}from"./bell-D_J8n5py.js";import{C as Ps}from"./circle-alert-fdq2HJGJ.js";import{H as it}from"./hash-BMnqfDJP.js";import{L as at}from"./lock-BYH4eWQF.js";import{L as Ms}from"./lock-open-vuAZdfib.js";import{D as js}from"./download-D20ssjnr.js";import{C as jn}from"./calendar-BRKuT5ig.js";import{R as rt}from"./rotate-ccw-BG8RtJpS.js";import{C as yn}from"./circle-x-D-Zzu-k7.js";import{f as vn}from"./format-BNsIsik2.js";import{p as bn}from"./parseISO-nowx8ZgE.js";import{u as wn}from"./useUnifiedSuppliers-CwEve0E8.js";import{T as Nn}from"./table-filters-BRQWEUf4.js";import{T as Cn}from"./table-pagination-B2prC1uA.js";import{g as Vs,E as Sn,a as qn}from"./supplier-workspace-DvOXBlDV.js";import{S as kn,f as Fn,a as Rn,b as Tn,c as In,d as En}from"./sheet-DJDfW3yO.js";import{F as Dn,a as ee,b as se,c as te,d as ne,e as ie}from"./form-_NusB7TB.js";import{B as An}from"./bp-management.service-C6f8_Xjn.js";import{T as On}from"./tenant-supplier.service-BLdZCHmK.js";import{L as ys}from"./LocationCombobox-roWJOk0Z.js";import{u as Ln}from"./useEnterpriseCurrency-1pHPOBlf.js";import{g as Pn}from"./currencyMapping-1G6dNd9g.js";import{T as Mn}from"./truck-D3to_uA1.js";import{u as Vn}from"./useTreasury-SDWek2jD.js";import{T as vs}from"./supplier-performance.types-Cu58d-XD.js";import{C as Kn}from"./chevron-down-CBTgOjRy.js";import{U as kt}from"./users-CJVUTlgG.js";import{S as ot}from"./search-D8EpZ0fC.js";import{C as Ks}from"./credit-card-B9w_D6OO.js";import{P as Bn}from"./phone-DOznAFpx.js";import{G as zn}from"./globe-w0eJprUB.js";import{C as Qn}from"./clipboard-check-C4sle1af.js";import"./page-loading-skeleton-4D6bqyxN.js";import"./skeleton-SzYbfBe8.js";import"./supplier-portal-access-Cp-MEMEj.js";import"./external-link-MAu19lE7.js";import"./ReportIssueNavButton-MNOTQtM_.js";import"./invoke-with-timeout-DkZz97zy.js";import"./chevron-left-CY2vcSY_.js";import"./dropdown-menu-BrjSoHpK.js";import"./index-mv2OQ3rD.js";import"./index-vn5I50JC.js";import"./chevron-right-BMfLBvfF.js";import"./circle-C9kQjdj5.js";import"./index-Bxa1BARx.js";import"./package-B8JO3UKs.js";import"./file-search-DRon2YxQ.js";import"./gavel-Bv1luoG0.js";import"./shopping-cart-p9wTX4gk.js";import"./receipt-BviW3zR7.js";import"./useSessionTimeout-DnZmlsg6.js";import"./message-square-bCpHu4AC.js";import"./file-spreadsheet-DpuWicXj.js";import"./usePlatformGateways-Y5aj7N8C.js";import"./dollar-sign-DFcX39B_.js";import"./trending-up-CcTRyStr.js";import"./file-check-IKPtt_g4.js";import"./layers-67wq7vRj.js";
1import"./inputGuards-CXYpBdQu.js";import"./circle-check-big-DoZsDENA.js";import"./tag-DumzuIPt.js";import"./target-BT3eTOb5.js";import"./shield-DXEYH4S0.js";import"./index-CFv-gKgT.js";import"./command-Dhw9oFy6.js";import"./file-pen-line-CwjQAw1X.js";import"./scroll-area-D129GkEw.js";import"./index-BdQq_4o_.js";import"./check-check-BM5M83P9.js";import"./upload-guards-CdQL-gCK.js";import"./CurrencyCombobox-DKisj_cu.js";import"./popover-C4qOaIzR.js";import"./currencies-suByQj3c.js";import"./upload-BxLDh_tK.js";import"./menu-DjiFzD6u.js";import"./user-C5-a_H_o.js";import"./useVisitorLocation-BKQKnpE8.js";import"./pause-DWu-n91J.js";import"./coins--QNZBJPb.js";import"./sparkles-Bvj092ko.js";import"./circuit-breaker-Dph3tCSQ.js";import"./route-error-boundary-DNnC0hUN.js";import"./handshake-Ci-BtBzX.js";import"./EnterprisePortalGate-C_C-yV5y.js";import"./users-round-S9GP_F_B.js";import"./function-error-DXPgkFD2.js";import"./supplier-connect.routes-mB_4QLwf.js";import"./tenant-supplier.routes-BO7qIm-t.js";import"./useTenantSupplierAuth-ChtmHNw4.js";import"./index-DZuVH9fJ.js";import"./en-US-CulqtCeB.js";import"./endOfMonth-BUxpEBTO.js";import"./addDays-Bok_Rf8F.js";import"./addMonths-DDeD-NVq.js";import"./addYears-CNbB4t9q.js";import"./filter-FBj3Dlhd.js";import"./chevrons-right-CttYD1iN.js";import"./usePaymentTerms-C-v-Qbpj.js";import"./useTaxSettings-BW8sFDWi.js";import"./business-partner.service-Bu1E7H3w.js";import"./BankAccountsTab-ByACnVop.js";import"./pencil-DKrsDPSm.js";import"./useTenantSupplierMasterData-kDDi-jxK.js";import"./money-J8dQvlKN.js";import"./invoice-payment-status-BNeaGzOR.js";function $n(p){var O,m,S;const v=Be(),g=_e({queryKey:["incoming-supplier-requests",p],queryFn:async()=>{if(!p)return[];const{data:x,error:k}=await c.from("supplier_connection_requests").select("*").eq("tenant_company_id",p).order("created_at",{ascending:!1});if(k)throw k;if(!(x!=null&&x.length))return[];const R=[...new Set(x.map(I=>I.supplier_org_id))],{data:q}=await c.from("supplier_orgs").select("id, legal_name, trading_name, contact_email, industry_tags, country, address").in("id",R),r=x.filter(I=>I.onboarding_submission_id).map(I=>I.onboarding_submission_id);let C=[];if(r.length>0){const{data:I}=await c.from("supplier_onboarding_submissions").select("id, status, submitted_at").in("id",r);C=I||[]}const{data:V}=await c.from("supplier_buyer_links").select("id, supplier_org_id, buyer_company_id, status, tenant_supplier_id").eq("buyer_company_id",p).in("supplier_org_id",R);return x.map(I=>({...I,supplier_org:q==null?void 0:q.find(L=>L.id===I.supplier_org_id),onboarding_submission:I.onboarding_submission_id&&C.find(L=>L.id===I.onboarding_submission_id)||null,supplier_buyer_link:(V==null?void 0:V.find(L=>L.supplier_org_id===I.supplier_org_id))||null}))},enabled:!!p}),l=$({mutationFn:async x=>{const{data:k,error:R}=await c.from("supplier_connection_requests").select("supplier_org_id, tenant_company_id").eq("id",x).single();if(R||!k)throw new Error("Request not found");const{data:q}=await c.from("supplier_connection_requests").select("onboarding_required, onboarding_submission_id").eq("id",x).single();if(q!=null&&q.onboarding_required&&(q!=null&&q.onboarding_submission_id)){const{data:I}=await c.from("supplier_onboarding_submissions").select("status").eq("id",q.onboarding_submission_id).single();if(I&&I.status!=="approved")throw new Error("Please review and approve the onboarding form before approving this connection.")}const{error:r}=await c.from("supplier_connection_requests").update({status:"approved"}).eq("id",x);if(r)throw r;const{data:C,error:V}=await c.from("supplier_buyer_links").upsert({supplier_org_id:k.supplier_org_id,buyer_company_id:k.tenant_company_id,status:"approved",approved_at:new Date().toISOString()},{onConflict:"supplier_org_id,buyer_company_id"}).select("tenant_supplier_id").single();if(V)throw V;return await c.functions.invoke("connection-request-notifications",{body:{type:"connection_request_approved",connectionRequestId:x,supplierOrgId:k.supplier_org_id,tenantCompanyId:k.tenant_company_id,additionalData:{tenantSupplierId:C==null?void 0:C.tenant_supplier_id}}}),{tenantSupplierId:C==null?void 0:C.tenant_supplier_id}},onSuccess:()=>
1{v.invalidateQueries({queryKey:["incoming-supplier-requests"]}),y.success("Request approved",{description:"The supplier has been notified of the approval."})},onError:x=>{y.error("Failed to approve request",{description:x.message})}}),i=$({mutationFn:async({requestId:x,reason:k})=>{const{error:R}=await c.from("supplier_connection_requests").update({status:"rejected"}).eq("id",x);if(R)throw R;const{data:q}=await c.from("supplier_connection_requests").select("supplier_org_id, tenant_company_id").eq("id",x).single();q&&(await c.from("supplier_onboarding_submissions").update({status:"rejected",reviewed_at:new Date().toISOString()}).eq("connection_request_id",x).in("status",["draft","submitted","under_review","needs_revision"]),await c.functions.invoke("connection-request-notifications",{body:{type:"connection_request_rejected",connectionRequestId:x,supplierOrgId:q.supplier_org_id,tenantCompanyId:q.tenant_company_id,additionalData:{reason:k}}}))},onSuccess:()=>{v.invalidateQueries({queryKey:["incoming-supplier-requests"]}),y.success("Request rejected",{description:"The supplier has been notified."})},onError:x=>{y.error("Failed to reject request",{description:x.message})}}),D=$({mutationFn:async({requestId:x,templateId:k})=>{const{data:R,error:q}=await c.from("supplier_connection_requests").select("supplier_org_id, tenant_company_id").eq("id",x).single();if(q||!R)throw new Error("Request not found");const{data:r}=await c.from("supplier_orgs").select("*").eq("id",R.supplier_org_id).single(),{data:C}=await c.from("supplier_onboarding_fields").select("field_name").eq("template_id",k),V=C&&r?Zt(C,r):{},{data:I,error:L}=await c.from("supplier_onboarding_submissions").insert([{connection_request_id:x,supplier_org_id:R.supplier_org_id,tenant_company_id:R.tenant_company_id,template_id:k,status:"draft",submitted_data:V,metadata:{source:"network_supplier_self_initiated",compliance_evidence_mode:"connect_central"}}]).select().single();if(L)throw L;const{error:z}=await c.from("supplier_connection_requests").update({onboarding_required:!0,onboarding_submission_id:I.id}).eq("id",x);if(z)throw z;return await c.functions.invoke("connection-request-notifications",{body:{type:"onboarding_form_sent",connectionRequestId:x,supplierOrgId:R.supplier_org_id,tenantCompanyId:R.tenant_company_id}}),I},onSuccess:()=>{v.invalidateQueries({queryKey:["incoming-supplier-requests"]}),y.success("Onboarding form sent",{description:"The supplier has been notified to complete the onboarding form."})},onError:x=>{y.error("Failed to send onboarding form",{description:x.message})}}),E=$({mutationFn:async({submissionId:x,notes:k})=>{const{data:R,error:q}=await c.from("supplier_onboarding_submissions").select("connection_request_id, supplier_org_id, tenant_company_id, revision_count").eq("id",x).single();if(q||!R)throw new Error("Submission not found");const{error:r}=await c.from("supplier_onboarding_submissions").update({status:"needs_revision",review_notes:k,revision_count:(R.revision_count||0)+1}).eq("id",x);if(r)throw r;await c.functions.invoke("connection-request-notifications",{body:{type:"onboarding_revision_requested",connectionRequestId:R.connection_request_id,supplierOrgId:R.supplier_org_id,tenantCompanyId:R.tenant_company_id,additionalData:{notes:k}}})},onSuccess:()=>{v.invalidateQueries({queryKey:["incoming-supplier-requests"]}),y.success("Revision requested",{description:"The supplier has been notified to update their submission."})},onError:x=>{y.error("Failed to request revision",{description:x.message})}}),N=$({mutationFn:async x=>{const{data:k,error:R}=await c.from("supplier_connection_requests").select("supplier_org_id, tenant_company_id, onboarding_required").eq("id",x).single();if(R||!k)throw new Error("Request not found");const{error:q}=await c.functions.invoke("connection-request-notifications",{body:{type:"invitation_reminder",connectionRequestId:x,supplierOrgId:k.supplier_org_id,tenantCompanyId:k.tenant_company_id,additionalData:{isResend:!0,onboardingRequired:k.onboarding_required}}});if(q)throw q},onSuccess:()=>{y.success("Invitation resent",{description:"The supplier has been notified again."})},onError:x=>{y.error("Failed to resend invitation",{description:x.message})}}),b=((O=g.data)==null?void 0:O.filter(x=>x.status==="pending"))||[],A=((m=g.data)==null?void 0:m.filter(x=>x.status==="approved"))||[],U=((S=g.data)==null?void 0:S.filter(x=>x.status==="rejected"))||[];return{requests:g.data||[],pendingRequests:b,approvedRequests:A,rejectedRequests:U,isLoading:g.isLoading,approve:l.mutate,isApproving:l.isPending,reject:i.mutate,isRejecting:i.isPending,sendOnboarding:D.mutate,isSendingO
1nboarding:D.isPending,requestRevision:E.mutate,isRequestingRevision:E.isPending,resendInvitation:N.mutate,isResending:N.isPending}}function Un({companyId:p,onboardingTemplates:v=[],onReviewSubmission:g}){const{pendingRequests:l,approvedRequests:i,isLoading:D,approve:E,isApproving:N,reject:b,isRejecting:A,sendOnboarding:U,isSendingOnboarding:O,resendInvitation:m,isResending:S}=$n(p),[x,k]=j.useState(!1),[R,q]=j.useState(!1),[r,C]=j.useState(null),[V,I]=j.useState(""),[L,z]=j.useState(""),G=h=>{const Q=Xt().find(K=>K.code===h);if(Q)return`${h} - ${Q.name}`;const _=en().find(K=>K.code===h);return _?`${h} - ${_.name}`:h},fe=h=>{E(h)},we=h=>{C(h),I(""),k(!0)},le=()=>{r&&(b({requestId:r,reason:V}),k(!1),C(null))},pe=h=>{C(h),z(""),q(!0)},Z=()=>{r&&L&&(U({requestId:r,templateId:L}),q(!1),C(null))};return D?e.jsx(ue,{children:e.jsxs(me,{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ge,{className:"h-6 w-6 animate-spin mx-auto mb-2"}),"Loading requests..."]})}):l.length===0&&i.length===0?e.jsxs(ue,{children:[e.jsxs(ve,{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(Ne,{className:"h-5 w-5"}),"Incoming Supplier Requests"]}),e.jsx(qe,{children:"Connection requests from the supplier network"})]}),e.jsx(me,{children:e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ee,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No pending connection requests"}),e.jsx("p",{className:"text-sm mt-1",children:"Suppliers from the network can find and request to connect with you"})]})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ue,{children:[e.jsxs(ve,{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(Ne,{className:"h-5 w-5"}),"Incoming Supplier Requests",l.length>0&&e.jsxs(T,{variant:"secondary",className:"ml-2",children:[l.length," pending"]})]}),e.jsx(qe,{children:"Review and respond to connection requests from suppliers"})]}),e.jsx(me,{children:e.jsxs("div",{className:"space-y-6",children:[l.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground",children:"Pending Requests"}),l.map(h=>{var P,Q,W,_;return e.jsxs("div",{className:"border rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-muted flex items-center justify-center",children:e.jsx(Ee,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold",children:((P=h.supplier_org)==null?void 0:P.trading_name)||((Q=h.supplier_org)==null?void 0:Q.legal_name)||"Unknown Supplier"}),((W=h.supplier_org)==null?void 0:W.contact_email)&&e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx($s,{className:"h-3 w-3"}),h.supplier_org.contact_email]}),((_=h.supplier_org)==null?void 0:_.country)&&e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(bt,{className:"h-3 w-3"}),h.supplier_org.country]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(tn,{className:"h-3 w-3"}),zs(new Date(h.created_at),{addSuffix:!0})]})]}),h.message&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-3 text-sm",children:[e.jsx("p",{className:"text-muted-foreground text-xs mb-1",children:"Message:"}),h.message]}),h.categories&&h.categories.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:h.categories.map(K=>e.jsx(T,{variant:"outline",className:"text-xs",children:G(K)},K))}),(()=>{var Y,je;const K=h.onboarding_required&&((Y=h.onboarding_submission)==null?void 0:Y.status)!=="approved",t=(je=h.onboarding_submission)==null?void 0:je.status,F=!h.onboarding_submission_id||t==="draft"?"Waiting for supplier to complete and submit the onboarding form.":t==="needs_revision"?"Revision requested — supplier must resubmit before you can approve.":"Review and approve the onboarding submission (section below) before approving this connection.";return e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2",children:[K?e.jsx(Ys,{children:e.jsxs(Ws,{children:[e.jsx(Zs,{asChild:!0,children:e.jsx("span",{tabIndex:0,children:e.jsxs(f,{size:"sm",disabled:!0,"aria-disabled":!0,children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Approve"]})})}),e.jsx(Js,{children:F})]})}):e.jsxs(f,{size:"sm",onClick:()=>fe(h.id),disabled:N,children:[e.jsx(As,{className:"h-4 w-4 mr-1"}),"Approve"]}),v.length>0&&!h.onboarding_required&&e.jsxs(f,{size:"sm",variant:"outline",onClick:()=>pe(h.id),disabled:O,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Send Onboarding Form"]}),h.onboarding_required&&(()=>{if(!!h.onboarding_submission_id&&(t==="submitted"||t==="under_review")&&!!g)return e.jsxs(f,{size:"sm",variant:"outline",className:"text-amber-700 border-amber-300 hover:bg-amber-50 dark:hover:bg-amber-950",onClick:()=>g(h.onboarding_submission_id),children:[e.jsx(Ne,{className:"h-4 w-4 mr-1"}),"Review Submission"]});
1const ze=!h.onboarding_submission_id||t==="draft"?"Awaiting Onboarding":t==="needs_revision"?"Revision Requested":"Awaiting Onboarding";return e.jsx(T,{variant:"outline",className:"text-amber-600 border-amber-200",children:ze})})(),e.jsx(Ys,{children:e.jsxs(Ws,{children:[e.jsx(Zs,{asChild:!0,children:e.jsxs(f,{size:"sm",variant:"outline",onClick:()=>m(h.id),disabled:S,children:[e.jsx(ws,{className:`h-4 w-4 mr-1 ${S?"animate-spin":""}`}),"Resend"]})}),e.jsx(Js,{children:e.jsx("p",{children:"Resend invitation notification to supplier"})})]})}),e.jsxs(f,{size:"sm",variant:"ghost",onClick:()=>we(h.id),disabled:A,children:[e.jsx(ht,{className:"h-4 w-4 mr-1"}),"Reject"]})]})})()]},h.id)})]}),i.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-medium text-muted-foreground",children:"Recently Approved"}),i.slice(0,5).map(h=>{var P,Q,W,_;return e.jsx("div",{className:"border rounded-lg p-4 bg-green-50/50 dark:bg-green-950/10",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-green-100 dark:bg-green-900/20 flex items-center justify-center",children:e.jsx(As,{className:"h-5 w-5 text-green-600"})}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-semibold flex items-center gap-2",children:[((P=h.supplier_org)==null?void 0:P.trading_name)||((Q=h.supplier_org)==null?void 0:Q.legal_name)||"Unknown Supplier",((W=h.supplier_buyer_link)==null?void 0:W.tenant_supplier_id)&&e.jsx(T,{variant:"secondary",className:"font-mono text-xs",children:h.supplier_buyer_link.tenant_supplier_id})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(_=h.supplier_org)==null?void 0:_.country})]})]}),e.jsx(T,{variant:"outline",className:"text-green-600 border-green-200",children:"Approved"})]})},h.id)})]})]})})]}),e.jsx(De,{open:x,onOpenChange:k,children:e.jsxs(Ae,{className:"bg-background",children:[e.jsxs(Oe,{children:[e.jsx(Le,{children:"Reject Connection Request"}),e.jsx(Pe,{children:"Optionally provide a reason for rejecting this request. The supplier will be notified."})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{htmlFor:"reject-reason",children:"Reason (optional)"}),e.jsx(as,{id:"reject-reason",placeholder:"Enter reason for rejection...",value:V,onChange:h=>I(h.target.value),rows:3})]})}),e.jsxs(Me,{children:[e.jsx(f,{variant:"outline",onClick:()=>k(!1),children:"Cancel"}),e.jsx(f,{variant:"destructive",onClick:le,disabled:A,children:"Reject Request"})]})]})}),e.jsx(De,{open:R,onOpenChange:q,children:e.jsxs(Ae,{className:"bg-background",children:[e.jsxs(Oe,{children:[e.jsx(Le,{children:"Send Onboarding Form"}),e.jsx(Pe,{children:"Select an onboarding form template to send to the supplier."})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{htmlFor:"template",children:"Onboarding Template"}),e.jsxs(ss,{value:L,onValueChange:z,children:[e.jsx(ts,{id:"template",children:e.jsx(ns,{placeholder:"Select a template"})}),e.jsx(is,{children:v.map(h=>e.jsx(ye,{value:h.id,children:h.name},h.id))})]})]})}),e.jsxs(Me,{children:[e.jsx(f,{variant:"outline",onClick:()=>q(!1),children:"Cancel"}),e.jsx(f,{onClick:Z,disabled:!L||O,children:"Send Form"})]})]})})]})}const lt=[{value:"text",label:"Text"},{value:"textarea",label:"Long Text"},{value:"email",label:"Email"},{value:"phone",label:"Phone"},{value:"url",label:"URL"},{value:"number",label:"Number"},{value:"date",label:"Date"},{value:"select",label:"Dropdown"},{value:"multiselect",label:"Multi-Select"},{value:"checkbox",label:"Checkbox"},{value:"checkbox_group",label:"Checkbox Group"},{value:"radio",label:"Radio (Yes/No)"},{value:"file",label:"File Upload"},{value:"section_header",label:"Section Header"}],Hn=Ct.pick({completion_term_days:!0});function dt(p=0){return{id:"",field_type:"text",field_name:"",field_label:"",placeholder:"",help_text:"",is_required:!1,is_compliance:!1,is_time_bound:!1,validity_term_value:null,validity_term_unit:null,options:[],section:"General",display_order:p}}function Gn({companyId:p,userId:v}){var _,K;const g=Be(),[l,i]=j.useState(!1),[D,E]=j.useState(!1),[N,b]=j.useState(null),[A,U]=j.useState(""),O=Ze({resolver:Je(Ct),defaultValues:{name:"",description:"",is_default:!1,completion_term_days:30}}),m=Ze({resolver:Je(ln),defaultValues:dt()}),S=m.watch(),x=Ze({resolver:Je(Hn),defaultValues:{completion_term_days:30}}),{data:k=[],isLoading:R}=_e({queryKey:["onboarding-templates",p],queryFn:async()=>{const{data:t,error:F}=await c.from("supplier_onboarding_templates").select("*").eq("company_id",p).order("created_at",{ascending:!1});if(F)throw F;return t},enabled:!!p}),{data:q=[],isLoading:r}=_e({queryKey:["onboarding-template-fields",N],queryFn:async()=>
1{if(!N)return[];const{data:t,error:F}=await c.from("supplier_onboarding_fields").select("*").eq("template_id",N).order("display_order");if(F)throw F;return t||[]},enabled:!!N}),C=$({mutationFn:async t=>{const{error:F}=await c.from("supplier_onboarding_templates").insert({company_id:p,created_by:v,name:t.name,description:t.description,is_default:t.is_default,completion_term_days:t.completion_term_days,is_active:!0});if(F)throw F},onSuccess:()=>{g.invalidateQueries({queryKey:["onboarding-templates"]}),y.success("Template created successfully"),i(!1),O.reset()},onError:t=>{const F=t.message.includes("idx_one_default_template_per_company")||t.message.toLowerCase().includes("duplicate key");y.error(F?"Could not switch the default template. Please retry.":"Failed to create template: "+t.message)}}),V=$({mutationFn:async t=>{const F={template_id:N,field_type:t.field_type,field_name:t.field_name||on(t.field_label),field_label:t.field_label,placeholder:t.placeholder||null,help_text:t.help_text||null,is_required:t.is_required,is_compliance:t.field_type==="file"&&t.is_compliance,is_time_bound:t.field_type==="file"&&t.is_compliance&&t.is_time_bound,val
1idity_term_value:t.field_type==="file"&&t.is_time_bound?t.validity_term_value:null,validity_term_unit:t.field_type==="file"&&t.is_time_bound?t.validity_term_unit:null,options:t.options.length>0?t.options:null,section:t.section||"General",display_order:t.display_order};if(t.id){const{error:Y}=await c.from("supplier_onboarding_fields").update(F).eq("id",t.id);if(Y)throw Y}else{const{error:Y}=await c.from("supplier_onboarding_fields").insert(F);if(Y)throw Y}},onSuccess:()=>{g.invalidateQueries({queryKey:["onboarding-template-fields"]}),y.success("Field saved successfully"),E(!1),G()},onError:t=>{y.error("Failed to save field: "+t.message)}}),I=$({mutationFn:async t=>{if(!N)throw new Error("Template is not selected");const{error:F}=await c.from("supplier_onboarding_templates").update({completion_term_days:t.completion_term_days}).eq("id",N).eq("company_id",p);if(F)throw F},onSuccess:()=>{g.invalidateQueries({queryKey:["onboarding-templates"]}),y.success("Completion period updated")},onError:t=>y.error(t.message)}),L=$({mutationFn:async t=>{const{error:F}=await c.from("supplier_onboarding_fields").delete().eq("id",t);if(F)throw F},onSuccess:()=>{g.invalidateQueries({queryKey:["onboarding-template-fields"]}),y.success("Field deleted")},onError:t=>{y.error("Failed to delete field: "+t.message)}}),z=$({mutationFn:async t=>{await c.from("supplier_onboarding_fields").delete().eq("template_id",t);const{error:F}=await c.from("supplier_onboarding_templates").delete().eq("id",t);if(F)throw F},onSuccess:()=>{g.invalidateQueries({queryKey:["onboarding-templates"]}),y.success("Template deleted"),b(null)},onError:t=>{y.error("Failed to delete template: "+t.message)}}),G=()=>{U(""),m.reset(dt(q.length))},fe=t=>{U("");const F=Array.isArray(t.options)?t.options.map(Y=>typeof Y=="string"?Y:String(Y)):[];m.reset({id:t.id,field_type:t.field_type,field_name:t.field_name,field_label:t.field_label,placeholder:t.placeholder||"",help_text:t.help_text||"",is_required:t.is_required,is_compliance:t.is_compliance,is_time_bound:t.is_time_bound,val
1idity_term_value:t.validity_term_value,validity_term_unit:t.validity_term_unit,options:F,section:t.section||"General",display_order:t.display_order}),E(!0)},we=()=>{G(),E(!0)},le=()=>{const t=A.trim();if(t){if(S.options.some(F=>F.toLocaleLowerCase()===t.toLocaleLowerCase())){m.setError("options",{message:"That option has already been added"});return}m.setValue("options",[...S.options,t],{shouldDirty:!0,shouldValidate:!0}),m.clearErrors("options"),U("")}},pe=t=>{m.setValue("options",S.options.filter(F=>F!==t),{shouldDirty:!0,shouldValidate:!0})},Z=t=>{x.reset({completion_term_days:t.completion_term_days??30}),b(t.id)},h=m.handleSubmit(t=>{V.mutate({...t,is_required:t.field_type==="section_header"?!1:t.is_required,is_compliance:t.field_type==="file"&&t.is_compliance,is_time_bound:t.field_type==="file"&&t.is_compliance&&t.is_time_bound,validity_term_value:t.field_type==="file"&&t.is_time_bound?t.validity_term_value:null,validity_term_unit:t.field_type==="file"&&t.is_time_bound?t.validity_term_unit:null})}),P=O.handleSubmit(t=>{C.mutate(t)}),Q=x.handleSubmit(t=>{I.mutate(t)});if(R)return e.jsx(ue,{children:e.jsx(me,{className:"py-8 text-center",children:e.jsx(ge,{className:"h-6 w-6 animate-spin mx-auto"})})});if(!N)return e.jsxs(e.Fragment,{children:[e.jsxs(ue,{children:[e.jsx(ve,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(St,{className:"h-5 w-5"}),"Onboarding Form Templates"]}),e.jsx(qe,{children:"Create custom forms for suppliers to complete during onboarding"})]}),e.jsxs(f,{onClick:()=>i(!0),children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),"Create Template"]})]})}),e.jsx(me,{children:k.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ne,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No onboarding templates yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Create your first template to collect information from suppliers"})]}):e.jsx("div",{className:"space-y-3",children:k.map(t=>e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-medium",children:t.name}),t.is_default&&e.jsx(T,{variant:"secondary",children:"Default"}),!t.is_active&&e.jsx(T,{variant:"outline",children:"Inactive"})]}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:t.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Completion period: ",t.completion_term_days??30," days"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(f,{variant:"outline",size:"sm",onClick:()=>Z(t),children:[e.jsx(Cs,{className:"h-4 w-4 mr-1"}),"Edit Fields"]}),e.jsx(f,{variant:"ghost",size:"sm",onClick:()=>z.mutate(t.id),children:e.jsx(Ss,{className:"h-4 w-4 text-destructive"})})]})]},t.id))})})]}),e.jsx(De,{open:l,onOpenChange:i,children:e.jsxs(Ae,{className:"bg-background",children:[e.jsxs(Oe,{children:[e.jsx(Le,{children:"Create Onboarding Template"}),e.jsx(Pe,{children:"Define a new form template for supplier onboarding"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{htmlFor:"template-name",children:"Template Name"}),e.jsx(H,{id:"template-name",placeholder:"e.g., Standard Vendor Onboarding",...O.register("name")}),O.formState.errors.name&&e.jsx("p",{className:"text-sm text-destructive",children:O.formState.errors.name.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{htmlFor:"template-description",children:"Description"}),e.jsx(as,{id:"template-description",placeholder:"Brief description of this template...",...O.register("description"),rows:2})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Re,{id:"template-default",checked:O.watch("is_default"),onCheckedChange:t=>O.setValue("is_default",t)}),e.jsx(M,{htmlFor:"template-default",children:"Set as default template"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{htmlFor:"template-completion-term",children:"Supplier completion period (days)"}),e.jsx(H,{id:"template-completion-term",type:"number",min:1,max:365,...O.register("completion_term_days",{valueAsNumber:!0})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Existing suppliers keep access while this buyer-specific completion CTA is active."})]})]}),e.jsxs(Me,{children:[e.jsx(f,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(f,{onClick:P,disabled:C.isPending,children:"Create Template"})]})]})})]});const W=k.find(t=>
1t.id===N);return e.jsxs(e.Fragment,{children:[e.jsxs(ue,{children:[e.jsx(ve,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(f,{variant:"ghost",size:"sm",onClick:()=>b(null),className:"mb-2",children:"← Back to Templates"}),e.jsxs(be,{children:["Editing: ",W==null?void 0:W.name]}),e.jsx(qe,{children:"Add and configure form fields for this template"})]}),e.jsxs(f,{onClick:we,children:[e.jsx(Xe,{className:"h-4 w-4 mr-2"}),"Add Field"]})]})}),e.jsxs(me,{children:[e.jsxs("div",{className:"mb-4 rounded-lg border p-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(M,{htmlFor:"completion-term-days",children:"Completion period"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Deadline shown to suppliers for this questionnaire and its required compliance evidence."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(H,{id:"completion-term-days",type:"number",min:1,max:365,className:"w-24",...x.register("completion_term_days",{valueAsNumber:!0})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"days"}),e.jsxs(f,{size:"sm",variant:"outline",onClick:Q,disabled:I.isPending,children:[e.jsx(tt,{className:"h-4 w-4 mr-1"}),"Save"]})]})]}),x.formState.errors.completion_term_days&&e.jsx("p",{className:"mt-2 text-sm text-destructive",children:x.formState.errors.completion_term_days.message})]}),e.jsxs(wt,{className:"mb-4",children:[e.jsx(mn,{className:"h-4 w-4"}),e.jsxs(Nt,{children:[e.jsx("strong",{children:"Auto-populated Fields:"})," Legal Name, Trading Name, Country, Currency, Tax ID, Registration Number, Contact Email, Phone, Website, and Address are automatically filled from the supplier's profile. Custom fields you add here will be shown alongside the pre-filled information."]})]}),r?e.jsx("div",{className:"text-center py-8",children:e.jsx(ge,{className:"h-6 w-6 animate-spin mx-auto"})}):q.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground border-2 border-dashed rounded-lg",children:[e.jsx(Xs,{className:"h-8 w-8 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"No fields added yet"}),e.jsx("p",{className:"text-sm mt-1",children:'Click "Add Field" to start building your form'})]}):e.jsx("div",{className:"space-y-2",children:q.map(t=>{var F;return e.jsxs("div",{className:"flex items-center gap-3 border rounded-lg p-3",children:[e.jsx(Xs,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:t.field_label}),e.jsx(T,{variant:"outline",className:"text-xs",children:((F=lt.find(Y=>Y.value===t.field_type))==null?void 0:F.label)||t.field_type}),t.is_required&&e.jsx(T,{variant:"secondary",className:"text-xs",children:"Required"}),t.is_compliance&&e.jsxs(T,{variant:"outline",className:"text-xs",children:[e.jsx(es,{className:"h-3 w-3 mr-1"}),"Compliance"]}),t.is_time_bound&&e.jsxs(T,{variant:"outline",className:"text-xs",children:[e.jsx(pn,{className:"h-3 w-3 mr-1"}),"Time-bound"]}),Jt(t.field_name)&&e.jsx(T,{variant:"secondary",className:"text-xs bg-success/10 text-success",children:"Auto-filled"})]}),t.section&&t.section!=="General"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Section: ",t.section]}),t.validity_term_value&&t.validity_term_unit&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["End date calculated from start date + ",t.validity_term_value," ",t.validity_term_unit]})]}),e.jsx(f,{variant:"ghost",size:"sm",onClick:()=>fe(t),children:e.jsx(Cs,{className:"h-4 w-4"})}),e.jsx(f,{variant:"ghost",size:"sm",onClick:()=>L.mutate(t.id),children:e.jsx(Ss,{className:"h-4 w-4 text-destructive"})})]},t.id)})})]})]}),e.jsx(De,{open:D,onOpenChange:E,children:e.jsxs(Ae,{className:"bg-background max-w-lg",children:[e.jsxs(Oe,{children:[e.jsx(Le,{children:S.id?"Edit Field":"Add Field"}),e.jsx(Pe,{children:"Configure the field properties"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-y-auto",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{htmlFor:"field-type",children:"Field Type"}),e.jsxs(ss,{value:S.field_type,onValueChange:t=>m.setValue("field_type",t,{shouldValidate:!0}),children:[e.jsx(ts,{id:"field-type",children:e.jsx(ns,{})}),e.jsx(is,{children:lt.map(t=>e.jsx(ye,{value:t.value,children:t.label},t.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{htmlFor:"field-section",children:"Section"}),e.jsx(H,{id:"field-section",placeholder:"e.g., Company Info",value:S.section,onChange:t=>m.setValue("section",t.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{htmlFor:"field-label",children:"Field Label *"}),e.jsx(H,{id:"field-label",placeholder:"e.g., Company Registration Number",value:S.field_label,onChange:t=>m.setValue("field_label",t.target.value,{shouldValidate:!0})}),((_=m.formState.errors.field_label)==null?void 0:_.message)&&e.jsx("p",{className:"text-xs text-destructive",children:m.formState.errors.field_label.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{htmlFor:"field-
1placeholder",children:"Placeholder"}),e.jsx(H,{id:"field-placeholder",placeholder:"Placeholder text...",value:S.placeholder,onChange:t=>m.setValue("placeholder",t.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{htmlFor:"field-help",children:"Help Text"}),e.jsx(H,{id:"field-help",placeholder:"Additional instructions...",value:S.help_text,onChange:t=>m.setValue("help_text",t.target.value)})]}),(S.field_type==="select"||S.field_type==="multiselect"||S.field_type==="checkbox_group"||S.field_type==="radio")&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(M,{htmlFor:"field-option-input",children:"Options"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{id:"field-option-input",placeholder:"Enter an option",value:A,onChange:t=>U(t.target.value),onKeyDown:t=>{t.key==="Enter"&&(t.preventDefault(),le())}}),e.jsxs(f,{type:"button",variant:"outline",onClick:le,disabled:!A.trim(),children:[e.jsx(Xe,{className:"mr-2 h-4 w-4"}),"Add option"]})]}),S.options.length>0?e.jsx("div",{className:"flex flex-wrap gap-2 rounded-md border bg-muted/30 p-3",children:S.options.map(t=>e.jsxs(T,{variant:"secondary",className:"gap-1 pr-1",children:[e.jsx("span",{className:"max-w-[240px] truncate",children:t}),e.jsx("button",{type:"button",className:"rounded-full p-0.5 hover:bg-background/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>pe(t),"aria-label":`Remove ${t}`,children:e.jsx(ht,{className:"h-3 w-3"})})]},t))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add each choice separately. Press Enter or use Add option."}),((K=m.formState.errors.options)==null?void 0:K.message)&&e.jsx("p",{className:"text-xs text-destructive",children:m.formState.errors.options.message})]}),S.field_type!=="section_header"&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Re,{id:"field-required",checked:S.is_required,onCheckedChange:t=>m.setValue("is_required",t)}),e.jsx(M,{htmlFor:"field-required",children:"Required field"})]}),S.field_type==="file"&&e.jsxs("div",{className:"space-y-4 rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(M,{htmlFor:"field-compliance",children:"Compliance document"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Track this buyer-requested upload in the tenant supplier compliance workspace."})]}),e.jsx(Re,{id:"field-compliance",checked:S.is_compliance,onCheckedChange:t=>{m.setValue("is_compliance",t,{shouldValidate:!0}),t||(m.setValue("is_time_bound",!1),m.setValue("validity_term_value",null),m.setValue("validity_term_unit",null))}})]}),S.is_compliance&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(M,{htmlFor:"field-time-bound",children:"Time-bound and tracked"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Require a validity end date and send renewal reminders."})]}),e.jsx(Re,{id:"field-time-bound",checked:S.is_time_bound,onCheckedChange:t=>{m.setValue("is_time_bound",t,{shouldValidate:!0}),t||(m.setValue("validity_term_value",null),m.setValue("validity_term_unit",null))}})]}),S.is_time_bound&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{children:"Standard term (optional)"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(H,{"aria-label":"Standard validity term",type:"number",min:1,step:1,placeholder:"e.g., 12",value:S.validity_term_value??"",onChange:t=>{const F=t.target.valueAsNumber;m.setValue("validity_term_value",Number.isFinite(F)?F:null,{shouldValidate:!0})}}),e.jsxs(ss,{value:S.validity_term_unit??"",onValueChange:t=>m.setValue("validity_term_unit",t,{shouldValidate:!0}),children:[e.jsx(ts,{"aria-label":"Standard validity unit",children:e.jsx(ns,{placeholder:"Unit"})}),e.jsxs(is,{children:[e.jsx(ye,{value:"days",children:"Days"}),e.jsx(ye,{value:"months",children:"Months"}),e.jsx(ye,{value:"years",children:"Years"})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When set, the supplier enters a start date and the end date is calculated automatically. Leave blank to require start and end dates."})]})]})]})]}),e.jsxs(Me,{children:[e.jsx(f,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsxs(f,{onClick:h,disabled:V.isPending,children:[e.jsx(tt,{className:"h-4 w-4 mr-2"}),"Save Field"]})]})]})})]})}const Yn=qt({industryTags:_n(ae()).min(1,"Select at least one business category").max(5)});
1function Wn({applicationId:p,companyId:v,country:g}){const l=Be(),i=Ze({resolver:Je(Yn),defaultValues:{industryTags:[]}}),D=_e({queryKey:["tenant-supplier-applicant-category-review",v,p],queryFn:async()=>{const{data:N,error:b}=await c.functions.invoke("tenant-supplier-master-data",{body:{action:"load_application_for_buyer",company_id:v,application_id:p}});if(b)throw b;if(!(N!=null&&N.success))throw new Error((N==null?void 0:N.error)||"Could not load business categories");return N.applicant_profile}});j.useEffect(()=>{D.data&&i.reset({industryTags:D.data.industry_tags??[]})},[i,D.data]);const E=$({mutationFn:async N=>{const{data:b,error:A}=await c.functions.invoke("tenant-supplier-master-data",{body:{action:"save_application_for_buyer",company_id:v,application_id:p,master_data:{industry_tags:N.industryTags,industry_standard:sn(g)?"NAICS":"ISIC"}}});if(A)throw A;if(!(b!=null&&b.success))throw new Error((b==null?void 0:b.error)||"Could not save business categories")},onSuccess:async()=>{await l.invalidateQueries({queryKey:["tenant-supplier-applicant-category-review",v,p]}),await l.invalidateQueries({queryKey:["onboarding-submissions-review"]}),y.success("Business categories updated for approval")},onError:N=>y.error(_t(N))});return D.isError?e.jsx("p",{className:"text-sm text-destructive",children:"Business categories could not be loaded."}):e.jsxs("form",{className:"space-y-3",onSubmit:i.handleSubmit(N=>E.mutate(N)),children:[e.jsx(M,{children:"Business categories for approval"}),e.jsx(an,{control:i.control,name:"industryTags",render:({field:N})=>e.jsx(hn,{value:N.value,onChange:N.onChange,country:g})}),i.formState.errors.industryTags&&e.jsx("p",{className:"text-xs text-destructive",children:i.formState.errors.industryTags.message}),e.jsx(f,{type:"submit",variant:"outline",size:"sm",disabled:D.isLoading||E.isPending,children:"Save reviewed categories"})]})}const Bs=Qs("OnboardingSubmissionReview");function Zn(p){switch(p){case"approved":return"default";case"pending":return"secondary";case"rejected":case"expired":return"destructive";default:return"outline"}}function ct(p){return typeof p=="string"&&p.startsWith("enc::")}function Jn(p){if(!p)return 0;let v=0;for(const g of Object.values(p))g!=null&&(typeof g=="string"&&g.trim()===""||Array.isArray(g)&&g.length===0||(v+=1));return v}function Xn(p){switch(p){case"submitted":return{label:"Submitted",className:"bg-blue-100 text-blue-800 border-blue-200"};case"under_review":return{label:"Under Review",className:"bg-blue-100 text-blue-800 border-blue-200"};case"needs_revision":return{label:"Revision Requested",className:"bg-orange-100 text-orange-800 border-orange-200"};case"draft":return{label:"In Progress",className:"bg-amber-100 text-amber-800 border-amber-200"};case"approved":return{label:"Approved",className:"bg-success/10 text-success border-success/20"};default:return{label:p,className:"bg-slate-100 text-slate-700 border-slate-200"}}}const ut=j.forwardRef(function({companyId:v},g){var ps,Ge,Ye,xs,hs,_s,gs,Ke,We;const l=Be(),[i,D]=j.useState(null),[E,N]=j.useState(!1),[b,A]=j.useState(!1),[U,O]=j.useState(""),[m,S]=j.useState(!1),[x,k]=j.useState(""),[R,q]=j.useState(null),[r,C]=j.useState(null),[V,I]=j.useState(!1),L=(ps=i==null?void 0:i.metadata)==null?void 0:ps.supplier_bp_id,z=((Ge=i==null?void 0:i.metadata)==null?void 0:Ge.entity_type)==="tenant_supplier_applicant",G=st({supplierOrgId:i==null?void 0:i.supplier_org_id,source:(Ye=i==null?void 0:i.metadata)==null?void 0:Ye.source,complianceEvidenceMode:(xs=i==null?void 0:i.metadata)==null?void 0:xs.compliance_evidence_mode}),fe=dn({supplierOrgId:i==null?void 0:i.supplier_org_id,source:(hs=i==null?void 0:i.metadata)==null?void 0:hs.source,complianceOnly:(_s=i==null?void 0:i.metadata)==null?void 0:_s.compliance_only}),we=cn({supplierOrgId:i==null?void 0:i.supplier_org_id,complianceEvidenceMode:(gs=i==null?void 0:i.metadata)==null?void 0:gs.compliance_evidence_mode}),le=!!(fe||we),pe=!!(!G&&!le&&(L||z)),Z=!!(G||pe),{data:h=[],isLoading:P}=_e({queryKey:["onboarding-submissions-review",v],queryFn:async()=>{if(!v)return[];const{data:n,error:u}=await c.from("supplier_onboarding_submissions").select(`
2          id, status, submitted_at, review_notes, revision_count, submitted_data, created_at, metadata, supplier_org_id, applicant_profile,
3          supplier_orgs:supplier_org_id(legal_name, trading_name, contact_email),
4          supplier_onboarding_templates:template_id(name)
5        `).eq("tenant_company_id",v).in("status",["draft","submitted","under_review","needs_revision","approved"]).order("created_at",{ascending:!1});if(u)throw u;return await Promise.all((n||[]).map(async a=>{let o=a.supplier_orgs;const w=a.metadata;if(!o&&(w!=null&&w.supplier_bp_id)){const{data:B}=await c.from("business_partners").select("legal_name, trading_name").eq("id",w.supplier_bp_id).eq("company_id",v).single();B&&(o={legal_name:B.legal_name||"Unknown",trading_name:B.trading_name,contact_email:null})}const d=a.applicant_profile;return!o&&(w==null?void 0:w.entity_type)==="tenant_supplier_applicant"&&(o={legal_name:typeof(d==null?void 0:d.legal_name)=="str
5ing"?d.legal_name:"Registration in progress",trading_name:typeof(d==null?void 0:d.trading_name)=="string"?d.trading_name:null,contact_email:typeof(d==null?void 0:d.contact_email)=="string"?d.contact_email:null}),{...a,supplier_org:o,applicant_profile:d,metadata:w,template:a.supplier_onboarding_templates}}))},enabled:!!v}),{data:Q=[],isLoading:W}=_e({queryKey:["submission-template-fields",i==null?void 0:i.id],queryFn:async()=>{if(!i)return[];const{data:n}=await c.from("supplier_onboarding_submissions").select("template_id").eq("id",i.id).eq("tenant_company_id",v).single();if(!(n!=null&&n.template_id))return[];const{data:u,error:s}=await c.from("supplier_onboarding_fields").select("*").eq("template_id",n.template_id).order("display_order");if(s)throw s;return u||[]},enabled:!!i}),{data:_}=_e({queryKey:["supplier-review-profile",i==null?void 0:i.id],queryFn:async()=>{var u,s;if(!i)return null;if(((u=i.metadata)==null?void 0:u.entity_type)==="tenant_supplier_applicant"){const a=i.applicant_profile??{},o=a.bank_profile&&typeof a.bank_profile=="object"?a.bank_profile:null;return{legal_name:typeof a.legal_name=="string"?a.legal_name:"Registration in progress",trading_name:typeof a.trading_name=="string"?a.trading_name:null,contact_email:typeof a.contact_email=="string"?a.contact_email:null,country:typeof a.country=="string"?a.country:null,address_line1:typeof a.street=="string"?a.street:null,city:typeof a.city=="string"?a.city:null,state:typeof a.state=="string"?a.state:null,postal_code:typeof a.postal_code=="string"?a.postal_code:null,registration_no:typeof a.registration_no=="string"?a.registration_no:null,tax_id:typeof a.tax_id=="string"?a.tax_id:null,industry_tags:Array.isArray(a.industry_tags)?a.industry_tags:[],industry_standard:typeof a.industry_standard=="string"?a.industry_standard:null,bank_profile:o,source:"applicant"}}if(i.supplier_org_id){const{data:a}=await c.from("supplier_orgs").select("legal_name, trading_name, contact_email, country, address, registration_no, tax_id").eq("id",i.supplier_org_id).single();if(a){const o=a.address;return{legal_name:a.legal_name,trading_name:a.trading_name,contact_email:a.contact_email,country:a.country,address_line1:(o==null?void 0:o.street)||null,city:(o==null?void 0:o.city)||null,state:(o==null?void 0:o.state)||null,postal_code:(o==null?void 0:o.postal_code)||null,registration_no:a.registration_no,tax_id:a.tax_id,source:"supplier_org"}}}const n=(s=i.metadata)==null?void 0:s.supplier_bp_id;if(n){const{data:a}=await c.from("business_partners").select("legal_name, trading_name, tax_id, registration_no, country").eq("id",n).eq("company_id",v).single(),{data:o}=await c.from("bp_addresses").select("street, city, state, postal_code, country").eq("bp_id",n).eq("is_primary",!0).maybeSingle(),{data:w}=await c.from("bp_contacts").select("email").eq("bp_id",n).eq("is_primary",!0).maybeSingle();if(a)return{legal_name:a.legal_name||"Unknown",trading_name:a.trading_name,contact_email:(w==null?void 0:w.email)||null,country:a.country||(o==null?void 0:o.country)||null,address_line1:(o==null?void 0:o.street)||null,city:(o==null?void 0:o.city)||null,state:(o==null?void 0:o.state)||null,postal_code:(o==null?void 0:o.postal_code)||null,registration_no:a.registration_no||null,tax_id:a.tax_id||null,source:"business_partner"}}return null},enabled:!!i}),{data:K=[],isLoading:t}=_e({queryKey:["supplier-review-compliance",v,i==null?void 0:i.id,i==null?void 0:i.supplier_org_id,L,G,le],queryFn:async()=>{const n=pe?L:i==null?void 0:i.supplier_org_id;if(!n)return[];const u=pe?"supplier_bp_id":"supplier_org_id",{data:s,error:a}=await c.from("supplier_compliance_docs").select(`
6          id, doc_name, doc_type, status, file_url, issue_date, expiry_date,
7          issuing_body, term_value, term_unit, supersedes_document_id, superseded_at,
8          onboarding_field_id
9        `).eq(u,n).order("created_at",{ascending:!1});if(a)throw a;const o=s||[];if((G||le)&&(i!=null&&i.supplier_org_id)&&o.length>0&&v){let w=new Map;if(G){const{data:d,error:B}=await c.from("supplier_onboarding_document_assignments").select("id, compliance_doc_id").eq("submission_id",i.id).is("unassigned_at",null).in("compliance_doc_id",o.map(ce=>ce.id));if(B)throw B;const oe=d||[];if(oe.length===0)return o.map(ce=>({...ce,status:"pending"}));const{data:Fe,error:de}=await c.from("supplier_compliance_buyer_reviews").select("assignment_id, status").eq("buyer_company_id",v).in("assignment_id",oe.map(ce=>ce.id));if(de)throw de;const Se=new Map((Fe||[]).map(ce=>[ce.assignment_id,ce.status]));w=new Map(oe.flatMap(ce=>{const Gs=Se.get(ce.id);return Gs?[[ce.compliance_doc_id,Gs]]:[]}))}else{const{data:d,error:B}=await c.from("supplier_compliance_buyer_reviews").select("compliance_doc_id, status").eq("buyer_company_id",v).is("assignment_id",null).in("compliance_doc_id",o.map(oe=>oe.id));if(B)throw B;w=new Map((d||[]).map(oe=>[oe.compliance_doc_id,oe.status]))}return o.map(d=>({...d,status:["rejected","expired","superseded"].includes(d.status)?d.status:w.get(d.id)??"pending"}))}return o},enabled:!!i&&!!(i.supplier_org_id||L)}),{data:F=[],isLoading:Y}=_e({queryKey:["supplier-review-compliance-requirements",_==null?void 0:_.country],queryFn:async()=>
9{if(!(_!=null&&_.country))return[];const{data:n,error:u}=await c.from("compliance_requirements").select("id, requirement_name, document_types, is_required").or(`country.eq.${_.country},country.eq.ALL`).eq("is_required",!0).order("display_order");if(u)throw u;return n||[]},enabled:!Z&&!!(_!=null&&_.country)}),je=Q.filter(n=>n.field_type==="file"&&n.is_compliance).map(n=>({id:n.id,onboarding_field_id:n.id,requirement_name:n.field_label,document_types:[n.field_name],is_required:n.is_required??!1})),rs=z?Q.filter(n=>n.field_type==="file"&&n.is_compliance).flatMap(n=>{var o;const u=(o=i==null?void 0:i.submitted_data)==null?void 0:o[n.field_name],s=u&&typeof u=="object"?u:null,a=typeof u=="string"?u:typeof(s==null?void 0:s.file_path)=="string"?s.file_path:"";return a?[{id:`application-${n.id}`,doc_name:n.field_label,doc_type:n.field_name,status:"pending",file_url:a,issue_date:typeof(s==null?void 0:s.issue_date)=="string"?s.issue_date:null,expiry_date:typeof(s==null?void 0:s.expiry_date)=="string"?s.expiry_date:null,term_value:n.validity_term_value??null,term_unit:n.validity_term_unit??null,supersedes_document_id:null,
9superseded_at:null,issuing_body:null,onboarding_field_id:n.id}]:[]}):[],ze=Z?je:F,os=new Set(je.map(n=>n.onboarding_field_id)),qs=new Map(G?Q.flatMap(n=>{var s;const u=un((s=i==null?void 0:i.submitted_data)==null?void 0:s[n.field_name]);return u?[[u,n.id]]:[]}):[]),ke=z?rs:G?K.flatMap(n=>{const u=qs.get(n.id);return u?[{...n,onboarding_field_id:u}]:[]}):le?K:pe?K.filter(n=>n.onboarding_field_id&&os.has(n.onboarding_field_id)):K,ks=new Set(ke.filter(n=>n.status==="approved"&&Ls(n.expiry_date)!=="expired").map(n=>n.doc_type)),ls=new Set(ke.filter(n=>(n.status==="approved"||z)&&Ls(n.expiry_date)!=="expired").map(n=>n.onboarding_field_id)),Qe=ze.filter(n=>n.is_required&&(Z?!ls.has(n.onboarding_field_id):!n.document_types.some(u=>ks.has(u)))),ds=!!((Z||_!=null&&_.country)&&!t&&!(Z?W:Y)&&Qe.length===0),cs=$({mutationFn:async n=>{const{data:u,error:s}=await c.functions.invoke("review-compliance-doc",{body:{docId:n,action:"approve",submissionId:i==null?void 0:i.id}});if(s)throw s;return u},onSuccess:()=>{l.invalidateQueries({queryKey:["supplier-review-compliance"]}),y.success("Compliance document approved")},onError:n=>{y.error("Failed to approve document: "+n.message)}}),xe=$({mutationFn:async n=>{const{data:u,error:s}=await c.functions.invoke("onboarding-workflow",{body:{action:"check_workflow",submissionId:n}});if(s)throw s;return u},onSuccess:n=>{q(n.requiresApproval)},onError:n=>{Bs.error("Failed to check workflow:",n),q(!1)}}),$e=$({mutationFn:async n=>{const{data:u,error:s}=await c.functions.invoke("onboarding-workflow",{body:{action:"approve",submissionId:n}});if(s)throw s;return u},onSuccess:()=>{l.invalidateQueries({queryKey:["onboarding-submissions-review"]}),l.invalidateQueries({queryKey:["unified-suppliers"]}),l.invalidateQueries({queryKey:["incoming-supplier-requests"]}),y.success("Supplier certified and approved"),N(!1),D(null),q(null),C(null)},onError:n=>{y.error("Failed to approve: "+n.message)}}),Ue=$({mutationFn:async({submissionId:n,reason:u})=>{const{data:s,error:a}=await c.functions.invoke("onboarding-workflow",{body:{action:"reject",submissionId:n,reason:u}});if(a)throw a;if(!(s!=null&&s.success))throw new Error((s==null?void 0:s.error)||"Could not reject supplier application")},onSuccess:()=>{l.invalidateQueries({queryKey:["onboarding-submissions-review"]}),l.invalidateQueries({queryKey:["incoming-supplier-requests"]}),y.success("Supplier application rejected"),S(!1),N(!1),D(null),k("")},onError:n=>y.error("Failed to reject: "+n.message)}),he=$({mutationFn:async n=>{const{data:u}=await c.from("supplier_onboarding_submissions").select("connection_request_id, supplier_org_id, tenant_company_id, status").eq("id",n).eq("tenant_company_id",v).single();if(!u)throw new Error("Submission not found");if(u.status!=="draft"&&u.status!=="needs_revision")throw new Error("Only draft / needs-revision submissions can be nudged");const{error:s}=await c.functions.invoke("connection-request-notifications",{body:{type:"onboarding_form_sent",connectionRequestId:u.connection_request_id,supplierOrgId:u.supplier_org_id,tenantCompanyId:u.tenant_company_id}});if(s)throw s},onSuccess:()=>{y.success("Reminder sent to supplier")},onError:n=>{y.error("Failed to nudge supplier: "+n.message)}}),Ce=$({mutationFn:async({submissionId:n,notes:u})=>{var w,d,B;const{data:s}=await c.from("supplier_onboarding_submissions").select("connection_request_id, supplier_org_id, tenant_company_id, revision_count, status, metadata").eq("id",n).eq("tenant_company_id",v).single();if(!s)throw new Error("Submission not found");const a=s.status==="approved"&&st({supplierOrgId:s.supplier_org_id,supplierBpId:(w=s.metadata)==null?void 0:w.supplier_bp_id,source:(d=s.metadata)==null?void 0:d.source,complianceEvidenceMode:(B=s.metadata)==null?void 0:B.compliance_evidence_mode});if(s.status==="approved"&&!a)throw new Error("Approved tenant and legacy submissions cannot enter Connect document renewal");const{error:o}=a?await c.rpc("request_connect_onboarding_document_renewal",{p_submission_id:n,p_notes:u}):await c.from("supplier_onboarding_submissions").update({status:"needs_revision",review_notes:u,revision_count:((s==null?void 0:s.revision_count)||0)+1}).eq("id",n).eq("tenant_company_id",v);if(o)throw o;s&&await c.functions.invoke("connection-request-notifications",{body:{type:"onboarding_revision_requested",connectionRequestId:s.connection_request_id,supplierOrgId:s.supplier_org_id,tenantCompanyId:s.tenant_company_id,additionalData:{notes:u}}})},onSuccess:()=>
9{l.invalidateQueries({queryKey:["onboarding-submissions-review"]}),l.invalidateQueries({queryKey:["incoming-supplier-requests"]}),y.success("Revision requested"),A(!1),N(!1),D(null),O(""),q(null),C(null)},onError:n=>{y.error("Failed to request revision: "+n.message)}}),re=n=>{D(n),N(!0),q(null),C(null),xe.mutate(n.id)};j.useImperativeHandle(g,()=>({openSubmissionById:async n=>{const u=h.find(w=>w.id===n);if(u){re(u);return}const{data:s,error:a}=await c.from("supplier_onboarding_submissions").select(`id, status, submitted_at, review_notes, revision_count,
10             submitted_data, created_at, supplier_org_id, metadata, applicant_profile,
11             supplier_orgs:supplier_org_id(legal_name, trading_name, contact_email),
12             supplier_onboarding_templates:template_id(name)`).eq("id",n).eq("tenant_company_id",v).maybeSingle();if(a||!s){y.error("Unable to open this submission"),Bs.error("openSubmissionById fetch failed",a??"no row");return}const o={id:s.id,status:s.status,submitted_at:s.submitted_at,review_notes:s.review_notes,revision_count:s.revision_count,submitted_data:s.submitted_data??{},created_at:s.created_at,supplier_org_id:s.supplier_org_id,metadata:s.metadata??null,applicant_profile:s.applicant_profile??null,supplier_org:s.supplier_orgs??null,template:s.supplier_onboarding_templates??null};re(o)}}),[h]);const He=()=>{A(!0)},us=async()=>{if(i){I(!0);try{const{data:n,error:u}=await c.functions.invoke("decrypt-onboarding-data",{body:{submissionId:i.id}});if(u)throw u;n!=null&&n.submitted_data&&(C(n.submitted_data),y.success("Sensitive fields decrypted"))}catch(n){y.error("Failed to decrypt data"),Bs.error("Failed to decrypt data:",n)}finally{I(!1)}}},Ve=async(n,u)=>{try{const{data:s,error:a}=await c.storage.from("supplier-documents").createSignedUrl(n,3600);if(a)throw a;window.open(s.signedUrl,"_blank")}catch{y.error(`Failed to open ${u}`)}},Fs=r||(i==null?void 0:i.submitted_data)||{},ms=typeof((Ke=i==null?void 0:i.submitted_data)==null?void 0:Ke.contact_email)=="string"?i.submitted_data.contact_email:null,Hs=i!=null&&i.submitted_data?Object.values(i.submitted_data).some(ct):!1,Rs=Q.reduce((n,u)=>{const s=u.section||"General Information",a=n.find(o=>o.section===s);return a?a.fields.push(u):n.push({section:s,fields:[u]}),n},[]);return P?e.jsx(ue,{children:e.jsx(me,{className:"py-8 text-center",children:e.jsx(ge,{className:"h-6 w-6 animate-spin mx-auto"})})}):h.length===0?e.jsxs(ue,{children:[e.jsxs(ve,{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(Ne,{className:"h-5 w-5"}),"Onboarding Submissions"]}),e.jsx(qe,{children:"Review submitted onboarding forms from suppliers"})]}),e.jsx(me,{children:e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ne,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}
12),e.jsx("p",{children:"No submissions pending review"})]})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ue,{children:[e.jsxs(ve,{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(Ne,{className:"h-5 w-5"}),"Onboarding Submissions",e.jsx(T,{variant:"secondary",children:h.length})]}),e.jsx(qe,{children:"Review submitted onboarding forms from suppliers"})]}),e.jsx(me,{children:e.jsxs(gt,{children:[e.jsx(ft,{children:e.jsxs(Ns,{children:[e.jsx(J,{children:"Supplier"}),e.jsx(J,{children:"Template"}),e.jsx(J,{children:"Status"}),e.jsx(J,{children:"Progress"}),e.jsx(J,{children:"Updated"}),e.jsx(J,{children:"Revisions"}),e.jsx(J,{className:"text-right",children:"Actions"})]})}),e.jsx(jt,{children:h.map(n=>{var B,oe,Fe,de,Se,ce;const u=Xn(n.status),s=n.status==="draft"||n.status==="needs_revision",a=n.status==="submitted"||n.status==="under_review",o=n.status==="approved",w=typeof((B=n.submitted_data)==null?void 0:B.contact_email)=="string"?n.submitted_data.contact_email:null,d=Jn(n.submitted_data);return e.jsxs(Ns,{children:[e.jsx(X,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((oe=n.supplier_org)==null?void 0:oe.trading_name)||((Fe=n.supplier_org)==null?void 0:Fe.legal_name)||"Unknown"}),(w||((de=n.supplier_org)==null?void 0:de.contact_email))&&e.jsx("p",{className:"text-xs text-muted-foreground",children:w||((Se=n.supplier_org)==null?void 0:Se.contact_email)})]})]})}),e.jsx(X,{children:((ce=n.template)==null?void 0:ce.name)||"-"}),e.jsx(X,{children:e.jsx(T,{variant:"outline",className:`${u.className} text-xs`,children:u.label})}),e.jsx(X,{children:s?e.jsx("span",{className:"text-xs text-muted-foreground",children:d===0?"Not started":`${d} field${d===1?"":"s"} saved`}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Complete"})}),e.jsx(X,{children:n.submitted_at?zs(new Date(n.submitted_at),{addSuffix:!0}):n.created_at?zs(new Date(n.created_at),{addSuffix:!0}):"-"}),e.jsx(X,{children:n.revision_count>0?e.jsx(T,{variant:"outline",children:n.revision_count}):"-"}),e.jsx(X,{className:"text-right",children:a||o?e.jsxs(f,{size:"sm",onClick:()=>re(n),children:[e.jsx(Us,{className:"h-4 w-4 mr-1"}),o?"View compliance":"Review"]}):e.jsxs(f,{size:"sm",variant:"outline",onClick:()=>he.mutate(n.id),disabled:he.isPending&&he.variables===n.id,children:[he.isPending&&he.variables===n.id?e.jsx(ge,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(nt,{className:"h-4 w-4 mr-1"}),"Nudge"]})})]},n.id)})})]})})]}),e.jsx(De,{open:E,onOpenChange:n=>{N(n),n||(C(null),D(null))},children:e.jsxs(Ae,{className:"bg-background max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Oe,{children:[e.jsxs(Le,{className:"flex items-center gap-2",children:[e.jsx(es,{className:"h-5 w-5 text-primary"}),"Supplier Certification Review"]}),e.jsx(Pe,{children:"Review supplier KYC details, compliance documents, and submitted data before certification."})]}),i&&(i.status==="draft"||i.status==="needs_revision")&&e.jsxs("div",{className:"p-3 rounded-md flex items-start gap-2 bg-amber-50 text-amber-800 dark:bg-amber-950 dark:text-amber-200",children:[e.jsx(Ps,{className:"h-4 w-4 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-sm flex-1",children:[e.jsx("p",{className:"font-medium mb-1",children:i.status==="draft"?"Supplier has not submitted yet":"Supplier is revising the submission"}),e.jsx("p",{className:"text-xs opacity-90 mb-2",children:"You can view the supplier's progress below but cannot certify until they submit."}),Q.length>0&&(()=>{const n=Q.filter(o=>o.field_type!=="section_header"&&o.is_required),u=n.filter(o=>{var d;const w=(d=i.submitted_data)==null?void 0:d[o.field_name];return!(w==null||typeof w=="string"&&w.trim()===""||Array.isArray(w)&&w.length===0)}).length,s=n.length,a=s===0?0:Math.round(u/s*100);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsxs("span",{children:[u," of ",s," required fields completed"]}),e.jsxs("span",{children:[a,"%"]})]}),e.jsx(xn,{value:a,className:"h-1.5"})]})})()]})]}),R!==null&&e.jsxs("div",{className:`p-3 rounded-md flex items-center gap-2 ${R?"bg-amber-50 text-amber-800 dark:bg-amber-950 dar
12k:text-amber-200":"bg-blue-50 text-blue-800 dark:bg-blue-950 dark:text-blue-200"}`,children:[e.jsx(Ps,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"text-sm",children:R?"Workflow approval is configured. Your certification will finalize this submission.":"Direct certification enabled. No additional workflow steps required."})]}),e.jsx(Os,{title:"Supplier Profile",children:_?e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Legal Name"}),e.jsx("p",{className:"font-medium",children:_.legal_name})]}),_.trading_name&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Trading Name"}),e.jsx("p",{className:"font-medium",children:_.trading_name})]}),(ms||_.contact_email)&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx($s,{className:"h-3.5 w-3.5 text-muted-foreground mt-4"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Contact Email"}),e.jsx("p",{children:ms||_.contact_email})]})]}),(_.address_line1||_.city||_.country)&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(bt,{className:"h-3.5 w-3.5 text-muted-foreground mt-4"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Address"}),e.jsx("p",{children:[_.address_line1,_.city,_.state,_.postal_code,_.country].filter(Boolean).join(", ")})]})]}),_.registration_no&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(it,{className:"h-3.5 w-3.5 text-muted-foreground mt-4"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Registration No."}),e.jsx("p",{children:_.registration_no})]})]}),_.tax_id&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(it,{className:"h-3.5 w-3.5 text-muted-foreground mt-4"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Tax ID"}),e.jsx("p",{children:_.tax_id})]})]}),_.industry_tags&&_.industry_tags.length>0&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Business categories"}),e.jsxs("p",{children:[_.industry_tags.join(", "),_.industry_standard?` (${_.industry_standard})`:""]})]}),z&&v&&_.country&&(i==null?void 0:i.status)!=="approved"&&e.jsx("div",{className:"col-span-2 rounded-md border p-3",children:e.jsx(Wn,{applicationId:i.id,companyId:v,country:_.country})}),((We=_.bank_profile)==null?void 0:We.account_number_masked)&&e.jsxs("div",{className:"col-span-2 rounded-md border p-3",children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Payment profile"}),e.jsxs("p",{className:"font-medium",children:[_.bank_profile.bank_name," ",_.bank_profile.account_number_masked]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[_.bank_profile.account_name," · ",_.bank_profile.currency," · Unverified until treasury review"]})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No profile details available."})}),e.jsx(fs,{}),e.jsxs(Os,{title:"KYC Submitted Data",children:[Hs&&!r&&e.jsxs("div",{className:"mb-4 p-3 rounded-md bg-muted/50 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(at,{className:"h-4 w-4"}),e.jsx("span",{children:"This submission contains encrypted sensitive fields."})]}),e.jsxs(f,{size:"sm",variant:"outline",onClick:us,disabled:V,children:[V?e.jsx(ge,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ms,{className:"h-4 w-4 mr-1"}),"Decrypt"]})]}),r&&e.jsxs("div",{className:"mb-4 p-3 rounded-md bg-green-50 dark:bg-green-950 flex items-center gap-2 text-sm text-green-800 dark:text-green-200",children:[e.jsx(Ms,{className:"h-4 w-4"}),e.jsx("span",{children:"Sensitive fields have been decrypted for this session."})]}),e.jsx("div",{className:"space-y-6",children:Rs.map((n,u)=>e.jsxs("div",{children:[u>0&&e.jsx(fs,{className:"mb-4"}),e.jsx("h5",{className:"text-sm font-semibold text-muted-foreground mb-3",children:n.section}),e.jsx("div",{className:"space-y-3",children:n.fields.map(s=>{var w;if(s.field_type==="section_header")return null;const a=Fs[s.field_name],o=ct((w=i==null?void 0:i.submitted_data)==null?void 0:w[s.field_name]);return e.jsxs("div",{className:"border-b border-border/50 pb-3 last:border-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(M,{className:"text-muted-foreground text-xs",children:s.field_label}),o&&!r&&e.jsx(at,{className:"h-3 w-3 text-muted-foreground"}),o&&r&&e.jsx(Ms,{className:"h-3 w-3 text-green-600"})]}),e.jsx("div",{className:"mt-1",children:s.field_type==="file"&&s.is_compliance?(()=>
12{const d=a&&typeof a=="object"?a:null,B=typeof a=="string"?a:typeof(d==null?void 0:d.file_path)=="string"?d.file_path:"";return z&&B?e.jsxs("div",{className:"space-y-1",children:[e.jsxs(f,{variant:"link",size:"sm",className:"h-auto p-0 text-primary",onClick:()=>Ve(B,s.field_label),children:[e.jsx(js,{className:"mr-1 h-3.5 w-3.5"}),"View uploaded file"]}),typeof(d==null?void 0:d.issue_date)=="string"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Starts ",d.issue_date,typeof d.expiry_date=="string"?` · Expires ${d.expiry_date}`:""]}),Array.isArray(d==null?void 0:d.history)&&d.history.length>0&&e.jsxs("div",{className:"space-y-1 pt-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Replaced onboarding evidence"}),d.history.map((oe,Fe)=>{const de=oe&&typeof oe=="object"?oe:null,Se=typeof(de==null?void 0:de.file_path)=="string"?de.file_path:"";return Se?e.jsxs(f,{variant:"link",size:"sm",className:"block h-auto p-0 text-muted-foreground",onClick:()=>Ve(Se,typeof(de==null?void 0:de.file_name)=="string"?de.file_name:`${s.field_label} previous version`),children:[e.jsx(js,{className:"mr-1 h-3.5 w-3.5"}),"Previous version ",Fe+1]},`${Se}-${Fe}`):null})]})]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Tracked in the Compliance Documents section below"})})():s.field_type==="file"&&typeof a=="string"&&a?e.jsxs(f,{variant:"link",size:"sm",className:"p-0 h-auto text-primary",onClick:()=>Ve(a,s.field_label),children:[e.jsx(js,{className:"h-3.5 w-3.5 mr-1"}),"View uploaded file"]}):o&&!r?e.jsx("span",{className:"text-muted-foreground italic text-sm",children:"••••••••"}):a!=null&&a!==""?e.jsx("p",{className:"text-sm",children:String(a)}):e.jsx("span",{className:"text-muted-foreground italic text-sm",children:"Not provided"})})]},s.id)})})]},n.section))})]}),((i==null?void 0:i.supplier_org_id)||L||z)&&e.jsxs(e.Fragment,{children:[e.jsx(fs,{}),e.jsxs(Os,{title:"Compliance Documents",children:[ke.length>0?e.jsx("div",{className:"space-y-3",children:ke.map(n=>{const u=Ls(n.expiry_date),s=u==="expired"&&n.status!=="superseded"?"expired":n.status;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-md border",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ne,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:n.doc_name}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[e.jsx("span",{className:"capitalize",children:n.doc_type.replace(/_/g," ")}),n.issuing_body&&e.jsxs("span",{children:["• ",n.issuing_body]}),n.expiry_date&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jn,{className:"h-3 w-3"}),"Expires ",vn(bn(n.expiry_date),"dd MMM yyyy")]}),n.term_value&&n.term_unit&&e.jsxs("span",{children:["• Calculated from ",n.term_value," ",n.term_unit]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{variant:Zn(s),className:"capitalize",children:s}),e.jsx(f,{variant:"ghost",size:"sm",onClick:()=>Ve(n.file_url,n.doc_name),children:e.jsx(js,{className:"h-4 w-4"})}),n.status==="pending"&&!z&&u!=="expired"&&e.jsxs(f,{variant:"outline",size:"sm",onClick:()=>cs.mutate(n.id),disabled:cs.isPending,children:[e.jsx(es,{className:"h-4 w-4 mr-1"}),"Approve document"]})]})]},n.id)})}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"No compliance documents uploaded yet."}),!ds&&!t&&!(Z?W:Y)&&e.jsxs(wt,{variant:"destructive",className:"mt-4",children:[e.jsx(Ps,{className:"h-4 w-4"}),e.jsx(rn,{children:"Compliance approval required"}),e.jsx(Nt,{children:!Z&&!(_!=null&&_.country)?"The supplier country is missing, so requirements cannot be evaluated.":Qe.length>0?`${z?"Supplier must provide":"Approve evidence for"}: ${Qe.map(n=>n.requirement_name).join(", ")}.`:"Compliance evidence is still being checked."})]})]})]}),e.jsx(fs,{}),e.jsx("div",{className:"p-3 rounded-md bg-muted/50 text-sm text-muted-foreground",children:(i==null?void 0:i.status)==="approved"?"Review the supplier’s current compliance evidence and document status.":"By certifying, you confirm this supplier meets your qual
12ification criteria and will be added to your supplier list."}),e.jsx(Me,{className:"gap-2",children:(i==null?void 0:i.status)==="approved"?e.jsxs(e.Fragment,{children:[G&&e.jsxs(f,{variant:"outline",onClick:He,children:[e.jsx(rt,{className:"h-4 w-4 mr-1"}),"Request document renewal"]}),e.jsx(f,{variant:"outline",onClick:()=>N(!1),children:"Close"})]}):i&&(i.status==="draft"||i.status==="needs_revision")?e.jsxs(f,{variant:"outline",onClick:()=>he.mutate(i.id),disabled:he.isPending,children:[he.isPending?e.jsx(ge,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(nt,{className:"h-4 w-4 mr-1"}),"Nudge Supplier"]}):e.jsxs(e.Fragment,{children:[z&&e.jsxs(f,{variant:"destructive",onClick:()=>S(!0),children:[e.jsx(yn,{className:"h-4 w-4 mr-1"}),"Reject"]}),e.jsxs(f,{variant:"outline",onClick:He,children:[e.jsx(rt,{className:"h-4 w-4 mr-1"}),"Request Revision"]}),e.jsxs(f,{onClick:()=>i&&$e.mutate(i.id),disabled:$e.isPending||xe.isPending||!ds,children:[$e.isPending?e.jsx(ge,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(es,{className:"h-4 w-4 mr-1"}),"Certify & Approve"]})]})})]})}),e.jsx(De,{open:m,onOpenChange:S,children:e.jsxs(Ae,{className:"bg-background",children:[e.jsxs(Oe,{children:[e.jsx(Le,{children:"Reject supplier application"}),e.jsx(Pe,{children:"Give the supplier a clear reason. Rejection does not provision a BP number."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{htmlFor:"rejection-reason",children:"Rejection reason"}),e.jsx(as,{id:"rejection-reason",value:x,onChange:n=>k(n.target.value),placeholder:"Explain why the application cannot be approved",rows:4})]}),e.jsxs(Me,{children:[e.jsx(f,{variant:"outline",onClick:()=>S(!1),children:"Cancel"}),e.jsx(f,{variant:"destructive",onClick:()=>i&&Ue.mutate({submissionId:i.id,reason:x}),disabled:!x.trim()||Ue.isPending,children:"Reject application"})]})]})}),e.jsx(De,{open:b,onOpenChange:A,children:e.jsxs(Ae,{className:"bg-background",children:[e.jsxs(Oe,{children:[e.jsx(Le,{children:(i==null?void 0:i.status)==="approved"&&G?"Request document renewal":"Request Revision"}),e.jsx(Pe,{children:(i==null?void 0:i.status)==="approved"&&G?"Reopen this buyer onboarding so the supplier can assign and submit a replacement document version.":"Provide feedback for the supplier about what needs to be updated."})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(M,{htmlFor:"revision-notes",children:"Revision Notes"}),e.jsx(as,{id:"revision-notes",placeholder:(i==null?void 0:i.status)==="approved"&&G?"Identify the document that must be renewed...":"Please explain what needs to be revised...",value:U,onChange:n=>O(n.target.value),rows:4})]})}),e.jsxs(Me,{children:[e.jsx(f,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsx(f,{onClick:()=>i&&Ce.mutate({submissionId:i.id,notes:U}),disabled:!U.trim()||Ce.isPending,children:"Send Request"})]})]})})]})});function ei(p){return _e({queryKey:["onboarding-templates-list",p],queryFn:async()=>{if(!p)return[];const{data:v,error:g}=await c.from("supplier_onboarding_templates").select("id, name").eq("company_id",p).eq("is_active",!0).order("is_default",{ascending:!1});if(g)throw g;return v||[]},enabled:!!p})}const mt=Qs("AddSupplierSheet"),si=qt({legal_name:ae().min(1,"Legal name is required"),trading_name:ae().optional(),tax_id:ae().optional(),registration_no:ae().optional(),country:ae().optional(),website:ae().optional(),supplier_type:fn(["regular","one_time","employee"]).default("regular"),address_street:ae().optional(),address_city:ae().optional(),address_state:ae().optional(),address_postal_code:ae().optional(),address_country:ae().optional(),contact_name:ae().optional(),contact_email:ae().email().optional().or(gn("")),contact_phone:ae().optional(),contact_title:ae().optional()});function pt({userId:p,onSuccess:v,trigger:g}){const[l,i]=j.useState(!1),[D,E]=j.useState(!1),[N,b]=j.useState(""),{currency:A}=Ln(p),[U,O]=j.useState(""),m=Ze({resolver:Je(si),defaultValues:{legal_name:"",trading_name:"",tax_id:"",registration_no:"",country:"",website:"",supplier_type:"regular",address_street:"",address_city:"",address_state:"",address_postal_code:"",address_country:"",contact_name:"",contact_email:"",contact_phone:"",contact_title:""}}),S=m.watch("address_country"),x=m.watch("address_state"),k=j.useRef(S),R=j.useRef(x);j.useEffect(()=>{S!==k.current&&(k.current&&(m.setValue("address_state",""),m.setValue("address_city",""),O("")),b(S||""),k.current=S)},[S,m]),j.useEffect(()=>{x!==R.current&&(R.current&&m.setValue("address_city",""),O(x||""),R.current=x)},[x,m]);const q=async r=>
12{E(!0);try{const{data:C,error:V}=await c.from("profiles").select("company_id").eq("id",p).maybeSingle();if(V)throw V;if(!(C!=null&&C.company_id)){y.error("Company information not found"),E(!1);return}const I=C.company_id,L=await An.createSupplier(I,{bp_type:"organization",legal_name:r.legal_name,trading_name:r.trading_name||void 0,tax_id:r.tax_id||void 0,registration_no:r.registration_no||void 0,country:r.country||r.address_country||void 0,website:r.website||void 0,default_currency:A||Pn(r.country||r.address_country||""),supplier_type:r.supplier_type,primary_address:r.address_street||r.address_city||r.address_country?{street:r.address_street||void 0,city:r.address_city||void 0,state:r.address_state||void 0,postal_code:r.address_postal_code||void 0,country:r.address_country||void 0,is_primary:!0}:void 0,primary_contact:r.contact_name||r.contact_email||r.contact_phone?{name:r.contact_name||r.legal_name,email:r.contact_email||void 0,phone:r.contact_phone||void 0,title:r.contact_title||void 0,is_primary:!0}:void 0});if(r.contact_email&&L.bp.id)try{await On.sendOnboardingInvite(I,L.bp.id,r.contact_email,r.contact_name),y.success("Supplier created and invitation sent!")}catch(z){mt.error("Failed to send invitation:",z),y.success("Supplier created",{description:"Invitation email failed - use 'Resend Invite' to try again"})}else y.success("Supplier created successfully");m.reset(),b(""),O(""),i(!1),v()}catch(C){mt.error("Error creating supplier:",C),y.error(C instanceof Error?C.message:"Failed to create supplier")}finally{E(!1)}};return e.jsxs(kn,{open:l,onOpenChange:i,children:[e.jsx(Fn,{asChild:!0,children:g||e.jsxs(f,{children:[e.jsx(Xe,{className:"mr-2 h-4 w-4"}),"Add Supplier"]})}),e.jsxs(Rn,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsxs(Tn,{children:[e.jsxs(In,{className:"flex items-center gap-2",children:[e.jsx(Mn,{className:"h-5 w-5"}),"Add New Supplier"]}),e.jsx(En,{children:"Create a supplier as a Business Partner with proper role and address management."})]}),e.jsx(Dn,{...m,children:e.jsxs("form",{onSubmit:m.handleSubmit(q),className:"space-y-6 mt-6",children:[e.jsxs(yt,{defaultValue:"organization",className:"w-full",children:[e.jsxs(vt,{className:"grid w-full grid-cols-3",children:[e.jsx(Te,{value:"organization",children:"Organization"}),e.jsx(Te,{value:"address",children:"Address"}),e.jsx(Te,{value:"contact",children:"Contact"})]}),e.jsxs(Ie,{value:"organization",className:"space-y-4 mt-4",children:[e.jsx(ee,{control:m.control,name:"legal_name",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Legal Name *"}),e.jsx(ne,{children:e.jsx(H,{...r,placeholder:"Company legal name"})}),e.jsx(ie,{})]})}),e.jsx(ee,{control:m.control,name:"trading_name",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Trading Name"}),e.jsx(ne,{children:e.jsx(H,{...r,placeholder:"DBA or trading name"})}),e.jsx(ie,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(ee,{control:m.control,name:"tax_id",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Tax ID"}),e.jsx(ne,{children:e.jsx(H,{...r,placeholder:"VAT/Tax ID"})}),e.jsx(ie,{})]})}),e.jsx(ee,{control:m.control,name:"registration_no",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Registration No."}),e.jsx(ne,{children:e.jsx(H,{...r,placeholder:"Company registration"})}),e.jsx(ie,{})]})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(ee,{control:m.control,name:"country",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Country"}),e.jsx(ne,{children:e.jsx(ys,{type:"country",value:r.value||"",onChange:r.onChange,placeholder:"Select country"})}),e.jsx(ie,{})]})}),e.jsx(ee,{control:m.control,name:"website",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Website"}),e.jsx(ne,{children:e.jsx(H,{...r,placeholder:"https://example.com"})}),e.jsx(ie,{})]})})]}),e.jsx(ee,{control:m.control,name:"supplier_type",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Supplier Type"}),e.jsxs(ss,{onValueChange:r.onChange,defaultValue:r.value,children:[e.jsx(ne,{children:e.jsx(ts,{children:e.jsx(ns,{placeholder:"Select type"})})}),e.jsxs(is,{children:[e.jsx(ye,{value:"regular",children:"Regular Supplier"}),e.jsx(ye,{value:"one_time",children:"One-Time Supplier"}),e.jsx(ye,{value:"employee",children:"Employee/Contractor"})]})]}),e.jsx(ie,{})]})})]}
12),e.jsxs(Ie,{value:"address",className:"space-y-4 mt-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Primary Address (you can add additional locations later)"}),e.jsx(ee,{control:m.control,name:"address_street",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Street Address"}),e.jsx(ne,{children:e.jsx(as,{...r,placeholder:"Street address",rows:2})}),e.jsx(ie,{})]})}),e.jsx(ee,{control:m.control,name:"address_country",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Country"}),e.jsx(ne,{children:e.jsx(ys,{type:"country",value:r.value||"",onChange:C=>{r.onChange(C),b(C)},placeholder:"Select country"})}),e.jsx(ie,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(ee,{control:m.control,name:"address_state",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"State / Region"}),e.jsx(ne,{children:e.jsx(ys,{type:"state",value:r.value||"",onChange:C=>{r.onChange(C),O(C)},selectedCountry:N,placeholder:"Select state"})}),e.jsx(ie,{})]})}),e.jsx(ee,{control:m.control,name:"address_city",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"City"}),e.jsx(ne,{children:e.jsx(ys,{type:"city",value:r.value||"",onChange:r.onChange,selectedCountry:N,selectedState:U,placeholder:"Enter city"})}),e.jsx(ie,{})]})})]}),e.jsx(ee,{control:m.control,name:"address_postal_code",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Postal Code"}),e.jsx(ne,{children:e.jsx(H,{...r,placeholder:"Postal / ZIP code"})}),e.jsx(ie,{})]})})]}),e.jsxs(Ie,{value:"contact",className:"space-y-4 mt-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Primary Contact Person"}),e.jsx(ee,{control:m.control,name:"contact_name",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Contact Name"}),e.jsx(ne,{children:e.jsx(H,{...r,placeholder:"Full name"})}),e.jsx(ie,{})]})}),e.jsx(ee,{control:m.control,name:"contact_title",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Job Title"}),e.jsx(ne,{children:e.jsx(H,{...r,placeholder:"e.g. Sales Manager"})}),e.jsx(ie,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(ee,{control:m.control,name:"contact_email",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Email"}),e.jsx(ne,{children:e.jsx(H,{...r,type:"email",placeholder:"[email protected]"})}),e.jsx(ie,{})]})}),e.jsx(ee,{control:m.control,name:"contact_phone",render:({field:r})=>e.jsxs(se,{children:[e.jsx(te,{children:"Phone"}),e.jsx(ne,{children:e.jsx(H,{...r,placeholder:"+1 234 567 8900"})}),e.jsx(ie,{})]})})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx(f,{type:"button",variant:"outline",onClick:()=>i(!1),disabled:D,children:"Cancel"}),e.jsx(f,{type:"submit",disabled:D,children:D?"Creating...":"Create Supplier"})]})]})})]})]})}const bs=Qs("Suppliers"),ti=(p,v)=>{if(v==="manual")return e.jsx(T,{variant:"default",children:"Active"});if(v==="tenant_bp")switch(p){case"active":return e.jsx(T,{variant:"default",className:"bg-green-600",children:"Active"});case"invited":return e.jsx(T,{variant:"secondary",className:"bg-blue-100 text-blue-700",children:"Invited"});case"pending":return e.jsx(T,{variant:"outline",className:"border-amber-500 text-amber-600",children:"Pending Approval"});default:return e.jsx(T,{variant:"outline",children:p})}switch(p){case"approved":return e.jsx(T,{variant:"default",className:"bg-green-600",children:"Active"});case"invited":return e.jsx(T,{variant:"secondary",className:"bg-blue-100 text-blue-700",children:"Invited"});case"pending_onboarding":return e.jsx(T,{variant:"outline",className:"border-amber-500 text-amber-600",children:"Pending KYC"});default:return e.jsx(T,{variant:"outline",children:p})}},ni=p=>{switch(p){case"network":return e.jsx(T,{variant:"secondary",children:"Network"});case"regular":return e.jsx(T,{variant:"default",children:"Regular"});case"one_time":return e.jsx(T,{variant:"outline",children:"One-Time"});case"employee":return e.jsx(T,{variant:"secondary",children:"Employee"});default:return e.jsx(T,{variant:"outline",children:p})}};function ii({companyId:p,templates:v}){const g=Be(),{data:l,isLoading:i}=_e({queryKey:["company-supplier-settings",p],queryFn:async()=>{const{data:b,error:A}=await c.from("companies").select("is_discoverable, accepting_suppliers, requires_supplier_onboarding, default_onboarding_template_id").eq("id",p).single();if(A)throw A;return b},enabled:!!p}),D=$({mutationFn:async b=>{const{error:A}=await c.from("companies").update(b).eq("id",p);if(A)throw A},onSuccess:()=>{g.invalidateQueries({queryKey:["company-supplier-settings"]}),y.success("Settings updated")},onError:b=>{y.error("Failed to update settings: "+b.message)}}),E=(b,A)=>{D.mutate({[b]:A})},N=b=>{D.mutate({default_onboarding_template_id:b==="none"?null:b})};return i?e.jsx(ue,{children:e.jsx(me,{className:"py-8 text-center",children:e.jsx(ge,{className:"h-6 w-6 animate-spin mx-auto"})})}):e.jsxs(ue,{children:[e.jsxs(ve,{children:[e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(zn,{className:"h-5 w-5"}),"Supplier Network Settings"]}),e.jsx(qe,{children:"Configure how your company appears in the supplier directory and how connection requests are handled"})]}),e.jsxs(me,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs(M,{className:"flex items-center gap-2",children:[e.jsx(Us,{className:"h-4 w-4 text-muted-foreground"}),"Visible in Supplier Directory"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Allow suppliers to find your company in the directory"})]}),e.jsx(Re,{checked:!!(l!=null&&l.is_discoverable),onCheckedChange:b=>E("is_discoverable",b),disabled:D.isPending})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs(M,{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"h-4 w-4 text-muted-foreground"}),"Accept Connection Requests"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Allow suppliers to send you connection requests"})]}),e.jsx(Re,{checked:!!(l!=null&&l.accepting_suppliers),onCheckedChange:b=>E("accepting_suppliers",b),disabled:D.isPending})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs(M,{className:"flex items-center gap-2",children:[e.jsx(Qn,{className:"h-4 w-4 text-muted-foreground"}),"Require Onboarding Form"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Require suppliers to complete an onboarding form when connecting"})]}),e.jsx(Re,{checked:!!(l!=null&&l.requires_supplier_onboarding),onCheckedChange:b=>E("requires_supplier_onboarding",b),disabled:D.isPending})]}),(l==null?void 0:l.requires_supplier_onboarding)&&e.jsxs("div",{className:"space-y-2 pl-6 border-l-2 border-muted",children:[e.jsx(M,{children:"Default Onboarding Template"}),e.jsxs(ss,{value:(l==null?void 0:l.default_onboarding_template_id)||"none",onValueChange:N,children:[e.jsx(ts,{className:"w-full max-w-xs",children:e.jsx(ns,{placeholder:"Select a template"})}),e.jsxs(is,{children:[e.jsx(ye,{value:"none",children:"No default template"}),v.map(b=>e.jsx(ye,{value:b.id,children:b.name},b.id))]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This template will be automatically sent when suppliers request a connection"})]})]})]})}const xt=[{value:"active",label:"Active"},{value:"approved",label:"Approved"},{value:"invited",label:"Invited"},{value:"pending",label:"Pending"},{value:"pending_onboarding",label:"Pending KYC"}],ai=["supplier","q"];function ri(p,v){return p.id===v||p.bpId===v||p.supplierOrgId===v||p.networkSupplierOrgId===v||p.manualSupplierId===v}function Wr(){const{isAuthenticated:p,loading:v,user:g}=Ft(),{profile:l,isLoading:i}=Et(g==null?void 0:g.id),D=Rt(),E=Be(),[N,b]=j.useState(!1),[A,U]=j.useState(null),[O,m]=j.useState(null),[S,x]=j.useState("suppliers"),[k,R]=j.useState(!1),[q,r]=j.useState(null),{data:C=[]}=ei(l==null?void 0:l.company_id),{data:V}=Vn(),I=j.useMemo(()=>{const s=new Map;if(!V)return s;for(const a of V){if(!a.active)continue;const o=s.get(a.supplier_id);o?a.verification_status==="verified"&&(o.verified=!0):s.set(a.supplier_id,{hasAccount:!0,verified:a.verification_status==="verified"})}return s},[V]),{data:L}=_e({queryKey:["all-unified-supplier-performance","suppliers-list",l==null?void 0:l.company_id],queryFn:async()=>{const{data:s,error:a}=await c.from("supplier_performance_summary").select("supplier_bp_id, supplier_org_id, avg_overall_score, total_evaluations, performance_tier").eq("company_id",l.company_id);if(a)throw a;return s??[]},enabled:!!(l!=null&&l.company_id)}),z=j.useMemo(()=>{const s=new Map;for(const a of L??[]){const o=a.supplier_bp_id||a.supplier_org_id;o&&s.set(o,{score:a.avg_overall_score??null,tier:a.performance_tier??null,evaluations:a.total_evaluations??0})}return s},[L]),G=j.useCallback(s=>{const a=s.bpId||s.supplierOrgId;return a?z.get(a):void 0},[z]),[fe,we]=j.useState(""),[le,pe]=j.useState([]),[Z,h]=Tt(),P=j.useMemo(()=>Es(Z),[Z]),Q=P.supplier,[W,_]=j.useState(1),[K,t]=j.useState(10),F=[{id:"status",label:"Status",type:"select",options:xt},{id:"type",label:"Type",type:"select",options:[{value:"regular",label:"Regular"},{value:"one_time",label:"One-Time"},{value:"employee",label:"Employee"},{value:"network",label:"Network"}]},{id:"source",label:"Source",type:"select",options:[{value:"tenant_bp",label:"BP Suppliers"},{value:"manual",label:"Legacy Manual"},{value:"network",label:"Network"}]}],Y=window.location.hostname.includes("preview")||window.location.hostname.includes("localhost"),{suppliers:je,isLoading:rs,resendInvite:ze,isResending:os,sendManualInvite:qs,isSendingManualInvite:ke,sendTenantInvite:ks,isSendingTenantInvite:ls,isUpdatingTenantSupplier:Qe,deleteTenantSupplier:ds,isDeletingTenantSupplier:cs}=wn({userId:g==null?void 0:g.id,companyId:l==null?void 0:l.company_id}),xe=j.useMemo(()=>je.filter(s=>{var a,o,w;if(fe){const d=fe.toLowerCase();if(!s.name.toLowerCase().includes(d)&&!((a=s.email)!=null&&a.toLowerCase().includes(d))&&!((o=s.supplierCode)!=null&&o.toLowerCase().includes(d))&&!((w=s.calabashId)!=null&&w.toLowerCase().includes(d)))return!1}for(const d of le)if(d.field==="status"&&s.status!==d.value||d.field==="type"&&s.type!==d.value||d.field==="source"&&s.source!==d.value)return!1;return!0}),[je,fe,le]),$e=Math.ceil(xe.length/K),Ue=j.useMemo(()=>{const s=(W-1)*K;return xe.slice(s,s+K)},[xe,W,K]);j.useEffect(()=>{_(1)},[le,fe]);const he=Ds(P),Ce=j.useRef("");j.useEffect(()=>{if(he===Ce.current)return;const s=Pt(Ce.current,P);Ce.current=he,s.size!==0&&(s.has("q")&&we(P.q??""),s.has("status")&&pe(a=>{const o=a.filter(d=>d.field!=="status");if(!P.status)return o;const w=xt.find(d=>d.value===P.status);return[...o,{field:"status",value:P.status,label:(w==null?void 0:w.label)||P.status}]}))},[P,he]);const re=j.useMemo(()=>Q?xe.find(s=>
12ri(s,Q))??null:null,[xe,Q]);j.useEffect(()=>{if(!re)return;const s=xe.indexOf(re);s<0||_(Math.floor(s/K)+1)},[re,xe,K]);const He=j.useRef(null);j.useEffect(()=>{if(!re)return;const s=He.current;s&&typeof s.scrollIntoView=="function"&&s.scrollIntoView({block:"center",behavior:"smooth"})},[re,W]);const us=s=>{const a=et(Z,s);Ce.current=Ds(Es(a)),h(a,{replace:!0})},Ve=s=>h(et(Z,s),{replace:!0}),Fs=()=>{if(we(""),pe([]),!Kt(P))return;const s=Bt(Z);Ce.current=Ds(Es(s)),h(s,{replace:!0})},ms=Mt(P,{only:ai,displayOverrides:{supplier:(re==null?void 0:re.name)??Vt(Q)}}),[Hs,Rs]=j.useState({name:"",contact_person:"",email:"",phone:"",address:"",supplier_type:"regular"});j.useEffect(()=>{!v&&!i&&!p&&D("/auth")},[p,v,i,D]),$({mutationFn:async s=>{if(!g||!(l!=null&&l.company_id))throw new Error("Not authenticated or missing company");const{data:a,error:o}=await c.from("suppliers").insert({user_id:g.id,company_id:l.company_id,name:s.name,contact_person:s.contact_person||null,email:s.email||null,phone:s.phone||null,address:s.address||null,supplier_type:s.supplier_type}).select("id").single();if(o)throw o;return{supplierId:a.id,email:s.email,name:s.name}},onSuccess:async s=>{if(E.invalidateQueries({queryKey:["unified-suppliers"]}),s.email&&s.supplierId)try{const{data:a}=await c.from("companies").select("company_name").eq("id",l==null?void 0:l.company_id).single();await c.functions.invoke("send-supplier-invite",{body:{supplierId:s.supplierId,supplierEmail:s.email,companyName:(a==null?void 0:a.company_name)||"A company",companyId:l==null?void 0:l.company_id}}),y.success("Supplier created and invitation sent!")}catch(a){bs.error("Failed to send invite:",a),y.success("Supplier created",{description:"Invitation email failed - use 'Resend Invite' to try again"})}else y.success("Supplier created successfully");b(!1),Ge()},onError:s=>{y.error("Failed to create supplier"),bs.error("Failed to create supplier:",s)}}),$({mutationFn:async({id:s,data:a})=>{const{error:o}=await c.from("suppliers").update({name:a.name,contact_person:a.contact_person||null,email:a.email||null,phone:a.phone||null,address:a.address||null,supplier_type:a.supplier_type}).eq("id",s);if(o)throw o},onSuccess:()=>{E.invalidateQueries({queryKey:["unified-suppliers"]}),y.success("Supplier updated successfully"),b(!1),U(null),Ge()},onError:s=>{y.error("Failed to update supplier"),bs.error("Failed to update supplier:",s)}});const ps=$({mutationFn:async s=>{const{error:a}=await c.from("suppliers").delete().eq("id",s);if(a)throw a},onSuccess:()=>{E.invalidateQueries({queryKey:["unified-suppliers"]}),y.success("Supplier deleted successfully"),m(null)},onError:s=>{y.error("Failed to delete supplier"),bs.error("Failed to delete supplier:",s)}}),Ge=()=>{Rs({name:"",contact_person:"",email:"",phone:"",address:"",supplier_type:"regular"}),U(null)},Ye=s=>{if(s.source==="network"){y.error("Network suppliers cannot be edited directly");return}U(s),b(!0)},xs=s=>{s.supplierBuyerLinkId&&ze(s.supplierBuyerLinkId)},hs=s=>{if(!s.email){y.error("Cannot send invite: supplier has no email address");return}s.manualSupplierId&&qs({supplierId:s.manualSupplierId,email:s.email})},_s=s=>{if(!s.email){y.error("Cannot send invite: supplier has no email address");return}s.bpId&&ks({bpId:s.bpId,email:s.email,contactName:s.contactPerson||void 0})},gs=s=>{t(s),_(1)},Ke=$({mutationFn:async s=>{if(!s.email)throw new Error("Supplier must have an email");if(!(l!=null&&l.company_id))throw new Error("No company ID");const a=`CAL-DEV-${Date.now().toString(36).toUpperCase()}`,{data:o,error:w}=await c.from("supplier_orgs").insert({legal_name:s.name,trading_name:s.name,contact_email:s.email,phone:s.phone||null,country:"Nigeria",status:"pending",calabash_id:a}).select("id").single();if(w)throw w;const{error:d}=await c.from("supplier_buyer_links").insert({buyer_company_id:l.company_id,supplier_org_id:o.id,status:"approved"});if(d)throw d;return o.id},onSuccess:()=>{E.invalidateQueries({queryKey:["unified-suppliers"]}),y.success("Manual supplier promoted to network for testing!")},onError:s=>{y.error("Failed to promote supplier",{description:_t(s)})}}),We=j.useRef(null),n=j.useCallback(async s=>{var a;await((a=We.current)==null?void 0:a.openSubmissionById(s))},[]);if(v||i)return e.jsxs("div",{className:"flex items-center justify-center min-h-[400px]",children:[e.jsx(It,{children:e.jsx("title",{children:"Suppliers | Calabash"})}),e.jsx(ge,{className:"h-8 w-8 animate-spin text-muted-foreground"})]});if(!p)return null;const u=je.filter(s=>s.source==="manual"&&s.email);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold",children:"Suppliers"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Manage your supplier information and contacts"})]}),Y&&e.jsx(Dt,{open:k,onOpenChange:R,children:e.jsxs(ue,{className:"border-amber-300 bg-amber-50",children:[e.jsx(At,{asChild:!0,children:e.jsx(ve,{className:"pb-2 cursor-pointer hover:bg-amber-100/50 transition-colors",children:e.jsxs(be,{className:"text-sm flex items-center justify-between text-amber-800",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Development Tools"]}),e.jsx(Kn,{className:`h-4 w-4 transition-transform ${k?"rotate-180":""}`})]})})}),e.jsx(Ot,{children:e.jsxs(me,{className:"space-y-3 pt-0",children:[e.jsx("p",{className:"text-xs text-amber-700",children:"Promote manual suppliers to network suppliers for testing sourcing invitations."}),u.length===0?e.jsx("p",{className:"text-xs text-amber-600",children:"No manual suppliers with email addresses found. Add a manual supplier with an email first."}):e.jsx("div",{className:"flex flex-wrap gap-2",children:u.map(s=>e.jsxs(f,{size:"sm",variant:"outline",className:"text-xs border-amber-400 hover:bg-amber-100",onClick:()=>Ke.mutate(s),disabled:Ke.isPending,children:[Ke.isPending?e.jsx(ge,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(Is,{className:"h-3 w-3 mr-1"}),'Promote "',s.name,'"']},s.id))})]})})]})}),e.jsxs(yt,{value:S,onValueChange:x,children:[e.jsx("div",{className:"overflow-x-auto -mx-1 px-1",children:e.jsxs(vt,{className:"w-max",children:[e.jsxs(Te,{value:"suppliers",className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"h-4 w-4"}),"My Suppliers"]}),e.jsxs(Te,{value:"incoming",className:"flex items-center gap-2",children:[e.jsx(kt,{className:"h-4 w-4"}),"Incoming Requests"]}),e.jsxs(Te,{value:"onboarding",className:"flex items-center gap-2",children:[e.jsx(St,{className:"h-4 w-4"}),"Onboarding Forms"]}),e.jsxs(Te,{value:"compliance",className:"flex items-center gap-2",children:[e.jsx(es,{className:"h-4 w-4"}),"Compliance"]})]})}),e.jsxs(Ie,{value:"suppliers",className:"space-y-6",children:[e.jsx("div",{className:"flex justify-end",children:e.jsx(pt,{userId:(g==null?void 0:g.id)||"",onSuccess:()=>{E.invalidateQueries({queryKey:["unified-suppliers"]})}})}),e.jsxs(ue,{children:[e.jsxs(ve,{children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs(be,{className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"h-5 w-5"}),"All Suppliers (",xe.length,")"]})}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4 pt-4",children:[e.jsxs("div",{className:"relative w-full sm:max-w-sm sm:flex-1",children:[e.jsx(ot,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(H,{placeholder:"Search by name, email, or code...",value:fe,onChange:s=>{we(s.target.value),P.q!==void 0&&us("q")},className:"pl-9"})]}),e.jsx(Nn,{fields:F,filters:le,onFiltersChange:s=>{var a;pe(s),P.status!==void 0&&((a=s.find(o=>o.field==="status"))==null?void 0:a.value)!==P.status&&us("status")}}),e.jsx(Lt,{chips:ms,onRemove:Ve})]})]}),e.jsx(me,{children:rs?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ge,{className:"h-6 w-6 animate-spin mx-auto mb-2"}),"Loading suppliers..."]}):je.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ee,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No suppliers found"}),e.jsx(pt,{userId:(g==null?void 0:g.id)||"",onSuccess:()=>{E.invalidateQueries({queryKey:["unified-suppliers"]})},trigger:e.jsxs(f,{children:[e.jsx(Xe,{className:"mr-2 h-4 w-4"}),"Add Your First Supplier"]})})]}):Ue.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ot,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No suppliers match your search or filters"}),e.jsx(f,{variant:"outline",onClick:Fs,children:"Clear Filters"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(gt,{children:[e.jsx(ft,{children:e.jsxs(Ns,{children:[e.jsx(J,{children:"Supplier Code"}),e.jsx(J,{children:"Supplier Name"}),e.jsx(J,{children:"Type"}),e.jsx(J,{children:"Status"}),e.jsx(J,{children:"Performance"}),e.jsx(J,{children:"Tier"}),e.jsx(J,{children:"Payment"}),e.jsx(J,{children:"Email"}),e.jsx(J,{children:"Phone"}),e.jsx(J,{className:"text-right",children:"Actions"})]})}),e.jsx(jt,{children:Ue.map(s=>{var o,w;const a=(re==null?void 0:re.id)===s.id;return e.jsxs(Ns,{ref:a?He:void 0,"data-highlighted":a?"true":void 0,className:a?"bg-primary/5 ring-2 ring-primary/40":void 0,children:[e.jsx(X,{children:e.jsxs(Ts,{to:Vs(s),className:"flex items-center gap-2 rounded-sm text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx(Ne,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"font-mono text-xs",children:s.supplierCode||s.calabashId||"-"})]})}),e.jsx(X,{className:"font-medium",children:e.jsxs(Ts,{to:Vs(s),className:"flex items-center gap-2 rounded-sm hover:text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx(Ee,{className:"h-4 w-4 text-muted-foreground"}),s.name]})}),e.jsx(X,{children:ni(s.type)}),e.jsx(X,{children:ti(s.status,s.source)}),e.jsx(X,{children:(()=>{const d=G(s);return!d||d.evaluations===0||d.score===null?e.jsx("span",{className:"text-muted-foreground text-xs whitespace-nowrap",children:"Not scored"}):e.jsxs("span",{className:"font-medium tabular-nums",children:[Number(d.score).toFixed(1),e.jsx("span",{className:"text-muted-foreground text-xs",children:" / 5.0"})]})})()}),e.jsx(X,{children:(()=>{const d=G(s),B=d==null?void 0:d.tier;return!d||d.evaluations===0||!B||!vs[B]?e.jsx("span",{className:"text-muted-foreground text-xs",children:"-"}):e.jsx(T,{variant:"outline",className:`${vs[B].bgColor} ${vs[B].color} whitespace-nowrap`,children:vs[B].label})})()}),e.jsx(X,{children:s.bpId&&((o=I.get(s.bpId))!=null&&o.verified)?e.jsxs(T,{variant:"default",className:"bg-green-600 text-[10px] px-1.5 py-0",children:[e.jsx(Ks,{className:"h-3 w-3 mr-0.5"}),"Ready"]}):s.bpId&&((w=I.get(s.bpId))!=null&&w.hasAccount)?e.jsxs(T,{variant:"outline",className:"text-amber-600 border-amber-400 text-[10px] px-1.5 py-0",children:[e.jsx(Ks,{className:"h-3 w-3 mr-0.5"}),"Unverified"]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"-"})}),e.jsx(X,{children:s.email?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($s,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-sm",children:s.email})]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(X,{children:s.phone?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-sm",children:s.phone})]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(X,{className:"text-right",children:e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(f,{variant:"ghost",size:"icon",asChild:!0,title:"View supplier workspace",children:e.jsx(Ts,{to:Vs(s),"aria-label":`View ${s.name}`,children:e.jsx(Us,{className:"h-4 w-4"})})}),s.source==="tenant_bp"&&e.jsxs(e.Fragment,{children:[s.email&&s.status!=="active"&&e.jsxs(f,{variant:"outline",size:"sm",onClick:()=>_s(s),disabled:ls,title:"Send/resend onboarding invite",children:[e.jsx(ws,{className:`h-4 w-4 mr-1 ${ls?"animate-spin":""}`}),s.hasPendingInvite?"Resend Invite":"Send Invite"]}),e.jsx(f,{variant:"ghost",size:"icon",onClick:()=>Ye(s),disabled:Qe,title:"Edit supplier","aria-label":`Edit ${s.name}`,children:e.jsx(Cs,{className:"h-4 w-4"})}),e.jsx(f,{variant:"ghost",size:"icon",onClick:()=>r(s),title:"Edit commercial terms","aria-label":`Edit commercial terms for ${s.name}`,children:e.jsx(Ks,{className:"h-4 w-4"})}),s.networkSupplierOrgId&&e.jsxs(T,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(Is,{className:"h-3 w-3 mr-1"}),"Network"]}),e.jsx(f,{variant:"ghost",size:"icon",onClick:()=>m(s.bpId||null),disabled:cs,title:"Delete supplier","aria-label":`Delete ${s.name}`,children:e.jsx(Ss,{className:"h-4 w-4 text-destructive"})})]}),s.source==="network"&&s.status!=="approved"&&e.jsxs(f,{variant:"outline",size:"sm",onClick:()=>xs(s),disabled:os,children:[e.jsx(ws,{className:`h-4 w-4 mr-1 ${os?"animate-spin":""}`}),"Resend"]}),s.source==="manual"&&e.jsxs(e.Fragment,{children:[s.email&&e.jsxs(f,{variant:"outline",size:"sm",onClick:()=>hs(s),disabled:ke,title:"Resend invite to join Calabash Connect",children:[e.jsx(ws,{className:`h-4 w-4 mr-1 ${ke?"animate-spin":""}`}),"Resend Invite"]}),e.jsx(f,{variant:"ghost",size:"icon",onClick:()=>Ye(s),children:e.jsx(Cs,{className:"h-4 w-4"})}),e.jsx(f,{variant:"ghost",size:"icon",onClick:()=>
12m(s.manualSupplierId||null),children:e.jsx(Ss,{className:"h-4 w-4 text-destructive"})})]})]})})]},s.id)})})]})}),e.jsx(Cn,{currentPage:W,totalPages:$e,pageSize:K,totalItems:xe.length,onPageChange:_,onPageSizeChange:gs})]})})]})]}),e.jsxs(Ie,{value:"incoming",className:"space-y-6",children:[e.jsx(Un,{companyId:l==null?void 0:l.company_id,onboardingTemplates:C,onReviewSubmission:n}),e.jsx(ut,{ref:We,companyId:l==null?void 0:l.company_id})]}),e.jsxs(Ie,{value:"onboarding",className:"space-y-6",children:[(l==null?void 0:l.company_id)&&e.jsx(ii,{companyId:l.company_id,templates:C}),(l==null?void 0:l.company_id)&&(g==null?void 0:g.id)&&e.jsx(Gn,{companyId:l.company_id,userId:g.id})]}),e.jsxs(Ie,{value:"compliance",className:"space-y-6",children:[e.jsx(ue,{children:e.jsxs(ve,{children:[e.jsx(be,{children:"Supplier Compliance"}),e.jsx(qe,{children:"Open a supplier submission to review questionnaire answers and compliance evidence together."})]})}),e.jsx(ut,{companyId:l==null?void 0:l.company_id})]})]}),e.jsx(zt,{open:!!O,onOpenChange:()=>m(null),children:e.jsxs(Qt,{className:"bg-background",children:[e.jsxs($t,{children:[e.jsx(Ut,{children:"Delete Supplier?"}),e.jsx(Ht,{children:"This action cannot be undone. This will permanently delete the supplier and remove their data from the system."})]}),e.jsxs(Gt,{children:[e.jsx(Yt,{children:"Cancel"}),e.jsx(Wt,{onClick:()=>{if(!O)return;const s=je.find(a=>a.bpId===O||a.manualSupplierId===O);(s==null?void 0:s.source)==="tenant_bp"&&s.bpId?ds(s.bpId):(s==null?void 0:s.source)==="manual"&&s.manualSupplierId&&ps.mutate(s.manualSupplierId),m(null)},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Sn,{open:N,onOpenChange:s=>{b(s),s||U(null)},supplier:A,userId:(g==null?void 0:g.id)||"",companyId:(l==null?void 0:l.company_id)||"",onSuccess:()=>{E.invalidateQueries({queryKey:["unified-suppliers"]}),U(null)}}),e.jsx(qn,{open:!!q,onOpenChange:s=>!s&&r(null),supplier:q,userId:(g==null?void 0:g.id)||"",onSuccess:()=>E.invalidateQueries({queryKey:["unified-suppliers"]})})]})}export{Wr as default};

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.