@accounter/client 0.0.8-alpha-20251023121008-8c51a83a479af2fcbc3aa02c876285dc4e21f02b → 0.0.8-alpha-20251023122652-765c7f951395441461726b3b4345eebd020632d7

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.
Files changed (92) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/dist/assets/{Checkbox-Bu7lbyW3.js → Checkbox-CpANMiXr.js} +2 -2
  3. package/dist/assets/{Progress-Cq1kNJW5.js → Progress-BEKiyNRK.js} +1 -1
  4. package/dist/assets/{Typography-qy9vYtPs.js → Typography-C0c5augK.js} +1 -1
  5. package/dist/assets/{accordion-DOoNLp8s.js → accordion-ZFVTCyDy.js} +1 -1
  6. package/dist/assets/accountant-approvals-CpzuSBgK.js +1 -0
  7. package/dist/assets/{all-charges-CkXCeGgB.js → all-charges-BTyaAlp7.js} +1 -1
  8. package/dist/assets/{arrow-up-down-DvV6Dq8U.js → arrow-up-down-PQdrJdei.js} +1 -1
  9. package/dist/assets/business-DiQFqEHI.js +42 -0
  10. package/dist/assets/{business-transactions-single-BSpUxu3D.js → business-transactions-single-DJqvqlMO.js} +1 -1
  11. package/dist/assets/{business-trip-Bv1KXZPV.js → business-trip-BXAjI1mO.js} +1 -1
  12. package/dist/assets/charges-filters-r7FjeZLc.js +1 -0
  13. package/dist/assets/{charges-ledger-validation-BcO2gYIK.js → charges-ledger-validation-CFc_zJFO.js} +1 -1
  14. package/dist/assets/{chart-Cg9PgOtK.js → chart-C5LuxRSv.js} +1 -1
  15. package/dist/assets/{data-table-pagination-aFECnXu9.js → data-table-pagination-g2cF8_uB.js} +1 -1
  16. package/dist/assets/{editable-business-trip-qxr12Yt0.js → editable-business-trip-DyQsUJjl.js} +2 -2
  17. package/dist/assets/index-2g0J28D2.js +1 -0
  18. package/dist/assets/{index-CuIQrA5k.js → index-6-J73JPC.js} +1 -1
  19. package/dist/assets/index-B5j8Fmt8.js +1 -0
  20. package/dist/assets/index-BSBV6pv2.js +9 -0
  21. package/dist/assets/{index-BFERto_M.js → index-BSg8ocop.js} +2 -2
  22. package/dist/assets/{index-B2_BlI07.js → index-Bpef3vuz.js} +2 -2
  23. package/dist/assets/index-BziuNiXZ.js +1 -0
  24. package/dist/assets/{index-BDsbL_Kg.js → index-C0OGGVXE.js} +2 -2
  25. package/dist/assets/index-C7KKktQ5.js +1 -0
  26. package/dist/assets/{index-Dh7go2PN.js → index-C99l-a0m.js} +1 -1
  27. package/dist/assets/index-CE3kLG2a.js +1 -0
  28. package/dist/assets/{index-GwuBtmZO.js → index-CJdrnxxy.js} +2 -2
  29. package/dist/assets/{index-DOrujuWI.js → index-CN2818Wt.js} +223 -233
  30. package/dist/assets/index-CjDRKTTf.js +1 -0
  31. package/dist/assets/index-CzzfC-dD.css +1 -0
  32. package/dist/assets/index-D2xdQJAx.js +1 -0
  33. package/dist/assets/index-DGvh10a7.js +1 -0
  34. package/dist/assets/index-DLI6Z9VU.js +1 -0
  35. package/dist/assets/index-DXL1qPt9.js +1 -0
  36. package/dist/assets/{index-BYyokQ1_.js → index-Is4LJW4y.js} +2 -2
  37. package/dist/assets/{index-aW2k8oov.js → index-S6eSocQH.js} +7 -7
  38. package/dist/assets/index-T-JiUNDA.js +1 -0
  39. package/dist/assets/{index-BNXVR9UW.js → index-gBZ-7Z07.js} +1 -1
  40. package/dist/assets/{index-M3bu66aM.js → index-o_W5PWRq.js} +6 -6
  41. package/dist/assets/{index.es-Bg5AVQ7i.js → index.es-DZgQ4YcV.js} +1 -1
  42. package/dist/assets/{issue-document-B4ZlDg1e.js → issue-document-D-JoFiMZ.js} +1 -1
  43. package/dist/assets/login-page-DsHy5amR.js +1 -0
  44. package/dist/assets/{missing-info-charges-Ck_n6s6i.js → missing-info-charges-CPnjfjfW.js} +1 -1
  45. package/dist/assets/page-not-found-CYmXF0n2.js +1 -0
  46. package/dist/assets/{pencil-CpRI4b2y.js → pencil-BUwX_eHK.js} +1 -1
  47. package/dist/assets/report-commentary-row-Bpvvtwpd.js +1 -0
  48. package/dist/assets/save-Ck68rh6u.js +11 -0
  49. package/dist/assets/similar-charges-by-business-modal-bUtiFfAw.js +1 -0
  50. package/dist/assets/{sub-Daf_8shG.js → sub-C2zifPY5.js} +1 -1
  51. package/dist/assets/subMonths-uUfFviD2.js +1 -0
  52. package/dist/index.html +2 -2
  53. package/package.json +1 -1
  54. package/src/components/business/business-header.tsx +2 -21
  55. package/src/components/businesses/all-businesses-row.tsx +87 -0
  56. package/src/components/businesses/cells/hebrew-name.tsx +31 -0
  57. package/src/components/businesses/cells/index.ts +2 -0
  58. package/src/components/businesses/cells/name.tsx +31 -0
  59. package/src/components/businesses/index.tsx +39 -56
  60. package/src/components/common/forms/business-card.tsx +234 -0
  61. package/src/components/common/forms/index.ts +1 -0
  62. package/src/components/common/modals/insert-business.tsx +51 -659
  63. package/src/gql/gql.ts +30 -6
  64. package/src/gql/graphql.ts +30 -7
  65. package/src/providers/urql-client.ts +2 -3
  66. package/src/providers/urql-error-handler.ts +27 -0
  67. package/src/providers/urql.tsx +5 -0
  68. package/src/router/loaders/business-loader.ts +2 -4
  69. package/src/router/loaders/charge-loader.ts +2 -4
  70. package/dist/assets/accountant-approvals-Be5zF2_c.js +0 -1
  71. package/dist/assets/building-2-B-rX_xIy.js +0 -6
  72. package/dist/assets/business-CNkwr3_Z.js +0 -32
  73. package/dist/assets/business-header-Drp6R3A0.js +0 -1
  74. package/dist/assets/charges-filters-CpNNXLPU.js +0 -1
  75. package/dist/assets/index--C4Az49P.js +0 -1
  76. package/dist/assets/index-A1xHtOLI.js +0 -1
  77. package/dist/assets/index-BrsmDzry.js +0 -1
  78. package/dist/assets/index-C3AdAlvt.js +0 -9
  79. package/dist/assets/index-CD53YLxm.js +0 -1
  80. package/dist/assets/index-CY2CmEvR.js +0 -1
  81. package/dist/assets/index-Crn32InT.js +0 -1
  82. package/dist/assets/index-CyI9xpFz.js +0 -1
  83. package/dist/assets/index-DStQk1jH.js +0 -1
  84. package/dist/assets/index-DtE5Y1ZB.css +0 -1
  85. package/dist/assets/index-DwzG6-LK.js +0 -1
  86. package/dist/assets/index-bPa4yB-5.js +0 -1
  87. package/dist/assets/index-vHwCjYSy.js +0 -1
  88. package/dist/assets/login-page-v4kHU0le.js +0 -1
  89. package/dist/assets/page-not-found-TWjTuISB.js +0 -1
  90. package/dist/assets/report-commentary-row-BNIW-6Qg.js +0 -1
  91. package/dist/assets/save-CjLvssI1.js +0 -6
  92. package/dist/assets/subMonths-DIZWyi5T.js +0 -1
@@ -8,6 +8,7 @@ import {
8
8
  } from 'urql';
9
9
  import { authExchange } from '@urql/exchange-auth';
10
10
  import { UserService } from '../services/user-service.js';
11
+ import { handleUrqlError } from './urql-error-handler.js';
11
12
 
12
13
  /**
13
14
  * Singleton URQL client for use in loaders and server-side operations
@@ -43,9 +44,7 @@ export function getUrqlClient(): Client {
43
44
  exchanges: [
44
45
  mapExchange({
45
46
  onResult(result) {
46
- if (result.error?.networkError) {
47
- console.error('Network Error:', result.error.networkError);
48
- }
47
+ handleUrqlError(result);
49
48
  },
50
49
  }),
51
50
  authExchange(async utils => {
@@ -0,0 +1,27 @@
1
+ import { toast } from 'sonner';
2
+ import type { OperationResult } from 'urql';
3
+
4
+ export function handleUrqlError(result: OperationResult) {
5
+ // Handle network errors
6
+ if (result.error?.networkError) {
7
+ console.error('Network Error:', result.error.networkError);
8
+ toast.error('Network Error', {
9
+ description: 'Failed to connect to the server. Please check your connection.',
10
+ duration: 5000,
11
+ });
12
+ return;
13
+ }
14
+
15
+ // Handle common GraphQL errors with toast notifications
16
+ if (result.error?.graphQLErrors?.length) {
17
+ const graphqlError = result.error.graphQLErrors[0];
18
+ const { message } = graphqlError;
19
+
20
+ // Show toast for common GraphQL errors
21
+ console.error('GraphQL Error:', graphqlError);
22
+ toast.error('Operation Error', {
23
+ description: message || 'An error occurred while processing your request.',
24
+ duration: 5000,
25
+ });
26
+ }
27
+ }
@@ -11,6 +11,7 @@ import {
11
11
  import { authExchange } from '@urql/exchange-auth';
12
12
  import { ROUTES } from '../router/routes.js';
13
13
  import { AuthContext } from './auth-guard.js';
14
+ import { handleUrqlError } from './urql-error-handler.js';
14
15
 
15
16
  export function UrqlProvider({ children }: { children?: ReactNode }): ReactNode {
16
17
  const { authService } = useContext(AuthContext);
@@ -47,6 +48,7 @@ export function UrqlProvider({ children }: { children?: ReactNode }): ReactNode
47
48
  exchanges: [
48
49
  mapExchange({
49
50
  onResult(result) {
51
+ // Handle authentication errors
50
52
  const isAuthError =
51
53
  result?.error?.graphQLErrors.some(e => e.extensions?.code === 'FORBIDDEN') ||
52
54
  result?.error?.response?.status === 401;
@@ -54,7 +56,10 @@ export function UrqlProvider({ children }: { children?: ReactNode }): ReactNode
54
56
  navigate(ROUTES.LOGIN, {
55
57
  state: { message: 'You are not authorized to access this page' },
56
58
  });
59
+ return;
57
60
  }
61
+
62
+ handleUrqlError(result);
58
63
  },
59
64
  }),
60
65
  authExchange(async utils => {
@@ -13,10 +13,8 @@ export async function businessLoader({ params }: LoaderFunctionArgs) {
13
13
  const client = getUrqlClient();
14
14
  const result = await client.query(BusinessScreenDocument, { businessId }).toPromise();
15
15
 
16
- if (result.error) {
17
- throw new Response('Failed to load business', { status: 500 });
18
- }
19
-
16
+ // GraphQL errors are now handled by toast notifications in urql-client
17
+ // Only throw for 404 to show the error boundary
20
18
  if (!result.data?.business) {
21
19
  throw new Response('Business not found', { status: 404 });
22
20
  }
@@ -13,10 +13,8 @@ export async function chargeLoader({ params }: LoaderFunctionArgs) {
13
13
  const client = getUrqlClient();
14
14
  const result = await client.query(ChargeScreenDocument, { chargeId }).toPromise();
15
15
 
16
- if (result.error) {
17
- throw new Response('Failed to load charge', { status: 500 });
18
- }
19
-
16
+ // GraphQL errors are now handled by toast notifications in urql-client
17
+ // Only throw for 404 to show the error boundary
20
18
  if (!result.data?.charge) {
21
19
  throw new Response('Charge not found', { status: 404 });
22
20
  }
@@ -1 +0,0 @@
1
- import{r as a,F as h,u as v,ae as C,ag as A,a as F,j as e,c as P,L as b,fq as y}from"./index-DOrujuWI.js";import{C as j}from"./charges-filters-CpNNXLPU.js";import{P as D}from"./Progress-Cq1kNJW5.js";import"./sub-Daf_8shG.js";import"./subMonths-DIZWyi5T.js";const w=()=>{const{setFiltersContext:c}=a.useContext(h),{get:i}=v(),{userContext:p}=a.useContext(C),[s,x]=a.useState(i("chargesFilters")?JSON.parse(decodeURIComponent(i("chargesFilters"))):{byOwners:p?.context.adminBusinessId?[p?.context.adminBusinessId]:[],sortBy:{field:A.Date,asc:!1},toAnyDate:null,fromAnyDate:null}),[{data:r,fetching:u}]=F({query:y,variables:{filters:s,page:1,limit:999999}}),t=r?.allCharges?.nodes.length??0;let o=0,l=0,n=0;r?.allCharges?.nodes.map(f=>{switch(f.accountantApproval){case"APPROVED":o+=1;break;case"PENDING":l+=1;break;case"UNAPPROVED":n+=1;break}});const d=100*o/t,g=100*l/t,m=100*n/t;return a.useEffect(()=>{c(e.jsx("div",{className:"flex flex-row gap-x-5",children:e.jsx(j,{filter:s,setFilter:x,activePage:1,setPage:()=>{},totalPages:1})}))},[r,u,s,c,x]),e.jsx(P,{title:"Accountant Approvals Status",children:u?e.jsx(b,{className:"h-10 w-10 animate-spin mr-2 self-center"}):e.jsxs("div",{className:"mx-10 mt-5 flex flex-col gap-5",children:[`Total charges: ${t}`,e.jsx(D,{color:"green",radius:"xl",size:"xl",sections:[{value:d,color:"green",label:`${d.toFixed(1)}% (${o})`},{value:g,color:"orange",label:`${g.toFixed(1)}% (${l})`},{value:m,color:"red",label:`${m.toFixed(1)}% (${n})`}]})]})})};export{w as AccountantApprovals};
@@ -1,6 +0,0 @@
1
- import{D as a}from"./index-DOrujuWI.js";/**
2
- * @license lucide-react v0.546.0 - ISC
3
- *
4
- * This source code is licensed under the ISC license.
5
- * See the LICENSE file in the root directory of this source tree.
6
- */const e=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],h=a("building-2",e);export{h as B};
@@ -1,32 +0,0 @@
1
- import{D as xe,G as be,S as Te,H as Ne,a as we,J as Ms,r as y,j as e,K as Pe,N as Be,O as Us,n as Cs,Q as zs,i as pe,t as O,l as je,U as qs,V as Ie,W as Oe,X as De,Y as G,Z as W,_ as K,$ as H,a0 as Ae,a1 as X,a2 as j,a3 as g,a4 as f,a5 as N,v as T,a6 as I,a7 as C,a8 as Ye,B as E,a9 as Gs,aa as Le,ab as Ze,ac as V,ad as bs,ae as es,af as Ws,s as Ks,C as Hs,ag as Xs,ah as L,ai as ds,aj as Js,ak as Qs,al as Ys,am as de,an as ss,ao as q,ap as ns,aq as ts,ar as as,as as Z,at as ue,au as re,av as ie,aw as le,ax as ce,ay as oe,az as rs,aA as is,aB as Ue,aC as ae,aD as ze,aE as qe,aF as Fe,aG as Zs,aH as ee,aI as Y,aJ as en,aK as sn,aL as nn,aM as Ge,aN as tn,aO as an,aP as rn,aQ as ln,aR as cn,aS as We,aT as Ke,aU as ws,aV as on,aW as He,aX as dn,aY as Is,aZ as Ds,a_ as un,a$ as mn,b0 as As,b1 as ls,b2 as hn,b3 as us,b4 as xn,b5 as pn,b6 as jn,b7 as gn,b8 as fn,b9 as vn,ba as yn,bb as D,bc as Nn,bd as cs,be as Cn,bf as bn,bg as wn,bh as In,bi as Dn,bj as An,bk as Q,bl as Sn,bm as kn,bn as z,bo as Tn,bp as En,bq as Pn,br as Bn}from"./index-DOrujuWI.js";import{S as os}from"./save-CjLvssI1.js";import{B as On}from"./business-header-Drp6R3A0.js";import{i as Ln,D as Vn,f as Fn,E as _n,L as _e,a as Se,C as $n,A as Rn,b as ve,c as Mn,d as Xe,h as Un,e as zn,g as Ss,u as qn,G as Gn,j as ms,k as Wn,X as ks,Y as Ts,l as Kn,m as Hn,R as Xn,n as Jn,o as Qn,p as Yn}from"./chart-Cg9PgOtK.js";import{P as Zn}from"./pencil-CpRI4b2y.js";import{A as et,a as $e,b as Re,c as hs}from"./accordion-DOoNLp8s.js";import{B as st}from"./building-2-B-rX_xIy.js";import"./sequential-CAnleQny.js";/**
2
- * @license lucide-react v0.546.0 - ISC
3
- *
4
- * This source code is licensed under the ISC license.
5
- * See the LICENSE file in the root directory of this source tree.
6
- */const nt=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],xs=xe("circle-check",nt);/**
7
- * @license lucide-react v0.546.0 - ISC
8
- *
9
- * This source code is licensed under the ISC license.
10
- * See the LICENSE file in the root directory of this source tree.
11
- */const tt=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],ke=xe("dollar-sign",tt);/**
12
- * @license lucide-react v0.546.0 - ISC
13
- *
14
- * This source code is licensed under the ISC license.
15
- * See the LICENSE file in the root directory of this source tree.
16
- */const at=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m9 15 2 2 4-4",key:"1grp1n"}]],rt=xe("file-check",at);/**
17
- * @license lucide-react v0.546.0 - ISC
18
- *
19
- * This source code is licensed under the ISC license.
20
- * See the LICENSE file in the root directory of this source tree.
21
- */const it=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]],lt=xe("plug",it);/**
22
- * @license lucide-react v0.546.0 - ISC
23
- *
24
- * This source code is licensed under the ISC license.
25
- * See the LICENSE file in the root directory of this source tree.
26
- */const ct=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],Es=xe("shield",ct);/**
27
- * @license lucide-react v0.546.0 - ISC
28
- *
29
- * This source code is licensed under the ISC license.
30
- * See the LICENSE file in the root directory of this source tree.
31
- */const ot=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Me=xe("trending-up",ot);function Ps(s){switch(s){case be.Annual:return"Annual";case be.Monthly:return"Monthly";default:throw new Error(`Unsupported Billing Cycle: ${s}`)}}function Bs(s){switch(s){case Te.Enterprise:return"Enterprise";case Te.Pro:return"Pro";default:throw new Error(`Unsupported Subscription plan: ${s}`)}}function dt(s){return Ne(s,"yyyy-MM-dd")}function ut({businessId:s,tagIds:n,description:t,open:a,onOpenChange:l,onClose:i}){const[{data:c,fetching:r},o]=we({pause:!0,query:Ms,variables:{businessId:s,tagsDifferentThan:n?n.map(m=>m.id):void 0,descriptionDifferentThan:t}});y.useEffect(()=>{a&&(n||t)&&!c&&o()},[a,n,t,o,c]);const d=y.useCallback(m=>{l(m),a&&!m&&i?.()},[l,i,a]),h=y.useMemo(()=>a&&(!!n||!!t)&&c&&c?.similarChargesByBusiness.length>0,[a,n,t,c]);return e.jsx(Pe,{open:h,onOpenChange:d,children:e.jsx(Be,{className:"overflow-scroll max-h-screen w-full sm:max-w-[640px] md:max-w-[768px] lg:max-w-[900px]",onClick:m=>m.stopPropagation(),children:e.jsx(Us,{fallback:e.jsx("div",{children:"Error fetching similar charges"}),children:r?e.jsx(Cs,{}):n||t?e.jsx(zs,{data:c?.similarChargesByBusiness??[],tagIds:n,description:t,onOpenChange:d,title:"Similar Charges by Business"}):null})})})}const mt="updateAdminBusiness",ht=()=>{const[{fetching:s},n]=pe(qs),t=y.useCallback(async a=>{const l=`Error updating admin business ID [${a.adminBusinessId}]`,i=`${mt}-${a.adminBusinessId}`;O.loading("Updating admin business",{id:i});try{const c=await n(a),r=je(c,l,i,"updateAdminBusiness");if(r)return O.success("Success",{id:i,description:"Admin Business Updated"}),r.updateAdminBusiness}catch(c){console.error(`${l}: ${c}`),O.error("Error",{id:i,description:l,duration:1e5,closeButton:!0})}},[n]);return{fetching:s,updateAdminBusiness:t}},xt=Le({employerWithholdingTaxAccountNumber:V().min(1,{message:"Employer Withholding Tax Account Number is required"}),taxPrepaymentId:V().min(1,{message:"Tax Prepayment ID is required"}),nationalInsuranceEmployerId:V().min(1,{message:"National Insurance Employer ID is required"}),advanceTaxRate:bs().min(0,{message:"Advance Tax Rate must be at least 0"}).max(100,{message:"Advance Tax Rate must be at most 100"}),registrationDate:V().min(1,{message:"Registration Date is required"})});function ps(s){return!s||s.__typename!=="LtdFinancialEntity"||!s.adminInfo?{}:{employerWithholdingTaxAccountNumber:s.adminInfo.employerWithholdingTaxAccountNumber??"",taxPrepaymentId:s.adminInfo.taxPrepaymentId??"",nationalInsuranceEmployerId:s.adminInfo.nationalInsuranceEmployerId??"",advanceTaxRate:s.adminInfo.advanceTaxRate??0,registrationDate:s.adminInfo.registrationDate??""}}function pt(s){return{employerWithholdingTaxAccountNumber:s.employerWithholdingTaxAccountNumber,taxPrepaymentId:s.taxPrepaymentId,nationalInsuranceEmployerId:s.nationalInsuranceEmployerId,advanceTaxRate:s.advanceTaxRate,registrationDate:s.registrationDate?dt(new Date(s.registrationDate)):void 0}}function jt({data:s,refetchBusiness:n}){const t=De(Gs,s),[a,l]=y.useState(ps(t)),{updateAdminBusiness:i,fetching:c}=ht(),r=Ie({resolver:Oe(xt),defaultValues:a}),o=async d=>{if(!t)return;const h=Ze(d,r.formState.dirtyFields);if(!h)return;const m=pt(h);await i({adminBusinessId:t.id,fields:m}),n?.()};return y.useEffect(()=>{if(t){const d=ps(t);l(d),r.reset(d)}},[t,r]),e.jsxs(G,{children:[e.jsxs(W,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Es,{className:"h-5 w-5 text-primary"}),e.jsx(K,{children:"Admin Business Configuration"})]}),e.jsx(H,{children:"Tax and registration information for the business operating this application"})]}),e.jsx(Ae,{...r,children:e.jsxs("form",{onSubmit:r.handleSubmit(o),className:"space-y-6",children:[e.jsx(X,{children:e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsx(j,{control:r.control,name:"employerWithholdingTaxAccountNumber",render:({field:d,fieldState:h})=>e.jsxs(g,{children:[e.jsx(f,{children:"Employer Withholding Tax Account Number"}),e.jsx(N,{children:e.jsx(T,{placeholder:"Enter account number",...d,className:I(h)})}),e.jsx(C,{})]})}),e.jsx(j,{control:r.control,name:"taxPrepaymentId",render:({field:d,fieldState:h})=>e.jsxs(g,{children:[e.jsx(f,{children:"Tax Prepayment ID"}),e.jsx(N,{children:e.jsx(T,{placeholder:"Enter prepayment ID",...d,className:I(h)})}),e.jsx(C,{})]})}),e.jsx(j,{control:r.control,name:"nationalInsuranceEmployerId",render:({field:d,fieldState:h})=>e.jsxs(g,{children:[e.jsx(f,{children:"National Insurance Employer ID"}),e.jsx(N,{children:e.jsx(T,{placeholder:"Enter employer ID",...d,className:I(h)})}),e.jsx(C,{})]})}),e.jsx(j,{control:r.control,name:"advanceTaxRate",render:({field:d,fieldState:h})=>e.jsxs(g,{children:[e.jsx(f,{children:"Advance Tax Rate (%)"}),e.jsx(N,{children:e.jsx(T,{type:"number",step:"0.01",min:"0",max:"100",placeholder:"Enter tax rate",...d,className:I(h)})}),e.jsx(C,{})]})}),e.jsx(j,{control:r.control,name:"registrationDate",render:({field:d,fieldState:h})=>e.jsxs(g,{children:[e.jsx(f,{children:"Registration Date"}),e.jsx(N,{children:e.jsx(T,{type:"date",...d,className:I(h)})}),e.jsx(C,{})]})})]})}),e.jsx(Ye,{className:"flex justify-end border-t mt-4 pt-6",children:e.jsxs(E,{type:"submit",disabled:c||Object.keys(r.formState.dirtyFields).length===0||!r.formState.isValid,children:[e.jsx(os,{className:"h-4 w-4"}),"Save Changes"]})})]})})]})}function gt({businessId:s}){const{userContext:n}=y.useContext(es),[t,a]=y.useState(1),[{data:l,fetching:i}]=we({query:Ws,variables:{filters:{byOwners:n?.context.adminBusinessId?[n.context.adminBusinessId]:void 0,sortBy:{field:Xs.Date,asc:!1},byBusinesses:[s]},page:t,limit:100}}),c=l?.allCharges?.pageInfo.totalPages??1,r=l?.allCharges?.nodes??[];return i?e.jsx("div",{children:"Loading charges..."}):e.jsxs(G,{children:[e.jsxs(W,{className:"flex w-full justify-between items-center",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx(K,{children:"Charges"}),e.jsx(H,{children:"Recurring and one-time charges for this business"})]})}),c>1&&e.jsx(Ks,{className:"flex-fit",value:t,onChange:a,total:c})]}),e.jsx(X,{children:e.jsx("div",{className:"rounded-md border",children:e.jsx(Hs,{data:r,isAllOpened:!1})})})]})}var ft=["type","layout","connectNulls","ref"],vt=["key"];function me(s){"@babel/helpers - typeof";return me=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},me(s)}function js(s,n){if(s==null)return{};var t=yt(s,n),a,l;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(l=0;l<i.length;l++)a=i[l],!(n.indexOf(a)>=0)&&Object.prototype.propertyIsEnumerable.call(s,a)&&(t[a]=s[a])}return t}function yt(s,n){if(s==null)return{};var t={};for(var a in s)if(Object.prototype.hasOwnProperty.call(s,a)){if(n.indexOf(a)>=0)continue;t[a]=s[a]}return t}function Ce(){return Ce=Object.assign?Object.assign.bind():function(s){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(s[a]=t[a])}return s},Ce.apply(this,arguments)}function gs(s,n){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(s);n&&(a=a.filter(function(l){return Object.getOwnPropertyDescriptor(s,l).enumerable})),t.push.apply(t,a)}return t}function _(s){for(var n=1;n<arguments.length;n++){var t=arguments[n]!=null?arguments[n]:{};n%2?gs(Object(t),!0).forEach(function(a){M(s,a,t[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):gs(Object(t)).forEach(function(a){Object.defineProperty(s,a,Object.getOwnPropertyDescriptor(t,a))})}return s}function te(s){return wt(s)||bt(s)||Ct(s)||Nt()}function Nt(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
32
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Ct(s,n){if(s){if(typeof s=="string")return Je(s,n);var t=Object.prototype.toString.call(s).slice(8,-1);if(t==="Object"&&s.constructor&&(t=s.constructor.name),t==="Map"||t==="Set")return Array.from(s);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return Je(s,n)}}function bt(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function wt(s){if(Array.isArray(s))return Je(s)}function Je(s,n){(n==null||n>s.length)&&(n=s.length);for(var t=0,a=new Array(n);t<n;t++)a[t]=s[t];return a}function It(s,n){if(!(s instanceof n))throw new TypeError("Cannot call a class as a function")}function fs(s,n){for(var t=0;t<n.length;t++){var a=n[t];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(s,Ls(a.key),a)}}function Dt(s,n,t){return n&&fs(s.prototype,n),t&&fs(s,t),Object.defineProperty(s,"prototype",{writable:!1}),s}function At(s,n,t){return n=Ee(n),St(s,Os()?Reflect.construct(n,t||[],Ee(s).constructor):n.apply(s,t))}function St(s,n){if(n&&(me(n)==="object"||typeof n=="function"))return n;if(n!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return kt(s)}function kt(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}function Os(){try{var s=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Os=function(){return!!s})()}function Ee(s){return Ee=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},Ee(s)}function Tt(s,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");s.prototype=Object.create(n&&n.prototype,{constructor:{value:s,writable:!0,configurable:!0}}),Object.defineProperty(s,"prototype",{writable:!1}),n&&Qe(s,n)}function Qe(s,n){return Qe=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(a,l){return a.__proto__=l,a},Qe(s,n)}function M(s,n,t){return n=Ls(n),n in s?Object.defineProperty(s,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[n]=t,s}function Ls(s){var n=Et(s,"string");return me(n)=="symbol"?n:n+""}function Et(s,n){if(me(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var a=t.call(s,n);if(me(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(s)}var he=(function(s){function n(){var t;It(this,n);for(var a=arguments.length,l=new Array(a),i=0;i<a;i++)l[i]=arguments[i];return t=At(this,n,[].concat(l)),M(t,"state",{isAnimationFinished:!0,totalLength:0}),M(t,"generateSimpleStrokeDasharray",function(c,r){return"".concat(r,"px ").concat(c-r,"px")}),M(t,"getStrokeDasharray",function(c,r,o){var d=o.reduce(function(b,k){return b+k});if(!d)return t.generateSimpleStrokeDasharray(r,c);for(var h=Math.floor(c/d),m=c%d,x=r-c,A=[],u=0,p=0;u<o.length;p+=o[u],++u)if(p+o[u]>m){A=[].concat(te(o.slice(0,u)),[m-p]);break}var S=A.length%2===0?[0,x]:[x];return[].concat(te(n.repeat(o,h)),te(A),S).map(function(b){return"".concat(b,"px")}).join(", ")}),M(t,"id",qn("recharts-line-")),M(t,"pathRef",function(c){t.mainCurve=c}),M(t,"handleAnimationEnd",function(){t.setState({isAnimationFinished:!0}),t.props.onAnimationEnd&&t.props.onAnimationEnd()}),M(t,"handleAnimationStart",function(){t.setState({isAnimationFinished:!1}),t.props.onAnimationStart&&t.props.onAnimationStart()}),t}return Tt(n,s),Dt(n,[{key:"componentDidMount",value:function(){if(this.props.isAnimationActive){var a=this.getTotalLength();this.setState({totalLength:a})}}},{key:"componentDidUpdate",value:function(){if(this.props.isAnimationActive){var a=this.getTotalLength();a!==this.state.totalLength&&this.setState({totalLength:a})}}},{key:"getTotalLength",value:function(){var a=this.mainCurve;try{return a&&a.getTotalLength&&a.getTotalLength()||0}catch{return 0}}},{key:"renderErrorBar",value:function(a,l){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var i=this.props,c=i.points,r=i.xAxis,o=i.yAxis,d=i.layout,h=i.children,m=Fn(h,_n);if(!m)return null;var x=function(p,S){return{x:p.x,y:p.y,value:p.value,errorVal:Ss(p.payload,S)}},A={clipPath:a?"url(#clipPath-".concat(l,")"):null};return L.createElement(_e,A,m.map(function(u){return L.cloneElement(u,{key:"bar-".concat(u.props.dataKey),data:c,xAxis:r,yAxis:o,layout:d,dataPointFormatter:x})}))}},{key:"renderDots",value:function(a,l,i){var c=this.props.isAnimationActive;if(c&&!this.state.isAnimationFinished)return null;var r=this.props,o=r.dot,d=r.points,h=r.dataKey,m=Se(this.props,!1),x=Se(o,!0),A=d.map(function(p,S){var b=_(_(_({key:"dot-".concat(S),r:3},m),x),{},{index:S,cx:p.x,cy:p.y,value:p.value,dataKey:h,payload:p.payload,points:d});return n.renderDotItem(o,b)}),u={clipPath:a?"url(#clipPath-".concat(l?"":"dots-").concat(i,")"):null};return L.createElement(_e,Ce({className:"recharts-line-dots",key:"dots"},u),A)}},{key:"renderCurveStatically",value:function(a,l,i,c){var r=this.props,o=r.type,d=r.layout,h=r.connectNulls;r.ref;var m=js(r,ft),x=_(_(_({},Se(m,!0)),{},{fill:"none",className:"recharts-line-curve",clipPath:l?"url(#clipPath-".concat(i,")"):null,points:a},c),{},{type:o,layout:d,connectNulls:h});return L.createElement($n,Ce({},x,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(a,l){var i=this,c=this.props,r=c.points,o=c.strokeDasharray,d=c.isAnimationActive,h=c.animationBegin,m=c.animationDuration,x=c.animationEasing,A=c.animationId,u=c.animateNewValues,p=c.width,S=c.height,b=this.state,k=b.prevPoints,F=b.totalLength;return L.createElement(Rn,{begin:h,duration:m,isActive:d,easing:x,from:{t:0},to:{t:1},key:"line-".concat(A),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(R){var $=R.t;if(k){var J=k.length/r.length,U=r.map(function(B,Ve){var ge=Math.floor(Ve*J);if(k[ge]){var fe=k[ge],ne=ve(fe.x,B.x),_s=ve(fe.y,B.y);return _(_({},B),{},{x:ne($),y:_s($)})}if(u){var $s=ve(p*2,B.x),Rs=ve(S/2,B.y);return _(_({},B),{},{x:$s($),y:Rs($)})}return _(_({},B),{},{x:B.x,y:B.y})});return i.renderCurveStatically(U,a,l)}var se=ve(0,F),v=se($),w;if(o){var P="".concat(o).split(/[,\s]+/gim).map(function(B){return parseFloat(B)});w=i.getStrokeDasharray(v,F,P)}else w=i.generateSimpleStrokeDasharray(F,v);return i.renderCurveStatically(r,a,l,{strokeDasharray:w})})}},{key:"renderCurve",value:function(a,l){var i=this.props,c=i.points,r=i.isAnimationActive,o=this.state,d=o.prevPoints,h=o.totalLength;return r&&c&&c.length&&(!d&&h>0||!Mn(d,c))?this.renderCurveWithAnimation(a,l):this.renderCurveStatically(c,a,l)}},{key:"render",value:function(){var a,l=this.props,i=l.hide,c=l.dot,r=l.points,o=l.className,d=l.xAxis,h=l.yAxis,m=l.top,x=l.left,A=l.width,u=l.height,p=l.isAnimationActive,S=l.id;if(i||!r||!r.length)return null;var b=this.state.isAnimationFinished,k=r.length===1,F=ds("recharts-line",o),R=d&&d.allowDataOverflow,$=h&&h.allowDataOverflow,J=R||$,U=Xe(S)?this.id:S,se=(a=Se(c,!1))!==null&&a!==void 0?a:{r:3,strokeWidth:2},v=se.r,w=v===void 0?3:v,P=se.strokeWidth,B=P===void 0?2:P,Ve=Un(c)?c:{},ge=Ve.clipDot,fe=ge===void 0?!0:ge,ne=w*2+B;return L.createElement(_e,{className:F},R||$?L.createElement("defs",null,L.createElement("clipPath",{id:"clipPath-".concat(U)},L.createElement("rect",{x:R?x:x-A/2,y:$?m:m-u/2,width:R?A:A*2,height:$?u:u*2})),!fe&&L.createElement("clipPath",{id:"clipPath-dots-".concat(U)},L.createElement("rect",{x:x-ne/2,y:m-ne/2,width:A+ne,height:u+ne}))):null,!k&&this.renderCurve(J,U),this.renderErrorBar(J,U),(k||c)&&this.renderDots(J,fe,U),(!p||b)&&zn.renderCallByParent(this.props,r))}}],[{key:"getDerivedStateFromProps",value:function(a,l){return a.animationId!==l.prevAnimationId?{prevAnimationId:a.animationId,curPoints:a.points,prevPoints:l.curPoints}:a.points!==l.curPoints?{curPoints:a.points}:null}},{key:"repeat",value:function(a,l){for(var i=a.length%2!==0?[].concat(te(a),[0]):a,c=[],r=0;r<l;++r)c=[].concat(te(c),te(i));return c}},{key:"renderDotItem",value:function(a,l){var i;if(L.isValidElement(a))i=L.cloneElement(a,l);else if(Ln(a))i=a(l);else{var c=l.key,r=js(l,vt),o=ds("recharts-line-dot",typeof a!="boolean"?a.className:"");i=L.createElement(Vn,Ce({key:c},r,{className:o}))}return i}}])})(y.PureComponent);M(he,"displayName","Line");M(he,"defaultProps",{xAxisId:0,yAxisId:0,connectNulls:!1,activeDot:!0,dot:!0,legendType:"line",stroke:"#3182bd",strokeWidth:1,fill:"#fff",points:[],isAnimationActive:!Gn.isSsr,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",hide:!1,label:!1});M(he,"getComposedData",function(s){var n=s.props,t=s.xAxis,a=s.yAxis,l=s.xAxisTicks,i=s.yAxisTicks,c=s.dataKey,r=s.bandSize,o=s.displayedData,d=s.offset,h=n.layout,m=o.map(function(x,A){var u=Ss(x,c);return h==="horizontal"?{x:ms({axis:t,ticks:l,bandSize:r,entry:x,index:A}),y:Xe(u)?null:a.scale(u),value:u,payload:x}:{x:Xe(u)?null:t.scale(u),y:ms({axis:a,ticks:i,bandSize:r,entry:x,index:A}),value:u,payload:x}});return _({points:m,layout:h},d)});var Pt=Wn({chartName:"LineChart",GraphicalChild:he,axisComponents:[{axisType:"xAxis",AxisComp:ks},{axisType:"yAxis",AxisComp:Ts}],formatAxisMap:Kn});const ye=[{month:"Jan",revenue:12500,expenses:8200},{month:"Feb",revenue:15800,expenses:9100},{month:"Mar",revenue:18200,expenses:10500},{month:"Apr",revenue:16900,expenses:9800},{month:"May",revenue:21300,expenses:11200},{month:"Jun",revenue:24500,expenses:12800},{month:"Jul",revenue:22800,expenses:11900},{month:"Aug",revenue:26100,expenses:13500},{month:"Sep",revenue:28900,expenses:14200},{month:"Oct",revenue:31200,expenses:15100}];function Bt(){const s=ye.reduce((t,a)=>t+a.revenue,0),n=s/ye.length;return e.jsxs(G,{children:[e.jsxs(W,{children:[e.jsx(K,{children:"Revenue Analytics"}),e.jsx(H,{children:"Revenue and expenses over time"})]}),e.jsxs(X,{children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3 mb-6",children:[e.jsxs("div",{className:"rounded-lg border p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ke,{className:"h-4 w-4"}),"Total Revenue"]}),e.jsxs("p",{className:"text-2xl font-bold",children:["$",s.toLocaleString()]}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-green-600",children:[e.jsx(Me,{className:"h-3 w-3"}),e.jsx("span",{children:"+24.5% from last period"})]})]}),e.jsxs("div",{className:"rounded-lg border p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ke,{className:"h-4 w-4"}),"Average Monthly"]}),e.jsxs("p",{className:"text-2xl font-bold",children:["$",n.toLocaleString(void 0,{maximumFractionDigits:0})]}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-green-600",children:[e.jsx(Me,{className:"h-3 w-3"}),e.jsx("span",{children:"+18.2% growth rate"})]})]}),e.jsxs("div",{className:"rounded-lg border p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ke,{className:"h-4 w-4"}),"Current Month"]}),e.jsxs("p",{className:"text-2xl font-bold",children:["$",ye[ye.length-1].revenue.toLocaleString()]}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-green-600",children:[e.jsx(Me,{className:"h-3 w-3"}),e.jsx("span",{children:"+8.0% from last month"})]})]})]}),e.jsx(Hn,{config:{revenue:{label:"Revenue",color:"hsl(var(--chart-1))"},expenses:{label:"Expenses",color:"hsl(var(--chart-2))"}},className:"h-[400px]",children:e.jsx(Xn,{width:"100%",height:"100%",children:e.jsxs(Pt,{data:ye,margin:{top:5,right:10,left:10,bottom:5},children:[e.jsx(Jn,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(ks,{dataKey:"month",className:"text-xs",tick:{fill:"hsl(var(--muted-foreground))"}}),e.jsx(Ts,{className:"text-xs",tick:{fill:"hsl(var(--muted-foreground))"}}),e.jsx(Qn,{content:e.jsx(Yn,{})}),e.jsx(he,{type:"monotone",dataKey:"revenue",stroke:"var(--color-revenue)",strokeWidth:2,dot:{fill:"var(--color-revenue)",r:4}}),e.jsx(he,{type:"monotone",dataKey:"expenses",stroke:"var(--color-expenses)",strokeWidth:2,dot:{fill:"var(--color-expenses)",r:4}})]})})})]})]})}const Ot="updateBusiness",Vs=()=>{const[{fetching:s},n]=pe(Js),t=y.useCallback(async a=>{const l=`Error updating business ID [${a.businessId}]`,i=`${Ot}-${a.businessId}`;O.loading("Updating business",{id:i});try{const c=await n(a),r=je(c,l,i,"updateBusiness");if(r)return O.success("Success",{id:i,description:"Business updated"}),r.updateBusiness}catch(c){console.error(`${l}: ${c}`),O.error("Error",{id:i,description:l,duration:1e5,closeButton:!0})}},[n]);return{fetching:s,updateBusiness:t}},Lt="insertClient",Vt=()=>{const[{fetching:s},n]=pe(Qs),t=y.useCallback(async a=>{const l=`Error creating client [${a.fields.businessId}]`,i=`${Lt}-${a.fields.businessId}`;O.loading("Creating Client...",{id:i});try{const c=await n(a),r=je(c,l,i,"insertClient");if(r)return O.success("Success",{id:i,description:`Client [${a.fields.businessId}] was created`}),r.insertClient}catch(c){console.error(`${l}: ${c}`),O.error("Error",{id:i,description:l,duration:1e5,closeButton:!0})}},[n]);return{fetching:s,insertClient:t}},Ft="updateClient",Fs=()=>{const[{fetching:s},n]=pe(Ys),t=y.useCallback(async a=>{const l=`Error updating client ID [${a.businessId}]`,i=`${Ft}-${a.businessId}`;O.loading("Updating client",{id:i});try{const c=await n(a),r=je(c,l,i,"updateClient");if(r)return O.success("Success",{id:i,description:"Client updated"}),r.updateClient}catch(c){console.error(`${l}: ${c}`),O.error("Error",{id:i,description:l,duration:1e5,closeButton:!0})}},[n]);return{fetching:s,updateClient:t}},_t=Le({id:Ue().optional(),emails:ze(qe()).optional(),generatedDocumentType:ae(Object.values(de)),greenInvoiceId:Ue().optional(),hiveId:V().optional()});function $t({client:s,businessId:n,onDone:t}){const[a,l]=y.useState(!1),[i,c]=y.useState(null),{updateClient:r}=Fs(),{insertClient:o}=Vt(),[d,h]=y.useState(""),m={id:n,generatedDocumentType:de.Proforma,emails:[]},x=Ie({resolver:Oe(_t),defaultValues:s||m});y.useEffect(()=>{s&&(c(s),x.reset({emails:s.emails,greenInvoiceId:s.greenInvoiceId,hiveId:s.hiveId,generatedDocumentType:s.generatedDocumentType,id:s.id}),l(!0))},[s,x]);const A=()=>{c(null),x.reset(m),l(!0)},u=()=>{if(d.trim()){const b=x.getValues("emails");x.setValue("emails",[...b??[],d.trim()],{shouldDirty:!0}),h("")}},p=b=>{const k=x.getValues("emails");x.setValue("emails",(k??[]).filter((F,R)=>R!==b),{shouldDirty:!0})},S=y.useCallback(async b=>{if(i)r({businessId:n,fields:b});else{if(!b.greenInvoiceId){x.setError("greenInvoiceId",{message:"Green Invoice ID is required"});return}o({fields:{...b,greenInvoiceId:b.greenInvoiceId,businessId:n}})}l(!1),c(null),t?.()},[i,t,r,n,o,x]);return e.jsxs(Pe,{open:a,onOpenChange:l,children:[e.jsx(ss,{asChild:!0,children:e.jsxs(E,{size:"sm",onClick:A,children:[e.jsx(q,{className:"h-4 w-4 mr-2"}),"New Client"]})}),e.jsxs(Be,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ns,{children:[e.jsx(ts,{children:i?"Edit Client":"Create New Client"}),e.jsx(as,{children:i?"Update client details":"Add a new client with all required details"})]}),e.jsx(Ae,{...x,children:e.jsxs("form",{onSubmit:x.handleSubmit(S),children:[e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(j,{control:x.control,name:"emails",render:({field:b})=>e.jsxs(g,{children:[e.jsx(f,{children:"Emails"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(T,{placeholder:"Add email...",value:d,onChange:k=>h(k.target.value),onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),u())}}),e.jsx(E,{type:"button",size:"sm",onClick:u,children:e.jsx(q,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:b.value?.map((k,F)=>e.jsxs(Z,{variant:"secondary",className:"gap-1",children:[k,e.jsx(E,{variant:"ghost",size:"icon",className:"p-0 size-3",onClick:()=>p(F),children:e.jsx(ue,{className:"size-3 cursor-pointer"})})]},F))}),e.jsx(C,{})]})}),e.jsx(j,{control:x.control,name:"generatedDocumentType",render:({field:b})=>e.jsxs(g,{children:[e.jsx(f,{children:"Default Document Type"}),e.jsxs(re,{onValueChange:b.onChange,defaultValue:b.value,children:[e.jsx(N,{children:e.jsx(ie,{children:e.jsx(le,{})})}),e.jsx(ce,{children:Object.values(de).map(k=>e.jsx(oe,{value:k,children:rs(k)},k))})]}),e.jsx(C,{})]})}),e.jsx(j,{control:x.control,name:"greenInvoiceId",render:({field:b})=>e.jsxs(g,{children:[e.jsx(f,{children:"Green Invoice ID"}),e.jsx(N,{children:e.jsx(T,{type:"text",placeholder:"Enter Green Invoice ID",...b,required:!i})}),e.jsx(C,{})]})}),e.jsx(j,{control:x.control,name:"hiveId",render:({field:b})=>e.jsxs(g,{children:[e.jsx(f,{children:"Hive ID"}),e.jsx(N,{children:e.jsx(T,{type:"text",placeholder:"Enter Hive ID",...b,required:!i})}),e.jsx(C,{})]})})]})}),e.jsxs(is,{children:[e.jsx(E,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(E,{type:"submit",children:i?"Update Client":"Create Client"})]})]})})]})]})}const Rt=Object.values(ln);function vs(s){return!s||s.__typename!=="LtdFinancialEntity"?{}:{isClient:!!s.clientInfo?.id,isActive:s.isActive,isReceiptEnough:s.isReceiptEnough??void 0,isDocumentsOptional:s.isDocumentsOptional??void 0,isVatOptional:s.optionalVAT??void 0,isExemptDealer:s.exemptDealer??void 0,sortCode:s.sortCode?.key?.toString()??void 0,taxCategory:s.taxCategory?.id??void 0,pcn874RecordType:s?.pcn874RecordType??void 0,irsCode:s?.irsCode??void 0,description:s.suggestions?.description??void 0,tags:s.suggestions?.tags?.map(n=>n.id)??[],phrases:s.suggestions?.phrases??[],emails:s.suggestions?.emails??[],internalLinks:s.suggestions?.emailListener?.internalEmailLinks??[],attachmentTypes:s.suggestions?.emailListener?.attachments??[],useMessageBody:s.suggestions?.emailListener?.emailBody??void 0}}function Mt(s){const t=s.internalLinks||s.useMessageBody||s.attachmentTypes?{internalEmailLinks:s.internalLinks,emailBody:s.useMessageBody,attachments:s.attachmentTypes}:void 0,l=s.description||s.tags||s.phrases||s.emails||t?{description:s.description,tags:s.tags?.map(i=>({id:i})),phrases:s.phrases,emails:s.emails,emailListener:t}:void 0;return{optionalVAT:s.isVatOptional,exemptDealer:s.isExemptDealer,sortCode:s.sortCode?parseInt(s.sortCode):void 0,taxCategory:s.taxCategory,pcn874RecordType:s.pcn874RecordType,irsCode:s.irsCode,isActive:s.isActive,isReceiptEnough:s.isReceiptEnough,isDocumentsOptional:s.isDocumentsOptional,suggestions:l}}function Ut({data:s,refetchBusiness:n}){const t=De(Zs,s),[a,l]=y.useState(vs(t)),{userContext:i}=y.useContext(es),{updateBusiness:c,fetching:r}=Vs(),[o,d]=y.useState(!1),[h,m]=y.useState(void 0),x=Ie({defaultValues:a}),A=async p=>{if(!t||!i?.context.adminBusinessId)return;const S=Ze(p,x.formState.dirtyFields);if(!S)return;const b=Mt(S);await c({businessId:t.id,ownerId:i.context.adminBusinessId,fields:b}),S.tags?.length||S.description?(m({tagIds:S.tags?.map(k=>({id:k})),description:S.description}),d(!0)):n?.()};if(y.useEffect(()=>{if(t){const p=vs(t);l(p),x.reset(p)}},[t,x]),!t)return e.jsx("div",{});const u=x.watch("isClient");return e.jsxs(G,{children:[e.jsx(W,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(K,{children:"Configurations"}),e.jsx(H,{children:"Business status, tax settings, automation rules, and integration preferences"})]}),!u&&e.jsx($t,{businessId:t.id,onDone:n})]})}),e.jsx(Ae,{...x,children:e.jsxs("form",{onSubmit:x.handleSubmit(A),children:[e.jsxs(X,{className:"space-y-6",children:[e.jsx(zt,{form:x}),e.jsx(Fe,{}),e.jsx(qt,{form:x}),e.jsx(Fe,{}),e.jsx(Gt,{form:x}),e.jsx(Fe,{}),e.jsx(Wt,{form:x})]}),e.jsx(Ye,{className:"flex justify-end border-t pt-6",children:e.jsxs(E,{type:"submit",disabled:r||Object.keys(x.formState.dirtyFields).length===0,children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Save Changes"]})})]})}),e.jsx(ut,{businessId:t.id,tagIds:h?.tagIds,description:h?.description,open:o,onOpenChange:d,onClose:n})]})}function zt({form:s}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Business Status & Behavior"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(j,{control:s.control,name:"isClient",render:({field:n,fieldState:t})=>e.jsxs(g,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(f,{children:"Is Client"}),e.jsx(ee,{children:"Mark this business as a client"})]}),e.jsx(N,{children:e.jsx(Y,{disabled:!0,checked:n.value,onCheckedChange:n.onChange,className:I(t)})})]})}),e.jsx(j,{control:s.control,name:"isActive",render:({field:n,fieldState:t})=>e.jsxs(g,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(f,{children:"Is Active"}),e.jsx(ee,{children:"Business is currently active"})]}),e.jsx(N,{children:e.jsx(Y,{checked:n.value,onCheckedChange:n.onChange,className:I(t)})})]})}),e.jsx(j,{control:s.control,name:"isReceiptEnough",render:({field:n,fieldState:t})=>e.jsxs(g,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(f,{children:"Is Receipt Enough"}),e.jsx(ee,{children:"Generate ledger for receipt documents if no invoice available"})]}),e.jsx(N,{children:e.jsx(Y,{checked:n.value,onCheckedChange:n.onChange,className:I(t)})})]})}),e.jsx(j,{control:s.control,name:"isDocumentsOptional",render:({field:n,fieldState:t})=>e.jsxs(g,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(f,{children:"No Docs Required"}),e.jsx(ee,{children:"Skip document validation for common charges"})]}),e.jsx(N,{children:e.jsx(Y,{checked:n.value,onCheckedChange:n.onChange,className:I(t)})})]})}),e.jsx(j,{control:s.control,name:"isVatOptional",render:({field:n,fieldState:t})=>e.jsxs(g,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(f,{children:"Is VAT Optional"}),e.jsx(ee,{children:"Mute missing VAT indicator"})]}),e.jsx(N,{children:e.jsx(Y,{checked:n.value,onCheckedChange:n.onChange,className:I(t)})})]})}),e.jsx(j,{control:s.control,name:"isExemptDealer",render:({field:n,fieldState:t})=>e.jsxs(g,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(f,{children:"Is Exempt Dealer"}),e.jsx(ee,{children:"Business is exempt from VAT requirements"})]}),e.jsx(N,{children:e.jsx(Y,{checked:n.value,onCheckedChange:n.onChange,className:I(t)})})]})})]})]})}function qt({form:s}){const{selectableTaxCategories:n,fetching:t}=en(),{selectableSortCodes:a,fetching:l,sortCodes:i}=sn(),{selectableTags:c,fetching:r}=nn(),o=y.useCallback(d=>{if(d){const h=i.find(m=>Number(m.key)===Number(d));h&&(h.defaultIrsCode?s.setValue("irsCode",h.defaultIrsCode,{shouldDirty:!0}):s.setValue("irsCode",null,{shouldDirty:!0}))}},[s,i]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Default Settings"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(j,{control:s.control,name:"sortCode",render:({field:d,fieldState:h})=>e.jsxs(g,{children:[e.jsx(f,{children:"Sort Code"}),e.jsx(N,{children:e.jsx(Ge,{onChange:m=>{o(m),d.onChange(m)},data:a,value:d.value,disabled:l,placeholder:"Scroll to see all options",formPart:!0,triggerProps:{className:I(h)}})}),e.jsx(C,{})]})}),e.jsx(j,{control:s.control,name:"taxCategory",render:({field:d,fieldState:h})=>e.jsxs(g,{children:[e.jsx(f,{children:"Tax Category"}),e.jsx(N,{children:e.jsx(Ge,{data:n,disabled:t,value:d.value,onChange:d.onChange,placeholder:"Scroll to see all options",formPart:!0,triggerProps:{className:I(h)}})}),e.jsx(C,{})]})}),e.jsx(j,{control:s.control,name:"pcn874RecordType",render:({field:d,fieldState:h})=>e.jsxs(g,{children:[e.jsx(f,{children:"PCN874 Record Type"}),e.jsxs(re,{onValueChange:d.onChange,value:d.value,children:[e.jsx(N,{children:e.jsx(ie,{className:I(h),children:e.jsx(le,{})})}),e.jsx(ce,{children:Object.entries(tn).map(([m,x])=>e.jsx(oe,{value:m,children:`${x} (${m})`},m))})]}),e.jsx(C,{})]})}),e.jsx(j,{control:s.control,name:"irsCode",render:({field:d,fieldState:h})=>e.jsxs(g,{children:[e.jsx(f,{children:"IRS Code"}),e.jsx(N,{children:e.jsx(an,{value:d.value??void 0,onValueChange:m=>d.onChange(m??null),hideControls:!0,decimalScale:0,className:I(h)})}),e.jsx(C,{})]})}),e.jsx(j,{control:s.control,name:"description",render:({field:d,fieldState:h})=>e.jsxs(g,{children:[e.jsx(f,{children:"Charge Description"}),e.jsx(N,{children:e.jsx(T,{placeholder:"Enter default charge description",...d,className:I(h)})}),e.jsx(C,{})]})}),e.jsx(j,{control:s.control,name:"tags",render:({field:d,fieldState:h})=>e.jsxs(g,{children:[e.jsx(f,{children:"Tags"}),e.jsx(N,{children:e.jsx(rn,{options:Object.values(c).map(({value:m,label:x})=>({label:x,value:m})),onValueChange:d.onChange,defaultValue:d.value,value:d.value,placeholder:"Select Default Tags",variant:"default",disabled:r,className:I(h)})}),e.jsx(C,{})]})})]})]})}function Gt({form:s}){const[n,t]=y.useState(""),[a,l]=y.useState(""),i=()=>{if(n.trim()){const d=s.getValues("phrases");s.setValue("phrases",[...d,n.trim()],{shouldDirty:!0}),t("")}},c=()=>{if(a.trim()){const d=s.getValues("emails");s.setValue("emails",[...d,a.trim()],{shouldDirty:!0}),l("")}},r=d=>{const h=s.getValues("phrases");s.setValue("phrases",h.filter((m,x)=>x!==d),{shouldDirty:!0})},o=d=>{const h=s.getValues("emails");s.setValue("emails",h.filter((m,x)=>x!==d),{shouldDirty:!0})};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Auto-matching Configuration"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure patterns for automatic matching of bank transactions and documents"}),e.jsx(j,{control:s.control,name:"phrases",render:({field:d,fieldState:h})=>e.jsxs(g,{children:[e.jsx(f,{children:"Phrases"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(T,{placeholder:"Add phrase...",value:n,onChange:m=>t(m.target.value),onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),i())},className:I(h)}),e.jsx(E,{type:"button",size:"sm",onClick:i,children:e.jsx(q,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:d.value?.map((m,x)=>e.jsxs(Z,{variant:"secondary",className:"gap-1",children:[m,e.jsx(E,{variant:"ghost",size:"icon",className:"p-0 size-3",onClick:()=>r(x),children:e.jsx(ue,{className:"size-3 cursor-pointer",onClick:()=>r(x)})})]},x))}),e.jsx(C,{})]})}),e.jsx(j,{control:s.control,name:"emails",render:({field:d,fieldState:h})=>e.jsxs(g,{children:[e.jsx(f,{children:"Email Addresses"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(T,{type:"email",placeholder:"Add email...",value:a,onChange:m=>l(m.target.value),onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),c())},className:I(h)}),e.jsx(E,{type:"button",size:"sm",onClick:c,children:e.jsx(q,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:d.value?.map((m,x)=>e.jsxs(Z,{variant:"secondary",className:"gap-1",children:[m,e.jsx(E,{variant:"ghost",size:"icon",className:"p-0 size-3",onClick:()=>o(x),children:e.jsx(ue,{className:"size-3 cursor-pointer"})})]},x))}),e.jsx(C,{})]})})]})}function Wt({form:s}){const[n,t]=y.useState(""),a=()=>{if(n.trim()){const c=s.getValues("internalLinks");s.setValue("internalLinks",[...c,n.trim()],{shouldDirty:!0}),t("")}},l=c=>{const r=s.getValues("attachmentTypes");s.setValue("attachmentTypes",r?.includes(c)?r.filter(o=>o!==c):[...r,c],{shouldDirty:!0})},i=c=>{const r=s.getValues("internalLinks");s.setValue("internalLinks",r.filter((o,d)=>d!==c),{shouldDirty:!0})};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Gmail Feature Configuration"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure Gmail integration settings for document processing"}),e.jsx(j,{control:s.control,name:"attachmentTypes",render:({field:c,fieldState:r})=>e.jsxs(g,{children:[e.jsx(f,{children:"Attachment Types"}),e.jsx("div",{className:I(r)+" rounded-md flex flex-wrap gap-2",children:Rt.map(o=>e.jsx(Z,{variant:c.value?.includes(o)?"default":"outline",className:"cursor-pointer",onClick:()=>l(o),children:o},o))}),e.jsx(C,{})]})}),e.jsx(j,{control:s.control,name:"internalLinks",render:({field:c,fieldState:r})=>e.jsxs(g,{children:[e.jsx(f,{children:"Internal Links"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(T,{type:"url",placeholder:"Add internal link...",value:n,onChange:o=>t(o.target.value),onKeyDown:o=>{o.key==="Enter"&&(o.preventDefault(),a())}}),e.jsx(E,{type:"button",size:"sm",onClick:a,children:e.jsx(q,{className:"h-4 w-4"})})]}),e.jsx("div",{className:I(r)+" flex flex-wrap gap-2 rounded-md",children:c.value?.map((o,d)=>e.jsxs(Z,{variant:"secondary",className:"gap-1 max-w-xs truncate",children:[o,e.jsx(E,{variant:"ghost",size:"icon",className:"p-0 size-3",onClick:()=>i(d),children:e.jsx(ue,{className:"size-3 cursor-pointer flex-shrink-0"})})]},d))}),e.jsx(C,{})]})}),e.jsx(j,{control:s.control,name:"useMessageBody",render:({field:c,fieldState:r})=>e.jsxs(g,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(f,{children:"Should Use Message Body"}),e.jsx(ee,{children:"Extract information from email message body"})]}),e.jsx(N,{children:e.jsx(Y,{checked:c.value,onCheckedChange:c.onChange,className:I(r)})})]})})]})}const Kt=Le({businessName:V().min(1,"Business name is required"),locality:V().min(1,"Locality is required"),localName:V().optional(),govId:V().optional(),address:V().optional(),localAddress:V().optional(),phone:V().optional(),website:Is("Invalid URL").optional().or(Ds("")),generalContacts:ze(qe()).optional(),billingEmails:ze(qe()).optional()});function ys(s){return!s||s.__typename!=="LtdFinancialEntity"?{}:{businessName:s.name,locality:s.country,localName:s.hebrewName??void 0,govId:s.governmentId??void 0,address:s.address??void 0,phone:s.phoneNumber??void 0,website:s.website??void 0,generalContacts:s.email?.split(",").map(n=>n.trim()),billingEmails:s.clientInfo?.emails}}function Ht(s){return{name:s.businessName,country:s.locality,hebrewName:s.localName,governmentId:s.govId,address:s.address,phoneNumber:s.phone,website:s.website,email:s.generalContacts?.join(", ")}}function Xt({data:s,refetchBusiness:n}){const t=De(dn,s),[a,l]=y.useState(ys(t)),{userContext:i}=y.useContext(es),{updateBusiness:c,fetching:r}=Vs(),o=Ie({resolver:Oe(Kt),defaultValues:a}),{countries:d,fetching:h}=cn(),[m,x]=y.useState(""),[A,u]=y.useState(""),p=o.watch("locality"),S=o.watch("address"),b=o.watch("localAddress");y.useEffect(()=>{S!==a.address&&o.setValue("address",S,{shouldDirty:!0})},[S,a.address,o]),y.useEffect(()=>{b!==a.localAddress&&o.setValue("localAddress",b,{shouldDirty:!0})},[b,a.localAddress,o]);const k=t&&"clientInfo"in t&&!!t.clientInfo,F=p===i?.context.locality,R=v=>{m.trim()&&(o.setValue("generalContacts",[...v,m.trim()],{shouldDirty:!0}),x(""))},$=(v,w)=>{o.setValue("generalContacts",v.filter((P,B)=>B!==w),{shouldDirty:!0})},J=v=>{A.trim()&&(o.setValue("billingEmails",[...v,A.trim()],{shouldDirty:!0}),u(""))},U=(v,w)=>{o.setValue("billingEmails",v.filter((P,B)=>B!==w),{shouldDirty:!0})},se=async v=>{if(!t||!i?.context.adminBusinessId)return;const w=Ze(v,o.formState.dirtyFields);if(!w)return;const P=Ht(w);await c({businessId:t.id,ownerId:i.context.adminBusinessId,fields:P}),n?.()};return y.useEffect(()=>{if(t){const v=ys(t);l(v),o.reset(v)}},[t,o]),e.jsxs(G,{children:[e.jsxs(W,{children:[e.jsx(K,{children:"Contact Information"}),e.jsx(H,{children:"Business contact details and address information"})]}),e.jsx(Ae,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(se),children:[e.jsx(X,{children:e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsx(j,{control:o.control,name:"businessName",render:({field:v,fieldState:w})=>e.jsxs(g,{children:[e.jsx(f,{children:"Business Name"}),e.jsx(N,{children:e.jsx(T,{...v,className:I(w)})}),e.jsx(C,{})]})}),e.jsx(j,{control:o.control,name:"locality",render:({field:v,fieldState:w})=>e.jsxs(g,{children:[e.jsx(f,{children:"Locality / Country"}),e.jsx(Ge,{onChange:v.onChange,data:d.map(P=>({value:P.code,label:P.name})),value:v.value,disabled:h,placeholder:"Scroll to see all options",formPart:!0,triggerProps:{className:I(w)}}),e.jsx(C,{})]})}),F&&e.jsx(j,{control:o.control,name:"localName",render:({field:v,fieldState:w})=>e.jsxs(g,{children:[e.jsx(f,{children:"Local Name"}),e.jsx(N,{children:e.jsx(T,{...v,placeholder:"Business name in local language",className:I(w)})}),e.jsx(C,{})]})}),F&&e.jsx(j,{control:o.control,name:"govId",render:({field:v,fieldState:w})=>e.jsxs(g,{children:[e.jsx(f,{children:"Government ID"}),e.jsx(N,{children:e.jsx(T,{...v,placeholder:"Enter Government ID",className:I(w)})}),e.jsx(C,{})]})}),e.jsx(j,{control:o.control,name:"address",render:({field:v,fieldState:w})=>e.jsxs(g,{className:"md:col-span-2",children:[e.jsxs(f,{className:"flex items-center gap-2",children:[e.jsx(We,{className:"h-4 w-4"}),"Address"]}),e.jsx(N,{children:e.jsx(Ke,{...v,rows:3,placeholder:"Enter business address",className:I(w)})}),e.jsx(C,{})]})}),F&&e.jsx(j,{control:o.control,name:"localAddress",render:({field:v,fieldState:w})=>e.jsxs(g,{className:"md:col-span-2",children:[e.jsxs(f,{className:"flex items-center gap-2",children:[e.jsx(We,{className:"h-4 w-4"}),"Local Address"]}),e.jsx(N,{children:e.jsx(Ke,{...v,rows:3,placeholder:"Enter address in local language",className:I(w)})}),e.jsx(C,{})]})}),e.jsx(j,{control:o.control,name:"phone",render:({field:v,fieldState:w})=>e.jsxs(g,{children:[e.jsxs(f,{className:"flex items-center gap-2",children:[e.jsx(ws,{className:"h-4 w-4"}),"Phone"]}),e.jsx(N,{children:e.jsx(T,{...v,type:"tel",placeholder:"+1 (555) 123-4567",className:I(w)})}),e.jsx(C,{})]})}),e.jsx(j,{control:o.control,name:"website",render:({field:v,fieldState:w})=>e.jsxs(g,{children:[e.jsxs(f,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4"}),"Website"]}),e.jsx(N,{children:e.jsx(T,{...v,type:"url",placeholder:"https://example.com",className:I(w)})}),e.jsx(C,{})]})}),e.jsx(j,{control:o.control,name:"generalContacts",render:({field:v,fieldState:w})=>e.jsxs(g,{className:"md:col-span-2",children:[e.jsxs(f,{className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-4 w-4"}),"General Contacts"]}),e.jsx(N,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:I(w)+" flex flex-wrap gap-2 mb-2 rounded-md",children:v.value?.map((P,B)=>e.jsxs(Z,{variant:"secondary",className:"gap-1 pr-1",children:[P,e.jsx("button",{type:"button",onClick:()=>$(v.value??[],B),className:"ml-1 hover:bg-muted rounded-sm p-0.5",children:e.jsx(ue,{className:"h-3 w-3"})})]},B))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(T,{value:m,onChange:P=>x(P.target.value),onKeyDown:P=>{P.key==="Enter"&&(P.preventDefault(),R(v.value??[]))},placeholder:"Add contact email",type:"email"}),e.jsx(E,{type:"button",variant:"outline",size:"icon",disabled:!m.trim(),onClick:()=>R(v.value??[]),children:e.jsx(q,{className:"h-4 w-4"})})]})]})}),e.jsx(C,{})]})}),k&&e.jsx(j,{control:o.control,name:"billingEmails",render:({field:v,fieldState:w})=>e.jsxs(g,{className:"md:col-span-2",children:[e.jsxs(f,{className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-4 w-4"}),"Billing Emails"]}),e.jsx(N,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:I(w)+" flex flex-wrap gap-2 mb-2 rounded-md",children:v.value?.map((P,B)=>e.jsxs(Z,{variant:"secondary",className:"gap-1 pr-1",children:[P,e.jsx("button",{type:"button",onClick:()=>U(v.value??[],B),className:"ml-1 hover:bg-muted rounded-sm p-0.5",children:e.jsx(ue,{className:"h-3 w-3"})})]},B))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(T,{value:A,onChange:P=>u(P.target.value),onKeyDown:P=>{P.key==="Enter"&&(P.preventDefault(),J(v.value??[]))},placeholder:"Add billing email",type:"email"}),e.jsx(E,{type:"button",variant:"outline",size:"icon",disabled:!A.trim(),onClick:()=>J(v.value??[]),children:e.jsx(q,{className:"h-4 w-4"})})]})]})}),e.jsx(C,{})]})})]})}),e.jsx(Ye,{className:"flex justify-end border-t mt-4 pt-6",children:e.jsxs(E,{type:"submit",disabled:r||Object.keys(o.formState.dirtyFields).length===0,children:[e.jsx(os,{className:"h-4 w-4 mr-2"}),"Save Changes"]})})]})})]})}const Jt="createContract",Qt=()=>{const[{fetching:s},n]=pe(un),t=y.useCallback(async a=>{const l=`Error creating new contract for client[${a.input.clientId}]`,i=`${Jt}-${a.input.clientId}`;O.loading("Creating contract",{id:i});try{const c=await n(a);je(c,l,i)&&O.success("Success",{id:i,description:`Contract for client ${a.input.clientId} was successfully created`})}catch(c){console.error(`${l}: ${c}`),O.error("Error",{id:i,description:l,duration:1e5,closeButton:!0})}},[n]);return{creating:s,createContract:t}},Yt="updateContract",Zt=()=>{const[{fetching:s},n]=pe(mn),t=y.useCallback(async a=>{const l=`Error updating contract ID [${a.contractId}]`,i=`${Yt}-${a.contractId}`;O.loading("Updating contract",{id:i});try{const c=await n(a),r=je(c,l,i,"updateContract");if(r)return O.success("Success",{id:i,description:"Contract updated"}),r.updateContract}catch(c){console.error(`${l}: ${c}`),O.error("Error",{id:i,description:l,duration:1e5,closeButton:!0})}},[n]);return{updating:s,updateContract:t}},ea=Le({id:Ue().optional(),startDate:us("Start date is required"),endDate:us("End date is required"),po:V().optional(),paymentAmount:bs().min(0,"Payment amount must be non-negative"),paymentCurrency:ae(Object.values(ls),"Currency is required"),productType:ae(Object.values(As)).optional(),msCloudLink:Is().optional().or(Ds("")),billingCycle:ae(Object.values(be)).optional(),subscriptionPlan:ae(Object.values(Te)).optional(),isActive:hn(),defaultRemark:V().optional(),defaultDocumentType:ae(Object.values(de))}),Ns={startDate:"",endDate:"",po:void 0,paymentAmount:0,paymentCurrency:ls.Usd,productType:As.Hive,msCloudLink:void 0,billingCycle:be.Monthly,subscriptionPlan:void 0,isActive:!0,defaultRemark:void 0,defaultDocumentType:de.Proforma};function sa({clientId:s,contract:n,onDone:t}){const[a,l]=y.useState(!1),[i,c]=y.useState(null),{updateContract:r,updating:o}=Zt(),{createContract:d,creating:h}=Qt(),m=Ie({resolver:Oe(ea),defaultValues:n||Ns});y.useEffect(()=>{n&&(c(n),m.reset({startDate:n.startDate,endDate:n.endDate,po:n.po,paymentAmount:n.paymentAmount,paymentCurrency:n.paymentCurrency,productType:n.productType,msCloudLink:n.msCloudLink,billingCycle:n.billingCycle,subscriptionPlan:n.subscriptionPlan,isActive:n.isActive,defaultRemark:n.defaultRemark,defaultDocumentType:n.defaultDocumentType}),l(!0))},[n,m]);const x=()=>{c(null),m.reset(Ns),l(!0)},A=y.useCallback(async u=>{if(i)await r({contractId:i.id,input:{amount:{raw:u.paymentAmount,currency:u.paymentCurrency},billingCycle:u.billingCycle,documentType:u.defaultDocumentType,endDate:Ne(new Date(u.endDate),"yyyy-MM-dd"),isActive:u.isActive,msCloud:u.msCloudLink,plan:u.subscriptionPlan,product:u.productType,purchaseOrder:u.po,remarks:u.defaultRemark,startDate:Ne(new Date(u.startDate),"yyyy-MM-dd")}});else{if(!u.billingCycle){m.setError("billingCycle",{message:"Billing cycle is required"});return}await d({input:{clientId:s,amount:{raw:u.paymentAmount,currency:u.paymentCurrency},billingCycle:u.billingCycle,documentType:u.defaultDocumentType,endDate:Ne(new Date(u.endDate),"yyyy-MM-dd"),isActive:u.isActive,msCloud:u.msCloudLink,plan:u.subscriptionPlan,product:u.productType,purchaseOrder:u.po,remarks:u.defaultRemark,startDate:Ne(new Date(u.startDate),"yyyy-MM-dd")}})}l(!1),c(null),t?.()},[i,t,d,r,s,m]);return e.jsxs(Pe,{open:a,onOpenChange:l,children:[e.jsx(ss,{asChild:!0,children:e.jsxs(E,{size:"sm",onClick:x,children:[e.jsx(q,{className:"h-4 w-4 mr-2"}),"New Contract"]})}),e.jsxs(Be,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ns,{children:[e.jsx(ts,{children:i?"Edit Contract":"Create New Contract"}),e.jsx(as,{children:i?"Update contract details":"Add a new contract with all required details"})]}),e.jsx(Ae,{...m,children:e.jsxs("form",{onSubmit:m.handleSubmit(A),children:[e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:e.jsx(j,{control:m.control,name:"po",render:({field:u})=>e.jsxs(g,{children:[e.jsx(f,{children:"PO Number"}),e.jsx(N,{children:e.jsx(T,{placeholder:"PO-2024-001",...u})}),e.jsx(C,{})]})})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(j,{control:m.control,name:"startDate",render:({field:{onChange:u,...p}})=>e.jsxs(g,{children:[e.jsx(f,{children:"Start Date"}),e.jsx(N,{children:e.jsx(T,{type:"date",...p,onInput:S=>u(S)})}),e.jsx(C,{})]})}),e.jsx(j,{control:m.control,name:"endDate",render:({field:{onChange:u,...p}})=>e.jsxs(g,{children:[e.jsx(f,{children:"End Date"}),e.jsx(N,{children:e.jsx(T,{type:"date",...p,onInput:S=>u(S)})}),e.jsx(C,{})]})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(j,{control:m.control,name:"paymentAmount",render:({field:u})=>e.jsxs(g,{className:"md:col-span-2",children:[e.jsx(f,{children:"Payment Amount"}),e.jsx(N,{children:e.jsx(T,{type:"number",placeholder:"24000",...u,onChange:p=>{u.onChange(p?.target.value?Number(p?.target.value):void 0)}})}),e.jsx(C,{})]})}),e.jsx(j,{control:m.control,name:"paymentCurrency",render:({field:u})=>e.jsxs(g,{children:[e.jsx(f,{children:"Currency"}),e.jsxs(re,{onValueChange:u.onChange,defaultValue:u.value,children:[e.jsx(N,{children:e.jsx(ie,{children:e.jsx(le,{})})}),e.jsx(ce,{children:Object.values(ls).map(p=>e.jsx(oe,{value:p,children:p},p))})]}),e.jsx(C,{})]})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(j,{control:m.control,name:"productType",render:({field:u})=>e.jsxs(g,{children:[e.jsx(f,{children:"Product Type"}),e.jsx(N,{children:e.jsx(T,{placeholder:"Cloud Services",...u})}),e.jsx(C,{})]})}),e.jsx(j,{control:m.control,name:"billingCycle",render:({field:u})=>e.jsxs(g,{children:[e.jsx(f,{children:"Billing Cycle"}),e.jsxs(re,{onValueChange:u.onChange,defaultValue:u.value,children:[e.jsx(N,{children:e.jsx(ie,{children:e.jsx(le,{})})}),e.jsx(ce,{children:Object.values(be).map(p=>e.jsx(oe,{value:p,children:Ps(p)},p))})]}),e.jsx(C,{})]})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(j,{control:m.control,name:"subscriptionPlan",render:({field:u})=>e.jsxs(g,{children:[e.jsx(f,{children:"Subscription Plan"}),e.jsx(N,{children:e.jsxs(re,{onValueChange:u.onChange,defaultValue:u.value,children:[e.jsx(N,{children:e.jsx(ie,{children:e.jsx(le,{})})}),e.jsx(ce,{children:Object.values(Te).map(p=>e.jsx(oe,{value:p,children:Bs(p)},p))})]})}),e.jsx(C,{})]})}),e.jsx(j,{control:m.control,name:"isActive",render:({field:u})=>e.jsxs(g,{className:"flex flex-row items-center justify-between rounded-lg border p-4",children:[e.jsx("div",{className:"space-y-0.5",children:e.jsx(f,{className:"text-base",children:"Active Status"})}),e.jsx(N,{children:e.jsx(Y,{checked:u.value,onCheckedChange:u.onChange})})]})})]}),e.jsx(j,{control:m.control,name:"msCloudLink",render:({field:u})=>e.jsxs(g,{children:[e.jsx(f,{children:"MS Cloud Link"}),e.jsx(N,{children:e.jsx(T,{type:"url",placeholder:"https://portal.azure.com/contract-id",...u})}),e.jsx(C,{})]})}),e.jsx(j,{control:m.control,name:"defaultDocumentType",render:({field:u})=>e.jsxs(g,{children:[e.jsx(f,{children:"Default Document Type"}),e.jsxs(re,{onValueChange:u.onChange,defaultValue:u.value,children:[e.jsx(N,{children:e.jsx(ie,{children:e.jsx(le,{})})}),e.jsx(ce,{children:Object.values(de).map(p=>e.jsx(oe,{value:p,children:rs(p)},p))})]}),e.jsx(C,{})]})}),e.jsx(j,{control:m.control,name:"defaultRemark",render:({field:u})=>e.jsxs(g,{children:[e.jsx(f,{children:"Default Remark"}),e.jsx(N,{children:e.jsx(Ke,{placeholder:"Enter default remark for this contract...",rows:3,...u})}),e.jsx(C,{})]})})]}),e.jsxs(is,{children:[e.jsx(E,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(E,{type:"submit",disabled:h||o,children:i?"Update Contract":"Create Contract"})]})]})})]})]})}function na(s){return{id:s.id,po:s.purchaseOrder??void 0,startDate:s.startDate,endDate:s.endDate,paymentAmount:s.amount.raw,paymentCurrency:s.amount.currency,productType:s.product??void 0,billingCycle:s.billingCycle,msCloudLink:s.msCloud?.toString(),isActive:s.isActive,subscriptionPlan:s.plan??void 0,defaultRemark:s.remarks??void 0,defaultDocumentType:s.documentType??void 0}}function ta({clientId:s}){const[n,t]=y.useState(null),[{data:a,fetching:l},i]=we({query:xn,variables:{clientId:s}}),c=a?.contractsByClient??[];return l?e.jsx("div",{children:"Loading contracts..."}):e.jsxs(G,{children:[e.jsx(W,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(K,{children:"Contracts"}),e.jsx(H,{children:"Current and past contracts sorted by start date"})]}),e.jsx(sa,{clientId:s,contract:n,onDone:i})]})}),e.jsx(X,{className:"space-y-4",children:c.map(r=>{const o=!!r.isActive;return e.jsxs("div",{className:"rounded-lg border p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-semibold",children:r.product}),e.jsx(Z,{variant:o?"default":"secondary",children:r.isActive?"Active":"Inactive"})]}),e.jsx("p",{className:"text-sm text-muted-foreground font-mono",children:r.id})]}),e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>t(na(r)),children:e.jsx(Zn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-0",children:[e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(pn,{className:"h-3 w-3"}),"Contract Period"]}),e.jsxs("p",{className:"text-sm font-medium",children:[new Date(r.startDate).toLocaleDateString()," →"," ",new Date(r.endDate).toLocaleDateString()]})]}),e.jsxs("div",{className:"space-y-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"PO Number"}),e.jsx("p",{className:"text-sm font-medium font-mono",children:r.purchaseOrder})]}),e.jsxs("div",{className:"space-y-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Payment"}),e.jsx("p",{className:"text-sm font-medium",children:jn(r.amount.raw,r.amount.currency)})]}),e.jsxs("div",{className:"space-y-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Billing Cycle"}),e.jsx("p",{className:"text-sm font-medium",children:Ps(r.billingCycle)})]}),e.jsxs("div",{className:"space-y-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscription Plan"}),e.jsx("p",{className:"text-sm font-medium",children:r.plan?Bs(r.plan):"N/A"})]}),e.jsxs("div",{className:"space-y-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Document Type"}),e.jsx("p",{className:"text-sm font-medium",children:rs(r.documentType)})]})]}),r.remarks&&e.jsxs("div",{className:"space-y-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Remark"}),e.jsx("p",{className:"text-sm",children:r.remarks})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.msCloud&&e.jsx(E,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:r.msCloud.toString(),target:"_blank",rel:"noopener noreferrer",children:[e.jsx(gn,{className:"h-4 w-4 mr-2"}),"MS Cloud",e.jsx(fn,{className:"h-3 w-3 ml-1"})]})})})]},r.id)})})]})}function aa({businessId:s}){return e.jsxs(G,{children:[e.jsx(W,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx(K,{children:"Documents"}),e.jsx(H,{children:"Invoices, proformas, receipts, and other accounting documents"})]})})}),e.jsx(X,{children:e.jsx(vn,{businessId:s,linkedDocumentIds:[],limit:1e3})})]})}const ra=[{id:"hive",name:"Hive",description:"Schema registry, analytics, metrics and gateway for GraphQL federation and other GraphQL APIs",status:"disconnected",lastSync:"Never"},{id:"slack",name:"Slack",description:"Team communication and notifications",status:"disconnected",lastSync:"Never"},{id:"retool",name:"Retool",description:"Internal tools and dashboards",status:"disconnected",lastSync:"Never"},{id:"linear",name:"Linear",description:"Issue tracking and project management",status:"disconnected",lastSync:"Never"},{id:"workflowy",name:"Workflowy",description:"Task management and note taking",status:"disconnected",lastSync:"Never"}];function ia({data:s}){const n=De(Cn,s),[{data:t,fetching:a},l]=we({query:yn,variables:{clientId:n?.id??""},pause:!n?.clientInfo?.greenInvoiceId||!n?.id}),{updateClient:i}=Fs(),c=y.useCallback((o,d)=>{if(!n?.id)return;const h={};h[d]=o,i({businessId:n?.id,fields:h})},[n?.id,i]);y.useEffect(()=>{n?.clientInfo?.greenInvoiceId&&n?.id&&l()},[n?.clientInfo?.greenInvoiceId,n?.id,l]);const r=t?.greenInvoiceClient;return e.jsxs(G,{children:[e.jsx(W,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(K,{children:"Integrations"}),e.jsx(H,{children:"Connected external services and providers"})]}),e.jsxs(E,{size:"sm",children:[e.jsx(q,{className:"h-4 w-4 mr-2"}),"Add Integration"]})]})}),e.jsx(X,{className:"space-y-6",children:e.jsxs(et,{type:"multiple",defaultValue:["green-invoice"],className:"space-y-4",children:[a?e.jsxs($e,{value:"green-invoice",className:"rounded-lg border-2 border-green-600/20 bg-green-600/5",children:[e.jsx("div",{className:"px-4 py-3 bg-green-600/10 rounded-t-lg",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx(D,{className:"h-10 w-10 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"h-6 w-32"}),e.jsx(D,{className:"h-5 w-5 rounded-full"})]}),e.jsx(D,{className:"h-4 w-64"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(D,{className:"h-8 w-24"}),e.jsx(D,{className:"h-8 w-8"})]})]})}),e.jsx(Re,{children:e.jsxs("div",{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(D,{className:"h-4 w-40"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{className:"h-3 w-24"}),e.jsx(D,{className:"h-4 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{className:"h-3 w-24"}),e.jsx(D,{className:"h-4 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{className:"h-3 w-24"}),e.jsx(D,{className:"h-4 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{className:"h-3 w-24"}),e.jsx(D,{className:"h-4 w-full"})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(D,{className:"h-4 w-40"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{className:"h-3 w-32"}),e.jsx(D,{className:"h-6 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{className:"h-3 w-24"}),e.jsx(D,{className:"h-4 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{className:"h-3 w-24"}),e.jsx(D,{className:"h-4 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{className:"h-3 w-24"}),e.jsx(D,{className:"h-4 w-full"})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(D,{className:"h-4 w-40"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(D,{className:"h-3 w-24"}),e.jsx(D,{className:"h-4 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{className:"h-3 w-24"}),e.jsx(D,{className:"h-4 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(D,{className:"h-3 w-24"}),e.jsx(D,{className:"h-4 w-full"})]})]})]})]})})]}):e.jsxs($e,{value:"green-invoice",className:"rounded-lg border-2 border-green-600/20 bg-green-600/5",children:[e.jsx("div",{className:"px-4 py-3 bg-green-600/10 rounded-t-lg",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-green-600 flex items-center justify-center text-white font-bold",children:"GI"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Green Invoice"}),e.jsx(xs,{className:"h-5 w-5 text-green-600"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Israeli invoicing system integration"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(la,{id:n?.clientInfo?.greenInvoiceId,provider:"Green Invoice",updateClient:async o=>c(o,"greenInvoiceId")}),e.jsx(hs,{className:"hover:no-underline p-2"})]})]})}),e.jsx(Re,{children:r&&e.jsxs("div",{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-semibold text-sm text-muted-foreground uppercase tracking-wide",children:"Business Information"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Integration ID"}),e.jsx("p",{className:"text-sm font-mono",children:n?.clientInfo?.greenInvoiceId})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Business Name"}),e.jsx("p",{className:"text-sm",children:r.name})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Country"}),e.jsx("p",{className:"text-sm",children:r.country})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Tax ID"}),e.jsx("p",{className:"text-sm font-mono",children:r.taxId})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-semibold text-sm text-muted-foreground uppercase tracking-wide",children:"Contact Information"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(He,{className:"h-3.5 w-3.5"}),"Email Addresses"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.emails?.map((o,d)=>e.jsx("span",{className:"text-sm px-2 py-1 bg-muted rounded",children:o},d))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(ws,{className:"h-3.5 w-3.5"}),"Phone"]}),e.jsx("p",{className:"text-sm font-mono",children:r.phone})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Mobile"}),e.jsx("p",{className:"text-sm font-mono",children:r.mobile})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Fax"}),e.jsx("p",{className:"text-sm font-mono",children:r.fax})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h4",{className:"font-semibold text-sm text-muted-foreground uppercase tracking-wide flex items-center gap-2",children:[e.jsx(We,{className:"h-3.5 w-3.5"}),"Address"]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-1 md:col-span-2",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Street Address"}),e.jsx("p",{className:"text-sm",children:r.address})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"City"}),e.jsx("p",{className:"text-sm",children:r.city})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Zip Code"}),e.jsx("p",{className:"text-sm font-mono",children:r.zip})]})]})]})]})})]}),ra.map(o=>e.jsxs($e,{value:o.id,className:"rounded-lg border",children:[e.jsx("div",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-3 flex-1",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-semibold",children:o.name}),o.status==="connected"?e.jsx(xs,{className:"h-4 w-4 text-green-600"}):e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o.description})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:d=>d.stopPropagation(),children:e.jsx(cs,{className:"h-4 w-4"})}),e.jsx(hs,{className:"hover:no-underline p-2"})]})]})}),e.jsx(Re,{children:e.jsx("div",{className:"px-4 pb-4 pt-2 border-t",children:e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Last sync: "}),e.jsx("span",{className:"font-medium",children:o.lastSync})]})})})]},o.id))]})})]})}function la({id:s,provider:n,updateClient:t}){const[a,l]=y.useState(!1),[i,c]=y.useState(s),r=y.useCallback(async()=>{await t(i),l(!1)},[i,t]);return e.jsxs(Pe,{open:a,onOpenChange:l,children:[e.jsx(ss,{asChild:!0,children:e.jsxs(E,{variant:"outline",size:"sm",onClick:o=>o.stopPropagation(),children:[e.jsx(cs,{className:"h-4 w-4 mr-2"}),"Configure"]})}),e.jsxs(Be,{onClick:o=>o.stopPropagation(),children:[e.jsxs(ns,{children:[e.jsxs(ts,{children:["Configure ",n]}),e.jsxs(as,{children:["Update your ",n," integration settings"]})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs(bn,{htmlFor:"id",children:[n," ID"]}),e.jsx(T,{id:"id",value:i,onChange:o=>c(o.target.value),placeholder:`Enter ${n} ID`})]})}),e.jsxs(is,{children:[e.jsx(E,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(E,{onClick:r,disabled:!i,children:"Save Changes"})]})]})]})}function ca({businessId:s}){return e.jsxs(G,{children:[e.jsx(W,{className:"flex w-full justify-between items-center",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx(K,{children:"Transactions"}),e.jsx(H,{children:"Complete transaction history for this business"})]})})}),e.jsx(X,{children:e.jsx("div",{className:"rounded-md border",children:e.jsx(wn,{businessID:s,filter:{}})})})]})}function oa({data:s,refetchBusiness:n}){const t=De(Tn,s),[a,l]=In(),i=a.get("tab")||"contact",c=d=>{l({tab:d})};if(!t)return e.jsx("div",{children:"Business not found"});const r="clientInfo"in t&&!!t.clientInfo,o="adminInfo"in t&&!!t.adminInfo;return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx(On,{data:t}),e.jsx("main",{className:"container mx-auto px-4 py-6 md:px-6 lg:px-8 max-w-7xl",children:e.jsxs(Dn,{value:i,onValueChange:c,className:"w-full",children:[e.jsxs(An,{className:"grid w-full lg:grid-cols-8 sm:grid-cols-4 grid-cols-8 mb-6 h-auto gap-1 bg-muted/50 p-1",children:[e.jsxs(Q,{value:"contact",className:"flex items-center gap-2 data-[state=active]:bg-background",children:[e.jsx(st,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Contact"})]}),e.jsxs(Q,{value:"config",className:"flex items-center gap-2 data-[state=active]:bg-background",children:[e.jsx(cs,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Config"})]}),e.jsxs(Q,{value:"charges",className:"flex items-center gap-2 data-[state=active]:bg-background",children:[e.jsx(ke,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Charges"})]}),e.jsxs(Q,{value:"transactions",className:"flex items-center gap-2 data-[state=active]:bg-background",children:[e.jsx(Sn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Transactions"})]}),e.jsxs(Q,{value:"documents",className:"flex items-center gap-2 data-[state=active]:bg-background",children:[e.jsx(kn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Documents"})]}),r&&e.jsxs(e.Fragment,{children:[e.jsxs(Q,{value:"contracts",className:"flex items-center gap-2 data-[state=active]:bg-background",children:[e.jsx(rt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Contracts"})]}),e.jsxs(Q,{value:"integrations",className:"flex items-center gap-2 data-[state=active]:bg-background",children:[e.jsx(lt,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Integrations"})]})]}),o&&e.jsxs(Q,{value:"admin",className:"flex items-center gap-2 data-[state=active]:bg-background",children:[e.jsx(Es,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Admin"})]})]}),e.jsx(z,{value:"contact",className:"mt-0",children:e.jsx(Xt,{data:t,refetchBusiness:n})}),e.jsx(z,{value:"config",className:"mt-0",children:e.jsx(Ut,{data:t,refetchBusiness:n})}),e.jsx(z,{value:"charges",className:"mt-0",children:e.jsx(gt,{businessId:t.id})}),e.jsx(z,{value:"transactions",className:"mt-0",children:e.jsx(ca,{businessId:t.id})}),e.jsx(z,{value:"documents",className:"mt-0",children:e.jsx(aa,{businessId:t.id})}),r&&e.jsxs(e.Fragment,{children:[e.jsx(z,{value:"contracts",className:"mt-0",children:e.jsx(ta,{clientId:t.id})}),e.jsx(z,{value:"integrations",className:"mt-0",children:e.jsx(ia,{data:t})}),e.jsx(z,{value:"charts",className:"mt-0",children:e.jsx(Bt,{})})]}),o&&e.jsx(z,{value:"admin",className:"mt-0",children:e.jsx(jt,{data:t})})]})})]})}function fa(s){return`/businesses/${s}`}const va=()=>{const{businessId:s}=En();let n;try{n=Pn()}catch{}const[{data:t,fetching:a},l]=we({query:Bn,pause:!s||!!n,variables:{businessId:s??""}}),i=n||t;return!n&&a&&!i?.business?e.jsx(Cs,{}):!s||!i?.business?e.jsx("div",{children:"Business not found"}):e.jsx(oa,{data:i.business,refetchBusiness:async()=>l()})};export{va as BusinessScreen,fa as getBusinessHref};
@@ -1 +0,0 @@
1
- import{X as l,j as e,as as t,H as m,bs as x}from"./index-DOrujuWI.js";import{B as o}from"./building-2-B-rX_xIy.js";function h({data:n}){const s=l(x,n);if(!s||s.__typename!=="LtdFinancialEntity")return e.jsx("div",{});const{isActive:i,adminInfo:r,clientInfo:a}=s,d=!!r?.id,c=!!a?.id;return e.jsx("header",{className:"sticky top-0 z-50 w-full border-b border-border bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/60",children:e.jsx("div",{className:"container mx-auto px-4 md:px-6 lg:px-8 max-w-7xl",children:e.jsxs("div",{className:"flex h-16 items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-accent",children:e.jsx(o,{className:"h-5 w-5 text-accent-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground",children:s.name}),i?e.jsx(t,{variant:"secondary",children:"Active"}):e.jsx(t,{variant:"destructive",children:"Inactive"}),d&&e.jsx(t,{variant:"outline",children:"Admin"}),c&&e.jsx(t,{variant:"outline",children:"Client"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:["Business ID: ",s.id]})]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-6 text-sm",children:[s.governmentId&&e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-muted-foreground",children:"Tax ID"}),e.jsx("p",{className:"font-medium text-foreground",children:s.governmentId})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-muted-foreground",children:"Since"}),e.jsx("p",{className:"font-medium text-foreground",children:m(s.createdAt,"MMM yyyy")})]})]})]})})})}export{h as B};
@@ -1 +0,0 @@
1
- import{cZ as B,r as i,u as H,d0 as R,j as e,c_ as U,s as W,bz as G,B as _,c$ as J,ae as q,V as K,H as N,ag as D,dh as Q,aL as X,a0 as Z,di as $,bO as h,ch as A,fr as Y,bT as O,bU as M,bP as P,ez as T,aI as x,fs as ee,bf as se,a2 as m,a3 as j,a4 as g,a5 as p,dJ as ae,dK as te,dL as ne}from"./index-DOrujuWI.js";import{s as oe}from"./sub-Daf_8shG.js";function re(a){return!a||B(a)?null:encodeURIComponent(JSON.stringify(a))}const le=[{value:D.AbsAmount,label:"Abs Amount"},{value:D.Amount,label:"Amount"},{value:D.Date,label:"Date"}],ce=[{label:"All",value:T.All},{label:"Income",value:T.Income},{label:"Expense",value:T.Expense}];function ie({filter:a,setFilter:w,closeModal:d}){const{userContext:y}=i.useContext(q),o=K({defaultValues:{byOwners:y?.context.adminBusinessId?[y.context.adminBusinessId]:void 0,sortBy:{field:D.Date,asc:!1},toAnyDate:N(new Date,"yyyy-MM-dd"),fromAnyDate:N(oe(new Date,{years:1}),"yyyy-MM-dd"),...a}}),{control:l,handleSubmit:k,watch:C}=o,[b,F]=i.useState(a.sortBy?.asc??!1),[c,u]=i.useState(!!a.sortBy?.field),{selectableFinancialEntities:S,fetching:t}=Q(),{selectableTags:v,fetching:I}=X(),E=C("sortBy.field");i.useEffect(()=>{E&&!c?u(!0):!E&&c&&u(!1)},[E,c]);const V=s=>{b!=null&&s.sortBy?.field&&(s.sortBy.asc=b),w(s),d()};function z(){w({}),F(!1),d()}return e.jsxs(e.Fragment,{children:[t?e.jsx("div",{children:"Loading..."}):e.jsx("div",{}),e.jsx(Z,{...o,children:e.jsxs("form",{onSubmit:k(V),children:[e.jsxs($,{cols:2,children:[e.jsx(h,{name:"byOwners",control:l,defaultValue:a.byOwners,render:({field:s,fieldState:n})=>e.jsx(A,{...s,data:S,value:s.value??[],disabled:t,label:"Owners",placeholder:"Scroll to see all options",maxDropdownHeight:160,searchable:!0,error:n.error?.message,withinPortal:!0})}),e.jsx(h,{name:"byBusinesses",control:l,defaultValue:a.byBusinesses,render:({field:s,fieldState:n})=>e.jsx(A,{...s,data:S,value:s.value??[],disabled:t,label:"Financial Entities",placeholder:"Scroll to see all options",maxDropdownHeight:160,searchable:!0,error:n.error?.message,withinPortal:!0})}),e.jsx(h,{name:"byTags",control:l,defaultValue:a.byTags,render:({field:s,fieldState:n})=>e.jsx(A,{...s,data:v,itemComponent:Y,value:s.value??[],disabled:I,label:"Tags",placeholder:"Scroll to see all options",maxDropdownHeight:160,searchable:!0,error:n.error?.message,withinPortal:!0,filter:(r,f,L)=>L.label?.toLowerCase().includes(r.toLowerCase().trim())||L.description?.toLowerCase().includes(r.toLowerCase().trim())})}),e.jsx(h,{name:"fromAnyDate",control:l,defaultValue:a.fromAnyDate,rules:{pattern:{value:O,message:"Date must be im format yyyy-mm-dd"}},render:({field:s,fieldState:n})=>e.jsx(M,{...s,onChange:r=>{const f=r?typeof r=="string"?r:N(r,"yyyy-MM-dd"):void 0;f!==s.value&&s.onChange(f)},value:s.value?new Date(s.value):void 0,error:n.error?.message,label:"From Date",popoverProps:{withinPortal:!0}})}),e.jsx(h,{name:"toAnyDate",control:l,defaultValue:a.toAnyDate,rules:{pattern:{value:O,message:"Date must be im format yyyy-mm-dd"}},render:({field:s,fieldState:n})=>e.jsx(M,{...s,onChange:r=>{const f=r?typeof r=="string"?r:N(r,"yyyy-MM-dd"):void 0;f!==s.value&&s.onChange(f)},value:s.value?new Date(s.value):void 0,error:n.error?.message,label:"To Date",popoverProps:{withinPortal:!0}})}),e.jsx(h,{name:"chargesType",control:l,defaultValue:a.chargesType,render:({field:s,fieldState:n})=>e.jsx(P,{...s,data:ce,value:s.value??T.All,disabled:t,label:"Charge Type",placeholder:"Filter income/expense",maxDropdownHeight:160,error:n.error?.message,withinPortal:!0})}),e.jsx(h,{name:"sortBy.field",control:l,defaultValue:a.sortBy?.field??D.Date,render:({field:s,fieldState:n})=>e.jsx(P,{...s,data:le,label:"Field to sort by",placeholder:"Scroll to see all options",maxDropdownHeight:160,searchable:!0,error:n.error?.message,rightSectionProps:{style:{width:"5rem"}},withinPortal:!0,rightSection:e.jsxs("div",{className:"flex flex-row items-center gap-1",children:[e.jsx(x,{defaultChecked:a.sortBy?.asc??!1,checked:b??!1,disabled:!c,onCheckedChange:F}),e.jsx("span",{className:"text-xs",children:b?"ASC":"DESC"})]})})}),e.jsx(h,{name:"accountantStatus",control:l,defaultValue:a.accountantStatus,render:({field:s,fieldState:n})=>e.jsx(A,{...s,value:s.value??[],data:ee,disabled:t,label:"Accountant Status",placeholder:"All",maxDropdownHeight:160,error:n.error?.message,withinPortal:!0})}),e.jsxs("div",{className:"flex flex-col gap-2 mt-4 rounded-lg border p-3 shadow-sm space-y-2",children:[e.jsx(se,{children:"Missing Information:"}),e.jsx(m,{control:o.control,name:"withoutInvoice",render:({field:s})=>e.jsxs(j,{className:"flex flex-row items-center justify-between",children:[e.jsx("div",{className:"space-y-0.5",children:e.jsx(g,{children:"Without Invoice"})}),e.jsx(p,{children:e.jsx(x,{defaultChecked:a.withoutInvoice??!1,onCheckedChange:s.onChange})})]})}),e.jsx(m,{control:o.control,name:"withoutReceipt",render:({field:s})=>e.jsxs(j,{className:"flex flex-row items-center justify-between",children:[e.jsx("div",{className:"space-y-0.5",children:e.jsx(g,{children:"Without Receipts"})}),e.jsx(p,{children:e.jsx(x,{defaultChecked:a.withoutReceipt??!1,onCheckedChange:s.onChange})})]})}),e.jsx(m,{control:o.control,name:"withoutDocuments",render:({field:s})=>e.jsxs(j,{className:"flex flex-row items-center justify-between",children:[e.jsx("div",{className:"space-y-0.5",children:e.jsx(g,{children:"Without Documents"})}),e.jsx(p,{children:e.jsx(x,{defaultChecked:a.withoutDocuments??!1,onCheckedChange:s.onChange})})]})}),e.jsx(m,{control:o.control,name:"withOpenDocuments",render:({field:s})=>e.jsxs(j,{className:"flex flex-row items-center justify-between",children:[e.jsx("div",{className:"space-y-0.5",children:e.jsx(g,{children:"With Open Documents"})}),e.jsx(p,{children:e.jsxs(ae,{children:[e.jsx(te,{children:e.jsx(x,{defaultChecked:a.withOpenDocuments??!1,onCheckedChange:s.onChange})}),e.jsx(ne,{children:e.jsx("p",{children:"Show only charges with documents that are currently open"})})]})})]})}),e.jsx(m,{control:o.control,name:"withoutTransactions",render:({field:s})=>e.jsxs(j,{className:"flex flex-row items-center justify-between",children:[e.jsx("div",{className:"space-y-0.5",children:e.jsx(g,{children:"Without Transactions"})}),e.jsx(p,{children:e.jsx(x,{defaultChecked:a.withoutTransactions??!1,onCheckedChange:s.onChange})})]})}),e.jsx(m,{control:o.control,name:"unbalanced",render:({field:s})=>e.jsxs(j,{className:"flex flex-row items-center justify-between",children:[e.jsx("div",{className:"space-y-0.5",children:e.jsx(g,{children:"Unbalanced businesses"})}),e.jsx(p,{children:e.jsx(x,{defaultChecked:a.unbalanced??!1,onCheckedChange:s.onChange})})]})}),e.jsx(m,{control:o.control,name:"withoutLedger",render:({field:s})=>e.jsxs(j,{className:"flex flex-row items-center justify-between",children:[e.jsx("div",{className:"space-y-0.5",children:e.jsx(g,{children:"Without ledger"})}),e.jsx(p,{children:e.jsx(x,{defaultChecked:a.withoutLedger??!1,onCheckedChange:s.onChange})})]})})]})]}),e.jsxs("div",{className:"flex justify-center mt-5 gap-3",children:[e.jsx("button",{type:"submit",disabled:t||I,className:"text-white bg-indigo-500 border-0 py-2 px-8 focus:outline-hidden hover:bg-indigo-600 rounded-sm text-lg",children:"Filter"}),e.jsx("button",{type:"button",className:"text-white bg-orange-500 border-0 py-2 px-8 focus:outline-hidden hover:bg-orange-600 rounded-sm text-lg",onClick:z,children:"Clear"}),e.jsx("button",{type:"button",className:"text-white bg-rose-500 border-0 py-2 px-8 focus:outline-hidden hover:bg-rose-600 rounded-sm text-lg",onClick:d,children:"Cancel"})]})]})})]})}function he({filter:a={},setFilter:w,activePage:d,setPage:y,totalPages:o=1,initiallyOpened:l=!1}){const[k,C]=i.useState(l),[b,F]=i.useState(!B(a)),{get:c,set:u}=H();i.useEffect(()=>{const t=d>1?d.toFixed(0):null,v=c("page");t!==v&&u("page",t)},[d,c,u]),i.useEffect(()=>{const t=re(a),v=c("chargesFilters");t!==v&&(u("chargesFilters",t),u("page"),y(1))},[a,c,u,y]);const S=i.useCallback(t=>{R(t,a)||(w(t),F(!B(t)))},[a,w]);return e.jsxs("div",{className:"flex flex-row gap-5 items-center",children:[e.jsx(U,{opened:k,onClose:()=>C(!1),content:e.jsx(ie,{filter:a,setFilter:S,closeModal:()=>C(!1)}),modalSize:"xl"}),o>1&&e.jsx(W,{className:"flex-auto",value:d,onChange:y,total:o}),e.jsx(G,{inline:!0,size:16,disabled:!b,children:e.jsx(_,{variant:"outline",size:"icon",className:"size-7.5",onClick:()=>C(!0),children:e.jsx(J,{className:"size-5"})})})]})}export{he as C,ce as c,re as e};
@@ -1 +0,0 @@
1
- import{r as h,j as e,c_ as u,eK as p,B as y,c$ as g,bp as D,F as P,a as w,c as R,L as E,ca as v,eL as F}from"./index-DOrujuWI.js";import{d as C}from"./graphql-document-dedupe-fragments-ByT8-wlV.js";import{R as d}from"./report-commentary-row-BNIW-6Qg.js";function A({year:l,setYear:m,referenceYears:o,setReferenceYears:j}){const[c,x]=h.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsx(u,{opened:c,onClose:()=>x(!1),withCloseButton:!0,content:e.jsxs(e.Fragment,{children:[e.jsx(p,{label:"Change report year",value:new Date(l,0,1),onChange:n=>n&&m(n?.getFullYear()),popoverProps:{withinPortal:!0},minDate:new Date(2010,0,1),maxDate:new Date}),e.jsx(p,{type:"multiple",label:"Pick reference years",value:o?.map(n=>new Date(n,0,1)),onChange:n=>j(n.map(i=>i.getFullYear()).filter(i=>l!==i)),popoverProps:{withinPortal:!0},minDate:new Date(2010,0,1),maxDate:new Date})]})}),e.jsx(y,{variant:"outline",size:"icon",className:"size-7.5",onClick:()=>x(!0),children:e.jsx(g,{className:"size-5"})})]})}const b=()=>{const{year:l}=D(),{setFiltersContext:m}=h.useContext(P),[o,j]=h.useState(l?Number(l):new Date().getFullYear()),[c,x]=h.useState([]),[{data:n,fetching:i}]=w({query:C(F),variables:{reportYear:o,referenceYears:c}});h.useEffect(()=>{m(e.jsx("div",{className:"flex flex-row gap-2",children:e.jsx(A,{year:o,setYear:j,referenceYears:c,setReferenceYears:x})}))},[o,i,m,c,x]);const f=n?.profitAndLossReport,a=f?.report,s=f?.reference??[];return e.jsx(R,{title:"Profit and Loss Report",children:i?e.jsx(E,{className:"h-10 w-10 animate-spin mr-2 self-center"}):e.jsx("div",{className:"flex flex-col gap-4",children:a&&e.jsxs(v,{highlightOnHover:!0,fontSize:"md",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{}),e.jsx("th",{children:o},o),e.jsx("th",{}),s.map(t=>e.jsx("th",{children:t.year},t.year))]})}),e.jsxs("tbody",{children:[e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("th",{children:"Revenue"}),e.jsx("th",{children:a.revenue.amount.formatted}),e.jsx("th",{children:t}),s.map(r=>e.jsx("th",{children:r.revenue.amount.formatted},r.year))]}),commentaryData:a.revenue}),e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("td",{children:"Cost of Sales"}),e.jsx("td",{children:a.costOfSales.amount.formatted}),e.jsx("th",{children:t}),s.map(r=>e.jsx("td",{children:r.costOfSales.amount.formatted},r.year))]}),commentaryData:a.costOfSales}),e.jsxs("tr",{children:[e.jsx("th",{children:"Gross Profit"}),e.jsx("th",{children:a.grossProfit.formatted}),e.jsx("th",{}),s.map(t=>e.jsx("th",{children:t.grossProfit.formatted},t.year))]}),e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("td",{children:"R&D Expenses"}),e.jsx("td",{children:a.researchAndDevelopmentExpenses.amount.formatted}),e.jsx("th",{children:t}),s.map(r=>e.jsx("td",{children:r.researchAndDevelopmentExpenses.amount.formatted},r.year))]}),commentaryData:a.researchAndDevelopmentExpenses}),e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("td",{children:"Marketing Expenses"}),e.jsx("td",{children:a.marketingExpenses.amount.formatted}),e.jsx("th",{children:t}),s.map(r=>e.jsx("td",{children:r.marketingExpenses.amount.formatted},r.year))]}),commentaryData:a.marketingExpenses}),e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("td",{children:"Management and General Expenses"}),e.jsx("td",{children:a.managementAndGeneralExpenses.amount.formatted}),e.jsx("th",{children:t}),s.map(r=>e.jsx("td",{children:r.managementAndGeneralExpenses.amount.formatted},r.year))]}),commentaryData:a.managementAndGeneralExpenses}),e.jsxs("tr",{children:[e.jsx("th",{children:"Operating Profit"}),e.jsx("th",{children:a.operatingProfit.formatted}),e.jsx("th",{}),s.map(t=>e.jsx("th",{children:t.operatingProfit.formatted},t.year))]}),e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("td",{children:"Financial Expenses"}),e.jsx("td",{children:a.financialExpenses.amount.formatted}),e.jsx("th",{children:t}),s.map(r=>e.jsx("td",{children:r.financialExpenses.amount.formatted},r.year))]}),commentaryData:a.financialExpenses}),e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("td",{children:"Other Income"}),e.jsx("td",{children:a.otherIncome.amount.formatted}),e.jsx("th",{children:t}),s.map(r=>e.jsx("td",{children:r.otherIncome.amount.formatted},r.year))]}),commentaryData:a.otherIncome}),e.jsxs("tr",{children:[e.jsx("th",{children:"Profit Before Tax"}),e.jsx("th",{children:a.profitBeforeTax.formatted}),e.jsx("th",{}),s.map(t=>e.jsx("th",{children:t.profitBeforeTax.formatted},t.year))]}),e.jsxs("tr",{children:[e.jsx("td",{children:"Tax"}),e.jsx("td",{children:a.tax.formatted}),e.jsx("td",{}),s.map(t=>e.jsx("td",{children:t.tax.formatted},t.year))]})]}),e.jsx("tfoot",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Net Profit"}),e.jsx("th",{children:a.netProfit.formatted}),e.jsx("th",{}),s.map(t=>e.jsx("th",{children:t.netProfit.formatted},t.year))]})})]})})})};export{b as ProfitAndLossReport};
@@ -1 +0,0 @@
1
- import{i as v,fX as U,r as u,t as m,l as F,aK as H,j as e,a2 as C,a3 as j,a4 as f,a5 as p,v as L,a6 as y,a7 as S,bO as K,bP as V,aO as z,aI as _,K as D,an as E,B as h,N as M,ap as A,aq as R,V as O,a0 as k,fY as G,c7 as Q,a as P,fZ as X,L as $,F as Y,dj as Z,c as J,dm as W,dn as ee,dp as T,dq as se,dr as b,ds as te,dt as w,f_ as ae,dz as re,dA as oe,dB as ne}from"./index-DOrujuWI.js";import{D as ie}from"./data-table-pagination-aFECnXu9.js";import{A as N}from"./arrow-up-down-DvV6Dq8U.js";const de="insertTaxCategory",ce=()=>{const[{fetching:s},n]=v(U),t=u.useCallback(async a=>{const d="Error creating tax category",r=de;m.loading("Adding Tax Category",{id:r});try{const i=await n(a),l=F(i,d,r);if(l)return m.success("Success",{id:r,description:`${l.insertTaxCategory.name} was created`}),l.insertTaxCategory}catch(i){console.error(`${d}: ${i}`),m.error("Error",{id:r,description:d,duration:1e5,closeButton:!0})}},[n]);return{fetching:s,insertTaxCategory:t}};function q({formManager:s,setFetching:n,isInsert:t}){const{control:a,watch:d,setValue:r}=s,{selectableSortCodes:i,fetching:l,sortCodes:x}=H();u.useEffect(()=>{n(l)},[n,l]);const c=d("sortCode");return u.useEffect(()=>{if(c){const o=x.find(g=>g.key===c);o?.defaultIrsCode&&r("irsCode",o.defaultIrsCode,{shouldDirty:!0})}},[c,x,r]),e.jsxs(e.Fragment,{children:[e.jsx(C,{name:"name",control:a,rules:{required:"Required",minLength:{value:2,message:"Must be at least 2 characters"}},render:({field:o,fieldState:g})=>e.jsxs(j,{children:[e.jsx(f,{children:"Name"}),e.jsx(p,{children:e.jsx(L,{...o,value:o.value??void 0,required:!0,className:t?"":y(g)})}),e.jsx(S,{})]})}),e.jsx(K,{name:"sortCode",control:a,render:({field:o,fieldState:g})=>e.jsx(V,{...o,onChange:B=>{o.onChange(Number(B))},data:i,value:o.value?.toString(),disabled:l,label:"Sort Code",placeholder:"Scroll to see all options",maxDropdownHeight:160,searchable:!0,className:t?"":y(g)})}),e.jsx(C,{name:"irsCode",control:a,render:({field:o,fieldState:g})=>e.jsxs(j,{children:[e.jsx(f,{children:"IRS Code"}),e.jsx(p,{children:e.jsx(z,{...o,className:t?"":y(g),value:o.value??void 0,hideControls:!0,decimalScale:0})}),e.jsx(S,{})]})}),e.jsx(C,{control:a,name:"taxExcluded",render:({field:o})=>e.jsxs(j,{className:"flex flex-row items-center justify-between",children:[e.jsx("div",{className:"space-y-0.5",children:e.jsx(f,{children:"Tax excluded category"})}),e.jsx(p,{children:e.jsx(_,{onCheckedChange:o.onChange,checked:o.value??void 0})})]})})]})}function le({onAdd:s}){const[n,t]=u.useState(!1);return e.jsxs(D,{open:n,onOpenChange:t,children:[e.jsx(E,{asChild:!0,children:e.jsx(h,{children:"Add Tax Category"})}),e.jsxs(M,{className:"w-[90vw] max-w-screen-md",children:[e.jsx(A,{children:e.jsx(R,{children:"Add New Tax Category"})}),e.jsx(xe,{close:()=>t(!1),onAdd:s})]})]})}function xe({close:s,onAdd:n}){const t=O({}),{handleSubmit:a}=t,[d,r]=u.useState(!1),{insertTaxCategory:i,fetching:l}=ce(),x=c=>{c.sortCode&&=parseInt(c.sortCode.toString()),i({fields:c}).then(o=>{o?.id&&(n?.(o.id),s())})};return e.jsx(k,{...t,children:e.jsxs("form",{onSubmit:a(x),children:[e.jsx("div",{className:"flex flex-col gap-4 my-4",children:e.jsx(q,{isInsert:!0,formManager:t,setFetching:r})}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsx(h,{type:"submit",disabled:l||d,children:"Add Tax Category"})})]})})}const ue="updateTaxCategory",ge=()=>{const[{fetching:s},n]=v(G),t=u.useCallback(async a=>{const d="Error updating tax category",r=`${ue}-${a.taxCategoryId}`;m.loading("Uploading Tax Category",{id:r});try{const i=await n(a),l=F(i,d,r,"updateTaxCategory");if(l)return m.success("Success",{id:r,description:`${l.updateTaxCategory.name} was updated`}),l.updateTaxCategory}catch(i){console.error(`${d}: ${i}`),m.error("Error",{id:r,description:d,duration:1e5,closeButton:!0})}},[n]);return{fetching:s,updateTaxCategory:t}};function me({taxCategoryId:s,onAdd:n}){const[t,a]=u.useState(!1);return e.jsxs(D,{open:t,onOpenChange:a,children:[e.jsx(E,{asChild:!0,children:e.jsx(h,{variant:"outline",size:"icon",children:e.jsx(Q,{})})}),e.jsxs(M,{className:"w-[400px] max-w-screen-md",children:[e.jsx(A,{children:e.jsx(R,{children:"Edit Tax Category"})}),e.jsx(he,{taxCategoryId:s,close:()=>a(!1),onAdd:n})]})]})}function he({taxCategoryId:s,close:n,onAdd:t}){const[{data:a,fetching:d}]=P({query:X,variables:{id:s}}),r=a?.taxCategory;return!r&&!d&&m.error("Error",{description:"Couldn'nt find tax category"}),d?e.jsx($,{className:"h-10 w-10 animate-spin"}):e.jsx(Ce,{taxCategory:r,close:n,onAdd:t})}function Ce({taxCategory:s,close:n,onAdd:t}){const a=O({defaultValues:{sortCode:s.sortCode?.key,name:s.name,irsCode:s.irsCode}}),{handleSubmit:d}=a,[r,i]=u.useState(!1),{updateTaxCategory:l,fetching:x}=ge(),c=o=>{o.sortCode&&=parseInt(o.sortCode.toString()),l({fields:o,taxCategoryId:s.id}).then(g=>{g?.id&&(t?.(g.id),n())})};return e.jsx(k,{...a,children:e.jsxs("form",{onSubmit:d(c),children:[e.jsx("div",{className:"flex flex-col gap-4 my-4",children:e.jsx(q,{isInsert:!1,formManager:a,setFetching:i})}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsx(h,{type:"submit",disabled:x||r,children:"Update"})})]})})}const je=({data:s})=>e.jsx("td",{children:s.name}),fe=({data:s})=>e.jsx("td",{children:s.sortCode?e.jsxs("span",{children:[s.sortCode?.name," (",s.sortCode?.id,")"]}):"N/A"}),I=[{id:"name",accessorKey:"name",cell:({row:s})=>e.jsx(je,{data:s.original}),header:({column:s})=>e.jsxs(h,{variant:"ghost",onClick:()=>s.toggleSorting(s.getIsSorted()==="asc"),children:["Name",e.jsx(N,{})]})},{id:"sortCode",accessorKey:"sortCode.key",cell:({row:s})=>e.jsx(fe,{data:s.original}),header:({column:s})=>e.jsxs(h,{variant:"ghost",onClick:()=>s.toggleSorting(s.getIsSorted()==="asc"),children:["Sort Code",e.jsx(N,{})]})},{id:"edit",cell:({row:s})=>e.jsx(me,{taxCategoryId:s.original.id})}],Se=()=>{const[{data:s,fetching:n,error:t},a]=P({query:ae}),{setFiltersContext:d}=u.useContext(Y),r=s?.taxCategories??[],i=Z({data:r,columns:I,getCoreRowModel:ne(),getPaginationRowModel:oe(),getSortedRowModel:re(),initialState:{pagination:{pageSize:30}}}),l=i.getPageOptions();return u.useEffect(()=>{d(e.jsx("div",{className:"flex items-center justify-end gap-10 space-x-2 py-4",children:e.jsx("div",{className:"flex items-center justify-between px-2",children:e.jsx(ie,{table:i})})}))},[d,i,l]),u.useEffect(()=>{t&&m.error("Error",{description:"Error fetching tax categories"})},[t]),e.jsx(J,{title:`Tax Categories (${r.length})`,description:"All tax categories",headerActions:e.jsx(le,{onAdd:()=>a()}),children:n?e.jsx("div",{className:"flex flex-row justify-center",children:e.jsx($,{className:"h-10 w-10 animate-spin mr-2"})}):e.jsx("div",{className:"flex flex-col gap-4 rounded-md border",children:e.jsxs(W,{children:[e.jsx(ee,{children:i.getHeaderGroups().map(x=>e.jsx(T,{children:x.headers.map(c=>e.jsx(se,{children:c.isPlaceholder?null:b(c.column.columnDef.header,c.getContext())},c.id))},x.id))}),e.jsx(te,{children:i.getRowModel().rows.length===0?e.jsx(T,{children:e.jsx(w,{colSpan:I.length,className:"text-center py-8",children:"No tax categories found"})}):i.getRowModel().rows.map(x=>e.jsx(T,{children:x.getVisibleCells().map(c=>e.jsx(w,{children:b(c.column.columnDef.cell,c.getContext())},c.id))},x.id))})]})})})};export{Se as TaxCategories};
@@ -1 +0,0 @@
1
- import{a as M,dD as K,t as C,r as s,i as Q,l as X,dE as Y,dF as _,X as S,dG as E,j as e,K as R,an as q,B as v,ao as J,N as G,ap as U,aq as Z,au as W,av as ee,aw as se,ax as te,ay as ne,dH as ae,dI as re,dJ as H,dK as V,c7 as ce,dL as z,dM as ie,Y as k,a1 as B,L as A,dN as le,g as oe,Z as de,_ as ue,dO as me,bm as he,b9 as xe,dP as je,H as P,dQ as L,V as pe,bM as fe,G as ge,a0 as ye,bf as ve,db as De,dm as be,dn as Ce,dp as O,dq as g,ds as Ne,dt as y,at as we,c1 as Ie,F as Me,n as Te}from"./index-DOrujuWI.js";import{s as $}from"./subMonths-DIZWyi5T.js";const Fe=()=>{const[{data:u,fetching:o,error:c},x]=M({query:K});c&&(console.error(`Error fetching contracts: ${c}`),C.error("Error",{description:"Unable to fetch contracts"}));const a=s.useMemo(()=>u?.allOpenContracts?.slice().sort((t,d)=>t.client.originalBusiness.name>d.client.originalBusiness.name?1:-1)??[],[u]),i=s.useMemo(()=>a.map(t=>({value:t.id,label:t.client.originalBusiness.name})),[a]);return{fetching:o,refresh:()=>x(),openContracts:a,selectableOpenContracts:i}},Se="IssueMonthlyDocuments",Ee=()=>{const[{fetching:u},o]=Q(Y),c=s.useCallback(async x=>{const a="Error issuing monthly documents",i=Se;C.loading("Issuing documents",{id:i});try{const t=await o(x),d=X(t,a,i);if(d?.issueGreenInvoiceDocuments?.success){C.success("Success",{id:i,description:"Documents issued successfully"});return}d?.issueGreenInvoiceDocuments?.errors&&console.error(d.issueGreenInvoiceDocuments.errors),C.error("Error",{id:i,description:a,duration:1e5,closeButton:!0})}catch(t){console.error(`${a}: ${t}`),C.error("Error",{id:i,description:a,duration:1e5,closeButton:!0})}},[o]);return{fetching:u,issueDocuments:c}};function Pe({issueMonth:u,contracts:o,onAdd:c}){const[x,a]=s.useState(!1),[i,t]=s.useState(""),[{data:d},h]=M({query:_,variables:{issueMonth:u,clientId:i}}),j=s.useCallback(n=>{t(n),h()},[h,t]);return s.useEffect(()=>{i!==""&&d&&(c(S(E,d.clientMonthlyChargeDraft)),a(!1))},[i,d,c]),e.jsxs(R,{open:x,onOpenChange:a,children:[e.jsx(q,{asChild:!0,children:e.jsx(v,{variant:"outline",size:"icon",children:e.jsx(J,{})})}),e.jsxs(G,{className:"w-[400px] max-w-screen-md",children:[e.jsx(U,{children:e.jsx(Z,{children:"Select document recipient"})}),e.jsxs(W,{onValueChange:j,children:[e.jsx(ee,{children:e.jsx(se,{placeholder:"Recipient"})}),e.jsx(te,{children:o.map(n=>e.jsx(ne,{value:n.client.originalBusiness.id,children:n.client.originalBusiness.name},n.client.originalBusiness.id))})]})]})]})}function ke({onApprove:u,draft:o}){const[c,x]=s.useState(!1),[a,i]=s.useState(!1),[t,d]=s.useState(null),{previewDocument:h,fetching:j}=ae(),[n,N]=s.useState(re(o)),T=s.useCallback((l,p)=>{N(f=>({...f,[l]:p}))},[]);s.useEffect(()=>{i(!1)},[n]);const D=s.useCallback(async()=>{try{const l=await h({input:n});if(!l)throw new Error("No preview data returned");d(l),i(!0)}catch(l){console.error("Failed to generate preview:",l)}},[n,h]);s.useEffect(()=>{c&&!t&&D()},[c,t,D]);const w=n.income?.reduce((l,p)=>{const f=p.price*p.quantity,r=f*((p.vatRate||0)/100);return l+f+r},0)||0,I=()=>{u(n),x(!1)};return e.jsxs(R,{open:c,onOpenChange:x,children:[e.jsx(q,{asChild:!0,type:"button",children:e.jsxs(H,{children:[e.jsx(V,{asChild:!0,type:"button",children:e.jsx(v,{className:"size-7.5",variant:"secondary",onClick:()=>x(l=>!l),type:"button",children:e.jsx(ce,{className:"size-5"})})}),e.jsx(z,{children:e.jsx("p",{children:"Edit document"})})]})}),e.jsx(G,{className:"w-7xl sm:max-w-[95%] max-h-[90vh] overflow-y-auto",children:e.jsx("div",{className:"min-h-screen bg-gray-50 p-4",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:"Edit Document"}),e.jsx("p",{className:"text-gray-600 mt-2",children:"Modify and preview your accounting document before issuing"})]}),e.jsxs("div",{className:"grid lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(ie,{formData:n,updateFormData:T}),e.jsx(k,{children:e.jsxs(B,{className:"pt-6",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(v,{onClick:D,disabled:j||a,variant:"outline",className:"flex-1 bg-transparent",children:j?e.jsxs(e.Fragment,{children:[e.jsx(A,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(le,{className:"w-4 h-4 mr-2"}),"Preview"]})}),e.jsxs(v,{onClick:I,className:"flex-1",children:[e.jsx(oe,{className:"w-4 h-4 mr-2"}),"Accept Changes"]})]}),w>0&&e.jsx("div",{className:"mt-4 p-3 bg-blue-50 rounded-lg",children:e.jsxs("div",{className:"flex justify-between items-center font-medium text-blue-900",children:[e.jsx("span",{children:"Total Document Amount:"}),e.jsxs("span",{children:[w.toFixed(2)," ",n.currency]})]})})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(k,{className:"h-fit",children:[e.jsx(de,{children:e.jsx(ue,{children:"Document Preview"})}),e.jsx(B,{children:e.jsx("div",{className:"border-2 border-dashed border-gray-200 rounded-lg min-h-[600px] flex items-center justify-center bg-gray-50",children:j?e.jsxs("div",{className:"text-center",children:[e.jsx(A,{className:"w-8 h-8 animate-spin mx-auto mb-4 text-gray-400"}),e.jsx("p",{className:"text-gray-500",children:"Generating document preview..."})]}):t?e.jsx("div",{className:"w-full",children:e.jsx("div",{className:"bg-white shadow-lg rounded-lg overflow-hidden",children:e.jsx("div",{className:"aspect-[8.5/11] bg-white border",children:e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsxs("div",{className:"text-center p-6",children:[e.jsx(me,{src:t}),!a&&e.jsx("p",{className:"text-xs text-amber-600 mt-3 bg-amber-50 px-2 py-1 rounded",children:"Preview may be outdated"})]})})})})}):e.jsxs("div",{className:"text-center",children:[e.jsx(he,{className:"w-16 h-16 mx-auto mb-4 text-gray-300"}),e.jsx("p",{className:"text-gray-500 mb-2",children:"No preview available"}),e.jsx("p",{className:"text-sm text-gray-400",children:"Click Preview to generate document"})]})})})]}),n.client?.id&&e.jsx(xe,{businessId:n.client?.id,linkedDocumentIds:n.linkedDocumentIds??[]}),e.jsx(je,{documentType:n.type})]})]})]})})})]})}const Be=({drafts:u})=>{const[o,c]=s.useState(u.map(r=>S(E,r))),x=P($(new Date,1),"yyyy-MM-dd"),[a,i]=s.useState(x),[{data:t},d]=M({query:L,variables:{issueMonth:a},pause:!0});s.useEffect(()=>{t?.clientMonthlyChargesDrafts&&c(t.clientMonthlyChargesDrafts.map(r=>S(E,r)))},[t,c]),s.useEffect(()=>{d()},[a,d]);const h=pe({values:{generateDocumentsInfo:o}}),{issueDocuments:j}=Ee(),{openContracts:n}=Fe(),{fields:N,append:T,remove:D,update:w}=fe({control:h.control,name:"generateDocumentsInfo"}),I=h.watch("generateDocumentsInfo"),l=s.useMemo(()=>N.map((r,m)=>({...r,...I[m],id:r.client?.id})),[N,I]),p=s.useCallback(r=>{j(r)},[j]),f=s.useMemo(()=>n.filter(r=>r.billingCycle===ge.Monthly&&!l.some(m=>m.client?.id===r.client.originalBusiness.id)),[l,n]);return e.jsx("div",{className:"p-2",children:e.jsx(ye,{...h,children:e.jsxs("form",{onSubmit:h.handleSubmit(p),children:[e.jsxs("div",{className:"flex gap-2 items-center mb-4",children:[e.jsx(ve,{children:"Issue Month:"}),e.jsx(De,{value:new Date(a),onChange:r=>{const m=new Date(r.getFullYear(),r.getMonth(),15);i(P(m,"yyyy-MM-dd"))},popoverProps:{withinPortal:!0}})]}),e.jsxs(be,{children:[e.jsx(Ce,{children:e.jsxs(O,{children:[e.jsx(g,{children:"Name"}),e.jsx(g,{children:"Document"}),e.jsx(g,{children:"Amount"}),e.jsx(g,{children:"Remark"}),e.jsx(g,{children:"Recipients"}),e.jsx(g,{})]})}),e.jsx(Ne,{children:l.map(({id:r,...m},F)=>e.jsxs(O,{children:[e.jsx(y,{children:m.client?.name}),e.jsx(y,{children:m.type}),e.jsxs(y,{children:[m.income?.[0]?.price," ",m.income?.[0]?.currency]}),e.jsx(y,{children:e.jsx("span",{className:"text-sm text-gray-500 whitespace-normal max-w-50",children:m.remarks})}),e.jsx(y,{children:e.jsx("div",{className:"flex flex-col",children:m.client?.emails?.map(b=>e.jsx("span",{className:"text-sm text-gray-500",children:b},b))})}),e.jsx(y,{children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs(H,{children:[e.jsx(V,{asChild:!0,type:"button",children:e.jsx(v,{className:"size-7.5",variant:"secondary",onClick:()=>D(F),children:e.jsx(we,{size:16})})}),e.jsx(z,{children:e.jsx("p",{children:"Remove document"})})]}),e.jsx(ke,{draft:m,onApprove:b=>{h.setValue(`generateDocumentsInfo.${F}`,b,{shouldDirty:!0,shouldTouch:!0,shouldValidate:!0}),w(F,{...b})}})]})})]},r))})]}),e.jsxs("div",{className:"flex justify-between items-center mt-4",children:[e.jsx(Pe,{contracts:f,onAdd:T,issueMonth:a}),e.jsx(Ie,{onConfirm:h.handleSubmit(p),title:`Are you sure you want to issue ${l.length} documents?`,children:e.jsx(v,{children:"Issue"})})]})]})})})},Re=()=>{const{setFiltersContext:u}=s.useContext(Me),[{data:o,fetching:c}]=M({query:L,variables:{issueMonth:P($(new Date,1),"yyyy-MM-dd")}});return s.useEffect(()=>{o?.clientMonthlyChargesDrafts||u(null)},[o,u]),c?e.jsx(Te,{}):e.jsx(Be,{drafts:o?.clientMonthlyChargesDrafts??[]})};export{Re as IssueDocuments};
@@ -1,9 +0,0 @@
1
- import{cZ as f,r as h,u as B,j as e,c_ as $,bz as N,B as S,c$ as R,V as k,cd as O,ae as z,a0 as A,bO as v,ch as D,bT as C,bU as F,H as T,a2 as E,a3 as P,a4 as L,a5 as V,aI as M,d0 as U,dR as _,b$ as w,T as I,P as q,b as G,bg as Z,b6 as j,b1 as p,X as H,dS as J,ca as Q,cS as y,F as X,a as K,dT as W,dU as Y,c as ee,L as te,dV as se}from"./index-DOrujuWI.js";function ae(t){return!t||f(t)?null:encodeURIComponent(JSON.stringify(t))}function re({filter:t,setFilter:s,closeModal:o}){const n=k({defaultValues:{...t}}),{control:r,handleSubmit:l}=n,{selectableBusinesses:a,fetching:u}=O(),{userContext:m}=h.useContext(z),c=i=>{i.fromDate?.trim()===""&&(i.fromDate=void 0),i.toDate?.trim()===""&&(i.toDate=void 0),s(i),o()};function d(){s({}),o()}return e.jsxs(e.Fragment,{children:[u?e.jsx("div",{children:"Loading..."}):e.jsx("div",{}),e.jsx(A,{...n,children:e.jsxs("form",{onSubmit:l(c),className:"space-y-2",children:[e.jsx(v,{name:"ownerIds",control:r,defaultValue:void 0,render:({field:i,fieldState:b})=>e.jsx(D,{...i,data:a,value:i.value??(m?.context.adminBusinessId?[m?.context.adminBusinessId]:void 0),disabled:u,label:"Owners",placeholder:"Scroll to see all options",maxDropdownHeight:160,searchable:!0,error:b.error?.message})}),e.jsx(v,{name:"businessIDs",control:r,defaultValue:void 0,render:({field:i,fieldState:b})=>e.jsx(D,{...i,data:a,value:i.value??void 0,disabled:u,label:"Businesses",placeholder:"Scroll to see all options",maxDropdownHeight:160,searchable:!0,error:b.error?.message})}),e.jsx(v,{name:"fromDate",control:r,defaultValue:t.fromDate,rules:{required:"Required",pattern:{value:C,message:"Date must be im format yyyy-mm-dd"}},render:({field:i,fieldState:b})=>e.jsx(F,{...i,onChange:x=>{const g=x?typeof x=="string"?x:T(x,"yyyy-MM-dd"):void 0;g!==i.value&&i.onChange(g)},value:i.value?new Date(i.value):void 0,label:"From Date",error:b.error?.message,required:!0,popoverProps:{withinPortal:!0}})}),e.jsx(v,{name:"toDate",control:r,defaultValue:t.toDate,rules:{pattern:{value:C,message:"Date must be im format yyyy-mm-dd"}},render:({field:i,fieldState:b})=>e.jsx(F,{...i,onChange:x=>{const g=x?typeof x=="string"?x:T(x,"yyyy-MM-dd"):void 0;g!==i.value&&i.onChange(g)},value:i.value?new Date(i.value):void 0,label:"To Date",error:b.error?.message,required:!0,popoverProps:{withinPortal:!0}})}),e.jsx(E,{name:"isShowZeroedAccounts",control:r,render:({field:i})=>e.jsxs(P,{className:"flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm",children:[e.jsx("div",{className:"space-y-0.5",children:e.jsx(L,{children:"Show zeroed accounts"})}),e.jsxs("div",{className:"flex flex-row items-center gap-1",children:[e.jsx(V,{children:e.jsx(M,{defaultChecked:t.isShowZeroedAccounts??!1,onCheckedChange:i.onChange,checked:i.value===!0})}),e.jsx("span",{children:i.value?"show":"remove"})]})]})}),e.jsxs("div",{className:"flex justify-center mt-5 gap-3",children:[e.jsx("button",{type:"submit",className:"text-white bg-indigo-500 border-0 py-2 px-8 focus:outline-hidden hover:bg-indigo-600 rounded-sm text-lg",children:"Filter"}),e.jsx("button",{type:"button",className:"text-white bg-orange-500 border-0 py-2 px-8 focus:outline-hidden hover:bg-orange-600 rounded-sm text-lg",onClick:d,children:"Clear"}),e.jsx("button",{type:"button",className:"text-white bg-rose-500 border-0 py-2 px-8 focus:outline-hidden hover:bg-rose-600 rounded-sm text-lg",onClick:o,children:"Cancel"})]})]})})]})}function ne({filter:t,setFilter:s}){const[o,n]=h.useState(!1),[r,l]=h.useState(!f(t)),{get:a,set:u}=B();function m(d){return Object.entries(d??{}).filter(([b,x])=>x!==void 0&&Array.isArray(x)&&x.length>0).length>0}function c(d){U(d,t)||(s(d),l(m(d)))}return h.useEffect(()=>{const d=f(t)?null:encodeURIComponent(JSON.stringify(t)),i=a("trialBalanceReportFilters");d!==i&&u("trialBalanceReportFilters",d)},[t,a,u]),e.jsxs(e.Fragment,{children:[e.jsx($,{opened:o,onClose:()=>n(!1),content:e.jsx(re,{filter:t,setFilter:c,closeModal:()=>n(!1)})}),e.jsx(N,{inline:!0,size:16,disabled:!r,children:e.jsx(S,{variant:"outline",onClick:()=>n(!0),className:"p-2",children:e.jsx(R,{size:20})})})]})}const oe=({data:t,fromDate:s,toDate:o})=>{const n=h.useCallback(async()=>{const r=le(t),l=`trial_balance_report${s?`_${s}`:""}${o?`_${o}`:""}`;return{fileContent:r,fileName:l}},[t,s,o]);return e.jsx(_,{createFileVariables:n})},le=t=>{let s="";s+=`Sort Code,Account Name,Debit,Credit,Balance\r
2
- `;for(const[o,n]of Object.entries(t)){const r=ie(o,n);s+=r}return s+=`Report total:,,${Object.values(t).reduce((o,n)=>o+n.totalDebit,0)},${Object.values(t).reduce((o,n)=>o+n.totalCredit,0)},${Object.values(t).reduce((o,n)=>o+n.sum,0)}\r
3
- `,s};function ie(t,s){let o="";return Object.values(s.sortCodes).sort((n,r)=>n.key-r.key).map(n=>{const r=ce(n);o+=r}),o+=`${t.replaceAll("0","*")},Group Total:,${s.totalDebit??""},${s.totalCredit??""},${s.sum}\r
4
- `,o}function ce(t){let s="";s+=`${t.name}\r
5
- `,t.records.sort((l,a)=>l.business.name.localeCompare(a.business.name)).map(l=>{const a=l?.total?.raw??0,u=l?.debit?.raw??0,m=l?.credit?.raw??0,c=`${t.key},${l.business.name?`"${de(l.business.name)}"`:""},${u?l?.debit?.raw:void 0},${m?l?.credit?.raw:void 0},${a>.001||a<-.001?l?.total?.raw??"":""}\r
6
- `;s+=c});const o=`${t.key},Group total:,${t.totalDebit??""},${t.totalCredit??""},${t.sum}\r
7
- `;s+=o;const n=t.debit?`,,,Total Debit Balances:,${t.debit}\r
8
- `:"";s+=n;const r=t.credit?`,,,Total Credit Balances:,${t.credit}\r
9
- `:"";return s+=r,s}function de(t){let s="";return s=t.replace(/"/g,'""'),s}const ue=({record:t,sortCodeKey:s,filter:o,isAllOpened:n})=>{const[r,l]=h.useState(n),a=t?.total?.raw??0,u=t?.debit?.raw??0,m=t?.credit?.raw??0;return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:s}),e.jsx("td",{children:t.business.id}),e.jsx("td",{children:t.business.name??void 0}),e.jsx("td",{children:u?t?.debit?.formatted:void 0}),e.jsx("td",{children:m?t?.credit?.formatted:void 0}),e.jsx("td",{children:(a>.001||a<-.001)&&e.jsx(w,{color:a>0?"green":"red",children:t?.total?.formatted})}),e.jsx("td",{children:e.jsx(I,{label:"Detailed records",children:e.jsx(S,{variant:"outline",size:"icon",className:"size-7.5",onClick:()=>l(c=>!c),children:r||n?e.jsx(q,{className:"size-5"}):e.jsx(G,{className:"size-5"})})})})]},t.business.id),(r||n)&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,children:e.jsx(Z,{businessID:t.business?.id,filter:o})})})]})},me=({sortCode:t,filter:s,isAllOpened:o})=>t.records.length>0?e.jsxs(e.Fragment,{children:[e.jsx("tr",{children:e.jsx("td",{colSpan:7,children:e.jsx("span",{className:"font-bold",children:t.name})})}),t.records.sort((n,r)=>n.business.name.localeCompare(r.business.name)).map(n=>e.jsx(ue,{record:n,sortCodeKey:t.key,filter:s,isAllOpened:o},n.business.id)),e.jsx("tr",{className:"bg-gray-100",children:t.records.length>1?e.jsxs(e.Fragment,{children:[e.jsx("td",{colSpan:2,children:"Group total:"}),e.jsx("td",{colSpan:1,children:t.key}),e.jsx("td",{colSpan:1,children:!!t.totalDebit&&j(t.totalDebit,p.Ils)}),e.jsx("td",{colSpan:1,children:!!t.totalCredit&&j(t.totalCredit,p.Ils)}),e.jsxs("td",{colSpan:1,children:[e.jsx(w,{c:t.sum>0?"green":t.sum<0?"red":void 0,children:j(t.sum,p.Ils)}),!!t.debit&&e.jsxs(e.Fragment,{children:[e.jsx("br",{}),"Total Debit Balances: ",j(t.debit,p.Ils)]}),!!t.credit&&e.jsxs(e.Fragment,{children:[e.jsx("br",{}),"Total Credit Balances: ",j(t.credit,p.Ils)]})]})]}):void 0})]}):null,xe=({group:t,data:s,filter:o,isAllOpened:n})=>e.jsxs(e.Fragment,{children:[Object.values(s.sortCodes).sort((r,l)=>r.key-l.key).map((r,l)=>e.jsx(me,{sortCode:r,filter:o,isAllOpened:n},`${r.key} ${l}`)),e.jsxs("tr",{className:"bg-gray-100",children:[e.jsx("td",{colSpan:2,children:"Group total:"}),e.jsx("td",{colSpan:1,children:t.replaceAll("0","*")}),e.jsx("td",{colSpan:1,children:!!s.totalDebit&&j(s.totalDebit,p.Ils)}),e.jsx("td",{colSpan:1,children:!!s.totalCredit&&j(s.totalCredit,p.Ils)}),e.jsx("td",{colSpan:1,children:e.jsx(w,{fw:700,c:s.sum>0?"green":s.sum<0?"red":void 0,children:j(s.sum,p.Ils)})})]},"group"+t)]});function he(t){return Math.floor(t/100)*100}const be=({data:t,filter:s,isAllOpened:o})=>{const{businessTransactionsSum:n}=H(J,t),r=h.useMemo(()=>{const l={};for(const a of n){a.business.sortCode??={id:"-999",key:-999,name:"Misc"};const u=!a.total.raw||a.total.raw<.001&&a.total.raw>-.001;if(!s.isShowZeroedAccounts&&u)continue;const m=he(a.business.sortCode.key);l[m]??={sortCodes:{},totalCredit:0,totalDebit:0,credit:0,debit:0,sum:0};const c=l[m];c.sortCodes[a.business.sortCode.key]??={...a.business.sortCode,totalCredit:0,totalDebit:0,records:[],credit:0,debit:0,sum:0};const d=c.sortCodes[a.business.sortCode.key];d.totalCredit+=a.credit.raw,d.totalDebit+=a.debit.raw,d.sum+=a.total.raw,c.totalCredit+=a.credit.raw,c.totalDebit+=a.debit.raw,c.sum+=a.total.raw,a.total.raw>0?(d.credit+=a.total.raw,c.credit+=a.total.raw):(d.debit+=a.total.raw,c.debit+=a.total.raw),d.records.push(a)}return l},[n,s.isShowZeroedAccounts]);return e.jsxs(Q,{highlightOnHover:!0,children:[e.jsx("thead",{style:{position:"sticky",top:0,zIndex:20},children:e.jsxs("tr",{className:"bg-gray-300",children:[e.jsx("th",{children:"Sort Code"}),e.jsx("th",{children:"Account"}),e.jsx("th",{children:"Account Name"}),e.jsx("th",{children:"Total Debit"}),e.jsx("th",{children:"Total Credit"}),e.jsx("th",{children:"Balance"}),e.jsx("th",{children:e.jsx(oe,{data:r,fromDate:s.fromDate??void 0,toDate:s.toDate??void 0})})]})}),e.jsxs("tbody",{children:[Object.entries(r).map(([l,a])=>e.jsx(xe,{data:a,group:l,filter:s,isAllOpened:o},l)),e.jsxs("tr",{className:"bg-gray-100",children:[e.jsx("td",{colSpan:2,children:"Report total:"}),e.jsx("td",{}),e.jsxs("td",{children:["(",y(Object.values(r).reduce((l,a)=>l+a.totalDebit,0)),")"]}),e.jsxs("td",{children:["(",y(Object.values(r).reduce((l,a)=>l+a.totalCredit,0)),")"]}),e.jsx("td",{colSpan:1,children:y(Object.values(r).reduce((l,a)=>l+a.sum,0))})]})]})]})};function pe(t){const s=new URLSearchParams,o=ae(t);return o&&s.append("trialBalanceReportFilters",o),`/reports/trial-balance${s.size>0?`?${s}`:""}`}const ge=()=>{const[t,s]=h.useState(!1),{get:o}=B(),{setFiltersContext:n}=h.useContext(X),[r,l]=h.useState(o("trialBalanceReportFilters")?JSON.parse(decodeURIComponent(o("trialBalanceReportFilters"))):{}),[{data:a,fetching:u}]=K({query:se,variables:{filters:{fromDate:r?.fromDate,toDate:r?.toDate,ownerIds:r?.ownerIds,businessIDs:r?.businessIDs}}});h.useEffect(()=>{n(e.jsxs("div",{className:"flex flex-row gap-2",children:[e.jsx(I,{label:"Expand all accounts",children:e.jsx(S,{variant:"outline",size:"icon",className:"size-7.5",onClick:()=>s(c=>!c),children:t?e.jsx(W,{className:"size-5"}):e.jsx(Y,{className:"size-5"})})}),e.jsx(ne,{filter:r,setFilter:l})]}))},[r,t,n]);const m=h.useMemo(()=>a?.businessTransactionsSumFromLedgerRecords.__typename==="CommonError"?void 0:a?.businessTransactionsSumFromLedgerRecords,[a?.businessTransactionsSumFromLedgerRecords]);return e.jsx(ee,{title:"Trial Balance Report",description:"Trial balance report for all businesses",children:u||!m?e.jsx(te,{className:"h-10 w-10 animate-spin mr-2 self-center"}):e.jsx(be,{data:m,filter:r,isAllOpened:t})})};export{ge as TrialBalanceReport,pe as getTrialBalanceReportHref};
@@ -1 +0,0 @@
1
- import{j as e,a2 as C,a3 as p,a4 as S,a5 as y,aO as v,a7 as I,v as L,i as D,f$ as H,r as u,t as m,l as E,K as M,an as R,B as x,c7 as z,N as A,ap as T,aq as $,a as q,g0 as V,L as O,V as P,a0 as K,ab as _,g1 as Q,F as G,dj as J,c as W,dm as X,dn as Y,dp as b,dq as Z,dr as w,ds as ee,dt as g,g2 as se,dz as te,dA as re,dB as oe}from"./index-DOrujuWI.js";import{D as ne}from"./data-table-pagination-aFECnXu9.js";import{A as F}from"./arrow-up-down-DvV6Dq8U.js";function B({isInsert:s,formManager:n}){const{control:r}=n;return e.jsxs(e.Fragment,{children:[e.jsx(C,{name:"key",control:r,disabled:!s,rules:{required:"Required",validate:{positive:t=>Number(t)>0||"Key must be a positive number",integer:t=>Number.isInteger(Number(t))||"Key must be an integer"}},render:({field:t})=>e.jsxs(p,{children:[e.jsx(S,{children:"Key"}),e.jsx(y,{children:e.jsx(v,{...t,value:t.value??void 0,hideControls:!0,decimalScale:0,thousandSeparator:"",required:!0})}),e.jsx(I,{})]})}),e.jsx(C,{name:"name",control:r,rules:{required:"Required",minLength:{value:2,message:"Must be at least 2 characters"}},render:({field:t})=>e.jsxs(p,{children:[e.jsx(S,{children:"Name"}),e.jsx(y,{children:e.jsx(L,{...t,value:t.value??void 0,required:!0})}),e.jsx(I,{})]})}),e.jsx(C,{name:"defaultIrsCode",control:r,render:({field:t})=>e.jsxs(p,{children:[e.jsx(S,{children:"Default IRS Code"}),e.jsx(y,{children:e.jsx(v,{...t,value:t.value??void 0,hideControls:!0,decimalScale:0})}),e.jsx(I,{})]})})]})}const ae="updateSortCode",de=()=>{const[{fetching:s},n]=D(H),r=u.useCallback(async t=>{const d=`Error updating sort code ID [${t.key}]`,o=`${ae}-${t.key}`;m.loading("Updating Sort Code...",{id:o});try{const a=await n(t),i=E(a,d,o,"updateSortCode");if(i)return m.success("Success",{id:o,description:"SortCode updated"}),i.updateSortCode}catch(a){console.error(`${d}: ${a}`),m.error("Error",{id:o,description:d,duration:1e5,closeButton:!0})}return!1},[n]);return{fetching:s,updateSortCode:r}};function ie({sortCodeKey:s,onAdd:n}){const[r,t]=u.useState(!1);return e.jsxs(M,{open:r,onOpenChange:t,children:[e.jsx(R,{asChild:!0,children:e.jsx(x,{variant:"outline",size:"icon",children:e.jsx(z,{})})}),e.jsxs(A,{className:"w-[400px] max-w-screen-md",children:[e.jsx(T,{children:e.jsx($,{children:"Edit Sort Code"})}),e.jsx(le,{sortCodeKey:s,close:()=>t(!1),onAdd:n})]})]})}function le({sortCodeKey:s,close:n,onAdd:r}){const[{data:t,fetching:d}]=q({query:V,variables:{key:s}}),o=t?.sortCode;return!o&&!d&&m.error("Error",{description:"Couldn't find sort code"}),d?e.jsx(O,{className:"h-10 w-10 animate-spin"}):o?e.jsx(ce,{sortCode:o,close:n,onAdd:r}):e.jsx("div",{children:"Sort code not found"})}function ce({sortCode:s,close:n,onAdd:r}){const t=P({defaultValues:s}),{handleSubmit:d,formState:{dirtyFields:o}}=t,{updateSortCode:a,fetching:i}=de(),l=({key:c,...U})=>{const h=_(U,o);if(h&&Object.keys(h).length>0){let N;if(h.defaultIrsCode){const j=h.defaultIrsCode,f=Number(j);if(!Number.isInteger(f)||f<2||f>9999)throw new Error(`Invalid IRS code: ${j}`);N=f}a({fields:{...h,defaultIrsCode:N},key:s.key}).then(j=>{j&&(r?.(s.key),n())})}};return e.jsx(K,{...t,children:e.jsxs("form",{onSubmit:d(l),children:[e.jsx("div",{className:"flex flex-col gap-4 my-4",children:e.jsx(B,{isInsert:!1,formManager:t})}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsx(x,{type:"submit",disabled:i,children:"Update"})})]})})}const ue="addSortCode",me=()=>{const[{fetching:s},n]=D(Q),r=u.useCallback(async t=>{const d=`Error adding new sort code [${t.name}]`,o=`${ue}-${t.name}`;m.loading("Adding sort code",{id:o});try{const a=await n(t);E(a,d,o)&&m.success("Success",{id:o,description:`"${t.name}" sort code was successfully added`})}catch(a){console.error(`${d}: ${a}`),m.error("Error",{id:o,description:d,duration:1e5,closeButton:!0})}},[n]);return{fetching:s,addSortCode:r}};function xe({onAdd:s}){const[n,r]=u.useState(!1);return e.jsxs(M,{open:n,onOpenChange:r,children:[e.jsx(R,{asChild:!0,children:e.jsx(x,{children:"Add Sort Code"})}),e.jsxs(A,{className:"w-[90vw] max-w-screen-md",children:[e.jsx(T,{children:e.jsx($,{children:"Add New Sort Code"})}),e.jsx(he,{close:()=>r(!1),onAdd:s})]})]})}function he({close:s,onAdd:n}){const r=P({}),{handleSubmit:t}=r,{addSortCode:d,fetching:o}=me(),a=i=>{i.key&&=parseInt(i.key.toString()),i.defaultIrsCode&&=parseInt(i.defaultIrsCode.toString()),d(i).then(()=>{s(),n?.()})};return e.jsx(K,{...r,children:e.jsxs("form",{onSubmit:t(a),children:[e.jsx("div",{className:"flex flex-col gap-4 my-4",children:e.jsx(B,{isInsert:!0,formManager:r})}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsx(x,{type:"submit",disabled:o,children:"Add Sort Code"})})]})})}const k=[{id:"key",accessorKey:"key",cell:({row:s})=>e.jsx(g,{children:s.original.key}),header:({column:s})=>e.jsxs(x,{variant:"ghost",onClick:()=>s.toggleSorting(s.getIsSorted()==="asc"),children:["Key",e.jsx(F,{})]})},{id:"name",accessorKey:"name",cell:({row:s})=>e.jsx(g,{children:s.original.name}),header:({column:s})=>e.jsxs(x,{variant:"ghost",onClick:()=>s.toggleSorting(s.getIsSorted()==="asc"),children:["Name",e.jsx(F,{})]})},{id:"defaultIrsCode",accessorKey:"defaultIrsCode",cell:({row:s})=>e.jsx(g,{className:"flex flex-wrap gap-1 p-1",children:s.original.defaultIrsCode&&e.jsx(x,{variant:"outline",disabled:!0,className:"p-1 w-15",children:s.original.defaultIrsCode})}),header:"Default IRS Code"},{id:"edit",cell:({row:s})=>e.jsx(ie,{sortCodeKey:s.original.key,onAdd:s.original.refetchSortCodes})}],Ce=()=>{const[{data:s,fetching:n,error:r},t]=q({query:se}),{setFiltersContext:d}=u.useContext(G),o=u.useMemo(()=>s?.allSortCodes?.map(l=>({...l,refetchSortCodes:t}))??[],[s?.allSortCodes,t]),a=J({data:o,columns:k,getCoreRowModel:oe(),getPaginationRowModel:re(),getSortedRowModel:te(),initialState:{pagination:{pageSize:100}}}),i=a.getPageOptions();return u.useEffect(()=>{d(e.jsx("div",{className:"flex items-center justify-end gap-10 space-x-2 py-4",children:e.jsx(ne,{table:a})}))},[d,a,i]),u.useEffect(()=>{r&&(console.error("Error fetching sort codes",r),m.error("Error",{description:"Error fetching sort codes"}))},[r]),e.jsx(W,{title:`Sort Codes (${o.length})`,description:"All sort codes",headerActions:e.jsx(xe,{onAdd:()=>t()}),children:n?e.jsx("div",{className:"flex flex-row justify-center",children:e.jsx(O,{className:"h-10 w-10 animate-spin mr-2"})}):e.jsx("div",{className:"flex flex-col gap-4 rounded-md border",children:e.jsxs(X,{children:[e.jsx(Y,{children:a.getHeaderGroups().map(l=>e.jsx(b,{children:l.headers.map(c=>e.jsx(Z,{children:c.isPlaceholder?null:w(c.column.columnDef.header,c.getContext())},c.id))},l.id))}),e.jsx(ee,{children:a.getRowModel().rows.length===0?e.jsx(b,{children:e.jsx(g,{colSpan:k.length,className:"text-center py-8",children:"No sort codes found"})}):a.getRowModel().rows.map(l=>e.jsx(b,{children:l.getVisibleCells().map(c=>e.jsx(g,{children:w(c.column.columnDef.cell,c.getContext())},c.id))},l.id))})]})})})};export{Ce as SortCodes};
@@ -1 +0,0 @@
1
- import{r as h,j as e,c_ as u,eK as f,B as y,c$ as R,bp as D,F as T,a as E,c as b,L as w,ca as F,eM as g}from"./index-DOrujuWI.js";import{d as v}from"./graphql-document-dedupe-fragments-ByT8-wlV.js";import{R as d}from"./report-commentary-row-BNIW-6Qg.js";function B({year:c,setYear:m,referenceYears:x,setReferenceYears:j}){const[i,o]=h.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsx(u,{opened:i,onClose:()=>o(!1),withCloseButton:!0,content:e.jsxs(e.Fragment,{children:[e.jsx(f,{label:"Change report year",value:new Date(c,0,1),onChange:n=>n&&m(n?.getFullYear()),popoverProps:{withinPortal:!0},minDate:new Date(2010,0,1),maxDate:new Date}),e.jsx(f,{type:"multiple",label:"Pick reference years",value:x?.map(n=>new Date(n,0,1)),onChange:n=>j(n.map(l=>l.getFullYear()).filter(l=>c!==l)),popoverProps:{withinPortal:!0},minDate:new Date(2010,0,1),maxDate:new Date})]})}),e.jsx(y,{variant:"outline",size:"icon",className:"size-7.5",onClick:()=>o(!0),children:e.jsx(R,{className:"size-5"})})]})}const Y=()=>{const{year:c}=D(),{setFiltersContext:m}=h.useContext(T),[x,j]=h.useState(c?Number(c):new Date().getFullYear()),[i,o]=h.useState([]),[{data:n,fetching:l}]=E({query:v(g),variables:{reportYear:x,referenceYears:i}});h.useEffect(()=>{m(e.jsx("div",{className:"flex flex-row gap-2",children:e.jsx(B,{year:x,setYear:j,referenceYears:i,setReferenceYears:o})}))},[x,l,m,i,o]);const p=n?.taxReport,s=p?.report,r=p?.reference??[];return e.jsx(b,{title:"Tax Report",children:l?e.jsx(w,{className:"h-10 w-10 animate-spin mr-2 self-center"}):e.jsx("div",{className:"flex flex-col gap-4",children:s&&e.jsxs(F,{highlightOnHover:!0,fontSize:"md",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{}),e.jsx("th",{children:x},x),e.jsx("th",{}),r.map(t=>e.jsx("th",{children:t.year},t.year))]})}),e.jsxs("tbody",{children:[e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("th",{children:"Profit Before Tax"}),e.jsx("th",{children:s.profitBeforeTax.amount.formatted}),e.jsx("th",{children:t}),r.map(a=>e.jsx("th",{children:a.profitBeforeTax.amount.formatted},a.year))]}),commentaryData:s.profitBeforeTax}),e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("td",{children:"R&D Expenses By Records"}),e.jsx("td",{children:s.researchAndDevelopmentExpensesByRecords.amount.formatted}),e.jsx("th",{children:t}),r.map(a=>e.jsx("td",{children:a.researchAndDevelopmentExpensesByRecords.amount.formatted},a.year))]}),commentaryData:s.researchAndDevelopmentExpensesByRecords}),e.jsxs("tr",{children:[e.jsx("td",{children:"R&D Expenses For Tax"}),e.jsx("td",{children:s.researchAndDevelopmentExpensesForTax.formatted}),e.jsx("td",{}),r.map(t=>e.jsx("td",{children:t.researchAndDevelopmentExpensesForTax.formatted},t.year)),e.jsx("td",{})]}),e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("td",{children:"Fines"}),e.jsx("td",{children:s.fines.amount.formatted}),e.jsx("th",{children:t}),r.map(a=>e.jsx("td",{children:a.fines.amount.formatted},a.year))]}),commentaryData:s.fines}),e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("td",{children:"Untaxable Gifts"}),e.jsx("td",{children:s.untaxableGifts.amount.formatted}),e.jsx("th",{children:t}),r.map(a=>e.jsx("td",{children:a.untaxableGifts.amount.formatted},a.year))]}),commentaryData:s.untaxableGifts}),e.jsxs("tr",{children:[e.jsx("td",{children:"Business Trips Excess Expenses"}),e.jsx("td",{children:s.businessTripsExcessExpensesAmount.formatted}),e.jsx("td",{}),r.map(t=>e.jsx("td",{children:t.businessTripsExcessExpensesAmount.formatted},t.year)),e.jsx("td",{})]}),e.jsxs("tr",{children:[e.jsx("td",{children:"Salary Excess Expenses"}),e.jsx("td",{children:s.salaryExcessExpensesAmount.formatted}),e.jsx("td",{}),r.map(t=>e.jsx("td",{children:t.salaryExcessExpensesAmount.formatted},t.year)),e.jsx("td",{})]}),e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("td",{children:"Reserves"}),e.jsx("td",{children:s.reserves.amount.formatted}),e.jsx("th",{children:t}),r.map(a=>e.jsx("td",{children:a.reserves.amount.formatted},a.year))]}),commentaryData:s.reserves}),e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("td",{children:"Nontaxable Linkage"}),e.jsx("td",{children:s.nontaxableLinkage.amount.formatted}),e.jsx("th",{children:t}),r.map(a=>e.jsx("td",{children:a.nontaxableLinkage.amount.formatted},a.year))]}),commentaryData:s.nontaxableLinkage}),e.jsxs("tr",{children:[e.jsx("th",{children:"Taxable Income"}),e.jsx("th",{children:s.taxableIncome.formatted}),e.jsx("th",{}),r.map(t=>e.jsx("th",{children:t.taxableIncome.formatted},t.year)),e.jsx("td",{})]}),e.jsxs("tr",{children:[e.jsx("td",{children:"Tax Rate"}),e.jsxs("td",{children:[(s.taxRate*100).toFixed(1),"%"]}),e.jsx("td",{}),r.map(t=>e.jsxs("td",{children:[(t.taxRate*100).toFixed(1),"%"]},t.year)),e.jsx("td",{})]}),e.jsx(d,{dataRow:t=>e.jsxs("tr",{children:[e.jsx("td",{children:"Income with Special Tax Rate"}),e.jsx("td",{children:s.specialTaxableIncome.amount.formatted}),e.jsx("th",{children:t}),r.map(a=>e.jsx("td",{children:a.specialTaxableIncome.amount.formatted},a.year))]}),commentaryData:s.specialTaxableIncome}),e.jsxs("tr",{children:[e.jsx("td",{children:"Special Tax Rate"}),e.jsxs("td",{children:[(s.specialTaxRate*100).toFixed(1),"%"]}),e.jsx("td",{}),r.map(t=>e.jsxs("td",{children:[(t.specialTaxRate*100).toFixed(1),"%"]},t.year)),e.jsx("td",{})]})]}),e.jsx("tfoot",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Annual Tax Expense"}),e.jsx("th",{children:s.annualTaxExpense.formatted}),e.jsx("th",{}),r.map(t=>e.jsx("th",{children:t.annualTaxExpense.formatted},t.year)),e.jsx("td",{})]})})]})})})};export{Y as TaxReport};
@@ -1 +0,0 @@
1
- import{i as f,fQ as I,r as u,t as l,l as p,V as b,X as y,j as e,a0 as C,fz as $,a2 as D,a3 as F,a4 as w,a5 as k,v as j,a7 as v,fR as E,fS as S,ab as z,o as A,T as M,B as T,c7 as O,q as L,fT as P,fU as q,F as B,a as U,fV as R,c as V,L as _,bR as Q,bS as G,fW as W}from"./index-DOrujuWI.js";const X="updateTag",H=()=>{const[{fetching:i},r]=f(I),c=u.useCallback(async a=>{const t=`Error updating tag ID [${a.tagId}]`,s=`${X}-${a.tagId}`;l.loading("Updating Tag...",{id:s});try{const n=await r(a),d=p(n,t,s,"updateTag");if(d)return l.success("Success",{id:s,description:"Tag updated"}),d.updateTag}catch(n){console.error(`${t}: ${n}`),l.error("Error",{id:s,description:t,duration:1e5,closeButton:!0})}return!1},[r]);return{fetching:i,updateTag:c}},J=({onDone:i,data:r,close:c})=>{const{updateTag:a,fetching:t}=H(),s=y(S,r),n=b({defaultValues:{name:s.name,parentId:s.parent?.id}}),{control:d,handleSubmit:m,formState:{dirtyFields:h}}=n,x=o=>{const g=z(o,h);c(),g&&Object.keys(g).length>0&&a({tagId:s.id,fields:g}).then(()=>i?.())};return e.jsx(C,{...n,children:e.jsxs("form",{onSubmit:m(x),children:[e.jsx("div",{className:"flex-row px-10 h-max justify-start block",children:e.jsxs($,{cols:3,children:[e.jsx(D,{name:"name",control:d,defaultValue:s.name,rules:{required:"Required",minLength:{value:2,message:"Must be at least 2 characters"}},render:({field:o})=>e.jsxs(F,{children:[e.jsx(w,{children:"Name"}),e.jsx(k,{children:e.jsx(j,{...o,value:o.value??void 0})}),e.jsx(v,{})]})}),e.jsx(E,{formManager:n,tagsPath:"parentId",label:"Parent Tag"})]})}),e.jsxs("div",{className:"mt-10 mb-5 flex justify-center gap-5",children:[e.jsx("button",{type:"submit",onClick:()=>m(x),className:"mt-8 text-white bg-indigo-500 border-0 py-2 px-8 focus:outline-hidden hover:bg-indigo-600 rounded-sm text-lg",disabled:t||Object.keys(h).length===0,children:"Accept"}),e.jsx("button",{type:"button",className:"mt-8 text-white bg-rose-500 border-0 py-2 px-8 focus:outline-hidden hover:bg-rose-600 rounded-sm text-lg",onClick:c,children:"Cancel"})]})]})})},K=({onDone:i,data:r})=>{const[c,{open:a,close:t}]=A(!1);function s(){t(),i?.()}return e.jsxs(e.Fragment,{children:[e.jsx(M,{label:"Edit Tag",children:e.jsx(T,{variant:"ghost",size:"icon",className:"size-7.5",onClick:a,children:e.jsx(O,{className:"size-5"})})}),e.jsx(L,{centered:!0,opened:c,onClose:t,title:"Insert Business Trip",children:e.jsx(J,{close:t,onDone:s,data:r})})]})},Y="addTag",Z=()=>{const[{fetching:i},r]=f(P),c=u.useCallback(async a=>{const t=`Error adding new tag [${a.tagName}]`,s=`${Y}-${a.tagName}`;l.loading("Adding tag",{id:s});try{const n=await r(a);p(n,t,s)&&l.success("Success",{id:s,description:`"${a.tagName}" tag was successfully added`})}catch(n){console.error(`${t}: ${n}`),l.error("Error",{id:s,description:t,duration:1e5,closeButton:!0})}},[r]);return{fetching:i,addTag:c}},ee="deleteTag",se=()=>{const[{fetching:i},r]=f(q),c=u.useCallback(async a=>{const t=`Error deleting new tag [${a.name}]`,s=`${ee}-${a.tagId}`;l.loading(`Deleting tag [${a.name}]`,{id:s});try{const n=await r(a);p(n,t,s)&&l.success("Tag Deleted",{id:s,description:`[${a.name}] tag was successfully removed`})}catch(n){console.error(`${t}: ${n}`),l.error("Error",{id:s,description:t,duration:1e5,closeButton:!0})}},[r]);return{fetching:i,deleteTag:c}},te=()=>{const{setFiltersContext:i}=u.useContext(B),[r,c]=u.useState(""),[{data:a,fetching:t},s]=U({query:W}),{addTag:n}=Z(),{deleteTag:d}=se();i(null);const m=R(a?.allTags??[]),h=u.useCallback(o=>{o.length>2&&n({tagName:o}).then(()=>{s()})},[n,s]),x=u.useCallback((o,g)=>{d({tagId:o,name:g}).then(()=>{s()})},[d,s]);return e.jsx(V,{title:"Tags",description:"Manage tags for your bookmarks.",children:t?e.jsx(_,{className:"h-10 w-10 animate-spin mr-2 self-center"}):e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[m?.map(o=>e.jsxs("div",{className:"flex items-center gap-2 text-gray-600 mb-2",children:[e.jsxs("div",{className:"w-full mt-1 relative rounded-md shadow-xs",children:[o.namePath?.map((g,N)=>e.jsx("span",{className:"ms-2"},N)),o.name]}),e.jsx(K,{data:o}),e.jsx(T,{variant:"ghost",size:"icon",className:"size-7.5",onClick:()=>x(o.id,o.name),children:e.jsx(Q,{className:"size-5"})})]},o.id)),e.jsxs("div",{className:"flex justify-start items-center gap-2 text-gray-600 mb-2",children:[e.jsx(j,{className:"w-80",value:r,onChange:o=>c(o.currentTarget.value),placeholder:"Add new tag",required:!0}),e.jsx(T,{variant:"ghost",size:"icon",className:"size-7.5",disabled:r.length<2,onClick:()=>h(r),children:e.jsx(G,{className:"size-5"})})]})]})})};export{te as TagsManager};
@@ -1 +0,0 @@
1
- import{cZ as k,r as m,u as R,d0 as V,j as e,c_ as q,bz as Q,B as I,c$ as z,V as G,cd as K,dh as X,aL as J,di as Z,bO as y,bP as A,bT as F,bU as B,H as S,ch as E,a as P,f7 as W,Y as U,n as $,Z as Y,_ as ee,at as ae,a1 as O,f8 as se,F as te,ae as re,aP as ne,c as oe,$ as le,e8 as ie,f9 as ce,b1 as de}from"./index-DOrujuWI.js";import{k as ue,B as N,X as H,Y as me,l as pe,m as xe,n as ge,o as he,p as fe,q as be,r as je}from"./chart-Cg9PgOtK.js";import{s as ye}from"./sub-Daf_8shG.js";import"./sequential-CAnleQny.js";import"./subMonths-DIZWyi5T.js";var ve=ue({chartName:"BarChart",GraphicalChild:N,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:H},{axisType:"yAxis",AxisComp:me}],formatAxisMap:pe});function _(s){return!s||k(s)?null:encodeURIComponent(JSON.stringify(s))}const L="balanceReportFilters",x={MONTHLY:"Monthly",BI_MONTHLY:"Bi-monthly",QUARTERLY:"Quarterly",SEMI_ANNUALLY:"Semi-Annually",ANNUALLY:"Annually"};function Ce({filter:s,setFilter:n,closeModal:c}){const{control:t,handleSubmit:r,watch:g}=G({defaultValues:{...s}}),{selectableBusinesses:b,fetching:h}=K(),{selectableFinancialEntities:f,fetching:v}=X(),{selectableTags:p,fetching:j}=J(),M=a=>{n(a),c()},C=g("excludedTags"),l=m.useMemo(()=>p.filter(a=>!C.includes(a.value)),[C,p]),d=g("includedTags"),o=m.useMemo(()=>p.filter(a=>!d.includes(a.value)),[d,p]);return e.jsxs("form",{onSubmit:r(M),children:[e.jsxs(Z,{cols:2,children:[e.jsx(y,{name:"ownerId",control:t,defaultValue:s?.ownerId,render:({field:a,fieldState:i})=>e.jsx(A,{...a,data:b,value:a.value,disabled:h,label:"Owners",placeholder:"Scroll to see all options",maxDropdownHeight:160,searchable:!0,error:i.error?.message,withinPortal:!0})}),e.jsx(y,{name:"fromDate",control:t,defaultValue:s?.fromDate,rules:{pattern:{value:F,message:"Date must be im format yyyy-mm-dd"}},render:({field:a,fieldState:i})=>e.jsx(B,{...a,onChange:u=>{const T=u?typeof u=="string"?u:S(u,"yyyy-MM-dd"):void 0;T!==a.value&&a.onChange(T)},value:a.value?new Date(a.value):void 0,error:i.error?.message,label:"From Date",popoverProps:{withinPortal:!0}})}),e.jsx(y,{name:"toDate",control:t,defaultValue:s?.toDate,rules:{pattern:{value:F,message:"Date must be im format yyyy-mm-dd"}},render:({field:a,fieldState:i})=>e.jsx(B,{...a,onChange:u=>{const T=u?typeof u=="string"?u:S(u,"yyyy-MM-dd"):void 0;T!==a.value&&a.onChange(T)},value:a.value?new Date(a.value):void 0,error:i.error?.message,label:"To Date",popoverProps:{withinPortal:!0}})}),e.jsx(y,{name:"period",control:t,defaultValue:x.MONTHLY,render:({field:a,fieldState:i})=>e.jsx(A,{...a,data:Object.values(x).map(u=>({value:u,label:u})),value:a.value,label:"Period",maxDropdownHeight:160,error:i.error?.message,withinPortal:!0})}),e.jsx(y,{name:"excludedCounterparties",control:t,defaultValue:s.excludedCounterparties,render:({field:a,fieldState:i})=>e.jsx(E,{...a,data:f,value:a.value??[],disabled:v,label:"Excluded Counterparties",placeholder:"Scroll to see all options",maxDropdownHeight:160,searchable:!0,error:i.error?.message,withinPortal:!0})}),e.jsx(y,{name:"includedTags",control:t,defaultValue:s.includedTags,render:({field:a,fieldState:i})=>e.jsx(E,{...a,data:l,value:a.value??[],disabled:j,label:"Included Tags",placeholder:"Scroll to see all options",maxDropdownHeight:160,searchable:!0,error:i.error?.message,withinPortal:!0})}),e.jsx(y,{name:"excludedTags",control:t,defaultValue:s.excludedTags,render:({field:a,fieldState:i})=>e.jsx(E,{...a,data:o,value:a.value??[],disabled:j,label:"Excluded Tags",placeholder:"Scroll to see all options",maxDropdownHeight:160,searchable:!0,error:i.error?.message,withinPortal:!0})})]}),e.jsxs("div",{className:"flex justify-center mt-5 gap-3",children:[e.jsx("button",{type:"submit",disabled:h,className:"text-white bg-indigo-500 border-0 py-2 px-8 focus:outline-hidden hover:bg-indigo-600 rounded-sm text-lg",children:"Filter"}),e.jsx("button",{type:"button",className:"text-white bg-rose-500 border-0 py-2 px-8 focus:outline-hidden hover:bg-rose-600 rounded-sm text-lg",onClick:c,children:"Cancel"})]})]})}function Te({filter:s,setFilter:n,initiallyOpened:c=!1}){const[t,r]=m.useState(c),[g,b]=m.useState(!!s),{get:h,set:f}=R();m.useEffect(()=>{const p=_(s),j=h(L);p!==j&&f(L,p)},[s,h,f]);const v=m.useCallback(p=>{V(p,s)||(n(p),b(!!p))},[s,n]);return e.jsxs("div",{className:"flex flex-row gap-5 items-center",children:[e.jsx(q,{opened:t,onClose:()=>r(!1),content:e.jsx(Ce,{filter:s,setFilter:v,closeModal:()=>r(!1)}),modalSize:"xl"}),e.jsx(Q,{inline:!0,size:16,disabled:!g,children:e.jsx(I,{variant:"outline",size:"icon",className:"size-7.5",onClick:()=>r(!0),children:e.jsx(z,{className:"size-5"})})})]})}const we=({period:s,transactionIDs:n,onCloseExtendedTransactions:c})=>{const[{data:t,fetching:r}]=P({query:W,variables:{transactionIDs:n}}),g=m.useMemo(()=>t?.transactionsByIDs?n.map(b=>t?.transactionsByIDs.find(h=>h.id===b)).filter(Boolean):[],[t,n]);return e.jsx(U,{className:"mt-5 w-full",children:r?e.jsx($,{}):e.jsxs(e.Fragment,{children:[e.jsx(Y,{children:e.jsxs(ee,{className:"flex justify-between",children:[e.jsxs("span",{children:[s," Transactions"]}),e.jsx(I,{variant:"link",onClick:c,children:e.jsx(ae,{className:"h-4 w-4"})})]})}),e.jsx(O,{children:e.jsx(se,{transactionsProps:g})})]})})};function Be(s){const n=new URLSearchParams,c=_(s);return c&&n.append(L,c),`/reports/balance${n.size>0?`?${n}`:""}`}const w={income:{label:"Income",color:"rgba(0, 255, 50, 0.5)"},expense:{label:"Expense",color:"rgba(255, 0, 0, 0.5)"},delta:{label:"Delta",color:"rgba(0, 30, 255, 0.5)"},cumulative:{label:"Cumulative Balance",color:"rgba(100, 0, 255, 0.5)"}};function Ne(s,n,c){switch(c){case x.MONTHLY:{const t=String(n).padStart(2,"0");return`${s}-${t}`}case x.BI_MONTHLY:{const t=n%2===0?n-1:n,r=String(t).padStart(2,"0");return`${s}-${r}`}case x.QUARTERLY:{const t=Math.ceil(n/3);return`${s}-Q${t}`}case x.SEMI_ANNUALLY:{const t=n>6?2:1;return`${s}-H${t}`}case x.ANNUALLY:return String(s)}}function Me(s,n){switch(n){case x.MONTHLY:{const[c,t]=s.split("-");return`${t}/${c}`}case x.BI_MONTHLY:{const[c,t]=s.split("-"),r=Number(t)+1,g=String(r).padStart(2,"0");return`${t}-${g}/${c}`}case x.QUARTERLY:{const[c,t]=s.split("-");return`${t}, ${c}`}case x.SEMI_ANNUALLY:{const[c,t]=s.split("-");return`${t}, ${c}`}case x.ANNUALLY:return s}}const D=ie(de.Usd),De=()=>{const{setFiltersContext:s}=m.useContext(te),{userContext:n}=m.useContext(re),{get:c}=R(),t=m.useMemo(()=>{const l={ownerId:n?.context.adminBusinessId,toDate:S(new Date,"yyyy-MM-dd"),period:x.MONTHLY,fromDate:S(ye(new Date,{years:1}),"yyyy-MM-dd"),excludedCounterparties:[],includedTags:[],excludedTags:[]},d=c(L);if(d)try{return JSON.parse(decodeURIComponent(d))}catch(o){console.log("Error parsing balance report filters from URL:",o)}return l},[n?.context.adminBusinessId,c]),[r,g]=m.useState(t),[b,h]=m.useState(void 0),[f,v]=m.useState(Object.keys(w)),p=m.useMemo(()=>{const{ownerId:l,fromDate:d,toDate:o}=r;return{ownerId:l,fromDate:d,toDate:o}},[r]),[{data:j,fetching:M}]=P({query:ce,variables:p,pause:!r});m.useEffect(()=>{s(e.jsxs("div",{className:"flex flex-row gap-x-5",children:[e.jsx(Te,{filter:r,setFilter:g,initiallyOpened:!r}),e.jsx(ne,{options:Object.entries(w).map(([l,d])=>({label:d.label,value:l})),onValueChange:v,defaultValue:f,placeholder:"Select Data Sets",variant:"default",maxCount:1})]})),h(void 0)},[j,M,r,s,g,f]),m.useEffect(()=>{g(l=>({...l,ownerId:n?.context.adminBusinessId}))},[n]);const C=m.useMemo(()=>{if(!j?.transactionsForBalanceReport)return[];const l=new Map;j.transactionsForBalanceReport.map(o=>{if(o.counterparty?.id&&(!o.isFee&&n?.context.financialAccountsBusinessesIds?.includes(o.counterparty.id)||r.excludedCounterparties?.includes(o.counterparty.id))||r.includedTags.length>0&&(!o.charge?.tags||o.charge.tags.length===0||!o.charge.tags.some(u=>r.includedTags.includes(u.id)))||r.excludedTags.length>0&&o.charge?.tags.length&&o.charge.tags.some(u=>r.excludedTags.includes(u.id)))return;const a=Ne(o.year,o.month,r.period);l.has(a)||l.set(a,{income:0,expense:0,delta:0,transactions:[]});const i=l.get(a);o.amountUsd.raw>0?i.income+=o.amountUsd.raw:i.expense+=o.amountUsd.raw,i.delta+=o.amountUsd.raw,i.transactions.push(o)});let d=0;return Array.from(l.entries()).sort((o,a)=>o[0].localeCompare(a[0])).map(([o,a])=>(d+=a.delta,{period:o,income:a.income,expense:a.expense,delta:a.delta,cumulative:d,transactions:a.transactions.sort((i,u)=>Math.abs(u.amountUsd.raw)-Math.abs(i.amountUsd.raw))}))},[j,r.period,r.excludedCounterparties,n?.context.financialAccountsBusinessesIds,r.includedTags,r.excludedTags]);return e.jsx(oe,{title:"Balance Report",description:"Accounts periodical balance",children:M?e.jsx($,{}):e.jsxs(e.Fragment,{children:[e.jsxs(U,{className:"w-full",children:[e.jsx(Y,{children:e.jsx(le,{children:"Click specific period to expand it's transactions data"})}),e.jsx(O,{children:e.jsx(xe,{config:w,className:"h-150 w-full",children:e.jsxs(ve,{accessibilityLayer:!0,data:C,onClick:l=>h(l.activeLabel),children:[e.jsx(ge,{vertical:!1}),e.jsx(H,{dataKey:"period",tickLine:!1,tickMargin:10,axisLine:!1,tickFormatter:l=>Me(l,r.period)}),e.jsx(he,{content:e.jsx(fe,{formatter:(l,d,o,a)=>{const i=`bg-[var(--color-${d})]`;return a<2?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`${i} h-2.5 w-2.5 shrink-0 rounded-[2px]`}),w[d]?.label||d,e.jsx("div",{className:"ml-auto flex items-baseline gap-0.5 font-mono font-medium tabular-nums text-foreground",children:D.format(Number(l))})]}):e.jsxs("div",{className:"mt-1.5 flex basis-full items-center border-t pt-1.5 text-xs font-medium text-foreground",children:[e.jsx("div",{className:`h-2.5 w-2.5 shrink-0 rounded-[2px] mr-2 ${i}`}),w[d]?.label||d,e.jsx("div",{className:"ml-auto flex items-baseline gap-0.5 font-mono font-medium tabular-nums text-foreground",children:D.format(Number(l))})]})}})}),e.jsx(be,{content:e.jsx(je,{})}),f.includes("income")&&e.jsx(N,{dataKey:"income",fill:"var(--color-income)",radius:4}),f.includes("expense")&&e.jsx(N,{dataKey:"expense",fill:"var(--color-expense)",radius:4}),f.includes("delta")&&e.jsx(N,{dataKey:"delta",fill:"var(--color-delta)",radius:4}),f.includes("cumulative")&&e.jsx(N,{dataKey:"cumulative",fill:"var(--color-cumulative)",radius:4})]})})})]}),b&&e.jsx(we,{period:b,onCloseExtendedTransactions:()=>h(void 0),transactionIDs:C.find(l=>l.period===b)?.transactions.map(l=>l.id)??[]})]})})};export{De as BalanceReport,Be as getBalanceReportHref};