@mercoa/react 0.0.54-rc10 → 0.0.54-rc11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- import { aC as s, aD as t, a8 as o, a9 as n, l as c, j as i, m as r, k as l, n as b, t as m, r as d, u as y, H as u, z as P, L as p, O as S, M as h, a$ as B, Y as A, A as k, am as C, ao as M, i as g, h as v, aa as D, o as T, C as E, q as F, b4 as I, F as N, I as O, G as R, x as f, D as L, K as x, J as w, a0 as U, aU as V, aR as z, as as H, R as j, bi as q, ae as G, ag as J, E as K, Q as W, a4 as Y, aF as Q, S as X, V as Z, U as _, aH as $, ax as aa, aE as ea, aI as sa, T as ta, aJ as oa, aK as na, au as ca, ba as ia, bD as ra, bC as la, ac as ba, by as ma, aY as da, aZ as ya, ai as ua, aL as Pa, ak as pa, aM as Sa, aW as ha, b3 as Ba, b2 as Aa, bb as ka, bw as Ca, _ as Ma, b6 as ga, bk as va, bl as Da, br as Ta, y as Ea, bd as Fa, bh as Ia, bj as Na, bz as Oa, be as Ra, bg as fa, bf as La, bx as xa, bv as wa, bm as Ua, bp as Va, bo as za, bA as Ha, bn as ja, bG as qa, b8 as Ga, bB as Ja, bq as Ka, b9 as Wa, aS as Ya, bH as Qa, a6 as Xa, P as Za, bI as _a, bJ as $a, bM as ae, bL as ee, bK as se, bN as te, aA as oe, ay as ne, az as ce, a2 as ie, a1 as re, aQ as le, aV as be, bF as me, bE as de, aT as ye, aO as ue, aN as Pe, aX as pe, aP as Se, av as he, W as Be, aB as Ae, aq as ke, a7 as Ce, X as Me, al as ge, an as ve, w as De, aw as Te, $ as Ee, ar as Fe, ad as Ie, af as Ne, a3 as Oe, aG as Re, bs as fe, N as Le, at as xe, b5 as we, b1 as Ue, bt as Ve, ab as ze, aj as He, ah as je, Z as qe, v as Ge, a5 as Je, bu as Ke, b7 as We, b0 as Ye, a_ as Qe, bc as Xe, ap as Ze } from "./index-BYy-itXa.mjs";
1
+ import { aC as s, aD as t, a8 as o, a9 as n, l as c, j as i, m as r, k as l, n as b, t as m, r as d, u as y, H as u, z as P, L as p, O as S, M as h, a$ as B, Y as A, A as k, am as C, ao as M, i as g, h as v, aa as D, o as T, C as E, q as F, b4 as I, F as N, I as O, G as R, x as f, D as L, K as x, J as w, a0 as U, aU as V, aR as z, as as H, R as j, bi as q, ae as G, ag as J, E as K, Q as W, a4 as Y, aF as Q, S as X, V as Z, U as _, aH as $, ax as aa, aE as ea, aI as sa, T as ta, aJ as oa, aK as na, au as ca, ba as ia, bD as ra, bC as la, ac as ba, by as ma, aY as da, aZ as ya, ai as ua, aL as Pa, ak as pa, aM as Sa, aW as ha, b3 as Ba, b2 as Aa, bb as ka, bw as Ca, _ as Ma, b6 as ga, bk as va, bl as Da, br as Ta, y as Ea, bd as Fa, bh as Ia, bj as Na, bz as Oa, be as Ra, bg as fa, bf as La, bx as xa, bv as wa, bm as Ua, bp as Va, bo as za, bA as Ha, bn as ja, bG as qa, b8 as Ga, bB as Ja, bq as Ka, b9 as Wa, aS as Ya, bH as Qa, a6 as Xa, P as Za, bI as _a, bJ as $a, bM as ae, bL as ee, bK as se, bN as te, aA as oe, ay as ne, az as ce, a2 as ie, a1 as re, aQ as le, aV as be, bF as me, bE as de, aT as ye, aO as ue, aN as Pe, aX as pe, aP as Se, av as he, W as Be, aB as Ae, aq as ke, a7 as Ce, X as Me, al as ge, an as ve, w as De, aw as Te, $ as Ee, ar as Fe, ad as Ie, af as Ne, a3 as Oe, aG as Re, bs as fe, N as Le, at as xe, b5 as we, b1 as Ue, bt as Ve, ab as ze, aj as He, ah as je, Z as qe, v as Ge, a5 as Je, bu as Ke, b7 as We, b0 as Ye, a_ as Qe, bc as Xe, ap as Ze } from "./index-C3OB9WO6.mjs";
2
2
  export {
3
3
  s as AcceptToSButton,
4
4
  t as AcceptTosForm,
package/dist/index.umd.js CHANGED
@@ -225,7 +225,7 @@ License: MIT
225
225
  `:"\r"}(ie,X)),A=!1,M.delimiter)I(M.delimiter)&&(M.delimiter=M.delimiter(ie),H.meta.delimiter=M.delimiter);else{var be=function(Ce,Te,Ee,ne,te){var _e,Me,Oe,de;te=te||[","," ","|",";",c.RECORD_SEP,c.UNIT_SEP];for(var F=0;F<te.length;F++){var fe=te[F],se=0,Pe=0,Ie=0;Oe=void 0;for(var nt=new y({comments:ne,delimiter:fe,newline:Te,preview:10}).parse(Ce),V=0;V<nt.data.length;V++)if(Ee&&Q(nt.data[V]))Ie++;else{var T=nt.data[V].length;Pe+=T,Oe!==void 0?0<T&&(se+=Math.abs(T-Oe),Oe=T):Oe=T}0<nt.data.length&&(Pe/=nt.data.length-Ie),(Me===void 0||se<=Me)&&(de===void 0||de<Pe)&&1.99<Pe&&(Me=se,_e=fe,de=Pe)}return{successful:!!(M.delimiter=_e),bestDelimiter:_e}}(ie,M.newline,M.skipEmptyLines,M.comments,M.delimitersToGuess);be.successful?M.delimiter=be.bestDelimiter:(A=!0,M.delimiter=c.DefaultDelimiter),H.meta.delimiter=M.delimiter}var xe=j(M);return M.preview&&M.header&&xe.preview++,E=ie,D=new y(xe),H=D.parse(E,le,U),ae(),re?{meta:{paused:!0}}:H||{meta:{paused:!1}}},this.paused=function(){return re},this.pause=function(){re=!0,D.abort(),E=I(M.chunk)?"":E.substring(D.getCharIndex())},this.resume=function(){W.streamer._halted?(re=!1,W.streamer.parseChunk(E,!0)):setTimeout(W.resume,3)},this.aborted=function(){return ue},this.abort=function(){ue=!0,D.abort(),H.meta.aborted=!0,I(M.complete)&&M.complete(H),E=""}}function _(M){return M.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function y(M){var E,D=(M=M||{}).delimiter,A=M.newline,z=M.comments,$=M.step,L=M.preview,B=M.fastMode,W=E=M.quoteChar===void 0||M.quoteChar===null?'"':M.quoteChar;if(M.escapeChar!==void 0&&(W=M.escapeChar),(typeof D!="string"||-1<c.BAD_DELIMITERS.indexOf(D))&&(D=","),z===D)throw new Error("Comment character same as delimiter");z===!0?z="#":(typeof z!="string"||-1<c.BAD_DELIMITERS.indexOf(z))&&(z=!1),A!==`
226
226
  `&&A!=="\r"&&A!==`\r
227
227
  `&&(A=`
228
- `);var K=0,Z=!1;this.parse=function(re,ue,ge){if(typeof re!="string")throw new Error("Input must be a string");var H=re.length,R=D.length,Q=A.length,ae=z.length,k=I($),N=[],q=[],ie=[],le=K=0;if(!re)return C();if(M.header&&!ue){var U=re.split(A)[0].split(D),X=[],be={},xe=!1;for(var Ce in U){var Te=U[Ce];I(M.transformHeader)&&(Te=M.transformHeader(Te,Ce));var Ee=Te,ne=be[Te]||0;for(0<ne&&(xe=!0,Ee=Te+"_"+ne),be[Te]=ne+1;X.includes(Ee);)Ee=Ee+"_"+ne;X.push(Ee)}if(xe){var te=re.split(A);te[0]=X.join(D),re=te.join(A)}}if(B||B!==!1&&re.indexOf(E)===-1){for(var _e=re.split(A),Me=0;Me<_e.length;Me++){if(ie=_e[Me],K+=ie.length,Me!==_e.length-1)K+=A.length;else if(ge)return C();if(!z||ie.substring(0,ae)!==z){if(k){if(N=[],Ie(ie.split(D)),oe(),Z)return C()}else Ie(ie.split(D));if(L&&L<=Me)return N=N.slice(0,L),C(!0)}}return C()}for(var Oe=re.indexOf(D,K),de=re.indexOf(A,K),F=new RegExp(_(W)+_(E),"g"),fe=re.indexOf(E,K);;)if(re[K]!==E)if(z&&ie.length===0&&re.substring(K,K+ae)===z){if(de===-1)return C();K=de+Q,de=re.indexOf(A,K),Oe=re.indexOf(D,K)}else if(Oe!==-1&&(Oe<de||de===-1))ie.push(re.substring(K,Oe)),K=Oe+R,Oe=re.indexOf(D,K);else{if(de===-1)break;if(ie.push(re.substring(K,de)),T(de+Q),k&&(oe(),Z))return C();if(L&&N.length>=L)return C(!0)}else for(fe=K,K++;;){if((fe=re.indexOf(E,fe+1))===-1)return ge||q.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:N.length,index:K}),V();if(fe===H-1)return V(re.substring(K,fe).replace(F,E));if(E!==W||re[fe+1]!==W){if(E===W||fe===0||re[fe-1]!==W){Oe!==-1&&Oe<fe+1&&(Oe=re.indexOf(D,fe+1)),de!==-1&&de<fe+1&&(de=re.indexOf(A,fe+1));var se=nt(de===-1?Oe:Math.min(Oe,de));if(re.substr(fe+1+se,R)===D){ie.push(re.substring(K,fe).replace(F,E)),re[K=fe+1+se+R]!==E&&(fe=re.indexOf(E,K)),Oe=re.indexOf(D,K),de=re.indexOf(A,K);break}var Pe=nt(de);if(re.substring(fe+1+Pe,fe+1+Pe+Q)===A){if(ie.push(re.substring(K,fe).replace(F,E)),T(fe+1+Pe+Q),Oe=re.indexOf(D,K),fe=re.indexOf(E,K),k&&(oe(),Z))return C();if(L&&N.length>=L)return C(!0);break}q.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:N.length,index:K}),fe++}}else fe++}return V();function Ie(ye){N.push(ye),le=K}function nt(ye){var je=0;if(ye!==-1){var Se=re.substring(fe+1,ye);Se&&Se.trim()===""&&(je=Se.length)}return je}function V(ye){return ge||(ye===void 0&&(ye=re.substring(K)),ie.push(ye),K=H,Ie(ie),k&&oe()),C()}function T(ye){K=ye,Ie(ie),ie=[],de=re.indexOf(A,K)}function C(ye){return{data:N,errors:q,meta:{delimiter:D,linebreak:A,aborted:Z,truncated:!!ye,cursor:le+(ue||0)}}}function oe(){$(C()),N=[],q=[]}},this.abort=function(){Z=!0},this.getCharIndex=function(){return K}}function x(M){var E=M.data,D=i[E.workerId],A=!1;if(E.error)D.userError(E.error,E.file);else if(E.results&&E.results.data){var z={abort:function(){A=!0,O(E.workerId,{data:[],errors:[],meta:{aborted:!0}})},pause:S,resume:S};if(I(D.userStep)){for(var $=0;$<E.results.data.length&&(D.userStep({data:E.results.data[$],errors:E.results.errors,meta:E.results.meta},z),!A);$++);delete E.results}else I(D.userChunk)&&(D.userChunk(E.results,z,E.file),delete E.results)}E.finished&&!A&&O(E.workerId,E.results)}function O(M,E){var D=i[M];I(D.userComplete)&&D.userComplete(E),D.terminate(),delete i[M]}function S(){throw new Error("Not implemented.")}function j(M){if(typeof M!="object"||M===null)return M;var E=Array.isArray(M)?[]:{};for(var D in M)E[D]=j(M[D]);return E}function P(M,E){return function(){M.apply(E,arguments)}}function I(M){return typeof M=="function"}return a&&(n.onmessage=function(M){var E=M.data;if(c.WORKER_ID===void 0&&E&&(c.WORKER_ID=E.workerId),typeof E.input=="string")n.postMessage({workerId:c.WORKER_ID,results:c.parse(E.input,E.config),finished:!0});else if(n.File&&E.input instanceof File||E.input instanceof Object){var D=c.parse(E.input,E.config);D&&n.postMessage({workerId:c.WORKER_ID,results:D,finished:!0})}}),(h.prototype=Object.create(u.prototype)).constructor=h,(p.prototype=Object.create(u.prototype)).constructor=p,(m.prototype=Object.create(m.prototype)).constructor=m,(g.prototype=Object.create(u.prototype)).constructor=g,c})})(hY);var I9e=hY.exports;const pY=mn(I9e);function CR(e,t,r){return r?U9e(e):z9e(e,t)}function z9e(e,t){return{UNASSIGNED:"Unassigned",DRAFT:"Inbox",NEW:"Ready for Review",APPROVED:t!=null&&t.length?"Approved":"Ready for Payment",SCHEDULED:"Payment Scheduled",PENDING:"Payment Processing",FAILED:"Payment Failed",PAID:"Paid",CANCELED:"Canceled",REFUSED:"Rejected",ARCHIVED:"Archived"}[e]}function U9e(e,t){return{UNASSIGNED:"Unassigned",DRAFT:"Draft",NEW:"Ready for Review",APPROVED:"Awaiting Payment",SCHEDULED:"Payment Scheduled",PENDING:"Payment Processing",FAILED:"Payment Failed",PAID:"Paid",CANCELED:"Canceled",REFUSED:"Rejected",ARCHIVED:"Archived"}[e]}async function mY({statuses:e,search:t,mercoaSession:r,setMetrics:n,returnByDate:o,excludeReceivables:a,excludePayables:i}){!i&&!a&&(a=!0);const s=(await Promise.all((e??[]).map(async l=>{var h,p;if(!r.token||!((h=r.entity)!=null&&h.id))return;const u=await((p=r.client)==null?void 0:p.entity.invoice.metrics(r.entity.id,{search:t,status:l,returnByDate:o,excludeReceivables:a,excludePayables:i}));return[l,(u==null?void 0:u[0])??{totalAmount:0,totalInvoices:0,totalCount:0,currency:"USD"}]}))).filter(l=>l),c=Object.fromEntries(s);n(c)}function gY({open:e,onClose:t,setDate:r}){const[n,o]=w.useState();return f.jsxs(fn,{as:"div",open:e,onClose:t,className:"mercoa-relative mercoa-z-10",children:[f.jsx("div",{className:"mercoa-fixed mercoa-inset-0 mercoa-bg-black/30","aria-hidden":"true"}),f.jsx("div",{className:"mercoa-fixed mercoa-inset-0 mercoa-overflow-y-auto",children:f.jsx("div",{className:"mercoa-flex mercoa-min-h-full mercoa-items-end mercoa-justify-center mercoa-p-4 mercoa-text-center sm:mercoa-items-center sm:mercoa-p-0",children:f.jsxs(fn.Panel,{className:"mercoa-relative mercoa-transform mercoa-rounded-mercoa mercoa-bg-white mercoa-shadow-xl mercoa-transition-all sm:mercoa-p-6",children:[f.jsx(fn.Title,{className:"mercoa-text-lg mercoa-font-semibold",children:"When should these payments be scheduled?"}),f.jsxs("div",{className:"mercoa-flex mercoa-mt-5",children:[f.jsx(FW,{className:"mercoa-block mercoa-w-full mercoa-rounded-mercoa mercoa-border-gray-300 focus:mercoa-border-mercoa-primary focus:mercoa-ring-mercoa-primary sm:mercoa-text-sm",placeholderText:"Select Payment Date",onChange:a=>o(a),selected:n,minDate:He().add(1,"day").toDate(),filterDate:XG}),f.jsx(Ue,{type:"button",className:"mercoa-ml-2",isEmphasized:!0,onClick:()=>{n&&r(n),t()},disabled:!n,children:"Schedule Payments"})]})]})})})]})}function N9e({open:e,onClose:t,setApprover:r}){const n=Le(),[o,a]=w.useState([]),[i,s]=w.useState();return w.useEffect(()=>{var c;n.entityId&&((c=n.client)==null||c.entity.user.getAll(n.entityId).then(l=>{a(l)}).catch(l=>{console.error(l)}))},[n.token,n.entityId]),f.jsxs(fn,{as:"div",open:e,onClose:t,className:"mercoa-relative mercoa-z-10",children:[f.jsx("div",{className:"mercoa-fixed mercoa-inset-0 mercoa-bg-black/30","aria-hidden":"true"}),f.jsx("div",{className:"mercoa-fixed mercoa-inset-0 mercoa-overflow-y-auto",children:f.jsx("div",{className:"mercoa-flex mercoa-min-h-full mercoa-items-end mercoa-justify-center mercoa-p-4 mercoa-text-center sm:mercoa-items-center sm:mercoa-p-0",children:f.jsxs(fn.Panel,{className:"mercoa-relative mercoa-transform mercoa-rounded-mercoa mercoa-bg-white mercoa-shadow-xl mercoa-transition-all sm:mercoa-p-6",children:[f.jsx(en,{title:"User will be added to the first available approval slot they are eligible for",children:f.jsxs(fn.Title,{className:"mercoa-text-lg mercoa-font-semibold mercoa-flex mercoa-items-center mercoa-justify-center",children:["Select Approver To Add",f.jsx(DF,{className:"mercoa-size-5 mercoa-ml-2"})]})}),f.jsxs("div",{className:"mercoa-flex mercoa-mt-5",children:[f.jsx(In,{options:o.map(c=>({disabled:!1,value:c})),displayIndex:"name",secondaryDisplayIndex:"email",onChange:c=>{n.debug(c),s(c)},value:i,displaySelectedAs:"pill"}),f.jsx(Ue,{type:"button",className:"mercoa-ml-2",isEmphasized:!0,onClick:()=>{i&&r(i.id),t()},disabled:!i,children:"Add Approver"})]})]})})})]})}function bY({statuses:e,search:t,metadata:r,startDate:n,endDate:o,onSelectInvoice:a,columns:i,children:s}){const c=Le(),[l,u]=w.useState(),[h,p]=w.useState(0),[m,g]=w.useState(G.Mercoa.InvoiceOrderByField.CreatedAt),[b,_]=w.useState(G.Mercoa.OrderDirection.Asc),[y,x]=w.useState(!0),[O,S]=w.useState(0),[j,P]=w.useState(!1),[I,M]=w.useState(e),[E,D]=w.useState([]),[A,z]=w.useState(20),[$,L]=w.useState(1),B=w.useRef(null),[W,K]=w.useState(!1),[Z,re]=w.useState(!1),[ue,ge]=w.useState([]),[H,R]=w.useState(!1),[Q,ae]=w.useState(!1),[k,N]=w.useState(!1);w.useLayoutEffect(()=>{const de=ue.length>0&&ue.length<(l?l.length:0);K(ue.length===(l?l.length:0)),re(de),B.current&&(B.current.indeterminate=de)},[ue,l]);function q(){ge(W||Z?[]:l??[]),K(!W&&!Z),re(!1)}async function ie(de){var fe;if(!c.token||!((fe=c.entity)!=null&&fe.id))return;P(!1);let F=!1;await Promise.all(ue.map(async se=>{var Pe;try{await((Pe=c.client)==null?void 0:Pe.invoice.update(se.id,{...(se.status===G.Mercoa.InvoiceStatus.Approved||se.status===G.Mercoa.InvoiceStatus.Failed)&&{status:G.Mercoa.InvoiceStatus.Scheduled},deductionDate:de})),F=!0}catch(Ie){console.error("Error updating invoice: ",Ie),console.log("Errored invoice: ",{invoice:se})}})),F?Ae.success("Payment Scheduled"):Ae.error("Error scheduling payment"),c.refresh()}async function le(de){var fe;if(!c.token||!((fe=c.entity)!=null&&fe.id))return;let F=!1;P(!1),await Promise.all(ue.map(async se=>{var Pe;try{await((Pe=c.client)==null?void 0:Pe.invoice.approval.addApprover(se.id,{userId:de})),F=!0}catch(Ie){console.error("Error adding approver to invoice ",Ie),console.log("Errored invoice: ",{invoice:se})}})),F?Ae.success("Approver Added"):Ae.error("Error adding approver"),c.refresh()}function U(de){let F=G.Mercoa.InvoiceStatus.Approved;const fe=de.approvalPolicy;return fe&&fe.length>0&&(F=G.Mercoa.InvoiceStatus.New),F}async function X(){var F;if(!c.token||!((F=c.entity)!=null&&F.id))return;let de=!1;P(!1),await Promise.all(ue.map(async fe=>{var se;try{await((se=c.client)==null?void 0:se.invoice.update(fe.id,{status:U(fe)})),de=!0}catch(Pe){console.error("Error submitting invoice: ",Pe),console.log("Errored invoice: ",{invoice:fe})}})),de?Ae.success("Invoice Submitted for Approval"):Ae.error("Error submitting invoice"),c.refresh()}async function be(){var F;if(!c.token||!((F=c.entity)!=null&&F.id))return;let de=!1;P(!1),await Promise.all(ue.map(async fe=>{var se;try{await((se=c.client)==null?void 0:se.invoice.delete(fe.id)),de=!0}catch(Pe){console.error("Error deleting invoice: ",Pe),console.log("Errored invoice: ",{invoice:fe})}})),de?Ae.success("Invoices Deleted"):Ae.error("Error deleting invoices"),c.refresh()}async function xe(){var F;if(!c.token||!((F=c.entity)!=null&&F.id))return;let de=!1;P(!1),await Promise.all(ue.map(async fe=>{var se;try{await((se=c.client)==null?void 0:se.invoice.update(fe.id,{status:G.Mercoa.InvoiceStatus.Archived})),de=!0}catch(Pe){console.error("Error archiving invoice: ",Pe),console.log("Errored invoice: ",{invoice:fe})}})),de?Ae.success("Invoices Archived"):Ae.error("Error archiving invoices"),c.refresh()}async function Ce(){var F;if(!c.token||!((F=c.entity)!=null&&F.id))return;let de=!1;P(!1),await Promise.all(ue.map(async fe=>{var se;try{await((se=c.client)==null?void 0:se.invoice.update(fe.id,{status:G.Mercoa.InvoiceStatus.Canceled})),de=!0}catch(Pe){console.error("Error cancelling invoice: ",Pe),console.log("Errored invoice: ",{invoice:fe})}})),de?Ae.success("Payments Cancelled"):Ae.error("Error cancelling payments"),c.refresh()}async function Te(){var F;if(!c.token||!((F=c.entity)!=null&&F.id)||!c.user)return;let de=!1;P(!1),await Promise.all(ue.map(async fe=>{var se,Pe,Ie;try{const nt=await((se=c.client)==null?void 0:se.invoice.get(fe.id));if((nt==null?void 0:nt.status)!=G.Mercoa.InvoiceStatus.New){de=!0;return}await((Ie=c.client)==null?void 0:Ie.invoice.approval.approve(fe.id,{userId:(Pe=c.user)==null?void 0:Pe.id})),de=!0}catch(nt){console.error("Error approving invoice: ",nt),console.log("Errored invoice: ",{invoice:fe})}})),de&&Ae.success("Approved"),c.refresh()}async function Ee(){var F;if(!c.token||!((F=c.entity)!=null&&F.id)||!c.user)return;let de=!1;P(!1),await Promise.all(ue.map(async fe=>{var se,Pe,Ie;try{const nt=await((se=c.client)==null?void 0:se.invoice.get(fe.id));if((nt==null?void 0:nt.status)!=G.Mercoa.InvoiceStatus.New){de=!0;return}await((Ie=c.client)==null?void 0:Ie.invoice.approval.reject(fe.id,{userId:(Pe=c.user)==null?void 0:Pe.id})),de=!0}catch(nt){console.error("Error rejecting invoice: ",nt),console.log("Errored invoice: ",{invoice:fe})}})),de&&Ae.success("Rejected"),c.refresh()}async function ne(){var se;if(!c.token||!((se=c.entity)!=null&&se.id))return;let de="",F=[];fe();async function fe(){var nt,V,T;if(!c.token||!((nt=c.entity)!=null&&nt.id))return;const Pe={status:I,search:t,startDate:n,endDate:o,orderBy:m,orderDirection:b,...k&&{approverId:(V=c.user)==null?void 0:V.id,approverAction:G.Mercoa.ApproverAction.None},limit:100,startingAfter:de,excludeReceivables:!0,metadata:r},Ie=await((T=c.client)==null?void 0:T.entity.invoice.find(c.entity.id,Pe));if(Ie)if(Ie.data.length>0)de=Ie.data[Ie.data.length-1].id,F=[...F,...Ie.data],await fe();else{const C=pY.unparse(F.map(Se=>{var ve,tt,et,ut,wt,dt;return{"Invoice ID":Se.id,"Invoice Number":Se.invoiceNumber,Status:Se.status,Amount:Se.amount,Currency:Se.currency,Note:Se.noteToSelf,"Payer ID":(ve=Se.payer)==null?void 0:ve.id,"Payer Email":(tt=Se.payer)==null?void 0:tt.email,"Payer Name":(et=Se.payer)==null?void 0:et.name,"Vendor ID":(ut=Se.vendor)==null?void 0:ut.id,"Vendor Email":(wt=Se.vendor)==null?void 0:wt.email,"Vendor Name":(dt=Se.vendor)==null?void 0:dt.name,Metadata:JSON.stringify(Se.metadata),"Due Date":He(Se.dueDate),"Deduction Date":He(Se.deductionDate),"Processed At":He(Se.processedAt),"Created At":He(Se.createdAt),"Updated At":He(Se.updatedAt)}})),oe=new Blob([C],{type:"text/csv"}),ye=window.URL.createObjectURL(oe),je=document.createElement("a");je.setAttribute("mercoa-hidden",""),je.setAttribute("href",ye),je.setAttribute("download",`mercoa-invoice-export-${He().format("YYYY-MM-DD")}.csv`),document.body.appendChild(je),je.click(),document.body.removeChild(je)}}}if(w.useEffect(()=>{M(e)},[e]),w.useEffect(()=>{var fe,se,Pe,Ie,nt;if(!c.token||!((fe=c.entity)!=null&&fe.id))return;let de=!0;ge([]),P(!1);const F={status:I,search:t,startDate:n,endDate:o,orderBy:m,orderDirection:b,...k&&{approverId:(se=c.user)==null?void 0:se.id,approverAction:G.Mercoa.ApproverAction.None},limit:A,startingAfter:E[E.length-1],excludeReceivables:!0,metadata:r};return(Pe=c.client)==null||Pe.entity.invoice.find(c.entity.id,F).then(V=>{V&&de&&(x(V.hasMore),S(V.count),u(V.data),P(!0))}),I.includes(G.Mercoa.InvoiceStatus.New)&&((nt=c.client)==null||nt.entity.invoice.find(c.entity.id,{...F,approverId:(Ie=c.user)==null?void 0:Ie.id,approverAction:G.Mercoa.ApproverAction.None}).then(V=>{V&&de&&p(V.count)})),()=>{de=!1}},[c.token,c.entity,c.refreshId,I,t,n,o,r,m,b,E,A,k]),w.useEffect(()=>{L(1),D([])},[t]),w.useEffect(()=>{e.some(de=>I.indexOf(de)<0)&&(M(e),N(!1),P(!1),D([]),L(1),S(0))},[e,n,o]),s)return s({dataLoaded:j,invoices:l||[],hasNext:y,getNext:()=>{l&&(L($+1),D([...E,l[l.length-1].id]))},hasPrevious:$!==1,getPrevious:()=>{L(Math.max(1,$-1)),D(E.slice(0,E.length-1))},resultsPerPage:A,setResultsPerPage:z,page:$,setPage:de=>{l&&L(de)},orderBy:m,setOrderBy:g,orderDirection:b,setOrderDirection:_,selectedInvoiceStatuses:I,setSelectedInvoiceStatues:M,downloadCSV:ne,count:O});if(!j||!c.entity||!l)return f.jsx("div",{className:"mercoa-min-h-[710px] mercoa-min-w-[710px]",children:f.jsx(Fm,{rows:20})});const te=[{title:"Vendor",field:"vendor",orderBy:G.Mercoa.InvoiceOrderByField.VendorName},{title:"Invoice Number",field:"invoiceNumber",orderBy:G.Mercoa.InvoiceOrderByField.InvoiceNumber},{title:"Due Date",field:"dueDate",orderBy:G.Mercoa.InvoiceOrderByField.DueDate},{title:"Amount",field:"amount",orderBy:G.Mercoa.InvoiceOrderByField.Amount},{title:"Approvers",field:"approvers",format:(de,F)=>{var fe;return F.approvers.every(se=>!se.assignedUserId)?null:f.jsx("div",{className:"mercoa-gap-1 mercoa-grid",children:(fe=F.approvers)==null?void 0:fe.map(se=>{if(!se.assignedUserId)return null;const Pe=c.users.find(Ie=>Ie.id===se.assignedUserId);return f.jsx(en,{title:Pe==null?void 0:Pe.email,children:f.jsx("div",{className:`mercoa-flex mercoa-items-center mercoa-rounded-mercoa mercoa-text-xs ${se.action===G.Mercoa.ApproverAction.Approve?"mercoa-bg-green-100 mercoa-text-green-800":""} ${se.action===G.Mercoa.ApproverAction.Reject?"mercoa-bg-red-100 mercoa-text-red-800":""} ${se.action===G.Mercoa.ApproverAction.None?"mercoa-bg-gray-50 mercoa-text-gray-800":""} mercoa-py-1 mercoa-px-2`,children:Pe==null?void 0:Pe.name},se.approvalSlotId)},se.approvalSlotId)})})}},{title:"Payment Destination",field:"paymentDestination",format:de=>(de=de,!de||!de.type?null:de.type===G.Mercoa.PaymentMethodType.BankAccount?`${de==null?void 0:de.bankName} ••••${String(de==null?void 0:de.accountNumber).slice(-4)}`:de.type===G.Mercoa.PaymentMethodType.Check?`Check • ${String(de==null?void 0:de.addressLine1).slice(-10)}`:de.type===G.Mercoa.PaymentMethodType.Custom?`${de==null?void 0:de.accountName} ••••${String(de==null?void 0:de.accountNumber).slice(-4)}`:null)},{title:"Status",field:"status",format:(de,F)=>f.jsx(YT,{failureType:F.failureType,status:F.status,vendorId:F.vendorId,payerId:F.payerId,paymentDestinationId:F.paymentDestinationId,paymentSourceId:F.paymentSourceId,dueDate:F.dueDate,amount:F.amount,type:"payable"})},{title:"Deduction Date",field:"deductionDate"}];function _e(de){return l?l.some(F=>de.field.startsWith("metadata.")?!0:F[`${de.field}`]&&de.format?de.format(F[`${de.field}`],F):F[`${de.field}`]):!1}const Me=f.jsx("thead",{children:f.jsxs("tr",{children:[f.jsx("th",{scope:"col",className:"mercoa-relative mercoa-px-7 sm:mercoa-w-12 sm:mercoa-px-6",children:l.length>0&&f.jsx("input",{type:"checkbox",className:"mercoa-absolute mercoa-left-4 mercoa-top-1/2 -mercoa-mt-2 mercoa-size-4 mercoa-rounded mercoa-border-gray-300 mercoa-text-mercoa-primary-text focus:mercoa-ring-mercoa-primary",ref:B,checked:W,onChange:q})}),(i??te).map((de,F)=>!_e(de)&&l.length>0?null:f.jsx("th",{scope:"col",className:`mercoa-min-w-[12rem] mercoa-py-3.5 mercoa-pl-4 mercoa-pr-3 mercoa-text-left mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 sm:mercoa-pl-3 ${ue.length>0?"mercoa-invisible":""}`,children:de.orderBy?f.jsx(Rm,{title:de.title,setOrder:fe=>{de.orderBy&&(g(de.orderBy),_(fe))},isSelected:m===de.orderBy,orderDirection:b}):de.title},F))]})}),Oe=f.jsx("tbody",{className:"mercoa-divide-y mercoa-divide-gray-200 mercoa-bg-white",children:l.map(de=>f.jsxs("tr",{className:$c("mercoa-cursor-pointer hover:mercoa-bg-gray-100",ue.includes(de)?"mercoa-bg-gray-50":void 0),children:[f.jsxs("td",{className:"mercoa-relative mercoa-px-7 sm:mercoa-w-12 sm:mercoa-px-6",children:[ue.includes(de)&&f.jsx("div",{className:"mercoa-absolute mercoa-inset-y-0 mercoa-left-0 mercoa-w-0.5 mercoa-bg-mercoa-primary"}),f.jsx("input",{type:"checkbox",className:"mercoa-absolute mercoa-left-4 mercoa-top-1/2 -mercoa-mt-2 mercoa-size-4 mercoa-rounded mercoa-border-gray-300 mercoa-text-mercoa-primary-text focus:mercoa-ring-mercoa-primary",value:de.id,checked:ue.includes(de),onChange:F=>ge(F.target.checked?[...ue,de]:ue.filter(fe=>fe!==de))})]}),(i??te).map((F,fe)=>{if(!_e(F))return null;let se;return F.field.startsWith("metadata.")?se=JSON.stringify(de.metadata[F.field.split(".")[1]]):se=de[F.field],F.format?se=F.format(se,de):F.field==="amount"?se=ea.formatMoney(se??"",nn(de.currency)):se instanceof Date?se=He(se).format("MMM DD, YYYY"):typeof se=="object"?se.name?se=se.name:se=JSON.stringify(se):se=(se==null?void 0:se.toString())??"",f.jsx("td",{className:`mercoa-whitespace-nowrap mercoa-py-3 mercoa-pl-4 mercoa-pr-3 mercoa-text-sm mercoa-text-gray-900 sm:mercoa-pl-3 ${ue.includes(de)?"mercoa-text-mercoa-primary-text":"mercoa-text-gray-900"} ${fe===0?"mercoa-font-medium":""}`,onClick:()=>{a&&a(de)},children:se},fe)})]},de.id))});return c.client?f.jsxs("div",{children:[f.jsxs("div",{className:"mercoa-min-h-[600px]",children:[I.includes(G.Mercoa.InvoiceStatus.New)&&h>0&&f.jsx("div",{className:"mercoa-flex mercoa-items-center mercoa-justify-start mercoa-my-4 mercoa-ml-4",children:f.jsxs("div",{className:"mercoa-flex mercoa-items-center mercoa-font-bold mercoa-font-xl mercoa-text-gray-600",children:[f.jsx("input",{id:"showOnlyInvoicesThatUserNeedsToApprove",type:"checkbox",className:"mercoa-mr-2 mercoa-size-4 mercoa-rounded mercoa-border-gray-300 focus:mercoa-ring-mercoa-primary mercoa-text-mercoa-primary-text mercoa-cursor-pointer",checked:k,onChange:()=>N(!k)}),f.jsxs("label",{htmlFor:"showOnlyInvoicesThatUserNeedsToApprove",className:"mercoa-cursor-pointer",children:["Only show invoices that need my approval ",f.jsx(PN,{count:h,selected:!0})]})]})}),f.jsxs("div",{className:"mercoa-relative mercoa-grid",style:{gridTemplateColumns:"repeat(1, minmax(0, 1fr))",overflow:"auto",whiteSpace:"normal"},children:[f.jsxs("div",{className:"mercoa-absolute mercoa-left-14 mercoa-top-6 mercoa-flex mercoa-h-12 mercoa-items-center mercoa-space-x-3 mercoa-bg-white sm:mercoa-left-12",children:[I.includes(G.Mercoa.InvoiceStatus.Draft)&&ue.length>0&&f.jsxs(f.Fragment,{children:[U(ue[0])===G.Mercoa.InvoiceStatus.New&&f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:()=>ae(!0),children:"Add Approver"}),f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:X,children:U(ue[0])===G.Mercoa.InvoiceStatus.New?"Submit for Approval":"Approve"}),f.jsx(N9e,{open:Q,onClose:()=>ae(!1),setApprover:le})]}),I.some(de=>[G.Mercoa.InvoiceStatus.Draft,G.Mercoa.InvoiceStatus.New,G.Mercoa.InvoiceStatus.Approved,G.Mercoa.InvoiceStatus.Failed].includes(de))&&ue.length>0&&f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:()=>R(!0),children:I.some(de=>[G.Mercoa.InvoiceStatus.Draft,G.Mercoa.InvoiceStatus.New].includes(de))?"Set Payment Date":"Schedule Payment"}),f.jsx(gY,{open:H,onClose:()=>R(!1),setDate:ie})]}),I.includes(G.Mercoa.InvoiceStatus.Scheduled)&&ue.length>0&&f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:()=>R(!0),children:"Reschedule Payment"}),f.jsx(gY,{open:H,onClose:()=>R(!1),setDate:ie})]}),I.includes(G.Mercoa.InvoiceStatus.New)&&ue.length>0&&ue.some(de=>de.approvers.some(F=>{var fe;return F.assignedUserId===((fe=c.user)==null?void 0:fe.id)}))&&f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:Te,children:"Approve"}),f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:Ee,children:"Reject"})]}),I.includes(G.Mercoa.InvoiceStatus.Draft)&&ue.length>0&&f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:()=>{confirm("Are you sure you want to delete these invoices? This action cannot be undone.")&&be()},children:"Delete"}),I.some(de=>[G.Mercoa.InvoiceStatus.New,G.Mercoa.InvoiceStatus.Approved,G.Mercoa.InvoiceStatus.Refused,G.Mercoa.InvoiceStatus.Scheduled,G.Mercoa.InvoiceStatus.Failed].includes(de))&&ue.length>0&&f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:()=>{confirm("Are you sure you want to cancel these invoices? This action cannot be undone.")&&Ce()},children:"Cancel"}),I.some(de=>[G.Mercoa.InvoiceStatus.Paid,G.Mercoa.InvoiceStatus.Canceled].includes(de))&&ue.length>0&&f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:()=>{confirm("Are you sure you want to archive these invoices? This action cannot be undone.")&&xe()},children:"Archive"})]}),f.jsxs("table",{className:"mercoa-min-w-full mercoa-divide-y mercoa-divide-gray-300 mercoa-mt-5",children:[Me,Oe]})]})]}),f.jsx($m,{data:l,page:$,setPage:L,hasMore:y,startingAfter:E,setStartingAfter:D,count:O,resultsPerPage:A,setResultsPerPage:z,downloadAll:ne})]}):f.jsx(at,{componentName:"PayablesTable"})}function YT({status:e,failureType:t,amount:r,payerId:n,vendorId:o,dueDate:a,paymentSourceId:i,paymentDestinationId:s,type:c}){const l=c==="receivable"?n:o;let u="mercoa-bg-gray-100",h="mercoa-text-black",p="";return!e||e===G.Mercoa.InvoiceStatus.Draft?!l||!r||!a?(u="mercoa-bg-yellow-100",h="mercoa-text-black",p="Draft Incomplete"):(u="mercoa-bg-green-100",h="mercoa-text-green-800",p="Draft Ready"):e===G.Mercoa.InvoiceStatus.New?!i||!l||!r||!a?(u="mercoa-bg-yellow-100",h="mercoa-text-gray-800",p="Incomplete"):(u="mercoa-bg-green-100",h="mercoa-text-green-800",p="Ready for Review"):e===G.Mercoa.InvoiceStatus.Approved?!i||!s||!l||!r||!a?(u="mercoa-bg-yellow-100",h="mercoa-text-black",p="Incomplete"):(u="mercoa-bg-green-100",h="mercoa-text-green-800",p=c==="receivable"?"Out for Payment":"Ready for Payment"):e===G.Mercoa.InvoiceStatus.Scheduled?!i||!s||!l||!r||!a?(u="mercoa-bg-yellow-100",h="mercoa-text-black",p="Incomplete"):(u="mercoa-bg-green-100",h="mercoa-text-green-800",p="Payment Scheduled"):e===G.Mercoa.InvoiceStatus.Pending?(u="mercoa-bg-yellow-100",h="mercoa-text-black",p="Payment Processing"):e===G.Mercoa.InvoiceStatus.Paid?(u="mercoa-bg-green-100",h="mercoa-text-green-800",p="Paid"):e===G.Mercoa.InvoiceStatus.Canceled?(u="mercoa-bg-red-100",h="mercoa-text-red-800",p="Canceled"):e===G.Mercoa.InvoiceStatus.Archived?(u="mercoa-bg-gray-100",h="mercoa-text-black",p="Archived"):e===G.Mercoa.InvoiceStatus.Refused?(u="mercoa-bg-red-100",h="mercoa-text-red-800",p="Rejected"):e===G.Mercoa.InvoiceStatus.Failed&&(u="mercoa-bg-red-100",h="mercoa-text-red-800",p="Failed",t===G.Mercoa.InvoiceFailureType.InsufficientFunds?p="Insufficient Funds":t===G.Mercoa.InvoiceFailureType.ProcessingError?p="Processing Error":t===G.Mercoa.InvoiceFailureType.DestinationPaymentError?p="Destination Payment Error":t===G.Mercoa.InvoiceFailureType.SourcePaymentError?p="Source Payment Error":t===G.Mercoa.InvoiceFailureType.RejectedHighRisk&&(p="Rejected High Risk")),p?f.jsx("p",{className:`mercoa-inline-flex mercoa-items-center mercoa-whitespace-nowrap mercoa-rounded-full mercoa-px-3 mercoa-py-0.5 mercoa-text-xs mercoa-font-medium ${u} ${h} md:mercoa-ml-2`,children:p}):f.jsx(f.Fragment,{})}function DR({statuses:e,search:t,returnByDate:r,excludePayables:n,excludeReceivables:o,children:a}){typeof n>"u"&&typeof o>"u"&&(o=!0);const i=Le(),[s,c]=w.useState();function l(h){const p=Object.entries(h).filter(([m])=>e.indexOf(m)>-1);return p==null?void 0:p.reduce((m,[,g])=>(m+=g.totalCount,m),0)}function u(h,p){const m=Object.entries(h).filter(([g])=>e.indexOf(g)>-1);return!m||m.length<1?ea.formatMoney(0,nn("USD")):m.length<2?ea.formatMoney(m[0][1][p]??0??"",nn(m[0][1].currency)):f.jsx("div",{children:m.map(([g,b])=>f.jsxs("p",{className:"mercoa-text-xs",children:[f.jsxs("span",{className:"mercoa-text-gray-600",children:[g,": "]}),f.jsx("span",{className:"mercoa-text-gray-900",children:ea.formatMoney(b[p]??0??"",nn(b.currency))}),f.jsxs("span",{className:"mercoa-text-gray-500",children:[" ",b.currency]})]},b.currency))})}return w.useEffect(()=>{var h;c(void 0),!(!i.token||!((h=i.entity)!=null&&h.id))&&mY({statuses:e,search:t,mercoaSession:i,setMetrics:c,returnByDate:r,excludePayables:n??!1,excludeReceivables:o??!1})},[t,e,i.token,i.entity,i.refreshId]),a?a({metrics:s}):i.client?f.jsx("div",{className:"mercoa-grid mercoa-grid-cols-3 mercoa-space-x-3 mercoa-mt-2 mercoa-mb-1 mercoa-min-h-[60px]",children:s?f.jsxs(f.Fragment,{children:[f.jsx(uT,{size:"sm",title:"Number of Invoices",value:l(s)}),f.jsx(uT,{size:"sm",title:"Total Amount",value:u(s,"totalAmount")}),f.jsx(uT,{size:"sm",title:"Average Amount",value:u(s,"averageAmount")})]}):f.jsxs(f.Fragment,{children:[f.jsx(Fm,{rows:2}),f.jsx(Fm,{rows:2}),f.jsx(Fm,{rows:2})]})}):f.jsx(at,{componentName:"InvoiceMetrics"})}function IR({statuses:e,selectedStatus:t,search:r,onStatusChange:n,excludePayables:o,excludeReceivables:a}){const i=Le(),[s,c]=w.useState([t??G.Mercoa.InvoiceStatus.Draft]),[l,u]=w.useState(),[h,p]=w.useState(e??[G.Mercoa.InvoiceStatus.Draft,G.Mercoa.InvoiceStatus.New,G.Mercoa.InvoiceStatus.Approved,G.Mercoa.InvoiceStatus.Scheduled,G.Mercoa.InvoiceStatus.Pending,G.Mercoa.InvoiceStatus.Paid,G.Mercoa.InvoiceStatus.Canceled,G.Mercoa.InvoiceStatus.Refused,G.Mercoa.InvoiceStatus.Failed]);w.useEffect(()=>{var b,_;!i.token||!((b=i.entity)!=null&&b.id)||(_=i.client)==null||_.entity.approvalPolicy.getAll(i.entity.id).then(y=>u(y)).catch(()=>u(void 0))},[i.token,i.entity,i.refreshId]),w.useEffect(()=>{n&&n(s)},[s]),w.useEffect(()=>{Array.isArray(l)&&(e?p(e):(!l||(l==null?void 0:l.length)<1)&&p(h.filter(b=>b!==G.Mercoa.InvoiceStatus.New)))},[e,l]);const[m,g]=w.useState();return w.useEffect(()=>{var b;!i.token||!((b=i.entity)!=null&&b.id)||mY({statuses:h,search:r,mercoaSession:i,setMetrics:g,excludePayables:o??!1,excludeReceivables:a??!1})},[r,h,i.client,i.entity,i.refreshId]),i.client?f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"md:mercoa-hidden mercoa-mt-2",children:[f.jsx("label",{htmlFor:"tabs",className:"mercoa-sr-only",children:"Select a tab"}),f.jsx("select",{id:"tabs",name:"tabs",className:"mercoa-block mercoa-w-full mercoa-rounded-mercoa mercoa-border-gray-300 mercoa-py-1 mercoa-pl-3 mercoa-pr-10 mercoa-text-base focus:mercoa-border-mercoa-primary focus:mercoa-outline-none focus:mercoa-ring-mercoa-primary sm:mercoa-text-sm",defaultValue:s,multiple:!0,onChange:b=>{c([b.target.value])},children:h.map(b=>f.jsx("option",{value:b,children:CR(b,l,o)},b))})]}),f.jsx("div",{className:"mercoa-hidden md:mercoa-block sm:mercoa-border-b sm:mercoa-border-gray-200",children:f.jsx("nav",{className:"-mercoa-mb-px mercoa-block sm:mercoa-flex sm:mercoa-space-x-6 mercoa-overflow-auto","aria-label":"Tabs",children:h.map(b=>{var _;return f.jsxs("a",{onClick:()=>{c([b])},href:"#",className:`${b==s[0]?"mercoa-text-mercoa-primary sm:mercoa-border-mercoa-primary":"mercoa-border-transparent mercoa-text-gray-500 hover:mercoa-border-gray-300 hover:mercoa-text-gray-700"} mercoa-mr-2 mercoa-whitespace-nowrap mercoa-py-4 mercoa-px-1 mercoa-text-sm mercoa-font-medium sm:mercoa-mr-0 sm:mercoa-border-b-2`,"aria-current":CR(b,l,o)==s[0]?"page":void 0,children:[CR(b,l,o)," ",f.jsx(PN,{count:((_=m==null?void 0:m[b])==null?void 0:_.totalCount)??0,selected:b==s[0]})]},b)})})})]}):f.jsx(at,{componentName:"StatusTabs"})}function zR({availableStatuses:e,currentStatuses:t,onStatusChange:r,placeholder:n,label:o,className:a,multiple:i}){const[s,c]=w.useState(t??[G.Mercoa.InvoiceStatus.Draft]),l=e??[G.Mercoa.InvoiceStatus.Draft,G.Mercoa.InvoiceStatus.New,G.Mercoa.InvoiceStatus.Approved,G.Mercoa.InvoiceStatus.Scheduled,G.Mercoa.InvoiceStatus.Pending,G.Mercoa.InvoiceStatus.Paid,G.Mercoa.InvoiceStatus.Canceled,G.Mercoa.InvoiceStatus.Refused,G.Mercoa.InvoiceStatus.Failed],u={UNASSIGNED:"#E0E7FF",DRAFT:"#E0E7FF",NEW:"#E0F2FE",APPROVED:"#BEF264",SCHEDULED:"#D1FAE5",PENDING:"#FDE68A",FAILED:"#FCA5A5",PAID:"#ECFCCB",CANCELED:"#E5E7EB",REFUSED:"#FEE2E2",ARCHIVED:"#E5E7EB"};return w.useEffect(()=>{r&&(Array.isArray(s)?r(s):r([s]))},[s]),f.jsx(f.Fragment,{children:f.jsx(In,{options:l.map(h=>({value:h,disabled:!1,color:u[h]})),onChange:h=>{c(h)},value:s,multiple:i,displaySelectedAs:"pill",placeholder:n??"All Invoices",label:o,inputClassName:a})})}function vY({statuses:e,onSelectInvoice:t,statusSelectionStyle:r,columns:n}){const[o,a]=w.useState([G.Mercoa.InvoiceStatus.Draft]),[i,s]=w.useState("");return f.jsxs("div",{className:"mercoa-mt-8",children:[f.jsxs("div",{className:"mercoa-grid mercoa-items-center mercoa-grid-cols-3",children:[f.jsx("div",{className:"mercoa-hidden md:mercoa-block md:mercoa-col-span-2",children:r=="dropdown"&&f.jsx("div",{className:"mercoa-grid mercoa-grid-cols-2",children:f.jsx(zR,{availableStatuses:e,onStatusChange:a,multiple:!0})})}),f.jsx("div",{className:"mercoa-flex mercoa-w-full mercoa-rounded-mercoa mercoa-shadow-sm mercoa-mr-2 mercoa-col-span-3 md:mercoa-col-span-1",children:f.jsx(lT,{placeholder:"Search Vendors, Invoice #, Amount",onSettle:s})})]}),r!="dropdown"&&f.jsx(IR,{statuses:e,search:i,onStatusChange:a,excludeReceivables:!0}),f.jsx(DR,{statuses:o,search:i,excludeReceivables:!0}),f.jsx(bY,{statuses:o,search:i,onSelectInvoice:t,columns:n})]})}function yY(){var t,r,n,o,a,i,s,c,l;const e=Le();return e.client?f.jsxs("div",{children:[((n=(r=(t=e.organization)==null?void 0:t.paymentMethods)==null?void 0:r.payerPayments)==null?void 0:n.find(u=>u.type===G.Mercoa.PaymentMethodType.BankAccount&&u.active))&&f.jsxs(f.Fragment,{children:[f.jsx("h3",{className:"mercoa-mt-8",children:"Bank Accounts"}),f.jsx(XH,{showEdit:!0,showAdd:!0})]}),((i=(a=(o=e.organization)==null?void 0:o.paymentMethods)==null?void 0:a.payerPayments)==null?void 0:i.find(u=>u.type===G.Mercoa.PaymentMethodType.Card&&u.active))&&f.jsxs(f.Fragment,{children:[f.jsx("h3",{className:"mercoa-mt-8",children:"Cards"}),f.jsx(YH,{showEdit:!0,showAdd:!0})]}),((l=(c=(s=e.organization)==null?void 0:s.paymentMethods)==null?void 0:c.payerPayments)==null?void 0:l.find(u=>u.type===G.Mercoa.PaymentMethodType.Custom&&u.active))&&f.jsxs(f.Fragment,{children:[f.jsx("h3",{className:"mercoa-mt-8",children:"Custom Payment Methods"}),f.jsx(x9,{showEdit:!0})]})]}):f.jsx(at,{componentName:"PaymentMethods"})}function R9e({selectedPayer:e,paymentDestination:t}){const[r,n]=w.useState("pdf"),o=Le(),{watch:a}=kt(),i=a(),s={id:i.id??"",status:i.status??"DRAFT",invoiceNumber:i.invoiceNumber,amount:i.amount,currency:i.currency??"USD",payerId:i.payerId,payer:e,vendor:o.entity,invoiceDate:i.invoiceDate,dueDate:i.dueDate,lineItems:i.lineItems,deductionDate:i.deductionDate,paymentDestination:t,paymentDestinationId:i.paymentDestinationId,paymentDestinationOptions:i.paymentDestinationOptions,paymentSourceId:i.paymentSourceId,noteToSelf:i.description,hasDocuments:i.hasDocuments??!1,metadata:i.metadata??{},comments:i.comments??[],creatorUser:i.creatorUser,paymentDestinationConfirmed:!1,hasSourceEmail:!1,approvers:[],approvalPolicy:[],createdAt:new Date,updatedAt:new Date},c=[{name:"Invoice PDF",action:"pdf"},{name:"Payment Page",action:"paymentPage"}];return f.jsx("div",{className:"mercoa-h-full mercoa-w-full mercoa-flex mercoa-flex-col mercoa-justify-center mercoa-items-center",children:f.jsxs("div",{className:"mercoa-h-full mercoa-w-[740px] mercoa-flex mercoa-flex-col mercoa-items-center",children:[f.jsx("nav",{className:"-mercoa-mb-px mercoa-flex mercoa-space-x-8",children:c.map(l=>f.jsx("button",{onClick:()=>n(l.action),className:`${l.action===r?"mercoa-border-mercoa-primary mercoa-text-mercoa-primary":"mercoa-border-transparent mercoa-text-gray-500 hover:mercoa-border-gray-300 hover:mercoa-text-gray-700"} mercoa-whitespace-nowrap mercoa-border-b-2 mercoa-px-1 mercoa-pb-4 mercoa-text-sm mercoa-font-medium`,children:l.name},l.name))}),f.jsxs("div",{style:{transform:"scale(0.75)"},className:"mercoa-w-full mercoa-grow mercoa-border mercoa-rounded-mercoa mercoa-shadow-md mercoa-p-10",children:[r==="pdf"&&f.jsx($9e,{invoice:s}),r==="email"&&f.jsx(F9e,{invoice:s}),r==="paymentPage"&&f.jsx(B9e,{invoice:s})]})]})})}function $9e({invoice:e}){return f.jsx(wY,{invoice:e})}function F9e({invoice:e}){const[t,r]=w.useState("");return w.useEffect(()=>{fetch("/api/generatePaymentLinkEmail",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},[e]),f.jsx("div",{dangerouslySetInnerHTML:{__html:t}})}function B9e({invoice:e}){var i;const[t,r]=w.useState(G.Mercoa.PaymentMethodType.BankAccount),o=((i=Le().organization)==null?void 0:i.supportEmail)??"support@mercoa.com",a=ea.formatMoney(e.amount??"",nn(e.currency));return f.jsx(_Y,{invoice:e,supportEmail:o,totalDisplay:a,selectedPaymentType:t,updateInvoice:()=>{},setSelectedPaymentType:r})}He.extend(FN);function L9e({invoiceId:e,invoice:t,onUpdate:r,admin:n,documentPosition:o="left",children:a}){var E,D,A,z,$,L,B,W,K;const i=Le(),[s,c]=w.useState([]),[l,u]=w.useState([]),[h,p]=w.useState([]),[m,g]=w.useState(t),[b,_]=w.useState(t==null?void 0:t.payer),[y,x]=w.useState([]),O=mo({id:Be().nullable(),status:Be(),amount:Za().positive().required().typeError("Please enter a valid number"),invoiceNumber:Be(),description:Be(),dueDate:To().required("Please select a due date").typeError("Please select a due date"),deductionDate:To().typeError("Please select a deduction date"),invoiceDate:To().required("Please select an invoice date").typeError("Please select an invoice date"),approvers:po(),lineItems:ZE().of(mo({id:Be(),description:Be().required(),amount:Za().required().typeError("Please enter a valid number"),currency:Be(),quantity:Za().required().typeError("Please enter a valid number"),unitPrice:Za().required().typeError("Please enter a valid number"),metadata:po().nullable(),glAccountId:Be(),createdAt:To(),updatedAt:To()})),currency:Be().required(),payerId:Be(),payerName:Be(),paymentDestinationId:Be(),paymentDestinationType:Be(),paymentSourceType:Be(),paymentDestinationOptions:po().nullable(),paymentSourceCheckEnabled:xu(),paymentSourceId:Be(),saveAsDraft:xu(),saveAsAdmin:xu(),metadata:po().nullable(),creatorUser:po().nullable()}).required(),S=Zn({resolver:Zi(O),defaultValues:{id:t==null?void 0:t.id,status:t==null?void 0:t.status,invoiceNumber:t==null?void 0:t.invoiceNumber,amount:t==null?void 0:t.amount,currency:(t==null?void 0:t.currency)??"USD",payerId:(E=t==null?void 0:t.payer)==null?void 0:E.id,payerName:(D=t==null?void 0:t.payer)==null?void 0:D.name,invoiceDate:t!=null&&t.invoiceDate?He(t==null?void 0:t.invoiceDate).toDate():void 0,dueDate:t!=null&&t.dueDate?He(t==null?void 0:t.dueDate).toDate():void 0,deductionDate:t!=null&&t.deductionDate?He(t==null?void 0:t.deductionDate).toDate():void 0,lineItems:(t==null?void 0:t.lineItems)??[],paymentDestinationId:(A=t==null?void 0:t.paymentDestination)==null?void 0:A.id,paymentDestinationType:((z=t==null?void 0:t.paymentDestination)==null?void 0:z.type)??"",paymentDestinationOptions:t==null?void 0:t.paymentDestinationOptions,paymentSourceId:($=t==null?void 0:t.paymentSource)==null?void 0:$.id,paymentSourceType:((L=t==null?void 0:t.paymentSource)==null?void 0:L.type)??"",paymentSourceCheckEnabled:((W=(B=t==null?void 0:t.paymentSource)==null?void 0:B.checkOptions)==null?void 0:W.enabled)??!1,description:(t==null?void 0:t.noteToSelf)??"",saveAsDraft:!1,metadata:(t==null?void 0:t.metadata)??{},creatorUser:t==null?void 0:t.creatorUser}});async function j(Z){var ue,ge;if(!i.token||!((ue=i.entity)!=null&&ue.id))return;const re=await((ge=i.client)==null?void 0:ge.invoice.get(Z));re&&(g(re),_(re.payer))}if(w.useEffect(()=>{var Z;!i.token||!((Z=i.entity)!=null&&Z.id)||!t&&e&&j(e)},[t,e,i.token,(K=i.entity)==null?void 0:K.id]),!i.client)return f.jsx(at,{componentName:"ReceivableDetails"});if(o==="none")return f.jsx(Us,{...S,children:f.jsx(UR,{invoice:m,onUpdate:r,refreshInvoice:j,admin:n,supportedCurrencies:y,setSupportedCurrencies:x,setDestinationPaymentMethods:u,setSourcePaymentMethods:p,setPaymentMethodSchemas:c,selectedPayer:b,setSelectedPayer:_,children:a})});const P=S.watch("paymentDestinationId"),I=f.jsx(bT,{minSize:0,maxSize:800,children:f.jsx(R9e,{selectedPayer:b,paymentDestination:l.find(Z=>Z.id===P)})}),M=f.jsx(bT,{className:`mercoa-relative ${o==="left"?"mercoa-pl-5":"mercoa-pr-5"}`,minSize:400,children:f.jsx(UR,{invoice:m,onUpdate:r,refreshInvoice:j,admin:n,supportedCurrencies:y,setSupportedCurrencies:x,setDestinationPaymentMethods:u,setSourcePaymentMethods:p,setPaymentMethodSchemas:c,selectedPayer:b,setSelectedPayer:_,children:a})});return f.jsx(Us,{...S,children:f.jsxs(bk,{children:[o==="left"?I:M,f.jsx(vk,{size:10,className:"mercoa-cursor-col-resize mercoa-invisible min-[450px]:mercoa-visible",style:{background:"linear-gradient(180deg, rgba(229,231,235,1) 48%, rgba(145,145,145,1) 48%, rgba(145,145,145,1) 52%, rgba(229,231,235,1) 52%)"}}),o==="right"?I:M]})})}function UR({invoice:e,onUpdate:t,refreshInvoice:r,admin:n,supportedCurrencies:o,setSupportedCurrencies:a,setDestinationPaymentMethods:i,setSourcePaymentMethods:s,setPaymentMethodSchemas:c,selectedPayer:l,setSelectedPayer:u,children:h}){var re,ue,ge,H,R,Q;const p=Le(),{register:m,handleSubmit:g,setValue:b,setError:_,clearErrors:y,watch:x,setFocus:O,control:S,formState:{errors:j}}=kt();w.useEffect(()=>{var ae,k,N,q,ie,le,U,X,be,xe,Ce,Te;e&&(((ae=e.paymentDestination)==null?void 0:ae.type)==="custom"?b("paymentDestinationType",((k=e.paymentDestination)==null?void 0:k.schemaId)??""):b("paymentDestinationType",((N=e.paymentDestination)==null?void 0:N.type)??""),((q=e.paymentSource)==null?void 0:q.type)==="custom"?b("paymentSourceType",((ie=e.paymentSource)==null?void 0:ie.schemaId)??""):b("paymentSourceType",((le=e.paymentSource)==null?void 0:le.type)??""),b("id",e.id),b("status",e.status),b("invoiceNumber",e.invoiceNumber),b("amount",e.amount),b("currency",e.currency??"USD"),b("payerId",(U=e.payer)==null?void 0:U.id),b("payerName",(X=e.payer)==null?void 0:X.name),b("invoiceDate",e.invoiceDate?He(e.invoiceDate).toDate():void 0),b("dueDate",e.dueDate?He(e.dueDate).toDate():void 0),b("deductionDate",e.deductionDate?He(e.deductionDate).toDate():void 0),b("lineItems",e.lineItems??[]),b("paymentDestinationId",(be=e.paymentDestination)==null?void 0:be.id),b("paymentDestinationOptions",e.paymentDestinationOptions),b("paymentSourceId",(xe=e.paymentSource)==null?void 0:xe.id),b("paymentSourceCheckEnabled",((Te=(Ce=e.paymentSource)==null?void 0:Ce.checkOptions)==null?void 0:Te.enabled)??!1),b("description",e.noteToSelf??""),b("hasDocuments",e.hasDocuments??!1),b("saveAsStatus",""),b("saveAsAdmin",!1),b("metadata",e.metadata??{}),b("creatorUser",e==null?void 0:e.creatorUser),b("comments",(e==null?void 0:e.comments)??[]))},[e]),w.useEffect(()=>{var ae,k,N,q,ie;e!=null&&e.id&&(b("status",e==null?void 0:e.status),b("invoiceNumber",e==null?void 0:e.invoiceNumber),e!=null&&e.amount&&b("amount",e.amount),b("currency",(e==null?void 0:e.currency)??"USD"),b("payerId",(ae=e==null?void 0:e.payer)==null?void 0:ae.id),b("payerName",(k=e==null?void 0:e.payer)==null?void 0:k.name),e!=null&&e.invoiceDate&&b("invoiceDate",He(e.invoiceDate).toDate()),e!=null&&e.dueDate&&b("dueDate",He(e==null?void 0:e.dueDate).toDate()),b("deductionDate",e!=null&&e.deductionDate?He(e==null?void 0:e.deductionDate).toDate():void 0),b("lineItems",((N=e==null?void 0:e.lineItems)==null?void 0:N.map(le=>({description:le.description??"",currency:le.currency??"USD",amount:le.amount??0,quantity:le.quantity??0,unitPrice:le.unitPrice??0,name:le.name??"",metadata:le.metadata??{},glAccountId:le.glAccountId??"",id:le.id??"",createdAt:le.createdAt??new Date,updatedAt:le.updatedAt??new Date})))??[]),b("paymentDestinationId",(q=e==null?void 0:e.paymentDestination)==null?void 0:q.id),b("paymentDestinationOptions",e==null?void 0:e.paymentDestinationOptions),b("paymentSourceId",(ie=e==null?void 0:e.paymentSource)==null?void 0:ie.id),b("description",(e==null?void 0:e.noteToSelf)??""))},[e,b]);const{fields:P,append:I,remove:M}=Hd({control:S,name:"lineItems"});x((ae,{name:k,type:N})=>{if(k==="currency"&&ae.lineItems.forEach((U,X)=>{b(`lineItems.${X}.currency`,ae.currency??"USD")}),!(k!=null&&k.startsWith("lineItems"))||k.endsWith("amount"))return;let ie=ae.lineItems.reduce((le,U,X)=>(U.amount=Math.floor((U.quantity??1)*(U.unitPrice??1)*100)/100,b(`lineItems.${X}.amount`,U.amount),le+U.amount),0);ie=Math.floor(ie*100)/100,b("amount",ie)});const E=x("payerId"),D=x("payerName"),A=x("currency");function z(){var ae;p.entityId&&((ae=p.client)==null||ae.entity.paymentMethod.getAll(p.entityId,{type:"bankAccount"}).then(k=>{i(k)}))}async function $(){var k;if(!p.token||!E)return;const ae=await((k=p.client)==null?void 0:k.entity.paymentMethod.getAll(E));ae&&s(ae)}w.useEffect(()=>{z()},[p.entityId]),w.useEffect(()=>{var ae,k;!p.token||!((ae=p.entity)!=null&&ae.id)||!p.client||($(),(k=p.client)==null||k.customPaymentMethodSchema.getAll().then(N=>{var q,ie;if(N){c(N);let le=[];((ie=(q=p.organization)==null?void 0:q.paymentMethods)==null?void 0:ie.payerPayments.some(X=>X.active&&(X.type==="bankAccount"||X.type==="card")))&&le.push("USD"),N.forEach(X=>{X.supportedCurrencies&&(le=[...new Set([...le,...X.supportedCurrencies])])}),a(le)}}))},[p.client,E,p.token]),w.useEffect(()=>{o.length>0&&b("currency",(e==null?void 0:e.currency)??o[0])},[o]);async function L(){var k;if(!(e!=null&&e.id))return;const ae=await((k=p.client)==null?void 0:k.invoice.document.generateInvoicePdf(e.id));ae!=null&&ae.uri?window.open(ae.uri,"_blank"):Ae.error("There was an issue generating the Invoice PDF. Please refresh and try again.")}async function B(){var k;if(!(e!=null&&e.id))return;const ae=await((k=p.client)==null?void 0:k.invoice.paymentLinks.getPayerLink(e.id));ae?window.open(ae,"_blank"):Ae.error("There was an issue creating the payment link. Please refresh and try again.")}async function W(){var ae,k,N;if(e!=null&&e.id){if(!((ae=e.payer)!=null&&ae.email)){Ae.error("There is no payer email address for this invoice.");return}try{await((k=p.client)==null?void 0:k.invoice.update(e.id,{status:G.Mercoa.InvoiceStatus.Approved}));try{await((N=p.client)==null?void 0:N.invoice.paymentLinks.sendPayerEmail(e.id)),Ae.info("Email Sent")}catch{Ae.error("There was an issue generating the email. Please refresh and try again.")}}catch(q){Ae.error(`There was an issue saving the invoice.
228
+ `);var K=0,Z=!1;this.parse=function(re,ue,ge){if(typeof re!="string")throw new Error("Input must be a string");var H=re.length,R=D.length,Q=A.length,ae=z.length,k=I($),N=[],q=[],ie=[],le=K=0;if(!re)return C();if(M.header&&!ue){var U=re.split(A)[0].split(D),X=[],be={},xe=!1;for(var Ce in U){var Te=U[Ce];I(M.transformHeader)&&(Te=M.transformHeader(Te,Ce));var Ee=Te,ne=be[Te]||0;for(0<ne&&(xe=!0,Ee=Te+"_"+ne),be[Te]=ne+1;X.includes(Ee);)Ee=Ee+"_"+ne;X.push(Ee)}if(xe){var te=re.split(A);te[0]=X.join(D),re=te.join(A)}}if(B||B!==!1&&re.indexOf(E)===-1){for(var _e=re.split(A),Me=0;Me<_e.length;Me++){if(ie=_e[Me],K+=ie.length,Me!==_e.length-1)K+=A.length;else if(ge)return C();if(!z||ie.substring(0,ae)!==z){if(k){if(N=[],Ie(ie.split(D)),oe(),Z)return C()}else Ie(ie.split(D));if(L&&L<=Me)return N=N.slice(0,L),C(!0)}}return C()}for(var Oe=re.indexOf(D,K),de=re.indexOf(A,K),F=new RegExp(_(W)+_(E),"g"),fe=re.indexOf(E,K);;)if(re[K]!==E)if(z&&ie.length===0&&re.substring(K,K+ae)===z){if(de===-1)return C();K=de+Q,de=re.indexOf(A,K),Oe=re.indexOf(D,K)}else if(Oe!==-1&&(Oe<de||de===-1))ie.push(re.substring(K,Oe)),K=Oe+R,Oe=re.indexOf(D,K);else{if(de===-1)break;if(ie.push(re.substring(K,de)),T(de+Q),k&&(oe(),Z))return C();if(L&&N.length>=L)return C(!0)}else for(fe=K,K++;;){if((fe=re.indexOf(E,fe+1))===-1)return ge||q.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:N.length,index:K}),V();if(fe===H-1)return V(re.substring(K,fe).replace(F,E));if(E!==W||re[fe+1]!==W){if(E===W||fe===0||re[fe-1]!==W){Oe!==-1&&Oe<fe+1&&(Oe=re.indexOf(D,fe+1)),de!==-1&&de<fe+1&&(de=re.indexOf(A,fe+1));var se=nt(de===-1?Oe:Math.min(Oe,de));if(re.substr(fe+1+se,R)===D){ie.push(re.substring(K,fe).replace(F,E)),re[K=fe+1+se+R]!==E&&(fe=re.indexOf(E,K)),Oe=re.indexOf(D,K),de=re.indexOf(A,K);break}var Pe=nt(de);if(re.substring(fe+1+Pe,fe+1+Pe+Q)===A){if(ie.push(re.substring(K,fe).replace(F,E)),T(fe+1+Pe+Q),Oe=re.indexOf(D,K),fe=re.indexOf(E,K),k&&(oe(),Z))return C();if(L&&N.length>=L)return C(!0);break}q.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:N.length,index:K}),fe++}}else fe++}return V();function Ie(ye){N.push(ye),le=K}function nt(ye){var je=0;if(ye!==-1){var Se=re.substring(fe+1,ye);Se&&Se.trim()===""&&(je=Se.length)}return je}function V(ye){return ge||(ye===void 0&&(ye=re.substring(K)),ie.push(ye),K=H,Ie(ie),k&&oe()),C()}function T(ye){K=ye,Ie(ie),ie=[],de=re.indexOf(A,K)}function C(ye){return{data:N,errors:q,meta:{delimiter:D,linebreak:A,aborted:Z,truncated:!!ye,cursor:le+(ue||0)}}}function oe(){$(C()),N=[],q=[]}},this.abort=function(){Z=!0},this.getCharIndex=function(){return K}}function x(M){var E=M.data,D=i[E.workerId],A=!1;if(E.error)D.userError(E.error,E.file);else if(E.results&&E.results.data){var z={abort:function(){A=!0,O(E.workerId,{data:[],errors:[],meta:{aborted:!0}})},pause:S,resume:S};if(I(D.userStep)){for(var $=0;$<E.results.data.length&&(D.userStep({data:E.results.data[$],errors:E.results.errors,meta:E.results.meta},z),!A);$++);delete E.results}else I(D.userChunk)&&(D.userChunk(E.results,z,E.file),delete E.results)}E.finished&&!A&&O(E.workerId,E.results)}function O(M,E){var D=i[M];I(D.userComplete)&&D.userComplete(E),D.terminate(),delete i[M]}function S(){throw new Error("Not implemented.")}function j(M){if(typeof M!="object"||M===null)return M;var E=Array.isArray(M)?[]:{};for(var D in M)E[D]=j(M[D]);return E}function P(M,E){return function(){M.apply(E,arguments)}}function I(M){return typeof M=="function"}return a&&(n.onmessage=function(M){var E=M.data;if(c.WORKER_ID===void 0&&E&&(c.WORKER_ID=E.workerId),typeof E.input=="string")n.postMessage({workerId:c.WORKER_ID,results:c.parse(E.input,E.config),finished:!0});else if(n.File&&E.input instanceof File||E.input instanceof Object){var D=c.parse(E.input,E.config);D&&n.postMessage({workerId:c.WORKER_ID,results:D,finished:!0})}}),(h.prototype=Object.create(u.prototype)).constructor=h,(p.prototype=Object.create(u.prototype)).constructor=p,(m.prototype=Object.create(m.prototype)).constructor=m,(g.prototype=Object.create(u.prototype)).constructor=g,c})})(hY);var I9e=hY.exports;const pY=mn(I9e);function CR(e,t,r){return r?U9e(e):z9e(e,t)}function z9e(e,t){return{UNASSIGNED:"Unassigned",DRAFT:"Inbox",NEW:"Ready for Review",APPROVED:t!=null&&t.length?"Approved":"Ready for Payment",SCHEDULED:"Payment Scheduled",PENDING:"Payment Processing",FAILED:"Payment Failed",PAID:"Paid",CANCELED:"Canceled",REFUSED:"Rejected",ARCHIVED:"Archived"}[e]}function U9e(e,t){return{UNASSIGNED:"Unassigned",DRAFT:"Draft",NEW:"Ready for Review",APPROVED:"Awaiting Payment",SCHEDULED:"Payment Scheduled",PENDING:"Payment Processing",FAILED:"Payment Failed",PAID:"Paid",CANCELED:"Canceled",REFUSED:"Rejected",ARCHIVED:"Archived"}[e]}async function mY({statuses:e,search:t,mercoaSession:r,setMetrics:n,returnByDate:o,excludeReceivables:a,excludePayables:i}){!i&&!a&&(a=!0);const s=(await Promise.all((e??[]).map(async l=>{var h,p;if(!r.token||!((h=r.entity)!=null&&h.id))return;const u=await((p=r.client)==null?void 0:p.entity.invoice.metrics(r.entity.id,{search:t,status:l,returnByDate:o,excludeReceivables:a,excludePayables:i}));return[l,(u==null?void 0:u[0])??{totalAmount:0,totalInvoices:0,totalCount:0,currency:"USD"}]}))).filter(l=>l),c=Object.fromEntries(s);n(c)}function gY({open:e,onClose:t,setDate:r}){const[n,o]=w.useState();return f.jsxs(fn,{as:"div",open:e,onClose:t,className:"mercoa-relative mercoa-z-10",children:[f.jsx("div",{className:"mercoa-fixed mercoa-inset-0 mercoa-bg-black/30","aria-hidden":"true"}),f.jsx("div",{className:"mercoa-fixed mercoa-inset-0 mercoa-overflow-y-auto",children:f.jsx("div",{className:"mercoa-flex mercoa-min-h-full mercoa-items-end mercoa-justify-center mercoa-p-4 mercoa-text-center sm:mercoa-items-center sm:mercoa-p-0",children:f.jsxs(fn.Panel,{className:"mercoa-relative mercoa-transform mercoa-rounded-mercoa mercoa-bg-white mercoa-shadow-xl mercoa-transition-all sm:mercoa-p-6",children:[f.jsx(fn.Title,{className:"mercoa-text-lg mercoa-font-semibold",children:"When should these payments be scheduled?"}),f.jsxs("div",{className:"mercoa-flex mercoa-mt-5",children:[f.jsx(FW,{className:"mercoa-block mercoa-w-full mercoa-rounded-mercoa mercoa-border-gray-300 focus:mercoa-border-mercoa-primary focus:mercoa-ring-mercoa-primary sm:mercoa-text-sm",placeholderText:"Select Payment Date",onChange:a=>o(a),selected:n,minDate:He().add(1,"day").toDate(),filterDate:XG}),f.jsx(Ue,{type:"button",className:"mercoa-ml-2",isEmphasized:!0,onClick:()=>{n&&r(n),t()},disabled:!n,children:"Schedule Payments"})]})]})})})]})}function N9e({open:e,onClose:t,setApprover:r}){const n=Le(),[o,a]=w.useState([]),[i,s]=w.useState();return w.useEffect(()=>{var c;n.entityId&&((c=n.client)==null||c.entity.user.getAll(n.entityId).then(l=>{a(l)}).catch(l=>{console.error(l)}))},[n.token,n.entityId]),f.jsxs(fn,{as:"div",open:e,onClose:t,className:"mercoa-relative mercoa-z-10",children:[f.jsx("div",{className:"mercoa-fixed mercoa-inset-0 mercoa-bg-black/30","aria-hidden":"true"}),f.jsx("div",{className:"mercoa-fixed mercoa-inset-0 mercoa-overflow-y-auto",children:f.jsx("div",{className:"mercoa-flex mercoa-min-h-full mercoa-items-end mercoa-justify-center mercoa-p-4 mercoa-text-center sm:mercoa-items-center sm:mercoa-p-0",children:f.jsxs(fn.Panel,{className:"mercoa-relative mercoa-transform mercoa-rounded-mercoa mercoa-bg-white mercoa-shadow-xl mercoa-transition-all sm:mercoa-p-6",children:[f.jsx(en,{title:"User will be added to the first available approval slot they are eligible for",children:f.jsxs(fn.Title,{className:"mercoa-text-lg mercoa-font-semibold mercoa-flex mercoa-items-center mercoa-justify-center",children:["Select Approver To Add",f.jsx(DF,{className:"mercoa-size-5 mercoa-ml-2"})]})}),f.jsxs("div",{className:"mercoa-flex mercoa-mt-5",children:[f.jsx(In,{options:o.map(c=>({disabled:!1,value:c})),displayIndex:"name",secondaryDisplayIndex:"email",onChange:c=>{n.debug(c),s(c)},value:i,displaySelectedAs:"pill"}),f.jsx(Ue,{type:"button",className:"mercoa-ml-2",isEmphasized:!0,onClick:()=>{i&&r(i.id),t()},disabled:!i,children:"Add Approver"})]})]})})})]})}function bY({statuses:e,search:t,metadata:r,startDate:n,endDate:o,onSelectInvoice:a,columns:i,children:s}){const c=Le(),[l,u]=w.useState(),[h,p]=w.useState(0),[m,g]=w.useState(G.Mercoa.InvoiceOrderByField.CreatedAt),[b,_]=w.useState(G.Mercoa.OrderDirection.Asc),[y,x]=w.useState(!0),[O,S]=w.useState(0),[j,P]=w.useState(!1),[I,M]=w.useState(e),[E,D]=w.useState([]),[A,z]=w.useState(20),[$,L]=w.useState(1),B=w.useRef(null),[W,K]=w.useState(!1),[Z,re]=w.useState(!1),[ue,ge]=w.useState([]),[H,R]=w.useState(!1),[Q,ae]=w.useState(!1),[k,N]=w.useState(!1);w.useLayoutEffect(()=>{const de=ue.length>0&&ue.length<(l?l.length:0);K(ue.length===(l?l.length:0)),re(de),B.current&&(B.current.indeterminate=de)},[ue,l]);function q(){ge(W||Z?[]:l??[]),K(!W&&!Z),re(!1)}async function ie(de){var fe;if(!c.token||!((fe=c.entity)!=null&&fe.id))return;P(!1);let F=!1;await Promise.all(ue.map(async se=>{var Pe;try{await((Pe=c.client)==null?void 0:Pe.invoice.update(se.id,{...(se.status===G.Mercoa.InvoiceStatus.Approved||se.status===G.Mercoa.InvoiceStatus.Failed)&&{status:G.Mercoa.InvoiceStatus.Scheduled},deductionDate:de})),F=!0}catch(Ie){console.error("Error updating invoice: ",Ie),console.log("Errored invoice: ",{invoice:se})}})),F?Ae.success("Payment Scheduled"):Ae.error("Error scheduling payment"),c.refresh()}async function le(de){var fe;if(!c.token||!((fe=c.entity)!=null&&fe.id))return;let F=!1;P(!1),await Promise.all(ue.map(async se=>{var Pe;try{await((Pe=c.client)==null?void 0:Pe.invoice.approval.addApprover(se.id,{userId:de})),F=!0}catch(Ie){console.error("Error adding approver to invoice ",Ie),console.log("Errored invoice: ",{invoice:se})}})),F?Ae.success("Approver Added"):Ae.error("Error adding approver"),c.refresh()}function U(de){let F=G.Mercoa.InvoiceStatus.Approved;const fe=de.approvalPolicy;return fe&&fe.length>0&&(F=G.Mercoa.InvoiceStatus.New),F}async function X(){var F;if(!c.token||!((F=c.entity)!=null&&F.id))return;let de=!1;P(!1),await Promise.all(ue.map(async fe=>{var se;try{await((se=c.client)==null?void 0:se.invoice.update(fe.id,{status:U(fe)})),de=!0}catch(Pe){console.error("Error submitting invoice: ",Pe),console.log("Errored invoice: ",{invoice:fe})}})),de?Ae.success("Invoice Submitted for Approval"):Ae.error("Error submitting invoice"),c.refresh()}async function be(){var F;if(!c.token||!((F=c.entity)!=null&&F.id))return;let de=!1;P(!1),await Promise.all(ue.map(async fe=>{var se;try{await((se=c.client)==null?void 0:se.invoice.delete(fe.id)),de=!0}catch(Pe){console.error("Error deleting invoice: ",Pe),console.log("Errored invoice: ",{invoice:fe})}})),de?Ae.success("Invoices Deleted"):Ae.error("Error deleting invoices"),c.refresh()}async function xe(){var F;if(!c.token||!((F=c.entity)!=null&&F.id))return;let de=!1;P(!1),await Promise.all(ue.map(async fe=>{var se;try{await((se=c.client)==null?void 0:se.invoice.update(fe.id,{status:G.Mercoa.InvoiceStatus.Archived})),de=!0}catch(Pe){console.error("Error archiving invoice: ",Pe),console.log("Errored invoice: ",{invoice:fe})}})),de?Ae.success("Invoices Archived"):Ae.error("Error archiving invoices"),c.refresh()}async function Ce(){var F;if(!c.token||!((F=c.entity)!=null&&F.id))return;let de=!1;P(!1),await Promise.all(ue.map(async fe=>{var se;try{await((se=c.client)==null?void 0:se.invoice.update(fe.id,{status:G.Mercoa.InvoiceStatus.Canceled})),de=!0}catch(Pe){console.error("Error cancelling invoice: ",Pe),console.log("Errored invoice: ",{invoice:fe})}})),de?Ae.success("Payments Cancelled"):Ae.error("Error cancelling payments"),c.refresh()}async function Te(){var F;if(!c.token||!((F=c.entity)!=null&&F.id)||!c.user)return;let de=!1;P(!1),await Promise.all(ue.map(async fe=>{var se,Pe,Ie;try{const nt=await((se=c.client)==null?void 0:se.invoice.get(fe.id));if((nt==null?void 0:nt.status)!=G.Mercoa.InvoiceStatus.New){de=!0;return}await((Ie=c.client)==null?void 0:Ie.invoice.approval.approve(fe.id,{userId:(Pe=c.user)==null?void 0:Pe.id})),de=!0}catch(nt){console.error("Error approving invoice: ",nt),console.log("Errored invoice: ",{invoice:fe})}})),de&&Ae.success("Approved"),c.refresh()}async function Ee(){var F;if(!c.token||!((F=c.entity)!=null&&F.id)||!c.user)return;let de=!1;P(!1),await Promise.all(ue.map(async fe=>{var se,Pe,Ie;try{const nt=await((se=c.client)==null?void 0:se.invoice.get(fe.id));if((nt==null?void 0:nt.status)!=G.Mercoa.InvoiceStatus.New){de=!0;return}await((Ie=c.client)==null?void 0:Ie.invoice.approval.reject(fe.id,{userId:(Pe=c.user)==null?void 0:Pe.id})),de=!0}catch(nt){console.error("Error rejecting invoice: ",nt),console.log("Errored invoice: ",{invoice:fe})}})),de&&Ae.success("Rejected"),c.refresh()}async function ne(){var se;if(!c.token||!((se=c.entity)!=null&&se.id))return;let de="",F=[];fe();async function fe(){var nt,V,T;if(!c.token||!((nt=c.entity)!=null&&nt.id))return;const Pe={status:I,search:t,startDate:n,endDate:o,orderBy:m,orderDirection:b,...k&&{approverId:(V=c.user)==null?void 0:V.id,approverAction:G.Mercoa.ApproverAction.None},limit:100,startingAfter:de,excludeReceivables:!0,metadata:r},Ie=await((T=c.client)==null?void 0:T.entity.invoice.find(c.entity.id,Pe));if(Ie)if(Ie.data.length>0)de=Ie.data[Ie.data.length-1].id,F=[...F,...Ie.data],await fe();else{const C=pY.unparse(F.map(Se=>{var ve,tt,et,ut,wt,dt;return{"Invoice ID":Se.id,"Invoice Number":Se.invoiceNumber,Status:Se.status,Amount:Se.amount,Currency:Se.currency,Note:Se.noteToSelf,"Payer ID":(ve=Se.payer)==null?void 0:ve.id,"Payer Email":(tt=Se.payer)==null?void 0:tt.email,"Payer Name":(et=Se.payer)==null?void 0:et.name,"Vendor ID":(ut=Se.vendor)==null?void 0:ut.id,"Vendor Email":(wt=Se.vendor)==null?void 0:wt.email,"Vendor Name":(dt=Se.vendor)==null?void 0:dt.name,Metadata:JSON.stringify(Se.metadata),"Due Date":He(Se.dueDate),"Deduction Date":He(Se.deductionDate),"Processed At":He(Se.processedAt),"Created At":He(Se.createdAt),"Updated At":He(Se.updatedAt)}})),oe=new Blob([C],{type:"text/csv"}),ye=window.URL.createObjectURL(oe),je=document.createElement("a");je.setAttribute("mercoa-hidden",""),je.setAttribute("href",ye),je.setAttribute("download",`mercoa-invoice-export-${He().format("YYYY-MM-DD")}.csv`),document.body.appendChild(je),je.click(),document.body.removeChild(je)}}}if(w.useEffect(()=>{M(e)},[e]),w.useEffect(()=>{var fe,se,Pe,Ie,nt;if(!c.token||!((fe=c.entity)!=null&&fe.id))return;let de=!0;ge([]),P(!1);const F={status:I,search:t,startDate:n,endDate:o,orderBy:m,orderDirection:b,...k&&{approverId:(se=c.user)==null?void 0:se.id,approverAction:G.Mercoa.ApproverAction.None},limit:A,startingAfter:E[E.length-1],excludeReceivables:!0,metadata:r};return(Pe=c.client)==null||Pe.entity.invoice.find(c.entity.id,F).then(V=>{V&&de&&(x(V.hasMore),S(V.count),u(V.data),P(!0))}),I.includes(G.Mercoa.InvoiceStatus.New)&&((nt=c.client)==null||nt.entity.invoice.find(c.entity.id,{...F,approverId:(Ie=c.user)==null?void 0:Ie.id,approverAction:G.Mercoa.ApproverAction.None}).then(V=>{V&&de&&p(V.count)})),()=>{de=!1}},[c.token,c.entity,c.refreshId,I,t,n,o,r,m,b,E,A,k]),w.useEffect(()=>{L(1),D([])},[t]),w.useEffect(()=>{e.some(de=>I.indexOf(de)<0)&&(M(e),N(!1),P(!1),D([]),L(1),S(0))},[e,n,o]),s)return s({dataLoaded:j,invoices:l||[],hasNext:y,getNext:()=>{l&&(L($+1),D([...E,l[l.length-1].id]))},hasPrevious:$!==1,getPrevious:()=>{L(Math.max(1,$-1)),D(E.slice(0,E.length-1))},resultsPerPage:A,setResultsPerPage:z,page:$,setPage:de=>{l&&L(de)},orderBy:m,setOrderBy:g,orderDirection:b,setOrderDirection:_,selectedInvoiceStatuses:I,setSelectedInvoiceStatues:M,downloadCSV:ne,count:O});if(!j||!c.entity||!l)return f.jsx("div",{className:"mercoa-min-h-[710px] mercoa-min-w-[710px]",children:f.jsx(Fm,{rows:20})});const te=[{title:"Vendor",field:"vendor",orderBy:G.Mercoa.InvoiceOrderByField.VendorName},{title:"Invoice Number",field:"invoiceNumber",orderBy:G.Mercoa.InvoiceOrderByField.InvoiceNumber},{title:"Due Date",field:"dueDate",orderBy:G.Mercoa.InvoiceOrderByField.DueDate},{title:"Amount",field:"amount",orderBy:G.Mercoa.InvoiceOrderByField.Amount},{title:"Approvers",field:"approvers",format:(de,F)=>{var fe;return F.approvers.every(se=>!se.assignedUserId)?null:f.jsx("div",{className:"mercoa-gap-1 mercoa-grid",children:(fe=F.approvers)==null?void 0:fe.map(se=>{if(!se.assignedUserId)return null;const Pe=c.users.find(Ie=>Ie.id===se.assignedUserId);return f.jsx(en,{title:Pe==null?void 0:Pe.email,children:f.jsx("div",{className:`mercoa-flex mercoa-items-center mercoa-rounded-mercoa mercoa-text-xs ${se.action===G.Mercoa.ApproverAction.Approve?"mercoa-bg-green-100 mercoa-text-green-800":""} ${se.action===G.Mercoa.ApproverAction.Reject?"mercoa-bg-red-100 mercoa-text-red-800":""} ${se.action===G.Mercoa.ApproverAction.None?"mercoa-bg-gray-50 mercoa-text-gray-800":""} mercoa-py-1 mercoa-px-2`,children:Pe==null?void 0:Pe.name},se.approvalSlotId)},se.approvalSlotId)})})}},{title:"Payment Destination",field:"paymentDestination",format:de=>(de=de,!de||!de.type?null:de.type===G.Mercoa.PaymentMethodType.BankAccount?`${de==null?void 0:de.bankName} ••••${String(de==null?void 0:de.accountNumber).slice(-4)}`:de.type===G.Mercoa.PaymentMethodType.Check?`Check • ${String(de==null?void 0:de.addressLine1).slice(-10)}`:de.type===G.Mercoa.PaymentMethodType.Custom?`${de==null?void 0:de.accountName} ••••${String(de==null?void 0:de.accountNumber).slice(-4)}`:null)},{title:"Status",field:"status",format:(de,F)=>f.jsx(YT,{failureType:F.failureType,status:F.status,vendorId:F.vendorId,payerId:F.payerId,paymentDestinationId:F.paymentDestinationId,paymentSourceId:F.paymentSourceId,dueDate:F.dueDate,amount:F.amount,type:"payable"})},{title:"Deduction Date",field:"deductionDate",orderBy:G.Mercoa.InvoiceOrderByField.DeductionDate}];function _e(de){return l?l.some(F=>de.field.startsWith("metadata.")?!0:F[`${de.field}`]&&de.format?de.format(F[`${de.field}`],F):F[`${de.field}`]):!1}const Me=f.jsx("thead",{children:f.jsxs("tr",{children:[f.jsx("th",{scope:"col",className:"mercoa-relative mercoa-px-7 sm:mercoa-w-12 sm:mercoa-px-6",children:l.length>0&&f.jsx("input",{type:"checkbox",className:"mercoa-absolute mercoa-left-4 mercoa-top-1/2 -mercoa-mt-2 mercoa-size-4 mercoa-rounded mercoa-border-gray-300 mercoa-text-mercoa-primary-text focus:mercoa-ring-mercoa-primary",ref:B,checked:W,onChange:q})}),(i??te).map((de,F)=>!_e(de)&&l.length>0?null:f.jsx("th",{scope:"col",className:`mercoa-min-w-[12rem] mercoa-py-3.5 mercoa-pl-4 mercoa-pr-3 mercoa-text-left mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 sm:mercoa-pl-3 ${ue.length>0?"mercoa-invisible":""}`,children:de.orderBy?f.jsx(Rm,{title:de.title,setOrder:fe=>{de.orderBy&&(g(de.orderBy),_(fe))},isSelected:m===de.orderBy,orderDirection:b}):de.title},F))]})}),Oe=f.jsx("tbody",{className:"mercoa-divide-y mercoa-divide-gray-200 mercoa-bg-white",children:l.map(de=>f.jsxs("tr",{className:$c("mercoa-cursor-pointer hover:mercoa-bg-gray-100",ue.includes(de)?"mercoa-bg-gray-50":void 0),children:[f.jsxs("td",{className:"mercoa-relative mercoa-px-7 sm:mercoa-w-12 sm:mercoa-px-6",children:[ue.includes(de)&&f.jsx("div",{className:"mercoa-absolute mercoa-inset-y-0 mercoa-left-0 mercoa-w-0.5 mercoa-bg-mercoa-primary"}),f.jsx("input",{type:"checkbox",className:"mercoa-absolute mercoa-left-4 mercoa-top-1/2 -mercoa-mt-2 mercoa-size-4 mercoa-rounded mercoa-border-gray-300 mercoa-text-mercoa-primary-text focus:mercoa-ring-mercoa-primary",value:de.id,checked:ue.includes(de),onChange:F=>ge(F.target.checked?[...ue,de]:ue.filter(fe=>fe!==de))})]}),(i??te).map((F,fe)=>{if(!_e(F))return null;let se;return F.field.startsWith("metadata.")?se=JSON.stringify(de.metadata[F.field.split(".")[1]]):se=de[F.field],F.format?se=F.format(se,de):F.field==="amount"?se=ea.formatMoney(se??"",nn(de.currency)):se instanceof Date?se=He(se).format("MMM DD, YYYY"):typeof se=="object"?se.name?se=se.name:se=JSON.stringify(se):se=(se==null?void 0:se.toString())??"",f.jsx("td",{className:`mercoa-whitespace-nowrap mercoa-py-3 mercoa-pl-4 mercoa-pr-3 mercoa-text-sm mercoa-text-gray-900 sm:mercoa-pl-3 ${ue.includes(de)?"mercoa-text-mercoa-primary-text":"mercoa-text-gray-900"} ${fe===0?"mercoa-font-medium":""}`,onClick:()=>{a&&a(de)},children:se},fe)})]},de.id))});return c.client?f.jsxs("div",{children:[f.jsxs("div",{className:"mercoa-min-h-[600px]",children:[I.includes(G.Mercoa.InvoiceStatus.New)&&h>0&&f.jsx("div",{className:"mercoa-flex mercoa-items-center mercoa-justify-start mercoa-my-4 mercoa-ml-4",children:f.jsxs("div",{className:"mercoa-flex mercoa-items-center mercoa-font-bold mercoa-font-xl mercoa-text-gray-600",children:[f.jsx("input",{id:"showOnlyInvoicesThatUserNeedsToApprove",type:"checkbox",className:"mercoa-mr-2 mercoa-size-4 mercoa-rounded mercoa-border-gray-300 focus:mercoa-ring-mercoa-primary mercoa-text-mercoa-primary-text mercoa-cursor-pointer",checked:k,onChange:()=>N(!k)}),f.jsxs("label",{htmlFor:"showOnlyInvoicesThatUserNeedsToApprove",className:"mercoa-cursor-pointer",children:["Only show invoices that need my approval ",f.jsx(PN,{count:h,selected:!0})]})]})}),f.jsxs("div",{className:"mercoa-relative mercoa-grid",style:{gridTemplateColumns:"repeat(1, minmax(0, 1fr))",overflow:"auto",whiteSpace:"normal"},children:[f.jsxs("div",{className:"mercoa-absolute mercoa-left-14 mercoa-top-6 mercoa-flex mercoa-h-12 mercoa-items-center mercoa-space-x-3 mercoa-bg-white sm:mercoa-left-12",children:[I.includes(G.Mercoa.InvoiceStatus.Draft)&&ue.length>0&&f.jsxs(f.Fragment,{children:[U(ue[0])===G.Mercoa.InvoiceStatus.New&&f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:()=>ae(!0),children:"Add Approver"}),f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:X,children:U(ue[0])===G.Mercoa.InvoiceStatus.New?"Submit for Approval":"Approve"}),f.jsx(N9e,{open:Q,onClose:()=>ae(!1),setApprover:le})]}),I.some(de=>[G.Mercoa.InvoiceStatus.Draft,G.Mercoa.InvoiceStatus.New,G.Mercoa.InvoiceStatus.Approved,G.Mercoa.InvoiceStatus.Failed].includes(de))&&ue.length>0&&f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:()=>R(!0),children:I.some(de=>[G.Mercoa.InvoiceStatus.Draft,G.Mercoa.InvoiceStatus.New].includes(de))?"Set Payment Date":"Schedule Payment"}),f.jsx(gY,{open:H,onClose:()=>R(!1),setDate:ie})]}),I.includes(G.Mercoa.InvoiceStatus.Scheduled)&&ue.length>0&&f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:()=>R(!0),children:"Reschedule Payment"}),f.jsx(gY,{open:H,onClose:()=>R(!1),setDate:ie})]}),I.includes(G.Mercoa.InvoiceStatus.New)&&ue.length>0&&ue.some(de=>de.approvers.some(F=>{var fe;return F.assignedUserId===((fe=c.user)==null?void 0:fe.id)}))&&f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:Te,children:"Approve"}),f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:Ee,children:"Reject"})]}),I.includes(G.Mercoa.InvoiceStatus.Draft)&&ue.length>0&&f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:()=>{confirm("Are you sure you want to delete these invoices? This action cannot be undone.")&&be()},children:"Delete"}),I.some(de=>[G.Mercoa.InvoiceStatus.New,G.Mercoa.InvoiceStatus.Approved,G.Mercoa.InvoiceStatus.Refused,G.Mercoa.InvoiceStatus.Scheduled,G.Mercoa.InvoiceStatus.Failed].includes(de))&&ue.length>0&&f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:()=>{confirm("Are you sure you want to cancel these invoices? This action cannot be undone.")&&Ce()},children:"Cancel"}),I.some(de=>[G.Mercoa.InvoiceStatus.Paid,G.Mercoa.InvoiceStatus.Canceled].includes(de))&&ue.length>0&&f.jsx("button",{type:"button",className:"mercoa-inline-flex mercoa-items-center mercoa-rounded mercoa-bg-white mercoa-px-2 mercoa-py-1 mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 hover:mercoa-bg-gray-50 disabled:mercoa-cursor-not-allowed disabled:mercoa-opacity-30 disabled:hover:mercoa-bg-white",onClick:()=>{confirm("Are you sure you want to archive these invoices? This action cannot be undone.")&&xe()},children:"Archive"})]}),f.jsxs("table",{className:"mercoa-min-w-full mercoa-divide-y mercoa-divide-gray-300 mercoa-mt-5",children:[Me,Oe]})]})]}),f.jsx($m,{data:l,page:$,setPage:L,hasMore:y,startingAfter:E,setStartingAfter:D,count:O,resultsPerPage:A,setResultsPerPage:z,downloadAll:ne})]}):f.jsx(at,{componentName:"PayablesTable"})}function YT({status:e,failureType:t,amount:r,payerId:n,vendorId:o,dueDate:a,paymentSourceId:i,paymentDestinationId:s,type:c}){const l=c==="receivable"?n:o;let u="mercoa-bg-gray-100",h="mercoa-text-black",p="";return!e||e===G.Mercoa.InvoiceStatus.Draft?!l||!r||!a?(u="mercoa-bg-yellow-100",h="mercoa-text-black",p="Draft Incomplete"):(u="mercoa-bg-green-100",h="mercoa-text-green-800",p="Draft Ready"):e===G.Mercoa.InvoiceStatus.New?!i||!l||!r||!a?(u="mercoa-bg-yellow-100",h="mercoa-text-gray-800",p="Incomplete"):(u="mercoa-bg-green-100",h="mercoa-text-green-800",p="Ready for Review"):e===G.Mercoa.InvoiceStatus.Approved?!i||!s||!l||!r||!a?(u="mercoa-bg-yellow-100",h="mercoa-text-black",p="Incomplete"):(u="mercoa-bg-green-100",h="mercoa-text-green-800",p=c==="receivable"?"Out for Payment":"Ready for Payment"):e===G.Mercoa.InvoiceStatus.Scheduled?!i||!s||!l||!r||!a?(u="mercoa-bg-yellow-100",h="mercoa-text-black",p="Incomplete"):(u="mercoa-bg-green-100",h="mercoa-text-green-800",p="Payment Scheduled"):e===G.Mercoa.InvoiceStatus.Pending?(u="mercoa-bg-yellow-100",h="mercoa-text-black",p="Payment Processing"):e===G.Mercoa.InvoiceStatus.Paid?(u="mercoa-bg-green-100",h="mercoa-text-green-800",p="Paid"):e===G.Mercoa.InvoiceStatus.Canceled?(u="mercoa-bg-red-100",h="mercoa-text-red-800",p="Canceled"):e===G.Mercoa.InvoiceStatus.Archived?(u="mercoa-bg-gray-100",h="mercoa-text-black",p="Archived"):e===G.Mercoa.InvoiceStatus.Refused?(u="mercoa-bg-red-100",h="mercoa-text-red-800",p="Rejected"):e===G.Mercoa.InvoiceStatus.Failed&&(u="mercoa-bg-red-100",h="mercoa-text-red-800",p="Failed",t===G.Mercoa.InvoiceFailureType.InsufficientFunds?p="Insufficient Funds":t===G.Mercoa.InvoiceFailureType.ProcessingError?p="Processing Error":t===G.Mercoa.InvoiceFailureType.DestinationPaymentError?p="Destination Payment Error":t===G.Mercoa.InvoiceFailureType.SourcePaymentError?p="Source Payment Error":t===G.Mercoa.InvoiceFailureType.RejectedHighRisk&&(p="Rejected High Risk")),p?f.jsx("p",{className:`mercoa-inline-flex mercoa-items-center mercoa-whitespace-nowrap mercoa-rounded-full mercoa-px-3 mercoa-py-0.5 mercoa-text-xs mercoa-font-medium ${u} ${h} md:mercoa-ml-2`,children:p}):f.jsx(f.Fragment,{})}function DR({statuses:e,search:t,returnByDate:r,excludePayables:n,excludeReceivables:o,children:a}){typeof n>"u"&&typeof o>"u"&&(o=!0);const i=Le(),[s,c]=w.useState();function l(h){const p=Object.entries(h).filter(([m])=>e.indexOf(m)>-1);return p==null?void 0:p.reduce((m,[,g])=>(m+=g.totalCount,m),0)}function u(h,p){const m=Object.entries(h).filter(([g])=>e.indexOf(g)>-1);return!m||m.length<1?ea.formatMoney(0,nn("USD")):m.length<2?ea.formatMoney(m[0][1][p]??0??"",nn(m[0][1].currency)):f.jsx("div",{children:m.map(([g,b])=>f.jsxs("p",{className:"mercoa-text-xs",children:[f.jsxs("span",{className:"mercoa-text-gray-600",children:[g,": "]}),f.jsx("span",{className:"mercoa-text-gray-900",children:ea.formatMoney(b[p]??0??"",nn(b.currency))}),f.jsxs("span",{className:"mercoa-text-gray-500",children:[" ",b.currency]})]},b.currency))})}return w.useEffect(()=>{var h;c(void 0),!(!i.token||!((h=i.entity)!=null&&h.id))&&mY({statuses:e,search:t,mercoaSession:i,setMetrics:c,returnByDate:r,excludePayables:n??!1,excludeReceivables:o??!1})},[t,e,i.token,i.entity,i.refreshId]),a?a({metrics:s}):i.client?f.jsx("div",{className:"mercoa-grid mercoa-grid-cols-3 mercoa-space-x-3 mercoa-mt-2 mercoa-mb-1 mercoa-min-h-[60px]",children:s?f.jsxs(f.Fragment,{children:[f.jsx(uT,{size:"sm",title:"Number of Invoices",value:l(s)}),f.jsx(uT,{size:"sm",title:"Total Amount",value:u(s,"totalAmount")}),f.jsx(uT,{size:"sm",title:"Average Amount",value:u(s,"averageAmount")})]}):f.jsxs(f.Fragment,{children:[f.jsx(Fm,{rows:2}),f.jsx(Fm,{rows:2}),f.jsx(Fm,{rows:2})]})}):f.jsx(at,{componentName:"InvoiceMetrics"})}function IR({statuses:e,selectedStatus:t,search:r,onStatusChange:n,excludePayables:o,excludeReceivables:a}){const i=Le(),[s,c]=w.useState([t??G.Mercoa.InvoiceStatus.Draft]),[l,u]=w.useState(),[h,p]=w.useState(e??[G.Mercoa.InvoiceStatus.Draft,G.Mercoa.InvoiceStatus.New,G.Mercoa.InvoiceStatus.Approved,G.Mercoa.InvoiceStatus.Scheduled,G.Mercoa.InvoiceStatus.Pending,G.Mercoa.InvoiceStatus.Paid,G.Mercoa.InvoiceStatus.Canceled,G.Mercoa.InvoiceStatus.Refused,G.Mercoa.InvoiceStatus.Failed]);w.useEffect(()=>{var b,_;!i.token||!((b=i.entity)!=null&&b.id)||(_=i.client)==null||_.entity.approvalPolicy.getAll(i.entity.id).then(y=>u(y)).catch(()=>u(void 0))},[i.token,i.entity,i.refreshId]),w.useEffect(()=>{n&&n(s)},[s]),w.useEffect(()=>{Array.isArray(l)&&(e?p(e):(!l||(l==null?void 0:l.length)<1)&&p(h.filter(b=>b!==G.Mercoa.InvoiceStatus.New)))},[e,l]);const[m,g]=w.useState();return w.useEffect(()=>{var b;!i.token||!((b=i.entity)!=null&&b.id)||mY({statuses:h,search:r,mercoaSession:i,setMetrics:g,excludePayables:o??!1,excludeReceivables:a??!1})},[r,h,i.client,i.entity,i.refreshId]),i.client?f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"md:mercoa-hidden mercoa-mt-2",children:[f.jsx("label",{htmlFor:"tabs",className:"mercoa-sr-only",children:"Select a tab"}),f.jsx("select",{id:"tabs",name:"tabs",className:"mercoa-block mercoa-w-full mercoa-rounded-mercoa mercoa-border-gray-300 mercoa-py-1 mercoa-pl-3 mercoa-pr-10 mercoa-text-base focus:mercoa-border-mercoa-primary focus:mercoa-outline-none focus:mercoa-ring-mercoa-primary sm:mercoa-text-sm",defaultValue:s,multiple:!0,onChange:b=>{c([b.target.value])},children:h.map(b=>f.jsx("option",{value:b,children:CR(b,l,o)},b))})]}),f.jsx("div",{className:"mercoa-hidden md:mercoa-block sm:mercoa-border-b sm:mercoa-border-gray-200",children:f.jsx("nav",{className:"-mercoa-mb-px mercoa-block sm:mercoa-flex sm:mercoa-space-x-6 mercoa-overflow-auto","aria-label":"Tabs",children:h.map(b=>{var _;return f.jsxs("a",{onClick:()=>{c([b])},href:"#",className:`${b==s[0]?"mercoa-text-mercoa-primary sm:mercoa-border-mercoa-primary":"mercoa-border-transparent mercoa-text-gray-500 hover:mercoa-border-gray-300 hover:mercoa-text-gray-700"} mercoa-mr-2 mercoa-whitespace-nowrap mercoa-py-4 mercoa-px-1 mercoa-text-sm mercoa-font-medium sm:mercoa-mr-0 sm:mercoa-border-b-2`,"aria-current":CR(b,l,o)==s[0]?"page":void 0,children:[CR(b,l,o)," ",f.jsx(PN,{count:((_=m==null?void 0:m[b])==null?void 0:_.totalCount)??0,selected:b==s[0]})]},b)})})})]}):f.jsx(at,{componentName:"StatusTabs"})}function zR({availableStatuses:e,currentStatuses:t,onStatusChange:r,placeholder:n,label:o,className:a,multiple:i}){const[s,c]=w.useState(t??[G.Mercoa.InvoiceStatus.Draft]),l=e??[G.Mercoa.InvoiceStatus.Draft,G.Mercoa.InvoiceStatus.New,G.Mercoa.InvoiceStatus.Approved,G.Mercoa.InvoiceStatus.Scheduled,G.Mercoa.InvoiceStatus.Pending,G.Mercoa.InvoiceStatus.Paid,G.Mercoa.InvoiceStatus.Canceled,G.Mercoa.InvoiceStatus.Refused,G.Mercoa.InvoiceStatus.Failed],u={UNASSIGNED:"#E0E7FF",DRAFT:"#E0E7FF",NEW:"#E0F2FE",APPROVED:"#BEF264",SCHEDULED:"#D1FAE5",PENDING:"#FDE68A",FAILED:"#FCA5A5",PAID:"#ECFCCB",CANCELED:"#E5E7EB",REFUSED:"#FEE2E2",ARCHIVED:"#E5E7EB"};return w.useEffect(()=>{r&&(Array.isArray(s)?r(s):r([s]))},[s]),f.jsx(f.Fragment,{children:f.jsx(In,{options:l.map(h=>({value:h,disabled:!1,color:u[h]})),onChange:h=>{c(h)},value:s,multiple:i,displaySelectedAs:"pill",placeholder:n??"All Invoices",label:o,inputClassName:a})})}function vY({statuses:e,onSelectInvoice:t,statusSelectionStyle:r,columns:n}){const[o,a]=w.useState([G.Mercoa.InvoiceStatus.Draft]),[i,s]=w.useState("");return f.jsxs("div",{className:"mercoa-mt-8",children:[f.jsxs("div",{className:"mercoa-grid mercoa-items-center mercoa-grid-cols-3",children:[f.jsx("div",{className:"mercoa-hidden md:mercoa-block md:mercoa-col-span-2",children:r=="dropdown"&&f.jsx("div",{className:"mercoa-grid mercoa-grid-cols-2",children:f.jsx(zR,{availableStatuses:e,onStatusChange:a,multiple:!0})})}),f.jsx("div",{className:"mercoa-flex mercoa-w-full mercoa-rounded-mercoa mercoa-shadow-sm mercoa-mr-2 mercoa-col-span-3 md:mercoa-col-span-1",children:f.jsx(lT,{placeholder:"Search Vendors, Invoice #, Amount",onSettle:s})})]}),r!="dropdown"&&f.jsx(IR,{statuses:e,search:i,onStatusChange:a,excludeReceivables:!0}),f.jsx(DR,{statuses:o,search:i,excludeReceivables:!0}),f.jsx(bY,{statuses:o,search:i,onSelectInvoice:t,columns:n})]})}function yY(){var t,r,n,o,a,i,s,c,l;const e=Le();return e.client?f.jsxs("div",{children:[((n=(r=(t=e.organization)==null?void 0:t.paymentMethods)==null?void 0:r.payerPayments)==null?void 0:n.find(u=>u.type===G.Mercoa.PaymentMethodType.BankAccount&&u.active))&&f.jsxs(f.Fragment,{children:[f.jsx("h3",{className:"mercoa-mt-8",children:"Bank Accounts"}),f.jsx(XH,{showEdit:!0,showAdd:!0})]}),((i=(a=(o=e.organization)==null?void 0:o.paymentMethods)==null?void 0:a.payerPayments)==null?void 0:i.find(u=>u.type===G.Mercoa.PaymentMethodType.Card&&u.active))&&f.jsxs(f.Fragment,{children:[f.jsx("h3",{className:"mercoa-mt-8",children:"Cards"}),f.jsx(YH,{showEdit:!0,showAdd:!0})]}),((l=(c=(s=e.organization)==null?void 0:s.paymentMethods)==null?void 0:c.payerPayments)==null?void 0:l.find(u=>u.type===G.Mercoa.PaymentMethodType.Custom&&u.active))&&f.jsxs(f.Fragment,{children:[f.jsx("h3",{className:"mercoa-mt-8",children:"Custom Payment Methods"}),f.jsx(x9,{showEdit:!0})]})]}):f.jsx(at,{componentName:"PaymentMethods"})}function R9e({selectedPayer:e,paymentDestination:t}){const[r,n]=w.useState("pdf"),o=Le(),{watch:a}=kt(),i=a(),s={id:i.id??"",status:i.status??"DRAFT",invoiceNumber:i.invoiceNumber,amount:i.amount,currency:i.currency??"USD",payerId:i.payerId,payer:e,vendor:o.entity,invoiceDate:i.invoiceDate,dueDate:i.dueDate,lineItems:i.lineItems,deductionDate:i.deductionDate,paymentDestination:t,paymentDestinationId:i.paymentDestinationId,paymentDestinationOptions:i.paymentDestinationOptions,paymentSourceId:i.paymentSourceId,noteToSelf:i.description,hasDocuments:i.hasDocuments??!1,metadata:i.metadata??{},comments:i.comments??[],creatorUser:i.creatorUser,paymentDestinationConfirmed:!1,hasSourceEmail:!1,approvers:[],approvalPolicy:[],createdAt:new Date,updatedAt:new Date},c=[{name:"Invoice PDF",action:"pdf"},{name:"Payment Page",action:"paymentPage"}];return f.jsx("div",{className:"mercoa-h-full mercoa-w-full mercoa-flex mercoa-flex-col mercoa-justify-center mercoa-items-center",children:f.jsxs("div",{className:"mercoa-h-full mercoa-w-[740px] mercoa-flex mercoa-flex-col mercoa-items-center",children:[f.jsx("nav",{className:"-mercoa-mb-px mercoa-flex mercoa-space-x-8",children:c.map(l=>f.jsx("button",{onClick:()=>n(l.action),className:`${l.action===r?"mercoa-border-mercoa-primary mercoa-text-mercoa-primary":"mercoa-border-transparent mercoa-text-gray-500 hover:mercoa-border-gray-300 hover:mercoa-text-gray-700"} mercoa-whitespace-nowrap mercoa-border-b-2 mercoa-px-1 mercoa-pb-4 mercoa-text-sm mercoa-font-medium`,children:l.name},l.name))}),f.jsxs("div",{style:{transform:"scale(0.75)"},className:"mercoa-w-full mercoa-grow mercoa-border mercoa-rounded-mercoa mercoa-shadow-md mercoa-p-10",children:[r==="pdf"&&f.jsx($9e,{invoice:s}),r==="email"&&f.jsx(F9e,{invoice:s}),r==="paymentPage"&&f.jsx(B9e,{invoice:s})]})]})})}function $9e({invoice:e}){return f.jsx(wY,{invoice:e})}function F9e({invoice:e}){const[t,r]=w.useState("");return w.useEffect(()=>{fetch("/api/generatePaymentLinkEmail",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},[e]),f.jsx("div",{dangerouslySetInnerHTML:{__html:t}})}function B9e({invoice:e}){var i;const[t,r]=w.useState(G.Mercoa.PaymentMethodType.BankAccount),o=((i=Le().organization)==null?void 0:i.supportEmail)??"support@mercoa.com",a=ea.formatMoney(e.amount??"",nn(e.currency));return f.jsx(_Y,{invoice:e,supportEmail:o,totalDisplay:a,selectedPaymentType:t,updateInvoice:()=>{},setSelectedPaymentType:r})}He.extend(FN);function L9e({invoiceId:e,invoice:t,onUpdate:r,admin:n,documentPosition:o="left",children:a}){var E,D,A,z,$,L,B,W,K;const i=Le(),[s,c]=w.useState([]),[l,u]=w.useState([]),[h,p]=w.useState([]),[m,g]=w.useState(t),[b,_]=w.useState(t==null?void 0:t.payer),[y,x]=w.useState([]),O=mo({id:Be().nullable(),status:Be(),amount:Za().positive().required().typeError("Please enter a valid number"),invoiceNumber:Be(),description:Be(),dueDate:To().required("Please select a due date").typeError("Please select a due date"),deductionDate:To().typeError("Please select a deduction date"),invoiceDate:To().required("Please select an invoice date").typeError("Please select an invoice date"),approvers:po(),lineItems:ZE().of(mo({id:Be(),description:Be().required(),amount:Za().required().typeError("Please enter a valid number"),currency:Be(),quantity:Za().required().typeError("Please enter a valid number"),unitPrice:Za().required().typeError("Please enter a valid number"),metadata:po().nullable(),glAccountId:Be(),createdAt:To(),updatedAt:To()})),currency:Be().required(),payerId:Be(),payerName:Be(),paymentDestinationId:Be(),paymentDestinationType:Be(),paymentSourceType:Be(),paymentDestinationOptions:po().nullable(),paymentSourceCheckEnabled:xu(),paymentSourceId:Be(),saveAsDraft:xu(),saveAsAdmin:xu(),metadata:po().nullable(),creatorUser:po().nullable()}).required(),S=Zn({resolver:Zi(O),defaultValues:{id:t==null?void 0:t.id,status:t==null?void 0:t.status,invoiceNumber:t==null?void 0:t.invoiceNumber,amount:t==null?void 0:t.amount,currency:(t==null?void 0:t.currency)??"USD",payerId:(E=t==null?void 0:t.payer)==null?void 0:E.id,payerName:(D=t==null?void 0:t.payer)==null?void 0:D.name,invoiceDate:t!=null&&t.invoiceDate?He(t==null?void 0:t.invoiceDate).toDate():void 0,dueDate:t!=null&&t.dueDate?He(t==null?void 0:t.dueDate).toDate():void 0,deductionDate:t!=null&&t.deductionDate?He(t==null?void 0:t.deductionDate).toDate():void 0,lineItems:(t==null?void 0:t.lineItems)??[],paymentDestinationId:(A=t==null?void 0:t.paymentDestination)==null?void 0:A.id,paymentDestinationType:((z=t==null?void 0:t.paymentDestination)==null?void 0:z.type)??"",paymentDestinationOptions:t==null?void 0:t.paymentDestinationOptions,paymentSourceId:($=t==null?void 0:t.paymentSource)==null?void 0:$.id,paymentSourceType:((L=t==null?void 0:t.paymentSource)==null?void 0:L.type)??"",paymentSourceCheckEnabled:((W=(B=t==null?void 0:t.paymentSource)==null?void 0:B.checkOptions)==null?void 0:W.enabled)??!1,description:(t==null?void 0:t.noteToSelf)??"",saveAsDraft:!1,metadata:(t==null?void 0:t.metadata)??{},creatorUser:t==null?void 0:t.creatorUser}});async function j(Z){var ue,ge;if(!i.token||!((ue=i.entity)!=null&&ue.id))return;const re=await((ge=i.client)==null?void 0:ge.invoice.get(Z));re&&(g(re),_(re.payer))}if(w.useEffect(()=>{var Z;!i.token||!((Z=i.entity)!=null&&Z.id)||!t&&e&&j(e)},[t,e,i.token,(K=i.entity)==null?void 0:K.id]),!i.client)return f.jsx(at,{componentName:"ReceivableDetails"});if(o==="none")return f.jsx(Us,{...S,children:f.jsx(UR,{invoice:m,onUpdate:r,refreshInvoice:j,admin:n,supportedCurrencies:y,setSupportedCurrencies:x,setDestinationPaymentMethods:u,setSourcePaymentMethods:p,setPaymentMethodSchemas:c,selectedPayer:b,setSelectedPayer:_,children:a})});const P=S.watch("paymentDestinationId"),I=f.jsx(bT,{minSize:0,maxSize:800,children:f.jsx(R9e,{selectedPayer:b,paymentDestination:l.find(Z=>Z.id===P)})}),M=f.jsx(bT,{className:`mercoa-relative ${o==="left"?"mercoa-pl-5":"mercoa-pr-5"}`,minSize:400,children:f.jsx(UR,{invoice:m,onUpdate:r,refreshInvoice:j,admin:n,supportedCurrencies:y,setSupportedCurrencies:x,setDestinationPaymentMethods:u,setSourcePaymentMethods:p,setPaymentMethodSchemas:c,selectedPayer:b,setSelectedPayer:_,children:a})});return f.jsx(Us,{...S,children:f.jsxs(bk,{children:[o==="left"?I:M,f.jsx(vk,{size:10,className:"mercoa-cursor-col-resize mercoa-invisible min-[450px]:mercoa-visible",style:{background:"linear-gradient(180deg, rgba(229,231,235,1) 48%, rgba(145,145,145,1) 48%, rgba(145,145,145,1) 52%, rgba(229,231,235,1) 52%)"}}),o==="right"?I:M]})})}function UR({invoice:e,onUpdate:t,refreshInvoice:r,admin:n,supportedCurrencies:o,setSupportedCurrencies:a,setDestinationPaymentMethods:i,setSourcePaymentMethods:s,setPaymentMethodSchemas:c,selectedPayer:l,setSelectedPayer:u,children:h}){var re,ue,ge,H,R,Q;const p=Le(),{register:m,handleSubmit:g,setValue:b,setError:_,clearErrors:y,watch:x,setFocus:O,control:S,formState:{errors:j}}=kt();w.useEffect(()=>{var ae,k,N,q,ie,le,U,X,be,xe,Ce,Te;e&&(((ae=e.paymentDestination)==null?void 0:ae.type)==="custom"?b("paymentDestinationType",((k=e.paymentDestination)==null?void 0:k.schemaId)??""):b("paymentDestinationType",((N=e.paymentDestination)==null?void 0:N.type)??""),((q=e.paymentSource)==null?void 0:q.type)==="custom"?b("paymentSourceType",((ie=e.paymentSource)==null?void 0:ie.schemaId)??""):b("paymentSourceType",((le=e.paymentSource)==null?void 0:le.type)??""),b("id",e.id),b("status",e.status),b("invoiceNumber",e.invoiceNumber),b("amount",e.amount),b("currency",e.currency??"USD"),b("payerId",(U=e.payer)==null?void 0:U.id),b("payerName",(X=e.payer)==null?void 0:X.name),b("invoiceDate",e.invoiceDate?He(e.invoiceDate).toDate():void 0),b("dueDate",e.dueDate?He(e.dueDate).toDate():void 0),b("deductionDate",e.deductionDate?He(e.deductionDate).toDate():void 0),b("lineItems",e.lineItems??[]),b("paymentDestinationId",(be=e.paymentDestination)==null?void 0:be.id),b("paymentDestinationOptions",e.paymentDestinationOptions),b("paymentSourceId",(xe=e.paymentSource)==null?void 0:xe.id),b("paymentSourceCheckEnabled",((Te=(Ce=e.paymentSource)==null?void 0:Ce.checkOptions)==null?void 0:Te.enabled)??!1),b("description",e.noteToSelf??""),b("hasDocuments",e.hasDocuments??!1),b("saveAsStatus",""),b("saveAsAdmin",!1),b("metadata",e.metadata??{}),b("creatorUser",e==null?void 0:e.creatorUser),b("comments",(e==null?void 0:e.comments)??[]))},[e]),w.useEffect(()=>{var ae,k,N,q,ie;e!=null&&e.id&&(b("status",e==null?void 0:e.status),b("invoiceNumber",e==null?void 0:e.invoiceNumber),e!=null&&e.amount&&b("amount",e.amount),b("currency",(e==null?void 0:e.currency)??"USD"),b("payerId",(ae=e==null?void 0:e.payer)==null?void 0:ae.id),b("payerName",(k=e==null?void 0:e.payer)==null?void 0:k.name),e!=null&&e.invoiceDate&&b("invoiceDate",He(e.invoiceDate).toDate()),e!=null&&e.dueDate&&b("dueDate",He(e==null?void 0:e.dueDate).toDate()),b("deductionDate",e!=null&&e.deductionDate?He(e==null?void 0:e.deductionDate).toDate():void 0),b("lineItems",((N=e==null?void 0:e.lineItems)==null?void 0:N.map(le=>({description:le.description??"",currency:le.currency??"USD",amount:le.amount??0,quantity:le.quantity??0,unitPrice:le.unitPrice??0,name:le.name??"",metadata:le.metadata??{},glAccountId:le.glAccountId??"",id:le.id??"",createdAt:le.createdAt??new Date,updatedAt:le.updatedAt??new Date})))??[]),b("paymentDestinationId",(q=e==null?void 0:e.paymentDestination)==null?void 0:q.id),b("paymentDestinationOptions",e==null?void 0:e.paymentDestinationOptions),b("paymentSourceId",(ie=e==null?void 0:e.paymentSource)==null?void 0:ie.id),b("description",(e==null?void 0:e.noteToSelf)??""))},[e,b]);const{fields:P,append:I,remove:M}=Hd({control:S,name:"lineItems"});x((ae,{name:k,type:N})=>{if(k==="currency"&&ae.lineItems.forEach((U,X)=>{b(`lineItems.${X}.currency`,ae.currency??"USD")}),!(k!=null&&k.startsWith("lineItems"))||k.endsWith("amount"))return;let ie=ae.lineItems.reduce((le,U,X)=>(U.amount=Math.floor((U.quantity??1)*(U.unitPrice??1)*100)/100,b(`lineItems.${X}.amount`,U.amount),le+U.amount),0);ie=Math.floor(ie*100)/100,b("amount",ie)});const E=x("payerId"),D=x("payerName"),A=x("currency");function z(){var ae;p.entityId&&((ae=p.client)==null||ae.entity.paymentMethod.getAll(p.entityId,{type:"bankAccount"}).then(k=>{i(k)}))}async function $(){var k;if(!p.token||!E)return;const ae=await((k=p.client)==null?void 0:k.entity.paymentMethod.getAll(E));ae&&s(ae)}w.useEffect(()=>{z()},[p.entityId]),w.useEffect(()=>{var ae,k;!p.token||!((ae=p.entity)!=null&&ae.id)||!p.client||($(),(k=p.client)==null||k.customPaymentMethodSchema.getAll().then(N=>{var q,ie;if(N){c(N);let le=[];((ie=(q=p.organization)==null?void 0:q.paymentMethods)==null?void 0:ie.payerPayments.some(X=>X.active&&(X.type==="bankAccount"||X.type==="card")))&&le.push("USD"),N.forEach(X=>{X.supportedCurrencies&&(le=[...new Set([...le,...X.supportedCurrencies])])}),a(le)}}))},[p.client,E,p.token]),w.useEffect(()=>{o.length>0&&b("currency",(e==null?void 0:e.currency)??o[0])},[o]);async function L(){var k;if(!(e!=null&&e.id))return;const ae=await((k=p.client)==null?void 0:k.invoice.document.generateInvoicePdf(e.id));ae!=null&&ae.uri?window.open(ae.uri,"_blank"):Ae.error("There was an issue generating the Invoice PDF. Please refresh and try again.")}async function B(){var k;if(!(e!=null&&e.id))return;const ae=await((k=p.client)==null?void 0:k.invoice.paymentLinks.getPayerLink(e.id));ae?window.open(ae,"_blank"):Ae.error("There was an issue creating the payment link. Please refresh and try again.")}async function W(){var ae,k,N;if(e!=null&&e.id){if(!((ae=e.payer)!=null&&ae.email)){Ae.error("There is no payer email address for this invoice.");return}try{await((k=p.client)==null?void 0:k.invoice.update(e.id,{status:G.Mercoa.InvoiceStatus.Approved}));try{await((N=p.client)==null?void 0:N.invoice.paymentLinks.sendPayerEmail(e.id)),Ae.info("Email Sent")}catch{Ae.error("There was an issue generating the email. Please refresh and try again.")}}catch(q){Ae.error(`There was an issue saving the invoice.
229
229
  Error: ${q.body}`)}}}async function K(ae){var q,ie;if(!p.entityId)return;const k={invoiceNumber:ae.invoiceNumber,invoiceDate:He(ae.invoiceDate).toDate(),dueDate:He(ae.dueDate).toDate(),currency:ae.currency??"USD",amount:ae.amount,payerId:ae.payerId,vendorId:p.entityId,paymentSourceId:ae.paymentSourceId,paymentDestinationId:ae.paymentDestinationId,creatorEntityId:p.entityId,noteToSelf:ae.description,lineItems:ae.lineItems.map(le=>({name:le.name,description:le.description,quantity:Number(le.quantity),unitPrice:Number(le.unitPrice),amount:Number(le.amount),currency:le.currency??"USD"}))};k.payerId&&p.entityId&&await((q=p.client)==null?void 0:q.entity.counterparty.addPayors(p.entityId,{payors:[k.payerId]}));const N=await((ie=p.client)==null?void 0:ie.invoice.create(k));p.debug(N),N!=null&&N.id?(Ae.success("Invoice created"),t&&t(N)):Ae.error("Invoice failed to create")}const Z=["Description","Quantity","Unit Price","Total Amount"];return p.client?f.jsxs("div",{className:"mercoa-p-2 mercoa-mx-4",children:[f.jsxs("h2",{className:"mercoa-text-lg mercoa-font-bold mercoa-leading-7 mercoa-text-gray-900",children:["Edit Invoice ",e&&f.jsx(YT,{status:(e==null?void 0:e.status)??"DRAFT"})]}),f.jsx("div",{className:"mercoa-grid mercoa-grid-cols-2 mercoa-gap-4 mercoa-items-center mercoa-mt-10 mercoa-w-full",children:f.jsxs("div",{className:"sm:mercoa-col-span-3",children:[f.jsx("label",{htmlFor:"vendor-name",className:"mercoa-block mercoa-text-lg mercoa-font-medium mercoa-leading-6 mercoa-text-gray-700",children:"Customer"}),f.jsx("div",{className:"mercoa-mt-2 mercoa-flex mercoa-items-center mercoa-justify-left mercoa-w-full",children:f.jsx(i9,{type:"payor",onSelect:ae=>{p.debug({payer:ae}),!(!ae||ae.id==="new")&&(u(ae),b("payerId",(ae==null?void 0:ae.id)??void 0,{shouldTouch:!0,shouldDirty:!0}),b("payerName",(ae==null?void 0:ae.name)??void 0,{shouldTouch:!0,shouldDirty:!0}),y("payerId"))},counterparty:l})}),((re=j.payerId)==null?void 0:re.message)&&f.jsx("p",{className:"mercoa-text-sm mercoa-text-red-500",children:(ue=j.payerId)==null?void 0:ue.message.toString()})]})}),f.jsxs("form",{onSubmit:g(K),children:[f.jsxs("div",{className:"mercoa-mt-5 mercoa-grid mercoa-grid-cols-3 mercoa-items-center mercoa-gap-4 mercoa-p-0.5",children:[f.jsx($e,{name:"invoiceDate",label:"Invoice Date",placeholder:"Invoice Date",type:"date",className:"sm:mercoa-col-span-1",control:S,errors:j}),f.jsx($e,{name:"dueDate",label:"Due Date",placeholder:"Due Date",type:"date",className:"sm:mercoa-col-span-1",control:S,errors:j}),f.jsx($e,{optional:!0,errors:j,register:m,name:"invoiceNumber",label:"Invoice #",type:"text",className:"sm:mercoa-col-span-1"})]}),f.jsx("div",{className:"mercoa-border-b mercoa-border-gray-900/10 mercoa-pb-6 mercoa-col-span-full"}),f.jsxs("div",{children:[f.jsx("p",{className:"mercoa-mb-1 mercoa-mt-5 mercoa-text-lg",children:"Line Items"}),f.jsxs("table",{className:"mercoa-min-w-full",children:[f.jsx("thead",{children:f.jsx("tr",{className:"mercoa-grid mercoa-grid-cols-[24%_24%_24%_24%_4%]",children:Z.map((ae,k)=>f.jsx("th",{className:"mercoa-text-left mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900",children:ae},ae))})}),f.jsxs("tbody",{children:[P.map((ae,k)=>f.jsxs("tr",{className:"mercoa-grid mercoa-grid-cols-[24%_24%_24%_24%_4%]",children:[f.jsx("td",{children:f.jsx($e,{name:`lineItems.${k}.description`,errors:j,register:m,placeholder:"Item Description"})}),f.jsx("td",{children:f.jsx($e,{name:`lineItems.${k}.quantity`,errors:j,register:m,placeholder:"Quantity",type:"number"})}),f.jsxs("td",{children:[" ",f.jsx($e,{name:`lineItems.${k}.unitPrice`,errors:j,control:S,placeholder:"Unit Price",type:"currency",leadingIcon:f.jsx("span",{className:"mercoa-text-gray-500 sm:mercoa-text-sm",children:nn(A)})})]}),f.jsxs("td",{children:[" ",f.jsx($e,{name:`lineItems.${k}.amount`,errors:j,control:S,placeholder:"Description",readOnly:!0,type:"currency",leadingIcon:f.jsx("span",{className:"mercoa-text-gray-500 sm:mercoa-text-sm",children:nn(A)})})]}),f.jsx("td",{className:"mercoa-flex mercoa-items-center",children:f.jsx(Cl,{className:"mercoa-size-5 mercoa-cursor-pointer mercoa-text-gray-500",onClick:()=>M(k)})})]},ae.id)),f.jsx("tr",{children:f.jsx("td",{children:f.jsx(Ue,{type:"button",isEmphasized:!1,className:"mercoa-mt-1",size:"sm",onClick:()=>I({id:"new",description:"",quantity:1,unitPrice:0,amount:0,currency:"USD",createdAt:new Date,updatedAt:new Date}),children:"Add Line Item"})})})]})]}),f.jsxs("table",{className:"mercoa-mt-5 mercoa-grid mercoa-grid-cols-4 mercoa-gap-4 mercoa-items-start mercoa-p-0.5",children:[f.jsx($e,{name:"amount",label:"Total Amount",type:"currency",readOnly:!0,errors:j,control:S,leadingIcon:f.jsx("span",{className:"mercoa-text-gray-500 sm:mercoa-text-sm",children:nn(A)}),trailingIcon:f.jsxs(f.Fragment,{children:[f.jsx("label",{htmlFor:"currency",className:"mercoa-sr-only",children:"Currency"}),f.jsx("select",{...m("currency"),className:"mercoa-h-full mercoa-rounded-mercoa mercoa-border-0 mercoa-bg-transparent mercoa-py-0 mercoa-pl-2 mercoa-pr-7 mercoa-text-gray-500 focus:mercoa-ring-1 focus:mercoa-ring-inset focus:mercoa-ring-mercoa-primary sm:mercoa-text-sm",children:o.map((ae,k)=>f.jsx("option",{value:ae,children:ae},k))})]})}),f.jsxs("div",{className:"mercoa-col-span-3",children:[f.jsx("label",{htmlFor:"description",className:"mercoa-block mercoa-text-sm mercoa-font-medium mercoa-leading-6 mercoa-text-gray-900 ",children:"Internal Notes"}),f.jsx("div",{className:"mercoa-mt-1",children:f.jsx("textarea",{id:"description",...m("description"),rows:3,className:"mercoa-block mercoa-w-full mercoa-rounded-mercoa mercoa-border-0 mercoa-py-1.5 mercoa-text-gray-900 mercoa-shadow-sm mercoa-ring-1 mercoa-ring-inset mercoa-ring-gray-300 placeholder:mercoa-text-gray-400 focus:mercoa-ring-1 focus:mercoa-ring-inset focus:mercoa-ring-mercoa-primary sm:mercoa-text-sm sm:mercoa-leading-6",style:{height:"36px"},defaultValue:""})})]})]})]}),f.jsx("div",{className:"mercoa-border-b mercoa-border-gray-900/10 mercoa-pb-6 mercoa-col-span-full"}),f.jsxs("div",{className:"mercoa-pb-6 mercoa-col-span-full",children:[f.jsxs("h2",{className:"mercoa-block mercoa-text-lg mercoa-font-medium mercoa-leading-6 mercoa-text-gray-700 mercoa-mt-5",children:["Choose existing payment method on file for"," ",f.jsx("span",{className:"mercoa-text-gray-800 mercoa-underline",children:D}),":"]}),f.jsx(NR,{isSource:!0}),((ge=j.paymentSourceId)==null?void 0:ge.message)&&f.jsx("p",{className:"mercoa-text-sm mercoa-text-red-500",children:(H=j.paymentSourceId)==null?void 0:H.message.toString()})]}),f.jsx("div",{className:"mercoa-border-b mercoa-border-gray-900/10 mercoa-pb-6 mercoa-col-span-full"}),f.jsxs("div",{className:"mercoa-border-b mercoa-border-gray-900/10 mercoa-pb-16 mercoa-col-span-full",children:[f.jsx("h2",{className:"mercoa-block mercoa-text-lg mercoa-font-medium mercoa-leading-6 mercoa-text-gray-700 mercoa-mt-5",children:"How do you want to get paid?"}),f.jsx(NR,{isDestination:!0}),((R=j.paymentDestinationId)==null?void 0:R.message)&&f.jsx("p",{className:"mercoa-text-sm mercoa-text-red-500",children:(Q=j.paymentDestinationId)==null?void 0:Q.message.toString()})]}),f.jsx("div",{className:"mercoa-mt-5 mercoa-grid mercoa-grid-cols-1 mercoa-gap-2 mercoa-items-end mercoa-p-0.5",children:e!=null&&e.id?f.jsxs(f.Fragment,{children:[f.jsxs(Ue,{isEmphasized:!1,onClick:L,type:"button",className:"mercoa-flex mercoa-justify-center",children:[f.jsx(JQ,{className:"mercoa-size-5 md:mercoa-mr-2"})," Preview Invoice"]}),f.jsxs(Ue,{isEmphasized:!1,onClick:B,type:"button",className:"mercoa-flex mercoa-justify-center",children:[f.jsx(lZ,{className:"mercoa-size-5 md:mercoa-mr-2"})," Get Payment Link"]}),e.status===G.Mercoa.InvoiceStatus.Draft&&f.jsx(Ue,{isEmphasized:!1,children:"Save Draft"}),f.jsxs(Ue,{isEmphasized:!0,onClick:W,type:"button",className:"mercoa-flex mercoa-justify-center",children:[f.jsx(_s,{className:"mercoa-size-5 md:mercoa-mr-2"}),e.status==="DRAFT"?"Send Invoice":"Resend Invoice"]})]}):f.jsx(Ue,{className:"mercoa-mt-5",isEmphasized:!0,children:"Create Invoice"})})]})]}):f.jsx(at,{componentName:"ReceivableForm"})}function NR({isSource:e,isDestination:t}){var I;const r=Le(),[n,o]=w.useState([]),[a,i]=w.useState(!0),{watch:s,setValue:c,clearErrors:l}=kt();if(e===t)throw new Error("Must specify exactly one of isSource or isDestination");const u=s("payerId"),h=e?u:(I=r.entity)==null?void 0:I.id;async function p(){var E;if(!r.token||!h||!r.client)return;const M=await((E=r.client)==null?void 0:E.entity.paymentMethod.getAll(h));o(M)}w.useEffect(()=>{!r.token||!h||!r.client||p()},[r.client,h,r.token]);const m=e?"paymentSourceType":"paymentDestinationType",g=e?"paymentSourceId":"paymentDestinationId",b=s(m),_=s(g),y=[];n.some(M=>M.type==="bankAccount")&&y.push({key:"bankAccount",value:"Bank Account"}),n.some(M=>M.type==="card")&&y.push({key:"card",value:"Card"}),n.some(M=>M.type==="check")&&y.push({key:"check",value:"Check"}),n.forEach(M=>{if(M.type==="custom"){if(y.some(E=>E.key===M.schemaId))return;y.push({key:M.schemaId??"",value:M.schema.name??""})}}),w.useEffect(()=>{if(!n||n.length===0||!a||(i(!1),_))return;let M;if(e?M=n.find(E=>E.isDefaultSource):M=n.find(E=>E.isDefaultDestination),M){M.type==="custom"?c(m,M.schemaId):c(m,M.type),c(g,M.id),l(g);return}if(n.some(E=>E.type==="bankAccount"))c(m,"bankAccount"),x("bankAccount");else if(n.some(E=>E.type==="card"))c(m,"card"),x("card");else if(n.some(E=>E.type==="check"))c(m,"check"),x("check");else if(n.some(E=>E.type==="custom")){const E=n.find(D=>D.type==="custom");E.schemaId&&(c(m,E.schemaId),x(E.schemaId))}},[n,_,a]);function x(M){var E,D,A;if(t&&c("paymentDestinationOptions",void 0),M===G.Mercoa.PaymentMethodType.BankAccount){const z=n.find($=>$.type===G.Mercoa.PaymentMethodType.BankAccount);c(g,z==null?void 0:z.id)}else M===G.Mercoa.PaymentMethodType.Card?c(g,(E=n.find(z=>z.type===G.Mercoa.PaymentMethodType.Card))==null?void 0:E.id):M===G.Mercoa.PaymentMethodType.Check?c(g,(D=n.find(z=>z.type===G.Mercoa.PaymentMethodType.Check))==null?void 0:D.id):c(g,(A=n.find(z=>z.type===G.Mercoa.PaymentMethodType.Custom&&z.schemaId===M))==null?void 0:A.id);l(g)}function O(){var E;const M=n==null?void 0:n.find(D=>D.type===G.Mercoa.PaymentMethodType.OffPlatform);M?(c(g,M.id),l(g)):(E=r.client)==null||E.entity.paymentMethod.create(h,{type:G.Mercoa.PaymentMethodType.OffPlatform}).then(async D=>{D&&(await p(),c(g,D.id),c(m,G.Mercoa.PaymentMethodType.OffPlatform),l(g))})}w.useEffect(()=>{b===G.Mercoa.PaymentMethodType.OffPlatform&&h&&O()},[t,h,b,n]),w.useEffect(()=>{var E;if(b!==G.Mercoa.PaymentMethodType.BankAccount||t)return;const M=n.find(D=>D.id===_);M&&c("paymentSourceCheckEnabled",((E=M==null?void 0:M.checkOptions)==null?void 0:E.enabled)??!1)},[t,b,n,_]),w.useEffect(()=>{t&&c("paymentDestinationOptions",void 0)},[t,b]),w.useEffect(()=>{if(b===G.Mercoa.PaymentMethodType.Custom){const M=n.find(E=>E.type===G.Mercoa.PaymentMethodType.Custom&&E.id===_);M!=null&&M.schemaId&&c(m,M.schemaId)}},[b,n,_]);const S=f.jsx("div",{className:"mercoa-max-h-[240px] mercoa-overflow-y-auto",children:n==null?void 0:n.filter(M=>M.type===G.Mercoa.PaymentMethodType.BankAccount).map(M=>f.jsx("div",{className:"mercoa-mt-1",children:f.jsx(Fc,{account:M,selected:_===M.id,onSelect:()=>{c(g,M.id),l(g)}})},M.id))}),j=f.jsx("div",{className:"mercoa-max-h-[240px] mercoa-overflow-y-auto",children:n==null?void 0:n.filter(M=>M.type===G.Mercoa.PaymentMethodType.Check).map(M=>f.jsx("div",{className:"mercoa-mt-1",children:f.jsx(ju,{account:M,selected:_===M.id,onSelect:()=>{c(g,M.id),l(g)}})},M.id))}),P=f.jsx("div",{className:"mercoa-max-h-[240px] mercoa-overflow-y-auto",children:n==null?void 0:n.filter(M=>M.type===G.Mercoa.PaymentMethodType.Card).map(M=>f.jsx("div",{className:"mercoa-mt-1",children:f.jsx(pm,{account:M,selected:_===M.id,onSelect:()=>{c(g,M.id),l(g)}})},M.id))});return r.client?f.jsxs("div",{children:[f.jsx(In,{options:y.map(M=>({value:M,disabled:!1})),onChange:M=>{c(m,M.key),x(M.key)},value:y.find(M=>M.key===b),displayIndex:"value"}),b===G.Mercoa.PaymentMethodType.BankAccount&&S,b===G.Mercoa.PaymentMethodType.Check&&j,b===G.Mercoa.PaymentMethodType.Card&&P]}):f.jsx(at,{componentName:"SelectPaymentMethod"})}function _Y({complete:e,invoice:t,supportEmail:r,totalDisplay:n,selectedPaymentType:o,updateInvoice:a,setSelectedPaymentType:i}){var _,y;const s=((_=t.vendor)==null?void 0:_.logo)??"https://storage.googleapis.com/mercoa-partner-logos/mercoa-logo.png",c=Le();return f.jsxs("div",{className:"mercoa-min-h-full",children:[f.jsx("div",{className:"mercoa-h-28",children:f.jsx("img",{src:s,alt:"logo",width:150,className:"mercoa-pt-4 mercoa-pl-4"})}),e?f.jsx(b,{invoice:t}):f.jsxs("div",{className:"mercoa-m-auto mercoa-grid sm:mercoa-grid-cols-12 sm:mercoa-max-w-5xl sm:mercoa-gap-x-4 mercoa-mt-5 mercoa-px-2 sm:mercoa-px-0 ",children:[f.jsx("div",{className:"mercoa-col-span-12 sm:mercoa-col-span-8",children:f.jsx(p,{invoice:t})}),f.jsx("aside",{className:"mercoa-col-span-12 mercoa-mt-4 sm:mercoa-mt-0 sm:mercoa-col-span-4",children:f.jsxs("div",{className:"mercoa-flex mercoa-flex-col mercoa-gap-y-5",children:[f.jsx(u,{invoice:t}),t.vendor&&f.jsx(h,{vendor:t.vendor}),f.jsxs("div",{className:"mercoa-flex mercoa-items-center mercoa-border-t-2 mercoa-border-gray-200 mercoa-text-left mercoa-text-xs mercoa-text-gray-400",children:[f.jsx(lC,{className:"mercoa-mr-2 mercoa-h-16 mercoa-w-16"}),f.jsxs("span",{children:["All your account information will remain private, secure, and hidden from"," ",f.jsx("b",{children:(y=t.vendor)==null?void 0:y.name})," and other businesses."]})]})]})})]}),f.jsxs("div",{className:"mercoa-mt-5 mercoa-p-2 mercoa-text-center mercoa-text-xs mercoa-text-gray-500",children:[f.jsx("b",{className:"mercoa-mr-2",children:"Have any questions?"}),f.jsx("a",{href:`mailto:${r??"support@mercoa.com"}`,target:"_blank",rel:"noreferrer",children:r??"support@mercoa.com"})]}),f.jsxs("div",{className:"mercoa-mt-5 mercoa-p-2 mercoa-text-center mercoa-text-xs mercoa-text-gray-500",children:[f.jsx("a",{href:"https://mercoa.com/legal/privacy-policy",target:"_blank",rel:"noreferrer",children:"Privacy Policy"})," ","|"," ",f.jsx("a",{href:"https://mercoa.com/legal/platform-agreement",target:"_blank",rel:"noreferrer",children:"Terms of Service"})]})]});async function l(){var O;if(!(t!=null&&t.id))return;const x=await((O=c.client)==null?void 0:O.invoice.document.generateInvoicePdf(t.id));x!=null&&x.uri?window.open(x.uri,"_blank"):Ae.error("There was an issue generating the Invoice PDF. Please refresh and try again.")}function u({invoice:x}){var O;return f.jsxs("div",{className:"mercoa-flex-1 mercoa-shadow-sm mercoa-bg-white mercoa-rounded-mercoa mercoa-px-3 mercoa-py-4 mercoa-border mercoa-border-gray-300",children:[f.jsx("h3",{className:"mercoa-text-lg mercoa-font-semibold mercoa-leading-6 mercoa-text-gray-900",children:(O=x.vendor)==null?void 0:O.name}),f.jsxs("p",{className:"mercoa-mt-5 mercoa-text-sm mercoa-font-medium mercoa-flex",children:[f.jsx("span",{className:"mercoa-text-gray-600",children:"Invoice"}),f.jsx("span",{className:"mercoa-ml-auto mercoa-text-gray-800",children:x.invoiceNumber})]}),f.jsxs("p",{className:"mercoa-mt-1 mercoa-text-sm mercoa-font-medium mercoa-flex",children:[f.jsx("span",{className:"mercoa-text-gray-600",children:"Due date"}),f.jsx("span",{className:"mercoa-ml-auto mercoa-text-gray-800",children:He(x.dueDate).format("MMM D, YYYY")})]}),f.jsxs("p",{className:"mercoa-mt-1 mercoa-text-sm mercoa-font-medium mercoa-flex",children:[f.jsx("span",{className:"mercoa-text-gray-600",children:"Invoice Amount"}),f.jsx("span",{className:"mercoa-ml-auto mercoa-text-gray-800",children:n})]}),f.jsx("hr",{className:"mercoa-my-3"}),f.jsxs("div",{className:"mercoa-flex mercoa-items-center",children:[f.jsx("div",{className:"mercoa-flex-1"}),f.jsx(Ue,{isEmphasized:!1,size:"sm",onClick:l,children:f.jsx(vF,{className:"mercoa-size-4"})}),f.jsx(Ue,{isEmphasized:!1,size:"sm",className:"mercoa-ml-3",children:f.jsx(zZ,{className:"mercoa-size-4",onClick:l})})]})]})}function h({vendor:x}){var M,E,D,A,z,$,L,B,W,K,Z,re,ue,ge,H,R;const O=((D=(E=(M=x.profile)==null?void 0:M.business)==null?void 0:E.phone)==null?void 0:D.number)??(($=(z=(A=x.profile)==null?void 0:A.individual)==null?void 0:z.phone)==null?void 0:$.number),j=`+${((W=(B=(L=x.profile)==null?void 0:L.business)==null?void 0:B.phone)==null?void 0:W.countryCode)??((re=(Z=(K=x.profile)==null?void 0:K.individual)==null?void 0:Z.phone)==null?void 0:re.countryCode)??"1"} ${O}`,P=((ge=(ue=x.profile)==null?void 0:ue.business)==null?void 0:ge.address)??((R=(H=x.profile)==null?void 0:H.individual)==null?void 0:R.address),I=`${(P==null?void 0:P.addressLine1)??""} ${(P==null?void 0:P.addressLine2)??""}, ${(P==null?void 0:P.city)??""}, ${(P==null?void 0:P.stateOrProvince)??""} ${(P==null?void 0:P.postalCode)??""}`;return f.jsxs("div",{className:"mercoa-flex-1 mercoa-shadow-sm mercoa-bg-white mercoa-rounded-mercoa mercoa-px-3 mercoa-py-4 mercoa-border mercoa-border-gray-300",children:[f.jsx("h3",{className:"mercoa-text-base mercoa-font-medium mercoa-leading-3 mercoa-text-gray-800",children:"Merchant details"}),f.jsxs("p",{className:"mercoa-mt-1 mercoa-text-sm mercoa-flex mercoa-text-gray-600",children:["Email: ",x.email]}),f.jsx("hr",{className:"mercoa-my-3"}),O&&f.jsxs("p",{className:"mercoa-flex mercoa-items-center mercoa-mt-3",children:[f.jsx(SF,{className:"mercoa-size-4 mercoa-inline-block mercoa-mr-2"}),f.jsx("a",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-blue-400",href:`tel:${j}`,children:j})]}),(P==null?void 0:P.addressLine1)&&f.jsxs("p",{className:"mercoa-flex mercoa-items-center mercoa-mt-3",children:[f.jsx(TF,{className:"mercoa-size-4 mercoa-inline-block mercoa-mr-2"}),f.jsx("a",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-blue-400",href:`https://www.google.com/maps/search/?api=1&query=${I}`,target:"_blank",rel:"noopener noreferrer",children:I})]})]})}function p({invoice:x}){const O=f.jsx("div",{className:"mercoa-w-full",children:f.jsxs(Ue,{isEmphasized:!0,size:"lg",className:"mercoa-w-full",children:["Pay ",n]})});return f.jsxs("div",{className:"mercoa-shadow-sm mercoa-bg-white mercoa-rounded-mercoa mercoa-px-5 mercoa-py-6 mercoa-border mercoa-border-gray-300",children:[f.jsx("p",{className:"mercoa-font-semibold mercoa-leading-6 mercoa-text-gray-400 mercoa-text-sm",children:"Payment Amount"}),f.jsx("p",{className:"mercoa-font-bold mercoa-leading-6 mercoa-text-gray-900 mercoa-text-3xl mercoa-mt-2",children:n}),f.jsx(m,{lineItems:(x==null?void 0:x.lineItems)??[]}),f.jsx("p",{className:"mercoa-font-semibold mercoa-leading-6 mercoa-text-gray-400 mercoa-text-sm mercoa-mt-5",children:"Payment Method"}),f.jsx(g,{}),f.jsx("div",{className:"mercoa-w-full mercoa-mt-5",children:o===G.Mercoa.PaymentMethodType.BankAccount&&f.jsx(Qz,{title:f.jsx(f.Fragment,{}),actions:O,onSubmit:a})})]})}function m({lineItems:x}){return x.length?f.jsxs(f.Fragment,{children:[f.jsx("p",{className:"mercoa-font-semibold mercoa-leading-6 mercoa-text-gray-400 mercoa-text-sm mercoa-mt-5",children:"Details"}),f.jsx("ul",{children:x.map(O=>f.jsxs("li",{className:"mercoa-flex mercoa-items-center mercoa-justify-between mercoa-p-2 mercoa-border-b",children:[f.jsx("div",{className:"mercoa-flex mercoa-items-center",children:f.jsxs("div",{className:"",children:[f.jsx("p",{className:"mercoa-text-md mercoa-font-medium mercoa-text-gray-900",children:O.name}),f.jsx("p",{className:"mercoa-text-xs mercoa-font-medium mercoa-text-gray-400",children:O.description}),f.jsxs("p",{className:"mercoa-text-sm mercoa-text-gray-500",children:[O.quantity," x ",nn(O.currency),O.unitPrice]})]})}),f.jsxs("div",{className:"mercoa-text-sm mercoa-text-gray-500",children:[nn(O.currency),O.amount]})]},O.id))})]}):f.jsx(f.Fragment,{})}function g(){return f.jsx("div",{className:"mercoa-flex mercoa-gap-x-4 mercoa-justify-center mercoa-mt-5",children:f.jsxs("button",{className:"mercoa-w-[150px]",onClick:()=>{i(G.Mercoa.PaymentMethodType.BankAccount)},children:[f.jsx("div",{className:"mercoa-rounded-mercoa mercoa-shadow-sm mercoa-p-3 mercoa-flex mercoa-items-center mercoa-justify-center mercoa-border-t-4 mercoa-border mercoa-border-gray-100"+(o===G.Mercoa.PaymentMethodType.BankAccount?" mercoa-border-t-primary":""),children:f.jsx(Al,{className:"mercoa-h-6 mercoa-w-6"})}),f.jsx("p",{className:"mercoa-mt-1 mercoa-text-gray-600"+(o===G.Mercoa.PaymentMethodType.BankAccount?" mercoa-font-bold":""),children:"Bank Account"})]})})}function b({invoice:x}){var O;return f.jsx("div",{className:"mercoa-max-w-2xl mercoa-m-auto",children:f.jsxs("div",{className:"mercoa-shadow-sm mercoa-bg-white mercoa-rounded-mercoa mercoa-px-5 mercoa-py-6 mercoa-border mercoa-border-gray-300",children:[f.jsx("h2",{className:"mercoa-primary-text mercoa-font-bold mercoa-leading-6 mercoa-text-gray-900 mercoa-text-3xl mercoa-mt-2 mercoa-text-center",children:"Success!"}),f.jsxs("div",{className:"mercoa-max-w-md mercoa-m-auto",children:[f.jsxs("p",{className:"mercoa-flex mercoa-items-center mercoa-justify-between mercoa-mt-5 mercoa-text-center mercoa-text-gray-500 ",children:[f.jsx("span",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-gray-700",children:"Merchant"}),f.jsx("span",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-gray-900",children:(O=x.vendor)==null?void 0:O.name})]}),f.jsxs("p",{className:"mercoa-flex mercoa-items-center mercoa-justify-between mercoa-mt-5 mercoa-text-center mercoa-text-gray-500 ",children:[f.jsx("span",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-gray-700",children:"Invoice Number"}),f.jsx("span",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-gray-900",children:x.invoiceNumber})]}),f.jsxs("p",{className:"mercoa-flex mercoa-items-center mercoa-justify-between mercoa-mt-5 mercoa-text-center mercoa-text-gray-500 ",children:[f.jsx("span",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-gray-700",children:"Payment Method"}),f.jsx("span",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-gray-900",children:"Wells Fargo ****1234"})]}),f.jsxs("p",{className:"mercoa-flex mercoa-items-center mercoa-justify-between mercoa-mt-5 mercoa-text-center mercoa-text-gray-500 ",children:[f.jsx("span",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-gray-700",children:"Transaction ID"}),f.jsx("span",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-gray-900",children:x==null?void 0:x.id})]}),f.jsxs("p",{className:"mercoa-flex mercoa-items-center mercoa-justify-between mercoa-mt-5 mercoa-text-center mercoa-text-gray-500 ",children:[f.jsx("span",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-gray-700",children:"Due Date"}),f.jsx("span",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-gray-900",children:He(x.dueDate).format("MMM D, YYYY")})]}),f.jsxs("p",{className:"mercoa-flex mercoa-items-center mercoa-justify-between mercoa-mt-5 mercoa-text-center mercoa-text-gray-500 ",children:[f.jsx("span",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-gray-700",children:"Payment Amount"}),f.jsx("span",{className:"mercoa-text-sm mercoa-font-medium mercoa-leading-3 mercoa-text-gray-900",children:n})]}),f.jsx(Ue,{isEmphasized:!0,size:"lg",className:"mercoa-w-full mercoa-mt-10",children:"Download Receipt"}),f.jsx(Ue,{isEmphasized:!1,size:"lg",className:"mercoa-w-full mercoa-mt-2",children:"Download Invoice"})]})]})})}}function wY({invoice:e}){var l,u,h,p,m,g,b,_,y,x,O,S,j,P,I,M,E,D;const t=Le();if(!e)return f.jsx(ra,{});const r=((h=(u=(l=e.payer)==null?void 0:l.profile)==null?void 0:u.individual)==null?void 0:h.address)??((g=(m=(p=e.payer)==null?void 0:p.profile)==null?void 0:m.business)==null?void 0:g.address),n=((y=(_=(b=e.vendor)==null?void 0:b.profile)==null?void 0:_.individual)==null?void 0:y.address)??((S=(O=(x=e.vendor)==null?void 0:x.profile)==null?void 0:O.business)==null?void 0:S.address),o=(j=e.vendor)==null?void 0:j.logo,a=f.jsxs("div",{className:"mercoa-flex mercoa-justify-between mercoa-mt-10",children:[f.jsxs("div",{children:[f.jsx("p",{className:"mercoa-text-2xl mercoa-font-bold",children:"Bill To:"}),f.jsx("p",{className:"mercoa-text-xl",children:(P=e.payer)==null?void 0:P.name}),(r==null?void 0:r.addressLine1)&&f.jsxs(f.Fragment,{children:[f.jsxs("p",{children:[r.addressLine1," ",r.addressLine2]}),f.jsxs("p",{children:[r.city,", ",r.stateOrProvince,", ",r.postalCode]})]})]}),f.jsxs("div",{className:"mercoa-border-l-2 mercoa-border-gray-500 mercoa-pl-6",children:[o&&f.jsx("img",{src:o,alt:"logo",width:150}),f.jsx("p",{className:"mercoa-text-xl mercoa-mt-2",children:(I=e.vendor)==null?void 0:I.name}),(n==null?void 0:n.addressLine1)&&f.jsxs(f.Fragment,{children:[f.jsxs("p",{children:[n.addressLine1," ",n.addressLine2]}),f.jsxs("p",{children:[n.city,", ",n.stateOrProvince,", ",n.postalCode]})]})]})]}),i=f.jsxs("div",{className:"mercoa-flex mercoa-justify-between mercoa-mt-10",children:[f.jsx("div",{className:"mercoa-text-5xl mercoa-font-medium",children:"INVOICE"}),f.jsxs("div",{children:[f.jsxs("div",{className:"mercoa-flex mercoa-justify-between",children:[f.jsx("span",{className:"mercoa-text-gray-500",children:"Invoice #"}),f.jsx("span",{className:"mercoa-text-gray-800 mercoa-pl-2",children:e.invoiceNumber})]}),f.jsxs("div",{className:"mercoa-flex mercoa-justify-between",children:[f.jsx("span",{className:"mercoa-text-gray-500",children:"Date"}),f.jsx("span",{className:"mercoa-text-gray-800 mercoa-pl-2",children:He(e.invoiceDate).format("MMM DD, YYYY")})]}),(E=(M=t.organization)==null?void 0:M.metadataSchema)==null?void 0:E.map(A=>{if(e.metadata[A.key])return f.jsxs("div",{children:[f.jsx("span",{className:"mercoa-text-gray-500",children:A.displayName}),f.jsx("span",{className:"mercoa-text-gray-800 mercoa-pl-2",children:e.metadata[A.key]})]},A.key)})]})]});function s({lineItems:A}){return A.length?f.jsx("div",{className:"mercoa-overflow-hidden mercoa-rounded-t-lg mercoa-mt-10 mercoa-pb-5 mercoa-border-b-2 mercoa-border-gray-300 ",children:f.jsxs("table",{className:"mercoa-min-w-full",children:[f.jsx("thead",{children:f.jsxs("tr",{children:[f.jsx("th",{scope:"col",className:"mercoa-py-3.5 mercoa-pl-4 mercoa-pr-3 mercoa-text-left mercoa-font-semibold mercoa-text-gray-900 sm:mercoa-pl-6",children:"ITEM"}),f.jsx("th",{scope:"col",className:"mercoa-px-3 mercoa-py-3.5 mercoa-text-left mercoa-font-semibold mercoa-text-gray-900",children:"PRICE"}),f.jsx("th",{scope:"col",className:"mercoa-px-3 mercoa-py-3.5 mercoa-text-left mercoa-font-semibold mercoa-text-gray-900",children:"QTY"}),f.jsx("th",{scope:"col",className:"mercoa-px-3 mercoa-py-3.5 mercoa-text-left mercoa-font-semibold mercoa-text-gray-900",children:"TOTAL"})]})}),f.jsx("tbody",{children:A.map(z=>f.jsxs("tr",{children:[f.jsxs("td",{className:"mercoa-whitespace-nowrap mercoa-py-4 mercoa-pl-4 mercoa-pr-3 mercoa-font-medium mercoa-text-gray-900 sm:mercoa-pl-6",children:[f.jsx("p",{className:"mercoa-text-md mercoa-font-medium mercoa-text-gray-900",children:z.name}),f.jsx("p",{className:"mercoa-text-xs mercoa-font-medium mercoa-text-gray-400",children:z.description})]}),f.jsx("td",{className:"mercoa-whitespace-nowrap mercoa-px-3 mercoa-py-4 mercoa-text-gray-700",children:ea.formatMoney(z.unitPrice??0,nn(z.currency))}),f.jsx("td",{className:"mercoa-whitespace-nowrap mercoa-px-3 mercoa-py-4 mercoa-text-gray-700",children:z.quantity}),f.jsx("td",{className:"mercoa-whitespace-nowrap mercoa-px-3 mercoa-py-4 mercoa-text-gray-800 mercoa-font-bold",children:ea.formatMoney(z.amount??0,nn(z.currency))})]},z.id))})]})}):f.jsx(f.Fragment,{})}const c=f.jsx("div",{className:"mercoa-flex mercoa-justify-end mercoa-mt-10 mercoa-text-xl",children:f.jsx("div",{children:f.jsxs("div",{className:"mercoa-flex mercoa-justify-between mercoa-items-baseline",children:[f.jsx("div",{className:"mercoa-text-gray-500",children:"Total"}),f.jsx("div",{className:"mercoa-text-gray-800 mercoa-ml-4 mercoa-mr-1",children:`${ea.formatMoney(e.amount??0,nn(e.currency))}`}),f.jsx("div",{className:"mercoa-text-gray-500 mercoa-text-xs",children:e.currency})]})})});return f.jsxs("div",{className:"mercoa-container mercoa-mx-auto mercoa-mt-10",children:[a,i,f.jsx(s,{lineItems:e.lineItems??[]}),c,((D=e.paymentDestination)==null?void 0:D.type)===G.Mercoa.PaymentMethodType.BankAccount&&e.vendor&&f.jsx("table",{children:f.jsxs("tbody",{children:[f.jsxs("tr",{children:[f.jsx("td",{className:"mercoa-text-gray-500",children:"Beneficiary Holder"}),f.jsx("td",{className:"mercoa-text-gray-800 mercoa-pl-2",children:e.vendor.name})]}),f.jsxs("tr",{children:[f.jsx("td",{className:"mercoa-text-gray-500",children:"Bank Name"}),f.jsx("td",{className:"mercoa-text-gray-800 mercoa-pl-2",children:e.paymentDestination.bankName})]}),f.jsxs("tr",{children:[f.jsx("td",{className:"mercoa-text-gray-500",children:"Account Number"}),f.jsx("td",{className:"mercoa-text-gray-800 mercoa-pl-2",children:e.paymentDestination.accountNumber})]}),f.jsxs("tr",{children:[f.jsx("td",{className:"mercoa-text-gray-500",children:"Routing Number"}),f.jsx("td",{className:"mercoa-text-gray-800 mercoa-pl-2",children:e.paymentDestination.routingNumber})]})]})})]})}He.extend(FN);function V9e({statuses:e,search:t,metadata:r,startDate:n,endDate:o,onSelectInvoice:a,columns:i,children:s}){const c=Le(),[l,u]=w.useState(),[h,p]=w.useState(G.Mercoa.InvoiceOrderByField.CreatedAt),[m,g]=w.useState(G.Mercoa.OrderDirection.Asc),[b,_]=w.useState(!0),[y,x]=w.useState(0),[O,S]=w.useState(!1),[j,P]=w.useState(e),[I,M]=w.useState([]),[E,D]=w.useState([]),[A,z]=w.useState(20),[$,L]=w.useState(1);async function B(){var re;if(!c.token||!((re=c.entity)!=null&&re.id))return;let W="",K=[];Z();async function Z(){var H,R;if(!c.token||!((H=c.entity)!=null&&H.id))return;const ue={status:j,search:t,startDate:n,endDate:o,orderBy:h,orderDirection:m,limit:100,startingAfter:W,excludePayables:!0,metadata:r},ge=await((R=c.client)==null?void 0:R.entity.invoice.find(c.entity.id,ue));if(ge)if(ge.data.length>0)W=ge.data[ge.data.length-1].id,K=[...K,...ge.data],await Z();else{const Q=pY.unparse(K.map(q=>{var ie,le,U,X,be,xe;return{"Invoice ID":q.id,"Invoice Number":q.invoiceNumber,Status:q.status,Amount:q.amount,Currency:q.currency,Note:q.noteToSelf,"Payer ID":(ie=q.payer)==null?void 0:ie.id,"Payer Email":(le=q.payer)==null?void 0:le.email,"Payer Name":(U=q.payer)==null?void 0:U.name,"Vendor ID":(X=q.vendor)==null?void 0:X.id,"Vendor Email":(be=q.vendor)==null?void 0:be.email,"Vendor Name":(xe=q.vendor)==null?void 0:xe.name,Metadata:JSON.stringify(q.metadata),"Due Date":He(q.dueDate),"Deduction Date":He(q.deductionDate),"Processed At":He(q.processedAt),"Created At":He(q.createdAt),"Updated At":He(q.updatedAt)}})),ae=new Blob([Q],{type:"text/csv"}),k=window.URL.createObjectURL(ae),N=document.createElement("a");N.setAttribute("mercoa-hidden",""),N.setAttribute("href",k),N.setAttribute("download",`mercoa-invoice-export-${He().format("YYYY-MM-DD")}.csv`),document.body.appendChild(N),N.click(),document.body.removeChild(N)}}}return w.useEffect(()=>{P(e)},[e]),w.useEffect(()=>{var Z,re;if(!c.token||!((Z=c.entity)!=null&&Z.id))return;let W=!0;M([]),S(!1);const K={status:j,search:t,startDate:n,endDate:o,orderBy:h,orderDirection:m,limit:A,startingAfter:E[E.length-1],excludePayables:!0,metadata:r};return(re=c.client)==null||re.entity.invoice.find(c.entity.id,K).then(ue=>{ue&&W&&(_(ue.hasMore),x(ue.count),u(ue.data),S(!0))}),()=>{W=!1}},[c.token,c.entity,c.refreshId,j,t,n,o,r,h,m,E,A]),w.useEffect(()=>{L(1),D([])},[t]),w.useEffect(()=>{e.some(W=>j.indexOf(W)<0)&&(P(e),S(!1),D([]),L(1),x(0))},[e,n,o]),s?s({dataLoaded:O,invoices:l||[],hasNext:b,getNext:()=>{l&&(L($+1),D([...E,l[l.length-1].id]))},hasPrevious:$!==1,getPrevious:()=>{L(Math.max(1,$-1)),D(E.slice(0,E.length-1))},resultsPerPage:A,setResultsPerPage:z,selectedInvoiceStatuses:j,setSelectedInvoiceStatues:P,downloadCSV:B,count:y}):O?f.jsx(f.Fragment,{children:c.entity&&l?f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"mercoa-min-h-[600px]",children:f.jsxs("table",{className:"mercoa-min-w-full mercoa-divide-y mercoa-divide-gray-300 mercoa-mt-5",children:[f.jsx("thead",{children:f.jsxs("tr",{children:[f.jsx("th",{scope:"col",className:"mercoa-py-3.5 mercoa-pl-4 mercoa-pr-3 mercoa-text-left mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 sm:mercoa-pl-3",children:f.jsx(Rm,{title:"Payer",setOrder:W=>{p(G.Mercoa.InvoiceOrderByField.PayerName),g(W)},isSelected:h===G.Mercoa.InvoiceOrderByField.PayerName,orderDirection:m})}),f.jsx("th",{scope:"col",className:"mercoa-px-3 mercoa-py-3.5 mercoa-text-left mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-hidden sm:mercoa-table-cell",children:f.jsx(Rm,{title:"Invoice Number",setOrder:W=>{p(G.Mercoa.InvoiceOrderByField.InvoiceNumber),g(W)},isSelected:h===G.Mercoa.InvoiceOrderByField.InvoiceNumber,orderDirection:m})}),f.jsx("th",{scope:"col",className:"mercoa-px-3 mercoa-py-3.5 mercoa-text-left mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900",children:f.jsx(Rm,{title:"Due Date",setOrder:W=>{p(G.Mercoa.InvoiceOrderByField.DueDate),g(W)},isSelected:h===G.Mercoa.InvoiceOrderByField.DueDate,orderDirection:m})}),f.jsx("th",{scope:"col",className:"mercoa-px-3 mercoa-py-3.5 mercoa-text-left mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900",children:f.jsx(Rm,{title:"Amount",setOrder:W=>{p(G.Mercoa.InvoiceOrderByField.Amount),g(W)},isSelected:h===G.Mercoa.InvoiceOrderByField.Amount,orderDirection:m})}),f.jsx("th",{scope:"col",className:"mercoa-px-3 mercoa-py-3.5 mercoa-text-left mercoa-text-sm mercoa-font-semibold mercoa-text-gray-900 mercoa-pl-6 mercoa-hidden lg:mercoa-table-cell",children:"Status"})]})}),f.jsx("tbody",{className:"mercoa-divide-y mercoa-divide-gray-200 mercoa-bg-white",children:l.map(W=>{var K;return f.jsxs("tr",{className:"mercoa-cursor-pointer hover:mercoa-bg-gray-100",onClick:()=>{a&&a(W)},children:[f.jsx("td",{className:"mercoa-whitespace-nowrap mercoa-py-3 mercoa-pl-4 mercoa-pr-3 mercoa-text-sm mercoa-font-medium mercoa-text-gray-900 sm:mercoa-pl-3",children:(K=W.payer)==null?void 0:K.name}),f.jsx("td",{className:"mercoa-whitespace-nowrap mercoa-px-3 mercoa-py-3 mercoa-text-sm mercoa-text-gray-900 mercoa-hidden sm:mercoa-table-cell",children:W.invoiceNumber}),f.jsx("td",{className:"mercoa-whitespace-nowrap mercoa-px-3 mercoa-py-3 mercoa-text-sm mercoa-text-gray-900",children:He(W.dueDate).format("MMM DD, YYYY")}),f.jsx("td",{className:"mercoa-whitespace-nowrap mercoa-px-3 mercoa-py-3 mercoa-text-sm mercoa-text-gray-900",children:ea.formatMoney(W.amount??"",nn(W.currency))}),f.jsx("td",{className:"mercoa-whitespace-nowrap mercoa-px-3 mercoa-py-3 mercoa-text-sm mercoa-hidden lg:mercoa-table-cell",children:W.status})]},W.id)})})]})}),f.jsx($m,{data:l,page:$,setPage:L,hasMore:b,startingAfter:E,setStartingAfter:D,count:y,resultsPerPage:A,setResultsPerPage:z})]}):f.jsx(Iw,{})}):f.jsx("div",{className:"mercoa-mt-7",children:f.jsx(Fm,{rows:10})})}function K9e({statuses:e,onSelectInvoice:t,statusSelectionStyle:r}){const[n,o]=w.useState([G.Mercoa.InvoiceStatus.Draft]),[a,i]=w.useState(""),s=e??[G.Mercoa.InvoiceStatus.Draft,G.Mercoa.InvoiceStatus.Approved,G.Mercoa.InvoiceStatus.Pending,G.Mercoa.InvoiceStatus.Paid];return f.jsxs("div",{className:"mercoa-mt-8",children:[f.jsxs("div",{className:"mercoa-grid mercoa-items-center mercoa-grid-cols-3",children:[f.jsx("div",{className:"mercoa-hidden md:mercoa-block md:mercoa-col-span-2",children:r=="dropdown"&&f.jsx("div",{className:"mercoa-grid mercoa-grid-cols-2",children:f.jsx(zR,{availableStatuses:s,onStatusChange:o,multiple:!0})})}),f.jsx("div",{className:"mercoa-flex mercoa-w-full mercoa-rounded-mercoa mercoa-shadow-sm mercoa-mr-2 mercoa-col-span-3 md:mercoa-col-span-1",children:f.jsx(lT,{placeholder:"Search Customers, Invoice #, Amount",onSettle:i})})]}),r!="dropdown"&&f.jsx(IR,{statuses:s,search:a,onStatusChange:o,excludePayables:!0}),f.jsx(DR,{statuses:n,search:a,excludePayables:!0}),f.jsx(V9e,{statuses:n,search:a,onSelectInvoice:t})]})}var H9e=null,xY=H9e;const X9e=$h({__proto__:null,default:mn(xY)},[xY]);var qT={},jY={exports:{}},RR={};(function(e){e.fetch=o(d.fetch)&&o(d.ReadableStream),e.writableStream=o(d.WritableStream),e.abortController=o(d.AbortController);var t;function r(){if(t!==void 0)return t;if(d.XMLHttpRequest){t=new d.XMLHttpRequest;try{t.open("GET",d.XDomainRequest?"/":"https://example.com")}catch{t=null}}else t=null;return t}function n(a){var i=r();if(!i)return!1;try{return i.responseType=a,i.responseType===a}catch{}return!1}e.arraybuffer=e.fetch||n("arraybuffer"),e.msstream=!e.fetch&&n("ms-stream"),e.mozchunkedarraybuffer=!e.fetch&&n("moz-chunked-arraybuffer"),e.overrideMimeType=e.fetch||(r()?o(r().overrideMimeType):!1);function o(a){return typeof a=="function"}t=null})(RR);var $R={exports:{}};typeof Object.create=="function"?$R.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:$R.exports=function(t,r){if(r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}};var Vu=$R.exports,JT={},FR={exports:{}},BR={exports:{}},Ym=typeof Reflect=="object"?Reflect:null,OY=Ym&&typeof Ym.apply=="function"?Ym.apply:function(t,r,n){return Function.prototype.apply.call(t,r,n)},QT;Ym&&typeof Ym.ownKeys=="function"?QT=Ym.ownKeys:Object.getOwnPropertySymbols?QT=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:QT=function(t){return Object.getOwnPropertyNames(t)};function W9e(e){console&&console.warn&&console.warn(e)}var MY=Number.isNaN||function(t){return t!==t};function Tr(){Tr.init.call(this)}BR.exports=Tr,BR.exports.once=q9e,Tr.EventEmitter=Tr,Tr.prototype._events=void 0,Tr.prototype._eventsCount=0,Tr.prototype._maxListeners=void 0;var SY=10;function ZT(e){if(typeof e!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}Object.defineProperty(Tr,"defaultMaxListeners",{enumerable:!0,get:function(){return SY},set:function(e){if(typeof e!="number"||e<0||MY(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");SY=e}}),Tr.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Tr.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||MY(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function PY(e){return e._maxListeners===void 0?Tr.defaultMaxListeners:e._maxListeners}Tr.prototype.getMaxListeners=function(){return PY(this)},Tr.prototype.emit=function(t){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var o=t==="error",a=this._events;if(a!==void 0)o=o&&a.error===void 0;else if(!o)return!1;if(o){var i;if(r.length>0&&(i=r[0]),i instanceof Error)throw i;var s=new Error("Unhandled error."+(i?" ("+i.message+")":""));throw s.context=i,s}var c=a[t];if(c===void 0)return!1;if(typeof c=="function")OY(c,this,r);else for(var l=c.length,u=DY(c,l),n=0;n<l;++n)OY(u[n],this,r);return!0};function EY(e,t,r,n){var o,a,i;if(ZT(r),a=e._events,a===void 0?(a=e._events=Object.create(null),e._eventsCount=0):(a.newListener!==void 0&&(e.emit("newListener",t,r.listener?r.listener:r),a=e._events),i=a[t]),i===void 0)i=a[t]=r,++e._eventsCount;else if(typeof i=="function"?i=a[t]=n?[r,i]:[i,r]:n?i.unshift(r):i.push(r),o=PY(e),o>0&&i.length>o&&!i.warned){i.warned=!0;var s=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");s.name="MaxListenersExceededWarning",s.emitter=e,s.type=t,s.count=i.length,W9e(s)}return e}Tr.prototype.addListener=function(t,r){return EY(this,t,r,!1)},Tr.prototype.on=Tr.prototype.addListener,Tr.prototype.prependListener=function(t,r){return EY(this,t,r,!0)};function k9e(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function TY(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},o=k9e.bind(n);return o.listener=r,n.wrapFn=o,o}Tr.prototype.once=function(t,r){return ZT(r),this.on(t,TY(this,t,r)),this},Tr.prototype.prependOnceListener=function(t,r){return ZT(r),this.prependListener(t,TY(this,t,r)),this},Tr.prototype.removeListener=function(t,r){var n,o,a,i,s;if(ZT(r),o=this._events,o===void 0)return this;if(n=o[t],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete o[t],o.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){for(a=-1,i=n.length-1;i>=0;i--)if(n[i]===r||n[i].listener===r){s=n[i].listener,a=i;break}if(a<0)return this;a===0?n.shift():G9e(n,a),n.length===1&&(o[t]=n[0]),o.removeListener!==void 0&&this.emit("removeListener",t,s||r)}return this},Tr.prototype.off=Tr.prototype.removeListener,Tr.prototype.removeAllListeners=function(t){var r,n,o;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var a=Object.keys(n),i;for(o=0;o<a.length;++o)i=a[o],i!=="removeListener"&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[t],typeof r=="function")this.removeListener(t,r);else if(r!==void 0)for(o=r.length-1;o>=0;o--)this.removeListener(t,r[o]);return this};function AY(e,t,r){var n=e._events;if(n===void 0)return[];var o=n[t];return o===void 0?[]:typeof o=="function"?r?[o.listener||o]:[o]:r?Y9e(o):DY(o,o.length)}Tr.prototype.listeners=function(t){return AY(this,t,!0)},Tr.prototype.rawListeners=function(t){return AY(this,t,!1)},Tr.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):CY.call(e,t)},Tr.prototype.listenerCount=CY;function CY(e){var t=this._events;if(t!==void 0){var r=t[e];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Tr.prototype.eventNames=function(){return this._eventsCount>0?QT(this._events):[]};function DY(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function G9e(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function Y9e(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}function q9e(e,t){return new Promise(function(r,n){function o(i){e.removeListener(t,a),n(i)}function a(){typeof e.removeListener=="function"&&e.removeListener("error",o),r([].slice.call(arguments))}IY(e,t,a,{once:!0}),t!=="error"&&J9e(e,o,{once:!0})})}function J9e(e,t,r){typeof e.on=="function"&&IY(e,"error",t,r)}function IY(e,t,r,n){if(typeof e.on=="function")n.once?e.once(t,r):e.on(t,r);else if(typeof e.addEventListener=="function")e.addEventListener(t,function o(a){n.once&&e.removeEventListener(t,o),r(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}var zY=BR.exports,UY=zY.EventEmitter;const eA=iC(Bne);var LR={},NY={},Q9e=G2,VR=function(){return Q9e()&&!!Symbol.toStringTag},Z9e=VR(),e7e=WC,KR=e7e("Object.prototype.toString"),tA=function(t){return Z9e&&t&&typeof t=="object"&&Symbol.toStringTag in t?!1:KR(t)==="[object Arguments]"},RY=function(t){return tA(t)?!0:t!==null&&typeof t=="object"&&typeof t.length=="number"&&t.length>=0&&KR(t)!=="[object Array]"&&KR(t.callee)==="[object Function]"},t7e=function(){return tA(arguments)}();tA.isLegacyArguments=RY;var r7e=t7e?tA:RY,n7e=Object.prototype.toString,o7e=Function.prototype.toString,a7e=/^\s*(?:function)?\*/,$Y=VR(),HR=Object.getPrototypeOf,i7e=function(){if(!$Y)return!1;try{return Function("return function*() {}")()}catch{}},XR,s7e=function(t){if(typeof t!="function")return!1;if(a7e.test(o7e.call(t)))return!0;if(!$Y){var r=n7e.call(t);return r==="[object GeneratorFunction]"}if(!HR)return!1;if(typeof XR>"u"){var n=i7e();XR=n?HR(n):!1}return HR(t)===XR},FY=Function.prototype.toString,qm=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,WR,rA;if(typeof qm=="function"&&typeof Object.defineProperty=="function")try{WR=Object.defineProperty({},"length",{get:function(){throw rA}}),rA={},qm(function(){throw 42},null,WR)}catch(e){e!==rA&&(qm=null)}else qm=null;var c7e=/^\s*class\b/,kR=function(t){try{var r=FY.call(t);return c7e.test(r)}catch{return!1}},GR=function(t){try{return kR(t)?!1:(FY.call(t),!0)}catch{return!1}},nA=Object.prototype.toString,l7e="[object Object]",u7e="[object Function]",d7e="[object GeneratorFunction]",f7e="[object HTMLAllCollection]",h7e="[object HTML document.all class]",p7e="[object HTMLCollection]",m7e=typeof Symbol=="function"&&!!Symbol.toStringTag,g7e=!(0 in[,]),YR=function(){return!1};if(typeof document=="object"){var b7e=document.all;nA.call(b7e)===nA.call(document.all)&&(YR=function(t){if((g7e||!t)&&(typeof t>"u"||typeof t=="object"))try{var r=nA.call(t);return(r===f7e||r===h7e||r===p7e||r===l7e)&&t("")==null}catch{}return!1})}var v7e=qm?function(t){if(YR(t))return!0;if(!t||typeof t!="function"&&typeof t!="object")return!1;try{qm(t,null,WR)}catch(r){if(r!==rA)return!1}return!kR(t)&&GR(t)}:function(t){if(YR(t))return!0;if(!t||typeof t!="function"&&typeof t!="object")return!1;if(m7e)return GR(t);if(kR(t))return!1;var r=nA.call(t);return r!==u7e&&r!==d7e&&!/^\[object HTML/.test(r)?!1:GR(t)},y7e=v7e,_7e=Object.prototype.toString,BY=Object.prototype.hasOwnProperty,w7e=function(t,r,n){for(var o=0,a=t.length;o<a;o++)BY.call(t,o)&&(n==null?r(t[o],o,t):r.call(n,t[o],o,t))},x7e=function(t,r,n){for(var o=0,a=t.length;o<a;o++)n==null?r(t.charAt(o),o,t):r.call(n,t.charAt(o),o,t)},j7e=function(t,r,n){for(var o in t)BY.call(t,o)&&(n==null?r(t[o],o,t):r.call(n,t[o],o,t))},O7e=function(t,r,n){if(!y7e(r))throw new TypeError("iterator must be a function");var o;arguments.length>=3&&(o=n),_7e.call(t)==="[object Array]"?w7e(t,r,o):typeof t=="string"?x7e(t,r,o):j7e(t,r,o)},M7e=O7e,S7e=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"],qR=S7e,P7e=typeof globalThis>"u"?d:globalThis,E7e=function(){for(var t=[],r=0;r<qR.length;r++)typeof P7e[qR[r]]=="function"&&(t[t.length]=qR[r]);return t},oA=M7e,T7e=E7e,LY=c4,JR=WC,aA=HC,A7e=JR("Object.prototype.toString"),VY=VR(),KY=typeof globalThis>"u"?d:globalThis,QR=T7e(),ZR=JR("String.prototype.slice"),e$=Object.getPrototypeOf,C7e=JR("Array.prototype.indexOf",!0)||function(t,r){for(var n=0;n<t.length;n+=1)if(t[n]===r)return n;return-1},iA={__proto__:null};VY&&aA&&e$?oA(QR,function(e){var t=new KY[e];if(Symbol.toStringTag in t){var r=e$(t),n=aA(r,Symbol.toStringTag);if(!n){var o=e$(r);n=aA(o,Symbol.toStringTag)}iA["$"+e]=LY(n.get)}}):oA(QR,function(e){var t=new KY[e],r=t.slice||t.set;r&&(iA["$"+e]=LY(r))});var D7e=function(t){var r=!1;return oA(iA,function(n,o){if(!r)try{"$"+n(t)===o&&(r=ZR(o,1))}catch{}}),r},I7e=function(t){var r=!1;return oA(iA,function(n,o){if(!r)try{n(t),r=ZR(o,1)}catch{}}),r},HY=function(t){if(!t||typeof t!="object")return!1;if(!VY){var r=ZR(A7e(t),8,-1);return C7e(QR,r)>-1?r:r!=="Object"?!1:I7e(t)}return aA?D7e(t):null},z7e=HY,U7e=function(t){return!!z7e(t)};(function(e){var t=r7e,r=s7e,n=HY,o=U7e;function a(te){return te.call.bind(te)}var i=typeof BigInt<"u",s=typeof Symbol<"u",c=a(Object.prototype.toString),l=a(Number.prototype.valueOf),u=a(String.prototype.valueOf),h=a(Boolean.prototype.valueOf);if(i)var p=a(BigInt.prototype.valueOf);if(s)var m=a(Symbol.prototype.valueOf);function g(te,_e){if(typeof te!="object")return!1;try{return _e(te),!0}catch{return!1}}e.isArgumentsObject=t,e.isGeneratorFunction=r,e.isTypedArray=o;function b(te){return typeof Promise<"u"&&te instanceof Promise||te!==null&&typeof te=="object"&&typeof te.then=="function"&&typeof te.catch=="function"}e.isPromise=b;function _(te){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(te):o(te)||R(te)}e.isArrayBufferView=_;function y(te){return n(te)==="Uint8Array"}e.isUint8Array=y;function x(te){return n(te)==="Uint8ClampedArray"}e.isUint8ClampedArray=x;function O(te){return n(te)==="Uint16Array"}e.isUint16Array=O;function S(te){return n(te)==="Uint32Array"}e.isUint32Array=S;function j(te){return n(te)==="Int8Array"}e.isInt8Array=j;function P(te){return n(te)==="Int16Array"}e.isInt16Array=P;function I(te){return n(te)==="Int32Array"}e.isInt32Array=I;function M(te){return n(te)==="Float32Array"}e.isFloat32Array=M;function E(te){return n(te)==="Float64Array"}e.isFloat64Array=E;function D(te){return n(te)==="BigInt64Array"}e.isBigInt64Array=D;function A(te){return n(te)==="BigUint64Array"}e.isBigUint64Array=A;function z(te){return c(te)==="[object Map]"}z.working=typeof Map<"u"&&z(new Map);function $(te){return typeof Map>"u"?!1:z.working?z(te):te instanceof Map}e.isMap=$;function L(te){return c(te)==="[object Set]"}L.working=typeof Set<"u"&&L(new Set);function B(te){return typeof Set>"u"?!1:L.working?L(te):te instanceof Set}e.isSet=B;function W(te){return c(te)==="[object WeakMap]"}W.working=typeof WeakMap<"u"&&W(new WeakMap);function K(te){return typeof WeakMap>"u"?!1:W.working?W(te):te instanceof WeakMap}e.isWeakMap=K;function Z(te){return c(te)==="[object WeakSet]"}Z.working=typeof WeakSet<"u"&&Z(new WeakSet);function re(te){return Z(te)}e.isWeakSet=re;function ue(te){return c(te)==="[object ArrayBuffer]"}ue.working=typeof ArrayBuffer<"u"&&ue(new ArrayBuffer);function ge(te){return typeof ArrayBuffer>"u"?!1:ue.working?ue(te):te instanceof ArrayBuffer}e.isArrayBuffer=ge;function H(te){return c(te)==="[object DataView]"}H.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&H(new DataView(new ArrayBuffer(1),0,1));function R(te){return typeof DataView>"u"?!1:H.working?H(te):te instanceof DataView}e.isDataView=R;var Q=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function ae(te){return c(te)==="[object SharedArrayBuffer]"}function k(te){return typeof Q>"u"?!1:(typeof ae.working>"u"&&(ae.working=ae(new Q)),ae.working?ae(te):te instanceof Q)}e.isSharedArrayBuffer=k;function N(te){return c(te)==="[object AsyncFunction]"}e.isAsyncFunction=N;function q(te){return c(te)==="[object Map Iterator]"}e.isMapIterator=q;function ie(te){return c(te)==="[object Set Iterator]"}e.isSetIterator=ie;function le(te){return c(te)==="[object Generator]"}e.isGeneratorObject=le;function U(te){return c(te)==="[object WebAssembly.Module]"}e.isWebAssemblyCompiledModule=U;function X(te){return g(te,l)}e.isNumberObject=X;function be(te){return g(te,u)}e.isStringObject=be;function xe(te){return g(te,h)}e.isBooleanObject=xe;function Ce(te){return i&&g(te,p)}e.isBigIntObject=Ce;function Te(te){return s&&g(te,m)}e.isSymbolObject=Te;function Ee(te){return X(te)||be(te)||xe(te)||Ce(te)||Te(te)}e.isBoxedPrimitive=Ee;function ne(te){return typeof Uint8Array<"u"&&(ge(te)||k(te))}e.isAnyArrayBuffer=ne,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(te){Object.defineProperty(e,te,{enumerable:!1,value:function(){throw new Error(te+" is not supported in userland")}})})})(NY);var N7e=function(t){return t&&typeof t=="object"&&typeof t.copy=="function"&&typeof t.fill=="function"&&typeof t.readUInt8=="function"};(function(e){var t=Object.getOwnPropertyDescriptors||function(R){for(var Q=Object.keys(R),ae={},k=0;k<Q.length;k++)ae[Q[k]]=Object.getOwnPropertyDescriptor(R,Q[k]);return ae},r=/%[sdj%]/g;e.format=function(H){if(!j(H)){for(var R=[],Q=0;Q<arguments.length;Q++)R.push(i(arguments[Q]));return R.join(" ")}for(var Q=1,ae=arguments,k=ae.length,N=String(H).replace(r,function(ie){if(ie==="%%")return"%";if(Q>=k)return ie;switch(ie){case"%s":return String(ae[Q++]);case"%d":return Number(ae[Q++]);case"%j":try{return JSON.stringify(ae[Q++])}catch{return"[Circular]"}default:return ie}}),q=ae[Q];Q<k;q=ae[++Q])x(q)||!E(q)?N+=" "+q:N+=" "+i(q);return N},e.deprecate=function(H,R){if(typeof st<"u"&&st.noDeprecation===!0)return H;if(typeof st>"u")return function(){return e.deprecate(H,R).apply(this,arguments)};var Q=!1;function ae(){if(!Q){if(st.throwDeprecation)throw new Error(R);st.traceDeprecation?console.trace(R):console.error(R),Q=!0}return H.apply(this,arguments)}return ae};var n={},o=/^$/;if(st.env.NODE_DEBUG){var a=st.env.NODE_DEBUG;a=a.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),o=new RegExp("^"+a+"$","i")}e.debuglog=function(H){if(H=H.toUpperCase(),!n[H])if(o.test(H)){var R=st.pid;n[H]=function(){var Q=e.format.apply(e,arguments);console.error("%s %d: %s",H,R,Q)}}else n[H]=function(){};return n[H]};function i(H,R){var Q={seen:[],stylize:c};return arguments.length>=3&&(Q.depth=arguments[2]),arguments.length>=4&&(Q.colors=arguments[3]),y(R)?Q.showHidden=R:R&&e._extend(Q,R),I(Q.showHidden)&&(Q.showHidden=!1),I(Q.depth)&&(Q.depth=2),I(Q.colors)&&(Q.colors=!1),I(Q.customInspect)&&(Q.customInspect=!0),Q.colors&&(Q.stylize=s),u(Q,H,Q.depth)}e.inspect=i,i.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},i.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function s(H,R){var Q=i.styles[R];return Q?"\x1B["+i.colors[Q][0]+"m"+H+"\x1B["+i.colors[Q][1]+"m":H}function c(H,R){return H}function l(H){var R={};return H.forEach(function(Q,ae){R[Q]=!0}),R}function u(H,R,Q){if(H.customInspect&&R&&z(R.inspect)&&R.inspect!==e.inspect&&!(R.constructor&&R.constructor.prototype===R)){var ae=R.inspect(Q,H);return j(ae)||(ae=u(H,ae,Q)),ae}var k=h(H,R);if(k)return k;var N=Object.keys(R),q=l(N);if(H.showHidden&&(N=Object.getOwnPropertyNames(R)),A(R)&&(N.indexOf("message")>=0||N.indexOf("description")>=0))return p(R);if(N.length===0){if(z(R)){var ie=R.name?": "+R.name:"";return H.stylize("[Function"+ie+"]","special")}if(M(R))return H.stylize(RegExp.prototype.toString.call(R),"regexp");if(D(R))return H.stylize(Date.prototype.toString.call(R),"date");if(A(R))return p(R)}var le="",U=!1,X=["{","}"];if(_(R)&&(U=!0,X=["[","]"]),z(R)){var be=R.name?": "+R.name:"";le=" [Function"+be+"]"}if(M(R)&&(le=" "+RegExp.prototype.toString.call(R)),D(R)&&(le=" "+Date.prototype.toUTCString.call(R)),A(R)&&(le=" "+p(R)),N.length===0&&(!U||R.length==0))return X[0]+le+X[1];if(Q<0)return M(R)?H.stylize(RegExp.prototype.toString.call(R),"regexp"):H.stylize("[Object]","special");H.seen.push(R);var xe;return U?xe=m(H,R,Q,q,N):xe=N.map(function(Ce){return g(H,R,Q,q,Ce,U)}),H.seen.pop(),b(xe,le,X)}function h(H,R){if(I(R))return H.stylize("undefined","undefined");if(j(R)){var Q="'"+JSON.stringify(R).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return H.stylize(Q,"string")}if(S(R))return H.stylize(""+R,"number");if(y(R))return H.stylize(""+R,"boolean");if(x(R))return H.stylize("null","null")}function p(H){return"["+Error.prototype.toString.call(H)+"]"}function m(H,R,Q,ae,k){for(var N=[],q=0,ie=R.length;q<ie;++q)Z(R,String(q))?N.push(g(H,R,Q,ae,String(q),!0)):N.push("");return k.forEach(function(le){le.match(/^\d+$/)||N.push(g(H,R,Q,ae,le,!0))}),N}function g(H,R,Q,ae,k,N){var q,ie,le;if(le=Object.getOwnPropertyDescriptor(R,k)||{value:R[k]},le.get?le.set?ie=H.stylize("[Getter/Setter]","special"):ie=H.stylize("[Getter]","special"):le.set&&(ie=H.stylize("[Setter]","special")),Z(ae,k)||(q="["+k+"]"),ie||(H.seen.indexOf(le.value)<0?(x(Q)?ie=u(H,le.value,null):ie=u(H,le.value,Q-1),ie.indexOf(`
230
230
  `)>-1&&(N?ie=ie.split(`
231
231
  `).map(function(U){return" "+U}).join(`