@temboplus/afloat 0.2.0-beta.9 → 0.2.0
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/README.md +150 -238
- 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 +8 -8
- package/dist/modules/auth/auth.contract.d.ts +30 -28
- package/dist/modules/auth/auth.dtos.d.ts +117 -0
- package/dist/modules/auth/auth.repository.d.ts +9 -4
- package/dist/modules/auth/company-membership.model.d.ts +13 -13
- package/dist/modules/auth/index.d.ts +1 -0
- package/dist/modules/auth/user.model.d.ts +27 -66
- package/dist/modules/beneficiary/beneficiary-info.model.d.ts +34 -16
- package/dist/modules/beneficiary/beneficiary.model.d.ts +42 -62
- package/dist/modules/beneficiary/index.d.ts +2 -2
- package/dist/modules/login/login.model.d.ts +26 -3
- package/dist/modules/payout/payout.api-contract.d.ts +40 -0
- package/dist/modules/payout/payout.model.d.ts +4 -4
- package/dist/modules/profile/profile.model.d.ts +3 -3
- package/dist/modules/team-member/role.model.d.ts +3 -3
- package/dist/modules/team-member/team-member.model.d.ts +8 -8
- package/dist/modules/wallet/narration.model.d.ts +3 -3
- package/dist/modules/wallet/statement-entry.model.d.ts +23 -23
- package/dist/modules/wallet/wallet.model.d.ts +3 -3
- package/dist/modules/wallet/wallet.repository.d.ts +2 -2
- package/package.json +3 -4
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{MobileMoneyProviderHelpers as n,PhoneNumber as a,CountryHelpers as o,PhoneNumberFormat as s,BankHelpers as i,Bank as c,CurrencyHelpers as u,Amount as d,BankRegistry as l,PhoneNumberType as m,Country as h,Currency as p,CurrencyCodesSet as f,ISO2CountryCodesSet as y,AmountJSONSchema as g}from"@temboplus/frontend-core";class b 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 b.schema.safeParse(e).success}static unknown(e){return new b({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 N={Profile:{ViewCurrent:"profile.getCurrent",Update:"profile.update"},Beneficiary:{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 v 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(N.Profile)),t.enum(Object.values(N.Beneficiary)),t.enum(Object.values(N.Payment)),t.enum(Object.values(N.Payout)),t.enum(Object.values(N.Transfer)),t.enum(Object.values(N.Wallet))]);return t.object({name:t.literal("PermissionError").nullish(),message:t.string(),requiredPermissions:t.array(r)}).safeParse(e).success}}function w(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message}const S=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"),O=e=>"method"in e&&"path"in e,I=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,a,o,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,S(s)?S(i)?s.merge(i):s:S(i)?i:Object.assign({},s,i)),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(a=r.validateResponseOnClient)&&void 0!==a?a: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!==(o=r.metadata)&&void 0!==o?o:{}}:r.metadata}]:[e,I(r,t)]})),C=Symbol("ContractPlainType"),_=()=>({router:(e,t)=>I(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>C,body:()=>C,type:()=>C,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>A}),P=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("&"):"",E=e=>e?Object.keys(e).flatMap(t=>D(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",D=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>D(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>D(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class T extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const R=async({route:e,path:t,method:r,headers:n,body:a,validateResponse:o,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:n,body:a}),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!=o?o: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}},J=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])),j=(e,t,r,n,a)=>{const o=(({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?P(e):E(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,a);return`${t}${o}${s}`},M=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const a=((e,t,r)=>{const{query:n,params:a,body:o,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...m}=r||{},h={...t,...c};return{path:j(n,h.baseUrl,a,e,!!h.jsonQuery),clientArgs:h,route:e,body:o,query:n,extraInputArgs:m,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...i,...s}}})(e,t,n),o=await(e=>{const{path:t,clientArgs:r,route:n,body:a,query:o,extraInputArgs:s,headers:i,fetchOptions:c}=e,u=r.api||R,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:a,rawQuery:o,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:a instanceof FormData?a:J(a)}:"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 a?a:new URLSearchParams(a)}:null!=a&&(m={...m,contentType:"application/json",headers:{"content-type":"application/json",...m.headers},body:JSON.stringify(a)})),u({...m,...s})})(a);if(!t.throwOnUnknownStatus)return o;if(r.includes(o.status.toString()))return o;throw new T(o,r)}},k=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>O(r)?[e,M(r,t)]:[e,k(r,t)]));let x;const F=e=>{x=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(x){const e=x();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 b(r.data);throw new b({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===t.status)throw new b({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===t.status)throw new b({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===t.status)throw new b({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new b({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}var U,$;!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"}(U||(U={})),function(e){e.ASC="asc",e.DESC="desc"}($||($={}));const q=Symbol("query-builder-type");class V{options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*"};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}}[q]="query-builder";static is(e){return null!==e&&"object"==typeof e&&q in e&&"query-builder"===e[q]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:U.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:U.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:U.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:U.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:U.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:U.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:U.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:U.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:U.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:U.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:U.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:U.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:U.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:U.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=$.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,$.ASC)}orderByDesc(e){return this.orderBy(e,$.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 U.IS_NULL:e[`${t.field}:isNull`]=1;break;case U.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case U.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case U.LIKE:e[`${t.field}:like`]=t.value;break;case U.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case U.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case U.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===$.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 V(e)}}const W=t.object({page:t.coerce.number().int().min(1).default(1),limit:t.coerce.number().int().min(1).max(100).default(10)}),G=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 H(e){return t.object({results:t.array(e),pagination:G})}class Q{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 Q(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new Q(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 Q(t,r,n)}}function K(e=1,t=10){return{results:[],pagination:new Q(e,t,0)}}const Y={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()})},z=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 X{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return Y.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 X({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 X.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?X.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=z.safeParse(t);if(!r.success)return void console.error("Invalid ProfileJSON:",r.error.flatten());const n=r.data;return X.from(n)}catch(e){return void console.error("Error parsing ProfileJSON:",e)}}static isProfileJSON(e){return z.safeParse(e).success}}const ee={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())})},te=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 re{_id;_profileId;_name;_identity;_type;_roleId;_isActive;_isArchived;_resetPassword;_createdAt;_updatedAt;_access;constructor(e,t,r,n,a,o,s,i,c,u,d,l){this._id=e,this._profileId=t,this._name=r,this._identity=n,this._type=a,this._roleId=o,this._isActive=s,this._isArchived=i,this._resetPassword=c,this._createdAt=u,this._updatedAt=d,this._access=l}static from(e){const t=ee.loginDTO.parse(e);return new re(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=te.safeParse(t);if(!r.success)return void console.error("Invalid LogInJSON:",r.error.flatten());const n=r.data;return re.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 te.safeParse(e).success}}const ne=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 ae{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 ae(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=ne.safeParse(t);if(!r.success)return void console.error("Invalid RoleJSON:",r.error.flatten());const n=r.data;return ae.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 ne.safeParse(e).success}}const oe=e.object({companyProfile:z,role:ne.optional(),version:e.string().optional().default("1.0")});class se{_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return X.is(e.companyProfile)?new se(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=oe.safeParse(t);if(!r.success)return void console.error("Invalid CompanyMembershipJSON:",r.error.flatten());const n=r.data,a=X.fromJSON(n.companyProfile),o=n.role?ae.fromJSON(n.role):void 0;return a?se.from({companyProfile:a,role:o}):void console.error("Failed to reconstruct Profile from CompanyMembershipJSON")}catch(e){return void console.error("Error parsing CompanyMembershipJSON:",e)}}static isCompanyMembershipJSON(e){return oe.safeParse(e).success}}const ie=e.object({logIn:te,companyProfile:z,role:ne.optional(),token:e.string().min(1),version:e.string().optional().default("1.0")});class ce{_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=se.from({companyProfile:e.companyProfile,role:e.role});return t?new ce({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(N.TeamManagement.ViewMembers)}canViewRoles(){return this.can(N.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=ie.safeParse(t);if(!r.success)return void console.error("Invalid UserJSON:",r.error.flatten());const n=r.data,a=re.fromJSON(n.logIn),o=X.fromJSON(n.companyProfile),s=n.role?ae.fromJSON(n.role):void 0;if(!a||!o)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=se.from({companyProfile:o,role:s});return i?new ce({logIn:a,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 ie.safeParse(e).success}}const ue=_().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:Y.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:{}}}),de=_().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:ee.loginDTO}}});class le extends L{constructor(e){super("login",de,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 me=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"),he=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")}),pe=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:he.optional(),createdAt:t.string().datetime("Invalid creation timestamp"),updatedAt:t.string().datetime("Invalid update timestamp")}),fe={role:he,teamMember:pe,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:me.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:me.optional(),resetPassword:t.boolean().optional(),isActive:t.boolean().optional()}),resetPasswordRequest:t.object({newPassword:me.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:me},ye=_().router({getTeamMembers:{method:"GET",path:"/login",query:fe.teamMemberQueryParams,responses:{200:t.array(fe.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:fe.teamMemberQueryParams,responses:{200:fe.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:fe.createTeamMemberRequest,responses:{201:fe.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:fe.updateTeamMemberRequest,responses:{200:fe.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:fe.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:fe.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:fe.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(fe.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:fe.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"}}),ge=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:ne.optional(),createdAt:e.string(),updatedAt:e.string(),version:e.string().optional().default("1.0")});class be{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 ae(e.role)}catch(e){}}static from(e){try{return e?.id&&e?.name&&e?.identity&&e?.roleId?new be(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 be.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>be.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=ge.safeParse(t);if(!r.success)return void console.error("Invalid TeamMemberJSON:",r.error.flatten());const n=r.data,a=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 be.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:a,createdAt:n.createdAt,updatedAt:n.updatedAt})}catch(e){return void console.error("Error parsing TeamMemberJSON:",e)}}static isTeamMemberJSON(e){return ge.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>be.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 Ne extends L{constructor(e){super("admin",ye,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),a=be.from(n);if(!a)throw new Error("Invalid team member data received from server");return a}async archiveTeamMember(e){const t=await this.client.archiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),n=be.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=be.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 be.createMany(r)}async getTeamMember(e,t={eager:"role"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),n=this.handleResponse(r,200),a=be.from(n);if(!a)throw new Error("Invalid team member data received from server");return a}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=ae.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=ae.from(r);if(!n)throw new Error("Invalid role data received from server");return n}}class ve extends L{constructor(e){super("auth",ue,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 b({message:"Invalid email or password",statusCode:400});if(201===n.status){const e=n.body.token,t=new le({token:e}),r=await t.getIdentity(),a=re.from(r);if(!a)throw new b({message:"Failed to construct login credentials",statusCode:502});const o=n.body.profile,s=X.from(o);if(!s)throw new b({message:"Failed to construct user profile",statusCode:502});let i;if(a.access.includes(N.Role.ViewRole))try{const t=new Ne({token:e});i=await t.getRole(a.roleId)}catch(e){console.warn("Failed to fetch role details:",e)}const c=ce.from({logIn:a,companyProfile:s,role:i,token:e});if(!c)throw new b({message:"Failed to construct user session",statusCode:502});return c}throw new b({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 b({message:"Invalid current password",statusCode:400});throw new b({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 we;!function(e){e.Bank="Bank",e.Mobile="Mobile"}(we||(we={}));const Se=t.nativeEnum(we),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:Se}),Oe={beneficiaryDTO:t.object({id:t.string().min(1,"Beneficiary id is required"),profileId:t.string(),createdAt:t.string().datetime(),updatedAt:t.string().datetime()}).merge(Ae),beneficiaryInputDTO:Ae,beneficiaryType:Se},Ie=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")}),Ce=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")}),_e=t.discriminatedUnion("type",[Ie,Ce]);class Pe extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="BeneficiaryError"}}class Ee{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}toJSONString(){return JSON.stringify(this.toJSON())}get isMobile(){return this.type===we.Mobile}get isBank(){return this.type===we.Bank}get displayName(){return this.accountName}}class De extends Ee{name;phoneNumber;mnoId;constructor(e,t,r){super(we.Mobile,t.countryCode),this.name=e,this.phoneNumber=t;const n=De.resolveMnoId(t,r),a=De.checkInputs(e,t,n);if(!a.isValid)throw new Pe(a.errors[0],{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format,mnoId:n});this.mnoId=n}static resolveMnoId(e,t){return n.requiresExplicitProvider(e.countryCode)?t:n.detectProviderByPhoneNumber(e)?.id}static checkInputs(e,t,r){const a=[];return e?.trim()||a.push("Name is required and cannot be empty"),t?.validate()||a.push("Invalid phone number"),r?n.validateProviderForPhoneNumber(t,r)||a.push(`Invalid MNO ${r} for phone number ${t.e164Format}`):a.push(n.requiresExplicitProvider(t.countryCode)?`MNO must be explicitly provided for phone numbers in ${t.countryCode}`:`Failed to determine MNO for phone number ${t.e164Format}`),{isValid:0===a.length,errors:a,warnings:[]}}static pickMnoIdFromDTO(e,t){if(n.requiresExplicitProvider(e.countryCode)){if("string"!=typeof t)return;return n.isProviderSupported(e.countryCode,t)?t:void console.warn(`Invalid MNO ${t} for country ${e.countryCode}`)}const r=n.detectProviderByPhoneNumber(e);if(r)return r.id;console.warn(`Failed to auto-detect MNO for phone number ${e.e164Format}`)}static from(e){try{return new De(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileBeneficiaryInfo:",e)}}static fromBeneficiaryDTO(e){if(e.type!==we.Mobile)return;const t=e.accountNo.startsWith("+")?e.accountNo:`+${e.accountNo}`,r=a.from(t);if(!r)return void console.error(`Failed to parse phone number ${t}`);const n=De.pickMnoIdFromDTO(r,e.channel);return n?De.from({name:e.displayName,phoneNumber:r,mnoId:n}):void 0}static fromPayoutDTO(e){if(!o.isISO2Code(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=a.from(e.msisdn,{defaultCountry:e.countryCode});if(!t)return void console.error(`Failed to parse phone number: ${e.msisdn}`);const r=De.pickMnoIdFromDTO(t,e.channel);return r?De.from({name:e.payeeName,phoneNumber:t,mnoId:r}):void 0}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===we.Mobile&&(!("string"!=typeof t.name||!t.name.trim())&&(!!a.is(t.phoneNumber)&&("string"==typeof t.mnoId&&n.isProviderSupported(t.phoneNumber.countryCode,t.mnoId))))}validate(){return De.checkInputs(this.name,this.phoneNumber,this.mnoId).isValid}getValidationDetails(){return De.checkInputs(this.name,this.phoneNumber,this.mnoId)}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.findById(this.mnoId,this.countryCode);return e?.mobileMoneyServiceName??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=Ie.safeParse(t);if(!r.success)return void console.error("Invalid MobileBeneficiaryJSON:",r.error.flatten());const n=a.from(r.data.phoneNumber);if(!n)return;return De.from({name:r.data.name,phoneNumber:n,mnoId:r.data.mnoId})}catch(e){return void console.error("Error parsing MobileBeneficiaryJSON:",e)}}static fromJSONString(e){return De.fromJSON(e)}static isJSON(e){return Ie.safeParse(e).success}}class Te extends Ee{accName;bank;accNo;constructor(e,t,r){super(we.Bank,t.countryCode),this.accName=e,this.bank=t,this.accNo=r;const n=Te.checkInputs(e,t,r);if(!n.isValid)throw new Pe(n.errors[0],{operation:"constructor",countryCode:t.countryCode})}static checkInputs(e,t,r){const n=[];return i.validateAccountName(e)||n.push("Invalid account name"),c.is(t)?i.validateAccountNumber(r,t.countryCode)||n.push("Invalid account number"):n.push("Invalid bank reference"),{isValid:0===n.length,errors:n,warnings:[]}}static from(e){try{return new Te(e.accName,e.bank,e.accNo)}catch(e){return void console.error("Failed to create BankBeneficiaryInfo:",e)}}static fromBeneficiaryDTO(e){if(e.type!==we.Bank)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank beneficiaries");const r=i.getCountryFromSwiftCode(t);if(!r)return void console.error(`Could not identify country from SWIFT code: ${t}`);const n=c.fromBIC(t,r);if(n)return Te.from({accName:e.displayName,bank:n,accNo:e.accountNo});console.error(`Bank with SWIFT code ${t} not found`)}static fromPayoutDTO(e){if(!o.isISO2Code(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,a=c.fromBIC(r,e.countryCode);if(a)return Te.from({accName:e.payeeName,bank:a,accNo:n});console.error(`Bank with SWIFT code ${r} not found`)}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===we.Bank&&("string"==typeof t.accName&&("string"==typeof t.accNo&&(!!c.is(t.bank)&&(i.validateAccountName(t.accName)&&i.validateAccountNumber(t.accNo,t.bank.countryCode)))))}validate(){return Te.checkInputs(this.accName,this.bank,this.accNo).isValid}getValidationDetails(){return Te.checkInputs(this.accName,this.bank,this.accNo)}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.bic}get channelName(){return this.bank.shortName}toJSON(){return{type:"Bank",accName:this.accName,swiftCode:this.bank.bic,countryCode:this.bank.countryCode,accNo:this.accNo,version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Ce.safeParse(t);if(!r.success)return void console.error("Invalid BankBeneficiaryJSON:",r.error.flatten());const n=r.data;if(!o.isISO2Code(n.countryCode))return;const a=c.fromBIC(n.swiftCode,n.countryCode);if(!a)return;return Te.from({accName:n.accName,bank:a,accNo:n.accNo})}catch(e){return void console.error("Error parsing BankBeneficiaryJSON:",e)}}static fromJSONString(e){return Te.fromJSON(e)}static isJSON(e){return Ce.safeParse(e).success}}const Re={fromBeneficiaryDTO:e=>e.type===we.Mobile?De.fromBeneficiaryDTO(e):Te.fromBeneficiaryDTO(e),fromPayoutDTO:e=>e.msisdn.includes(":")?Te.fromPayoutDTO(e):De.fromPayoutDTO(e),fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=_e.safeParse(t);if(!r.success)return;return"Mobile"===r.data.type?De.fromJSON(r.data):Te.fromJSON(r.data)}catch{return}},fromJSONString:e=>Re.fromJSON(e),is:e=>De.is(e)||Te.is(e),isJSON:e=>_e.safeParse(e).success},Je=t.object({data:Oe.beneficiaryDTO,version:t.string().optional().default("1.0")});class Be{data;_info;_infoComputed=!1;constructor(e){this.data=Oe.beneficiaryDTO.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._infoComputed||(this._infoComputed=!0,this.data.type===we.Mobile?this._info=De.fromBeneficiaryDTO(this.data):this.data.type===we.Bank&&(this._info=Te.fromBeneficiaryDTO(this.data))),this._info}get accNo(){const e=this.info;return e?e.accountNumber:this.data.accountNo}get accName(){return this.data.displayName}get accNoLabel(){return this.type===we.Mobile?"Phone Number":this.type===we.Bank?"Bank Account Number":"Account Number"}get channelLabel(){return this.type===we.Mobile?"Channel":this.type===we.Bank?"Bank":"Channel"}get accNameLabel(){return this.type===we.Mobile?"Full Name":this.type===we.Bank?"Bank Account Name":"Display Name"}get channelName(){return this.info?.channelName??""}static from(e){try{return new Be(e)}catch(e){return void console.error("Failed to create Beneficiary:",e)}}static create(e){return new Be(e)}static createMany(e){return e.map(e=>new Be(e))}static createSafe(e){return Be.from(e)??null}static canConstruct(e){return Oe.beneficiaryDTO.safeParse(e).success}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&Be.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 BeneficiaryJSON:",r.error.flatten());const n=r.data;return Be.from(n.data)}catch(e){return void console.error("Error parsing BeneficiaryJSON:",e)}}static fromJSONString(e){return Be.fromJSON(e)}static isBeneficiaryJSON(e){return Je.safeParse(e).success}}class je{canHandle(e){return"Mobile"===e.type&&De.is(e)}createInput(e){if(De.is(e))return{type:we.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile BeneficiaryInfo Info")}}class Me{canHandle(e){return"Bank"===e.type&&Te.is(e)}createInput(e){if(Te.is(e))return{type:we.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Bank BeneficiaryInfo Info")}}class ke{handlers=[new je,new Me];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 xe=_().router({createBeneficiary:{method:"POST",path:"/",body:Oe.beneficiaryInputDTO,responses:{201:Oe.beneficiaryDTO}},editBeneficiary:{method:"PATCH",path:"/:id",body:Oe.beneficiaryInputDTO,responses:{200:Oe.beneficiaryDTO}},getBeneficiaries:{method:"GET",path:"/",query:t.object({orderByDesc:t.string()}),responses:{200:t.array(Oe.beneficiaryDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:Oe.beneficiaryDTO}},deleteBeneficiary:{method:"DELETE",path:"/:id",body:t.object({}),responses:{200:t.object({})}}});class Fe extends L{constructor(e){super("contact",xe,e)}async create(e){const t=(new ke).resolve(e),r=await this.client.createBeneficiary({body:t}),n=this.handleResponse(r,201);return Be.create(n)}async edit(e,t){const r=(new ke).resolve(t),n=await this.client.editBeneficiary({params:{id:e},body:r}),a=this.handleResponse(n,200);return Be.create(a)}async remove(e){const t=await this.client.deleteBeneficiary({params:{id:e}});this.handleResponse(t,200)}async getAll(){const e=await this.client.getBeneficiaries({query:{orderByDesc:"createdAt"}}),t=this.handleResponse(e,200);return Be.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return Be.create(r)}}var Le,Ue,$e;!function(e){e.MOBILE="Mobile",e.BANK="Bank"}(Le||(Le={})),function(e){e.CREATED="CREATED",e.PENDING="PENDING",e.PAID="PAID",e.FAILED="FAILED",e.REJECTED="REJECTED",e.REVERSED="REVERSED",e.QUEUED="QUEUED"}(Ue||(Ue={})),function(e){e.PENDING="Pending",e.APPROVED="Approved",e.REJECTED="Rejected"}($e||($e={}));const qe=t.object({id:t.string(),name:t.string(),identity:t.string()}),Ve=t.nativeEnum(Ue),We=t.nativeEnum($e),Ge=t.object({channel:t.string(),msisdn:t.string(),amount:t.coerce.number(),description:t.string(),notes:t.string().nullish()}),He=Ge.extend({payeeName:t.string()}),Qe=Ge.extend({id:t.string(),profileId:t.string(),payeeName:t.string(),countryCode:t.string().default("TZ").refine(e=>o.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.string().default("TZS").refine(e=>u.isCode(e),{message:"Provided currency code is not a valid currency code."}),channel:t.string(),status:Ve,statusMessage:t.string(),partnerReference:t.string().nullish(),createdAt:t.coerce.date(),updatedAt:t.coerce.date(),actionedAt:t.coerce.date().nullish(),approvalStatus:We.nullish(),createdBy:qe.nullish(),actionedBy:qe.nullish()}),Ze=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:Ve.nullish(),approvalStatus:We.nullish(),minAmount:t.number().min(0).nullish(),maxAmount:t.number().min(0).nullish(),search:t.string().nullish()}),Ke={PayoutDTO:Qe,PayoutInputDTO:He,PayoutStatus:Ve,PayoutApprovalStatus:We,PayoutAuthorizer:qe,PayoutFilters:Ze,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(Ue).includes(e)).transform(e=>e).optional(),approvalStatus:t.string().refine(e=>Object.values($e).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()})},Ye=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:Ke.PayoutStatus,statusMessage:e.string(),partnerReference:e.string().nullish(),createdAt:e.string(),updatedAt:e.string(),actionedAt:e.string().nullish(),approvalStatus:Ke.PayoutApprovalStatus.nullish(),createdBy:Ke.PayoutAuthorizer.nullish(),actionedBy:Ke.PayoutAuthorizer.nullish(),version:e.string().optional().default("1.0")});class ze{data;constructor(e){this.data=Ke.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?Ue.REJECTED:"Approved"===this.data.approvalStatus?"FAILED"===this.data.status?Ue.FAILED:Ue.PAID:"Pending"===this.data.approvalStatus?Ue.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 beneficiaryInfo(){return"TZ-BANK-B2C"===this.channel?Te.fromPayoutDTO(this.data):De.fromPayoutDTO(this.data)}get contactInfo(){return this.beneficiaryInfo}static create(e){return new ze(e)}static createMany(e){return e.map(e=>new ze(e))}static createSafe(e){try{return new ze(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=Ke.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==ze.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&ze.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=Ye.safeParse(t);if(!r.success)return void console.error("Invalid PayoutJSON:",r.error.flatten());const n=r.data,a=n.currencyCode;if(!u.isCode(a))return void console.error("Invalid currency code:",a);const s=n.countryCode;if(!o.isISO2Code(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:a,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 ze.create(i)}catch(e){return void console.error("Error parsing PayoutJSON:",e)}}static isPayoutJSON(e){return Ye.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>ze.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 Xe="MOBILE TRANSFER ",et="PAYOUT",tt="PAYOUT TO BANK",rt="TO_BANK",nt="PAYOUT TO MOBILE",at="TO_MOMO",ot=e.object({text:e.string(),version:e.string().optional().default("2.0")});class st{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 De.is(e)?st.generateMobilePayoutNarrationV2(e):Te.is(e)?st.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${et.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:n}=e;return`${et.toUpperCase()} ${t.bic.trim()} ${n.trim()} ${r.trim()}`.toUpperCase()}getBeneficiaryDetails=()=>{const e=this.getBankBeneficiaryDetails(),t=this.getMobileBeneficiaryDetails();return e||(t||void 0)};getBankBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(Xe)&&(e=e.substring(16));try{if(e.startsWith(et)){const t=e.replace(et,"").trim().split(" ");if(t.length>=3){const e=t[0],r=t[1],n=t.slice(2).map(it).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 a=c.fromBIC(e,t);if(r&&n&&a)return new Te(n,a,r)}}}}}if(e.startsWith(rt)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=r.account_number,a=r.account_name,o=r.swift_code,s=i.getCountryFromSwiftCode(o);if(!s)return;if(!i.validateSwiftCode(o,s))return;const u=c.fromBIC(o,s);if(n&&a&&u)return new Te(a,u,n)}if(e.startsWith(tt)){const t=e.replace(tt,"").trim().split(" "),r=l.getInstance().searchBanks("TZ",t[0]),n=r.length>0?r[0]:void 0,a=t[1],o=t.slice(2).map(it).join(" ");if(o&&a&&n)return new Te(o,n,a)}}catch(e){return}};getMobileBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(Xe)&&(e=e.substring(16));try{if(e.startsWith(et)){const t=e.replace(et,"").trim().split(" ");if(t.length>=2){const e=t[0],r=t.slice(1).map(it).join(" ");if(e.startsWith("+")){const t=a.from(e);if(t&&r)return new De(r,t)}}}if(e.startsWith(at)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=a.from(r.phone_number,{defaultCountry:"TZ"});let o=r.username;void 0===o&&(o="");let s=o.split(" ");if(s=s.filter(e=>e.trim().length>0),o=s.map(it).join(" "),n&&o)return new De(o,n)}if(e.startsWith(nt)){const t=e.replace(nt,"").trim().split(" "),r=a.from(t[0],{defaultCountry:"TZ"}),n=t.slice(1).map(it).join(" ");if(r&&n)return new De(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.getBeneficiaryDetails&&"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=ot.safeParse(t);if(!r.success)return void console.error("Invalid NarrationJSON:",r.error.flatten());const n=r.data;return new st(n.text)}catch(e){return void console.error("Error parsing NarrationJSON:",e)}}static isNarrationJSON(e){return ot.safeParse(e).success}toJson(){return this.toJSON()}static fromJson(e){return st.fromJSON(e)}}function it(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}const ct={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 TZ and KE banks are supported for now",UNSUPPORTED_COUNTRY_MOBILE:"Only TZ and KE mobile numbers are supported for now",NO_HANDLER_FOUND:"Cannot create payout input!"}};class ut{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}static isPhoneEligibleForPayout(e){const t=e.getNumberType();return t===m.MOBILE||t===m.FIXED_LINE_OR_MOBILE}}class dt{static forBank(e,t){if(!ct.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(ct.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,t,r){if(!a.is(e))throw new Error(ct.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!ct.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(ct.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!ut.isPhoneEligibleForPayout(e))throw new Error(ct.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const o=n.findById(t,e.countryCode);if(!o)throw new Error(ct.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return"VODACOM"===o.id?`${r.countryCode}-TIGO-B2C`:`${r.countryCode}-${o.id}-B2C`}}class lt{canHandle(e,t,r){return e===Le.MOBILE&&De.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===h.fromCode(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=ut.processNotes(e.notes),a=r.phoneNumber;return{channel:dt.forMobile(a,r.mnoId,t),msisdn:a.getWithFormat(s.INTERNATIONAL_NUMERIC),description:n??st.generateDefaultPayoutNarration(r),payeeName:r.name,notes:n,amount:e.amount.numericValue}}}class mt{canHandle(e,t,r){return e===Le.BANK&&Te.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===h.fromCode(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=ut.processNotes(e.notes);return{channel:dt.forBank(r,t),msisdn:`${r.bank.bic}:${r.accNo}`,description:n??st.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:n,amount:e.amount.numericValue}}}class ht{handlers=[new lt,new mt];getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(ct.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const pt={bank:dt.forBank.bind(dt),mobile:dt.forMobile.bind(dt)},ft=_().router({getPayouts:{method:"GET",path:"",query:t.object({}),responses:{200:t.object({results:t.array(Ke.PayoutDTO),total:t.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:t.object({rangeStart:t.number(),rangeEnd:t.number(),eager:t.string(),approvalStatus:Ke.PayoutApprovalStatus,orderByDesc:t.string()}),responses:{200:t.object({results:t.array(Ke.PayoutDTO),total:t.number()})}},postPayout:{method:"POST",path:"",body:Ke.PayoutInputDTO,responses:{201:Ke.PayoutDTO,400:b.schema}},approve:{method:"POST",path:"/:id/approve",body:t.object({action:t.enum(["Approve","Reject"]),notes:t.string().optional()}),responses:{201:Ke.PayoutDTO,404:t.object({}),409:t.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:Ke.PayoutDTO,404:t.object({})}}});class yt extends V{static create(){return new yt}static fromFilters(e){return(new yt).applyFilters(e)}static fromUrlParams(e){try{const t=Ke.PayoutURLQueryParams.parse(e),r=Ke.PayoutFilters.parse(t);return yt.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 yt.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return yt.fromSearchParams(t)}static from(e){try{return null==e?new yt:V.is(e)?new yt(e.options):e instanceof URLSearchParams?yt.fromSearchParams(e):this.isStringRecord(e)?yt.fromUrlParams(e):yt.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($e.PENDING)}whereApproved(){return this.whereApprovalStatus($e.APPROVED)}whereRejected(){return this.whereApprovalStatus($e.REJECTED)}wherePaid(){return this.whereStatus(Ue.PAID)}whereFailed(){return this.whereStatus(Ue.FAILED)}whereAmountBetween(e,t){return e.currencyCode!==t.currencyCode||e.numericValue>t.numericValue?this:this.whereBetween("amount",e.numericValue,t.numericValue)}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,a=n||"TZS";if(!u.isCode(a))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,a),r=d.from(e.maxAmount,a);t&&r&&this.whereAmountBetween(t,r)}else t?this.whereGreaterThanOrEqual("amount",e.minAmount):r&&this.whereLessThanOrEqual("amount",e.maxAmount)}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)}describeFilters(e){const t=[],r=this.toFilters(),n=e?.formatDate??(e=>e);if(r.sortBy){const e="asc"===r.sortOrder?"Ascending":"Descending";t.push({label:"Sort",value:`${this.formatSortField(r.sortBy)} (${e})`})}if(r.startDate&&r.endDate?t.push({label:"Date Range",value:`${n(r.startDate)} — ${n(r.endDate)}`}):r.startDate?t.push({label:"From",value:n(r.startDate)}):r.endDate&&t.push({label:"Until",value:n(r.endDate)}),r.status&&t.push({label:"Status",value:r.status}),r.approvalStatus&&t.push({label:"Approval Status",value:r.approvalStatus}),r.channel&&t.push({label:"Channel",value:r.channel}),void 0!==r.minAmount&&void 0!==r.maxAmount){const e=Number(r.minAmount),n=Number(r.maxAmount);if(Number.isFinite(e)&&Number.isFinite(n)){const r=d.from(e,"TZS"),a=d.from(n,"TZS");r&&a&&t.push({label:"Amount Range",value:`${r.label} — ${a.label}`})}}else if(void 0!==r.minAmount){const e=Number(r.minAmount);if(Number.isFinite(e)){const r=d.from(e,"TZS");r&&t.push({label:"Minimum Amount",value:r.label})}}else if(void 0!==r.maxAmount){const e=Number(r.maxAmount);if(Number.isFinite(e)){const r=d.from(e,"TZS");r&&t.push({label:"Maximum Amount",value:r.label})}}return r.search&&t.push({label:"Search",value:`"${r.search}"`}),r.payeeName&&t.push({label:"Beneficiary Name",value:r.payeeName}),r.msisdn&&t.push({label:"MSISDN",value:r.msisdn}),r.profileId&&t.push({label:"Profile",value:r.profileId}),r.partnerReference&&t.push({label:"Reference",value:r.partnerReference}),t}describeFiltersAsText(){return this.describeFilters().map(e=>`${e.label}: ${e.value}`)}formatSortField(e){return{createdAt:"Date Created",updatedAt:"Date Updated",amount:"Amount",payeeName:"Beneficiary Name",status:"Status"}[e]??e}build(){return super.build()}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(Ue).includes(e)}isValidApprovalStatus(e){return Object.values($e).includes(e)}}class gt extends L{constructor(e){super("payout",ft,e)}async getPayouts(e){try{const t=yt.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),a=this.handleResponse(n,200),o=t.toFilters(),s=new Q(o.page??1,o.limit??10,a.total);return{results:ze.createMany(a.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=yt.from(e).build();delete t.rangeStart,delete t.rangeEnd;const r=await this.client.getPayouts({query:t}),n=this.handleResponse(r,200);return ze.createMany(n)}catch(e){throw console.log("error: ",e),new Error(`Failed to fetch all payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=yt.fromRequest(e);return this.getPayouts(t)}async pay(e){const{wallet:t,channel:r,receiver:n,amount:a,notes:o}=e,{min:s,max:i}=d.getTransactionLimits(a.currencyCode);if(a.lessThan(s)||a.greaterThan(i))throw new b({statusCode:400,message:`Please make sure the amount is between ${s.label} - ${i.label}`});const c=(new ht).getPayoutInput({channel:r,receiver:n,amount:a,notes:o},t),u=await this.client.postPayout({body:c});if(201===u.status)return ze.create(u.body);if(400===u.status)throw new b(u.body);throw b.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 ze.create(t.body);if(404===t.status)throw new b({message:"Payout not found",statusCode:404});if(409===t.status)throw new b({message:"Payout already approved",statusCode:409});throw b.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 ze.create(t.body);if(404===t.status)throw new b({message:"Payout not found",statusCode:404});if(409===t.status)throw new b({message:"Payout already rejected",statusCode:409});throw b.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return ze.create(t.body);if(404===t.status)throw new b({message:"Payout not found",statusCode:404});throw b.unknown()}async count(e){const t=yt.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),Nt={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=>o.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.string().default("TZS").refine(e=>u.isCode(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=>y.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:t.string().default("TZS").refine(e=>{const t=p.from(e);return void 0!==t&&f.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 wt{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return Nt.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=wt.schema.safeParse(e);if(t.success)return new wt(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=wt.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 wt.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&&o.isISO2Code(t._countryCode)&&"string"==typeof t._currencyCode&&u.isCode(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 wt.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:ot,txnDate:e.string(),valueDate:e.string(),amountCredited:g,amountDebited:g,balance:g,currencyCode:e.string(),version:e.string().optional().default("2.0")});class At{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return Nt.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=p.from(e.currencyCode);if(!r)throw new Error(`Currency not found for code: ${e.currencyCode}`);const n=d.from(e.amountCredited,r.code),a=d.from(e.amountDebited,r.code),o=d.from(e.balance,r.code);if(!n||!a||!o)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=n,this._amountDebited=a,this._balance=o}static create(e){const t="string"==typeof e.narration?new st(e.narration):e.narration,r={...e,narration:t.text},n=At.schema.safeParse(r);if(n.success)try{const{narration:e,...r}=n.data;return new At(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=At.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&&st.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 At.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,a,o=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const a=d.fromJSON(e.amountCredited),s=d.fromJSON(e.amountDebited),i=d.fromJSON(e.balance);if(!a||!s||!i)return void console.error("Failed to deserialize Amount objects from JSON");t=a.numericValue,r=s.numericValue,n=i.numericValue,e.currencyCode||(o=a.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)a=e.narration;else if(st.is(e.narration))a=e.narration;else{if(!st.isNarrationJSON(e.narration))return void console.error("Invalid narration data");{const t=st.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");a=t}}return At.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:a,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:r,balance:n,currencyCode:o})}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,a=st.fromJSON(n.narration);if(!a)return void console.warn("Failed to deserialize narration");const o=d.fromJSON(n.amountCredited),s=d.fromJSON(n.amountDebited),i=d.fromJSON(n.balance);return o&&s&&i?o.currencyCode!==n.currencyCode||s.currencyCode!==n.currencyCode||i.currencyCode!==n.currencyCode?void console.warn("Currency code mismatch"):At.create({accountNo:n.accountNo,debitOrCredit:n.debitOrCredit,tranRefNo:n.tranRefNo,narration:a,txnDate:n.txnDate,valueDate:n.valueDate,amountCredited:o.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=>At.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 At.fromJSON(e)}static fromJsonArray(e){return At.fromJSONArray(e)}static toJsonArray(e){return At.toJSONArray(e)}}const Ot=_().router({getWallets:{method:"GET",path:"/",query:Nt.walletQuery,responses:{200:t.array(wt.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(At.schema)}}});class It extends V{static create(){return new It}static fromFilters(e){return(new It).applyFilters(e)}static fromUrlParams(e){try{const t=Nt.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:V.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}build(){return super.build()}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 Ct extends L{constructor(e){super("wallet",Ot,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=wt.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),a=e.range??{startDate:r,endDate:n};let o,s;if(e.wallet)o=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}`);o=t[0],s=e.accountNo}}const i={...a,accountNo:s},c=await this.client.getStatement({body:i});if(201===c.status){return c.body.map(e=>({...e,currencyCode:o.currencyCode})).reduce((e,t)=>{const r=At.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 _t={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)},Pt=_().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:X.schema}}});class Et extends L{constructor(e){super("profile",Pt,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=X.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{b as APIError,ve as AuthRepository,tt as BANK_NARR_PREFIX,Te as BankBeneficiaryInfo,Ce as BankBeneficiaryJSONSchema,L as BaseRepository,Be as Beneficiary,Oe as BeneficiaryDTOSchemas,Pe as BeneficiaryError,Re as BeneficiaryInfo,Fe as BeneficiaryRepository,we as BeneficiaryType,se as CompanyMembership,oe as CompanyMembershipJSONSchema,Xe as ECOBANK_PREFIX,U as FilterOperator,le as IdentityRepository,rt as LEGACY_BANK_NARR_PREFIX,at as LEGACY_MOBILE_NARR_PREFIX,re as LogIn,te as LogInJSONSchema,ee as LogInSchemas,nt as MOBILE_NARR_PREFIX,De as MobileBeneficiaryInfo,Ie as MobileBeneficiaryJSONSchema,et as NARR_V2_PREFIX,st as Narration,ot as NarrationJSONSchema,Q as Pagination,W as PaginationParamsSchema,G as PaginationSchema,ze as Payout,$e as PayoutApprovalStatus,Le as PayoutChannel,Ke as PayoutDTOSchemas,ht as PayoutInputFactory,Ye as PayoutJSONSchema,yt as PayoutQuery,gt as PayoutRepository,Ue as PayoutStatus,v as PermissionError,N as Permissions,X as Profile,Y as ProfileDTOSchemas,z as ProfileJSONSchema,Et as ProfileRepository,q as QUERY_BUILDER_TYPE,V as QueryBuilder,ae as Role,ne as RoleJSONSchema,$ as SortDirection,fe as TeamManagementDTOSchemas,be as TeamMember,ge as TeamMemberJSONSchema,Ne as TeamMemberRepository,ce as User,ie as UserJSONSchema,ke as ValidatedBeneficiaryInputFactory,wt as Wallet,Nt as WalletDTOSchemas,vt as WalletJSONSchema,Ct as WalletRepository,At as WalletStatementEntry,St as WalletStatementEntryJSONSchema,_t as WalletUtils,xe as contract,Z as createPaginatedResponse,H as createPaginatedResponseSchema,pt as createPayoutChannelCode,K as emptyPaginatedResponse,w as isError,F as setGlobalTokenGetter};
|
|
1
|
+
import e,{z as t}from"zod";import{v4 as r}from"uuid";import{MobileMoneyProviderHelpers as n,PhoneNumber as a,CountryHelpers as o,PhoneNumberFormat as s,BankHelpers as i,Bank as c,CurrencyHelpers as u,Amount as d,BankRegistry as l,PhoneNumberType as m,Country as h,TemboCoverage as p,ChannelType as f,TransactionDirection as y,Currency as g,CurrencyCodesSet as b,ISO2CountryCodesSet as N,AmountJSONSchema as w}from"@temboplus/frontend-core";class v 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 v.schema.safeParse(e).success}static unknown(e){return new v({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 S={Profile:{ViewCurrent:"profile.getCurrent",Update:"profile.update"},Beneficiary:{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 O 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(S.Profile)),t.enum(Object.values(S.Beneficiary)),t.enum(Object.values(S.Payment)),t.enum(Object.values(S.Payout)),t.enum(Object.values(S.Transfer)),t.enum(Object.values(S.Wallet))]);return t.object({name:t.literal("PermissionError").nullish(),message:t.string(),requiredPermissions:t.array(r)}).safeParse(e).success}}function A(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 C=Symbol("ContractNoBody"),_=e=>"method"in e&&"path"in e,P=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,a,o,s,i;return _(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!==(a=r.validateResponseOnClient)&&void 0!==a?a: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!==(o=r.metadata)&&void 0!==o?o:{}}:r.metadata}]:[e,P(r,t)]})),E=Symbol("ContractPlainType"),D=()=>({router:(e,t)=>P(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>E,body:()=>E,type:()=>E,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>C}),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 B 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:a,validateResponse:o,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:n,body:a}),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!=o?o: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},x=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),F=(e,t,r,n,a)=>{const o=(({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,a);return`${t}${o}${s}`},k=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const a=((e,t,r)=>{const{query:n,params:a,body:o,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...m}=r||{},h={...t,...c};return{path:F(n,h.baseUrl,a,e,!!h.jsonQuery),clientArgs:h,route:e,body:o,query:n,extraInputArgs:m,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...i,...s}}})(e,t,n),o=await(e=>{const{path:t,clientArgs:r,route:n,body:a,query:o,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&&x(d),...x(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:a,rawQuery:o,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:a instanceof FormData?a:M(a)}:"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 a?a:new URLSearchParams(a)}:null!=a&&(m={...m,contentType:"application/json",headers:{"content-type":"application/json",...m.headers},body:JSON.stringify(a)})),u({...m,...s})})(a);if(!t.throwOnUnknownStatus)return o;if(r.includes(o.status.toString()))return o;throw new B(o,r)}},L=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>_(r)?[e,k(r,t)]:[e,L(r,t)]));let U;const $=e=>{U=e};class q{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(U){const e=U();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 L(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 v(r.data);throw new v({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===t.status)throw new v({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===t.status)throw new v({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===t.status)throw new v({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new v({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}var W,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"}(W||(W={})),function(e){e.ASC="asc",e.DESC="desc"}(V||(V={}));const G=Symbol("query-builder-type");class H{options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*"};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}}[G]="query-builder";static is(e){return null!==e&&"object"==typeof e&&G in e&&"query-builder"===e[G]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:W.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:W.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:W.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:W.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:W.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:W.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:W.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:W.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:W.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:W.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:W.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:W.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:W.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:W.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 W.IS_NULL:e[`${t.field}:isNull`]=1;break;case W.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case W.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case W.LIKE:e[`${t.field}:like`]=t.value;break;case W.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case W.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case W.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 H(e)}}const Q=t.object({page:t.coerce.number().int().min(1).default(1),limit:t.coerce.number().int().min(1).max(100).default(10)}),Z=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:Z})}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 X(e=1,t=10){return{results:[],pagination:new Y(e,t,0)}}const ee={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()})},te=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 re{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return ee.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 re({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 re.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?re.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=te.safeParse(t);if(!r.success)return void console.error("Invalid ProfileJSON:",r.error.flatten());const n=r.data;return re.from(n)}catch(e){return void console.error("Error parsing ProfileJSON:",e)}}static isProfileJSON(e){return te.safeParse(e).success}}const ne={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())})},ae=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;_permissionMap;constructor(e,t,r,n,a,o,s,i,c,u,d,l){this._id=e,this._profileId=t,this._name=r,this._identity=n,this._type=a,this._roleId=o,this._isActive=s,this._isArchived=i,this._resetPassword=c,this._createdAt=u,this._updatedAt=d,this._access=l,this._permissionMap={},this._access.forEach(e=>{this._permissionMap[e]=!0})}static from(e){const t=ne.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}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))}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=ae.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 ae.safeParse(e).success}}const se=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 ie{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 ie(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=se.safeParse(t);if(!r.success)return void console.error("Invalid RoleJSON:",r.error.flatten());const n=r.data;return ie.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 se.safeParse(e).success}}const ce=e.object({companyProfile:te,role:se.optional(),_version:e.string().optional().default("1.0")});class ue{_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return re.is(e.companyProfile)?new ue(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=ce.safeParse(t);if(!r.success)return void console.error("Invalid CompanyMembershipJSON:",r.error.flatten());const n=r.data,a=re.fromJSON(n.companyProfile),o=n.role?ie.fromJSON(n.role):void 0;return a?ue.from({companyProfile:a,role:o}):void console.error("Failed to reconstruct Profile from CompanyMembershipJSON")}catch(e){return void console.error("Error parsing CompanyMembershipJSON:",e)}}static isCompanyMembershipJSON(e){return ce.safeParse(e).success}}const de=e.object({logIn:ae,companyProfile:te,role:se.optional(),_version:e.string().optional().default("1.0")});class le{_logIn;_membership;constructor(e){this._logIn=e.logIn,this._membership=e.membership}static from(e){try{if(!e.logIn||!e.companyProfile)return void console.error("Missing required User fields");const t=ue.from({companyProfile:e.companyProfile,role:e.role});return t?new le({logIn:e.logIn,membership:t}):void console.error("Failed to create CompanyMembership")}catch(e){return void console.error("Error creating User:",e)}}get logIn(){return this._logIn}get login(){return this._logIn}get membership(){return this._membership}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}toJSON(){return{logIn:this._logIn.toJSON(),companyProfile:this._membership.companyProfile.toJSON(),role:this._membership.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=de.safeParse(t);if(!r.success)return void console.error("Invalid UserJSON:",r.error.flatten());const n=r.data,a=oe.fromJSON(n.logIn),o=re.fromJSON(n.companyProfile),s=n.role?ie.fromJSON(n.role):void 0;if(!a||!o)return void console.error("Failed to reconstruct nested objects from UserJSON");const i=ue.from({companyProfile:o,role:s});return i?new le({logIn:a,membership:i}):void console.error("Failed to create CompanyMembership from UserJSON")}catch(e){return void console.error("Error parsing UserJSON:",e)}}static isUserJSON(e){return de.safeParse(e).success}}const me={logInRequestDTO:t.object({type:t.string().default("password"),identity:t.string().email(),password:t.string()}),logInResponseDTO:t.object({profile:ee.profileDTOSchema,token:t.string(),access:t.array(t.string()),resetPassword:t.boolean()}),accessResponseDTO:t.array(t.string()),resetPasswordRequestDTO:t.object({currentPassword:t.string(),newPassword:t.string()}),emptyResponseDTO:t.object({})},he=D().router({logIn:{method:"POST",path:"/login",body:me.logInRequestDTO,responses:{201:me.logInResponseDTO,400:me.emptyResponseDTO}},access:{method:"GET",path:"/access",responses:{200:me.accessResponseDTO}},resetPassword:{method:"PUT",path:"/password",body:me.resetPasswordRequestDTO,responses:{200:me.emptyResponseDTO,400:me.emptyResponseDTO}}}),pe=D().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:ne.loginDTO}}});class fe extends q{constructor(e){super("login",pe,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 ye=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"),ge=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")}),be=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:ge.optional(),createdAt:t.string().datetime("Invalid creation timestamp"),updatedAt:t.string().datetime("Invalid update timestamp")}),Ne={role:ge,teamMember:be,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:ye.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:ye.optional(),resetPassword:t.boolean().optional(),isActive:t.boolean().optional()}),resetPasswordRequest:t.object({newPassword:ye.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:ye},we=D().router({getTeamMembers:{method:"GET",path:"/login",query:Ne.teamMemberQueryParams,responses:{200:t.array(Ne.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:Ne.teamMemberQueryParams,responses:{200:Ne.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:Ne.createTeamMemberRequest,responses:{201:Ne.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:Ne.updateTeamMemberRequest,responses:{200:Ne.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:Ne.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:Ne.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:Ne.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(Ne.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:Ne.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"}}),ve=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:se.optional(),createdAt:e.string(),updatedAt:e.string(),_version:e.string().optional().default("1.0")});class Se{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 ie(e.role)}catch(e){}}static from(e){try{return e?.id&&e?.name&&e?.identity&&e?.roleId?new Se(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 Se.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>Se.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=ve.safeParse(t);if(!r.success)return void console.error("Invalid TeamMemberJSON:",r.error.flatten());const n=r.data,a=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 Se.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:a,createdAt:n.createdAt,updatedAt:n.updatedAt})}catch(e){return void console.error("Error parsing TeamMemberJSON:",e)}}static isTeamMemberJSON(e){return ve.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>Se.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 Oe extends q{constructor(e){super("admin",we,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),a=Se.from(n);if(!a)throw new Error("Invalid team member data received from server");return a}async archiveTeamMember(e){const t=await this.client.archiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),n=Se.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=Se.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 Se.createMany(r)}async getTeamMember(e,t={eager:"role"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),n=this.handleResponse(r,200),a=Se.from(n);if(!a)throw new Error("Invalid team member data received from server");return a}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=ie.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=ie.from(r);if(!n)throw new Error("Invalid role data received from server");return n}}class Ae extends q{constructor(e){super("auth",he,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 v({message:"Invalid email or password",statusCode:400});if(201===n.status){const e=n.body.token,t=new fe({token:e}),r=await t.getIdentity(),a=oe.from(r);if(!a)throw new v({message:"Failed to construct login credentials",statusCode:502});const o=n.body.profile,s=re.from(o);if(!s)throw new v({message:"Failed to construct user profile",statusCode:502});let i;if(a.can(S.Role.ViewRole))try{const t=new Oe({token:e});i=await t.getRole(a.roleId)}catch(e){console.warn("Failed to fetch role details:",e)}const c=le.from({logIn:a,companyProfile:s,role:i});if(!c)throw new v({message:"Failed to construct user session",statusCode:502});return{token:e,user:c}}throw new v({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 v({message:"Invalid current password",statusCode:400});throw new v({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 Ie;!function(e){e.Bank="Bank",e.Mobile="Mobile"}(Ie||(Ie={}));const Ce=t.nativeEnum(Ie),_e=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:Ce}),Pe={beneficiaryDTO:t.object({id:t.string().min(1,"Beneficiary id is required"),profileId:t.string(),createdAt:t.string().datetime(),updatedAt:t.string().datetime()}).merge(_e),beneficiaryInputDTO:_e,beneficiaryType:Ce},Ee=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")}),De=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")}),Te=t.discriminatedUnion("type",[Ee,De]);class Re extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="BeneficiaryError"}}class Je{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}toJSONString(){return JSON.stringify(this.toJSON())}get isMobile(){return this.type===Ie.Mobile}get isBank(){return this.type===Ie.Bank}get displayName(){return this.accountName}}class Be extends Je{name;phoneNumber;mnoId;constructor(e,t,r){super(Ie.Mobile,t.countryCode),this.name=e,this.phoneNumber=t;const n=Be.resolveMnoId(t,r),a=Be.checkInputs(e,t,n);if(!a.isValid)throw new Re(a.errors[0],{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format,mnoId:n});this.mnoId=n}static resolveMnoId(e,t){return n.requiresExplicitProvider(e.countryCode)?t:n.detectProviderByPhoneNumber(e)?.id}static checkInputs(e,t,r){const a=[];return e?.trim()||a.push("Name is required and cannot be empty"),t?.validate()||a.push("Invalid phone number"),r?n.validateProviderForPhoneNumber(t,r)||a.push(`Invalid MNO ${r} for phone number ${t.e164Format}`):a.push(n.requiresExplicitProvider(t.countryCode)?`MNO must be explicitly provided for phone numbers in ${t.countryCode}`:`Failed to determine MNO for phone number ${t.e164Format}`),{isValid:0===a.length,errors:a,warnings:[]}}static pickMnoIdFromDTO(e,t){if(n.requiresExplicitProvider(e.countryCode)){if("string"!=typeof t)return;return n.isProviderSupported(e.countryCode,t)?t:void console.warn(`Invalid MNO ${t} for country ${e.countryCode}`)}const r=n.detectProviderByPhoneNumber(e);if(r)return r.id;console.warn(`Failed to auto-detect MNO for phone number ${e.e164Format}`)}static from(e){try{return new Be(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==Ie.Mobile)return;const t=e.accountNo.startsWith("+")?e.accountNo:`+${e.accountNo}`,r=a.from(t);if(!r)return void console.error(`Failed to parse phone number ${t}`);const n=Be.pickMnoIdFromDTO(r,e.channel);return n?Be.from({name:e.displayName,phoneNumber:r,mnoId:n}):void 0}static fromBeneficiaryDTO(e){return Be.fromInputDTO(e)}static fromPayoutDTO(e){if(!o.isISO2Code(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=a.from(e.msisdn,{defaultCountry:e.countryCode});if(!t)return void console.error(`Failed to parse phone number: ${e.msisdn}`);const r=Be.pickMnoIdFromDTO(t,e.channel);return r?Be.from({name:e.payeeName,phoneNumber:t,mnoId:r}):void 0}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===Ie.Mobile&&(!("string"!=typeof t.name||!t.name.trim())&&(!!a.is(t.phoneNumber)&&("string"==typeof t.mnoId&&n.isProviderSupported(t.phoneNumber.countryCode,t.mnoId))))}validate(){return Be.checkInputs(this.name,this.phoneNumber,this.mnoId).isValid}getValidationDetails(){return Be.checkInputs(this.name,this.phoneNumber,this.mnoId)}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.findById(this.mnoId,this.countryCode);return e?.mobileMoneyServiceName??e?.displayName??this.mnoId}get mobileMoneyProvider(){return n.findById(this.mnoId,this.countryCode)}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=Ee.safeParse(t);if(!r.success)return void console.error("Invalid MobileBeneficiaryJSON:",r.error.flatten());const n=a.from(r.data.phoneNumber);if(!n)return;return Be.from({name:r.data.name,phoneNumber:n,mnoId:r.data.mnoId})}catch(e){return void console.error("Error parsing MobileBeneficiaryJSON:",e)}}static fromJSONString(e){return Be.fromJSON(e)}static isJSON(e){return Ee.safeParse(e).success}}class je extends Je{accName;bank;accNo;constructor(e,t,r){super(Ie.Bank,t.countryCode),this.accName=e,this.bank=t,this.accNo=r;const n=je.checkInputs(e,t,r);if(!n.isValid)throw new Re(n.errors[0],{operation:"constructor",countryCode:t.countryCode})}static checkInputs(e,t,r){const n=[];return i.validateAccountName(e)||n.push("Invalid account name"),c.is(t)?i.validateAccountNumber(r,t.countryCode)||n.push("Invalid account number"):n.push("Invalid bank reference"),{isValid:0===n.length,errors:n,warnings:[]}}static from(e){try{return new je(e.accName,e.bank,e.accNo)}catch(e){return void console.error("Failed to create BankBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==Ie.Bank)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank beneficiaries");const r=i.getCountryFromSwiftCode(t);if(!r)return void console.error(`Could not identify country from SWIFT code: ${t}`);const n=c.fromBIC(t,r);if(n)return je.from({accName:e.displayName,bank:n,accNo:e.accountNo});console.error(`Bank with SWIFT code ${t} not found`)}static fromBeneficiaryDTO(e){return je.fromInputDTO(e)}static fromPayoutDTO(e){if(!o.isISO2Code(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,a=c.fromBIC(r,e.countryCode);if(a)return je.from({accName:e.payeeName,bank:a,accNo:n});console.error(`Bank with SWIFT code ${r} not found`)}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===Ie.Bank&&("string"==typeof t.accName&&("string"==typeof t.accNo&&(!!c.is(t.bank)&&(i.validateAccountName(t.accName)&&i.validateAccountNumber(t.accNo,t.bank.countryCode)))))}validate(){return je.checkInputs(this.accName,this.bank,this.accNo).isValid}getValidationDetails(){return je.checkInputs(this.accName,this.bank,this.accNo)}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.bic}get channelName(){return this.bank.shortName}toJSON(){return{type:"Bank",accName:this.accName,swiftCode:this.bank.bic,countryCode:this.bank.countryCode,accNo:this.accNo,_version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=De.safeParse(t);if(!r.success)return void console.error("Invalid BankBeneficiaryJSON:",r.error.flatten());const n=r.data;if(!o.isISO2Code(n.countryCode))return;const a=c.fromBIC(n.swiftCode,n.countryCode);if(!a)return;return je.from({accName:n.accName,bank:a,accNo:n.accNo})}catch(e){return void console.error("Error parsing BankBeneficiaryJSON:",e)}}static fromJSONString(e){return je.fromJSON(e)}static isJSON(e){return De.safeParse(e).success}}class Me{static fromInputDTO(e){return Me.fromDTO(e)}static fromBeneficiaryDTO(e){return Me.fromDTO(e)}static fromPayoutDTO(e){return e.msisdn.includes(":")?je.fromPayoutDTO(e):Be.fromPayoutDTO(e)}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Te.safeParse(t);if(!r.success)return;return"Mobile"===r.data.type?Be.fromJSON(r.data):je.fromJSON(r.data)}catch{return}}static fromJSONString(e){return Me.fromJSON(e)}static is(e){return Be.is(e)||je.is(e)}static isJSON(e){return Te.safeParse(e).success}static fromDTO(e){return e.type===Ie.Mobile?Be.fromInputDTO(e):je.fromInputDTO(e)}}const xe={fromInputDTO:e=>Me.fromInputDTO(e),fromBeneficiaryDTO:e=>Me.fromBeneficiaryDTO(e),fromPayoutDTO:e=>Me.fromPayoutDTO(e),fromJSON:e=>Me.fromJSON(e),fromJSONString:e=>Me.fromJSONString(e),is:e=>Me.is(e),isJSON:e=>Me.isJSON(e)},Fe=Pe.beneficiaryDTO.extend({_version:t.string().optional().default("1.0")});class ke{data;_info;_infoComputed=!1;constructor(e){this.data=Pe.beneficiaryDTO.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._infoComputed||(this._infoComputed=!0,this._info=Me.fromBeneficiaryDTO(this.data)),this._info}get accNo(){const e=this.info;return e?e.accountNumber:this.data.accountNo}get accName(){return this.data.displayName}get accNoLabel(){return this.type===Ie.Mobile?"Phone Number":this.type===Ie.Bank?"Bank Account Number":"Account Number"}get channelLabel(){return this.type===Ie.Mobile?"Channel":this.type===Ie.Bank?"Bank":"Channel"}get accNameLabel(){return this.type===Ie.Mobile?"Full Name":this.type===Ie.Bank?"Bank Account Name":"Display Name"}get channelName(){return this.info?.channelName??""}static from(e){try{return new ke(e)}catch(e){return void console.error("Failed to create Beneficiary:",e)}}static create(e){return new ke(e)}static createMany(e){return e.map(e=>new ke(e))}static createSafe(e){return ke.from(e)??null}static canConstruct(e){return Pe.beneficiaryDTO.safeParse(e).success}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&ke.canConstruct(e.data))}toJSON(){return{...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=t&&"object"==typeof t&&"data"in t?t.data:t,n=Fe.safeParse(r);if(!n.success)return void console.error("Invalid BeneficiaryJSON:",n.error.flatten());const a=n.data,{_version:o,...s}=a;return ke.from(s)}catch(e){return void console.error("Error parsing BeneficiaryJSON:",e)}}static fromJSONString(e){return ke.fromJSON(e)}static isBeneficiaryJSON(e){return Fe.safeParse(e).success}}class Le{canHandle(e){return"Mobile"===e.type&&Be.is(e)}createInput(e){if(Be.is(e))return{type:Ie.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile BeneficiaryInfo Info")}}class Ue{canHandle(e){return"Bank"===e.type&&je.is(e)}createInput(e){if(je.is(e))return{type:Ie.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Bank BeneficiaryInfo Info")}}class $e{handlers=[new Le,new Ue];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 qe=D().router({createBeneficiary:{method:"POST",path:"/",body:Pe.beneficiaryInputDTO,responses:{201:Pe.beneficiaryDTO}},editBeneficiary:{method:"PATCH",path:"/:id",body:Pe.beneficiaryInputDTO,responses:{200:Pe.beneficiaryDTO}},getBeneficiaries:{method:"GET",path:"/",query:t.object({orderByDesc:t.string()}),responses:{200:t.array(Pe.beneficiaryDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:Pe.beneficiaryDTO}},deleteBeneficiary:{method:"DELETE",path:"/:id",body:t.object({}),responses:{200:t.object({})}}});class We extends q{constructor(e){super("contact",qe,e)}async create(e){const t=(new $e).resolve(e),r=await this.client.createBeneficiary({body:t}),n=this.handleResponse(r,201);return ke.create(n)}async edit(e,t){const r=(new $e).resolve(t),n=await this.client.editBeneficiary({params:{id:e},body:r}),a=this.handleResponse(n,200);return ke.create(a)}async remove(e){const t=await this.client.deleteBeneficiary({params:{id:e}});this.handleResponse(t,200)}async getAll(){const e=await this.client.getBeneficiaries({query:{orderByDesc:"createdAt"}}),t=this.handleResponse(e,200);return ke.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return ke.create(r)}}var Ve,Ge,He;!function(e){e.MOBILE="Mobile",e.BANK="Bank"}(Ve||(Ve={})),function(e){e.CREATED="CREATED",e.PENDING="PENDING",e.PAID="PAID",e.FAILED="FAILED",e.REJECTED="REJECTED",e.REVERSED="REVERSED",e.QUEUED="QUEUED"}(Ge||(Ge={})),function(e){e.PENDING="Pending",e.APPROVED="Approved",e.REJECTED="Rejected"}(He||(He={}));const Qe=t.object({id:t.string(),name:t.string(),identity:t.string()}),Ze=t.nativeEnum(Ge),Ke=t.nativeEnum(He),Ye=t.object({channel:t.string(),msisdn:t.string(),amount:t.coerce.number(),description:t.string(),notes:t.string().nullish()}),ze=Ye.extend({payeeName:t.string()}),Xe=Ye.extend({id:t.string(),profileId:t.string(),payeeName:t.string(),countryCode:t.string().default("TZ").refine(e=>o.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.string().default("TZS").refine(e=>u.isCode(e),{message:"Provided currency code is not a valid currency code."}),channel:t.string(),status:Ze,statusMessage:t.string(),partnerReference:t.string().nullish(),createdAt:t.coerce.date(),updatedAt:t.coerce.date(),actionedAt:t.coerce.date().nullish(),approvalStatus:Ke.nullish(),createdBy:Qe.nullish(),actionedBy:Qe.nullish()}),et=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:Ze.nullish(),approvalStatus:Ke.nullish(),minAmount:t.number().min(0).nullish(),maxAmount:t.number().min(0).nullish(),search:t.string().nullish()}),tt={PayoutDTO:Xe,PayoutInputDTO:ze,PayoutStatus:Ze,PayoutApprovalStatus:Ke,PayoutAuthorizer:Qe,PayoutFilters:et,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(Ge).includes(e)).transform(e=>e).optional(),approvalStatus:t.string().refine(e=>Object.values(He).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()})},rt=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:tt.PayoutStatus,statusMessage:e.string(),partnerReference:e.string().nullish(),createdAt:e.string(),updatedAt:e.string(),actionedAt:e.string().nullish(),approvalStatus:tt.PayoutApprovalStatus.nullish(),createdBy:tt.PayoutAuthorizer.nullish(),actionedBy:tt.PayoutAuthorizer.nullish(),_version:e.string().optional().default("1.0")});class nt{data;constructor(e){this.data=tt.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?Ge.REJECTED:"Approved"===this.data.approvalStatus?"FAILED"===this.data.status?Ge.FAILED:Ge.PAID:"Pending"===this.data.approvalStatus?Ge.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 beneficiaryInfo(){return Me.fromPayoutDTO(this.data)}get contactInfo(){return this.beneficiaryInfo}static create(e){return new nt(e)}static createMany(e){return e.map(e=>new nt(e))}static createSafe(e){try{return new nt(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=tt.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==nt.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&nt.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=rt.safeParse(t);if(!r.success)return void console.error("Invalid PayoutJSON:",r.error.flatten());const n=r.data,a=n.currencyCode;if(!u.isCode(a))return void console.error("Invalid currency code:",a);const s=n.countryCode;if(!o.isISO2Code(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:a,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 nt.create(i)}catch(e){return void console.error("Error parsing PayoutJSON:",e)}}static isPayoutJSON(e){return rt.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>nt.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 at="MOBILE TRANSFER ",ot="PAYOUT",st="PAYOUT TO BANK",it="TO_BANK",ct="PAYOUT TO MOBILE",ut="TO_MOMO",dt=e.object({text:e.string(),_version:e.string().optional().default("2.0")});class lt{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 Be.is(e)?lt.generateMobilePayoutNarrationV2(e):je.is(e)?lt.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${ot.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:n}=e;return`${ot.toUpperCase()} ${t.bic.trim()} ${n.trim()} ${r.trim()}`.toUpperCase()}getBeneficiaryDetails=()=>{const e=this.getBankBeneficiaryDetails(),t=this.getMobileBeneficiaryDetails();return e||(t||void 0)};getBankBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(at)&&(e=e.substring(16));try{if(e.startsWith(ot)){const t=e.replace(ot,"").trim().split(" ");if(t.length>=3){const e=t[0],r=t[1],n=t.slice(2).map(mt).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 a=c.fromBIC(e,t);if(r&&n&&a)return new je(n,a,r)}}}}}if(e.startsWith(it)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=r.account_number,a=r.account_name,o=r.swift_code,s=i.getCountryFromSwiftCode(o);if(!s)return;if(!i.validateSwiftCode(o,s))return;const u=c.fromBIC(o,s);if(n&&a&&u)return new je(a,u,n)}if(e.startsWith(st)){const t=e.replace(st,"").trim().split(" "),r=l.getInstance().searchBanks("TZ",t[0]),n=r.length>0?r[0]:void 0,a=t[1],o=t.slice(2).map(mt).join(" ");if(o&&a&&n)return new je(o,n,a)}}catch(e){return}};getMobileBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(at)&&(e=e.substring(16));try{if(e.startsWith(ot)){const t=e.replace(ot,"").trim().split(" ");if(t.length>=2){const e=t[0],r=t.slice(1).map(mt).join(" ");if(e.startsWith("+")){const t=a.from(e);if(t&&r)return new Be(r,t)}}}if(e.startsWith(ut)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=a.from(r.phone_number,{defaultCountry:"TZ"});let o=r.username;void 0===o&&(o="");let s=o.split(" ");if(s=s.filter(e=>e.trim().length>0),o=s.map(mt).join(" "),n&&o)return new Be(o,n)}if(e.startsWith(ct)){const t=e.replace(ct,"").trim().split(" "),r=a.from(t[0],{defaultCountry:"TZ"}),n=t.slice(1).map(mt).join(" ");if(r&&n)return new Be(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.getBeneficiaryDetails&&"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=dt.safeParse(t);if(!r.success)return void console.error("Invalid NarrationJSON:",r.error.flatten());const n=r.data;return new lt(n.text)}catch(e){return void console.error("Error parsing NarrationJSON:",e)}}static isNarrationJSON(e){return dt.safeParse(e).success}toJson(){return this.toJSON()}static fromJson(e){return lt.fromJSON(e)}}function mt(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}const ht={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 TZ and KE banks are supported for now",UNSUPPORTED_COUNTRY_MOBILE:"Only TZ and KE mobile numbers are supported for now",NO_HANDLER_FOUND:"Cannot create payout input!"}};class pt{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}static isPhoneEligibleForPayout(e){const t=e.getNumberType();return t===m.MOBILE||t===m.FIXED_LINE_OR_MOBILE}}class ft{static forBank(e,t){if(!ht.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(ht.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,t,r){if(!a.is(e))throw new Error(ht.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!ht.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(ht.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!pt.isPhoneEligibleForPayout(e))throw new Error(ht.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const o=n.findById(t,e.countryCode);if(!o)throw new Error(ht.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return"VODACOM"===o.id?`${r.countryCode}-TIGO-B2C`:`${r.countryCode}-${o.id}-B2C`}}class yt{canHandle(e,t,r){return e===Ve.MOBILE&&Be.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===h.fromCode(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=pt.processNotes(e.notes),a=r.phoneNumber;return{channel:ft.forMobile(a,r.mnoId,t),msisdn:a.getWithFormat(s.INTERNATIONAL_NUMERIC),description:n??lt.generateDefaultPayoutNarration(r),payeeName:r.name,notes:n,amount:e.amount.numericValue}}}class gt{canHandle(e,t,r){return e===Ve.BANK&&je.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===h.fromCode(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=pt.processNotes(e.notes);return{channel:ft.forBank(r,t),msisdn:`${r.bank.bic}:${r.accNo}`,description:n??lt.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:n,amount:e.amount.numericValue}}}class bt{handlers=[new yt,new gt];getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(ht.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const Nt={bank:ft.forBank.bind(ft),mobile:ft.forMobile.bind(ft)},wt=D().router({getPayouts:{method:"GET",path:"",query:t.object({}),responses:{200:t.object({results:t.array(tt.PayoutDTO),total:t.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:t.object({rangeStart:t.number(),rangeEnd:t.number(),eager:t.string(),approvalStatus:tt.PayoutApprovalStatus,orderByDesc:t.string()}),responses:{200:t.object({results:t.array(tt.PayoutDTO),total:t.number()})}},postPayout:{method:"POST",path:"",body:tt.PayoutInputDTO,responses:{201:tt.PayoutDTO,400:v.schema}},approve:{method:"POST",path:"/:id/approve",body:t.object({action:t.enum(["Approve","Reject"]),notes:t.string().optional()}),responses:{201:tt.PayoutDTO,400:v.schema,401:v.schema,404:t.object({}),409:t.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:tt.PayoutDTO,404:t.object({})}}});class vt extends H{static create(){return new vt}static fromFilters(e){return(new vt).applyFilters(e)}static fromUrlParams(e){try{const t=tt.PayoutURLQueryParams.parse(e),r=tt.PayoutFilters.parse(t);return vt.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 vt.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return vt.fromSearchParams(t)}static from(e){try{return null==e?new vt:H.is(e)?new vt(e.options):e instanceof URLSearchParams?vt.fromSearchParams(e):this.isStringRecord(e)?vt.fromUrlParams(e):vt.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(He.PENDING)}whereApproved(){return this.whereApprovalStatus(He.APPROVED)}whereRejected(){return this.whereApprovalStatus(He.REJECTED)}wherePaid(){return this.whereStatus(Ge.PAID)}whereFailed(){return this.whereStatus(Ge.FAILED)}whereAmountBetween(e,t){return e.currencyCode!==t.currencyCode||e.numericValue>t.numericValue?this:this.whereBetween("amount",e.numericValue,t.numericValue)}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,a=n||"TZS";if(!u.isCode(a))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,a),r=d.from(e.maxAmount,a);t&&r&&this.whereAmountBetween(t,r)}else t?this.whereGreaterThanOrEqual("amount",e.minAmount):r&&this.whereLessThanOrEqual("amount",e.maxAmount)}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)}describeFilters(e){const t=[],r=this.toFilters(),n=e?.formatDate??(e=>e);if(r.sortBy){const e="asc"===r.sortOrder?"Ascending":"Descending";t.push({label:"Sort",value:`${this.formatSortField(r.sortBy)} (${e})`})}if(r.startDate&&r.endDate?t.push({label:"Date Range",value:`${n(r.startDate)} — ${n(r.endDate)}`}):r.startDate?t.push({label:"From",value:n(r.startDate)}):r.endDate&&t.push({label:"Until",value:n(r.endDate)}),r.status&&t.push({label:"Status",value:r.status}),r.approvalStatus&&t.push({label:"Approval Status",value:r.approvalStatus}),r.channel&&t.push({label:"Channel",value:r.channel}),void 0!==r.minAmount&&void 0!==r.maxAmount){const e=Number(r.minAmount),n=Number(r.maxAmount);if(Number.isFinite(e)&&Number.isFinite(n)){const r=d.from(e,"TZS"),a=d.from(n,"TZS");r&&a&&t.push({label:"Amount Range",value:`${r.label} — ${a.label}`})}}else if(void 0!==r.minAmount){const e=Number(r.minAmount);if(Number.isFinite(e)){const r=d.from(e,"TZS");r&&t.push({label:"Minimum Amount",value:r.label})}}else if(void 0!==r.maxAmount){const e=Number(r.maxAmount);if(Number.isFinite(e)){const r=d.from(e,"TZS");r&&t.push({label:"Maximum Amount",value:r.label})}}return r.search&&t.push({label:"Search",value:`"${r.search}"`}),r.payeeName&&t.push({label:"Beneficiary Name",value:r.payeeName}),r.msisdn&&t.push({label:"MSISDN",value:r.msisdn}),r.profileId&&t.push({label:"Profile",value:r.profileId}),r.partnerReference&&t.push({label:"Reference",value:r.partnerReference}),t}describeFiltersAsText(){return this.describeFilters().map(e=>`${e.label}: ${e.value}`)}formatSortField(e){return{createdAt:"Date Created",updatedAt:"Date Updated",amount:"Amount",payeeName:"Beneficiary Name",status:"Status"}[e]??e}build(){return super.build()}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(Ge).includes(e)}isValidApprovalStatus(e){return Object.values(He).includes(e)}}class St extends q{constructor(e){super("payout",wt,e)}async getPayouts(e){try{const t=vt.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),a=this.handleResponse(n,200),o=t.toFilters(),s=new Y(o.page??1,o.limit??10,a.total);return{results:nt.createMany(a.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=vt.from(e).build();delete t.rangeStart,delete t.rangeEnd;const r=await this.client.getPayouts({query:t}),n=this.handleResponse(r,200);return nt.createMany(n)}catch(e){throw console.log("error: ",e),new Error(`Failed to fetch all payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=vt.fromRequest(e);return this.getPayouts(t)}async pay(e){const{wallet:t,channel:r,receiver:n,amount:a,notes:o}=e,s=p.getTransactionLimits({countryCode:t.countryCode,currencyCode:a.currencyCode,direction:y.PAYOUT,channelType:r===Ve.BANK?f.BANK:f.MOBILE_MONEY});if(!s)throw new v({statusCode:400,message:`Payout limits are not configured for ${t.countryCode} ${a.currencyCode} ${r} payouts`});const{min:i,max:c}=s;if(a.lessThan(i)||a.greaterThan(c))throw new v({statusCode:400,message:`Please make sure the amount is between ${i.label} - ${c.label}`});const u=(new bt).getPayoutInput({channel:r,receiver:n,amount:a,notes:o},t),d=await this.client.postPayout({body:u});if(201===d.status)return nt.create(d.body);if(400===d.status)throw new v(d.body);throw v.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 nt.create(t.body);if(401===t.status)throw new v({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new v({message:"Payout not found",statusCode:404});if(409===t.status)throw new v({message:"Payout already approved",statusCode:409});throw v.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 nt.create(t.body);if(401===t.status)throw new v({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new v({message:"Payout not found",statusCode:404});if(409===t.status)throw new v({message:"Payout already rejected",statusCode:409});throw v.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return nt.create(t.body);if(404===t.status)throw new v({message:"Payout not found",statusCode:404});throw v.unknown()}async count(e){const t=vt.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 Ot=e=>e.optional().transform(e=>e??void 0),At={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=>o.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.string().default("TZS").refine(e=>u.isCode(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=g.fromCode(e);return void 0!==t&&b.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:t.object({accountNo:Ot(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:Ot(t.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})},It=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 At.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&&o.isISO2Code(t._countryCode)&&"string"==typeof t._currencyCode&&u.isCode(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=It.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 It.safeParse(e).success}}const _t=e.object({accountNo:e.string().optional(),debitOrCredit:e.string(),tranRefNo:e.string(),narration:dt,txnDate:e.string(),valueDate:e.string(),amountCredited:w,amountDebited:w,balance:w,currencyCode:e.string(),_version:e.string().optional().default("2.0")});class Pt{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return At.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=g.fromCode(e.currencyCode);if(!r)throw new Error(`Currency not found for code: ${e.currencyCode}`);const n=d.from(e.amountCredited,r.code),a=d.from(e.amountDebited,r.code),o=d.from(e.balance,r.code);if(!n||!a||!o)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=n,this._amountDebited=a,this._balance=o}static create(e){const t="string"==typeof e.narration?new lt(e.narration):e.narration,r={...e,narration:t.text},n=Pt.schema.safeParse(r);if(n.success)try{const{narration:e,...r}=n.data;return new Pt(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=Pt.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&<.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 Pt.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,a,o=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const a=d.fromJSON(e.amountCredited),s=d.fromJSON(e.amountDebited),i=d.fromJSON(e.balance);if(!a||!s||!i)return void console.error("Failed to deserialize Amount objects from JSON");t=a.numericValue,r=s.numericValue,n=i.numericValue,e.currencyCode||(o=a.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)a=e.narration;else if(lt.is(e.narration))a=e.narration;else{if(!lt.isNarrationJSON(e.narration))return void console.error("Invalid narration data");{const t=lt.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");a=t}}return Pt.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:a,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:r,balance:n,currencyCode:o})}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=_t.safeParse(t);if(!r.success)return void console.error("Invalid WalletStatementEntryJSON:",r.error.flatten());const n=r.data,a=lt.fromJSON(n.narration);if(!a)return void console.warn("Failed to deserialize narration");const o=d.fromJSON(n.amountCredited),s=d.fromJSON(n.amountDebited),i=d.fromJSON(n.balance);return o&&s&&i?o.currencyCode!==n.currencyCode||s.currencyCode!==n.currencyCode||i.currencyCode!==n.currencyCode?void console.warn("Currency code mismatch"):Pt.create({accountNo:n.accountNo,debitOrCredit:n.debitOrCredit,tranRefNo:n.tranRefNo,narration:a,txnDate:n.txnDate,valueDate:n.valueDate,amountCredited:o.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 _t.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>Pt.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 Pt.fromJSON(e)}static fromJsonArray(e){return Pt.fromJSONArray(e)}static toJsonArray(e){return Pt.toJSONArray(e)}}const Et=D().router({getWallets:{method:"GET",path:"/",query:At.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(Pt.schema)}}});class Dt extends H{static create(){return new Dt}static fromFilters(e){return(new Dt).applyFilters(e)}static fromUrlParams(e){try{const t=At.walletQuery.parse(e);return Dt.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 Dt.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Dt.fromSearchParams(t)}static from(e){try{return null==e?new Dt:H.is(e)?new Dt(e.options):e instanceof URLSearchParams?Dt.fromSearchParams(e):this.isStringRecord(e)?Dt.fromUrlParams(e):Dt.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}build(){return super.build()}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 Tt extends q{constructor(e){super("wallet",Et,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=Dt.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=Dt.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),a=e.range??{startDate:r,endDate:n};let o,s;if(e.wallet)o=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}`);o=t[0],s=e.accountNo}}const i={...a,accountNo:s},c=await this.client.getStatement({body:i});if(201===c.status){return c.body.map(e=>({...e,currencyCode:o.currencyCode})).reduce((e,t)=>{const r=Pt.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 Rt={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)},Jt=D().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:re.schema}}});class Bt extends q{constructor(e){super("profile",Jt,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=re.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{v as APIError,me as AuthDTOSchemas,Ae as AuthRepository,st as BANK_NARR_PREFIX,je as BankBeneficiaryInfo,De as BankBeneficiaryJSONSchema,q as BaseRepository,ke as Beneficiary,Pe as BeneficiaryDTOSchemas,Re as BeneficiaryError,xe as BeneficiaryInfo,Me as BeneficiaryInfoFactory,Te as BeneficiaryInfoJSONSchema,Fe as BeneficiaryJSONSchema,We as BeneficiaryRepository,Ie as BeneficiaryType,ue as CompanyMembership,ce as CompanyMembershipJSONSchema,at as ECOBANK_PREFIX,W as FilterOperator,fe as IdentityRepository,it as LEGACY_BANK_NARR_PREFIX,ut as LEGACY_MOBILE_NARR_PREFIX,oe as LogIn,ae as LogInJSONSchema,ne as LogInSchemas,ct as MOBILE_NARR_PREFIX,Be as MobileBeneficiaryInfo,Ee as MobileBeneficiaryJSONSchema,ot as NARR_V2_PREFIX,lt as Narration,dt as NarrationJSONSchema,Y as Pagination,Q as PaginationParamsSchema,Z as PaginationSchema,nt as Payout,He as PayoutApprovalStatus,Ve as PayoutChannel,tt as PayoutDTOSchemas,bt as PayoutInputFactory,rt as PayoutJSONSchema,vt as PayoutQuery,St as PayoutRepository,Ge as PayoutStatus,O as PermissionError,S as Permissions,re as Profile,ee as ProfileDTOSchemas,te as ProfileJSONSchema,Bt as ProfileRepository,G as QUERY_BUILDER_TYPE,H as QueryBuilder,ie as Role,se as RoleJSONSchema,V as SortDirection,Ne as TeamManagementDTOSchemas,Se as TeamMember,ve as TeamMemberJSONSchema,Oe as TeamMemberRepository,le as User,de as UserJSONSchema,$e as ValidatedBeneficiaryInputFactory,Ct as Wallet,At as WalletDTOSchemas,It as WalletJSONSchema,Tt as WalletRepository,Pt as WalletStatementEntry,_t as WalletStatementEntryJSONSchema,Rt as WalletUtils,qe as contract,z as createPaginatedResponse,K as createPaginatedResponseSchema,Nt as createPayoutChannelCode,X as emptyPaginatedResponse,A as isError,$ as setGlobalTokenGetter};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|