1import{r as n,j as e,aB as ft,p as C,g as S,an as _t,a5 as bt,ax as rt,L as vt,a8 as gt,ay as Je,a6 as nt,az as Ye,f as jt,e as yt,y as Nt,d as St,u as Ct}from"./index-C5qvHg02.js";import{U as Be,e as et,C as Ze,a as lt,j as kt,h as ot,f as $e,b as wt,E as Ft,i as Pt,t as dt,g as Rt,S as Et,c as Tt}from"./usStates-C1Y3oNz1.js";import{C as ct}from"./CertificateStatusBadge-DD-q_KB-.js";import{S as ut}from"./Skeleton-adeP8rWy.js";import{P as Lt}from"./PurchasingExemptionCertificateUploadModal-BcUtJeGZ.js";import{A as It}from"./AddressAutocompleteInput-BEykE5tR.js";/* empty css */import"./usStates-Bcwtldu-.js";import"./certificateUploadSummary-8K-oD5Hm.js";function Dt({onSignatureChange:r,disabled:_=!1,width:b=600,height:$=160}){const L=n.useRef(null),p=n.useRef([]),d=n.useRef(null),[f,O]=n.useState(0),U=()=>L.current?.getContext("2d")??null,q=h=>{h.strokeStyle="#111111",h.lineWidth=2,h.lineCap="round",h.lineJoin="round"},x=n.useCallback(()=>{const h=L.current,g=U();if(!(!h||!g)){g.clearRect(0,0,h.width,h.height),q(g);for(const j of p.current)if(j.length!==0){g.beginPath(),g.moveTo(j[0].x,j[0].y);for(let D=1;D<j.length;D+=1)g.lineTo(j[D].x,j[D].y);j.length===1&&g.lineTo(j[0].x+.5,j[0].y+.5),g.stroke()}}},[]),T=n.useCallback(()=>{const h=L.current;if(!h||p.current.length===0){r(null);return}r(h.toDataURL("image/png"))},[r]),M=h=>{const g=L.current;if(!g)return null;const j=g.getBoundingClientRect();return{x:(h.clientX-j.left)*(g.width/j.width),y:(h.clientY-j.top)*(g.height/j.height)}},P=h=>
1{if(_)return;h.preventDefault(),h.currentTarget.setPointerCapture(h.pointerId);const g=M(h);g&&(d.current=[g])},ee=h=>{const g=d.current;if(_||!g)return;h.preventDefault();const j=M(h);if(!j)return;const D=g[g.length-1];g.push(j);const K=U();K&&(q(K),K.beginPath(),K.moveTo(D.x,D.y),K.lineTo(j.x,j.y),K.stroke())},R=()=>{const h=d.current;h&&(d.current=null,p.current=[...p.current,h],O(p.current.length),x(),T())},v=()=>{p.current=[],d.current=null,O(0),x(),T()},I=()=>{p.current=p.current.slice(0,-1),O(p.current.length),x(),T()};return n.useEffect(()=>{x()},[x]),e.jsxs("div",{children:[e.jsxs("div",{className:"exc-signpad","data-testid":"signature-pad",children:[e.jsx("canvas",{ref:L,width:b,height:$,"aria-label":"Signature drawing area",onPointerDown:P,onPointerMove:ee,onPointerUp:R,onPointerCancel:R,onPointerLeave:()=>{d.current&&R()},"data-testid":"signature-pad-canvas"}),f===0&&!d.current&&e.jsx("span",{className:"exc-signpad__hint",children:"Draw your signature here (mouse or touch)"})]}),e.jsxs("div",{className:"exc-signpad__actions",children:[e.jsx("button",{type:"button",className:"exc-link",onClick:I,disabled:_||f===0,"data-testid":"signature-pad-undo",children:"Undo stroke"}),e.jsx("button",{type:"button",className:"exc-link exc-link--danger",onClick:v,disabled:_||f===0,"data-testid":"signature-pad-clear",children:"Clear"})]})]})}const pt=[{id:"state",label:"State"},{id:"details",label:"Details"},{id:"preview",label:"Preview"},{id:"sign",label:"Sign"},{id:"send",label:"Send"}],it={generation:{label:"Generate",className:"exc-chip exc-chip--success"},multistate_generation:{label:"Generate (SST form)",className:"exc-chip exc-chip--success"},upload_only:{label:"Upload only",className:"exc-chip exc-chip--warning"},dor_issued:{label:"Issued by state",className:"exc-chip exc-chip--warning"},no_sales_tax:{label:"No sales tax",className:"exc-chip exc-chip--muted"}},At={vendorName:"",purchaserName:"",businessType:"",taxId:"",streetAddress:"",city:"",state:"OH",zip:"",exemptionReason:"",description:"",signerTitle:""};async function xt(r,_){const b=r?.response?.data;if(b instanceof Blob)try{const $=JSON.parse(await b.text());if(typeof $.detail=="string")return $.detail}catch{}return S(r,_)}function Ut({orgId:r,locationId:_,cert:b=null,initialStep:$,prefill:L=null,sourceRecord:p=null,onClose:d,onChanged:f,onRequestUpload:O}){const[U,q]=n.useState($??"state"),[x,T]=n.useState(b),[M,P]=n.useState(null),[ee,R]=n.useState(null),[v,I]=n.useState(!1),h=ft(),[g,j]=n.useState(null),[D,K]=n.useState(null),[V,xe]=n.useState((b?.state_code||L?.state||"OH").toUpperCase()),[u,N]=n.useState({...At,...L??{}}),[te,H]=n.useState(null),se=n.useRef(null),[Q,ke]=n.useState(!1),[i,w]=n.useState(null),[k,E]=n.useState(()=>new Date().toISOString().split("T")[0]),[oe,me]=n.useState(!1),[he,ge]=n.useState(null),[G,Ee]=n.useState(null),[X,fe]=n.useState(null),[Te,De]=n.useState(null),de=n.useRef(null),[Y,ue]=n.useState(b?.sent_to_email??""),[ae,ce]=n.useState(""),[W,_e]=n.useState(null),[Le,we]=n.useState(!1),Fe=(x?.status??"").toLowerCase(),Ie=["signed","sent","resent","active"].includes(Fe),Pe=n.useCallback(s=>{se.current&&URL.revokeObjectURL(se.current),se.current=s,H(s)},[]);n.useEffect(()=>{const s=c=>{c.key==="Escape"&&d()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[d]),n.useEffect(()=>()=>{se.current&&URL.revokeObjectURL(se.current),de.current&&URL.revokeObjectURL(de.current)},[]),n.useEffect(()=>{let s=!1;return C.getStateForms().then(c=>{s||j(c.state_forms??[])}).catch(c=>{s||K(S(c,"Failed to load state form availability."))}),()=>{s=!0}},[]);const Ae=n.useRef(!1);n.useEffect(()=>{if(Ae.current||b)return;Ae.current=!0;const s=!!L?.state;C.getOrganizationSettings().then(c=>{c&&N(m=>({...m,purchaserName:m.purchaserName||c.organization_name||"",businessType:m.businessType||c.business_type||"",taxId:m.taxId||c.tax_id||"",streetAddress:m.streetAddress||c.address_line1||"",city:m.city||c.city||"",state:s||m.state!=="OH"?m.state:c.state||"OH",zip:m.zip||c.zip_code||"",exemptionReason:m.exemptionReason||c.default_exemption_reason||c.exemption_reason||"",signerTitle:m.signerTitle||c.default_signer_title||c.signature_title||"",description:m.description||c.description||""}))}).catch(()=>{})},[b,L]);const Z=n.useMemo(()=>g?.find(s=>
1(s.state_code||"").toUpperCase()===V)??null,[g,V]),B=Z?.support??null,A=B?.mode??null,be=A==="multistate_generation",re=A?A==="generation"||be:!!Z?.supports_generation,ve=B?.form_number??Z?.form_number??null,le=Z?.signature??null,je=le?.mode==="manual_placement",ye=Math.max(1,Number(le?.page??1));n.useEffect(()=>{me(je),ge(null),Ee(null),fe(null)},[je,V]);const z=s=>Be.find(c=>c.iso_code===s)?.name??s,Ue=()=>({state_code:V,vendor_name:u.vendorName,exemption_reason:u.exemptionReason,purchaser_name:u.purchaserName,purchaser_business_type:u.businessType,purchaser_address_line1:u.streetAddress,purchaser_city:`${u.city}, ${u.state}, ${u.zip}`.replace(/^,\s*|,\s*$/g,""),signer_title:u.signerTitle,purchaser_tax_id:u.taxId,description_of_property:u.description,purchaser_state:u.state||V,purchaser_zip:u.zip}),Ne=n.useCallback(async s=>{ke(!0);try{const c=await C.download(s);Pe(URL.createObjectURL(c))}catch(c){P(S(c,"Failed to load the certificate preview."))}finally{ke(!1)}},[Pe]),Re=n.useRef(!1);n.useEffect(()=>{Re.current||!b||(Re.current=!0,($==="preview"||$==="sign"||$==="send")&&(b.output_pdf_s3_uri||b.original_document_s3_uri)&&Ne(b.id))},[b,$,Ne]);const Oe=()=>{P(null),N(s=>({...s,state:s.state||V})),q("details")},Me=async()=>{I(!0),P(null);try{let s=x;if(!s){const m={};r!=null&&(m.org_id=r),_!=null&&(m.location_id=_),be&&(m.form_source="sst_f0003");const F={...Ue()};p&&(F.source_record_type=p.type,F.source_record_id=p.id),s=await C.create(F,m),T(s)}const c=await C.render(s.id,Ue());T(c),f(),await Ne(s.id),q("preview")}catch(s){P(S(s,"Failed to generate the certificate."))}finally{I(!1)}},Ke=()=>{P(null),q("sign")},He=s=>{if(!oe||!he||!te)return;s.stopPropagation();const c=s.currentTarget.getBoundingClientRect(),m=s.clientX-c.left,F=s.clientY-c.top;if(m<0||F<0||m>612||F>792)return;const ne=Math.max(0,Math.min(612,m/612*612)),pe=Math.max(0,Math.min(792,(1-F/792)*792));Number.isNaN(ne)||Number.isNaN(pe)||(he==="signature"?Ee({x:ne,y:pe}):fe({x:ne,y:pe}))},Ge=async()=>{if(!(!x||!i||!k)){I(!0),P(null);try{const s={signature_dataurl:i,signature_date:k};oe&&(G&&(s.manual_signature_rect=[G.x-50,G.y-25,G.x+50,G.y+25],s.manual_signature_page=ye),X&&(s.manual_date_rect=[X.x-30,X.y-10,X.x+30,X.y+10],s.manual_date_page=ye));const c=await C.sign(x.id,s);de.current&&URL.revokeObjectURL(de.current);const m=URL.createObjectURL(c);de.current=m,De(m),T(F=>F&&{...F,status:"Signed",output_pdf_s3_uri:F.output_pdf_s3_uri||"signed"}),R("Certificate signed. The signed PDF is now immutable."),f(),q("send")}catch(s){P(await xt(s,"Failed to sign the certificate."))}finally{I(!1)}}},qe=async()=>{if(!(!x||_==null)){I(!0),P(null),_e(null);try{const c=(await C.send(x.id,{to_email:Y.trim(),...ae.trim()?{message:ae.trim()}:{}})).data.approval;if(!c?.id)throw new Error("The exact delivery approval was not created. No email was sent.");const m=c.preview?.resolved??c.preview??{},F=m.attachment??{},ne=await h.requestApproval({eyebrow:"External communication",title:"Send signed certificate?",description:String(m.external_effect??"Email this signed certificate outside ITMS."),facts:[{label:"Certificate",value:String(m.certificate_uid??x.uid??x.id)},{label:"Recipient",value:String(m.recipient_email??Y.trim())},{label:"Attachment",value:String(F.filename??`certificate-${x.uid??x.id}.pdf`)},{label:"Checksum",value:String(F.checksum_sha256??"Recorded at send time")}],attestation:String(m.human_attestation??"I authorize this exact email and attachment to this exact recipient."),confirmLabel:"Ap
1prove & send",riskLabel:"Leaves ITMS"}),pe=await bt.decideApproval(c.id,_,ne);if(!ne){R("Delivery canceled. No email was sent.");return}if(pe.action_status!=="completed")throw new Error("The approved delivery did not complete. Review action history before retrying.");const Ce=pe.data;_e(Ce),T(a=>a&&{...a,status:Ce.status,sent_to_email:Ce.sent_to_email??void 0,sent_at:Ce.sent_at??void 0,send_count:Ce.send_count??void 0}),R(`Certificate emailed to ${Ce.sent_to_email??Y.trim()}.`),f()}catch(s){const c=S(s,"Failed to send the certificate.");P(c.includes("SMTP_NOT_CONFIGURED")?"Email delivery is not configured. Add SMTP settings in the module Settings panel, then retry.":c)}finally{I(!1)}}},We=async()=>{if(x){I(!0),P(null);try{await C.voidCertificate(x.id,{}),T(s=>s&&{...s,status:"Void"}),R("Certificate voided."),f(),we(!1)}catch(s){P(S(s,"Failed to void the certificate."))}finally{I(!1)}}},Se=()=>{if(!Te&&x){C.download(x.id).then(s=>{const c=URL.createObjectURL(s);Ve(c),URL.revokeObjectURL(c)}).catch(async s=>P(await xt(s,"Failed to download the signed PDF.")));return}Te&&Ve(Te)},Ve=s=>{const c=document.createElement("a");c.href=s,c.download=`signed-certificate-${x?.uid??x?.id??"exemption"}.pdf`,document.body.appendChild(c),c.click(),document.body.removeChild(c)},t=pt.findIndex(s=>s.id===U),o=n.useMemo(()=>{const s=new Map((g??[]).map(c=>[(c.state_code||"").toUpperCase(),c]));return Be.map(c=>({code:c.iso_code,name:c.name,availability:s.get(c.iso_code)??null}))},[g]);return e.jsxs("div",{className:"exc-drawer-overlay",onClick:d,"data-testid":"prepare-sign-drawer",children:[e.jsxs("aside",{className:"exc-drawer exc-drawer--wide",role:"dialog","aria-modal":"true","aria-label":"Prepare and sign exemption certificate",onClick:s=>s.stopPropagation(),children:[e.jsxs("header",{className:"exc-drawer__header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:x?`Certificate ${x.uid??x.id}`:"Prepare exemption certificate"}),e.jsxs("div",{className:"exc-drawer__sub",children:[e.jsxs("span",{children:["State: ",e.jsx("strong",{children:V})]}),x?.status&&e.jsxs("span",{children:["Status: ",e.jsx("strong",{children:x.status})]}),u.vendorName&&e.jsxs("span",{children:["Vendor: ",e.jsx("strong",{children:u.vendorName})]})]})]}),e.jsx("button",{type:"button",className:"exc-drawer__close",onClick:d,"data-testid":"prepare-drawer-close",children:"Close"})]}),e.jsx("div",{className:"exc-steps",role:"list","aria-label":"Preparation steps",children:pt.map((s,c)=>e.jsxs("span",{role:"listitem",className:`exc-step-pill${s.id===U?" is-active":""}${c<t?" is-done":""}`,"data-testid":`step-pill-${s.id}`,children:[e.jsx("span",{className:"exc-step-pill__num",children:c<t?"â":c+1}),s.label]},s.id))}),e.jsxs("div",{className:"exc-drawer__body",children:[M&&e.jsxs("div",{className:"exc-banner exc-banner--error","data-testid":"prepare-error",children:[e.jsx("span",{children:M}),e.jsx("button",{type:"button",className:"exc-banner__dismiss",onClick:()=>P(null),"aria-label":"Dismiss",children:"Ã"})]}),ee&&e.jsxs("div",{className:"exc-banner exc-banner--success","data-testid":"prepare-message",children:[e.jsx("span",{children:ee}),e.jsx("button",{type:"button",className:"exc-banner__dismiss",onClick:()=>R(null),"aria-label":"Dismiss",children:"Ã"})]}),U==="state"&&e.jsxs("section",{className:"exc-section",children:[e.jsx("div",{className:"exc-section__head",children:e.jsx("span",{className:"exc-section__title",children:"Which state is this certificate for?"})}),D&&e.jsx("div",{className:"exc-banner exc-banner--error",children:e.jsx("span",{children:D})}),e.jsx("div",{className:"exc-form-grid",children:e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"State"}),e.jsx("select",{className:"exc-select",value:V,onChange:s=>xe(s.target.value),"data-testid":"prepare-state-select",children:o.map(s=>e.jsxs("option",{value:s.code,children:[s.code," â ",s.name]},s.code))})]})}),!g&&!D&&e.jsx("p",{className:"exc-section__hint",children:"Checking form availabilityâ¦"}),g&&e.jsxs("div",{className:"exc-state-option is-selected","data-testid":"prepare-state-availability",children:[e.jsxs("span",{children:[e.jsx("span",{className:"exc-cell-strong",children:z(V)}),ve&&e.jsxs("span",{className:"exc-cell-sub",children:["Form ",ve,B?.revision??Z?.revision_code?` (rev. ${B?.revision??Z?.revision_code})`:""]})]}),A&&it[A]?e.jsx("span",{className:it[A].className,"data-testid":"prepare-support-chip",children:it[A].label}):re?e.jsx("span",{className:"exc-chip exc-chip--success",children:"Generation supported"}):e.jsx("span",{className:"exc-chip exc-chip--warning",children:"Generation not available"})]}),g&&B?.explanation&&e.jsx("p",{className:"exc-section__hint","data-testid":"prepare-support-explanation",children:B.explanation}),g&&!re&&A!=="no_sales_tax"&&e.jsx("div",{className:"exc-banner exc-banner--info","data-testid":"prepare-unsupported-guidance",children:e.jsx("span",{children:B?.explanation?e.jsxs(e.Fragment,{children:[B.explanation," ",A==="dor_issued"&&B.source_url&&e.jsx("a",{href:B.source_url,target:"_blank",rel:"noreferrer",className:"exc-link","data-testid":"prepare-support-source-link",children:"State form page"})," ","Uploaded certificates get the same tracking, expiration, and coverage matching."]}):e.jsxs(e.Fragment,{children:["In-app generation is not built for ",z(V)," yet",Z?.form_number?` (form ${Z.form_number})`:"",". Complete the state form outside the platform and upload the signed copy instead â it gets the same tracking, expiration, and coverage matching."]})})}),e.jsxs("div",{className:"exc-modal__actions",children:[g&&!re&&A!=="no_sales_tax"&&O&&e.jsx("button",{type:"button",className:"exc-btn exc-btn--secondary",onClick:()=>{d(),O()},"data-testid":"prepare-upload-instead",children:"Upload an existing certificate"}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--primary",disabled:!g||!re,onClick:Oe,"data-testid":"prepare-continue-state",children:"Continue"})]})]}),U==="details"&&e.jsxs("section",{className:"exc-section",children:[e.jsxs("div",{className:"exc-section__head",children:[e.jsxs("span",{className:"exc-section__title",children:["Certificate details â ",z(V)]}),ve&&e.jsxs("span",{className:"exc-chip exc-chip--muted",children:["Form ",ve]})]}),e.jsxs("div",{className:"exc-form-grid",children:[e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Vendor name *"}),e.jsx("input",{className:"exc-input",value:u.vendorName,required:!0,onChange:s=>N({...u,vendorName:s.target.value}),"data-testid":"prepare-vendor-name"})]}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Purchaser (your business) *"}),e.jsx("input",{className:"exc-input",value:u.purchaserName,required:!0,onChange:s=>N({...u,purchaserName:s.target.value}),"data-testid":"prepare-purchaser-name"})]}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Business type"}),e.jsx("input",{className:"exc-input",value:u.businessType,onCh
1ange:s=>N({...u,businessType:s.target.value})})]}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Tax ID"}),e.jsx("input",{className:"exc-input",value:u.taxId,onChange:s=>N({...u,taxId:s.target.value})})]}),e.jsx(It,{className:"exc-field",inputClassName:"exc-input",label:"Street address",value:u.streetAddress,onValueChange:s=>N(c=>({...c,streetAddress:s})),onAddressSelected:s=>N(c=>({...c,streetAddress:s.addressLine1||c.streetAddress,city:s.city||c.city,state:s.state||c.state,zip:s.zipCode||c.zip}))}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"City"}),e.jsx("input",{className:"exc-input",value:u.city,onChange:s=>N({...u,city:s.target.value})})]}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"State"}),e.jsx("select",{className:"exc-select",value:u.state,onChange:s=>N({...u,state:s.target.value}),children:Be.map(s=>e.jsx("option",{value:s.iso_code,children:s.iso_code},s.iso_code))})]}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"ZIP"}),e.jsx("input",{className:"exc-input",value:u.zip,onChange:s=>N({...u,zip:s.target.value})})]}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Exemption reason *"}),e.jsx("input",{className:"exc-input",value:u.exemptionReason,required:!0,placeholder:"e.g. resale, manufacturing",onChange:s=>N({...u,exemptionReason:s.target.value}),"data-testid":"prepare-exemption-reason"})]}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Signer title"}),e.jsx("input",{className:"exc-input",value:u.signerTitle,onChange:s=>N({...u,signerTitle:s.target.value})})]})]}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Description of property / use"}),e.jsx("textarea",{className:"exc-input",rows:3,value:u.description,onChange:s=>N({...u,description:s.target.value})})]}),e.jsxs("div",{className:"exc-modal__actions",children:[e.jsx("button",{type:"button",className:"exc-btn exc-btn--secondary",disabled:v,onClick:()=>q("state"),children:"Back"}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--primary",disabled:v||!u.vendorName.trim()||!u.purchaserName.trim()||!u.exemptionReason.trim(),onClick:()=>{Me()},"data-testid":"prepare-generate",children:v?"Generatingâ¦":x?"Regenerate preview":"Generate preview"})]})]}),U==="preview"&&e.jsxs("section",{className:"exc-section",children:[e.jsxs("div",{className:"exc-section__head",children:[e.jsx("span",{className:"exc-section__title",children:"Preview the filled form"}),x?.uid&&e.jsx("span",{className:"exc-chip exc-chip--muted",children:x.uid})]}),Q?e.jsx("p",{className:"exc-section__hint",children:"Loading previewâ¦"}):te?e.jsx("iframe",{className:"exc-preview-frame",src:`${te}#toolbar=0&navpanes=0&view=FitH`,title:"Certificate preview","data-testid":"prepare-preview-frame"}):e.jsx("p",{className:"exc-section__hint",children:"No preview available yet â go back and generate the form."}),e.jsxs("div",{className:"exc-modal__actions",children:[e.jsx("button",{type:"button",className:"exc-btn exc-btn--secondary",disabled:v||Ie,onClick:()=>q("details"),children:"Back to details"}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--primary",disabled:!te||v,onClick:Ke,"data-testid":"prepare-continue-sign",children:"Continue to sign"})]})]}),U==="sign"&&e.jsxs("section",{className:"exc-section",children:[e.jsx("div",{className:"exc-section__head",children:e.jsx("span",{className:"exc-section__title",children:"Sign the certificate"})}),Ie?e.jsx("div",{className:"exc-banner exc-banner--info",children:e.jsx("span",{children:"This certificate is already signed; the signed PDF is immutable. Void it and prepare a replacement to make changes."})}):e.jsxs(e.Fragment,{children:[e.jsx(Dt,{onSignatureChange:w,disabled:v}),e.jsx("div",{className:"exc-form-grid",children:e.jsxs("label",{className:"exc-field",style:{maxWidth:220},children:[e.jsx("span",{children:"Signature date"}),e.jsx("input",{type:"date",className:"exc-input",value:k,onChange:s=>E(s.target.value),"data-testid":"prepare-signature-date"})]})}),je?e.jsxs("p",{className:"exc-section__hint",children:["This form requires placement on page ",ye,". Place both the signature and date on the preview."]}):e.jsxs("label",{className:"exc-field",style:{flexDirection:"row",alignItems:"center",gap:8,display:"flex"},children:[e.jsx("input",{type:"checkbox",checked:oe,disabled:!i,onChange:s=>{me(s.target.checked),s.target.checked||ge(null)},"data-testid":"prepare-manual-placement"}),e.jsx("span",{children:"Place signature manually on the document"})]}),oe&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"exc-item__actions",children:[e.jsx("button",{type:"button",className:`exc-btn exc-btn--sm ${he==="signature"?"exc-btn--primary":"exc-btn--secondary"}`,onClick:()=>ge("signature"),"data-testid":"placement-mode-signature",children:G?"Signature placed â":"Click to place signature"}),e.jsx("button",{type:"button",className:`exc-btn exc-btn--sm ${he==="date"?"exc-btn--primary":"exc-btn--secondary"}`,onClick:()=>ge("date"),"data-testid":"placement-mode-date",children:X?"Date placed â":"Click to place date"}),e.jsx("button",{type:"button",className:"exc-link",onClick:()=>{Ee(null),fe(null)},children:"Clear placements"})]}),e.jsx("div",{className:"exc-place-scroll",children:te?e.jsxs("div",{className:"exc-place-frame",children:[e.jsx("iframe",{src:`${te}#page=${ye}&toolbar=0&navpanes=0&view=FitH`,title:"Placement preview"}),e.jsxs("div",{className:"exc-place-overlay",onClick:He,role:"presentation","data-testid":"placement-overlay",children:[G&&e.jsx("span",{className:"exc-place-marker",style:{left:G.x,top:792-G.y},children:"Signature"}),X&&e.jsx("span",{className:"exc-place-marker",style:{left:X.x,top:792-X.y},children:"Date"})]})]}):e.jsx("p",{className:"exc-section__hint",children:"Preview unavailable â generate the form first."})})]})]}),e.jsxs("div",{className:"exc-modal__actions",children:[e.jsx("button",{type:"button",className:"exc-btn exc-btn--secondary",disabled:v,onClick:()=>q("preview"),children:"Back"}),Ie?e.jsx("button",{type:"button",className:"exc-btn exc-btn--primary",onClick:()=>q("send"),children:"Continue to send"}):e.jsx("button",{type:"button",className:"exc-btn exc-btn--primary",disabled:v||!i||!k||!x||je&&(!G||!X),onClick:()=>{Ge()},"data-testid":"prepare-sign-button",children:v?"Signingâ¦":"Sign certificate"})]})]}),U==="send"&&e.jsxs("section",{className:"exc-section",children:[e.jsxs("div",{className:"exc-section__head",children:[e.jsx("span",{className:"exc-section__title",children:"Deliver to the vendor"}),x?.status&&e.jsx("span",{className:"exc-chip exc-chip--muted",children:x.status})]}),Fe==="void"?e.jsx("div",{className:"exc-banner exc-banner--info",children:e.jsx("span",{children:"This certificate has been voided."})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"exc-item__actions",children:e.jsx("button",{type:"button",className:"exc-link",onClick:Se,"data-testid":"prepare-download-signed",children:"Download signed PDF"})}),e.jsx("div",{className:"exc-form-grid",children:e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Vendor email *"}),e.jsx("input",{className:"exc-input",type:"email",value:Y,required:!0,placeholder:"[email protected]",onChange:s=>ue(s.target.value),"data-testid":"prepare-send-email"})]})}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Message (optional)"}),e.jsx("textarea",{className:"exc-input",rows:3,value:ae,onChange:s=>ce(s.target.value),"data-testid":"prepare-send-message"})]}),W&&e.jsx("div",{className:"exc-banner exc-banner--success","data-testid":"prepare-send-result",children:e.jsxs("span",{children:["Delivered to ",W.sent_to_email,W.sent_at?` at ${et(W.sent_at)}`:""," ","(send #",W.send_count??1,")."]})}),x?.sent_at!=null&&!W&&e.jsxs("p",{className:"exc-section__hint",children:["Previously sent to ",String(x.sent_to_email??"the vendor")," at ",et(String(x.sent_at)),x.send_count!=null?` (${String(x.send_count)} send${Number(x.send_count)===1?"":"s"})`:"","."]})]}),Le&&e.jsxs("div",{className:"exc-confirm","data-testid":"prepare-void-confirm",children:[e.jsx("span",{children:"Void this certificate? It becomes terminal and stops providing exemption coverage."}),e.jsxs("div",{className:"exc-confirm__actions",children:[e.jsx("button",{type:"button",className:"exc-btn exc-btn--secondary exc-btn--sm",disabled:v,onClick:()=>we(!1),children:"Cancel"}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--danger exc-btn--sm",disabled:v,onClick:()=>{We()},"data-testid":"prepare-void-go",children:v?"Voidingâ¦":"Void certificate"})]})]}),e.jsxs("div",{className:"exc-modal__actions",children:[Fe!=="void"&&e.jsx("button",{type:"button",className:"exc-link exc-link--danger",disabled:v,onClick:()=>we(!0),"data-testid":"prepare-void",children:"Voidâ¦"}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--secondary",onClick:d,children:"Done"}),Fe!=="void"&&e.jsx("button",{type:"button",className:"exc-btn exc-btn--primary",disabled:v||!Y.trim(),onClick:()=>{qe()},"data-testid":"prepare-send-button",children:v?"Sendingâ¦":W||x?.sent_at?"Send again":"Send certificate"})]})]})]})]}),e.jsx(_t,{request:h.pending,onDecision:h.decide})]})}const mt={extraction:"Extraction review",matching:"Matching review",missing_info:"Missing info"};function Qe(r){const _=r.state_specific_fields;return _&&typeof _=="object"?_:{}}const ht=200;function Mt({orgId:r,locationId:_,onOpenDetail:b,refreshNonce:$=0,onChanged:L}){const[p,d]=n.useState("extraction"),[f,O]=n.useState([]),[U,q]=n.useState([]),[x,T]=n.useState([]),[M,P]=n.useState(!0),[ee,R]=n.useState(null),[v,I]=n.useState(null),[h,g]=n.useState(null),[j,D]=n.useState(null),[K,V]=n.useState(0),xe=n.useCallback(async()=>
1{if(r!=null){P(!0),R(null);try{const[i,w]=await Promise.all([rt.listMatches({orgId:r,locationId:_,counterpartyRole:"vendor"}),C.search({org_id:r,..._!=null?{location_id:_}:{},limit:ht,offset:0})]);O(Array.isArray(i)?i:[]);const k=w?.certificates??[];q(k.filter(E=>(E.status||"").toLowerCase()==="pending")),T(k.filter(E=>{const oe=(E.status||"").toLowerCase();return oe==="deleted"||oe==="void"?!1:!E.vendor_name||!E.effective_to}))}catch(i){R(S(i,"Failed to load review queues"))}finally{P(!1)}}},[r,_]);n.useEffect(()=>{xe()},[xe,$,K]);const u=()=>V(i=>i+1),N=async(i,w)=>{if(r!=null){g(i.id),R(null);try{await rt.decideMatch(i.id,w?{confirmed:!0,alias_name:i.counterparty_name||void 0}:{confirmed:!1},{orgId:r,locationId:_}),I(w?"Match confirmed.":"Match rejected."),L?.(),u()}catch(k){R(S(k,"Failed to save match decision"))}finally{g(null)}}},te=async(i,w)=>{D(i.id),R(null);try{await C.update(i.id,{status:w?"active":"void"}),I(w?"Certificate approved and activated.":"Certificate rejected (voided)."),L?.(),u()}catch(k){R(S(k,"Failed to save extraction review decision"))}finally{D(null)}},H=[{key:"vendor",header:"Vendor",sortValue:i=>i.vendor_name||"",render:i=>e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"exc-cell-strong",children:i.vendor_name||e.jsx("span",{className:"exc-cell-warning",children:"Unknown"})}),i.uid&&e.jsx("span",{className:"exc-cell-sub",children:i.uid})]})},{key:"jurisdiction",header:"Jurisdiction",sortValue:i=>i.state_code??"",render:i=>i.state_code||"â"},{key:"confidence",header:"Confidence",align:"center",sortValue:i=>Qe(i).overall_confidence??null,render:i=>{const w=Qe(i).overall_confidence;return typeof w=="number"?e.jsx(lt,{value:w}):"â"}},{key:"deficiencies",header:"Deficiencies",sortValue:i=>(Qe(i).deficiencies??[]).length,render:i=>{const w=Qe(i).deficiencies??[];return w.length===0?e.jsx("span",{className:"exc-cell-muted",children:kt(Qe(i))}):e.jsxs("span",{className:"exc-actions-cell",children:[w.slice(0,2).map((k,E)=>e.jsx("span",{className:"exc-chip exc-chip--warning",title:k.description||k.code,children:ot(k.code)},`${k.code}-${k.field??E}`)),w.length>2&&e.jsxs("span",{className:"exc-cell-sub",children:["+",w.length-2," more"]})]})}},{key:"status",header:"Status",sortValue:i=>i.status??"",render:i=>e.jsx(ct,{status:i.status,fixedWidth:!0})},{key:"created",header:"Uploaded",sortValue:i=>i.created_at??"",render:i=>$e(i.created_at)},{key:"actions",header:"Actions",align:"right",interactive:!0,render:i=>e.jsxs("span",{className:"exc-actions-cell",children:[e.jsx("button",{type:"button",className:"exc-link",onClick:()=>b(i.id),"data-testid":`pq-extraction-open-${i.id}`,children:"Open"}),e.jsx("button",{type:"button",className:"exc-link",disabled:j===i.id,onClick:()=>{te(i,!0)},"data-testid":`pq-extraction-approve-${i.id}`,children:j===i.id?"Savingâ¦":"Approve"}),e.jsx("button",{type:"button",className:"exc-link exc-link--danger",disabled:j===i.id,onClick:()=>{te(i,!1)},"data-testid":`pq-extraction-reject-${i.id}`,children:"Reject"})]})}],se=[{key:"vendor",header:"Vendor",sortValue:i=>i.counterparty_name??"",render:i=>e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"exc-cell-strong",children:i.counterparty_name||"Unknown"}),e.jsxs("span",{className:"exc-cell-sub",children:[i.source_module," · ",i.source_record_type," #",i.source_record_id]})]})},{key:"jurisdiction",header:"Jurisdiction",sortValue:i=>i.jurisdiction_code??"",render:i=>i.jurisdiction_code||"â"},{key:"reason",header:"Review reason",sortValue:i=>i.review_reason??"",render:i=>ot(i.review_reason||i.match_method||"review needed")},{key:"confidence",header:"Confidence",align:"center",sortValue:i=>i.confidence??null,render:i=>e.jsx(lt,{value:i.confidence})},{key:"date",header:"Txn date",sortValue:i=>i.transaction_date??"",render:i=>$e(i.transaction_date)},{key:"actions",header:"Actions",align:"right",interactive:!0,render:i=>e.jsxs("span",{className:"exc-actions-cell",children:[i.source_certificate_id!=null&&e.jsx("button",{type:"button",className:"exc-link",onClick:()=>b(Number(i.source_certificate_id)),children:"Certificate"}),e.jsx("button",{type:"button",className:"exc-link",disabled:h===i.id,onClick:()=>
1{N(i,!0)},"data-testid":`pq-match-confirm-${i.id}`,children:h===i.id?"Savingâ¦":"Confirm"}),e.jsx("button",{type:"button",className:"exc-link exc-link--danger",disabled:h===i.id,onClick:()=>{N(i,!1)},"data-testid":`pq-match-reject-${i.id}`,children:"Reject"})]})}],Q=[{key:"vendor",header:"Vendor",sortValue:i=>i.vendor_name||"",render:i=>e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"exc-cell-strong",children:i.vendor_name||e.jsx("span",{className:"exc-cell-warning",children:"Missing"})}),i.uid&&e.jsx("span",{className:"exc-cell-sub",children:i.uid})]})},{key:"jurisdiction",header:"Jurisdiction",sortValue:i=>i.state_code??"",render:i=>i.state_code||"â"},{key:"missing",header:"Missing",render:i=>e.jsxs("span",{className:"exc-actions-cell",children:[!i.vendor_name&&e.jsx("span",{className:"exc-chip exc-chip--warning",children:"Vendor name"}),!i.effective_to&&e.jsx("span",{className:"exc-chip exc-chip--warning",children:"Expiration date"})]})},{key:"status",header:"Status",sortValue:i=>i.status??"",render:i=>e.jsx(ct,{status:i.status,fixedWidth:!0})},{key:"created",header:"Created",sortValue:i=>i.created_at??"",render:i=>$e(i.created_at)},{key:"actions",header:"Actions",align:"right",interactive:!0,render:i=>e.jsx("button",{type:"button",className:"exc-link",onClick:()=>b(i.id),"data-testid":`pq-missing-open-${i.id}`,children:"Fix"})}],ke={extraction:U.length,matching:f.length,missing_info:x.length};return e.jsxs("div",{className:"exc-queues","data-testid":"purchasing-review-panel",children:[e.jsx("div",{className:"exc-queue-tabs",role:"tablist","aria-label":"Purchasing review queues",children:Object.keys(mt).map(i=>e.jsxs("button",{type:"button",role:"tab","aria-selected":p===i,className:`exc-queue-tab${p===i?" is-active":""}`,onClick:()=>d(i),"data-testid":`pq-tab-${i}`,children:[mt[i],e.jsx("span",{className:"exc-tab__count",children:ke[i]})]},i))}),v&&e.jsxs("div",{className:"exc-banner exc-banner--success",children:[e.jsx("span",{children:v}),e.jsx("button",{type:"button",className:"exc-banner__dismiss",onClick:()=>I(null),"aria-label":"Dismiss",children:"Ã"})]}),p==="extraction"&&e.jsx(Ze,{tableTestId:"pq-extraction-table",columns:H,rows:U,rowKey:i=>String(i.id),loading:M,error:ee,onRetry:u,emptyTitle:"No uploads waiting on extraction review",emptyBody:"Certificates requiring human review, including structured JSON evidence, appear here.",onOpenDetail:i=>b(i.id)}),p==="matching"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:["This queue contains saved certificate-match decisions. Calculation can also flag purchase lines with multiple plausible candidates before a decision record exists; those lines are not included in this count. ",e.jsx(vt,{to:"/purchasing-tax-compliance?view=calculation",children:"Review purchase lines in Calculation"})," and use Review match on the affected line. Pending certificates remain subject to approval."]}),e.jsx(Ze,{tableTestId:"pq-matching-table",columns:se,rows:f,rowKey:i=>String(i.id),loading:M,error:ee,onRetry:u,emptyTitle:"No saved vendor-match decisions waiting on review",emptyBody:"This does not mean every purchase line has a resolved certificate match. Review candidate ambiguity in Purchasing Calculation."})]}),p==="missing_info"&&e.jsx(Ze,{tableTestId:"pq-missing-table",columns:Q,rows:x,rowKey:i=>String(i.id),loading:M,error:ee,onRetry:u,emptyTitle:"Every certificate has vendor and expiration details",emptyBody:`Certificates missing a vendor name or expiration date appear here (newest ${ht} scanned).`,onOpenDetail:i=>b(i.id)})]})}const Vt=[{id:"forms",label:"State Forms",icon:"fas fa-file-alt"},{id:"organization",label:"Organization",icon:"fas fa-building"},{id:"account",label:"Account",icon:"fas fa-user"},{id:"expiration",label:"Expiration",icon:"fas fa-clock"},{id:"formConfig",label:"Form Fields",icon:"fas fa-cog"}],$t=[{key:"organization_name",label:"Organization name"},{key:"business_type",label:"Business type"},{key:"tax_id",label:"Tax ID"},{key:"industry",label:"Industry"},{key:"address_line1",label:"Address line 1"},{key:"address_line2",label:"Address line 2"},{key:"city",label:"City"},{key:"state",label:"State"},{key:"zip_code",label:"ZIP code"},{key:"phone",label:"Phone"},{key:"email",label:"Email"},{key:"website",label:"Website"},{key:"default_exemption_reason",label:"Default exemption reason"},{key:"default_signer_title",label:"Default signer title"}];function Ot({open:r,onClose:_,orgId:b,locationId:$,onDataChanged:L}){const{showToast:p}=gt(),[d,f]=n.useState("forms"),O=n.useMemo(()=>{const a={};return b!=null&&(a.org_id=b),$!=null&&(a.location_id=$),a},[b,$]),[U,q]=n.useState([]),[x,T]=n.useState(""),[M,P]=n.useState([]),[ee,R]=n.useState(!1),[v,I]=n.useState(null),[h,g]=n.useState(null),[j,D]=n.useState(!1),[K,V]=n.useState(!1),xe=n.useCallback(async()=>{R(!0);try{const[a,l]=await Promise.all([Je.getForms(),Je.getStates()]);q(a||[]),P(l||[])}catch(a){p({title:"Failed to load forms",message:S(a,"Request failed"),variant:"error"})}finally{R(!1)}},[p]);n.useEffect(()=>{r&&d==="forms"&&xe()},[r,d,xe]);const u=n.useMemo(()=>wt(U,x),[U,x]),N=async(a,l)=>{try{const y=await Je.getFormComplete(a);l==="details"?I(y):g(y)}catch(y){p({title:"Failed to load form",message:S(y,"Request failed"),variant:"error"})}},te=async()=>{D(!1),V(!0);try{const a=await Je.getStates();let l=0,y=0;for(const J of a||[])try{await Je.importForms(J.code),l+=1}catch{y+=1}p({message:`Updated ${l} states${y?`, ${y} errors`:""}.`,variant:y?"warning":"success"}),await xe()}catch(a){p({title:"Failed to update states",message:S(a,"Request failed"),variant:"error"})}finally{V(!1)}},[H,se]=n.useState({}),[Q,ke]=n.useState(!1),[i,w]=n.useState(!1),[k,E]=n.useState(!1),[oe,me]=n.useState(!1),[he,ge]=n.useState(!1);n.useEffect(()=>{!r||d!=="organization"||C.getOrganizationSettings().then(a=>{se(a??{}),w(!!a?.enable_ec_validation_logging)}
1).catch(()=>{})},[r,d]);const G=async a=>{a.preventDefault(),ke(!0);try{await C.saveOrganizationSettings(H),p({message:"Organization settings saved",variant:"success"})}catch(l){p({title:"Failed to save settings",message:S(l,"Request failed"),variant:"error"})}finally{ke(!1)}},Ee=async a=>{const l=i;w(a),E(!0);try{await C.saveOrganizationSettings({enable_ec_validation_logging:a}),p({message:a?"Validation logging enabled":"Validation logging disabled",variant:"success"})}catch(y){w(l),p({title:"Could not update setting",message:S(y,"Save failed"),variant:"error"})}finally{E(!1)}},X=async()=>{me(!1),ge(!0);try{await C.emptyTrash(O),p({message:"Trash emptied",variant:"success"}),L()}catch(a){p({title:"Failed to empty trash",message:S(a,"Request failed"),variant:"error"})}finally{ge(!1)}},[fe,Te]=n.useState(null),[De,de]=n.useState(""),[Y,ue]=n.useState(!1),[ae,ce]=n.useState(""),[W,_e]=n.useState(""),[Le,we]=n.useState(""),[Fe,Ie]=n.useState(!1);n.useEffect(()=>{!r||d!=="account"||nt.getMe().then(a=>{Te(a),de(a?.full_name||"")}).catch(()=>{})},[r,d]);const Pe=async()=>{const a=De.trim();if(!a){p({message:"Full name cannot be empty",variant:"warning"});return}ue(!0);try{const l=await nt.updateMe({full_name:a});Te(l),p({message:"Profile updated",variant:"success"})}catch(l){p({title:"Failed to update profile",message:S(l,"Request failed"),variant:"error"})}finally{ue(!1)}},Ae=async()=>{if(W!==Le){p({message:"New password and confirmation do not match",variant:"warning"});return}if(W.length<8){p({message:"New password must be at least 8 characters",variant:"warning"});return}Ie(!0);try{await nt.changePassword({old_password:ae,new_password:W,confirm_new_password:Le}),ce(""),_e(""),we(""),p({message:"Password updated",variant:"success"})}catch(a){p({title:"Failed to change password",message:S(a,"Request failed"),variant:"error"})}finally{Ie(!1)}},[Z,B]=n.useState(90),[A,be]=n.useState([]),[re,ve]=n.useState(""),[le,je]=n.useState(!1),[ye,z]=n.useState(null),[Ue,Ne]=n.useState(24),[Re,Oe]=n.useState(!1),Me=n.useCallback(async()=>{if(b!=null){je(!0);try{const[a,l]=await Promise.all([Ye.getSettings({...O,active_only:!1}),Ye.getThreshold(O).catch(()=>null)]);l?.threshold_days!==void 0?B(l.threshold_days):l?.expiring_threshold_days!==void 0&&B(l.expiring_threshold_days);const y=Array.isArray(a)?a:a?.settings||a?.items||[],J=new Map;for(const ie of y){const ze=ie.state_code||ie.jurisdiction_iso;if(!ze)continue;const tt=J.get(ze)??{state:ze,internal_control:null,state_law:null},st=ie.expiration_type==="internal_control"?"internal_control":ie.expiration_type==="state_law"?"state_law":null;if(st){const at=tt[st];(!at||new Date(ie.updated_at??ie.created_at??0).getTime()>=new Date(at.updated_at??at.created_at??0).getTime())&&(tt[st]=ie)}J.set(ze,tt)}be([...J.values()].sort((ie,ze)=>ie.state.localeCompare(ze.state)))}catch(a){p({title:"Failed to load expiration settings",message:S(a,"Request failed"),variant:"error"})}finally{je(!1)}}},[b,O,p]);n.useEffect(()=>{r&&d==="expiration"&&Me()},[r,d,Me]);const Ke=async()=>{try{await Ye.updateThreshold(Z,O),p({message:"Threshold saved",variant:"success"}),L()}catch(a){p({title:"Failed to save threshold",message:S(a,"Request failed"),variant:"error"})}},He=(a,l,y)=>{z(`${a}:${l}`),Oe(y?.has_expiration??!1),Ne(typeof y?.expiration_months=="number"?y.expiration_months:24)},Ge=async()=>{if(!ye)return;const[a,l]=ye.split(":");try{await Ye.updateStateSetting(a,{expiration_type:l,has_expiration:Re,expiration_months:Re?Ue:null,expiration_unit:"months"},O),z(null),p({message:"Expiration setting saved",variant:"success"}),await Me(),L()}catch(y){p({title:"Failed to save expiration setting",message:S(y,"Request failed"),variant:"error"})}},qe=n.useMemo(()=>re?A.filter(a=>a.state.toLowerCase().includes(re.toLowerCase())):A,[A,re]),We=a=>a?a.has_expiration?`${a.expiration_months??"?"} months`:"No expiration":"â",[Se,Ve]=n.useState("OH"),[t,o]=n.useState({}),[s,c]=n.useState(!1),[m,F]=n.useState(!1),[ne,pe]=n.useState("");n.useEffect(()=>{!r||d!=="formConfig"||(c(!0),C.getFormConfig(Se).then(a=>o(a?.field_mapping??{})).catch(()=>o({})).finally(()=>c(!1)))},[r,d,Se]);const Ce=async()=>{F(!0);try{await C.updateFormConfig(Se,{state_code:Se,field_mapping:t}),p({message:"Form configuration saved",variant:"success"})}catch(a){p({title:"Failed to save form configuration",message:S(a,"Request failed"),variant:"error"})}finally{F(!1)}};return r?e.jsxs(e.Fragment,{children:[e.jsxs(Ft,{open:r,title:"Purchasing Exemption Settings",subtitle:"State forms, organization defaults, expiration policy, and renderer field mappings.",sections:Vt,activeSection:d,onSelectSection:a=>f(a),onClose:_,children:[d==="forms"&&e.jsxs("div",{className:"exc-stack exc-stack--lg",children:[e.jsxs("div",{className:"exc-toolbar",children:[e.jsxs("select",{className:"exc-select",value:x,"aria-label":"Filter forms by state",onCh
1ange:a=>T(a.target.value),children:[e.jsx("option",{value:"",children:"All states"}),e.jsx("option",{value:"__reference__",children:"Reference templates / unverified forms"}),M.filter(a=>Pt(a.code??a.iso_code)).map(a=>e.jsxs("option",{value:a.code??a.iso_code,children:[a.code??a.iso_code," â ",a.name]},a.code??a.iso_code))]}),e.jsx("span",{className:"exc-toolbar__spacer"}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--secondary exc-btn--sm",disabled:K,onClick:()=>D(!0),children:K?"Updatingâ¦":"Update all states"})]}),j&&e.jsxs("div",{className:"exc-confirm exc-confirm--neutral",children:[e.jsx("span",{children:"Re-import forms for every state? This may take a while."}),e.jsxs("div",{className:"exc-confirm__actions",children:[e.jsx("button",{type:"button",className:"exc-btn exc-btn--secondary exc-btn--sm",onClick:()=>D(!1),children:"Cancel"}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--primary exc-btn--sm",onClick:()=>{te()},children:"Continue"})]})]}),e.jsx("section",{className:"exc-table-card",children:e.jsx("div",{className:"exc-table-scroll",children:e.jsxs("table",{className:"exc-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"State"}),e.jsx("th",{children:"Form"}),e.jsx("th",{children:"Code"}),e.jsx("th",{children:"Version"}),e.jsx("th",{children:"Updated"}),e.jsx("th",{className:"exc-num",children:"Actions"})]})}),e.jsx("tbody",{children:ee?e.jsx("tr",{children:e.jsx("td",{colSpan:6,children:e.jsx("div",{className:"exc-loading",children:"Loading formsâ¦"})})}):u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,children:e.jsxs("div",{className:"exc-empty",children:[e.jsx("p",{className:"exc-empty__title",children:"No forms found"}),e.jsx("p",{children:"No supported forms are available in this view. Check another jurisdiction or the reference-template view; an empty list does not establish exemption eligibility."})]})})}):u.map(a=>{const l=String(a.id??a.form_id??"");return e.jsxs("tr",{children:[e.jsx("td",{children:a.state_code||a.jurisdiction_iso||"â"}),e.jsx("td",{children:e.jsx("span",{className:"exc-cell-strong",children:a.name||a.form_name||a.official_legal_name||"â"})}),e.jsx("td",{children:a.code||a.form_number||"â"}),e.jsx("td",{children:String(a.version??a.revision??"â")}),e.jsx("td",{children:e.jsx("span",{className:"exc-cell-nowrap",children:$e(a.updated_at??a.created_at)})}),e.jsx("td",{className:"exc-num",children:e.jsxs("span",{className:"exc-actions-cell",children:[e.jsx("button",{type:"button",className:"exc-link",onClick:()=>{N(l,"details")},children:"Details"}),e.jsx("button",{type:"button",className:"exc-link",onClick:()=>{N(l,"schema")},children:"Schema"})]})})]},l||`${a.state_code}-${a.code}`)})})]})})})]}),d==="organization"&&e.jsxs("div",{className:"exc-stack exc-stack--lg",children:[e.jsxs("form",{onSubmit:a=>{G(a)},className:"exc-stack",children:[e.jsx("div",{className:"exc-form-grid",children:$t.map(({key:a,label:l})=>e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:l}),e.jsx("input",{className:"exc-input",value:String(H[a]??""),onChange:y=>se(J=>({...J,[a]:y.target.value}))})]},String(a)))}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Description"}),e.jsx("textarea",{className:"exc-input",rows:2,value:String(H.description??""),onChange:a=>se(l=>({...l,description:a.target.value}))})]}),e.jsx("div",{className:"exc-modal__actions",children:e.jsx("button",{type:"submit",className:"exc-btn exc-btn--primary",disabled:Q,children:Q?"Savingâ¦":"Save organization defaults"})})]}),e.jsxs("section",{className:"exc-section",children:[e.jsx("div",{className:"exc-section__head",children:e.jsx("span",{className:"exc-section__title",children:"Validation logging"})}),e.jsxs("label",{className:"exc-field",style:{flexDirection:"row",display:"flex",alignItems:"center",gap:8},children:[e.jsx("input",{type:"checkbox",checked:i,disabled:k,onChange:a=>{Ee(a.target.checked)}}),e.jsx("span",{children:"Record certificate validation decisions to the EC validation log"})]})]}),e.jsxs("section",{className:"exc-section",children:[e.jsx("div",{className:"exc-section__head",children:e.jsx("span",{className:"exc-section__title",children:"Trash"})}),e.jsx("p",{className:"exc-section__hint",children:"Permanently removes every deleted purchasing certificate in the current scope."}),oe?e.jsxs("div",{className:"exc-confirm",children:[e.jsx("span",{children:"Permanently delete ALL purchasing certificates in trash? This cannot be undone."}),e.jsxs("div",{className:"exc-confirm__actions",children:[e.jsx("button",{type:"button",className:"exc-btn exc-btn--secondary exc-btn--sm",onClick:()=>me(!1),children:"Cancel"}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--danger exc-btn--sm",disabled:he,onClick:()=>{X()},children:he?"Deletingâ¦":"Empty trash"})]})]}):e.jsx("button",{type:"button",className:"exc-btn exc-btn--danger exc-btn--sm",onClick:()=>me(!0),children:"Empty trashâ¦"})]})]}),d==="account"&&e.jsxs("div",{className:"exc-stack exc-stack--lg",children:[e.jsxs("section",{className:"exc-section",children:[e.jsx("div",{className:"exc-section__head",children:e.jsx("span",{className:"exc-section__title",children:"Profile"})}),e.jsxs("div",{className:"exc-form-grid",children:[e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Email"}),e.jsx("input",{className:"exc-input",value:fe?.email??"",readOnly:!0,disabled:!0})]}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Full name"}),e.jsx("input",{className:"exc-input",value:De,onChange:a=>de(a.target.value)})]})]}),e.jsx("div",{className:"exc-modal__actions",children:e.jsx("button",{type:"button",className:"exc-btn exc-btn--primary",disabled:Y,onClick:()=>{Pe()},children:Y?"Savingâ¦":"Save profile"})})]}),e.jsxs("section",{className:"exc-section",children:[e.jsx("div",{className:"exc-section__head",children:e.jsx("span",{className:"exc-section__title",children:"Change password"})}),e.jsxs("div",{className:"exc-form-grid",children:[e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Current password"}),e.jsx("input",{className:"exc-input",type:"password",value:ae,onChange:a=>ce(a.target.value),autoComplete:"current-password"})]}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"New password"}),e.jsx("input",{className:"exc-input",type:"password",value:W,onChange:a=>_e(a.target.value),autoComplete:"new-password"})]}),e.jsxs("label",{className:"exc-field",children:[e.jsx("span",{children:"Confirm new password"}),e.jsx("input",{className:"exc-input",type:"password",value:Le,onChange:a=>we(a.target.value),autoComplete:"new-password"})]})]}),e.jsx("div",{className:"exc-modal__actions",children:e.jsx("button",{type:"button",className:"exc-btn exc-btn--primary",disabled:Fe||!ae||!W||!Le,onClick:()=>{Ae()},children:Fe?"Updatingâ¦":"Change password"})})]})]}),d==="expiration"&&e.jsxs("div",{className:"exc-stack exc-stack--lg",children:[e.jsxs("section",{className:"exc-section",children:[e.jsx("div",{className:"exc-section__head",children:e.jsx("span",{className:"exc-section__title",children:"Expiring-soon threshold"})}),e.jsxs("div",{className:"exc-toolbar",children:[e.jsx("input",{type:"number",min:1,
1className:"exc-input",style:{maxWidth:120},value:Z,"aria-label":"Expiring threshold in days",onChange:a=>B(parseInt(a.target.value,10)||90)}),e.jsx("span",{className:"exc-cell-muted",children:'days before expiration counts as "expiring"'}),e.jsx("span",{className:"exc-toolbar__spacer"}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--primary exc-btn--sm",onClick:()=>{Ke()},children:"Save threshold"})]})]}),e.jsxs("section",{className:"exc-section",children:[e.jsxs("div",{className:"exc-section__head",children:[e.jsx("span",{className:"exc-section__title",children:"Per-state expiration policy"}),e.jsx("input",{type:"search",className:"exc-input",style:{maxWidth:180},placeholder:"Filter statesâ¦","aria-label":"Filter states",value:re,onChange:a=>ve(a.target.value)})]}),e.jsx("div",{className:"exc-table-scroll",children:e.jsxs("table",{className:"exc-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"State"}),e.jsx("th",{children:"Internal control"}),e.jsx("th",{children:"State law"})]})}),e.jsx("tbody",{children:le?e.jsx("tr",{children:e.jsx("td",{colSpan:3,children:e.jsx("div",{className:"exc-loading",children:"Loading expiration settingsâ¦"})})}):qe.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:3,children:e.jsx("div",{className:"exc-empty",children:e.jsx("p",{className:"exc-empty__title",children:"No per-state settings yet"})})})}):qe.map(a=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("span",{className:"exc-cell-strong",children:a.state})}),["internal_control","state_law"].map(l=>{const y=`${a.state}:${l}`,J=a[l]??null;return e.jsx("td",{children:ye===y?e.jsxs("span",{className:"exc-kv__edit",children:[e.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx("input",{type:"checkbox",checked:Re,onChange:ie=>Oe(ie.target.checked)}),e.jsx("span",{children:"Expires"})]}),Re&&e.jsx("input",{type:"number",min:1,className:"exc-input",style:{maxWidth:80},value:Ue,"aria-label":"Expiration months",onChange:ie=>Ne(parseInt(ie.target.value,10)||24)}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--primary exc-btn--sm",onClick:()=>{Ge()},children:"Save"}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--secondary exc-btn--sm",onClick:()=>z(null),children:"Cancel"})]}):e.jsxs("span",{className:"exc-actions-cell",children:[e.jsx("span",{children:We(J)}),e.jsx("button",{type:"button",className:"exc-link",onClick:()=>He(a.state,l,J),children:"Edit"})]})},l)})]},a.state))})]})})]})]}),d==="formConfig"&&e.jsxs("div",{className:"exc-stack exc-stack--lg",children:[e.jsxs("div",{className:"exc-toolbar",children:[e.jsx("select",{className:"exc-select",value:Se,"aria-label":"Form config state",onChange:a=>Ve(a.target.value),children:Be.map(a=>e.jsxs("option",{value:a.iso_code,children:[a.iso_code," â ",a.name]},a.iso_code))}),e.jsx("span",{className:"exc-toolbar__spacer"}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--primary exc-btn--sm",disabled:m,onClick:()=>{Ce()},children:m?"Savingâ¦":"Save mapping"})]}),e.jsxs("p",{className:"exc-section__hint",children:["Maps certificate fields to the PDF form field names used when rendering the ",Se," template."]}),s?e.jsx("div",{className:"exc-loading",children:"Loading mappingâ¦"}):e.jsxs("div",{className:"exc-stack exc-stack--sm",children:[Object.entries(t).map(([a,l])=>e.jsxs("div",{className:"exc-toolbar",children:[e.jsx("input",{className:"exc-input",value:a,readOnly:!0,"aria-label":"Certificate field",style:{maxWidth:220}}),e.jsx("input",{className:"exc-input",value:l,"aria-label":`PDF field for ${a}`,onChange:y=>o(J=>({...J,[a]:y.target.value}))}),e.jsx("button",{type:"button",className:"exc-link exc-link--danger",onClick:()=>o(y=>{const J={...y};return delete J[a],J}),children:"Remove"})]},a)),e.jsxs("div",{className:"exc-toolbar",children:[e.jsx("input",{className:"exc-input",placeholder:"New certificate field key",value:ne,"aria-label":"New mapping key",style:{maxWidth:220},onChange:a=>pe(a.target.value)}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--secondary exc-btn--sm",disabled:!ne.trim()||ne.trim()in t,onClick:()=>{o(a=>({...a,[ne.trim()]:""})),pe("")},children:"Add field"})]})]})]})]}),v&&e.jsx("div",{className:"exc-modal-overlay",onClick:()=>I(null),children:e.jsxs("div",{className:"exc-modal",role:"dialog","aria-modal":"true","aria-label":"Form details",onClick:a=>a.stopPropagation(),children:[e.jsxs("div",{className:"exc-modal__header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:v.form?.name||"Form details"}),e.jsxs("p",{className:"exc-modal__sub",children:["Code ",v.form?.code||"â"," · version ",String(v.version?.version??"â")]})]}),e.jsx("button",{type:"button",className:"exc-drawer__close",onClick:()=>I(null),children:"Close"})]}),e.jsxs("div",{className:"exc-modal__body",children:[e.jsxs("div",{className:"exc-kv",children:[e.jsx("span",{className:"exc-kv__label",children:"Sections"}),e.jsx("span",{className:"exc-kv__value",children:v.sections?.length??0})]}),e.jsxs("div",{className:"exc-kv",children:[e.jsx("span",{className:"exc-kv__label",children:"Fields"}),e.jsx("span",{className:"exc-kv__value",children:v.fields?.length??0})]}),e.jsxs("div",{className:"exc-kv",children:[e.jsx("span",{className:"exc-kv__label",children:"Rules"}),e.jsx("span",{className:"exc-kv__value",children:v.rules?.length??0})]}),(v.fields??[]).slice(0,25).map((a,l)=>e.jsxs("div",{className:"exc-kv",children:[e.jsx("span",{className:"exc-kv__label",children:a.label||a.name||`Field ${l+1}`}),e.jsxs("span",{className:"exc-kv__value",children:[a.data_type||"text",a.required_default?" · required":""]})]},String(a.id??l)))]})]})}),h&&e.jsx("div",{className:"exc-modal-overlay",onClick:()=>g(null),children:e.jsxs("div",{className:"exc-modal exc-modal--wide",role:"dialog","aria-modal":"true","aria-label":"Form schema",onClick:a=>a.stopPropagation(),children:[e.jsxs("div",{className:"exc-modal__header",children:[e.jsx("div",{children:e.jsxs("h2",{children:["Schema â ",h.form?.name||"form"]})}),e.jsx("button",{type:"button",className:"exc-drawer__close",onClick:()=>g(null),children:"Close"})]}),e.jsx("div",{className:"exc-modal__body",children:e.jsx("pre",{style:{overflow:"auto",maxHeight:"55vh",fontSize:11},children:JSON.stringify(h,null,2)})})]})})]}):null}const qt={warning:"exc-kpi-card__value--warning",danger:"exc-kpi-card__value--danger",success:"exc-kpi-card__value--success",accent:"exc-kpi-card__value--accent"},zt=["Draft","Prepared","Previewed","Signed","Sent","Resent","Active","Void","Deleted"],Xe=new Set(["signed","sent","resent","active"]),Bt=new Set(["party_id","effective_from","effective_to","signed_by","signer_title"]);function Kt(r){const _=!!(r.output_pdf_s3_uri||r.original_document_s3_uri),b=r.state_specific_fields?.structured_intake;return{cert_id:String(r.id),uid:r.uid,party_id:r.vendor_name||"",jurisdiction_iso:r.state_code,reason_code:r.exemption_reason,form_code:r.form_number,effective_from:r.effective_from,effective_to:r.effective_to,created_at:r.created_at,updated_at:r.updated_at,status:(r.status||"").toLowerCase(),source:r.source,signed_by:r.signed_by,signer_title:r.signer_title,state_specific_fields:r.state_specific_fields,blanket:typeof b?.blanket=="boolean"?b.blanket:void 0,artifacts:_?[{artifact_id:String(r.id),kind:r.output_pdf_s3_uri?"certificate PDF":"original document"}]:[]}}const ss=()=>{const r=jt(),_=yt(),{user:b,isLoading:$}=Nt(),{activeOrganization:L,activeLocation:p}=St(),d=L?.id,f=p?.id,O=L?.name||"Organization",U=p?.name||"Location",{colors:q,theme:x}=Ct(),{showToast:T}=gt(),[M,P]=n.useState("certificates"),[ee,R]=n.useState(null),[v,I]=n.useState(null),[h,g]=n.useState([]),[j,D]=n.useState(0),[K,V]=n.useState(!0),[xe,u]=n.useState(null),[N,te]=n.useState(""),[H,se]=n.useState(""),[Q,ke]=n.useState(""),[i,w]=n.useState(1),k=20,[E,oe]=n.useState(null),[me,he]=n.useState(!0),[ge,G]=n.useState(null),[Ee,X]=n.useState(90),[fe,Te]=n.useState(null),[De,de]=n.useState(null),[Y,ue]=n.useState(null),[ae,ce]=n.useState(null),[W,_e]=n.useState(!1),[Le,we]=n.useState(!1),[Fe,Ie]=n.useState(0),Pe=n.useRef(0),Ae=n.useRef(null),Z=n.useRef(null),B=n.useRef(null),A=n.useCallback(async()=>
1{if(d==null)return;const t=++Pe.current;try{V(!0);const o={org_id:d,limit:k,offset:(i-1)*k};f!=null&&(o.location_id=f),N&&(o.search_term=N),H&&(o.status=H),Q&&(o.jurisdiction_iso=Q);const s=await C.search(o);if(t!==Pe.current)return;const c=s?.certificates??[];g(c),D(s?.total_count??c.length),u(null)}catch(o){t===Pe.current&&u(S(o,"Unable to load purchasing exemption certificates."))}finally{t===Pe.current&&V(!1)}},[d,f,i,N,H,Q]),be=n.useCallback(async()=>{if(d!=null){he(!0);try{const t=await C.getDashboardKpis(d,f??void 0);oe(t),G(null)}catch(t){G(S(t,"Unable to load certificate KPIs."))}finally{he(!1)}}},[d,f]),re=n.useCallback(async()=>{if(d!=null)try{const t={org_id:d};f!=null&&(t.location_id=f);const o=await Ye.getThreshold(t),s=o?.threshold_days??o?.expiring_threshold_days;typeof s=="number"&&X(s)}catch{}},[d,f]),ve=n.useCallback(async()=>{try{const t=await C.getStateForms();Te(t.state_forms??[]),de(null)}catch(t){de(S(t,"Unable to load state form availability."))}},[]),le=n.useCallback(()=>{A(),be(),Ie(t=>t+1)},[A,be]);n.useEffect(()=>{const t=[d??"",f??"",i,k,N,H,Q].join("|");t!==Ae.current&&(Ae.current=t,A())},[d,f,i,N,H,Q,A]),n.useEffect(()=>{const t=`${d??""}|${f??""}`;t!==Z.current&&(Z.current=t,be(),re())},[d,f,be,re]),n.useEffect(()=>{w(1)},[N,H,Q,d,f]),n.useEffect(()=>{const t=localStorage.getItem("purchasingExemptionView");(t==="prepare"||t==="review")&&P(t)},[]),n.useEffect(()=>{M==="prepare"&&fe==null&&ve()},[M,fe,ve]),n.useEffect(()=>
1{const t=new URLSearchParams(r.search),o=t.get("certificateId");if(!o)return;const s=Number(o);if(!Number.isFinite(s))return;const c=t.get("sourceModule"),m=t.get("sourceRecordId");R(c==="ptc"?`Opened from Purchasing Tax Compliance${m?` line ${m}`:""}.`:"Opened from certificate coverage context."),ue(s),_(r.pathname,{replace:!0})},[r.pathname,r.search,_]),n.useEffect(()=>{const t=new URLSearchParams(r.search);if(t.get("certificateId"))return;const o=t.get("sourceModule"),s=t.get("sourceRecordId");if(t.get("prepare")==="1"&&(o!=="ptc"||!s)){ce({}),_(r.pathname,{replace:!0});return}if(o!=="ptc"||!s)return;const c=Number(s);if(!Number.isFinite(c)||c<=0||B.current===c)return;const m=Number(t.get("orgId")||d||""),F=Number(t.get("locationId")||f||"");if(!Number.isFinite(m)||m<=0||!Number.isFinite(F)||F<=0)return;B.current=c;const ne=t.get("returnTo"),pe=t.get("vendorName")||"",Ce=(t.get("stateCode")||"OH").toUpperCase(),a=t.get("reason")||"";I(ne),R(`Preparing a certificate from Purchasing Tax Compliance line ${c}.`),_(r.pathname,{replace:!0}),C.getPtcLinePrefill(c,{org_id:m,location_id:F}).then(l=>{const y=(l.jurisdiction_code||l.purchaser_state||"OH").toUpperCase();ce({initialStep:"details",sourceRecord:{type:"ptc_line",id:c},prefill:{vendorName:l.vendor_name||"",purchaserName:l.purchaser_name||"",businessType:l.purchaser_business_type||"",taxId:l.purchaser_tax_id||"",streetAddress:l.purchaser_street_address||"",city:l.purchaser_city||"",state:(l.purchaser_state||y).toUpperCase(),zip:l.purchaser_zip||"",exemptionReason:l.exemption_reason||"other",description:l.description||"",signerTitle:l.signer_title||"Controller"}}),l.missing_purchaser_fields?.length&&T({title:"Prefill incomplete",message:`Some purchaser details are missing (${l.missing_purchaser_fields.join(", ")}). Review before generating.`,variant:"warning"})}).catch(l=>{ce({initialStep:"details",sourceRecord:{type:"ptc_line",id:c},prefill:{vendorName:pe,state:Ce,description:a,signerTitle:"Controller"}}),T({title:"PTC prefill unavailable",message:S(l,"Prefill failed; starting from organization defaults."),variant:"warning"})})},[d,f,r.pathname,r.search,_,T]);const je=n.useCallback(t=>{const o=(t.status||"").toLowerCase();if(!Xe.has(o))return o||"draft";const s=dt(t.effective_to);if(!s||Number.isNaN(s.getTime()))return o;const c=new Date;return c.setHours(0,0,0,0),s.setHours(0,0,0,0),s<c?"expired":Math.ceil((s.getTime()-c.getTime())/(1e3*60*60*24))<=(Ee||90)?"expiring":o},[Ee]),ye=n.useMemo(()=>E?[E.valid_coverage,E.at_risk,E.action_needed]:[],[E]),z=n.useMemo(()=>Y!=null?h.find(t=>t.id===Y)??null:null,[h,Y]),Ue=t=>{P(t),localStorage.setItem("purchasingExemptionView",t)},Ne=t=>{const o=(t.status||"").toLowerCase(),s=Xe.has(o)?"send":o==="prepared"||o==="previewed"?"preview":"details";ce({cert:t,initialStep:s,prefill:{vendorName:t.vendor_name||"",purchaserName:t.purchaser_name||"",taxId:t.purchaser_tax_id||"",exemptionReason:t.exemption_reason||"",description:t.description_of_property||"",signerTitle:t.signer_title||"",state:(t.state_code||"OH").toUpperCase()}})},Re=async t=>{try{await C.delete(t),T({message:"Certificate moved to trash (restorable).",variant:"success"}),le()}catch(o){T({title:"Delete failed",message:S(o,"Request failed"),variant:"error"})}},Oe=async t=>{try{await C.restore(t),T({message:"Certificate restored.",variant:"success"}),le()}catch(o){T({title:"Restore failed",message:S(o,"Request failed"),variant:"error"})}},Me=n.useCallback(async t=>{const o=await C.get(Number(t));return Kt(o)},[]),Ke=n.useCallback(async()=>[],[]),He=n.useCallback(t=>C.download(Number(t)),[]),Ge=n.useCallback((t,o)=>{const s={};for(const[c,m]of Object.entries(o))s[c==="party_id"?"vendor_name":c]=m;return C.update(Number(t),s)},[]),qe=[{key:"vendor",header:"Vendor",sortValue:t=>t.vendor_name||"",render:t=>e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"exc-cell-strong",children:t.vendor_name||"â"}),t.uid&&e.jsx("span",{className:"exc-cell-sub",children:t.uid})]})},{key:"jurisdiction",header:"Jurisdiction",sortValue:t=>t.state_code??"",render:t=>t.state_code||"â"},{key:"reason",header:"Exemption reason",sortValue:t=>t.exemption_reason??"",render:t=>t.exemption_reason||t.form_number||"â"},{key:"effective_from",header:"Effective from",sortValue:t=>t.effective_from??"",render:t=>e.jsx("span",{className:"exc-cell-nowrap",children:$e(t.effective_from)})},{key:"effective_to",header:"Effective to",sortValue:t=>{const o=dt(t.effective_to);return o?o.getTime():Number.MAX_SAFE_INTEGER},render:t=>e.jsx("span",{className:"exc-cell-nowrap",children:$e(t.effective_to,{emptyLabel:"No expiration"})})},{key:"created",header:"Created",sortValue:t=>t.created_at??"",render:t=>e.jsx("span",{className:"exc-cell-nowrap",children:$e(t.created_at)})},{key:"status",header:"Status",sortValue:t=>je(t),render:t=>e.jsx(ct,{status:je(t),fixedWidth:!0})},{key:"actions",header:"Actions",align:"right",interactive:!0,render:t=>{const o=(t.status||"").toLowerCase(),s=o==="deleted",m=!s&&!(o==="void")&&!Xe.has(o),F=!s&&Xe.has(o)&&!!t.output_pdf_s3_uri;return e.jsxs("span",{className:"exc-actions-cell",children:[e.jsx("button",{type:"button",className:"exc-link",onClick:()=>ue(t.id),"data-testid":`cert-view-${t.id}`,children:"View"}),m&&e.jsx("button",{type:"button",className:"exc-link",onClick:()=>Ne(t),"data-testid":`cert-continue-${t.id}`,children:"Continue"}),F&&e.jsx("button",{type:"button",className:"exc-link",onClick:()=>Ne(t),"data-testid":`cert-send-${t.id}`,children:"Send"}),s?e.jsx("button",{type:"button",className:"exc-link",onClick:()=>{Oe(t.id)},"data-testid":`cert-restore-${t.id}`,children:"Restore"}):e.jsx("button",{type:"button",className:"exc-link exc-link--danger",onClick:()=>{Re(t.id)},"data-testid":`cert-delete-${t.id}`,children:"Delete"})]})}}],We=[{key:"state",header:"State",sortValue:t=>t.state_code,render:t=>e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"exc-cell-strong",children:t.state_code}),e.jsx("span",{className:"exc-cell-sub",children:t.name||Be.find(o=>o.iso_code===t.state_code)?.name||""})]})},{key:"form",header:"Form",sortValue:t=>t.form_number??"",render:t=>t.is_nomad?e.jsx("span",{className:"exc-cell-muted",children:"No state sales tax"}):t.support?.mode==="multistate_generation"?t.support.form_number||t.form_number||"â":t.form_number||"â"},{key:"revision",header:"Revision",render:t=>t.revision_code||"â"},{key:"generation",header:"In-app generation",align:"center",sortValue:t=>{const o=t.support?.mode;return o?["generation","multistate_generation","upload_only","dor_issued","no_sales_tax"].indexOf(o):t.supports_generation?0:2},render:t=>{switch(t.support?.mode){case"generation":return e.jsx("span",{className:"exc-chip exc-chip--success",title:t.support?.explanation??void 0,children:"Generate"});case"multistate_generation":return e.jsx("span",{className:"exc-chip exc-chip--success",title:t.support?.explanation??void 0,children:"Generate (SST form)"});case"dor_issued":return e.jsx("span",{className:"exc-chip exc-chip--warning",title:t.support?.explanation??void 0,children:"Issued by state"});case"no_sales_tax":return e.jsx("span",{className:"exc-chip exc-chip--muted",title:t.support?.explanation??void 0,children:"No sales tax"});case"upload_only":return e.jsx("span",{className:"exc-chip exc-chip--warning",title:t.support?.explanation??void 0,children:"Upload only"});default:return t.supports_generation?e.jsx("span",{className:"exc-chip exc-chip--success",children:"Supported"}):t.is_nomad?e.jsx("span",{className:"exc-chip exc-chip--muted",children:"Not applicable"}):e.jsx("span",{className:"exc-chip exc-chip--warning",children:"Upload only"})}}},{key:"actions",header:"Actions",align:"right",interactive:!0,render:t=>{const o=t.support?.mode?t.support.mode==="generation"||t.support.mode==="multistate_generation":t.supports_generation,s=t.support?.mode?t.support.mode==="no_sales_tax":!!t.is_nomad;return e.jsx("span",{className:"exc-actions-cell",children:o?e.jsx("button",{type:"button",className:"exc-link",onClick:()=>ce({prefill:{state:t.state_code}}),"data-testid":`stateform-prepare-${t.state_code}`,children:"Prepare"}):!s&&e.jsx("button",{type:"button",className:"exc-link",onClick:()=>_e(!0),"data-testid":`stateform-upload-${t.state_code}`,children:"Upload instead"})})}}];if($)return e.jsx("div",{className:"exc-loading",style:{minHeight:"40vh"},children:"Loadingâ¦"});if(!b)return _("/login"),null;const Se={...Rt(x),"--highlight-color":q.highlight,"--highlight-gradient":q.highlightGradient},Ve=(z?.status||"").toLowerCase();return e.jsxs("div",{className:"sales-exemption-page exc-page",style:Se,children:[e.jsxs("div",{className:"exc-container",children:[e.jsx(Et,{organization:O,title:"Purchasing Exemption Certificates",location:U,"data-testid":"purchasing-exemption-header",actions:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"exc-btn exc-btn--primary",onClick:()=>ce({}),"data-testid":"open-prepare",children:"Prepare certificate"}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--secondary",onClick:()=>_e(!0),"data-testid":"open-upload",children:"Upload certificates"}),e.jsx("button",{type:"button",className:"exc-btn exc-btn--secondary",onClick:()=>we(!0),"data-testid":"open-settings",children:"Settings"})]})}),ee&&e.jsxs("div",{className:"exc-banner exc-banner--info",children:[e.jsx("span",{children:ee}),e.jsxs("span",{className:"exc-doc__bar-actions",children:[v&&e.jsx("button",{type:"button",className:"exc-link",onClick:()=>_(v),"data-testid":"return-to-ptc",children:"Return to Purchasing Tax Compliance"}),e.jsx("button",{type:"button",className:"exc-banner__dismiss",onClick:()=>R(null),"aria-label":"Dismiss",children:"Ã"})]})]}),e.jsx("section",{className:"exc-kpi-grid","data-testid":"cert-kpis",children:(E?ye:["Valid Coverage","At Risk","A
1ction Needed"].map(t=>({label:t,value:"",caption:"",tone:"neutral"}))).map(t=>e.jsxs("article",{className:"exc-kpi-card",children:[e.jsx("span",{className:"exc-kpi-card__label",children:t.label}),e.jsx("span",{className:`exc-kpi-card__value ${qt[t.tone??""]??""}`,children:E?t.value:me?e.jsx(ut,{width:90,height:24}):"â"}),e.jsx("span",{className:"exc-kpi-card__caption",children:E?t.caption??"":me?e.jsx(ut,{width:"70%",height:12}):"Certificate summary unavailable"})]},t.label))}),!E&&!me&&ge&&e.jsxs("div",{className:"exc-banner exc-banner--error",children:[e.jsx("span",{children:ge}),e.jsx("button",{type:"button",className:"exc-link",onClick:()=>{be()},children:"Retry"})]}),e.jsx("div",{className:"exc-tabs",role:"tablist","aria-label":"Certificate views",children:[["certificates","Certificates"],["prepare","Prepare"],["review","Review"]].map(([t,o])=>e.jsx("button",{type:"button",role:"tab","aria-selected":M===t,className:`exc-tab${M===t?" is-active":""}`,onClick:()=>Ue(t),"data-testid":`view-tab-${t}`,children:o},t))}),M==="certificates"&&e.jsx(Ze,{tableTestId:"purchasing-cert-table",columns:qe,rows:h,rowKey:t=>String(t.id),loading:K,error:h.length===0?xe:null,onRetry:()=>{A()},emptyTitle:"No certificates found",emptyBody:"Prepare a certificate for a supported state or upload signed copies you already have.",searchValue:N,onSearchChange:te,searchPlaceholder:"Search certificatesâ¦",filters:e.jsxs(e.Fragment,{children:[e.jsxs("select",{className:"exc-select",value:H,"aria-label":"Filter by status",onChange:t=>se(t.target.value),"data-testid":"cert-status-filter",children:[e.jsx("option",{value:"",children:"All statuses"}),zt.map(t=>e.jsx("option",{value:t,children:t},t))]}),e.jsxs("select",{className:"exc-select",value:Q,"aria-label":"Filter by jurisdiction",onChange:t=>ke(t.target.value),"data-testid":"cert-jurisdiction-filter",children:[e.jsx("option",{value:"",children:"All jurisdictions"}),Be.map(t=>e.jsx("option",{value:t.iso_code,children:t.iso_code},t.iso_code))]})]}),pagination:{page:i,pageSize:k,totalCount:j,totalPages:Math.max(1,Math.ceil(j/k)),onPageChange:w,itemNoun:"certificates"},onOpenDetail:t=>ue(t.id),rowTestId:t=>`cert-row-${t.id}`}),M==="prepare"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"exc-section__hint",style:{margin:"4px 2px"},children:"States with in-app generation produce a filled, signable PDF. For every other state, complete the official form outside the platform and upload the signed copy â it gets the same tracking, expiration, and coverage matching."}),e.jsx(Ze,{tableTestId:"state-forms-table",columns:We,rows:(fe??[]).filter(t=>t.state_code),rowKey:t=>t.state_code,loading:fe==null&&!De,error:De,onRetry:()=>{ve()},emptyTitle:"No state form registry entries",emptyBody:"State exemption form availability has not been loaded yet."})]}),M==="review"&&e.jsx(Mt,{orgId:d,locationId:f??void 0,onOpenDetail:t=>ue(t),refreshNonce:Fe,onChanged:le})]}),Y!=null&&e.jsx(Tt,{certId:String(Y),orgId:d,locationId:f??void 0,side:"purchasing",onClose:()=>ue(null),onChanged:le,loadDetail:Me,loadVersions:Ke,loadDocument:He,updateField:Ge,editableFields:Bt,hiddenSections:["contact","notifications","versions"],extraSections:e.jsxs("section",{className:"exc-section","data-testid":"cert-send-history-section",children:[e.jsxs("div",{className:"exc-section__head",children:[e.jsx("span",{className:"exc-section__title",children:"Signature & delivery"}),e.jsx("span",{className:"exc-doc__bar-actions",children:z&&!["deleted","void"].includes(Ve)&&e.jsx("button",{type:"button",className:"exc-link",onClick:()=>{ue(null),Ne(z)},"data-testid":"cert-drawer-workflow",children:Xe.has(Ve)?"Send / voidâ¦":"Continue preparationâ¦"})})]}),z?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"exc-kv",children:[e.jsx("span",{className:"exc-kv__label",children:"Signed"}),e.jsx("span",{className:"exc-kv__value",children:z.signed_at?et(String(z.signed_at)):"Not signed yet"})]}),e.jsxs("div",{className:"exc-kv",children:[e.jsx("span",{className:"exc-kv__label",children:"Last sent to"}),e.jsx("span",{className:"exc-kv__value",children:String(z.sent_to_email??"")||"â"})]}),e.jsxs("div",{className:"exc-kv",children:[e.jsx("span",{className:"exc-kv__label",children:"Last sent at"}),e.jsx("span",{className:"exc-kv__value",children:z.sent_at?et(String(z.sent_at)):"Never"})]}),e.jsxs("div",{className:"exc-kv",children:[e.jsx("span",{className:"exc-kv__label",children:"Send count"}),e.jsx("span",{className:"exc-kv__value",children:String(z.send_count??0)})]})]}):e.jsx("p",{className:"exc-section__hint",children:"Delivery details appear once this certificate is on the current page of the list."})]})}),ae&&e.jsx(Ut,{orgId:d,locationId:f??void 0,cert:ae.cert??null,initialStep:ae.initialStep,prefill:ae.prefill??null,sourceRecord:ae.sourceRecord??null,onClose:()=>ce(null),onChanged:le,onRequestUpload:()=>_e(!0)}),e.jsx(Lt,{open:W,orgId:d,locationId:f,organizationLabel:O,locationLabel:U,onClose:()=>_e(!1),onCertificatesChanged:le}),e.jsx(Ot,{open:Le,onClose:()=>we(!1),orgId:d,locationId:f??void 0,onDataChanged:le})]})};export{ss as PurchasingExemption,ss 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.