1import{u as we,U as ve,x as Le,o as ke,r as d,z as de,d as U,aq as Z,W as Ie,J as De,t as Ae,b as Oe,a0 as Te,j as e,D as $e,c as Fe,X as Re,Q as ue,Y as me,I as q,Z as Ue,B as Y,g as M,ah as ze,T as H,aU as Q,av as he,_ as Be,w as qe,aW as Me,aQ as Qe,by as Ve,C as _e,aw as Je,bB as We}from"../index.js";import{C as Ye}from"./CustomerDetails-Bg0SM9E6.js";import{C as Ze}from"./customer-status-Cww_sR-5.js";import{a as He}from"./RegionDropdown-wSegm46l.js";import{u as Xe,P as Ge}from"./PermissionsSection-Bp7ij5fv.js";import{u as Ke}from"./user-permissions-Cy1t-3uL.js";import{F as Pe,a as Ee}from"./UserCircleIcon-B8ALt3Ch.js";import"./ChevronDownIcon-IoQOyGWS.js";function mt(){var te,se,ae,ne,oe,re,ce;const[S]=we(),F=ve(),{language:p}=Le(),{labels:l}=ke(),u=S.get("documentId")||"",[f,i]=d.useState(!1),x=d.useRef(null),[b,C]=d.useState(null),[m,N]=d.useState(null),{data:a,isLoading:g,error:R,mutate:r,isValidating:z}=de(`${U.getCustomerContact(u)}`,Z,{revalidateOnFocus:!1}),s=(te=a==null?void 0:a.data)==null?void 0:te.user,h=(se=a==null?void 0:a.data)==null?void 0:se.customer,[y,V]=d.useState(null),[X,G]=d.useState(null),[K,P]=d.useState(!1);async function fe(){P(!0);try{const n=await Z(`${U.customerContactSsoIdentity(u)}`);if(!(n!=null&&n.ssoId)){M("This contact has no SSO id yet â they need to sign in once before they can be synced.");return}const o=await fetch(ze.userSsoUpdate,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${H()}`},body:JSON.stringify({email:n.email,ssoId:n.ssoId})}),j=await o.json().catch(()=>null),v=j==null?void 0:j.message;v?Q(v):o.ok?Q("Distributor portal returned no message."):M(`Distributor portal sync failed (${o.status})`)}catch{M("Could not reach the distributor portal sync.")}finally{P(!1)}}function pe(n){const o=y??h;!n||n.documentId===(o==null?void 0:o.documentId)||he({title:"Confirm change",description:e.jsxs("p",{className:"text-sm text-gray-500",children:["Are you sure you want to change the customer to",e.jsx("br",{}),e.jsx("span",{className:"font-semibold text-gray-900",children:n==null?void 0:n.name})]}),onConfirm:()=>{V(n),G(null)},confirmLabel:"Yes",cancelLabel:"No"})}const w=Ie((ae=s==null?void 0:s.avatar)==null?void 0:ae.url),[E,xe]=d.useState(new Set),{allPermissions:be,isLoading:ge}=Xe(s==null?void 0:s.id,void 0,"customer"),{data:_,loading:ye}=De({language:p,path:"user-management",query:"user-management"}),t=(oe=(ne=_==null?void 0:_.userManagementByPath)==null?void 0:ne.item)==null?void 0:oe.edit,c=Ae((t==null?void 0:t.inputFields)||[]),L=c==null?void 0:c["InputField.Email"],k=c==null?void 0:c["InputField.FirstName"],I=c==null?void 0:c["InputField.LastName"],D=c==null?void 0:c["InputField.Telephone"],A=c==null?void 0:c["InputField.Department"],O=c==null?void 0:c["InputField.Region"],ee=Oe((t==null?void 0:t.toastMessages)||[]),T=ee["Message.Success"],$=ee["Message.Error"],je=Te((t==null?void 0:t.checkboxes)||[]);async function Se(n){n.preventDefault();try{if(f||!s)return;if(!m){Q("Missing Info","Please select a region");return}i(!0);const o=new FormData(n.target),j={firstName:o.get("firstName")||"",lastName:o.get("lastName")||"",department:o.get("department")||"",telephone:String(o.get("dialing-code")||"")+String(o.get("telephone")||""),region:JSON.stringify({documentId:m==null?void 0:m.documentId,id:m==null?void 0:m.id})},v=new FormData;Object.entries(j).forEach(([Ce,Ne])=>{v.append(Ce,Ne||"")});const J=o.get("avatar");(J==null?void 0:J.size)>0&&v.append("files.avatar",o.get("avatar")),y&&y.documentId!==(h==null?void 0:h.documentId)&&v.append("customerDocumentId",y.documentId);const le=await fetch(`${U.updateCustomerContact(u)}`,{method:"POST",headers:{Authorization:`Bearer ${H()}`},body:v});if(!le.ok)throw new Error("Failed to update profile");const W=await le.json(),B=W==null?void 0:W.salesforceSync,ie=B&&B.ok===!1;G(ie?{reason:B.reason||"SYNC_FAILED",duplicate:B.duplicate}:null),await Ke(s.id,E,be),V(null),await r(),ie?Q("Saved","Salesforce needs attention - see the note under the customer dropdown."):Be(T==null?void 0:T.title,T==null?void 0:T.description)}
1catch(o){console.log(o),M($==null?void 0:$.title,$==null?void 0:$.description)}finally{i(!1)}}return d.useEffect(()=>{var o;const n=(o=a==null?void 0:a.data)==null?void 0:o.user;N((n==null?void 0:n.region)||null)},[(re=a==null?void 0:a.data)==null?void 0:re.user]),g||ye||z||ge?e.jsx($e,{}):R?(console.log("error::",R),e.jsx("div",{className:"grow",children:Fe.serverError})):e.jsxs("main",{className:"p-2 lg:p-6",children:[e.jsx("h2",{className:"font-bold text-lg",children:t==null?void 0:t.editUserTitle}),e.jsxs("form",{onSubmit:Se,className:"grid bg-white shadow-sm lg:grid-cols-3 py-7 px-8 gap-x-8 gap-y-8 mt-4",children:[e.jsxs("div",{className:"col-span-full",children:[e.jsx("label",{htmlFor:"photo",className:"block text-base font-medium text-primary-black",children:t==null?void 0:t.photoLabel}),e.jsxs("div",{className:"relative mt-1.5 size-12 rounded-full inline-flex items-center gap-x-3 group",children:[e.jsx("input",{type:"file",className:"hidden",ref:x,name:"avatar",accept:"image/jpeg, image/png, image/jpg, image/svg+xml",onChange:n=>{var j;const o=(j=n.target.files)==null?void 0:j[0];o?(b&&URL.revokeObjectURL(b),C(URL.createObjectURL(o))):C(null)}}),b?e.jsx("img",{src:b,className:"absolute inset-0 aspect-square"}):w?e.jsx(Re,{src:w==null?void 0:w.src,authToken:w==null?void 0:w.token,loadingComponent:e.jsx(ue,{custom:"size-4"}),className:"absolute inset-0 aspect-square"}):e.jsx(Pe,{"aria-hidden":"true",className:"text-gray-300 absolute inset-0"}),e.jsx("button",{className:"absolute inset-0 bg-white/50 p-3 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer focus-visible:opacity-100",title:l[me.editPhoto],type:"button",onClick:()=>{const n=x.current;n&&(n.value="",n.click())},children:e.jsx(Ee,{className:"size-4"})})]})]}),e.jsx(q,{label:L==null?void 0:L.inputLabel,placeholder:L==null?void 0:L.inputPlaceholder,name:"email",value:s==null?void 0:s.email,disabled:!0}),e.jsx(q,{label:k==null?void 0:k.inputLabel,placeholder:k==null?void 0:k.inputPlaceholder,name:"firstName",defaultValue:s==null?void 0:s.firstName,required:!0}),e.jsx(q,{label:I==null?void 0:I.inputLabel,placeholder:I==null?void 0:I.inputPlaceholder,name:"lastName",defaultValue:s==null?void 0:s.lastName,required:!0}),e.jsx(Ue,{label:D==null?void 0:D.inputLabel,placeholder:D==null?void 0:D.inputPlaceholder,name:"telephone",defaultValue:s==null?void 0:s.telephone,type:"tel",pattern:"\\d*",title:l[me.digitsOnly],required:!0}),e.jsx(He,{selectedRegion:m,setSelectedRegion:N,label:O==null?void 0:O.inputLabel,placeholder:O==null?void 0:O.inputPlaceholder}),e.jsx(q,{label:A==null?void 0:A.inputLabel,placeholder:A==null?void 0:A.inputPlaceholder,name:"department",defaultValue:(s==null?void 0:s.department)||""}),e.jsx(Ge,{userId:s==null?void 0:s.id,variant:"customer",selectedPermissions:E,setSelectedPermissions:xe,inputFields:c,checkboxes:je}),e.jsxs("div",{className:"col-span-full gap-x-6 flex justify-end",children:[e.jsx(Y,{type:"button",variant:"light",onClick:()=>F(-1),disabled:f,children:t==null?void 0:t.backButtonLabel}),e.jsx(Y,{type:"submit",loading:f,disabled:f,children:t==null?void 0:t.submitButtonLabel})]})]}),e.jsx("h2",{className:"font-bold text-lg mt-8 mb-4",children:"Distributor Portal"}),e.jsx("div",{className:"bg-white shadow-sm py-7 px-8 mb-4",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsx("p",{className:"text-sm text-primary-gray max-w-2xl",children:"Sends this contactâs email and SSO id to the distributor portal so their single sign-on keeps working there. Safe to run again at any time."}),e.jsx(Y,{type:"button",onClick:fe,loading:K,disabled:K||!(s!=null&&s.email),children:"Sync SSO"})]})}),h&&e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"font-bold text-lg mt-8 mb-4",children:t==null?void 0:t.customerDetailsHeading}),e.jsxs("div",{className:"bg-white shadow-sm py-7 px-8 mb-4 ",children:[e.jsx("div",{className:"grid lg:grid-cols-3",children:e.jsx(et,{selected:y??h,onSelect:pe})}),e.jsxs("div",{children:[y&&y.documentId!==(h==null?void 0:h.documentId)&&e.jsxs("p",{className:"mt-1.5 text-sm text-gray-500",children:["Applies on save ·"," ",e.jsx("button",{type:"button",onClick:()=>V(null),className:"font-semibold text-primary-black cursor-pointer underline",children:"Undo"})]}),X&&e.jsx(tt,{sync:X,currentContactId:(ce=a==null?void 0:a.data)==null?void 0:ce.salesforceContactId,userDocumentId:u})]})]}),e.jsx(Ye,{customer:y??h,showSourceSystem:!0,labels:{customerName:t==null?void 0:t.customerName,customerAddress:t==null?void 0:t.customerAddress,customerCity:t==null?void 0:t.customerCity,customerZipCode:t==null?void 0:t.customerZipCode,customerCountry:t==null?void 0:t.customerCountry,customerAccountNumber:t==null?void 0:t.customerAccountNumber,customerIndustries:t==null?void 0:t.customerIndustries,customerProducts:t==null?void 0:t.customerProducts,customerParticipatesInPoc:t==null?void 0:t.participatesInPoc}})]})]})}function et({selected:S,onSelect:F}){var a,g,R;const[p,l]=d.useState(""),[u,f]=d.useState(""),i=(g=(a=qe().user)==null?void 0:a.region)==null?void 0:g.id,{data:x,isLoading:b,error:C}=de(i?`${U.getCustomers}?${Me.stringify({filters:{customerStatus:Ze.Active,region:{id:{$eq:i}}},populate:"*",_q:u||void 0})}`:null,Z,{revalidateOnFocus:!1,dedupingInterval:1e4});d.useEffect(()=>{const r=setTimeout(()=>{f((p==null?void 0:p.trim())||"")},500);return()=>clearTimeout(r)},[p]);const m=r=>({...r,title:r==null?void 0:r.name,description:We(r)}),N=((R=x==null?void 0:x.data)==null?void 0:R.map(m))||[];return C&&console.log(C),e.jsx(Qe,{renderDescription:r=>{var z;return e.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-x-2 justify-items-center justify-between",children:[e.jsx("span",{className:"block text-sm text-gray-400 group-data-focus:text-white mt-1 justify-self-start",title:r==null?void 0:r.description,children:r==null?void 0:r.description}),e.jsx(Ve,{minItemsToRender:1,isStatic:!0,items:((z=r==null?void 0:r.industries)==null?void 0:z.map(s=>s==null?void 0:s.title))||[]})]})},label:"Customer",options:N,selectedOption:S?m(S):null,onChange:r=>{r&&F(r)},placeholder:"Search customers",onQueryChange:l,loading:b,unfiltered:!0})}function tt({sync:S,currentContactId:F,userDocumentId:p}){const[l,u]=d.useState(null),f=d.useRef(null),{duplicate:i}=S;d.useEffect(()=>{var m;(m=f.current)==null||m.scrollIntoView({block:"center"})},[]);
1function x(){!i||(l==null?void 0:l.status)==="busy"||he({title:"Link to the existing Salesforce contact?",description:e.jsxs("div",{className:"text-sm text-gray-500",children:[e.jsxs("p",{children:["This user now: ",e.jsx("span",{className:"font-semibold text-gray-900",children:F||"none"}),e.jsx("br",{}),"Will change to: ",e.jsx("span",{className:"font-semibold text-gray-900",children:i.contactId}),i.confidence!=null?` (${i.confidence}% match)`:""]}),e.jsx("p",{className:"mt-2",children:"Check in Salesforce that both are the same person. The old contact is not deleted."})]}),confirmLabel:"Link contact",cancelLabel:"Cancel",onConfirm:()=>b(i.contactId)})}async function b(m){var N;u({status:"busy"});try{const a=await fetch(U.adoptSalesforceContact(p),{method:"POST",headers:{Authorization:`Bearer ${H()}`,"Content-Type":"application/json"},body:JSON.stringify({salesforceContactId:m})});if(!a.ok){const g=await a.json().catch(()=>null);throw new Error(((N=g==null?void 0:g.error)==null?void 0:N.message)||"Failed to link the Salesforce contact")}u({status:"done"})}catch(a){u({status:"failed",message:a instanceof Error&&a.message?a.message:"Failed to link the Salesforce contact"})}}if((l==null?void 0:l.status)==="done")return e.jsxs("p",{className:"mt-1.5 flex items-center gap-x-1.5 text-sm text-gray-500",children:[e.jsx(_e,{"aria-hidden":"true",className:"size-4 shrink-0 text-green-500"}),"This user is now linked to the Salesforce contact on the new customer."]});const C=S.reason==="DUPLICATES_DETECTED"?`Customer changed in the portal, but not in Salesforce - the new customer already has a contact that looks like this user${(i==null?void 0:i.confidence)!=null?` (${i.confidence}% match)`:""}.${i?"":" Fix it in Salesforce."}`:"Customer changed in the portal, but this user's Salesforce contact could not be moved to the new customer. Fix it in Salesforce.";return e.jsxs("div",{ref:f,className:"mt-1.5 flex gap-1.5 text-sm text-gray-500",children:[e.jsx(Je,{"aria-hidden":"true",className:"size-4 shrink-0 mt-0.5 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{children:C}),i&&((l==null?void 0:l.status)==="busy"?e.jsxs("p",{className:"mt-0.5 flex gap-x-2 items-center font-semibold",children:[e.jsx(ue,{extraSmall:!0}),"Linkingâ¦"]}):e.jsx("p",{className:"mt-0.5",children:e.jsx("button",{type:"button",onClick:x,className:"font-semibold text-primary-black cursor-pointer underline",children:"Link this user to that contact"})})),(l==null?void 0:l.status)==="failed"&&e.jsx("p",{className:"mt-0.5 text-red-600",children:l.message})]})]})}export{mt 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.