@temboplus/afloat 0.2.1-beta.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 s,PhoneNumberFormat as o,BankHelpers as i,Bank as c,CurrencyHelpers as d,Amount as u,BankRegistry as l,PhoneNumberType as h,Country as m,TemboCoverage as p,ChannelType as y,TransactionDirection as f,Currency as g,CurrencyCodesSet as N,ISO2CountryCodesSet as b,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 I={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 S 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(I.Profile)),t.enum(Object.values(I.Beneficiary)),t.enum(Object.values(I.Payment)),t.enum(Object.values(I.Payout)),t.enum(Object.values(I.Transfer)),t.enum(Object.values(I.Wallet))]);return t.object({name:t.literal("PermissionError").nullish(),message:t.string(),requiredPermissions:t.array(r)}).safeParse(e).success}}function _(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message}const A=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 O=Symbol("ContractNoBody"),C=e=>"method"in e&&"path"in e,P=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,a,s,o,i;return C(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,A(o)?A(i)?o.merge(i):o:A(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,P(r,t)]})),B=Symbol("ContractPlainType"),D=()=>({router:(e,t)=>P(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>B,body:()=>B,type:()=>B,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>O}),E=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("&"):"",T=e=>e?Object.keys(e).flatMap(t=>R(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",R=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>R(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>R(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class J extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const j=async({route:e,path:t,method:r,headers:n,body: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==(d=r)?void 0:d.safeParse)?{...t,body:r.parse(t.body)}:t}var d;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 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?E(e):T(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,a);return`${t}${s}${o}`},k=(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:d,cache:u,next:l,...h}=r||{},m={...t,...c};return{path:F(n,m.baseUrl,a,e,!!m.jsonQuery),clientArgs:m,route:e,body:s,query:n,extraInputArgs:h,fetchOptions:{...u&&{cache:u},...l&&{next:l},...d},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,d=r.api||j,u=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...u&&x(u),...x(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:M(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)})),d({...h,...o})})(a);if(!t.throwOnUnknownStatus)return s;if(r.includes(s.status.toString()))return s;throw new J(s,r)}},L=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>C(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 V,W;!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"}(V||(V={})),function(e){e.ASC="asc",e.DESC="desc"}(W||(W={}));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:V.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:V.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:V.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:V.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:V.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:V.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:V.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:V.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:V.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:V.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:V.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:V.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:V.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:V.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=W.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,W.ASC)}orderByDesc(e){return this.orderBy(e,W.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 V.IS_NULL:e[`${t.field}:isNull`]=1;break;case V.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case V.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case V.LIKE:e[`${t.field}:like`]=t.value;break;case V.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case V.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case V.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===W.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 se{_id;_profileId;_name;_identity;_type;_roleId;_isActive;_isArchived;_resetPassword;_createdAt;_updatedAt;_access;_permissionMap;constructor(e,t,r,n,a,s,o,i,c,d,u,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=d,this._updatedAt=u,this._access=l,this._permissionMap={},this._access.forEach(e=>{this._permissionMap[e]=!0})}static from(e){const t=ne.loginDTO.parse(e);return new se(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 se.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 oe=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=oe.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 oe.safeParse(e).success}}const ce=e.object({companyProfile:te,role:oe.optional(),_version:e.string().optional().default("1.0")});class de{_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return re.is(e.companyProfile)?new de(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),s=n.role?ie.fromJSON(n.role):void 0;return a?de.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 ce.safeParse(e).success}}const ue=e.object({logIn:ae,companyProfile:te,role:oe.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=de.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=ue.safeParse(t);if(!r.success)return void console.error("Invalid UserJSON:",r.error.flatten());const n=r.data,a=se.fromJSON(n.logIn),s=re.fromJSON(n.companyProfile),o=n.role?ie.fromJSON(n.role):void 0;if(!a||!s)return void console.error("Failed to reconstruct nested objects from UserJSON");const i=de.from({companyProfile:s,role:o});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 ue.safeParse(e).success}}const he={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({})},me=D().router({logIn:{method:"POST",path:"/login",body:he.logInRequestDTO,responses:{201:he.logInResponseDTO,400:he.emptyResponseDTO}},access:{method:"GET",path:"/access",responses:{200:he.accessResponseDTO}},resetPassword:{method:"PUT",path:"/password",body:he.resetPasswordRequestDTO,responses:{200:he.emptyResponseDTO,400:he.emptyResponseDTO}}}),pe=D().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:ne.loginDTO}}});class ye 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 fe=t.string().min(8,"Password must be at least 8 characters long").max(128,"Password must not exceed 128 characters").regex(/[A-Z]/,"Password must contain at least one uppercase letter").regex(/[a-z]/,"Password must contain at least one lowercase letter").regex(/[0-9]/,"Password must contain at least one number").regex(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/,"Password must contain at least one special character (!@#$%^&*()_+-=[]{}|;:,.<>?)").refine(e=>![/(.)\1{2,}/,/123456|654321|abcdef|qwerty|password|admin|user/i,/^[0-9]+$/,/^[a-zA-Z]+$/].some(t=>t.test(e)),"Password contains weak patterns. Avoid repeated characters, common words, or simple sequences").refine(e=>!/(?:abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789)/i.test(e),"Password should not contain sequential characters").refine(e=>!/(?:qwer|wert|erty|rtyu|tyui|yuio|uiop|asdf|sdfg|dfgh|fghj|ghjk|hjkl|zxcv|xcvb|cvbn|vbnm)/i.test(e),"Password should not contain keyboard patterns"),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")}),Ne=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")}),be={role:ge,teamMember:Ne,teamMemberQueryParams:t.object({id:t.string().min(1).optional(),name:t.string().min(1).optional(),identity:t.string().email("Invalid email address").optional(),type:t.string().min(1).optional(),profileId:t.string().min(1).optional(),roleId:t.string().min(1).optional(),resetPassword:t.number().optional(),isActive:t.number().optional(),isArchived:t.number().optional(),createdAt:t.string().datetime("Invalid creation timestamp").optional(),updatedAt:t.string().datetime("Invalid update timestamp").optional(),eager:t.string().optional()}),createTeamMemberRequest:t.object({name:t.string().min(1,"Team member name is required"),identity:t.string().email("Valid email address is required"),password:fe.optional(),roleId:t.string().optional(),resetPassword:t.boolean().optional()}),updateTeamMemberRequest:t.object({name:t.string().min(1,"Team member name cannot be empty").optional(),roleId:t.string().min(1,"Role ID cannot be empty").optional(),password:fe.optional(),resetPassword:t.boolean().optional(),isActive:t.boolean().optional()}),resetPasswordRequest:t.object({newPassword:fe.optional(),sendNotification:t.boolean().optional()}),createTeamMemberResponse:t.object({id:t.string(),name:t.string(),identity:t.string(),type:t.string(),profileId:t.string(),resetPassword:t.boolean(),roleId:t.string(),isActive:t.boolean(),isArchived:t.boolean(),createdAt:t.string().datetime(),updatedAt:t.string().datetime()}),password:fe},we=D().router({getTeamMembers:{method:"GET",path:"/login",query:be.teamMemberQueryParams,responses:{200:t.array(be.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:be.teamMemberQueryParams,responses:{200:be.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:be.createTeamMemberRequest,responses:{201:be.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:be.updateTeamMemberRequest,responses:{200:be.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:be.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:be.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:be.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(be.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:be.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:oe.optional(),createdAt:e.string(),updatedAt:e.string(),_version:e.string().optional().default("1.0")});class Ie{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 Ie(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 Ie.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>Ie.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 Ie.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=>Ie.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 Se 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=Ie.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=Ie.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=Ie.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 Ie.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=Ie.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 _e extends q{constructor(e){super("auth",me,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 ye({token:e}),r=await t.getIdentity(),a=se.from(r);if(!a)throw new v({message:"Failed to construct login credentials",statusCode:502});const s=n.body.profile,o=re.from(s);if(!o)throw new v({message:"Failed to construct user profile",statusCode:502});let i;if(a.can(I.Role.ViewRole))try{const t=new Se({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:o,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 Ae;!function(e){e.Bank="Bank",e.Mobile="Mobile"}(Ae||(Ae={}));const Oe=t.nativeEnum(Ae),Ce=t.object({displayName:t.string().min(1,"Display name is required"),accountNo:t.string().min(1,"Account number is required"),channel:t.string().min(1,"Channel is required"),type:Oe}),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(Ce),beneficiaryInputDTO:Ce,beneficiaryType:Oe},Be=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")}),Ee=t.discriminatedUnion("type",[Be,De]);class Te extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="BeneficiaryError"}}class Re{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}toJSONString(){return JSON.stringify(this.toJSON())}get isMobile(){return this.type===Ae.Mobile}get isBank(){return this.type===Ae.Bank}get displayName(){return this.accountName}}class Je extends Re{name;phoneNumber;mnoId;constructor(e,t,r){super(Ae.Mobile,t.countryCode),this.name=e,this.phoneNumber=t;const n=Je.resolveMnoId(t,r),a=Je.checkInputs(e,t,n);if(!a.isValid)throw new Te(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 Je(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==Ae.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=Je.pickMnoIdFromDTO(r,e.channel);return n?Je.from({name:e.displayName,phoneNumber:r,mnoId:n}):void 0}static fromBeneficiaryDTO(e){return Je.fromInputDTO(e)}static fromPayoutDTO(e){if(!s.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=Je.pickMnoIdFromDTO(t,e.channel);return r?Je.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===Ae.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 Je.checkInputs(this.name,this.phoneNumber,this.mnoId).isValid}getValidationDetails(){return Je.checkInputs(this.name,this.phoneNumber,this.mnoId)}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(o.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=Be.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 Je.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 Je.fromJSON(e)}static isJSON(e){return Be.safeParse(e).success}}class je extends Re{accName;bank;accNo;constructor(e,t,r){super(Ae.Bank,t.countryCode),this.accName=e,this.bank=t,this.accNo=r;const n=je.checkInputs(e,t,r);if(!n.isValid)throw new Te(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!==Ae.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(!s.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===Ae.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(!s.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):Je.fromPayoutDTO(e)}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Ee.safeParse(t);if(!r.success)return;return"Mobile"===r.data.type?Je.fromJSON(r.data):je.fromJSON(r.data)}catch{return}}static fromJSONString(e){return Me.fromJSON(e)}static is(e){return Je.is(e)||je.is(e)}static isJSON(e){return Ee.safeParse(e).success}static fromDTO(e){return e.type===Ae.Mobile?Je.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{_id;_profileId;_displayName;_accountNo;_channel;_type;_createdAt;_updatedAt;_info;_infoComputed=!1;constructor(e){const t=Pe.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=Me.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===Ae.Mobile?"Phone Number":this.type===Ae.Bank?"Bank Account Number":"Account Number"}get channelLabel(){return this.type===Ae.Mobile?"Channel":this.type===Ae.Bank?"Bank":"Channel"}get accNameLabel(){return this.type===Ae.Mobile?"Full Name":this.type===Ae.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){if(!e||"object"!=typeof e)return!1;const t=e;if("function"!=typeof t.toJSON)return!1;try{return Fe.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=Fe.safeParse(r);if(!n.success)return void console.error("Invalid BeneficiaryJSON:",n.error.flatten());const a=n.data,{_version:s,...o}=a;return ke.from(o)}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}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 Le{canHandle(e){return"Mobile"===e.type&&Je.is(e)}createInput(e){if(Je.is(e))return{type:Ae.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:Ae.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 Ve 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 We,Ge,He;!function(e){e.MOBILE="Mobile",e.BANK="Bank"}(We||(We={})),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.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)),ze=Ye.pipe(t.array(Ze)),Xe=Ye.pipe(t.array(Ke)),et=t.object({channel:t.string(),msisdn:t.string(),amount:t.coerce.number(),description:t.string(),notes:t.string().nullish()}),tt=et.extend({payeeName:t.string()}),rt=et.extend({id:t.string(),profileId:t.string(),payeeName:t.string(),countryCode:t.string().default("TZ").refine(e=>s.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.string().default("TZS").refine(e=>d.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(),createdById:t.string().nullish(),actionedById:t.string().nullish(),createdBy:Qe.nullish(),actionedBy:Qe.nullish()}),nt=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:Ye.nullish(),profileId:t.string().nullish(),id:t.string().nullish(),partnerReference:t.string().nullish(),channel:t.string().nullish(),channelIn:Ye.nullish(),currencyCode:t.string().nullish(),status:Ze.nullish(),statusIn:ze.nullish(),approvalStatus:Ke.nullish(),approvalStatusIn:Xe.nullish(),createdById:t.string().nullish(),createdByIdIn:Ye.nullish(),actionedById:t.string().nullish(),actionedByIdIn:Ye.nullish(),minAmount:t.number().min(0).nullish(),maxAmount:t.number().min(0).nullish(),search:t.string().nullish()}),at={PayoutDTO:rt,PayoutInputDTO:tt,PayoutStatus:Ze,PayoutApprovalStatus:Ke,PayoutAuthorizer:Qe,PayoutFilters:nt,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:Ye.optional(),profileId:t.string().optional(),id:t.string().optional(),partnerReference:t.string().optional(),channel:t.string().optional(),channelIn:Ye.optional(),status:t.string().refine(e=>Object.values(Ge).includes(e)).transform(e=>e).optional(),statusIn:ze.optional(),approvalStatus:t.string().refine(e=>Object.values(He).includes(e)).transform(e=>e).optional(),approvalStatusIn:Xe.optional(),createdById:t.string().optional(),createdByIdIn:Ye.optional(),actionedById:t.string().optional(),actionedByIdIn:Ye.optional(),minAmount:t.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.string().transform(e=>parseFloat(e)).optional(),search:t.string().optional()})},st=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:at.PayoutStatus,statusMessage:e.string(),partnerReference:e.string().nullish(),createdAt:e.string(),updatedAt:e.string(),actionedAt:e.string().nullish(),approvalStatus:at.PayoutApprovalStatus.nullish(),createdById:e.string().nullish(),actionedById:e.string().nullish(),createdBy:at.PayoutAuthorizer.nullish(),actionedBy:at.PayoutAuthorizer.nullish(),_version:e.string().optional().default("1.0")});class ot{_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=at.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 u.from(this._amount,this._currencyCode)}get description(){return this._description}get notes(){return this._notes}get status(){return"Rejected"===this._approvalStatus?Ge.REJECTED:"Approved"===this._approvalStatus?"FAILED"===this._status?Ge.FAILED:Ge.PAID:"Pending"===this._approvalStatus?Ge.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 Me.fromPayoutDTO(this.toDTO())}get contactInfo(){return this.beneficiaryInfo}static create(e){return new ot(e)}static createMany(e){return e.map(e=>new ot(e))}static createSafe(e){try{return new ot(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=at.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==ot.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 st.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=st.safeParse(t);if(!r.success)return void console.error("Invalid PayoutJSON:",r.error.flatten());const n=r.data,a=n.currencyCode;if(!d.isCode(a))return void console.error("Invalid currency code:",a);const o=n.countryCode;if(!s.isISO2Code(o))return void console.error("Invalid country code:",o);const i={id:n.id,profileId:n.profileId,payeeName:n.payeeName,channel:n.channel,msisdn:n.msisdn,amount:n.amount,currencyCode:a,countryCode:o,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 ot.create(i)}catch(e){return void console.error("Error parsing PayoutJSON:",e)}}static isPayoutJSON(e){return st.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>ot.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing 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 it="MOBILE TRANSFER ",ct="PAYOUT",dt="PAYOUT TO BANK",ut="TO_BANK",lt="PAYOUT TO MOBILE",ht="TO_MOMO",mt=e.object({text:e.string(),_version:e.string().optional().default("2.0")});class pt{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 Je.is(e)?pt.generateMobilePayoutNarrationV2(e):je.is(e)?pt.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${ct.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:n}=e;return`${ct.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(it)&&(e=e.substring(16));try{if(e.startsWith(ct)){const t=e.replace(ct,"").trim().split(" ");if(t.length>=3){const e=t[0],r=t[1],n=t.slice(2).map(yt).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(ut)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=r.account_number,a=r.account_name,s=r.swift_code,o=i.getCountryFromSwiftCode(s);if(!o)return;if(!i.validateSwiftCode(s,o))return;const d=c.fromBIC(s,o);if(n&&a&&d)return new je(a,d,n)}if(e.startsWith(dt)){const t=e.replace(dt,"").trim().split(" "),r=l.getInstance().searchBanks("TZ",t[0]),n=r.length>0?r[0]:void 0,a=t[1],s=t.slice(2).map(yt).join(" ");if(s&&a&&n)return new je(s,n,a)}}catch(e){return}};getMobileBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(it)&&(e=e.substring(16));try{if(e.startsWith(ct)){const t=e.replace(ct,"").trim().split(" ");if(t.length>=2){const e=t[0],r=t.slice(1).map(yt).join(" ");if(e.startsWith("+")){const t=a.from(e);if(t&&r)return new Je(r,t)}}}if(e.startsWith(ht)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=a.from(r.phone_number,{defaultCountry:"TZ"});let s=r.username;void 0===s&&(s="");let o=s.split(" ");if(o=o.filter(e=>e.trim().length>0),s=o.map(yt).join(" "),n&&s)return new Je(s,n)}if(e.startsWith(lt)){const t=e.replace(lt,"").trim().split(" "),r=a.from(t[0],{defaultCountry:"TZ"}),n=t.slice(1).map(yt).join(" ");if(r&&n)return new Je(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=mt.safeParse(t);if(!r.success)return void console.error("Invalid NarrationJSON:",r.error.flatten());const n=r.data;return new pt(n.text)}catch(e){return void console.error("Error parsing NarrationJSON:",e)}}static isNarrationJSON(e){return mt.safeParse(e).success}toJson(){return this.toJSON()}static fromJson(e){return pt.fromJSON(e)}}function yt(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}const ft={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 gt{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===h.MOBILE||t===h.FIXED_LINE_OR_MOBILE}}class Nt{static forBank(e,t){if(!ft.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(ft.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,t,r){if(!a.is(e))throw new Error(ft.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!ft.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(ft.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!gt.isPhoneEligibleForPayout(e))throw new Error(ft.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const s=n.findById(t,e.countryCode);if(!s)throw new Error(ft.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return"VODACOM"===s.id?`${r.countryCode}-TIGO-B2C`:`${r.countryCode}-${s.id}-B2C`}}class bt{canHandle(e,t,r){return e===We.MOBILE&&Je.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===m.fromCode(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=gt.processNotes(e.notes),a=r.phoneNumber;return{channel:Nt.forMobile(a,r.mnoId,t),msisdn:a.getWithFormat(o.INTERNATIONAL_NUMERIC),description:n??pt.generateDefaultPayoutNarration(r),payeeName:r.name,notes:n,amount:e.amount.numericValue}}}class wt{canHandle(e,t,r){return e===We.BANK&&je.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===m.fromCode(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=gt.processNotes(e.notes);return{channel:Nt.forBank(r,t),msisdn:`${r.bank.bic}:${r.accNo}`,description:n??pt.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:n,amount:e.amount.numericValue}}}class vt{handlers=[new bt,new wt];getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(ft.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const It={bank:Nt.forBank.bind(Nt),mobile:Nt.forMobile.bind(Nt)},St=D().router({getPayouts:{method:"GET",path:"",query:t.object({}),responses:{200:t.object({results:t.array(at.PayoutDTO),total:t.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:t.object({rangeStart:t.number(),rangeEnd:t.number(),eager:t.string(),approvalStatus:at.PayoutApprovalStatus,orderByDesc:t.string()}),responses:{200:t.object({results:t.array(at.PayoutDTO),total:t.number()})}},postPayout:{method:"POST",path:"",body:at.PayoutInputDTO,responses:{201:at.PayoutDTO,400:v.schema}},approve:{method:"POST",path:"/:id/approve",body:t.object({action:t.enum(["Approve","Reject"]),notes:t.string().optional()}),responses:{201:at.PayoutDTO,400:v.schema,401:v.schema,404:t.object({}),409:t.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:at.PayoutDTO,404:t.object({})}}}),_t=["approvalStatus","status","channel","msisdn","createdById","actionedById"];class At extends H{static create(){return new At}static fromFilters(e){return(new At).applyFilters(e)}static fromUrlParams(e){try{const t=at.PayoutURLQueryParams.parse(this.normalizeUrlParams(e)),r=at.PayoutFilters.parse(t);return At.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return At.fromUrlParams(this.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return At.fromSearchParams(t)}static from(e){try{return null==e?new At:H.is(e)?new At(e.options):e instanceof URLSearchParams?At.fromSearchParams(e):this.isUrlParamsRecord(e)?At.fromUrlParams(e):At.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 _t){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,o=`${e}In[]`,i=t[r],c=At.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=>At.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(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)}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(!d.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=u.from(e.minAmount,a),r=u.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=u.from(e,"TZS"),a=u.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=u.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=u.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=At.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=At.toStringList(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=At.toStringList(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidApprovalStatuses(e){const t=At.toStringList(e).filter(e=>this.isValidApprovalStatus(e));return t.length>0?t:void 0}isValidStatus(e){return Object.values(Ge).includes(e)}isValidApprovalStatus(e){return Object.values(He).includes(e)}}class Ot extends q{constructor(e){super("payout",St,e)}async getPayouts(e){try{const t=At.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),a=this.handleResponse(n,200),s=t.toFilters(),o=new Y(s.page??1,s.limit??10,a.total);return{results:ot.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=At.from(e).build();delete t.rangeStart,delete t.rangeEnd;const r=await this.client.getPayouts({query:t}),n=this.handleResponse(r,200);return ot.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=At.fromRequest(e);return this.getPayouts(t)}async pay(e){const{wallet:t,channel:r,receiver:n,amount:a,notes:s}=e,o=p.getTransactionLimits({countryCode:t.countryCode,currencyCode:a.currencyCode,direction:f.PAYOUT,channelType:r===We.BANK?y.BANK:y.MOBILE_MONEY});if(!o)throw new v({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 v({statusCode:400,message:`Please make sure the amount is between ${i.label} - ${c.label}`});const d=(new vt).getPayoutInput({channel:r,receiver:n,amount:a,notes:s},t),u=await this.client.postPayout({body:d});if(201===u.status)return ot.create(u.body);if(400===u.status)throw new v(u.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 ot.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 ot.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 ot.create(t.body);if(404===t.status)throw new v({message:"Payout not found",statusCode:404});throw v.unknown()}async count(e){const t=At.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 Ct=e=>e.optional().transform(e=>e??void 0),Pt={walletDTO:t.object({id:t.string().min(1,{message:"Wallet ID is required."}),profileId:t.string().min(1,{message:"Profile ID is required."}),accountNo:t.string().min(1,{message:"Account number is required."}),accountName:t.string().min(1,{message:"Account name is required."}),channel:t.string().min(1,{message:"Channel is required."}),countryCode:t.string().default("TZ").refine(e=>s.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.string().default("TZS").refine(e=>d.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=>b.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&&N.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:t.object({accountNo:Ct(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:Ct(t.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})},Bt=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 Dt{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return Pt.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=Dt.schema.safeParse(e);if(t.success)return new Dt(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=Dt.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 Dt.create({id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt,currencyCode:e.currencyCode});console.error("Invalid data provided to Wallet.from: Input must be an object.")}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t._id&&"string"==typeof t._profileId&&"string"==typeof t._accountNo&&"string"==typeof t._accountName&&"string"==typeof t._channel&&"string"==typeof t._countryCode&&s.isISO2Code(t._countryCode)&&"string"==typeof t._currencyCode&&d.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=Bt.safeParse(t);if(!r.success)return void console.error("Invalid WalletJSON:",r.error.flatten());const n=r.data;return Dt.create(n)}catch(e){return void console.error("Error parsing WalletJSON:",e)}}static isWalletJSON(e){return Bt.safeParse(e).success}}const Et=e.object({accountNo:e.string().optional(),debitOrCredit:e.string(),tranRefNo:e.string(),narration:mt,txnDate:e.string(),valueDate:e.string(),amountCredited:w,amountDebited:w,balance:w,currencyCode:e.string(),_version:e.string().optional().default("2.0")});class Tt{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return Pt.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=u.from(e.amountCredited,r.code),a=u.from(e.amountDebited,r.code),s=u.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 pt(e.narration):e.narration,r={...e,narration:t.text},n=Tt.schema.safeParse(r);if(n.success)try{const{narration:e,...r}=n.data;return new Tt(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=Tt.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&&pt.is(t._narration)&&t._txnDate instanceof Date&&t._valueDate instanceof Date&&u.is(t._amountCredited)&&u.is(t._amountDebited)&&u.is(t._balance)&&"string"==typeof t._currencyCode}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return Tt.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=u.fromJSON(e.amountCredited),o=u.fromJSON(e.amountDebited),i=u.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(pt.is(e.narration))a=e.narration;else{if(!pt.isNarrationJSON(e.narration))return void console.error("Invalid narration data");{const t=pt.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");a=t}}return Tt.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=Et.safeParse(t);if(!r.success)return void console.error("Invalid WalletStatementEntryJSON:",r.error.flatten());const n=r.data,a=pt.fromJSON(n.narration);if(!a)return void console.warn("Failed to deserialize narration");const s=u.fromJSON(n.amountCredited),o=u.fromJSON(n.amountDebited),i=u.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"):Tt.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 Et.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>Tt.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 Tt.fromJSON(e)}static fromJsonArray(e){return Tt.fromJSONArray(e)}static toJsonArray(e){return Tt.toJSONArray(e)}}const Rt=D().router({getWallets:{method:"GET",path:"/",query:Pt.walletQuery,responses:{200:t.array(Dt.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(Tt.schema)}}});class Jt extends H{static create(){return new Jt}static fromFilters(e){return(new Jt).applyFilters(e)}static fromUrlParams(e){try{const t=Pt.walletQuery.parse(e);return Jt.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 Jt.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Jt.fromSearchParams(t)}static from(e){try{return null==e?new Jt:H.is(e)?new Jt(e.options):e instanceof URLSearchParams?Jt.fromSearchParams(e):this.isStringRecord(e)?Jt.fromUrlParams(e):Jt.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 jt extends q{constructor(e){super("wallet",Rt,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=u.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=u.from(e,r.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=Jt.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=Dt.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=Jt.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=Tt.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 Mt={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)},xt=D().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:re.schema}}});class Ft extends q{constructor(e){super("profile",xt,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,he as AuthDTOSchemas,_e as AuthRepository,dt as BANK_NARR_PREFIX,je as BankBeneficiaryInfo,De as BankBeneficiaryJSONSchema,q as BaseRepository,ke as Beneficiary,Pe as BeneficiaryDTOSchemas,Te as BeneficiaryError,xe as BeneficiaryInfo,Me as BeneficiaryInfoFactory,Ee as BeneficiaryInfoJSONSchema,Fe as BeneficiaryJSONSchema,Ve as BeneficiaryRepository,Ae as BeneficiaryType,de as CompanyMembership,ce as CompanyMembershipJSONSchema,it as ECOBANK_PREFIX,V as FilterOperator,ye as IdentityRepository,ut as LEGACY_BANK_NARR_PREFIX,ht as LEGACY_MOBILE_NARR_PREFIX,se as LogIn,ae as LogInJSONSchema,ne as LogInSchemas,lt as MOBILE_NARR_PREFIX,Je as MobileBeneficiaryInfo,Be as MobileBeneficiaryJSONSchema,ct as NARR_V2_PREFIX,pt as Narration,mt as NarrationJSONSchema,Y as Pagination,Q as PaginationParamsSchema,Z as PaginationSchema,ot as Payout,He as PayoutApprovalStatus,We as PayoutChannel,at as PayoutDTOSchemas,vt as PayoutInputFactory,st as PayoutJSONSchema,At as PayoutQuery,Ot as PayoutRepository,Ge as PayoutStatus,S as PermissionError,I as Permissions,re as Profile,ee as ProfileDTOSchemas,te as ProfileJSONSchema,Ft as ProfileRepository,G as QUERY_BUILDER_TYPE,H as QueryBuilder,ie as Role,oe as RoleJSONSchema,W as SortDirection,be as TeamManagementDTOSchemas,Ie as TeamMember,ve as TeamMemberJSONSchema,Se as TeamMemberRepository,le as User,ue as UserJSONSchema,$e as ValidatedBeneficiaryInputFactory,Dt as Wallet,Pt as WalletDTOSchemas,Bt as WalletJSONSchema,jt as WalletRepository,Tt as WalletStatementEntry,Et as WalletStatementEntryJSONSchema,Mt as WalletUtils,qe as contract,z as createPaginatedResponse,K as createPaginatedResponseSchema,It as createPayoutChannelCode,X as emptyPaginatedResponse,_ 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
|