@temboplus/afloat 0.1.77-beta.2 → 0.1.77-beta.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/lib/api/base-repository.d.ts +3 -1
- package/dist/lib/query/query.builder.d.ts +5 -1
- package/dist/modules/auth/auth.contract.d.ts +2 -2
- package/dist/modules/auth/company-membership.model.d.ts +122 -9
- package/dist/modules/auth/index.d.ts +0 -1
- package/dist/modules/auth/user.model.d.ts +238 -15
- package/dist/modules/contact/contact-info.model.d.ts +183 -533
- package/dist/modules/contact/contact.api-contract.d.ts +8 -8
- package/dist/modules/contact/contact.dtos.d.ts +2 -2
- package/dist/modules/contact/contact.model.d.ts +309 -32
- package/dist/modules/login/login.api-contract.d.ts +2 -2
- package/dist/modules/login/login.dtos.d.ts +4 -4
- package/dist/modules/login/login.model.d.ts +54 -24
- package/dist/modules/payout/payout.api-contract.d.ts +37 -37
- package/dist/modules/payout/payout.dtos.d.ts +47 -39
- package/dist/modules/payout/payout.model.d.ts +242 -2
- package/dist/modules/payout/payout.query.d.ts +11 -3
- package/dist/modules/payout/payout.repository.d.ts +48 -25
- package/dist/modules/profile/profile.model.d.ts +65 -30
- package/dist/modules/team-member/role.model.d.ts +49 -1
- package/dist/modules/team-member/team-member.contract.d.ts +44 -44
- package/dist/modules/team-member/team-member.dtos.d.ts +14 -14
- package/dist/modules/team-member/team-member.model.d.ts +106 -6
- package/dist/modules/wallet/index.d.ts +0 -1
- package/dist/modules/wallet/narration.model.d.ts +34 -38
- package/dist/modules/wallet/statement-entry.model.d.ts +172 -73
- package/dist/modules/wallet/wallet.contract.d.ts +6 -6
- package/dist/modules/wallet/wallet.dtos.d.ts +12 -12
- package/dist/modules/wallet/wallet.model.d.ts +56 -19
- package/dist/modules/wallet/wallet.query.d.ts +95 -0
- package/dist/modules/wallet/wallet.repository.d.ts +45 -13
- package/package.json +2 -2
- package/dist/modules/auth/auth.manager.d.ts +0 -249
- package/dist/modules/auth/auth.store.d.ts +0 -139
- package/dist/modules/auth/storage/client-store.d.ts +0 -29
- package/dist/modules/auth/storage/client-token-handler.d.ts +0 -31
- package/dist/modules/auth/storage/types.d.ts +0 -41
- package/dist/modules/wallet/wallet-manager.session.d.ts +0 -143
package/dist/index.esm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e,{z as t}from"zod";import{v4 as r}from"uuid";import{create as n,useStore as o}from"zustand";import{CurrencyValidation as a,CountryValidation as s,Currency as i,CurrencyCodesSet as c,ISO2CountryCodesSet as l,MNOUtils as d,PhoneNumber as u,PhoneNumberFormat as h,BankValidation as m,Bank as p,BankService as f,TZMobileNumber as y,Amount as g,Country as w,PhoneNumberFactory as b,TZMNOId as v}from"@temboplus/frontend-core";class N extends Error{statusCode;error;details;constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,this.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return N.schema.safeParse(e).success}static unknown(e){return new N({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return t.object({message:t.string(),statusCode:t.number().int(),error:t.string().optional(),details:t.object({}).optional()})}}const C={Profile:{ViewCurrent:"profile.getCurrent",Update:"profile.update"},Contact:{View:"contact.findById",List:"contact.findAll",Create:"contact.create",Update:"contact.update",Delete:"contact.delete"},Payment:{View:"payment.findById",List:"payment.findAll",Create:"payment.create"},Payout:{View:"payout.findById",List:"payout.findAll",Create:"payout.create",Approve:"payout.approve"},Transfer:{View:"transfer.findById",List:"transfer.findAll",Create:"transfer.create",Approve:"transfer.approve"},Wallet:{ViewBalance:"wallet.getBalance",ViewStatement:"wallet.getStatement"},Role:{ViewRoles:"role.findAll",ViewRole:"role.findById"},TeamManagement:{ViewMembers:"login.findAll",ViewMember:"login.findById",CreateMember:"login.create",UpdateMember:"login.update",ArchiveMember:"login.archive",UnArchiveMember:"login.unarchive",ResetPassword:"login.resetPassword"}};class A extends Error{requiredPermissions;constructor(e){super(e.message??`Missing required permissions: ${e.requiredPermissions.join(", ")}`),this.name="PermissionError",this.requiredPermissions=e.requiredPermissions}static is(e){const r=t.union([t.enum(Object.values(C.Profile)),t.enum(Object.values(C.Contact)),t.enum(Object.values(C.Payment)),t.enum(Object.values(C.Payout)),t.enum(Object.values(C.Transfer)),t.enum(Object.values(C.Wallet))]);return t.object({name:t.literal("PermissionError"),message:t.string(),requiredPermissions:t.array(r)}).safeParse(e).success}}function _(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message}const I=e=>"function"==typeof(null==e?void 0:e.passthrough);t.object({name:t.literal("ZodError"),issues:t.array(t.object({path:t.array(t.union([t.string(),t.number()])),message:t.string().optional(),code:t.nativeEnum(t.ZodIssueCode)}).catchall(t.any()))});const S=Symbol("ContractNoBody"),O=e=>"method"in e&&"path"in e,E=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,o,a,s,i;return O(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:(s=null==t?void 0:t.baseHeaders,i=r.headers,I(s)?I(i)?s.merge(i):s:I(i)?i:Object.assign({},s,i)),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(o=r.validateResponseOnClient)&&void 0!==o?o:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(a=r.metadata)&&void 0!==a?a:{}}:r.metadata}]:[e,E(r,t)]})),P=Symbol("ContractPlainType"),D=()=>({router:(e,t)=>E(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>P,body:()=>P,type:()=>P,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>S}),T=e=>e?Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r;return r="string"==typeof t&&!["true","false","null"].includes(t.trim())&&isNaN(Number(t))?t:JSON.stringify(t),`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).join("&"):"",R=e=>e?Object.keys(e).flatMap(t=>j(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",j=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>j(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>j(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class M extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const k=async({route:e,path:t,method:r,headers:n,body:o,validateResponse:a,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:n,body:o}),c=i.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t={status:i.status,body:await i.json(),headers:i.headers},r=e.responses[t.status];return(null!=a?a:e.validateResponseOnClient)&&"function"==typeof(null==(l=r)?void 0:l.safeParse)?{...t,body:r.parse(t.body)}:t}var l;return(null==c?void 0:c.includes("text/"))?{status:i.status,body:await i.text(),headers:i.headers}:{status:i.status,body:await i.blob(),headers:i.headers}},x=e=>{const t=new FormData,r=(e,r)=>{r instanceof File?t.append(e,r):t.append(e,JSON.stringify(r))};return Object.entries(e).forEach(([e,t])=>{if(Array.isArray(t))for(const n of t)r(e,n);else r(e,t)}),t},B=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),F=(e,t,r,n,o)=>{const a=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),s=((e,t=!1)=>{const r=t?T(e):R(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,o);return`${t}${a}${s}`},$=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const o=((e,t,r)=>{const{query:n,params:o,body:a,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:l,cache:d,next:u,...h}=r||{},m={...t,...c};return{path:F(n,m.baseUrl,o,e,!!m.jsonQuery),clientArgs:m,route:e,body:a,query:n,extraInputArgs:h,fetchOptions:{...d&&{cache:d},...u&&{next:u},...l},headers:{...i,...s}}})(e,t,n),a=await(e=>{const{path:t,clientArgs:r,route:n,body:o,query:a,extraInputArgs:s,headers:i,fetchOptions:c}=e,l=r.api||k,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),u={...d&&B(d),...B(i)};Object.keys(u).forEach(e=>{void 0===u[e]&&delete u[e]});let h={route:n,path:t,method:n.method,headers:u,body:void 0,rawBody:o,rawQuery:a,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?h={...h,contentType:"multipart/form-data",body:o instanceof FormData?o:x(o)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?h={...h,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...h.headers},body:"string"==typeof o?o:new URLSearchParams(o)}:null!=o&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(o)})),l({...h,...s})})(o);if(!t.throwOnUnknownStatus)return a;if(r.includes(a.status.toString()))return a;throw new M(a,r)}},U=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>O(r)?[e,$(r,t)]:[e,U(r,t)]));function L(e,t){let r;try{r=e()}catch(e){return}return{getItem:e=>{var n;const o=e=>null===e?null:JSON.parse(e,null==t?void 0:t.reviver),a=null!=(n=r.getItem(e))?n:null;return a instanceof Promise?a.then(o):o(a)},setItem:(e,n)=>r.setItem(e,JSON.stringify(n,null==t?void 0:t.replacer)),removeItem:e=>r.removeItem(e)}}const J=e=>t=>{try{const r=e(t);return r instanceof Promise?r:{then:e=>J(e)(r),catch(e){return this}}}catch(e){return{then(e){return this},catch:t=>J(t)(e)}}},q=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?("production"!==(import.meta.env?import.meta.env.MODE:void 0)&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),((e,t)=>(r,n,o)=>{let a={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},s=!1;const i=new Set,c=new Set;let l;try{l=a.getStorage()}catch(e){}if(!l)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),r(...e)},n,o);const d=J(a.serialize),u=()=>{const e=a.partialize({...n()});let t;const r=d({state:e,version:a.version}).then(e=>l.setItem(a.name,e)).catch(e=>{t=e});if(t)throw t;return r},h=o.setState;o.setState=(e,t)=>{h(e,t),u()};const m=e((...e)=>{r(...e),u()},n,o);let p;const f=()=>{var e;if(!l)return;s=!1,i.forEach(e=>e(n()));const t=(null==(e=a.onRehydrateStorage)?void 0:e.call(a,n()))||void 0;return J(l.getItem.bind(l))(a.name).then(e=>{if(e)return a.deserialize(e)}).then(e=>{if(e){if("number"!=typeof e.version||e.version===a.version)return e.state;if(a.migrate)return a.migrate(e.state,e.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}}).then(e=>{var t;return p=a.merge(e,null!=(t=n())?t:m),r(p,!0),u()}).then(()=>{null==t||t(p,void 0),s=!0,c.forEach(e=>e(p))}).catch(e=>{null==t||t(void 0,e)})};return o.persist={setOptions:e=>{a={...a,...e},e.getStorage&&(l=e.getStorage())},clearStorage:()=>{null==l||l.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>f(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e)})},f(),p||m})(e,t)):((e,t)=>(r,n,o)=>{let a={storage:L(()=>localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},s=!1;const i=new Set,c=new Set;let l=a.storage;if(!l)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),r(...e)},n,o);const d=()=>{const e=a.partialize({...n()});return l.setItem(a.name,{state:e,version:a.version})},u=o.setState;o.setState=(e,t)=>{u(e,t),d()};const h=e((...e)=>{r(...e),d()},n,o);let m;o.getInitialState=()=>h;const p=()=>{var e,t;if(!l)return;s=!1,i.forEach(e=>{var t;return e(null!=(t=n())?t:h)});const o=(null==(t=a.onRehydrateStorage)?void 0:t.call(a,null!=(e=n())?e:h))||void 0;return J(l.getItem.bind(l))(a.name).then(e=>{if(e){if("number"!=typeof e.version||e.version===a.version)return[!1,e.state];if(a.migrate)return[!0,a.migrate(e.state,e.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}return[!1,void 0]}).then(e=>{var t;const[o,s]=e;if(m=a.merge(s,null!=(t=n())?t:h),r(m,!0),o)return d()}).then(()=>{null==o||o(m,void 0),m=n(),s=!0,c.forEach(e=>e(m))}).catch(e=>{null==o||o(void 0,e)})};return o.persist={setOptions:e=>{a={...a,...e},e.storage&&(l=e.storage)},clearStorage:()=>{null==l||l.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>p(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e)})},a.skipHydration||p(),m||h})(e,t),W={profileDTOSchema:t.object({id:t.string(),firstName:t.string().nullish(),lastName:t.string().nullish(),displayName:t.string(),phone:t.string().nullish(),accountNo:t.string().min(1),email:t.string().email().nullish(),autoApprove:t.boolean().nullish()})};class z{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return W.profileDTOSchema}constructor(e){this._id=e.id,this._firstName=e.firstName,this._lastName=e.lastName,this._displayName=e.displayName,this._phone=e.phone,this._accountNo=e.accountNo,this._email=e.email,this._autoApprove=e.autoApprove}static create(e){return new z({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove})}get id(){return this._id}get firstName(){return this._firstName}get lastName(){return this._lastName}get displayName(){return this._displayName}get phone(){return this._phone}get accountNo(){return this._accountNo}get email(){return this._email}get autoApprove(){return this._autoApprove}getName(){if(this._displayName&&""!==this._displayName.trim())return this._displayName;return`${this._firstName??""} ${this._lastName??""}`.trim()}toObject(){return{id:this._id,firstName:this._firstName,lastName:this._lastName,displayName:this._displayName,phone:this._phone,accountNo:this._accountNo,email:this._email,autoApprove:this._autoApprove}}toJSON(){return JSON.stringify(this.toObject())}validate(){try{return z.schema.safeParse(this.toObject()).success}catch(e){return console.error("Profile validation error:",e),!1}}static fromJSON(e){try{const t=JSON.parse(e);return z.from(t)}catch(e){return void console.error("Error parsing profile JSON:",e)}}static from(e){try{return e?"object"!=typeof e?void console.error("Data is not an object"):e.id&&e.accountNo&&e.displayName?z.create({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove}):void console.error("Missing required profile fields"):void console.error("Data is null or undefined")}catch(e){return void console.error("Error creating profile from object:",e)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t._id||"string"!=typeof t._displayName||"string"!=typeof t._accountNo)return!1;if(null!==t._firstName&&void 0!==t._firstName&&"string"!=typeof t._firstName)return!1;if(null!==t._lastName&&void 0!==t._lastName&&"string"!=typeof t._lastName)return!1;if(null!==t._email&&void 0!==t._email&&"string"!=typeof t._email)return!1;const r=t._phone;if(null!=r&&"string"!=typeof r)return!1;const n=t._autoApprove;return null==n||"boolean"==typeof n}}const V={loginDTO:e.object({id:e.string().min(1,"ID is required"),profileId:e.string().min(1,"Profile ID is required"),name:e.string().min(1,"Name is required"),identity:e.string().email("Identity must be a valid email address"),type:e.string().min(1,"Type is required"),roleId:e.string().min(1,"Role ID is required"),isActive:e.boolean(),isArchived:e.boolean(),resetPassword:e.boolean(),createdAt:e.string().datetime("Invalid creation timestamp"),updatedAt:e.string().datetime("Invalid update timestamp"),access:e.array(e.string())})};class G{_id;_profileId;_name;_identity;_type;_roleId;_isActive;_isArchived;_resetPassword;_createdAt;_updatedAt;_access;constructor(e,t,r,n,o,a,s,i,c,l,d,u){this._id=e,this._profileId=t,this._name=r,this._identity=n,this._type=o,this._roleId=a,this._isActive=s,this._isArchived=i,this._resetPassword=c,this._createdAt=l,this._updatedAt=d,this._access=u}static from(e){const t=V.loginDTO.parse(e);return new G(t.id,t.profileId,t.name,t.identity,t.type,t.roleId,t.isActive,t.isArchived,t.resetPassword,new Date(t.createdAt),new Date(t.updatedAt),t.access)}static fromJson(e){try{const t=JSON.parse(e);return G.from(t)}catch(e){return void console.error("Error parsing LogIn JSON:",e)}}get id(){return this._id}get profileId(){return this._profileId}get name(){return this._name}get identity(){return this._identity}get type(){return this._type}get roleId(){return this._roleId}get isActive(){return this._isActive}get isArchived(){return this._isArchived}get resetPassword(){return this._resetPassword}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get access(){return this._access}toObject(){return{id:this._id,profileId:this._profileId,name:this._name,identity:this._identity,type:this._type,roleId:this._roleId,isActive:this._isActive,isArchived:this._isArchived,resetPassword:this._resetPassword,createdAt:this._createdAt.toISOString(),updatedAt:this._updatedAt.toISOString(),access:[...this._access]}}toJson(){return JSON.stringify(this.toObject())}}class H{_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return z.is(e.companyProfile)?new H(e):void console.error("Invalid company profile")}catch(e){return void console.error("Error creating CompanyMembership:",e)}}get companyProfile(){return this._companyProfile}get role(){return this._role}toObject(){return{companyProfile:this._companyProfile.toObject(),role:this._role?.toJSON()}}toJson(){return JSON.stringify(this.toObject())}}class Q{id;name;description;permissions;createdAt;updatedAt;constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.permissions=new Set(e.access),this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}hasPermission(e){return this.permissions.has(e)}static from(e){try{if(!e?.id||!e?.name||!Array.isArray(e?.access))return;return new Q(e)}catch(e){return void console.error("Error creating Role:",e)}}toJSON(){return{id:this.id,name:this.name,description:this.description,access:Array.from(this.permissions),createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}}class K{_logIn;_membership;_token;_permissionMap;constructor(e){this._logIn=e.logIn,this._membership=e.membership,this._token=e.token,this._permissionMap={},this._logIn.access.forEach(e=>{this._permissionMap[e]=!0})}static from(e){try{if(!e.logIn||!e.companyProfile||!e.token)return void console.error("Missing required User fields");if("string"!=typeof e.token||""===e.token.trim())return void console.error("Invalid token");const t=H.from({companyProfile:e.companyProfile,role:e.role});return t?new K({logIn:e.logIn,membership:t,token:e.token}):void console.error("Failed to create CompanyMembership")}catch(e){return void console.error("Error creating User:",e)}}static fromJson(e){try{const t=JSON.parse(e),r=G.from(t.logIn),n=z.from(t.companyProfile||t.profile),o=t.role?Q.from(t.role):void 0;return r&&n?K.from({logIn:r,companyProfile:n,role:o,token:t.token}):void console.error("Failed to reconstruct nested objects")}catch(e){return void console.error("Error parsing User JSON:",e)}}get logIn(){return this._logIn}get membership(){return this._membership}get token(){return this._token}get id(){return this._logIn.id}get name(){return this._logIn.name}get identity(){return this._logIn.identity}get roleId(){return this._logIn.roleId}get resetPassword(){return this._logIn.resetPassword}get profile(){return this._membership.companyProfile}get role(){return this._membership.role}get access(){return this._logIn.access}can(e){return this._permissionMap[e]??!1}canAny(e){return e.some(e=>this.can(e))}canAll(e){return e.every(e=>this.can(e))}canManageTeam(){return this.can(C.TeamManagement.ViewMembers)}canViewRoles(){return this.can(C.Role.ViewRole)}toObject(){return{logIn:this._logIn.toObject(),profile:this._membership.companyProfile.toObject(),role:this._membership.role?.toJSON(),token:this._token,access:[...this._logIn.access],resetPassword:this._logIn.resetPassword}}toJson(){return JSON.stringify(this.toObject())}}const Z=n(q((e,t)=>({user:void 0,token:void 0,getUser:()=>{try{const e=t().user;if(e)return K.fromJson(e)}catch(e){console.warn("Failed to deserialize user from store:",e)}},setUser:t=>{try{e({user:t.toJson()})}catch(e){console.error("Failed to serialize user to store:",e)}},getToken:()=>t().token,setToken:t=>e({token:t}),setUserAndToken:(t,r)=>{try{e({user:t.toJson(),token:r})}catch(e){console.error("Failed to serialize user and token to store:",e)}},clearAuth:()=>e({user:void 0,token:void 0})}),{name:"auth-store",storage:L(()=>"undefined"==typeof window?{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}:sessionStorage)})),Y=()=>{if("undefined"!=typeof window)return Z.getState().getToken()};class X{contract;endpoint;root;token;constructor(e,t,r){this.contract=t,this.endpoint=e,this.root=r?.root,this.token=r?.token}getToken(){if(this.token&&this.token.trim().length>0)return this.token;try{const e=Y();if(e&&e.trim().length>0)return e;console.warn(`No token available from global auth state for ${this.endpoint} repository`)}catch(e){console.warn(`No valid token available for ${this.endpoint} repository. Please provide a token directly in the constructor or ensure a user is logged in via AfloatAuth.instance.`)}return""}get client(){const e={baseUrl:this.root?`${this.root}/${this.endpoint}`:`https://api.afloat.money/v1/${this.endpoint}`,baseHeaders:{token:this.getToken(),"x-request-id":r()}};return U(this.contract,e)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(t,r){if(t.status===r)return t.body;if(400===t.status){const r=e.object({statusCode:e.number(),message:e.string(),error:e.string(),details:e.record(e.string()).optional()}).safeParse(t.body);if(r.success)throw new N(r.data);throw new N({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===t.status)throw new N({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===t.status)throw new N({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===t.status)throw new N({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new N({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}var ee,te;!function(e){e.EQUALS="eq",e.NOT_EQUALS="neq",e.LESS_THAN="lt",e.LESS_THAN_OR_EQUAL="lte",e.GREATER_THAN="gt",e.GREATER_THAN_OR_EQUAL="gte",e.LIKE="like",e.LIKE_LOWER="likeLower",e.IS_NULL="isNull",e.IS_NOT_NULL="isNotNull",e.IN="in"}(ee||(ee={})),function(e){e.ASC="asc",e.DESC="desc"}(te||(te={}));const re=Symbol("query-builder-type");class ne{options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8};constructor(e={}){this.options={filters:e.filters||[],sort:e.sort||[],includes:e.includes||[],groupBy:e.groupBy||[],join:e.join||[],page:e.page,limit:e.limit}}[re]="query-builder";static is(e){return null!==e&&"object"==typeof e&&re in e&&"query-builder"===e[re]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:ee.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:ee.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:ee.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:ee.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:ee.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:ee.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:ee.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:ee.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:ee.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:ee.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:ee.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:ee.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:ee.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:ee.LESS_THAN_OR_EQUAL,value:t})}whereBetween(e,t,r){return this.whereGreaterThanOrEqual(e,t).whereLessThanOrEqual(e,r)}whereDateBetween(e,t){return e&&this.whereGreaterThanOrEqual("createdAt",e),t&&this.whereLessThanOrEqual("createdAt",t),this}addSort(e){return this.options.sort=[...this.options.sort||[],e],this}orderBy(e,t=te.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,te.ASC)}orderByDesc(e){return this.orderBy(e,te.DESC)}paginate(e,t){return this.options.page=e,this.options.limit=t,this}with(e){const t=Array.isArray(e)?e:[e];return this.options.includes=[...this.options.includes||[],...t],this}join(e){const t=Array.isArray(e)?e:[e];return this.options.join=[...this.options.join||[],...t],this}groupBy(e){const t=Array.isArray(e)?e:[e];return this.options.groupBy=[...this.options.groupBy||[],...t],this}count(e="*"){return this.options.count=e,this}countAs(e,t){return this.options.count=`${e} as ${t}`,this}build(){const e={};if(void 0!==this.options.page&&void 0!==this.options.limit){const t=(this.options.page-1)*this.options.limit,r=t+this.options.limit-1;e.rangeStart=t,e.rangeEnd=r}if(this.options.filters&&this.options.filters.length>0)for(const t of this.options.filters)switch(t.operator){case ee.IS_NULL:e[`${t.field}:isNull`]=1;break;case ee.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case ee.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case ee.LIKE:e[`${t.field}:like`]=t.value;break;case ee.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case ee.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case ee.LESS_THAN_OR_EQUAL:e[`${t.field}:lte`]=t.value;break;default:e[`${t.field}:${t.operator}`]=t.value}if(this.options.sort&&this.options.sort.length>0){const t=[],r=[];for(const e of this.options.sort)e.direction===te.ASC?t.push(e.field):r.push(e.field);t.length>0&&(e.orderBy=t.join(",")),r.length>0&&(e.orderByDesc=r.join(","))}const t=this.options.filters?.filter(e=>"createdAt"===e.field&&(e.operator===ee.GREATER_THAN_OR_EQUAL||e.operator===ee.LESS_THAN_OR_EQUAL));if(t){const r=t.find(e=>e.operator===ee.GREATER_THAN_OR_EQUAL),n=t.find(e=>e.operator===ee.LESS_THAN_OR_EQUAL);r&&(e.startDate=r.value),n&&(e.endDate=n.value)}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?e.eager=this.options.includes[0]:e.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(e.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(e.groupBy=this.options.groupBy.join(",")),this.options.count&&(e.count=this.options.count),e}clone(){return new(0,this.constructor)({...this.options,filters:this.options.filters?[...this.options.filters]:[],sort:this.options.sort?[...this.options.sort]:[],includes:this.options.includes?[...this.options.includes]:[],groupBy:this.options.groupBy?[...this.options.groupBy]:[],join:this.options.join?[...this.options.join]:[]})}static create(e){return new ne(e)}}const oe=t.object({page:t.coerce.number().int().min(1).default(1),limit:t.coerce.number().int().min(1).max(100).default(10)}),ae=t.object({page:t.number().int().min(1),limit:t.number().int().min(1),total:t.number().int().min(0),totalPages:t.number().int().min(0),hasNext:t.boolean(),hasPrev:t.boolean()});function se(e){return t.object({results:t.array(e),pagination:ae})}class ie{page;limit;total;constructor(e,t,r){if(this.page=e,this.limit=t,this.total=r,e<1)throw new Error("Page must be >= 1");if(t<1)throw new Error("Limit must be >= 1");if(r<0)throw new Error("Total must be >= 0")}get totalPages(){return Math.ceil(this.total/this.limit)}get hasNext(){return this.page<this.totalPages}get hasPrev(){return this.page>1}get offset(){return(this.page-1)*this.limit}get isFirstPage(){return 1===this.page}get isLastPage(){return this.page===this.totalPages}nextPage(){return this.hasNext?new ie(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new ie(this.page-1,this.limit,this.total):null}toJSON(){return{page:this.page,limit:this.limit,total:this.total,totalPages:this.totalPages,hasNext:this.hasNext,hasPrev:this.hasPrev}}}function ce(e,t,r,n){return{results:e,pagination:new ie(t,r,n)}}function le(e=1,t=10){return{results:[],pagination:new ie(e,t,0)}}const de=e=>e.optional().transform(e=>e??void 0),ue={walletDTO:t.object({id:t.string().min(1,{message:"Wallet ID is required."}),profileId:t.string().min(1,{message:"Profile ID is required."}),accountNo:t.string().min(1,{message:"Account number is required."}),accountName:t.string().min(1,{message:"Account name is required."}),channel:t.string().min(1,{message:"Channel is required."}),countryCode:t.string().default("TZ").refine(e=>s.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.string().default("TZS").refine(e=>a.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:t.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:t.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:t.object({id:t.string().optional(),profileId:t.string().optional(),accountNo:t.string().optional(),accountName:t.string().optional(),channel:t.string().optional(),countryCode:t.string().default("TZ").refine(e=>l.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:t.string().default("TZS").refine(e=>{const t=i.from(e);return void 0!==t&&c.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:t.object({accountNo:de(t.string()),debitOrCredit:t.string().min(1,"Transaction type is required"),tranRefNo:t.string().min(1,"Transaction reference is required"),narration:t.string().min(1,"Transaction description is required"),txnDate:t.coerce.date({errorMap:()=>({message:"Invalid transaction date format"})}),valueDate:t.coerce.date({errorMap:()=>({message:"Invalid value date format"})}),amountCredited:t.number().min(0,"Credited amount must be non-negative"),amountDebited:t.number().min(0,"Debited amount must be non-negative"),balance:t.number(),currencyCode:de(t.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})};class he{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return ue.walletDTO}constructor(e){this._id=e.id,this._profileId=e.profileId,this._accountNo=e.accountNo,this._accountName=e.accountName,this._channel=e.channel,this._countryCode=e.countryCode,this._currencyCode=e.currencyCode,this._createdAt=e.createdAt,this._updatedAt=e.updatedAt}static create(e){const t=he.schema.safeParse(e);if(t.success)return new he(t.data);console.error("Wallet data validation failed:",t.error.flatten())}get id(){return this._id}get profileId(){return this._profileId}get accountNo(){return this._accountNo}get accountName(){return this._accountName}get channel(){return this._channel}get countryCode(){return this._countryCode}get currencyCode(){return this._currencyCode}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get createdAtDate(){return new Date(this._createdAt)}get updatedAtDate(){return new Date(this._updatedAt)}toObject(){return{id:this._id,profileId:this._profileId,accountNo:this._accountNo,accountName:this._accountName,channel:this._channel,countryCode:this._countryCode,createdAt:this._createdAt,updatedAt:this._updatedAt,currencyCode:this._currencyCode}}toJSON(){return JSON.stringify(this.toObject())}validate(){const e=he.schema.safeParse(this.toObject());return e.success||console.warn("Wallet instance validation failed:",e.error.flatten()),e.success}static fromJSON(e){try{const t=JSON.parse(e);return he.from(t)}catch(e){return void console.error("Error parsing wallet JSON:",e)}}static from(e){if(e&&"object"==typeof e)return he.create({id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt,currencyCode:e.currencyCode});console.error("Invalid data provided to Wallet.from: Input must be an object.")}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.profileId&&"string"==typeof t.accountNo&&"string"==typeof t.accountName&&"string"==typeof t.channel&&"string"==typeof t.countryCode&&s.isISO2CountryCode(t.countryCode)&&"string"==typeof t.currencyCode&&a.isCurrencyCode(t.currencyCode)&&"string"==typeof t.createdAt&&"string"==typeof t.updatedAt&&"function"==typeof t.toObject&&"function"==typeof t.validate}}const me={getUniqueCountries(e){const t=new Set;return e.forEach(e=>{e.countryCode&&t.add(e.countryCode)}),Array.from(t)},getWalletsByCountry:(e,t)=>e.filter(e=>e.countryCode===t)};var pe;!function(e){e.Bank="Bank",e.Mobile="Mobile"}(pe||(pe={}));const fe=t.nativeEnum(pe),ye=t.object({displayName:t.string().min(1,"Display name is required"),accountNo:t.string().min(1,"Account number is required"),channel:t.string().min(1,"Channel is required"),type:fe}),ge={contactDTO:t.object({id:t.string().min(1,"Contact id is required"),profileId:t.string(),createdAt:t.string().datetime(),updatedAt:t.string().datetime()}).merge(ye),contactInputDTO:ye,contactType:fe};class we extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="ContactInfoError"}}class be{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}}class ve extends be{name;phoneNumber;mnoId;constructor(e,t,r){if(super(pe.Mobile,t.countryCode),this.name=e,this.phoneNumber=t,!e?.trim())throw new we("Name is required and cannot be empty",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(!t?.validate())throw new we("Invalid phone number",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(d.requiresExplicitMNO(t.countryCode)){if(!r)throw new we(`MNO must be explicitly provided for phone numbers in ${t.countryCode} due to Mobile Number Portability`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});if(!d.isValidMNOForCountry(r,t.countryCode)){const e=d.getCountryMNOs(t.countryCode).map(e=>e.id);throw new we(`Invalid MNO ${r} for country ${t.countryCode}. Valid MNOs: ${e.join(", ")}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,mnoId:r,operation:"constructor"})}this.mnoId=r}else{const e=d.getMNOByPhoneNumber(t.e164Format,t.countryCode);if(!e?.id)throw new we(`Failed to determine MNO for phone number ${t.e164Format}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});this.mnoId=e.id}}static fromContactDTO(e){if("Mobile"!==e.type)return;let t=e.accountNo;t.startsWith("+")||(t=`+${t}`);const r=u.from(t);if(!r)return void console.error(`Failed to parse phone number ${t}`);const n=r.countryCode;try{let t;if(d.requiresExplicitMNO(n)){if(e.channel&&"string"==typeof e.channel){if(!d.isValidMNOForCountry(e.channel,n))return void console.warn(`Invalid MNO ${e.channel} for country ${n}`);t=e.channel}}else if(t=d.getMNOByPhoneNumber(r.e164Format,n)?.id,!t)return void console.warn(`Failed to auto-detect MNO for phone number ${r.e164Format}`);return new ve(e.displayName,r,t)}catch(e){return void console.error(`Failed to create MobileContactInfo: ${e}`)}}static fromPayoutDTO(e){try{if(!s.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=u.from(e.msisdn,{defaultCountry:e.countryCode});if(!t)return void console.error(`Failed to parse phone number: ${e.msisdn}`);let r;if(d.requiresExplicitMNO(t.countryCode)){if(e.channel&&"string"==typeof e.channel){if(!d.isValidMNOForCountry(e.channel,t.countryCode))return void console.warn(`Invalid MNO ${e.channel} for country ${t.countryCode} in PayoutDTO`);r=e.channel}}else if(r=d.getMNOByPhoneNumber(t.e164Format,t.countryCode)?.id,!r)return void console.warn(`Failed to auto-detect MNO for phone number ${t.e164Format}`);return new ve(e.payeeName,t,r)}catch(t){return void console.error("Failed to create MobileContactInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.name||!t.name.trim())return!1;let r;if("string"==typeof t.phoneNumber)r=u.from(t.phoneNumber);else if("object"==typeof t.phoneNumber){const e=t.phoneNumber;u.is(e)&&(r=u.from(e.e164Format))}if(!r)return!1;const n=t.mnoId;if("string"!=typeof n)return!1;if(!d.isValidMNOForCountry(n,r.countryCode))return!1;if(d.requiresExplicitMNO(r.countryCode))return!0;{const e=d.getMNOByPhoneNumber(r.e164Format,r.countryCode);return e?.id===n}}validate(){try{return!!this.name?.trim()&&(!!this.phoneNumber?.validate()&&(!!d.isValidMNOForCountry(this.mnoId,this.countryCode)&&(!!d.requiresExplicitMNO(this.countryCode)||d.validateMNOForPhoneNumber(this.phoneNumber.e164Format,this.mnoId,this.countryCode))))}catch{return!1}}getValidationDetails(){const e=[];if(this.name?.trim()||e.push("Name is required"),this.phoneNumber?.validate()||e.push("Phone number is invalid"),d.isValidMNOForCountry(this.mnoId,this.countryCode)||e.push(`Invalid MNO ${this.mnoId} for country ${this.countryCode}`),!d.requiresExplicitMNO(this.countryCode)){const t=d.getMNOByPhoneNumber(this.phoneNumber.e164Format,this.countryCode);t?.id!==this.mnoId&&e.push("MNO doesn't match auto-detected value from phone number prefix")}return{isValid:0===e.length,errors:e,warnings:[]}}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(h.E164)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){const e=d.getMNOById(this.mnoId,this.countryCode);return e?.mobileMoneyService??e?.displayName??this.mnoId}}class Ne extends be{accName;bank;accNo;constructor(e,t,r){if(super(pe.Bank,t.countryCode),this.accName=e,this.bank=t,this.accNo=r,!m.validateAccountName(e))throw new we("Invalid account name",{operation:"constructor",countryCode:t.countryCode});if(!m.validateAccountNumber(r,t.countryCode))throw new we("Invalid account number",{operation:"constructor",countryCode:t.countryCode})}static fromContactDTO(e){if("Bank"!==e.type)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank contacts");const r=m.getCountryFromSwiftCode(t);if(r)if(m.validateSwiftCode(t,r))try{const n=p.from(t,r);if(!n)throw new Error(`Bank with SWIFT code ${t} not found`);return new Ne(e.displayName,n,e.accountNo)}catch(e){return void console.error(`Failed to create BankContactInfo: ${e}`)}else console.error(`Invalid SWIFT code ${t} for country ${r}`);else console.error(`Could not identify country from SWIFT code: ${t}`)}static fromPayoutDTO(e){try{if(!s.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=e.msisdn.trim().split(":");if(2!==t.length)return void console.error("Invalid PayoutDTO format for bank - expected 'swiftcode:accountno'");const[r,n]=t;if(!m.validateSwiftCode(r,e.countryCode))return void console.error(`Invalid SWIFT code ${r} for country ${e.countryCode}`);const o=p.from(r,e.countryCode);return o?new Ne(e.payeeName,o,n):void console.error(`Bank with SWIFT code ${r} not found`)}catch(t){return void console.error("Failed to create BankContactInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.accName)return!1;if("string"!=typeof t.accNo)return!1;if(!t.bank||!p.is(t.bank))return!1;const r=t.accName,n=t.accNo,o=t.bank,a=m.validateAccountName(r),s=m.validateAccountNumber(n,o.countryCode);return a&&s}validate(){try{return m.validateAccountName(this.accName)&&m.validateAccountNumber(this.accNo,this.bank.countryCode)&&p.is(this.bank)}catch{return!1}}get accountName(){return this.accName}get accountNumber(){return this.accNo}get accountNameLabel(){return"Acc. Name"}get accountNumberLabel(){return"Bank Acc. No."}get channelLabel(){return"Bank"}get channelId(){return this.bank.swiftCode}get channelName(){return this.bank.shortName}}const Ce="MOBILE TRANSFER ",Ae="PAYOUT",_e="PAYOUT TO BANK",Ie="TO_BANK",Se="PAYOUT TO MOBILE",Oe="TO_MOMO";class Ee{text;constructor(e){this.text=e}get mediumText(){return this.text.length>50?this.text.substring(0,47)+"...":this.text}get shortText(){return this.text.length>35?this.text.substring(0,32)+"...":this.text}static generateDefaultPayoutNarration(e){return ve.is(e)?Ee.generateMobilePayoutNarrationV2(e):Ne.is(e)?Ee.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${Ae.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:n}=e;return`${Ae.toUpperCase()} ${t.swiftCode.trim()} ${n.trim()} ${r.trim()}`.toUpperCase()}getContactDetails=()=>{const e=this.getBankContactDetails(),t=this.getMobileContactDetails();return e||(t||void 0)};getBankContactDetails=()=>{let e=this.text.trim();e.startsWith(Ce)&&(e=e.substring(16));try{if(e.startsWith(Ae)){const t=e.replace(Ae,"").trim().split(" ");if(t.length>=3){const e=t[0],r=t[1],n=t.slice(2).map(Pe).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=m.getCountryFromSwiftCode(e);if(t){if(m.validateSwiftCode(e,t)){const o=p.from(e,t);if(r&&n&&o)return new Ne(n,o,r)}}}}}if(e.startsWith(Ie)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=r.account_number,o=r.account_name,a=r.swift_code,s=m.getCountryFromSwiftCode(a);if(!s)return;if(!m.validateSwiftCode(a,s))return;const i=p.from(a,s);if(n&&o&&i)return new Ne(o,i,n)}if(e.startsWith(_e)){const t=e.replace(_e,"").trim().split(" "),r=f.getInstance().searchBanks("TZ",t[0]),n=r.length>0?r[0]:void 0,o=t[1],a=t.slice(2).map(Pe).join(" ");if(a&&o&&n)return new Ne(a,n,o)}}catch(e){return}};getMobileContactDetails=()=>{let e=this.text.trim();e.startsWith(Ce)&&(e=e.substring(16));try{if(e.startsWith(Ae)){const t=e.replace(Ae,"").trim().split(" ");if(t.length>=2){const e=t[0],r=t.slice(1).map(Pe).join(" ");if(e.startsWith("+")){const t=u.from(e);if(t&&r)return new ve(r,t)}}}if(e.startsWith(Oe)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=y.from(r.phone_number);let o=r.username;void 0===o&&(o="");let a=o.split(" ");if(a=a.filter(e=>e.trim().length>0),o=a.map(Pe).join(" "),n&&o)return new ve(o,n)}if(e.startsWith(Se)){const t=e.replace(Se,"").trim().split(" "),r=y.from(t[0]),n=t.slice(1).map(Pe).join(" ");if(r&&n)return new ve(n,r)}}catch(e){return}};toJson(){return{text:this.text,version:"2.0"}}static fromJson(e){try{let t;return t="string"==typeof e?JSON.parse(e):e,t&&"object"==typeof t&&"string"==typeof t.text?new Ee(t.text):void console.warn("Invalid NarrationJson: missing or invalid text property")}catch(e){return void console.error("Error parsing NarrationJson:",e)}}static isNarrationJson(e){if(!e||"object"!=typeof e)return!1;return"string"==typeof e.text}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;try{return"string"==typeof t.text&&"function"==typeof t.getContactDetails&&"function"==typeof t.toJson}catch(e){return!1}}}function Pe(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}class De{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return ue.statementEntry}constructor(e,t){this._accountNo=e.accountNo,this._debitOrCredit=e.debitOrCredit,this._tranRefNo=e.tranRefNo,this._narration=t,this._txnDate=e.txnDate,this._valueDate=e.valueDate,this._currencyCode=e.currencyCode;const r=i.from(e.currencyCode);if(!r)throw new Error(`Currency not found for code: ${e.currencyCode}`);const n=g.from(e.amountCredited,r.code),o=g.from(e.amountDebited,r.code),a=g.from(e.balance,r.code);if(!n||!o||!a)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=n,this._amountDebited=o,this._balance=a}static create(e){const t="string"==typeof e.narration?new Ee(e.narration):e.narration,r={...e,narration:t.text},n=De.schema.safeParse(r);if(n.success)try{const{narration:e,...r}=n.data;return new De(r,t)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",n.error.flatten())}get accountNo(){return this._accountNo}get debitOrCredit(){return this._debitOrCredit}get tranRefNo(){return this._tranRefNo}get narration(){return this._narration}get txnDate(){return this._txnDate}get valueDate(){return this._valueDate}get amountCredited(){return this._amountCredited}get amountDebited(){return this._amountDebited}get balance(){return this._balance}get currencyCode(){return this._currencyCode}toJson(){return{accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.toJson(),txnDate:this._txnDate.toISOString(),valueDate:this._valueDate.toISOString(),amountCredited:this._amountCredited.toJson(),amountDebited:this._amountDebited.toJson(),balance:this._balance.toJson(),currencyCode:this._currencyCode,version:"2.0"}}static fromJson(e){try{let t;if(t="string"==typeof e?JSON.parse(e):e,!(t&&"object"==typeof t&&"string"==typeof t.debitOrCredit&&"string"==typeof t.tranRefNo&&t.narration&&"string"==typeof t.txnDate&&"string"==typeof t.valueDate&&"string"==typeof t.currencyCode&&t.amountCredited&&t.amountDebited&&t.balance))return void console.warn("Invalid WalletStatementEntryJson: missing or invalid required properties");const r=Ee.fromJson(t.narration);if(!r)return void console.warn("Invalid WalletStatementEntryJson: failed to deserialize narration");const n=g.fromJson(t.amountCredited),o=g.fromJson(t.amountDebited),a=g.fromJson(t.balance);return n&&o&&a?n.currencyCode!==t.currencyCode||o.currencyCode!==t.currencyCode||a.currencyCode!==t.currencyCode?void console.warn("Invalid WalletStatementEntryJson: currency code mismatch"):De.create({accountNo:t.accountNo,debitOrCredit:t.debitOrCredit,tranRefNo:t.tranRefNo,narration:r,txnDate:t.txnDate,valueDate:t.valueDate,amountCredited:n.numericValue,amountDebited:o.numericValue,balance:a.numericValue,currencyCode:t.currencyCode}):void console.warn("Invalid WalletStatementEntryJson: failed to deserialize Amount objects")}catch(e){return void console.error("Error parsing WalletStatementEntryJson:",e)}}static isWalletStatementEntryJson(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.debitOrCredit&&"string"==typeof t.tranRefNo&&Ee.isNarrationJson(t.narration)&&"string"==typeof t.txnDate&&"string"==typeof t.valueDate&&"string"==typeof t.currencyCode&&(void 0===t.accountNo||"string"==typeof t.accountNo)&&g.isAmountJson(t.amountCredited)&&g.isAmountJson(t.amountDebited)&&g.isAmountJson(t.balance)}validate(){const e={accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.text,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode},t=De.schema.safeParse(e);return t.success||console.warn("WalletStatementEntry instance validation failed:",t.error.flatten()),t.success}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;try{return("string"==typeof t.accountNo||void 0===t.accountNo)&&"string"==typeof t.debitOrCredit&&"string"==typeof t.tranRefNo&&Ee.is(t.narration)&&t.txnDate instanceof Date&&t.valueDate instanceof Date&&g.is(t.amountCredited)&&g.is(t.amountDebited)&&g.is(t.balance)&&"string"==typeof t.currencyCode&&"function"==typeof t.toJson&&"function"==typeof t.validate}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return De.create({accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode})}toString(){return`WalletStatementEntry(${this._tranRefNo}: ${this._debitOrCredit} ${this._amountCredited.isPositive()?this._amountCredited.label:this._amountDebited.label} on ${this._txnDate.toISOString().split("T")[0]}${this._narration})`}static toJsonArray(e){return e.map(e=>e.toJson())}static fromJsonArray(e){try{let t;return t="string"==typeof e?JSON.parse(e):e,Array.isArray(t)?t.map(e=>De.fromJson(e)).filter(e=>void 0!==e):(console.warn("fromJsonArray expects an array"),[])}catch(e){return console.error("Error parsing WalletStatementEntryJson array:",e),[]}}toObject(){return{accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.text,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.toJson(),amountDebited:this._amountDebited.toJson(),balance:this._balance.toJson(),currencyCode:this._currencyCode}}toJSON(){return JSON.stringify(this.toJson())}static fromJSON(e){return De.fromJson(e)}static from(e){if(e&&"object"==typeof e)try{let t,r,n,o,a=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const o=g.fromJson(e.amountCredited),s=g.fromJson(e.amountDebited),i=g.fromJson(e.balance);if(!o||!s||!i)return void console.error("Failed to deserialize Amount objects from JSON");t=o.numericValue,r=s.numericValue,n=i.numericValue,e.currencyCode||(a=o.currencyCode)}else if(t=Number(e.amountCredited),r=Number(e.amountDebited),n=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)o=e.narration;else if(Ee.is(e.narration))o=e.narration;else{if(!Ee.isNarrationJson(e.narration))return void console.error("Invalid narration data");{const t=Ee.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");o=t}}return De.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:o,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:r,balance:n,currencyCode:a})}catch(e){return void console.error("Error in WalletStatementEntry.from:",e)}else console.error("Invalid data provided to WalletStatementEntry.from: not an object or null.")}}const Te=D().router({getWallets:{method:"GET",path:"/",query:ue.walletQuery,responses:{200:t.array(he.schema)}},getBalance:{method:"POST",path:"/balance",body:t.object({accountNo:t.string().optional()}),responses:{201:t.object({availableBalance:t.number()})}},getStatement:{method:"POST",path:"/statement",summary:"Get Wallet Statement",body:t.object({endDate:t.date(),startDate:t.date(),accountNo:t.string().optional()}),responses:{201:t.array(De.schema)}}});class Re extends X{constructor(e){super("wallet",Te,e)}async getBalance(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");if(e.wallet){const t=await this.client.getBalance({body:{accountNo:e.wallet.accountNo}});if(201===t.status){const r=t.body.availableBalance,n=g.from(r,e.wallet.currencyCode);if(n)return n}}if(e.accountNo){const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);const r=t[0],n=await this.client.getBalance({body:{accountNo:e.accountNo}});if(201===n.status){const e=n.body.availableBalance,t=g.from(e,r.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=await this.client.getWallets({query:e});if(200===t.status){const e=t.body;try{return e.map(e=>{const t=he.from(e);if(!t)throw new Error(`Invalid wallet data: ${JSON.stringify(e)}`);return t})}catch(e){throw console.error("[WalletRepository] Error processing wallet data:",e),new Error("Failed to process wallet data from API")}}throw new Error(`Failed to fetch wallets. Status: ${t.status}`)}async getStatement(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");const t=new Date,r=new Date(t.getFullYear(),t.getMonth(),1),n=new Date(t.getFullYear(),t.getMonth()+1,0),o=e.range??{startDate:r,endDate:n};let a,s;if(e.wallet)a=e.wallet,s=e.wallet.accountNo;else{if(!e.accountNo)throw new Error("Either wallet or accountNo must be provided");{const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);a=t[0],s=e.accountNo}}const i={...o,accountNo:s},c=await this.client.getStatement({body:i});if(201===c.status){return c.body.map(e=>({...e,currencyCode:a.currencyCode})).reduce((e,t)=>{const r=De.create(t);return r?e.push(r):console.warn("[WalletRepository] Skipping invalid statement entry:",t),e},[])}throw new Error(`Failed to fetch statement. Status: ${c.status}`)}}const je=n()(q((e,t)=>({userId:"",wallets:[],selectedWalletId:"",selectedCountryCode:"TZ",lastSynced:new Date,isInitialized:!1,setWallets:r=>{const n=r.filter(e=>he.is(e));if(0===n.length)throw new Error("setWallets received an empty or invalid wallet list. User must have at least one valid wallet.");const o=t().selectedWalletId,a=t().isInitialized;let s;const i=n.some(e=>e.id===o);a&&i&&""!==o?(s=n.find(e=>e.id===o),s||(console.error("Inconsistency: currentWalletStillValid was true, but find failed."),s=n[0])):s=n[0],e({wallets:n,selectedWalletId:s.id,selectedCountryCode:s.countryCode,lastSynced:new Date,isInitialized:!0})},setSelectedWallet:r=>{if(!he.is(r))throw new Error("setSelectedWallet called with an invalid Wallet object.");if(!t().wallets.some(e=>e.id===r.id))throw new Error(`Attempted to select wallet (ID: ${r.id}) which is not present in the current wallet list.`);e({selectedWalletId:r.id,selectedCountryCode:r.countryCode})},setSelectedCountry:r=>{const n=t()._getWalletsByCountry(r);if(0===n.length)throw new Error(`Cannot select country ${r}: No wallets found for this country (check if code is valid or state is consistent).`);e({selectedCountryCode:r,selectedWalletId:n[0].id})},reset:()=>{e({userId:"",wallets:[],selectedWalletId:"",selectedCountryCode:"TZ",lastSynced:new Date,isInitialized:!1})},_getWalletsByCountry:e=>t().wallets.filter(t=>t.countryCode===e),_getSelectedWallet:()=>{const e=t();if(!e.isInitialized)throw new Error("Cannot get selected wallet: Wallet session not initialized.");if(""===e.selectedWalletId)throw new Error("Cannot get selected wallet: Selection is still placeholder (initialization incomplete?).");const r=e.wallets.find(t=>t.id===e.selectedWalletId);if(!r)throw console.error("Inconsistent state details:",{id:e.selectedWalletId,walletCount:e.wallets.length}),new Error(`Inconsistent state: Selected wallet ID '${e.selectedWalletId}' not found in wallet list.`);return r}}),{name:"wallet-session-storage",storage:L(()=>sessionStorage,{reviver:(e,t)=>{if("wallets"===e&&Array.isArray(t))return t.map(e=>{try{const t=he.from(e);return t||void console.warn("Filtering out invalid wallet data during rehydration:",e)}catch(t){return void console.error("Error rehydrating Wallet instance from persisted data:",e,t)}}).filter(e=>void 0!==e);if("lastSynced"===e&&"string"==typeof t)try{const e=new Date(t);return isNaN(e.getTime())?new Date:e}catch{return new Date}return t},replacer:(e,t)=>"lastSynced"===e&&t instanceof Date?t.toISOString():"wallets"===e&&Array.isArray(t)?t.map(e=>e instanceof he&&"function"==typeof e.toObject?e.toObject():e):t}),partialize:e=>({userId:e.userId,wallets:e.wallets,selectedWalletId:e.selectedWalletId,selectedCountryCode:e.selectedCountryCode,lastSynced:e.lastSynced,isInitialized:e.isInitialized})}));class Me{repo;static _instance;constructor(){this.repo=new Re}static get instance(){return this._instance||(this._instance=new Me),this._instance}isInitialized(){return je.getState().isInitialized}async initialize(e){if(!this.isInitialized()){if(!e)throw new Error("User must be authenticated to initialize wallet manager");await this.refreshWallets()}}async refreshWallets(){try{const e=await this.repo.getWallets();if(!e||0===e.length)throw new Error("User has no wallets associated with their account. Cannot proceed.");je.getState().setWallets(e)}catch(e){throw console.error("Failed to refresh wallets:",e),e}}getWallets(){const e=je.getState();if(!e.isInitialized)throw new Error("Cannot get wallets: Wallet session not initialized.");return e.wallets}getCountries(){const e=this.getWallets();return me.getUniqueCountries(e)}getWalletsByCountry(e){if(!this.isInitialized())throw new Error("Cannot get wallets by country: Wallet session not initialized.");return je.getState()._getWalletsByCountry(e)}getSelectedWallet(){return je.getState()._getSelectedWallet()}getSelectedCountryCode(){const e=je.getState();if(!e.isInitialized)throw new Error("Cannot get selected country code: Wallet session not initialized.");return e.selectedCountryCode}getSelectedCountry(){const e=this.getSelectedCountryCode();try{const t=w.fromCode(e);if(!t)throw new Error(`Country.fromCode returned invalid result for code: ${e}`);return t}catch(t){throw console.error(`Failed to get Country object for code ${e}:`,t),new Error(`Failed to create Country object for selected code ${e}.`)}}changeWallet(e){if(!this.isInitialized())throw new Error("Cannot change wallet: Wallet session not initialized.");const t=je.getState(),r=t.wallets.find(t=>t.id===e);if(!r)throw new Error(`Cannot change wallet: Wallet with ID ${e} not found.`);t.setSelectedWallet(r)}changeCountry(e){if(!this.isInitialized())throw new Error("Cannot change country: Wallet session not initialized.");je.getState().setSelectedCountry(e)}reset(){je.getState().reset()}}const ke=D().router({logIn:{method:"POST",path:"/login",body:t.object({type:t.string().default("password"),identity:t.string().email(),password:t.string()}),responses:{201:t.object({profile:W.profileDTOSchema,token:t.string(),access:t.array(t.string()),resetPassword:t.boolean()}),400:t.object({})}},access:{method:"GET",path:"/access",responses:{200:t.string().array()}},resetPassword:{method:"PUT",path:"/password",body:t.object({currentPassword:t.string(),newPassword:t.string()}),responses:{}}}),xe=D().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:V.loginDTO}}});class Be extends X{constructor(e){super("login",xe,e)}async getIdentity(){const e=await this.client.getUserCredentials();if(200===e.status)return e.body;throw new Error(`Failed to get user identity. Status: ${e.status}`)}}const Fe=t.string().min(8,"Password must be at least 8 characters long").max(128,"Password must not exceed 128 characters").regex(/[A-Z]/,"Password must contain at least one uppercase letter").regex(/[a-z]/,"Password must contain at least one lowercase letter").regex(/[0-9]/,"Password must contain at least one number").regex(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/,"Password must contain at least one special character (!@#$%^&*()_+-=[]{}|;:,.<>?)").refine(e=>![/(.)\1{2,}/,/123456|654321|abcdef|qwerty|password|admin|user/i,/^[0-9]+$/,/^[a-zA-Z]+$/].some(t=>t.test(e)),"Password contains weak patterns. Avoid repeated characters, common words, or simple sequences").refine(e=>!/(?:abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789)/i.test(e),"Password should not contain sequential characters").refine(e=>!/(?:qwer|wert|erty|rtyu|tyui|yuio|uiop|asdf|sdfg|dfgh|fghj|ghjk|hjkl|zxcv|xcvb|cvbn|vbnm)/i.test(e),"Password should not contain keyboard patterns"),$e=t.object({id:t.string().min(1),name:t.string().min(1,"Role name is required"),description:t.string().optional(),access:t.array(t.string()),createdAt:t.string().datetime("Invalid creation timestamp"),updatedAt:t.string().datetime("Invalid update timestamp")}),Ue=t.object({id:t.string().min(1),name:t.string().min(1,"Team member name is required"),identity:t.string().email("Invalid email address"),type:t.string().min(1,"Team member type is required"),profileId:t.string().min(1,"Profile ID is required"),roleId:t.string().min(1,"Role ID is required"),resetPassword:t.boolean(),isActive:t.boolean(),isArchived:t.boolean(),role:$e.optional(),createdAt:t.string().datetime("Invalid creation timestamp"),updatedAt:t.string().datetime("Invalid update timestamp")}),Le={role:$e,teamMember:Ue,teamMemberQueryParams:t.object({id:t.string().min(1).optional(),name:t.string().min(1).optional(),identity:t.string().email("Invalid email address").optional(),type:t.string().min(1).optional(),profileId:t.string().min(1).optional(),roleId:t.string().min(1).optional(),resetPassword:t.number().optional(),isActive:t.number().optional(),isArchived:t.number().optional(),createdAt:t.string().datetime("Invalid creation timestamp").optional(),updatedAt:t.string().datetime("Invalid update timestamp").optional(),eager:t.string().optional()}),createTeamMemberRequest:t.object({name:t.string().min(1,"Team member name is required"),identity:t.string().email("Valid email address is required"),password:Fe.optional(),roleId:t.string().optional(),resetPassword:t.boolean().optional()}),updateTeamMemberRequest:t.object({name:t.string().min(1,"Team member name cannot be empty").optional(),roleId:t.string().min(1,"Role ID cannot be empty").optional(),password:Fe.optional(),resetPassword:t.boolean().optional(),isActive:t.boolean().optional()}),resetPasswordRequest:t.object({newPassword:Fe.optional(),sendNotification:t.boolean().optional()}),createTeamMemberResponse:t.object({id:t.string(),name:t.string(),identity:t.string(),type:t.string(),profileId:t.string(),resetPassword:t.boolean(),roleId:t.string(),isActive:t.boolean(),isArchived:t.boolean(),createdAt:t.string().datetime(),updatedAt:t.string().datetime()}),password:Fe},Je=D().router({getTeamMembers:{method:"GET",path:"/login",query:Le.teamMemberQueryParams,responses:{200:t.array(Le.teamMember),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"List all team members",description:"Retrieve a list of all team member accounts in the system"},getTeamMember:{method:"GET",path:"/login/:id",pathParams:t.object({id:t.string()}),query:Le.teamMemberQueryParams,responses:{200:Le.teamMember,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Get team member details",description:"Retrieve detailed information about a specific team member"},createTeamMember:{method:"POST",path:"/login",body:Le.createTeamMemberRequest,responses:{201:Le.createTeamMemberResponse,400:t.object({message:t.string().optional(),errors:t.array(t.string()).optional()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),409:t.object({message:t.string().optional()})},summary:"Create new team member",description:"Create a new team member account with specified role and permissions"},updateTeamMember:{method:"PATCH",path:"/login/:id",pathParams:t.object({id:t.string()}),body:Le.updateTeamMemberRequest,responses:{200:Le.teamMember,400:t.object({message:t.string().optional(),errors:t.array(t.string()).optional()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Update team member",description:"Update team member information, role, status, or force password reset"},archiveTeamMember:{method:"POST",path:"/login/:id/archive",pathParams:t.object({id:t.string()}),body:t.object({}),responses:{200:Le.teamMember,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Archive team member",description:"Archive (soft delete) a team member account"},unArchiveTeamMember:{method:"POST",path:"/login/:id/unarchive",pathParams:t.object({id:t.string()}),body:t.object({}),responses:{200:Le.teamMember,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Unarchive team member",description:"Unarchive a previously archived team member account"},resetPassword:{method:"POST",path:"/login/:id/reset-password",pathParams:t.object({id:t.string()}),body:Le.resetPasswordRequest,responses:{200:t.object({success:t.boolean()}),400:t.object({message:t.string().optional()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Reset team member password",description:"Reset a team member's password and optionally send notification"},getRoles:{method:"GET",path:"/role",responses:{200:t.array(Le.role),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"List all roles",description:"Retrieve a list of all available roles in the system"},getRole:{method:"GET",path:"/role/:id",pathParams:t.object({id:t.string()}),responses:{200:Le.role,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Get role details",description:"Retrieve detailed information about a specific role"}});class qe{id;name;identity;type;profileId;roleId;resetPassword;isActive;isArchived;role;createdAt;updatedAt;permissions;constructor(e){if(this.id=e.id,this.name=e.name,this.identity=e.identity,this.type=e.type,this.profileId=e.profileId,this.roleId=e.roleId,this.resetPassword=e.resetPassword,this.isActive=e.isActive,this.isArchived=e.isArchived,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.permissions=new Set(e.role?.access??[]),e.role)try{this.role=new Q(e.role)}catch(e){}}static from(e){try{return e?.id&&e?.name&&e?.identity&&e?.roleId?new qe(e):void console.error("Missing required TeamMember fields:",e)}catch(e){return void console.error("Error creating TeamMember:",e)}}static fromJson(e){try{const t=JSON.parse(e);return qe.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>qe.from(e)).filter(Boolean)}can(e){return this.permissions.has(e)}canAny(e){return e.some(e=>this.permissions.has(e))}canAll(e){return e.every(e=>this.permissions.has(e))}isAccountActive(){return this.isActive}isAccountArchived(){return this.isArchived}needsPasswordReset(){return this.resetPassword}getAccountStatus(){return this.isArchived?{status:"archived",label:"Archived",color:"default",description:"Account has been archived and is no longer accessible"}:this.isActive?this.resetPassword?{status:"password_reset_required",label:"Password Reset Required",color:"warning",description:"User must reset their password on next login"}:{status:"active",label:"Active",color:"success",description:"Account is active and ready to use"}:{status:"inactive",label:"Inactive",color:"error",description:"Account has been deactivated by an administrator"}}getRoleName(){return this.role?.name??""}getCreatedDate(){return this.createdAt.toLocaleDateString()}getLastUpdateInfo(){const e=(new Date).getTime()-this.updatedAt.getTime(),t=Math.floor(e/864e5);return 0===t?"Today":1===t?"Yesterday":t<7?`${t} days ago`:t<30?`${Math.floor(t/7)} weeks ago`:this.updatedAt.toLocaleDateString()}toObject(){return{id:this.id,name:this.name,identity:this.identity,type:this.type,profileId:this.profileId,roleId:this.roleId,resetPassword:this.resetPassword,isActive:this.isActive,isArchived:this.isArchived,role:this.role?.toJSON(),createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}toJson(){return JSON.stringify(this.toObject())}toJSON(){return this.toObject()}}class We extends X{constructor(e){super("admin",Je,e)}async createTeamMember(e){const t=await this.client.createTeamMember({body:e});return this.handleResponse(t,201)}async updateTeamMember(e,t){const r=await this.client.updateTeamMember({params:{id:e},body:t}),n=this.handleResponse(r,200),o=qe.from(n);if(!o)throw new Error("Invalid team member data received from server");return o}async archiveTeamMember(e){const t=await this.client.archiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),n=qe.from(r);if(!n)throw new Error("Invalid team member data received from server");return n}async unArchiveTeamMember(e){const t=await this.client.unArchiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),n=qe.from(r);if(!n)throw new Error("Invalid team member data received from server");return n}async resetTeamMemberPassword(e,t={}){const r=await this.client.resetPassword({params:{id:e},body:t});return this.handleResponse(r,200)}async getAllTeamMembers(e={eager:"role"}){const t=await this.client.getTeamMembers({query:e}),r=this.handleResponse(t,200);return qe.createMany(r)}async getTeamMember(e,t={eager:"role"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),n=this.handleResponse(r,200),o=qe.from(n);if(!o)throw new Error("Invalid team member data received from server");return o}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=Q.from(e);if(!t)throw new Error("Invalid role data received from server");return t})}async getRole(e){const t=await this.client.getRole({params:{id:e}}),r=this.handleResponse(t,200),n=Q.from(r);if(!n)throw new Error("Invalid role data received from server");return n}}class ze extends X{constructor(e){super("auth",ke,e)}async logIn(e,t){const r={type:"password",identity:e,password:t},n=await this.client.logIn({body:r});if(400===n.status)throw new N({message:"Invalid email or password",statusCode:400});if(201===n.status){const e=n.body.token,t=new Be({token:e}),r=await t.getIdentity(),o=G.from(r);if(!o)throw new N({message:"Failed to construct login credentials",statusCode:502});const a=n.body.profile,s=z.from(a);if(!s)throw new N({message:"Failed to construct user profile",statusCode:502});let i;if(o.access.includes(C.Role.ViewRole))try{const t=new We({token:e});i=await t.getRole(o.roleId)}catch(e){console.warn("Failed to fetch role details:",e)}const c=K.from({logIn:o,companyProfile:s,role:i,token:e});if(!c)throw new N({message:"Failed to construct user session",statusCode:502});return c}throw new N({message:"An error occurred while trying to log in",statusCode:502})}async updatePassword(e,t){const r=await this.client.resetPassword({body:{currentPassword:e,newPassword:t}});if(200===r.status)return!0;if(400===r.status)throw new N({message:"Invalid current password",statusCode:400});throw new N({message:"An error occurred while trying to update password",statusCode:502})}async getAccessList(){const e=await this.client.access();if(200===e.status)return e.body;throw new Error(`Failed to get access list. Status: ${e.status}`)}}class Ve{static _instance=null;constructor(){}static get instance(){return Ve._instance||(Ve._instance=new Ve),Ve._instance}get repo(){return new ze({token:this.getUserToken()})}getUserToken(){return Y()}get currentUser(){return(()=>{if("undefined"!=typeof window)return Z.getState().getUser()})()}get isAuthenticated(){return!!this.currentUser&&!!this.getUserToken()}useCurrentUser(){return(()=>{if("undefined"==typeof window)throw new Error("useCurrentUser must only be used in a React component on the client side");const e=o(Z,e=>e.user);try{return e?K.fromJson(e):void 0}catch(e){return void console.warn("Failed to deserialize user from hook:",e)}})()}checkPermission(e){return this.currentUser?.can(e)??!1}async logIn(e,t){if(!e||!t)throw new Error("Email and password are required");const r=new ze,n=await r.logIn(e,t);this.clearSavedData(),Z.getState().setUserAndToken(n,n.token);try{await Me.instance.initialize(n)}catch(e){throw console.warn("Failed to initialize wallet session manager:",e),e}return n}async resetPassword(e,t){if(!this.isAuthenticated)throw new Error("User must be authenticated to reset password");if(!e||!t)throw new Error("Current password and new password are required");return await this.repo.updatePassword(e,t),this.clearSavedData(),!0}logOut(){this.clearSavedData()}refresh(){this.clearSavedData()}getDebugInfo(){return{hasUser:!!this.currentUser,hasToken:!!this.getUserToken(),isAuthenticated:this.isAuthenticated,userName:this.currentUser?.name||"Not logged in",tokenLength:this.getUserToken()?.length||0,managerInstance:"AfloatAuth singleton"}}clearSavedData(){Z.getState().clearAuth();try{Me.instance.reset()}catch(e){console.warn("Failed to reset wallet session manager:",e)}}}class Ge{data;constructor(e){this.data=ge.contactDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get displayName(){return this.data.displayName}get type(){return this.data.type}get createdAt(){return new Date(this.data.createdAt)}get updatedAt(){return new Date(this.data.updatedAt)}get info(){return this.data.type===pe.Mobile?ve.fromContactDTO(this.data):this.data.type===pe.Bank?Ne.fromContactDTO(this.data):void 0}get accNo(){const e=this.info;return e?e.accountNumber:this.data.accountNo}get accName(){return this.data.displayName}get accNoLabel(){const e=this.info;return e instanceof ve?"Phone Number":e instanceof Ne?"Bank Account Number":"Account Number"}get channelLabel(){const e=this.info;return e instanceof ve?"Channel":e instanceof Ne?"Bank":"Channel"}get accNameLabel(){const e=this.info;return e instanceof ve?"Full Name":e instanceof Ne?"Bank Account Name":"Display Name"}get channelName(){const e=this.info;return e instanceof ve||e instanceof Ne?e.channelName:""}static create(e){return new Ge(e)}static createMany(e){return e.map(e=>new Ge(e))}static createSafe(e){try{return new Ge(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=ge.contactDTO.safeParse(e);if(!t.success)return!1;return null!==Ge.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&Ge.canConstruct(e.data))}toJSON(){return{...this.data}}}class He{canHandle(e){return"Mobile"===e.type&&ve.is(e)}createInput(e){if(ve.is(e))return{type:pe.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Contact Info")}}class Qe{canHandle(e){return"Bank"===e.type&&Ne.is(e)}createInput(e){if(Ne.is(e))return{type:pe.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Contact Info")}}class Ke{handlers=[new He,new Qe];resolve(e){const t=this.handlers.find(t=>t.canHandle(e));if(!t)throw new Error("Please check your data and try again");return t.createInput(e)}}const Ze=D().router({createContact:{method:"POST",path:"/",body:ge.contactInputDTO,responses:{201:ge.contactDTO}},editContact:{method:"PATCH",path:"/:id",body:ge.contactInputDTO,responses:{200:ge.contactDTO}},getContacts:{method:"GET",path:"/",query:t.object({orderByDesc:t.string()}),responses:{200:t.array(ge.contactDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:ge.contactDTO}},deleteContact:{method:"DELETE",path:"/:id",body:t.object({}),responses:{200:t.object({})}}});class Ye extends X{constructor(e){super("contact",Ze,e)}async create(e){const t=(new Ke).resolve(e),r=await this.client.createContact({body:t}),n=this.handleResponse(r,201);return Ge.create(n)}async edit(e,t){const r=(new Ke).resolve(t),n=await this.client.editContact({params:{id:e},body:r}),o=this.handleResponse(n,200);return Ge.create(o)}async remove(e){const t=await this.client.deleteContact({params:{id:e}});this.handleResponse(t,200)}async getAll(){const e=await this.client.getContacts({query:{orderByDesc:"createdAt"}}),t=this.handleResponse(e,200);return Ge.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return Ge.create(r)}}var Xe,et,tt;!function(e){e.MOBILE="Mobile",e.BANK="Bank"}(Xe||(Xe={})),function(e){e.CREATED="CREATED",e.PENDING="PENDING",e.PAID="PAID",e.FAILED="FAILED",e.REJECTED="REJECTED",e.REVERSED="REVERSED"}(et||(et={})),function(e){e.PENDING="Pending",e.APPROVED="Approved",e.REJECTED="Rejected"}(tt||(tt={}));const rt=t.object({id:t.string(),name:t.string(),identity:t.string()}),nt=t.nativeEnum(et),ot=t.nativeEnum(tt),at=t.object({channel:t.string(),msisdn:t.string(),amount:t.coerce.number(),description:t.string(),notes:t.string().nullish()}),st=at.extend({payeeName:t.string()}),it=at.extend({id:t.string(),profileId:t.string(),payeeName:t.string(),countryCode:t.string().default("TZ").refine(e=>s.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.string().default("TZS").refine(e=>a.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),channel:t.string(),status:nt,statusMessage:t.string(),partnerReference:t.string().nullish(),createdAt:t.coerce.date(),updatedAt:t.coerce.date(),actionedAt:t.coerce.date().nullish(),approvalStatus:ot.nullish(),createdBy:rt.nullish(),actionedBy:rt.nullish()}),ct=t.object({page:t.number().int().positive().default(1),limit:t.number().int().positive().max(100).default(10),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().datetime().nullish(),endDate:t.string().datetime().nullish(),payeeName:t.string().nullish(),msisdn:t.string().nullish(),profileId:t.string().nullish(),id:t.string().nullish(),partnerReference:t.string().nullish(),channel:t.string().nullish(),status:nt.nullish(),approvalStatus:ot.nullish(),minAmount:t.number().min(0).nullish(),maxAmount:t.number().min(0).nullish(),search:t.string().nullish()}),lt={PayoutDTO:it,PayoutInputDTO:st,PayoutStatus:nt,PayoutApprovalStatus:ot,PayoutAuthorizer:rt,PayoutFilters:ct,PayoutURLQueryParams:t.object({page:t.string().transform(e=>parseInt(e)||1).optional(),limit:t.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().optional(),endDate:t.string().optional(),payeeName:t.string().optional(),msisdn:t.string().optional(),profileId:t.string().optional(),id:t.string().optional(),partnerReference:t.string().optional(),channel:t.string().optional(),status:t.string().refine(e=>Object.values(et).includes(e)).transform(e=>e).optional(),approvalStatus:t.string().refine(e=>Object.values(tt).includes(e)).transform(e=>e).optional(),minAmount:t.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.string().transform(e=>parseFloat(e)).optional(),search:t.string().optional()})};class dt{data;constructor(e){this.data=lt.PayoutDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get payeeName(){return this.data.payeeName}get channel(){return this.data.channel}get msisdn(){return this.data.msisdn}get amount(){return g.from(this.data.amount,this.data.currencyCode)}get description(){return this.data.description}get notes(){return this.data.notes}get status(){return"Rejected"===this.data.approvalStatus?et.REJECTED:"Approved"===this.data.approvalStatus?"FAILED"===this.data.status?et.FAILED:et.PAID:"Pending"===this.data.approvalStatus?et.PENDING:this.data.status}get statusMessage(){return this.data.statusMessage}get partnerReference(){return this.data.partnerReference}get createdAt(){return this.data.createdAt}get updatedAt(){return this.data.updatedAt}get actionedAt(){return this.data.actionedAt}get approvalStatus(){return this.data.approvalStatus}get createdBy(){return this.data.createdBy}get actionedBy(){return this.data.actionedBy}get contactInfo(){return"TZ-BANK-B2C"===this.channel?Ne.fromPayoutDTO(this.data):ve.fromPayoutDTO(this.data)}static create(e){return new dt(e)}static createMany(e){return e.map(e=>new dt(e))}static createSafe(e){try{return new dt(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=lt.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==dt.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&dt.canConstruct(e.data))}toJSON(){return{...this.data}}}const ut={SUPPORTED_COUNTRY_CODES:["TZ","KE"],ERROR_MESSAGES:{INVALID_PHONE_NUMBER:"Invalid phone number",INELIGIBLE_FOR_PAYOUT:"The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",MOBILE_NUMBER_MNO_MISMATCH:"There is a mismatch between the phone number provided and the MNO used.",UNSUPPORTED_COUNTRY_BANK:"Only Tanzanian Banks are supported for now",UNSUPPORTED_COUNTRY_MOBILE:"Only Tanzanian mobile numbers are supported for now",NO_HANDLER_FOUND:"Cannot create payout input!"}};class ht{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}}class mt{static forBank(e,t){if(!ut.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(ut.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,t,r){if(!u.is(e))throw new Error(ut.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!ut.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(ut.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!b.checkPayoutEligibility(e))throw new Error(ut.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const n=d.getMNOById(t,e.countryCode);if(!n)throw new Error(ut.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return n.id===v.VODACOM?`${r.countryCode}-${v.TIGO.toString().toUpperCase()}-B2C`:`${r.countryCode}-${n.id.toString().toUpperCase()}-B2C`}}class pt{canHandle(e,t,r){return e===Xe.MOBILE&&ve.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===w.from(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=ht.processNotes(e.notes),o=r.phoneNumber;return{channel:mt.forMobile(o,r.mnoId,t),msisdn:o.getWithFormat(h.INTERNATIONAL_NUMERIC),description:n??Ee.generateDefaultPayoutNarration(r),payeeName:r.name,notes:n,amount:e.amount.numericValue}}}class ft{canHandle(e,t,r){return e===Xe.BANK&&Ne.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===w.from(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=ht.processNotes(e.notes);return{channel:mt.forBank(r,t),msisdn:`${r.bank.swiftCode}:${r.accNo}`,description:n??Ee.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:n,amount:e.amount.numericValue}}}class yt{handlers=[new pt,new ft];getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(ut.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const gt={bank:mt.forBank,mobile:mt.forMobile},wt=D().router({getPayouts:{method:"GET",path:"",query:t.object({}),responses:{200:t.object({results:t.array(lt.PayoutDTO),total:t.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:t.object({rangeStart:t.number(),rangeEnd:t.number(),eager:t.string(),approvalStatus:lt.PayoutApprovalStatus,orderByDesc:t.string()}),responses:{200:t.object({results:t.array(lt.PayoutDTO),total:t.number()})}},postPayout:{method:"POST",path:"",body:lt.PayoutInputDTO,responses:{201:lt.PayoutDTO,400:N.schema}},approve:{method:"POST",path:"/:id/approve",body:t.object({action:t.enum(["Approve","Reject"]),notes:t.string().optional()}),responses:{201:lt.PayoutDTO,404:t.object({}),409:t.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:lt.PayoutDTO,404:t.object({})}}});class bt extends ne{static create(){return new bt}static fromFilters(e){return(new bt).applyFilters(e)}static fromUrlParams(e){try{const t=lt.PayoutURLQueryParams.parse(e),r=lt.PayoutFilters.parse(t);return bt.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return bt.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return bt.fromSearchParams(t)}static from(e){try{return null==e?new bt:ne.is(e)?new bt(e.options):e instanceof URLSearchParams?bt.fromSearchParams(e):this.isStringRecord(e)?bt.fromUrlParams(e):bt.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a PayoutQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereStatus(e){return this.where("status",e)}whereApprovalStatus(e){return this.where("approvalStatus",e)}whereChannel(e){return this.where("channel",e)}wherePending(){return this.whereApprovalStatus(tt.PENDING)}whereApproved(){return this.whereApprovalStatus(tt.APPROVED)}whereRejected(){return this.whereApprovalStatus(tt.REJECTED)}wherePaid(){return this.whereStatus(et.PAID)}whereFailed(){return this.whereStatus(et.FAILED)}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}wherePayee(e){return this.whereContains("payeeName",e)}whereMsisdn(e){return this.whereContains("msisdn",e)}whereProfileId(e){return this.where("profileId",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.status&&this.whereStatus(e.status),e.approvalStatus&&this.whereApprovalStatus(e.approvalStatus),e.channel&&this.whereChannel(e.channel),e.payeeName&&this.wherePayee(e.payeeName),e.msisdn&&this.whereMsisdn(e.msisdn),e.profileId&&this.whereProfileId(e.profileId),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&e.minAmount&&void 0!==e.maxAmount&&e.maxAmount?this.whereAmountBetween(e.minAmount,e.maxAmount):void 0!==e.minAmount?this.whereGreaterThanOrEqual("amount",e.minAmount):void 0!==e.maxAmount&&this.whereLessThanOrEqual("amount",e.maxAmount)),e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,payeeName:e.payeeName,msisdn:e.msisdn,profileId:e.profileId,id:e.id,partnerReference:e.partnerReference,channel:e.channel,status:this.isValidStatus(e.status)?e.status:void 0,approvalStatus:this.isValidApprovalStatus(e.approvalStatus)?e.approvalStatus:void 0,minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withApprovalStatus(e){const t=this.clone();return e&&t.whereApprovalStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.payeeName||e.msisdn||e.profileId||e.id||e.partnerReference||e.channel||e.status||e.approvalStatus||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.status&&e.push(`Status: ${t.status}`),t.approvalStatus&&e.push(`Approval: ${t.approvalStatus}`),t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.payeeName&&e.push(`Payee: ${t.payeeName}`),t.msisdn&&e.push(`MSISDN: ${t.msisdn}`),t.profileId&&e.push(`Profile: ${t.profileId}`),t.partnerReference&&e.push(`Ref: ${t.partnerReference}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"payeeName":case"msisdn":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}return e}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidStatus(e){return Object.values(et).includes(e)}isValidApprovalStatus(e){return Object.values(tt).includes(e)}}class vt extends X{constructor(e){super("payout",wt,e)}async getPayouts(e){try{const t=bt.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),o=this.handleResponse(n,200),a=t.toFilters(),s=new ie(a.page??1,a.limit??10,o.total);return{results:dt.createMany(o.results),pagination:s}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getAllPayouts(e){try{const t=bt.from(e).build();delete t.page,delete t.limit;const r=await this.client.getPayouts({query:t}),n=this.handleResponse(r,200);return dt.createMany(n.results)}catch(e){throw new Error(`Failed to fetch all payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=bt.fromRequest(e);return this.getPayouts(t)}async pay(e){const{min:t,max:r}=g.getTransactionLimits(e.amount.currencyCode);if(e.amount.lessThan(t)||e.amount.greaterThan(r))throw new N({statusCode:400,message:`Please make sure the amount is between ${t.label} - ${r.label}`});const n=Me.instance.getSelectedWallet();if(!n)throw new Error("You have not selected a wallet to process this payout");const o=(new yt).getPayoutInput(e,n),a=await this.client.postPayout({body:o});if(201===a.status)return dt.create(a.body);if(400===a.status)throw new N(a.body);throw N.unknown()}async approve(e,t){const r=await this.client.approve({params:{id:e},body:{action:"Approve",notes:t?.notes}});if(201===r.status)return dt.create(r.body);if(404===r.status)throw new N({message:"Payout not found",statusCode:404});if(409===r.status)throw new N({message:"Payout already approved",statusCode:409});throw N.unknown()}async reject(e,t){const r=await this.client.approve({params:{id:e},body:{action:"Reject",notes:t?.notes}});if(201===r.status)return dt.create(r.body);if(404===r.status)throw new N({message:"Payout not found",statusCode:404});if(409===r.status)throw new N({message:"Payout already rejected",statusCode:409});throw N.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return dt.create(t.body);if(404===t.status)throw new N({message:"Payout not found",statusCode:404});throw N.unknown()}async count(e){const t=bt.from(e).build(),r=await this.client.getPayouts({query:t});return this.handleResponse(r,200).total}async exists(e){return await this.count(e)>0}}const Nt=D().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:z.schema}}});class Ct extends X{constructor(e){super("profile",Nt,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=z.from(e.body);if(t)return t;throw new Error("Invalid profile data received from server")}throw new Error(`Failed to get current profile. Status: ${e.status}`)}}export{N as APIError,Ve as AfloatAuth,ze as AuthRepository,_e as BANK_NARR_PREFIX,Ne as BankContactInfo,X as BaseRepository,H as CompanyMembership,Ge as Contact,ge as ContactDTOSchemas,Ye as ContactRepository,pe as ContactType,Ce as ECOBANK_PREFIX,ee as FilterOperator,Be as IdentityRepository,Ie as LEGACY_BANK_NARR_PREFIX,Oe as LEGACY_MOBILE_NARR_PREFIX,G as LogIn,V as LogInSchemas,Se as MOBILE_NARR_PREFIX,ve as MobileContactInfo,Ae as NARR_V2_PREFIX,Ee as Narration,ie as Pagination,oe as PaginationParamsSchema,ae as PaginationSchema,dt as Payout,tt as PayoutApprovalStatus,Xe as PayoutChannel,lt as PayoutDTOSchemas,yt as PayoutInputFactory,bt as PayoutQuery,vt as PayoutRepository,et as PayoutStatus,A as PermissionError,C as Permissions,z as Profile,W as ProfileDTOSchemas,Ct as ProfileRepository,re as QUERY_BUILDER_TYPE,ne as QueryBuilder,Q as Role,te as SortDirection,Le as TeamManagementDTOSchemas,qe as TeamMember,We as TeamMemberRepository,K as User,he as Wallet,ue as WalletDTOSchemas,Re as WalletRepository,Me as WalletSessionManager,De as WalletStatementEntry,me as WalletUtils,ce as createPaginatedResponse,se as createPaginatedResponseSchema,gt as createPayoutChannelCode,le as emptyPaginatedResponse,_ as isError,je as walletsStore};
|
|
1
|
+
import e,{z as t}from"zod";import{v4 as r}from"uuid";import{MNOUtils as n,PhoneNumber as o,CountryValidation as a,PhoneNumberFormat as s,BankValidation as i,Bank as c,CurrencyValidation as u,Amount as d,BankService as l,TZMobileNumber as m,PhoneNumberFactory as h,TZMNOId as p,Country as f,Currency as y,CurrencyCodesSet as g,ISO2CountryCodesSet as N,AmountJSONSchema as b}from"@temboplus/frontend-core";class w extends Error{statusCode;error;details;constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,this.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return w.schema.safeParse(e).success}static unknown(e){return new w({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return t.object({message:t.string(),statusCode:t.number().int(),error:t.string().optional(),details:t.object({}).optional()})}}const v={Profile:{ViewCurrent:"profile.getCurrent",Update:"profile.update"},Contact:{View:"contact.findById",List:"contact.findAll",Create:"contact.create",Update:"contact.update",Delete:"contact.delete"},Payment:{View:"payment.findById",List:"payment.findAll",Create:"payment.create"},Payout:{View:"payout.findById",List:"payout.findAll",Create:"payout.create",Approve:"payout.approve"},Transfer:{View:"transfer.findById",List:"transfer.findAll",Create:"transfer.create",Approve:"transfer.approve"},Wallet:{ViewBalance:"wallet.getBalance",ViewStatement:"wallet.getStatement"},Role:{ViewRoles:"role.findAll",ViewRole:"role.findById"},TeamManagement:{ViewMembers:"login.findAll",ViewMember:"login.findById",CreateMember:"login.create",UpdateMember:"login.update",ArchiveMember:"login.archive",UnArchiveMember:"login.unarchive",ResetPassword:"login.resetPassword"}};class C extends Error{requiredPermissions;constructor(e){super(e.message??`Missing required permissions: ${e.requiredPermissions.join(", ")}`),this.name="PermissionError",this.requiredPermissions=e.requiredPermissions}static is(e){const r=t.union([t.enum(Object.values(v.Profile)),t.enum(Object.values(v.Contact)),t.enum(Object.values(v.Payment)),t.enum(Object.values(v.Payout)),t.enum(Object.values(v.Transfer)),t.enum(Object.values(v.Wallet))]);return t.object({name:t.literal("PermissionError").nullish(),message:t.string(),requiredPermissions:t.array(r)}).safeParse(e).success}}function S(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message}const O=e=>"function"==typeof(null==e?void 0:e.passthrough);t.object({name:t.literal("ZodError"),issues:t.array(t.object({path:t.array(t.union([t.string(),t.number()])),message:t.string().optional(),code:t.nativeEnum(t.ZodIssueCode)}).catchall(t.any()))});const A=Symbol("ContractNoBody"),I=e=>"method"in e&&"path"in e,_=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,o,a,s,i;return I(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:(s=null==t?void 0:t.baseHeaders,i=r.headers,O(s)?O(i)?s.merge(i):s:O(i)?i:Object.assign({},s,i)),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(o=r.validateResponseOnClient)&&void 0!==o?o:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(a=r.metadata)&&void 0!==a?a:{}}:r.metadata}]:[e,_(r,t)]})),P=Symbol("ContractPlainType"),E=()=>({router:(e,t)=>_(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>P,body:()=>P,type:()=>P,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>A}),D=e=>e?Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r;return r="string"==typeof t&&!["true","false","null"].includes(t.trim())&&isNaN(Number(t))?t:JSON.stringify(t),`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).join("&"):"",R=e=>e?Object.keys(e).flatMap(t=>T(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",T=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>T(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>T(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class J extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const j=async({route:e,path:t,method:r,headers:n,body:o,validateResponse:a,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:n,body:o}),c=i.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t={status:i.status,body:await i.json(),headers:i.headers},r=e.responses[t.status];return(null!=a?a:e.validateResponseOnClient)&&"function"==typeof(null==(u=r)?void 0:u.safeParse)?{...t,body:r.parse(t.body)}:t}var u;return(null==c?void 0:c.includes("text/"))?{status:i.status,body:await i.text(),headers:i.headers}:{status:i.status,body:await i.blob(),headers:i.headers}},M=e=>{const t=new FormData,r=(e,r)=>{r instanceof File?t.append(e,r):t.append(e,JSON.stringify(r))};return Object.entries(e).forEach(([e,t])=>{if(Array.isArray(t))for(const n of t)r(e,n);else r(e,t)}),t},B=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),F=(e,t,r,n,o)=>{const a=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),s=((e,t=!1)=>{const r=t?D(e):R(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,o);return`${t}${a}${s}`},x=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const o=((e,t,r)=>{const{query:n,params:o,body:a,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...m}=r||{},h={...t,...c};return{path:F(n,h.baseUrl,o,e,!!h.jsonQuery),clientArgs:h,route:e,body:a,query:n,extraInputArgs:m,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...i,...s}}})(e,t,n),a=await(e=>{const{path:t,clientArgs:r,route:n,body:o,query:a,extraInputArgs:s,headers:i,fetchOptions:c}=e,u=r.api||j,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&B(d),...B(i)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let m={route:n,path:t,method:n.method,headers:l,body:void 0,rawBody:o,rawQuery:a,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?m={...m,contentType:"multipart/form-data",body:o instanceof FormData?o:M(o)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?m={...m,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...m.headers},body:"string"==typeof o?o:new URLSearchParams(o)}:null!=o&&(m={...m,contentType:"application/json",headers:{"content-type":"application/json",...m.headers},body:JSON.stringify(o)})),u({...m,...s})})(o);if(!t.throwOnUnknownStatus)return a;if(r.includes(a.status.toString()))return a;throw new J(a,r)}},k=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>I(r)?[e,x(r,t)]:[e,k(r,t)]));let $;const U=e=>{$=e};class L{contract;endpoint;root;token;constructor(e,t,r){this.contract=t,this.endpoint=e,this.root=r?.root,this.token=r?.token}getToken(){if(this.token&&this.token.trim().length>0)return this.token;if($){const e=$();if(e&&e.trim().length>0)return e}return""}get client(){const e={baseUrl:this.root?`${this.root}/${this.endpoint}`:`https://api.afloat.money/v1/${this.endpoint}`,baseHeaders:{token:this.getToken(),"x-request-id":r()}};return k(this.contract,e)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(t,r){if(t.status===r)return t.body;if(400===t.status){const r=e.object({statusCode:e.number(),message:e.string(),error:e.string(),details:e.record(e.string()).optional()}).safeParse(t.body);if(r.success)throw new w(r.data);throw new w({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===t.status)throw new w({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===t.status)throw new w({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===t.status)throw new w({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new w({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}var q,V;!function(e){e.EQUALS="eq",e.NOT_EQUALS="neq",e.LESS_THAN="lt",e.LESS_THAN_OR_EQUAL="lte",e.GREATER_THAN="gt",e.GREATER_THAN_OR_EQUAL="gte",e.LIKE="like",e.LIKE_LOWER="likeLower",e.IS_NULL="isNull",e.IS_NOT_NULL="isNotNull",e.IN="in"}(q||(q={})),function(e){e.ASC="asc",e.DESC="desc"}(V||(V={}));const W=Symbol("query-builder-type");class G{options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8};constructor(e={}){this.options={filters:e.filters||[],sort:e.sort||[],includes:e.includes||[],groupBy:e.groupBy||[],join:e.join||[],page:e.page,limit:e.limit}}[W]="query-builder";static is(e){return null!==e&&"object"==typeof e&&W in e&&"query-builder"===e[W]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:q.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:q.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:q.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:q.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:q.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:q.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:q.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:q.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:q.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:q.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:q.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:q.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:q.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:q.LESS_THAN_OR_EQUAL,value:t})}whereBetween(e,t,r){return this.whereGreaterThanOrEqual(e,t).whereLessThanOrEqual(e,r)}whereDateBetween(e,t){if(e){const t=e instanceof Date?e.toISOString():e;this.whereGreaterThanOrEqual("createdAt",t)}if(t){const e=t instanceof Date?t.toISOString():t;this.whereLessThanOrEqual("createdAt",e)}return this}addSort(e){return this.options.sort=[...this.options.sort||[],e],this}orderBy(e,t=V.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,V.ASC)}orderByDesc(e){return this.orderBy(e,V.DESC)}paginate(e,t){return this.options.page=e,this.options.limit=t,this}with(e){const t=Array.isArray(e)?e:[e];return this.options.includes=[...this.options.includes||[],...t],this}join(e){const t=Array.isArray(e)?e:[e];return this.options.join=[...this.options.join||[],...t],this}groupBy(e){const t=Array.isArray(e)?e:[e];return this.options.groupBy=[...this.options.groupBy||[],...t],this}count(e="*"){return this.options.count=e,this}countAs(e,t){return this.options.count=`${e} as ${t}`,this}build(){const e={};if(void 0!==this.options.page&&void 0!==this.options.limit){const t=(this.options.page-1)*this.options.limit,r=t+this.options.limit-1;e.rangeStart=t,e.rangeEnd=r}if(this.options.filters&&this.options.filters.length>0)for(const t of this.options.filters)switch(t.operator){case q.IS_NULL:e[`${t.field}:isNull`]=1;break;case q.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case q.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case q.LIKE:e[`${t.field}:like`]=t.value;break;case q.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case q.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case q.LESS_THAN_OR_EQUAL:e[`${t.field}:lte`]=t.value;break;default:e[`${t.field}:${t.operator}`]=t.value}if(this.options.sort&&this.options.sort.length>0){const t=[],r=[];for(const e of this.options.sort)e.direction===V.ASC?t.push(e.field):r.push(e.field);t.length>0&&(e.orderBy=t.join(",")),r.length>0&&(e.orderByDesc=r.join(","))}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?e.eager=this.options.includes[0]:e.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(e.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(e.groupBy=this.options.groupBy.join(",")),this.options.count&&(e.count=this.options.count),e}clone(){return new(0,this.constructor)({...this.options,filters:this.options.filters?[...this.options.filters]:[],sort:this.options.sort?[...this.options.sort]:[],includes:this.options.includes?[...this.options.includes]:[],groupBy:this.options.groupBy?[...this.options.groupBy]:[],join:this.options.join?[...this.options.join]:[]})}static create(e){return new G(e)}}const H=t.object({page:t.coerce.number().int().min(1).default(1),limit:t.coerce.number().int().min(1).max(100).default(10)}),Q=t.object({page:t.number().int().min(1),limit:t.number().int().min(1),total:t.number().int().min(0),totalPages:t.number().int().min(0),hasNext:t.boolean(),hasPrev:t.boolean()});function K(e){return t.object({results:t.array(e),pagination:Q})}class Y{page;limit;total;constructor(e,t,r){if(this.page=e,this.limit=t,this.total=r,e<1)throw new Error("Page must be >= 1");if(t<1)throw new Error("Limit must be >= 1");if(r<0)throw new Error("Total must be >= 0")}get totalPages(){return Math.ceil(this.total/this.limit)}get hasNext(){return this.page<this.totalPages}get hasPrev(){return this.page>1}get offset(){return(this.page-1)*this.limit}get isFirstPage(){return 1===this.page}get isLastPage(){return this.page===this.totalPages}nextPage(){return this.hasNext?new Y(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new Y(this.page-1,this.limit,this.total):null}toJSON(){return{page:this.page,limit:this.limit,total:this.total,totalPages:this.totalPages,hasNext:this.hasNext,hasPrev:this.hasPrev}}}function Z(e,t,r,n){return{results:e,pagination:new Y(t,r,n)}}function z(e=1,t=10){return{results:[],pagination:new Y(e,t,0)}}const X={profileDTOSchema:t.object({id:t.string(),firstName:t.string().nullish(),lastName:t.string().nullish(),displayName:t.string(),phone:t.string().nullish(),accountNo:t.string().min(1),email:t.string().email().nullish(),autoApprove:t.boolean().nullish()})},ee=t.object({id:t.string(),firstName:t.string().nullable().optional(),lastName:t.string().nullable().optional(),displayName:t.string(),phone:t.string().nullable().optional(),accountNo:t.string(),email:t.string().nullable().optional(),autoApprove:t.boolean().nullable().optional(),version:t.string().optional().default("1.0")});class te{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return X.profileDTOSchema}constructor(e){this._id=e.id,this._firstName=e.firstName,this._lastName=e.lastName,this._displayName=e.displayName,this._phone=e.phone,this._accountNo=e.accountNo,this._email=e.email,this._autoApprove=e.autoApprove}static create(e){return new te({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove})}get id(){return this._id}get firstName(){return this._firstName}get lastName(){return this._lastName}get displayName(){return this._displayName}get phone(){return this._phone}get accountNo(){return this._accountNo}get email(){return this._email}get autoApprove(){return this._autoApprove}getName(){if(this._displayName&&""!==this._displayName.trim())return this._displayName;return`${this._firstName??""} ${this._lastName??""}`.trim()}validate(){try{return te.schema.safeParse(this.toJSON()).success}catch(e){return console.error("Profile validation error:",e),!1}}static from(e){try{return e?"object"!=typeof e?void console.error("Data is not an object"):e.id&&e.accountNo&&e.displayName?te.create({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove}):void console.error("Missing required profile fields"):void console.error("Data is null or undefined")}catch(e){return void console.error("Error creating profile from object:",e)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t._id||"string"!=typeof t._displayName||"string"!=typeof t._accountNo)return!1;if(null!==t._firstName&&void 0!==t._firstName&&"string"!=typeof t._firstName)return!1;if(null!==t._lastName&&void 0!==t._lastName&&"string"!=typeof t._lastName)return!1;if(null!==t._email&&void 0!==t._email&&"string"!=typeof t._email)return!1;const r=t._phone;if(null!=r&&"string"!=typeof r)return!1;const n=t._autoApprove;return null==n||"boolean"==typeof n}toJSON(){return{id:this._id,firstName:this._firstName,lastName:this._lastName,displayName:this._displayName,phone:this._phone,accountNo:this._accountNo,email:this._email,autoApprove:this._autoApprove,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ee.safeParse(t);if(!r.success)return void console.error("Invalid ProfileJSON:",r.error.flatten());const n=r.data;return te.from(n)}catch(e){return void console.error("Error parsing ProfileJSON:",e)}}static isProfileJSON(e){return ee.safeParse(e).success}}const re={loginDTO:e.object({id:e.string().min(1,"ID is required"),profileId:e.string().min(1,"Profile ID is required"),name:e.string().min(1,"Name is required"),identity:e.string().email("Identity must be a valid email address"),type:e.string().min(1,"Type is required"),roleId:e.string().min(1,"Role ID is required"),isActive:e.boolean(),isArchived:e.boolean(),resetPassword:e.boolean(),createdAt:e.string().datetime("Invalid creation timestamp"),updatedAt:e.string().datetime("Invalid update timestamp"),access:e.array(e.string())})},ne=t.object({id:t.string(),profileId:t.string(),name:t.string(),identity:t.string(),type:t.string(),roleId:t.string(),isActive:t.boolean(),isArchived:t.boolean(),resetPassword:t.boolean(),createdAt:t.string(),updatedAt:t.string(),access:t.array(t.string()),version:t.string().optional().default("1.0")});class oe{_id;_profileId;_name;_identity;_type;_roleId;_isActive;_isArchived;_resetPassword;_createdAt;_updatedAt;_access;constructor(e,t,r,n,o,a,s,i,c,u,d,l){this._id=e,this._profileId=t,this._name=r,this._identity=n,this._type=o,this._roleId=a,this._isActive=s,this._isArchived=i,this._resetPassword=c,this._createdAt=u,this._updatedAt=d,this._access=l}static from(e){const t=re.loginDTO.parse(e);return new oe(t.id,t.profileId,t.name,t.identity,t.type,t.roleId,t.isActive,t.isArchived,t.resetPassword,new Date(t.createdAt),new Date(t.updatedAt),t.access)}get id(){return this._id}get profileId(){return this._profileId}get name(){return this._name}get identity(){return this._identity}get type(){return this._type}get roleId(){return this._roleId}get isActive(){return this._isActive}get isArchived(){return this._isArchived}get resetPassword(){return this._resetPassword}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get access(){return this._access}toJSON(){return{id:this._id,profileId:this._profileId,name:this._name,identity:this._identity,type:this._type,roleId:this._roleId,isActive:this._isActive,isArchived:this._isArchived,resetPassword:this._resetPassword,createdAt:this._createdAt.toISOString(),updatedAt:this._updatedAt.toISOString(),access:[...this._access],version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ne.safeParse(t);if(!r.success)return void console.error("Invalid LogInJSON:",r.error.flatten());const n=r.data;return oe.from({id:n.id,profileId:n.profileId,name:n.name,identity:n.identity,type:n.type,roleId:n.roleId,isActive:n.isActive,isArchived:n.isArchived,resetPassword:n.resetPassword,createdAt:n.createdAt,updatedAt:n.updatedAt,access:n.access})}catch(e){return void console.error("Error parsing LogInJSON:",e)}}static isLogInJSON(e){return ne.safeParse(e).success}}const ae=e.object({id:e.string(),name:e.string(),description:e.string().optional(),access:e.array(e.string()),createdAt:e.string(),updatedAt:e.string(),version:e.string().optional().default("1.0")});class se{id;name;description;permissions;createdAt;updatedAt;constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.permissions=new Set(e.access),this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}hasPermission(e){return this.permissions.has(e)}static from(e){try{if(!e?.id||!e?.name||!Array.isArray(e?.access))return;return new se(e)}catch(e){return void console.error("Error creating Role:",e)}}toJSON(){return{id:this.id,name:this.name,description:this.description,access:Array.from(this.permissions),createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ae.safeParse(t);if(!r.success)return void console.error("Invalid RoleJSON:",r.error.flatten());const n=r.data;return se.from({id:n.id,name:n.name,description:n.description,access:n.access,createdAt:n.createdAt,updatedAt:n.updatedAt})}catch(e){return void console.error("Error parsing RoleJSON:",e)}}static isRoleJSON(e){return ae.safeParse(e).success}}const ie=e.object({companyProfile:ee,role:ae.optional(),version:e.string().optional().default("1.0")});class ce{_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return te.is(e.companyProfile)?new ce(e):void console.error("Invalid company profile")}catch(e){return void console.error("Error creating CompanyMembership:",e)}}get companyProfile(){return this._companyProfile}get role(){return this._role}toJSON(){return{companyProfile:this._companyProfile.toJSON(),role:this._role?.toJSON(),version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ie.safeParse(t);if(!r.success)return void console.error("Invalid CompanyMembershipJSON:",r.error.flatten());const n=r.data,o=te.fromJSON(n.companyProfile),a=n.role?se.fromJSON(n.role):void 0;return o?ce.from({companyProfile:o,role:a}):void console.error("Failed to reconstruct Profile from CompanyMembershipJSON")}catch(e){return void console.error("Error parsing CompanyMembershipJSON:",e)}}static isCompanyMembershipJSON(e){return ie.safeParse(e).success}}const ue=e.object({logIn:ne,companyProfile:ee,role:ae.optional(),token:e.string().min(1),version:e.string().optional().default("1.0")});class de{_logIn;_membership;_token;_permissionMap;constructor(e){this._logIn=e.logIn,this._membership=e.membership,this._token=e.token,this._permissionMap={},this._logIn.access.forEach(e=>{this._permissionMap[e]=!0})}static from(e){try{if(!e.logIn||!e.companyProfile||!e.token)return void console.error("Missing required User fields");if("string"!=typeof e.token||""===e.token.trim())return void console.error("Invalid token");const t=ce.from({companyProfile:e.companyProfile,role:e.role});return t?new de({logIn:e.logIn,membership:t,token:e.token}):void console.error("Failed to create CompanyMembership")}catch(e){return void console.error("Error creating User:",e)}}get logIn(){return this._logIn}get membership(){return this._membership}get token(){return this._token}get id(){return this._logIn.id}get name(){return this._logIn.name}get identity(){return this._logIn.identity}get roleId(){return this._logIn.roleId}get resetPassword(){return this._logIn.resetPassword}get profile(){return this._membership.companyProfile}get role(){return this._membership.role}get access(){return this._logIn.access}can(e){return this._permissionMap[e]??!1}canAny(e){return e.some(e=>this.can(e))}canAll(e){return e.every(e=>this.can(e))}canManageTeam(){return this.can(v.TeamManagement.ViewMembers)}canViewRoles(){return this.can(v.Role.ViewRole)}toJSON(){return{logIn:this._logIn.toJSON(),companyProfile:this._membership.companyProfile.toJSON(),role:this._membership.role?.toJSON(),token:this._token,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ue.safeParse(t);if(!r.success)return void console.error("Invalid UserJSON:",r.error.flatten());const n=r.data,o=oe.fromJSON(n.logIn),a=te.fromJSON(n.companyProfile),s=n.role?se.fromJSON(n.role):void 0;if(!o||!a)return void console.error("Failed to reconstruct nested objects from UserJSON");if(!n.token||""===n.token.trim())return void console.error("Invalid token in UserJSON");const i=ce.from({companyProfile:a,role:s});return i?new de({logIn:o,membership:i,token:n.token}):void console.error("Failed to create CompanyMembership from UserJSON")}catch(e){return void console.error("Error parsing UserJSON:",e)}}static isUserJSON(e){return ue.safeParse(e).success}}const le=E().router({logIn:{method:"POST",path:"/login",body:t.object({type:t.string().default("password"),identity:t.string().email(),password:t.string()}),responses:{201:t.object({profile:X.profileDTOSchema,token:t.string(),access:t.array(t.string()),resetPassword:t.boolean()}),400:t.object({})}},access:{method:"GET",path:"/access",responses:{200:t.string().array()}},resetPassword:{method:"PUT",path:"/password",body:t.object({currentPassword:t.string(),newPassword:t.string()}),responses:{}}}),me=E().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:re.loginDTO}}});class he extends L{constructor(e){super("login",me,e)}async getIdentity(){const e=await this.client.getUserCredentials();if(200===e.status)return e.body;throw new Error(`Failed to get user identity. Status: ${e.status}`)}}const pe=t.string().min(8,"Password must be at least 8 characters long").max(128,"Password must not exceed 128 characters").regex(/[A-Z]/,"Password must contain at least one uppercase letter").regex(/[a-z]/,"Password must contain at least one lowercase letter").regex(/[0-9]/,"Password must contain at least one number").regex(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/,"Password must contain at least one special character (!@#$%^&*()_+-=[]{}|;:,.<>?)").refine(e=>![/(.)\1{2,}/,/123456|654321|abcdef|qwerty|password|admin|user/i,/^[0-9]+$/,/^[a-zA-Z]+$/].some(t=>t.test(e)),"Password contains weak patterns. Avoid repeated characters, common words, or simple sequences").refine(e=>!/(?:abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789)/i.test(e),"Password should not contain sequential characters").refine(e=>!/(?:qwer|wert|erty|rtyu|tyui|yuio|uiop|asdf|sdfg|dfgh|fghj|ghjk|hjkl|zxcv|xcvb|cvbn|vbnm)/i.test(e),"Password should not contain keyboard patterns"),fe=t.object({id:t.string().min(1),name:t.string().min(1,"Role name is required"),description:t.string().optional(),access:t.array(t.string()),createdAt:t.string().datetime("Invalid creation timestamp"),updatedAt:t.string().datetime("Invalid update timestamp")}),ye=t.object({id:t.string().min(1),name:t.string().min(1,"Team member name is required"),identity:t.string().email("Invalid email address"),type:t.string().min(1,"Team member type is required"),profileId:t.string().min(1,"Profile ID is required"),roleId:t.string().min(1,"Role ID is required"),resetPassword:t.boolean(),isActive:t.boolean(),isArchived:t.boolean(),role:fe.optional(),createdAt:t.string().datetime("Invalid creation timestamp"),updatedAt:t.string().datetime("Invalid update timestamp")}),ge={role:fe,teamMember:ye,teamMemberQueryParams:t.object({id:t.string().min(1).optional(),name:t.string().min(1).optional(),identity:t.string().email("Invalid email address").optional(),type:t.string().min(1).optional(),profileId:t.string().min(1).optional(),roleId:t.string().min(1).optional(),resetPassword:t.number().optional(),isActive:t.number().optional(),isArchived:t.number().optional(),createdAt:t.string().datetime("Invalid creation timestamp").optional(),updatedAt:t.string().datetime("Invalid update timestamp").optional(),eager:t.string().optional()}),createTeamMemberRequest:t.object({name:t.string().min(1,"Team member name is required"),identity:t.string().email("Valid email address is required"),password:pe.optional(),roleId:t.string().optional(),resetPassword:t.boolean().optional()}),updateTeamMemberRequest:t.object({name:t.string().min(1,"Team member name cannot be empty").optional(),roleId:t.string().min(1,"Role ID cannot be empty").optional(),password:pe.optional(),resetPassword:t.boolean().optional(),isActive:t.boolean().optional()}),resetPasswordRequest:t.object({newPassword:pe.optional(),sendNotification:t.boolean().optional()}),createTeamMemberResponse:t.object({id:t.string(),name:t.string(),identity:t.string(),type:t.string(),profileId:t.string(),resetPassword:t.boolean(),roleId:t.string(),isActive:t.boolean(),isArchived:t.boolean(),createdAt:t.string().datetime(),updatedAt:t.string().datetime()}),password:pe},Ne=E().router({getTeamMembers:{method:"GET",path:"/login",query:ge.teamMemberQueryParams,responses:{200:t.array(ge.teamMember),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"List all team members",description:"Retrieve a list of all team member accounts in the system"},getTeamMember:{method:"GET",path:"/login/:id",pathParams:t.object({id:t.string()}),query:ge.teamMemberQueryParams,responses:{200:ge.teamMember,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Get team member details",description:"Retrieve detailed information about a specific team member"},createTeamMember:{method:"POST",path:"/login",body:ge.createTeamMemberRequest,responses:{201:ge.createTeamMemberResponse,400:t.object({message:t.string().optional(),errors:t.array(t.string()).optional()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),409:t.object({message:t.string().optional()})},summary:"Create new team member",description:"Create a new team member account with specified role and permissions"},updateTeamMember:{method:"PATCH",path:"/login/:id",pathParams:t.object({id:t.string()}),body:ge.updateTeamMemberRequest,responses:{200:ge.teamMember,400:t.object({message:t.string().optional(),errors:t.array(t.string()).optional()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Update team member",description:"Update team member information, role, status, or force password reset"},archiveTeamMember:{method:"POST",path:"/login/:id/archive",pathParams:t.object({id:t.string()}),body:t.object({}),responses:{200:ge.teamMember,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Archive team member",description:"Archive (soft delete) a team member account"},unArchiveTeamMember:{method:"POST",path:"/login/:id/unarchive",pathParams:t.object({id:t.string()}),body:t.object({}),responses:{200:ge.teamMember,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Unarchive team member",description:"Unarchive a previously archived team member account"},resetPassword:{method:"POST",path:"/login/:id/reset-password",pathParams:t.object({id:t.string()}),body:ge.resetPasswordRequest,responses:{200:t.object({success:t.boolean()}),400:t.object({message:t.string().optional()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Reset team member password",description:"Reset a team member's password and optionally send notification"},getRoles:{method:"GET",path:"/role",responses:{200:t.array(ge.role),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"List all roles",description:"Retrieve a list of all available roles in the system"},getRole:{method:"GET",path:"/role/:id",pathParams:t.object({id:t.string()}),responses:{200:ge.role,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Get role details",description:"Retrieve detailed information about a specific role"}}),be=e.object({id:e.string(),name:e.string(),identity:e.string(),type:e.string(),profileId:e.string(),roleId:e.string(),resetPassword:e.boolean(),isActive:e.boolean(),isArchived:e.boolean(),role:ae.optional(),createdAt:e.string(),updatedAt:e.string(),version:e.string().optional().default("1.0")});class we{id;name;identity;type;profileId;roleId;resetPassword;isActive;isArchived;role;createdAt;updatedAt;permissions;constructor(e){if(this.id=e.id,this.name=e.name,this.identity=e.identity,this.type=e.type,this.profileId=e.profileId,this.roleId=e.roleId,this.resetPassword=e.resetPassword,this.isActive=e.isActive,this.isArchived=e.isArchived,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.permissions=new Set(e.role?.access??[]),e.role)try{this.role=new se(e.role)}catch(e){}}static from(e){try{return e?.id&&e?.name&&e?.identity&&e?.roleId?new we(e):void console.error("Missing required TeamMember fields:",e)}catch(e){return void console.error("Error creating TeamMember:",e)}}static fromJson(e){try{const t=JSON.parse(e);return we.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>we.from(e)).filter(Boolean)}can(e){return this.permissions.has(e)}canAny(e){return e.some(e=>this.permissions.has(e))}canAll(e){return e.every(e=>this.permissions.has(e))}isAccountActive(){return this.isActive}isAccountArchived(){return this.isArchived}needsPasswordReset(){return this.resetPassword}getAccountStatus(){return this.isArchived?{status:"archived",label:"Archived",color:"default",description:"Account has been archived and is no longer accessible"}:this.isActive?this.resetPassword?{status:"password_reset_required",label:"Password Reset Required",color:"warning",description:"User must reset their password on next login"}:{status:"active",label:"Active",color:"success",description:"Account is active and ready to use"}:{status:"inactive",label:"Inactive",color:"error",description:"Account has been deactivated by an administrator"}}getRoleName(){return this.role?.name??""}getCreatedDate(){return this.createdAt.toLocaleDateString()}getLastUpdateInfo(){const e=(new Date).getTime()-this.updatedAt.getTime(),t=Math.floor(e/864e5);return 0===t?"Today":1===t?"Yesterday":t<7?`${t} days ago`:t<30?`${Math.floor(t/7)} weeks ago`:this.updatedAt.toLocaleDateString()}toJSON(){return{id:this.id,name:this.name,identity:this.identity,type:this.type,profileId:this.profileId,roleId:this.roleId,resetPassword:this.resetPassword,isActive:this.isActive,isArchived:this.isArchived,role:this.role?.toJSON(),createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=be.safeParse(t);if(!r.success)return void console.error("Invalid TeamMemberJSON:",r.error.flatten());const n=r.data,o=n.role?{id:n.role.id,name:n.role.name,description:n.role.description,access:n.role.access,createdAt:n.role.createdAt,updatedAt:n.role.updatedAt}:void 0;return we.from({id:n.id,name:n.name,identity:n.identity,type:n.type,profileId:n.profileId,roleId:n.roleId,resetPassword:n.resetPassword,isActive:n.isActive,isArchived:n.isArchived,role:o,createdAt:n.createdAt,updatedAt:n.updatedAt})}catch(e){return void console.error("Error parsing TeamMemberJSON:",e)}}static isTeamMemberJSON(e){return be.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>we.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing TeamMember JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}}class ve extends L{constructor(e){super("admin",Ne,e)}async createTeamMember(e){const t=await this.client.createTeamMember({body:e});return this.handleResponse(t,201)}async updateTeamMember(e,t){const r=await this.client.updateTeamMember({params:{id:e},body:t}),n=this.handleResponse(r,200),o=we.from(n);if(!o)throw new Error("Invalid team member data received from server");return o}async archiveTeamMember(e){const t=await this.client.archiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),n=we.from(r);if(!n)throw new Error("Invalid team member data received from server");return n}async unArchiveTeamMember(e){const t=await this.client.unArchiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),n=we.from(r);if(!n)throw new Error("Invalid team member data received from server");return n}async resetTeamMemberPassword(e,t={}){const r=await this.client.resetPassword({params:{id:e},body:t});return this.handleResponse(r,200)}async getAllTeamMembers(e={eager:"role"}){const t=await this.client.getTeamMembers({query:e}),r=this.handleResponse(t,200);return we.createMany(r)}async getTeamMember(e,t={eager:"role"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),n=this.handleResponse(r,200),o=we.from(n);if(!o)throw new Error("Invalid team member data received from server");return o}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=se.from(e);if(!t)throw new Error("Invalid role data received from server");return t})}async getRole(e){const t=await this.client.getRole({params:{id:e}}),r=this.handleResponse(t,200),n=se.from(r);if(!n)throw new Error("Invalid role data received from server");return n}}class Ce extends L{constructor(e){super("auth",le,e)}async logIn(e,t){const r={type:"password",identity:e,password:t},n=await this.client.logIn({body:r});if(400===n.status)throw new w({message:"Invalid email or password",statusCode:400});if(201===n.status){const e=n.body.token,t=new he({token:e}),r=await t.getIdentity(),o=oe.from(r);if(!o)throw new w({message:"Failed to construct login credentials",statusCode:502});const a=n.body.profile,s=te.from(a);if(!s)throw new w({message:"Failed to construct user profile",statusCode:502});let i;if(o.access.includes(v.Role.ViewRole))try{const t=new ve({token:e});i=await t.getRole(o.roleId)}catch(e){console.warn("Failed to fetch role details:",e)}const c=de.from({logIn:o,companyProfile:s,role:i,token:e});if(!c)throw new w({message:"Failed to construct user session",statusCode:502});return c}throw new w({message:"An error occurred while trying to log in",statusCode:502})}async updatePassword(e,t){const r=await this.client.resetPassword({body:{currentPassword:e,newPassword:t}});if(200===r.status)return!0;if(400===r.status)throw new w({message:"Invalid current password",statusCode:400});throw new w({message:"An error occurred while trying to update password",statusCode:502})}async getAccessList(){const e=await this.client.access();if(200===e.status)return e.body;throw new Error(`Failed to get access list. Status: ${e.status}`)}}var Se;!function(e){e.Bank="Bank",e.Mobile="Mobile"}(Se||(Se={}));const Oe=t.nativeEnum(Se),Ae=t.object({displayName:t.string().min(1,"Display name is required"),accountNo:t.string().min(1,"Account number is required"),channel:t.string().min(1,"Channel is required"),type:Oe}),Ie={contactDTO:t.object({id:t.string().min(1,"Contact id is required"),profileId:t.string(),createdAt:t.string().datetime(),updatedAt:t.string().datetime()}).merge(Ae),contactInputDTO:Ae,contactType:Oe},_e=t.object({type:t.literal("Mobile"),name:t.string().min(1),phoneNumber:t.string().regex(/^\+[1-9]\d{6,14}$/),mnoId:t.string().min(1),version:t.string().optional().default("1.0")}),Pe=t.object({type:t.literal("Bank"),accName:t.string().min(1),swiftCode:t.string().length(8),countryCode:t.string().length(2),accNo:t.string().min(1),version:t.string().optional().default("1.0")}),Ee=t.discriminatedUnion("type",[_e,Pe]);class De extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="ContactInfoError"}}class Re{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}toJSONString(){return JSON.stringify(this.toJSON())}get isMobile(){return this.type===Se.Mobile}get isBank(){return this.type===Se.Bank}get displayName(){return this.accountName}}class Te extends Re{name;phoneNumber;mnoId;constructor(e,t,r){if(super(Se.Mobile,t.countryCode),this.name=e,this.phoneNumber=t,!e?.trim())throw new De("Name is required and cannot be empty",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(!t?.validate())throw new De("Invalid phone number",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(n.requiresExplicitMNO(t.countryCode)){if(!r)throw new De(`MNO must be explicitly provided for phone numbers in ${t.countryCode} due to Mobile Number Portability`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});if(!n.isValidMNOForCountry(r,t.countryCode)){const e=n.getCountryMNOs(t.countryCode).map(e=>e.id);throw new De(`Invalid MNO ${r} for country ${t.countryCode}. Valid MNOs: ${e.join(", ")}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,mnoId:r,operation:"constructor"})}this.mnoId=r}else{const e=n.getMNOByPhoneNumber(t.e164Format,t.countryCode);if(!e?.id)throw new De(`Failed to determine MNO for phone number ${t.e164Format}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});this.mnoId=e.id}}static from(e){try{return new Te(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileContactInfo:",e)}}static fromContactDTO(e){if("Mobile"!==e.type)return;let t=e.accountNo;t.startsWith("+")||(t=`+${t}`);const r=o.from(t);if(!r)return void console.error(`Failed to parse phone number ${t}`);const a=r.countryCode;try{let t;if(n.requiresExplicitMNO(a)){if(e.channel&&"string"==typeof e.channel){if(!n.isValidMNOForCountry(e.channel,a))return void console.warn(`Invalid MNO ${e.channel} for country ${a}`);t=e.channel}}else if(t=n.getMNOByPhoneNumber(r.e164Format,a)?.id,!t)return void console.warn(`Failed to auto-detect MNO for phone number ${r.e164Format}`);return Te.from({name:e.displayName,phoneNumber:r,mnoId:t})}catch(e){return void console.error(`Failed to create MobileContactInfo: ${e}`)}}static fromPayoutDTO(e){try{if(!a.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=o.from(e.msisdn,{defaultCountry:e.countryCode});if(!t)return void console.error(`Failed to parse phone number: ${e.msisdn}`);let r;if(n.requiresExplicitMNO(t.countryCode)){if(e.channel&&"string"==typeof e.channel){if(!n.isValidMNOForCountry(e.channel,t.countryCode))return void console.warn(`Invalid MNO ${e.channel} for country ${t.countryCode} in PayoutDTO`);r=e.channel}}else if(r=n.getMNOByPhoneNumber(t.e164Format,t.countryCode)?.id,!r)return void console.warn(`Failed to auto-detect MNO for phone number ${t.e164Format}`);return Te.from({name:e.payeeName,phoneNumber:t,mnoId:r})}catch(t){return void console.error("Failed to create MobileContactInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.name||!t.name.trim())return!1;let r;if("string"==typeof t.phoneNumber)r=o.from(t.phoneNumber);else if("object"==typeof t.phoneNumber){const e=t.phoneNumber;o.is(e)&&(r=o.from(e.e164Format))}if(!r)return!1;const a=t.mnoId;if("string"!=typeof a)return!1;if(!n.isValidMNOForCountry(a,r.countryCode))return!1;if(n.requiresExplicitMNO(r.countryCode))return!0;{const e=n.getMNOByPhoneNumber(r.e164Format,r.countryCode);return e?.id===a}}validate(){try{return!!this.name?.trim()&&(!!this.phoneNumber?.validate()&&(!!n.isValidMNOForCountry(this.mnoId,this.countryCode)&&(!!n.requiresExplicitMNO(this.countryCode)||n.validateMNOForPhoneNumber(this.phoneNumber.e164Format,this.mnoId,this.countryCode))))}catch{return!1}}getValidationDetails(){const e=[];if(this.name?.trim()||e.push("Name is required"),this.phoneNumber?.validate()||e.push("Phone number is invalid"),n.isValidMNOForCountry(this.mnoId,this.countryCode)||e.push(`Invalid MNO ${this.mnoId} for country ${this.countryCode}`),!n.requiresExplicitMNO(this.countryCode)){const t=n.getMNOByPhoneNumber(this.phoneNumber.e164Format,this.countryCode);t?.id!==this.mnoId&&e.push("MNO doesn't match auto-detected value from phone number prefix")}return{isValid:0===e.length,errors:e,warnings:[]}}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(s.E164)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){const e=n.getMNOById(this.mnoId,this.countryCode);return e?.mobileMoneyService??e?.displayName??this.mnoId}toJSON(){return{type:"Mobile",name:this.name,phoneNumber:this.phoneNumber.e164Format,mnoId:this.mnoId,version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=_e.safeParse(t);if(!r.success)return void console.error("Invalid MobileContactInfoJSON:",r.error.flatten());const a=r.data,s=o.from(a.phoneNumber);if(!s?.validate())return void console.warn("Invalid phone number in JSON");if(!n.isValidMNOForCountry(a.mnoId,s.countryCode))return void console.warn("Invalid MNO for country");if(!n.requiresExplicitMNO(s.countryCode)){const e=n.getMNOByPhoneNumber(s.e164Format,s.countryCode);if(e?.id!==a.mnoId)return void console.warn("MNO mismatch with auto-detected value")}return Te.from({name:a.name,phoneNumber:s,mnoId:a.mnoId})}catch(e){return void console.error("Error parsing MobileContactInfoJSON:",e)}}static fromJSONString(e){return Te.fromJSON(e)}static isMobileContactInfoJSON(e){return _e.safeParse(e).success}}class Je extends Re{accName;bank;accNo;constructor(e,t,r){if(super(Se.Bank,t.countryCode),this.accName=e,this.bank=t,this.accNo=r,!i.validateAccountName(e))throw new De("Invalid account name",{operation:"constructor",countryCode:t.countryCode});if(!i.validateAccountNumber(r,t.countryCode))throw new De("Invalid account number",{operation:"constructor",countryCode:t.countryCode})}static from(e){try{return new Je(e.accName,e.bank,e.accNo)}catch(e){return void console.error("Failed to create BankContactInfo:",e)}}static fromContactDTO(e){if("Bank"!==e.type)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank contacts");const r=i.getCountryFromSwiftCode(t);if(r)if(i.validateSwiftCode(t,r))try{const n=c.from(t,r);if(!n)throw new Error(`Bank with SWIFT code ${t} not found`);return Je.from({accName:e.displayName,bank:n,accNo:e.accountNo})}catch(e){return void console.error(`Failed to create BankContactInfo: ${e}`)}else console.error(`Invalid SWIFT code ${t} for country ${r}`);else console.error(`Could not identify country from SWIFT code: ${t}`)}static fromPayoutDTO(e){try{if(!a.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=e.msisdn.trim().split(":");if(2!==t.length)return void console.error("Invalid PayoutDTO format for bank - expected 'swiftcode:accountno'");const[r,n]=t;if(!i.validateSwiftCode(r,e.countryCode))return void console.error(`Invalid SWIFT code ${r} for country ${e.countryCode}`);const o=c.from(r,e.countryCode);return o?Je.from({accName:e.payeeName,bank:o,accNo:n}):void console.error(`Bank with SWIFT code ${r} not found`)}catch(t){return void console.error("Failed to create BankContactInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.accName)return!1;if("string"!=typeof t.accNo)return!1;if(!t.bank||!c.is(t.bank))return!1;const r=t.accName,n=t.accNo,o=t.bank,a=i.validateAccountName(r),s=i.validateAccountNumber(n,o.countryCode);return a&&s}validate(){try{return i.validateAccountName(this.accName)&&i.validateAccountNumber(this.accNo,this.bank.countryCode)&&c.is(this.bank)}catch{return!1}}get accountName(){return this.accName}get accountNumber(){return this.accNo}get accountNameLabel(){return"Acc. Name"}get accountNumberLabel(){return"Bank Acc. No."}get channelLabel(){return"Bank"}get channelId(){return this.bank.swiftCode}get channelName(){return this.bank.shortName}toJSON(){return{type:"Bank",accName:this.accName,swiftCode:this.bank.swiftCode,countryCode:this.bank.countryCode,accNo:this.accNo,version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Pe.safeParse(t);if(!r.success)return void console.error("Invalid BankContactInfoJSON:",r.error.flatten());const n=r.data;if(!a.isISO2CountryCode(n.countryCode)||!i.validateSwiftCode(n.swiftCode,n.countryCode))return;const o=c.from(n.swiftCode,n.countryCode);if(!o)return;if(!i.validateAccountName(n.accName)||!i.validateAccountNumber(n.accNo,n.countryCode))return;return Je.from({accName:n.accName,bank:o,accNo:n.accNo})}catch(e){return void console.error("Error parsing BankContactInfoJSON:",e)}}static fromJSONString(e){return Je.fromJSON(e)}static isBankContactInfoJSON(e){return Pe.safeParse(e).success}}const je=t.object({data:Ie.contactDTO,version:t.string().optional().default("1.0")});class Me{data;constructor(e){this.data=Ie.contactDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get displayName(){return this.data.displayName}get type(){return this.data.type}get createdAt(){return new Date(this.data.createdAt)}get updatedAt(){return new Date(this.data.updatedAt)}get info(){return this.data.type===Se.Mobile?Te.fromContactDTO(this.data):this.data.type===Se.Bank?Je.fromContactDTO(this.data):void 0}get accNo(){const e=this.info;return e?e.accountNumber:this.data.accountNo}get accName(){return this.data.displayName}get accNoLabel(){const e=this.info;return e instanceof Te?"Phone Number":e instanceof Je?"Bank Account Number":"Account Number"}get channelLabel(){const e=this.info;return e instanceof Te?"Channel":e instanceof Je?"Bank":"Channel"}get accNameLabel(){const e=this.info;return e instanceof Te?"Full Name":e instanceof Je?"Bank Account Name":"Display Name"}get channelName(){const e=this.info;return e instanceof Te||e instanceof Je?e.channelName:""}static from(e){try{return new Me(e)}catch(e){return void console.error("Failed to create Contact:",e)}}static create(e){return new Me(e)}static createMany(e){return e.map(e=>new Me(e))}static createSafe(e){try{return new Me(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=Ie.contactDTO.safeParse(e);if(!t.success)return!1;return null!==Me.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&Me.canConstruct(e.data))}toJSON(){return{data:{...this.data},version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=je.safeParse(t);if(!r.success)return void console.error("Invalid ContactJSON:",r.error.flatten());const n=r.data;return Me.from(n.data)}catch(e){return void console.error("Error parsing ContactJSON:",e)}}static fromJSONString(e){return Me.fromJSON(e)}static isContactJSON(e){return je.safeParse(e).success}}class Be{canHandle(e){return"Mobile"===e.type&&Te.is(e)}createInput(e){if(Te.is(e))return{type:Se.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Contact Info")}}class Fe{canHandle(e){return"Bank"===e.type&&Je.is(e)}createInput(e){if(Je.is(e))return{type:Se.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Contact Info")}}class xe{handlers=[new Be,new Fe];resolve(e){const t=this.handlers.find(t=>t.canHandle(e));if(!t)throw new Error("Please check your data and try again");return t.createInput(e)}}const ke=E().router({createContact:{method:"POST",path:"/",body:Ie.contactInputDTO,responses:{201:Ie.contactDTO}},editContact:{method:"PATCH",path:"/:id",body:Ie.contactInputDTO,responses:{200:Ie.contactDTO}},getContacts:{method:"GET",path:"/",query:t.object({orderByDesc:t.string()}),responses:{200:t.array(Ie.contactDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:Ie.contactDTO}},deleteContact:{method:"DELETE",path:"/:id",body:t.object({}),responses:{200:t.object({})}}});class $e extends L{constructor(e){super("contact",ke,e)}async create(e){const t=(new xe).resolve(e),r=await this.client.createContact({body:t}),n=this.handleResponse(r,201);return Me.create(n)}async edit(e,t){const r=(new xe).resolve(t),n=await this.client.editContact({params:{id:e},body:r}),o=this.handleResponse(n,200);return Me.create(o)}async remove(e){const t=await this.client.deleteContact({params:{id:e}});this.handleResponse(t,200)}async getAll(){const e=await this.client.getContacts({query:{orderByDesc:"createdAt"}}),t=this.handleResponse(e,200);return Me.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return Me.create(r)}}var Ue,Le,qe;!function(e){e.MOBILE="Mobile",e.BANK="Bank"}(Ue||(Ue={})),function(e){e.CREATED="CREATED",e.PENDING="PENDING",e.PAID="PAID",e.FAILED="FAILED",e.REJECTED="REJECTED",e.REVERSED="REVERSED",e.QUEUED="QUEUED"}(Le||(Le={})),function(e){e.PENDING="Pending",e.APPROVED="Approved",e.REJECTED="Rejected"}(qe||(qe={}));const Ve=t.object({id:t.string(),name:t.string(),identity:t.string()}),We=t.nativeEnum(Le),Ge=t.nativeEnum(qe),He=t.object({channel:t.string(),msisdn:t.string(),amount:t.coerce.number(),description:t.string(),notes:t.string().nullish()}),Qe=He.extend({payeeName:t.string()}),Ke=He.extend({id:t.string(),profileId:t.string(),payeeName:t.string(),countryCode:t.string().default("TZ").refine(e=>a.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.string().default("TZS").refine(e=>u.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),channel:t.string(),status:We,statusMessage:t.string(),partnerReference:t.string().nullish(),createdAt:t.coerce.date(),updatedAt:t.coerce.date(),actionedAt:t.coerce.date().nullish(),approvalStatus:Ge.nullish(),createdBy:Ve.nullish(),actionedBy:Ve.nullish()}),Ye=t.object({page:t.number().int().positive().default(1),limit:t.number().int().positive().max(100).default(10),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().datetime().nullish(),endDate:t.string().datetime().nullish(),payeeName:t.string().nullish(),msisdn:t.string().nullish(),profileId:t.string().nullish(),id:t.string().nullish(),partnerReference:t.string().nullish(),channel:t.string().nullish(),currencyCode:t.string().nullish(),status:We.nullish(),approvalStatus:Ge.nullish(),minAmount:t.number().min(0).nullish(),maxAmount:t.number().min(0).nullish(),search:t.string().nullish()}),Ze={PayoutDTO:Ke,PayoutInputDTO:Qe,PayoutStatus:We,PayoutApprovalStatus:Ge,PayoutAuthorizer:Ve,PayoutFilters:Ye,PayoutURLQueryParams:t.object({page:t.string().transform(e=>parseInt(e)||1).optional(),limit:t.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().optional(),endDate:t.string().optional(),payeeName:t.string().optional(),msisdn:t.string().optional(),profileId:t.string().optional(),id:t.string().optional(),partnerReference:t.string().optional(),channel:t.string().optional(),status:t.string().refine(e=>Object.values(Le).includes(e)).transform(e=>e).optional(),approvalStatus:t.string().refine(e=>Object.values(qe).includes(e)).transform(e=>e).optional(),minAmount:t.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.string().transform(e=>parseFloat(e)).optional(),search:t.string().optional()})},ze=e.object({id:e.string(),profileId:e.string(),payeeName:e.string(),channel:e.string(),msisdn:e.string(),amount:e.number(),currencyCode:e.string(),countryCode:e.string(),description:e.string(),notes:e.string().nullish(),status:Ze.PayoutStatus,statusMessage:e.string(),partnerReference:e.string().nullish(),createdAt:e.string(),updatedAt:e.string(),actionedAt:e.string().nullish(),approvalStatus:Ze.PayoutApprovalStatus.nullish(),createdBy:Ze.PayoutAuthorizer.nullish(),actionedBy:Ze.PayoutAuthorizer.nullish(),version:e.string().optional().default("1.0")});class Xe{data;constructor(e){this.data=Ze.PayoutDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get payeeName(){return this.data.payeeName}get channel(){return this.data.channel}get msisdn(){return this.data.msisdn}get amount(){return d.from(this.data.amount,this.data.currencyCode)}get description(){return this.data.description}get notes(){return this.data.notes}get status(){return"Rejected"===this.data.approvalStatus?Le.REJECTED:"Approved"===this.data.approvalStatus?"FAILED"===this.data.status?Le.FAILED:Le.PAID:"Pending"===this.data.approvalStatus?Le.PENDING:this.data.status}get statusMessage(){return this.data.statusMessage}get partnerReference(){return this.data.partnerReference}get createdAt(){return this.data.createdAt}get updatedAt(){return this.data.updatedAt}get actionedAt(){return this.data.actionedAt}get approvalStatus(){return this.data.approvalStatus}get createdBy(){return this.data.createdBy}get actionedBy(){return this.data.actionedBy}get contactInfo(){return"TZ-BANK-B2C"===this.channel?Je.fromPayoutDTO(this.data):Te.fromPayoutDTO(this.data)}static create(e){return new Xe(e)}static createMany(e){return e.map(e=>new Xe(e))}static createSafe(e){try{return new Xe(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=Ze.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==Xe.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&Xe.canConstruct(e.data))}toJSON(){return{id:this.data.id,profileId:this.data.profileId,payeeName:this.data.payeeName,channel:this.data.channel,msisdn:this.data.msisdn,amount:this.data.amount,currencyCode:this.data.currencyCode,countryCode:this.data.countryCode,description:this.data.description,notes:this.data.notes,status:this.data.status,statusMessage:this.data.statusMessage,partnerReference:this.data.partnerReference,createdAt:this.data.createdAt.toISOString(),updatedAt:this.data.updatedAt.toISOString(),actionedAt:this.data.actionedAt?.toISOString()??null,approvalStatus:this.data.approvalStatus,createdBy:this.data.createdBy,actionedBy:this.data.actionedBy,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ze.safeParse(t);if(!r.success)return void console.error("Invalid PayoutJSON:",r.error.flatten());const n=r.data,o=n.currencyCode;if(!u.isCurrencyCode(o))return void console.error("Invalid currency code:",o);const s=n.countryCode;if(!a.isISO2CountryCode(s))return void console.error("Invalid country code:",s);const i={id:n.id,profileId:n.profileId,payeeName:n.payeeName,channel:n.channel,msisdn:n.msisdn,amount:n.amount,currencyCode:o,countryCode:s,description:n.description,notes:n.notes,status:n.status,statusMessage:n.statusMessage,partnerReference:n.partnerReference,createdAt:new Date(n.createdAt),updatedAt:new Date(n.updatedAt),actionedAt:n.actionedAt?new Date(n.actionedAt):null,approvalStatus:n.approvalStatus,createdBy:n.createdBy,actionedBy:n.actionedBy};return Xe.create(i)}catch(e){return void console.error("Error parsing PayoutJSON:",e)}}static isPayoutJSON(e){return ze.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>Xe.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing Payout JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}}const et="MOBILE TRANSFER ",tt="PAYOUT",rt="PAYOUT TO BANK",nt="TO_BANK",ot="PAYOUT TO MOBILE",at="TO_MOMO",st=e.object({text:e.string(),version:e.string().optional().default("2.0")});class it{text;constructor(e){this.text=e}get mediumText(){return this.text.length>50?this.text.substring(0,47)+"...":this.text}get shortText(){return this.text.length>35?this.text.substring(0,32)+"...":this.text}static generateDefaultPayoutNarration(e){return Te.is(e)?it.generateMobilePayoutNarrationV2(e):Je.is(e)?it.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${tt.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:n}=e;return`${tt.toUpperCase()} ${t.swiftCode.trim()} ${n.trim()} ${r.trim()}`.toUpperCase()}getContactDetails=()=>{const e=this.getBankContactDetails(),t=this.getMobileContactDetails();return e||(t||void 0)};getBankContactDetails=()=>{let e=this.text.trim();e.startsWith(et)&&(e=e.substring(16));try{if(e.startsWith(tt)){const t=e.replace(tt,"").trim().split(" ");if(t.length>=3){const e=t[0],r=t[1],n=t.slice(2).map(ct).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=i.getCountryFromSwiftCode(e);if(t){if(i.validateSwiftCode(e,t)){const o=c.from(e,t);if(r&&n&&o)return new Je(n,o,r)}}}}}if(e.startsWith(nt)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=r.account_number,o=r.account_name,a=r.swift_code,s=i.getCountryFromSwiftCode(a);if(!s)return;if(!i.validateSwiftCode(a,s))return;const u=c.from(a,s);if(n&&o&&u)return new Je(o,u,n)}if(e.startsWith(rt)){const t=e.replace(rt,"").trim().split(" "),r=l.getInstance().searchBanks("TZ",t[0]),n=r.length>0?r[0]:void 0,o=t[1],a=t.slice(2).map(ct).join(" ");if(a&&o&&n)return new Je(a,n,o)}}catch(e){return}};getMobileContactDetails=()=>{let e=this.text.trim();e.startsWith(et)&&(e=e.substring(16));try{if(e.startsWith(tt)){const t=e.replace(tt,"").trim().split(" ");if(t.length>=2){const e=t[0],r=t.slice(1).map(ct).join(" ");if(e.startsWith("+")){const t=o.from(e);if(t&&r)return new Te(r,t)}}}if(e.startsWith(at)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=m.from(r.phone_number);let o=r.username;void 0===o&&(o="");let a=o.split(" ");if(a=a.filter(e=>e.trim().length>0),o=a.map(ct).join(" "),n&&o)return new Te(o,n)}if(e.startsWith(ot)){const t=e.replace(ot,"").trim().split(" "),r=m.from(t[0]),n=t.slice(1).map(ct).join(" ");if(r&&n)return new Te(n,r)}}catch(e){return}};static is(e){if(!e||"object"!=typeof e)return!1;const t=e;try{return"string"==typeof t.text&&"function"==typeof t.getContactDetails&&"function"==typeof t.toJson}catch(e){return!1}}toJSON(){return{text:this.text,version:"2.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=st.safeParse(t);if(!r.success)return void console.error("Invalid NarrationJSON:",r.error.flatten());const n=r.data;return new it(n.text)}catch(e){return void console.error("Error parsing NarrationJSON:",e)}}static isNarrationJSON(e){return st.safeParse(e).success}toJson(){return this.toJSON()}static fromJson(e){return it.fromJSON(e)}}function ct(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}const ut={SUPPORTED_COUNTRY_CODES:["TZ","KE"],ERROR_MESSAGES:{INVALID_PHONE_NUMBER:"Invalid phone number",INELIGIBLE_FOR_PAYOUT:"The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",MOBILE_NUMBER_MNO_MISMATCH:"There is a mismatch between the phone number provided and the MNO used.",UNSUPPORTED_COUNTRY_BANK:"Only Tanzanian Banks are supported for now",UNSUPPORTED_COUNTRY_MOBILE:"Only Tanzanian mobile numbers are supported for now",NO_HANDLER_FOUND:"Cannot create payout input!"}};class dt{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}}class lt{static forBank(e,t){if(!ut.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(ut.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,t,r){if(!o.is(e))throw new Error(ut.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!ut.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(ut.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!h.checkPayoutEligibility(e))throw new Error(ut.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const a=n.getMNOById(t,e.countryCode);if(!a)throw new Error(ut.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return a.id===p.VODACOM?`${r.countryCode}-${p.TIGO.toString().toUpperCase()}-B2C`:`${r.countryCode}-${a.id.toString().toUpperCase()}-B2C`}}class mt{canHandle(e,t,r){return e===Ue.MOBILE&&Te.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===f.from(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=dt.processNotes(e.notes),o=r.phoneNumber;return{channel:lt.forMobile(o,r.mnoId,t),msisdn:o.getWithFormat(s.INTERNATIONAL_NUMERIC),description:n??it.generateDefaultPayoutNarration(r),payeeName:r.name,notes:n,amount:e.amount.numericValue}}}class ht{canHandle(e,t,r){return e===Ue.BANK&&Je.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===f.from(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=dt.processNotes(e.notes);return{channel:lt.forBank(r,t),msisdn:`${r.bank.swiftCode}:${r.accNo}`,description:n??it.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:n,amount:e.amount.numericValue}}}class pt{handlers=[new mt,new ht];getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(ut.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const ft={bank:lt.forBank,mobile:lt.forMobile},yt=E().router({getPayouts:{method:"GET",path:"",query:t.object({}),responses:{200:t.object({results:t.array(Ze.PayoutDTO),total:t.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:t.object({rangeStart:t.number(),rangeEnd:t.number(),eager:t.string(),approvalStatus:Ze.PayoutApprovalStatus,orderByDesc:t.string()}),responses:{200:t.object({results:t.array(Ze.PayoutDTO),total:t.number()})}},postPayout:{method:"POST",path:"",body:Ze.PayoutInputDTO,responses:{201:Ze.PayoutDTO,400:w.schema}},approve:{method:"POST",path:"/:id/approve",body:t.object({action:t.enum(["Approve","Reject"]),notes:t.string().optional()}),responses:{201:Ze.PayoutDTO,404:t.object({}),409:t.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:Ze.PayoutDTO,404:t.object({})}}});class gt extends G{static create(){return new gt}static fromFilters(e){return(new gt).applyFilters(e)}static fromUrlParams(e){try{const t=Ze.PayoutURLQueryParams.parse(e),r=Ze.PayoutFilters.parse(t);return gt.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return gt.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return gt.fromSearchParams(t)}static from(e){try{return null==e?new gt:G.is(e)?new gt(e.options):e instanceof URLSearchParams?gt.fromSearchParams(e):this.isStringRecord(e)?gt.fromUrlParams(e):gt.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a PayoutQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereStatus(e){return this.where("status",e)}whereApprovalStatus(e){return this.where("approvalStatus",e)}whereChannel(e){return this.where("channel",e)}wherePending(){return this.whereApprovalStatus(qe.PENDING)}whereApproved(){return this.whereApprovalStatus(qe.APPROVED)}whereRejected(){return this.whereApprovalStatus(qe.REJECTED)}wherePaid(){return this.whereStatus(Le.PAID)}whereFailed(){return this.whereStatus(Le.FAILED)}whereAmountBetween(e,t){return e.currencyCode!==t.currencyCode||e.numericValue>t.numericValue?this:this.whereBetween("amount",e.numericValue,t.numericValue).whereCurrencyCode(e.currencyCode)}wherePayee(e){return this.whereContains("payeeName",e)}whereMsisdn(e){return this.whereContains("msisdn",e)}whereProfileId(e){return this.where("profileId",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){if((e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.status&&this.whereStatus(e.status),e.approvalStatus&&this.whereApprovalStatus(e.approvalStatus),e.channel&&this.whereChannel(e.channel),e.payeeName&&this.wherePayee(e.payeeName),e.msisdn&&this.whereMsisdn(e.msisdn),e.profileId&&this.whereProfileId(e.profileId),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.id&&this.where("id",e.id),void 0!==e.minAmount||void 0!==e.maxAmount){const t=void 0!==e.minAmount&&null!==e.minAmount,r=void 0!==e.maxAmount&&null!==e.maxAmount,{currencyCode:n}=e;if(!n||!u.isCurrencyCode(n))return console.warn("Amount filter requires a valid currency code"),this;if(t&&r){if(e.minAmount>e.maxAmount)return console.warn(`Invalid amount range: min (${e.minAmount}) > max (${e.maxAmount})`),this;const t=d.from(e.minAmount,n),r=d.from(e.maxAmount,n);t&&r&&this.whereAmountBetween(t,r)}else t?this.whereGreaterThanOrEqual("amount",e.minAmount).whereCurrencyCode(n):r&&this.whereLessThanOrEqual("amount",e.maxAmount).whereCurrencyCode(n)}return e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,payeeName:e.payeeName,msisdn:e.msisdn,profileId:e.profileId,id:e.id,partnerReference:e.partnerReference,channel:e.channel,status:this.isValidStatus(e.status)?e.status:void 0,approvalStatus:this.isValidApprovalStatus(e.approvalStatus)?e.approvalStatus:void 0,minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withApprovalStatus(e){const t=this.clone();return e&&t.whereApprovalStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}includeDefaultRelations(){return this.with("[createdBy,actionedBy]")}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.payeeName||e.msisdn||e.profileId||e.id||e.partnerReference||e.channel||e.status||e.approvalStatus||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.status&&e.push(`Status: ${t.status}`),t.approvalStatus&&e.push(`Approval: ${t.approvalStatus}`),t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.payeeName&&e.push(`Payee: ${t.payeeName}`),t.msisdn&&e.push(`MSISDN: ${t.msisdn}`),t.profileId&&e.push(`Profile: ${t.profileId}`),t.partnerReference&&e.push(`Ref: ${t.partnerReference}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"payeeName":case"msisdn":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}return e}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidStatus(e){return Object.values(Le).includes(e)}isValidApprovalStatus(e){return Object.values(qe).includes(e)}}class Nt extends L{constructor(e){super("payout",yt,e)}async getPayouts(e){try{const t=gt.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),o=this.handleResponse(n,200),a=t.toFilters(),s=new Y(a.page??1,a.limit??10,o.total);return{results:Xe.createMany(o.results),pagination:s}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getAllPayouts(e){try{const t=gt.from(e).build();delete t.page,delete t.limit;const r=await this.client.getPayouts({query:t}),n=this.handleResponse(r,200);return Xe.createMany(n)}catch(e){throw new Error(`Failed to fetch all payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=gt.fromRequest(e);return this.getPayouts(t)}async pay(e){const{wallet:t,channel:r,receiver:n,amount:o,notes:a}=e,{min:s,max:i}=d.getTransactionLimits(o.currencyCode);if(o.lessThan(s)||o.greaterThan(i))throw new w({statusCode:400,message:`Please make sure the amount is between ${s.label} - ${i.label}`});const c=(new pt).getPayoutInput({channel:r,receiver:n,amount:o,notes:a},t),u=await this.client.postPayout({body:c});if(201===u.status)return Xe.create(u.body);if(400===u.status)throw new w(u.body);throw w.unknown()}async approve(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Approve",notes:e.notes}});if(201===t.status)return Xe.create(t.body);if(404===t.status)throw new w({message:"Payout not found",statusCode:404});if(409===t.status)throw new w({message:"Payout already approved",statusCode:409});throw w.unknown()}async reject(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Reject",notes:e.notes}});if(201===t.status)return Xe.create(t.body);if(404===t.status)throw new w({message:"Payout not found",statusCode:404});if(409===t.status)throw new w({message:"Payout already rejected",statusCode:409});throw w.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return Xe.create(t.body);if(404===t.status)throw new w({message:"Payout not found",statusCode:404});throw w.unknown()}async count(e){const t=gt.from(e).build(),r=await this.client.getPayouts({query:t});return this.handleResponse(r,200).total}async exists(e){return await this.count(e)>0}}const bt=e=>e.optional().transform(e=>e??void 0),wt={walletDTO:t.object({id:t.string().min(1,{message:"Wallet ID is required."}),profileId:t.string().min(1,{message:"Profile ID is required."}),accountNo:t.string().min(1,{message:"Account number is required."}),accountName:t.string().min(1,{message:"Account name is required."}),channel:t.string().min(1,{message:"Channel is required."}),countryCode:t.string().default("TZ").refine(e=>a.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.string().default("TZS").refine(e=>u.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:t.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:t.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:t.object({id:t.string().optional(),profileId:t.string().optional(),accountNo:t.string().optional(),accountName:t.string().optional(),channel:t.string().optional(),countryCode:t.string().default("TZ").refine(e=>N.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:t.string().default("TZS").refine(e=>{const t=y.from(e);return void 0!==t&&g.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:t.object({accountNo:bt(t.string()),debitOrCredit:t.string().min(1,"Transaction type is required"),tranRefNo:t.string().min(1,"Transaction reference is required"),narration:t.string().min(1,"Transaction description is required"),txnDate:t.coerce.date({errorMap:()=>({message:"Invalid transaction date format"})}),valueDate:t.coerce.date({errorMap:()=>({message:"Invalid value date format"})}),amountCredited:t.number().min(0,"Credited amount must be non-negative"),amountDebited:t.number().min(0,"Debited amount must be non-negative"),balance:t.number(),currencyCode:bt(t.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})},vt=e.object({id:e.string(),profileId:e.string(),accountNo:e.string(),accountName:e.string(),channel:e.string(),countryCode:e.string(),currencyCode:e.string(),createdAt:e.string(),updatedAt:e.string(),version:e.string().optional().default("1.0")});class Ct{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return wt.walletDTO}constructor(e){this._id=e.id,this._profileId=e.profileId,this._accountNo=e.accountNo,this._accountName=e.accountName,this._channel=e.channel,this._countryCode=e.countryCode,this._currencyCode=e.currencyCode,this._createdAt=e.createdAt,this._updatedAt=e.updatedAt}static create(e){const t=Ct.schema.safeParse(e);if(t.success)return new Ct(t.data);console.error("Wallet data validation failed:",t.error.flatten())}get id(){return this._id}get profileId(){return this._profileId}get accountNo(){return this._accountNo}get accountName(){return this._accountName}get channel(){return this._channel}get countryCode(){return this._countryCode}get currencyCode(){return this._currencyCode}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get createdAtDate(){return new Date(this._createdAt)}get updatedAtDate(){return new Date(this._updatedAt)}validate(){const e=Ct.schema.safeParse(this.toJSON());return e.success||console.warn("Wallet instance validation failed:",e.error.flatten()),e.success}static from(e){if(e&&"object"==typeof e)return Ct.create({id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt,currencyCode:e.currencyCode});console.error("Invalid data provided to Wallet.from: Input must be an object.")}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t._id&&"string"==typeof t._profileId&&"string"==typeof t._accountNo&&"string"==typeof t._accountName&&"string"==typeof t._channel&&"string"==typeof t._countryCode&&a.isISO2CountryCode(t._countryCode)&&"string"==typeof t._currencyCode&&u.isCurrencyCode(t._currencyCode)&&"string"==typeof t._createdAt&&"string"==typeof t._updatedAt}toJSON(){return{id:this._id,profileId:this._profileId,accountNo:this._accountNo,accountName:this._accountName,channel:this._channel,countryCode:this._countryCode,currencyCode:this._currencyCode,createdAt:this._createdAt,updatedAt:this._updatedAt,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=vt.safeParse(t);if(!r.success)return void console.error("Invalid WalletJSON:",r.error.flatten());const n=r.data;return Ct.create(n)}catch(e){return void console.error("Error parsing WalletJSON:",e)}}static isWalletJSON(e){return vt.safeParse(e).success}}const St=e.object({accountNo:e.string().optional(),debitOrCredit:e.string(),tranRefNo:e.string(),narration:st,txnDate:e.string(),valueDate:e.string(),amountCredited:b,amountDebited:b,balance:b,currencyCode:e.string(),version:e.string().optional().default("2.0")});class Ot{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return wt.statementEntry}constructor(e,t){this._accountNo=e.accountNo,this._debitOrCredit=e.debitOrCredit,this._tranRefNo=e.tranRefNo,this._narration=t,this._txnDate=e.txnDate,this._valueDate=e.valueDate,this._currencyCode=e.currencyCode;const r=y.from(e.currencyCode);if(!r)throw new Error(`Currency not found for code: ${e.currencyCode}`);const n=d.from(e.amountCredited,r.code),o=d.from(e.amountDebited,r.code),a=d.from(e.balance,r.code);if(!n||!o||!a)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=n,this._amountDebited=o,this._balance=a}static create(e){const t="string"==typeof e.narration?new it(e.narration):e.narration,r={...e,narration:t.text},n=Ot.schema.safeParse(r);if(n.success)try{const{narration:e,...r}=n.data;return new Ot(r,t)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",n.error.flatten())}get accountNo(){return this._accountNo}get debitOrCredit(){return this._debitOrCredit}get tranRefNo(){return this._tranRefNo}get narration(){return this._narration}get txnDate(){return this._txnDate}get valueDate(){return this._valueDate}get amountCredited(){return this._amountCredited}get amountDebited(){return this._amountDebited}get balance(){return this._balance}get currencyCode(){return this._currencyCode}validate(){const e={accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.text,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode},t=Ot.schema.safeParse(e);return t.success||console.warn("WalletStatementEntry instance validation failed:",t.error.flatten()),t.success}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;try{return("string"==typeof t._accountNo||void 0===t._accountNo)&&"string"==typeof t._debitOrCredit&&"string"==typeof t._tranRefNo&&it.is(t._narration)&&t._txnDate instanceof Date&&t._valueDate instanceof Date&&d.is(t._amountCredited)&&d.is(t._amountDebited)&&d.is(t._balance)&&"string"==typeof t._currencyCode}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return Ot.create({accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode})}toString(){return`WalletStatementEntry(${this._tranRefNo}: ${this._debitOrCredit} ${this._amountCredited.isPositive()?this._amountCredited.label:this._amountDebited.label} on ${this._txnDate.toISOString().split("T")[0]}${this._narration})`}static from(e){if(e&&"object"==typeof e)try{let t,r,n,o,a=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const o=d.fromJSON(e.amountCredited),s=d.fromJSON(e.amountDebited),i=d.fromJSON(e.balance);if(!o||!s||!i)return void console.error("Failed to deserialize Amount objects from JSON");t=o.numericValue,r=s.numericValue,n=i.numericValue,e.currencyCode||(a=o.currencyCode)}else if(t=Number(e.amountCredited),r=Number(e.amountDebited),n=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)o=e.narration;else if(it.is(e.narration))o=e.narration;else{if(!it.isNarrationJSON(e.narration))return void console.error("Invalid narration data");{const t=it.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");o=t}}return Ot.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:o,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:r,balance:n,currencyCode:a})}catch(e){return void console.error("Error in WalletStatementEntry.from:",e)}else console.error("Invalid data provided to WalletStatementEntry.from: not an object or null.")}toJSON(){return{accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.toJSON(),txnDate:this._txnDate.toISOString(),valueDate:this._valueDate.toISOString(),amountCredited:this._amountCredited.toJSON(),amountDebited:this._amountDebited.toJSON(),balance:this._balance.toJSON(),currencyCode:this._currencyCode,version:"2.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=St.safeParse(t);if(!r.success)return void console.error("Invalid WalletStatementEntryJSON:",r.error.flatten());const n=r.data,o=it.fromJSON(n.narration);if(!o)return void console.warn("Failed to deserialize narration");const a=d.fromJSON(n.amountCredited),s=d.fromJSON(n.amountDebited),i=d.fromJSON(n.balance);return a&&s&&i?a.currencyCode!==n.currencyCode||s.currencyCode!==n.currencyCode||i.currencyCode!==n.currencyCode?void console.warn("Currency code mismatch"):Ot.create({accountNo:n.accountNo,debitOrCredit:n.debitOrCredit,tranRefNo:n.tranRefNo,narration:o,txnDate:n.txnDate,valueDate:n.valueDate,amountCredited:a.numericValue,amountDebited:s.numericValue,balance:i.numericValue,currencyCode:n.currencyCode}):void console.warn("Failed to deserialize Amount objects")}catch(e){return void console.error("Error parsing WalletStatementEntryJSON:",e)}}static isWalletStatementEntryJSON(e){return St.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>Ot.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing WalletStatementEntry JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}toJson(){return this.toJSON()}static fromJson(e){return Ot.fromJSON(e)}static fromJsonArray(e){return Ot.fromJSONArray(e)}static toJsonArray(e){return Ot.toJSONArray(e)}}const At=E().router({getWallets:{method:"GET",path:"/",query:wt.walletQuery,responses:{200:t.array(Ct.schema)}},getBalance:{method:"POST",path:"/balance",body:t.object({accountNo:t.string().optional()}),responses:{201:t.object({availableBalance:t.number()})}},getStatement:{method:"POST",path:"/statement",summary:"Get Wallet Statement",body:t.object({endDate:t.date(),startDate:t.date(),accountNo:t.string().optional()}),responses:{201:t.array(Ot.schema)}}});class It extends G{static create(){return new It}static fromFilters(e){return(new It).applyFilters(e)}static fromUrlParams(e){try{const t=wt.walletQuery.parse(e);return It.fromFilters(t)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return It.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return It.fromSearchParams(t)}static from(e){try{return null==e?new It:G.is(e)?new It(e.options):e instanceof URLSearchParams?It.fromSearchParams(e):this.isStringRecord(e)?It.fromUrlParams(e):It.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a WalletQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereId(e){return this.where("id",e)}whereProfileId(e){return this.where("profileId",e)}whereAccountNo(e){return this.where("accountNo",e)}whereAccountName(e){return this.whereContains("accountName",e)}whereChannel(e){return this.where("channel",e)}whereCountryCode(e){return this.where("countryCode",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){return e.id&&this.whereId(e.id),e.profileId&&this.whereProfileId(e.profileId),e.accountNo&&this.whereAccountNo(e.accountNo),e.accountName&&this.whereAccountName(e.accountName),e.channel&&this.whereChannel(e.channel),e.countryCode&&this.whereCountryCode(e.countryCode),e.currencyCode&&this.whereCurrencyCode(e.currencyCode),this}toFilters(){const e=this.extractFilterValues();return{id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,currencyCode:e.currencyCode}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withId(e){const t=this.clone();return t.whereId(e),t}withProfileId(e){const t=this.clone();return t.whereProfileId(e),t}withAccountNo(e){const t=this.clone();return t.whereAccountNo(e),t}withCountryCode(e){const t=this.clone();return t.whereCountryCode(e),t}withCurrencyCode(e){const t=this.clone();return t.whereCurrencyCode(e),t}hasFilters(){const e=this.toFilters();return!!(e.id||e.profileId||e.accountNo||e.accountName||e.channel||e.countryCode||e.currencyCode)}getActiveFilters(){const e=[],t=this.toFilters();return t.id&&e.push(`ID: ${t.id}`),t.profileId&&e.push(`Profile: ${t.profileId}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.accountName&&e.push(`Name: ${t.accountName}`),t.channel&&e.push(`Channel: ${t.channel}`),t.countryCode&&e.push(`Country: ${t.countryCode}`),t.currencyCode&&e.push(`Currency: ${t.currencyCode}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)"eq"===t.operator?e[t.field]=t.value:"likeLower"===t.operator&&"string"==typeof t.value&&(e[t.field]=t.value.replace(/%/g,""));return e}}class _t extends L{constructor(e){super("wallet",At,e)}async getBalance(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");if(e.wallet){const t=await this.client.getBalance({body:{accountNo:e.wallet.accountNo}});if(201===t.status){const r=t.body.availableBalance,n=d.from(r,e.wallet.currencyCode);if(n)return n}}if(e.accountNo){const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);const r=t[0],n=await this.client.getBalance({body:{accountNo:e.accountNo}});if(201===n.status){const e=n.body.availableBalance,t=d.from(e,r.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=It.from(e).build(),r=await this.client.getWallets({query:t});if(200===r.status){const e=r.body;try{return e.map(e=>{const t=Ct.from(e);if(!t)throw new Error(`Invalid wallet data: ${JSON.stringify(e)}`);return t})}catch(e){throw console.error("[WalletRepository] Error processing wallet data:",e),new Error("Failed to process wallet data from API")}}throw new Error(`Failed to fetch wallets. Status: ${r.status}`)}async getByID(e){const t=It.create().whereId(e),r=await this.getWallets(t);return r.length>0?r[0]:void 0}async getStatement(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");const t=new Date,r=new Date(t.getFullYear(),t.getMonth(),1),n=new Date(t.getFullYear(),t.getMonth()+1,0),o=e.range??{startDate:r,endDate:n};let a,s;if(e.wallet)a=e.wallet,s=e.wallet.accountNo;else{if(!e.accountNo)throw new Error("Either wallet or accountNo must be provided");{const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);a=t[0],s=e.accountNo}}const i={...o,accountNo:s},c=await this.client.getStatement({body:i});if(201===c.status){return c.body.map(e=>({...e,currencyCode:a.currencyCode})).reduce((e,t)=>{const r=Ot.create(t);return r?e.push(r):console.warn("[WalletRepository] Skipping invalid statement entry:",t),e},[])}throw new Error(`Failed to fetch statement. Status: ${c.status}`)}async exists(e){return(await this.getWallets(e)).length>0}async count(e){return(await this.getWallets(e)).length}}const Pt={getUniqueCountries(e){const t=new Set;return e.forEach(e=>{e.countryCode&&t.add(e.countryCode)}),Array.from(t)},getWalletsByCountry:(e,t)=>e.filter(e=>e.countryCode===t)},Et=E().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:te.schema}}});class Dt extends L{constructor(e){super("profile",Et,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=te.from(e.body);if(t)return t;throw new Error("Invalid profile data received from server")}throw new Error(`Failed to get current profile. Status: ${e.status}`)}}export{w as APIError,Ce as AuthRepository,rt as BANK_NARR_PREFIX,Je as BankContactInfo,Pe as BankContactInfoJSONSchema,L as BaseRepository,ce as CompanyMembership,ie as CompanyMembershipJSONSchema,Me as Contact,Ie as ContactDTOSchemas,Ee as ContactInfoJSONSchema,je as ContactJSONSchema,$e as ContactRepository,Se as ContactType,et as ECOBANK_PREFIX,q as FilterOperator,he as IdentityRepository,nt as LEGACY_BANK_NARR_PREFIX,at as LEGACY_MOBILE_NARR_PREFIX,oe as LogIn,ne as LogInJSONSchema,re as LogInSchemas,ot as MOBILE_NARR_PREFIX,Te as MobileContactInfo,_e as MobileContactInfoJSONSchema,tt as NARR_V2_PREFIX,it as Narration,st as NarrationJSONSchema,Y as Pagination,H as PaginationParamsSchema,Q as PaginationSchema,Xe as Payout,qe as PayoutApprovalStatus,Ue as PayoutChannel,Ze as PayoutDTOSchemas,pt as PayoutInputFactory,ze as PayoutJSONSchema,gt as PayoutQuery,Nt as PayoutRepository,Le as PayoutStatus,C as PermissionError,v as Permissions,te as Profile,X as ProfileDTOSchemas,ee as ProfileJSONSchema,Dt as ProfileRepository,W as QUERY_BUILDER_TYPE,G as QueryBuilder,se as Role,ae as RoleJSONSchema,V as SortDirection,ge as TeamManagementDTOSchemas,we as TeamMember,be as TeamMemberJSONSchema,ve as TeamMemberRepository,de as User,ue as UserJSONSchema,Ct as Wallet,wt as WalletDTOSchemas,vt as WalletJSONSchema,_t as WalletRepository,Ot as WalletStatementEntry,St as WalletStatementEntryJSONSchema,Pt as WalletUtils,Z as createPaginatedResponse,K as createPaginatedResponseSchema,ft as createPayoutChannelCode,z as emptyPaginatedResponse,S as isError,U as setGlobalTokenGetter};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|