@temboplus/afloat 0.2.0 → 0.2.1-beta.1

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