@temboplus/afloat 0.2.0-beta.4 → 0.2.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("zod"),t=require("uuid"),r=require("@temboplus/frontend-core");function o(e){return e&&e.__esModule?e:{default:e}}var a=o(e);class n extends Error{statusCode;error;details;constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,this.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return n.schema.safeParse(e).success}static unknown(e){return new n({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return e.z.object({message:e.z.string(),statusCode:e.z.number().int(),error:e.z.string().optional(),details:e.z.object({}).optional()})}}const s={Profile:{ViewCurrent:"profile.getCurrent",Update:"profile.update"},Beneficiary:{View:"contact.findById",List:"contact.findAll",Create:"contact.create",Update:"contact.update",Delete:"contact.delete"},Payment:{View:"payment.findById",List:"payment.findAll",Create:"payment.create"},Payout:{View:"payout.findById",List:"payout.findAll",Create:"payout.create",Approve:"payout.approve"},Transfer:{View:"transfer.findById",List:"transfer.findAll",Create:"transfer.create",Approve:"transfer.approve"},Wallet:{ViewBalance:"wallet.getBalance",ViewStatement:"wallet.getStatement"},Role:{ViewRoles:"role.findAll",ViewRole:"role.findById"},TeamManagement:{ViewMembers:"login.findAll",ViewMember:"login.findById",CreateMember:"login.create",UpdateMember:"login.update",ArchiveMember:"login.archive",UnArchiveMember:"login.unarchive",ResetPassword:"login.resetPassword"}};class i extends Error{requiredPermissions;constructor(e){super(e.message??`Missing required permissions: ${e.requiredPermissions.join(", ")}`),this.name="PermissionError",this.requiredPermissions=e.requiredPermissions}static is(t){const r=e.z.union([e.z.enum(Object.values(s.Profile)),e.z.enum(Object.values(s.Beneficiary)),e.z.enum(Object.values(s.Payment)),e.z.enum(Object.values(s.Payout)),e.z.enum(Object.values(s.Transfer)),e.z.enum(Object.values(s.Wallet))]);return e.z.object({name:e.z.literal("PermissionError").nullish(),message:e.z.string(),requiredPermissions:e.z.array(r)}).safeParse(t).success}}const c=e=>"function"==typeof(null==e?void 0:e.passthrough);e.z.object({name:e.z.literal("ZodError"),issues:e.z.array(e.z.object({path:e.z.array(e.z.union([e.z.string(),e.z.number()])),message:e.z.string().optional(),code:e.z.nativeEnum(e.z.ZodIssueCode)}).catchall(e.z.any()))});const u=Symbol("ContractNoBody"),d=e=>"method"in e&&"path"in e,l=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var o,a,n,s,i;return d(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:(s=null==t?void 0:t.baseHeaders,i=r.headers,c(s)?c(i)?s.merge(i):s:c(i)?i:Object.assign({},s,i)),strictStatusCodes:null!==(o=r.strictStatusCodes)&&void 0!==o?o: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!==(n=r.metadata)&&void 0!==n?n:{}}:r.metadata}]:[e,l(r,t)]})),m=Symbol("ContractPlainType"),p=()=>({router:(e,t)=>l(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>m,body:()=>m,type:()=>m,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>u}),h=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("&"):"",f=e=>e?Object.keys(e).flatMap(t=>y(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",y=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>y(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>y(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class g extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const N=async({route:e,path:t,method:r,headers:o,body:a,validateResponse:n,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:o,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!=n?n: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}},b=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 o of t)r(e,o);else r(e,t)}),t},w=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),v=(e,t,r,o,a)=>{const n=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:o.path,params:r}),s=((e,t=!1)=>{const r=t?h(e):f(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,a);return`${t}${n}${s}`},S=(e,t)=>{const r=Object.keys(e.responses);return async o=>{const a=((e,t,r)=>{const{query:o,params:a,body:n,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...m}=r||{},p={...t,...c};return{path:v(o,p.baseUrl,a,e,!!p.jsonQuery),clientArgs:p,route:e,body:n,query:o,extraInputArgs:m,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...i,...s}}})(e,t,o),n=await(e=>{const{path:t,clientArgs:r,route:o,body:a,query:n,extraInputArgs:s,headers:i,fetchOptions:c}=e,u=r.api||N,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&w(d),...w(i)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let m={route:o,path:t,method:o.method,headers:l,body:void 0,rawBody:a,rawQuery:n,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"!==o.method&&("contentType"in o&&"multipart/form-data"===o.contentType?m={...m,contentType:"multipart/form-data",body:a instanceof FormData?a:b(a)}:"contentType"in o&&"application/x-www-form-urlencoded"===o.contentType?m={...m,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...m.headers},body:"string"==typeof a?a:new URLSearchParams(a)}:null!=a&&(m={...m,contentType:"application/json",headers:{"content-type":"application/json",...m.headers},body:JSON.stringify(a)})),u({...m,...s})})(a);if(!t.throwOnUnknownStatus)return n;if(r.includes(n.status.toString()))return n;throw new g(n,r)}},O=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>d(r)?[e,S(r,t)]:[e,O(r,t)]));let A;class C{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(A){const e=A();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":t.v4()}};return O(this.contract,e)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;if(400===e.status){const t=a.default.object({statusCode:a.default.number(),message:a.default.string(),error:a.default.string(),details:a.default.record(a.default.string()).optional()}).safeParse(e.body);if(t.success)throw new n(t.data);throw new n({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===e.status)throw new n({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new n({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new n({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new n({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}var P,I;exports.FilterOperator=void 0,(P=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",P.NOT_EQUALS="neq",P.LESS_THAN="lt",P.LESS_THAN_OR_EQUAL="lte",P.GREATER_THAN="gt",P.GREATER_THAN_OR_EQUAL="gte",P.LIKE="like",P.LIKE_LOWER="likeLower",P.IS_NULL="isNull",P.IS_NOT_NULL="isNotNull",P.IN="in",exports.SortDirection=void 0,(I=exports.SortDirection||(exports.SortDirection={})).ASC="asc",I.DESC="desc";const z=Symbol("query-builder-type");class _{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}}[z]="query-builder";static is(e){return null!==e&&"object"==typeof e&&z in e&&"query-builder"===e[z]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.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=exports.SortDirection.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,exports.SortDirection.ASC)}orderByDesc(e){return this.orderBy(e,exports.SortDirection.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 exports.FilterOperator.IS_NULL:e[`${t.field}:isNull`]=1;break;case exports.FilterOperator.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case exports.FilterOperator.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case exports.FilterOperator.LIKE:e[`${t.field}:like`]=t.value;break;case exports.FilterOperator.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case exports.FilterOperator.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case exports.FilterOperator.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===exports.SortDirection.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 _(e)}}const E=e.z.object({page:e.z.coerce.number().int().min(1).default(1),limit:e.z.coerce.number().int().min(1).max(100).default(10)}),x=e.z.object({page:e.z.number().int().min(1),limit:e.z.number().int().min(1),total:e.z.number().int().min(0),totalPages:e.z.number().int().min(0),hasNext:e.z.boolean(),hasPrev:e.z.boolean()});class R{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 R(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new R(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}}}const D={profileDTOSchema:e.z.object({id:e.z.string(),firstName:e.z.string().nullish(),lastName:e.z.string().nullish(),displayName:e.z.string(),phone:e.z.string().nullish(),accountNo:e.z.string().min(1),email:e.z.string().email().nullish(),autoApprove:e.z.boolean().nullish()})},T=e.z.object({id:e.z.string(),firstName:e.z.string().nullable().optional(),lastName:e.z.string().nullable().optional(),displayName:e.z.string(),phone:e.z.string().nullable().optional(),accountNo:e.z.string(),email:e.z.string().nullable().optional(),autoApprove:e.z.boolean().nullable().optional(),version:e.z.string().optional().default("1.0")});class B{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return D.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 B({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 B.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?B.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 o=t._autoApprove;return null==o||"boolean"==typeof o}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=T.safeParse(t);if(!r.success)return void console.error("Invalid ProfileJSON:",r.error.flatten());const o=r.data;return B.from(o)}catch(e){return void console.error("Error parsing ProfileJSON:",e)}}static isProfileJSON(e){return T.safeParse(e).success}}const M={loginDTO:a.default.object({id:a.default.string().min(1,"ID is required"),profileId:a.default.string().min(1,"Profile ID is required"),name:a.default.string().min(1,"Name is required"),identity:a.default.string().email("Identity must be a valid email address"),type:a.default.string().min(1,"Type is required"),roleId:a.default.string().min(1,"Role ID is required"),isActive:a.default.boolean(),isArchived:a.default.boolean(),resetPassword:a.default.boolean(),createdAt:a.default.string().datetime("Invalid creation timestamp"),updatedAt:a.default.string().datetime("Invalid update timestamp"),access:a.default.array(a.default.string())})},J=e.z.object({id:e.z.string(),profileId:e.z.string(),name:e.z.string(),identity:e.z.string(),type:e.z.string(),roleId:e.z.string(),isActive:e.z.boolean(),isArchived:e.z.boolean(),resetPassword:e.z.boolean(),createdAt:e.z.string(),updatedAt:e.z.string(),access:e.z.array(e.z.string()),version:e.z.string().optional().default("1.0")});class j{_id;_profileId;_name;_identity;_type;_roleId;_isActive;_isArchived;_resetPassword;_createdAt;_updatedAt;_access;constructor(e,t,r,o,a,n,s,i,c,u,d,l){this._id=e,this._profileId=t,this._name=r,this._identity=o,this._type=a,this._roleId=n,this._isActive=s,this._isArchived=i,this._resetPassword=c,this._createdAt=u,this._updatedAt=d,this._access=l}static from(e){const t=M.loginDTO.parse(e);return new j(t.id,t.profileId,t.name,t.identity,t.type,t.roleId,t.isActive,t.isArchived,t.resetPassword,new Date(t.createdAt),new Date(t.updatedAt),t.access)}get id(){return this._id}get profileId(){return this._profileId}get name(){return this._name}get identity(){return this._identity}get type(){return this._type}get roleId(){return this._roleId}get isActive(){return this._isActive}get isArchived(){return this._isArchived}get resetPassword(){return this._resetPassword}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get access(){return this._access}toJSON(){return{id:this._id,profileId:this._profileId,name:this._name,identity:this._identity,type:this._type,roleId:this._roleId,isActive:this._isActive,isArchived:this._isArchived,resetPassword:this._resetPassword,createdAt:this._createdAt.toISOString(),updatedAt:this._updatedAt.toISOString(),access:[...this._access],version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=J.safeParse(t);if(!r.success)return void console.error("Invalid LogInJSON:",r.error.flatten());const o=r.data;return j.from({id:o.id,profileId:o.profileId,name:o.name,identity:o.identity,type:o.type,roleId:o.roleId,isActive:o.isActive,isArchived:o.isArchived,resetPassword:o.resetPassword,createdAt:o.createdAt,updatedAt:o.updatedAt,access:o.access})}catch(e){return void console.error("Error parsing LogInJSON:",e)}}static isLogInJSON(e){return J.safeParse(e).success}}const F=a.default.object({id:a.default.string(),name:a.default.string(),description:a.default.string().optional(),access:a.default.array(a.default.string()),createdAt:a.default.string(),updatedAt:a.default.string(),version:a.default.string().optional().default("1.0")});class k{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 k(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=F.safeParse(t);if(!r.success)return void console.error("Invalid RoleJSON:",r.error.flatten());const o=r.data;return k.from({id:o.id,name:o.name,description:o.description,access:o.access,createdAt:o.createdAt,updatedAt:o.updatedAt})}catch(e){return void console.error("Error parsing RoleJSON:",e)}}static isRoleJSON(e){return F.safeParse(e).success}}const U=a.default.object({companyProfile:T,role:F.optional(),version:a.default.string().optional().default("1.0")});class ${_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return B.is(e.companyProfile)?new $(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=U.safeParse(t);if(!r.success)return void console.error("Invalid CompanyMembershipJSON:",r.error.flatten());const o=r.data,a=B.fromJSON(o.companyProfile),n=o.role?k.fromJSON(o.role):void 0;return a?$.from({companyProfile:a,role:n}):void console.error("Failed to reconstruct Profile from CompanyMembershipJSON")}catch(e){return void console.error("Error parsing CompanyMembershipJSON:",e)}}static isCompanyMembershipJSON(e){return U.safeParse(e).success}}const L=a.default.object({logIn:J,companyProfile:T,role:F.optional(),token:a.default.string().min(1),version:a.default.string().optional().default("1.0")});class q{_logIn;_membership;_token;_permissionMap;constructor(e){this._logIn=e.logIn,this._membership=e.membership,this._token=e.token,this._permissionMap={},this._logIn.access.forEach(e=>{this._permissionMap[e]=!0})}static from(e){try{if(!e.logIn||!e.companyProfile||!e.token)return void console.error("Missing required User fields");if("string"!=typeof e.token||""===e.token.trim())return void console.error("Invalid token");const t=$.from({companyProfile:e.companyProfile,role:e.role});return t?new q({logIn:e.logIn,membership:t,token:e.token}):void console.error("Failed to create CompanyMembership")}catch(e){return void console.error("Error creating User:",e)}}get logIn(){return this._logIn}get membership(){return this._membership}get token(){return this._token}get id(){return this._logIn.id}get name(){return this._logIn.name}get identity(){return this._logIn.identity}get roleId(){return this._logIn.roleId}get resetPassword(){return this._logIn.resetPassword}get profile(){return this._membership.companyProfile}get role(){return this._membership.role}get access(){return this._logIn.access}can(e){return this._permissionMap[e]??!1}canAny(e){return e.some(e=>this.can(e))}canAll(e){return e.every(e=>this.can(e))}canManageTeam(){return this.can(s.TeamManagement.ViewMembers)}canViewRoles(){return this.can(s.Role.ViewRole)}toJSON(){return{logIn:this._logIn.toJSON(),companyProfile:this._membership.companyProfile.toJSON(),role:this._membership.role?.toJSON(),token:this._token,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=L.safeParse(t);if(!r.success)return void console.error("Invalid UserJSON:",r.error.flatten());const o=r.data,a=j.fromJSON(o.logIn),n=B.fromJSON(o.companyProfile),s=o.role?k.fromJSON(o.role):void 0;if(!a||!n)return void console.error("Failed to reconstruct nested objects from UserJSON");if(!o.token||""===o.token.trim())return void console.error("Invalid token in UserJSON");const i=$.from({companyProfile:n,role:s});return i?new q({logIn:a,membership:i,token:o.token}):void console.error("Failed to create CompanyMembership from UserJSON")}catch(e){return void console.error("Error parsing UserJSON:",e)}}static isUserJSON(e){return L.safeParse(e).success}}const V=p().router({logIn:{method:"POST",path:"/login",body:e.z.object({type:e.z.string().default("password"),identity:e.z.string().email(),password:e.z.string()}),responses:{201:e.z.object({profile:D.profileDTOSchema,token:e.z.string(),access:e.z.array(e.z.string()),resetPassword:e.z.boolean()}),400:e.z.object({})}},access:{method:"GET",path:"/access",responses:{200:e.z.string().array()}},resetPassword:{method:"PUT",path:"/password",body:e.z.object({currentPassword:e.z.string(),newPassword:e.z.string()}),responses:{}}}),W=p().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:M.loginDTO}}});class G extends C{constructor(e){super("login",W,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 H=e.z.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"),Q=e.z.object({id:e.z.string().min(1),name:e.z.string().min(1,"Role name is required"),description:e.z.string().optional(),access:e.z.array(e.z.string()),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),K=e.z.object({id:e.z.string().min(1),name:e.z.string().min(1,"Team member name is required"),identity:e.z.string().email("Invalid email address"),type:e.z.string().min(1,"Team member type is required"),profileId:e.z.string().min(1,"Profile ID is required"),roleId:e.z.string().min(1,"Role ID is required"),resetPassword:e.z.boolean(),isActive:e.z.boolean(),isArchived:e.z.boolean(),role:Q.optional(),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),Y={role:Q,teamMember:K,teamMemberQueryParams:e.z.object({id:e.z.string().min(1).optional(),name:e.z.string().min(1).optional(),identity:e.z.string().email("Invalid email address").optional(),type:e.z.string().min(1).optional(),profileId:e.z.string().min(1).optional(),roleId:e.z.string().min(1).optional(),resetPassword:e.z.number().optional(),isActive:e.z.number().optional(),isArchived:e.z.number().optional(),createdAt:e.z.string().datetime("Invalid creation timestamp").optional(),updatedAt:e.z.string().datetime("Invalid update timestamp").optional(),eager:e.z.string().optional()}),createTeamMemberRequest:e.z.object({name:e.z.string().min(1,"Team member name is required"),identity:e.z.string().email("Valid email address is required"),password:H.optional(),roleId:e.z.string().optional(),resetPassword:e.z.boolean().optional()}),updateTeamMemberRequest:e.z.object({name:e.z.string().min(1,"Team member name cannot be empty").optional(),roleId:e.z.string().min(1,"Role ID cannot be empty").optional(),password:H.optional(),resetPassword:e.z.boolean().optional(),isActive:e.z.boolean().optional()}),resetPasswordRequest:e.z.object({newPassword:H.optional(),sendNotification:e.z.boolean().optional()}),createTeamMemberResponse:e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string(),type:e.z.string(),profileId:e.z.string(),resetPassword:e.z.boolean(),roleId:e.z.string(),isActive:e.z.boolean(),isArchived:e.z.boolean(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime()}),password:H},Z=p().router({getTeamMembers:{method:"GET",path:"/login",query:Y.teamMemberQueryParams,responses:{200:e.z.array(Y.teamMember),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.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:e.z.object({id:e.z.string()}),query:Y.teamMemberQueryParams,responses:{200:Y.teamMember,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Get team member details",description:"Retrieve detailed information about a specific team member"},createTeamMember:{method:"POST",path:"/login",body:Y.createTeamMemberRequest,responses:{201:Y.createTeamMemberResponse,400:e.z.object({message:e.z.string().optional(),errors:e.z.array(e.z.string()).optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),409:e.z.object({message:e.z.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:e.z.object({id:e.z.string()}),body:Y.updateTeamMemberRequest,responses:{200:Y.teamMember,400:e.z.object({message:e.z.string().optional(),errors:e.z.array(e.z.string()).optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.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:e.z.object({id:e.z.string()}),body:e.z.object({}),responses:{200:Y.teamMember,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Archive team member",description:"Archive (soft delete) a team member account"},unArchiveTeamMember:{method:"POST",path:"/login/:id/unarchive",pathParams:e.z.object({id:e.z.string()}),body:e.z.object({}),responses:{200:Y.teamMember,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Unarchive team member",description:"Unarchive a previously archived team member account"},resetPassword:{method:"POST",path:"/login/:id/reset-password",pathParams:e.z.object({id:e.z.string()}),body:Y.resetPasswordRequest,responses:{200:e.z.object({success:e.z.boolean()}),400:e.z.object({message:e.z.string().optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.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:e.z.array(Y.role),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List all roles",description:"Retrieve a list of all available roles in the system"},getRole:{method:"GET",path:"/role/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:Y.role,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Get role details",description:"Retrieve detailed information about a specific role"}}),X=a.default.object({id:a.default.string(),name:a.default.string(),identity:a.default.string(),type:a.default.string(),profileId:a.default.string(),roleId:a.default.string(),resetPassword:a.default.boolean(),isActive:a.default.boolean(),isArchived:a.default.boolean(),role:F.optional(),createdAt:a.default.string(),updatedAt:a.default.string(),version:a.default.string().optional().default("1.0")});class ee{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 k(e.role)}catch(e){}}static from(e){try{return e?.id&&e?.name&&e?.identity&&e?.roleId?new ee(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 ee.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>ee.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=X.safeParse(t);if(!r.success)return void console.error("Invalid TeamMemberJSON:",r.error.flatten());const o=r.data,a=o.role?{id:o.role.id,name:o.role.name,description:o.role.description,access:o.role.access,createdAt:o.role.createdAt,updatedAt:o.role.updatedAt}:void 0;return ee.from({id:o.id,name:o.name,identity:o.identity,type:o.type,profileId:o.profileId,roleId:o.roleId,resetPassword:o.resetPassword,isActive:o.isActive,isArchived:o.isArchived,role:a,createdAt:o.createdAt,updatedAt:o.updatedAt})}catch(e){return void console.error("Error parsing TeamMemberJSON:",e)}}static isTeamMemberJSON(e){return X.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>ee.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 te extends C{constructor(e){super("admin",Z,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}),o=this.handleResponse(r,200),a=ee.from(o);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),o=ee.from(r);if(!o)throw new Error("Invalid team member data received from server");return o}async unArchiveTeamMember(e){const t=await this.client.unArchiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),o=ee.from(r);if(!o)throw new Error("Invalid team member data received from server");return o}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 ee.createMany(r)}async getTeamMember(e,t={eager:"role"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),o=this.handleResponse(r,200),a=ee.from(o);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=k.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),o=k.from(r);if(!o)throw new Error("Invalid role data received from server");return o}}var re;exports.BeneficiaryType=void 0,(re=exports.BeneficiaryType||(exports.BeneficiaryType={})).Bank="Bank",re.Mobile="Mobile";const oe=e.z.nativeEnum(exports.BeneficiaryType),ae=e.z.object({displayName:e.z.string().min(1,"Display name is required"),accountNo:e.z.string().min(1,"Account number is required"),channel:e.z.string().min(1,"Channel is required"),type:oe}),ne={beneficiaryDTO:e.z.object({id:e.z.string().min(1,"Beneficiary id is required"),profileId:e.z.string(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime()}).merge(ae),beneficiaryInputDTO:ae,beneficiaryType:oe},se=e.z.object({type:e.z.literal("Mobile"),name:e.z.string().min(1),phoneNumber:e.z.string().regex(/^\+[1-9]\d{6,14}$/),mnoId:e.z.string().min(1),version:e.z.string().optional().default("1.0")}),ie=e.z.object({type:e.z.literal("Bank"),accName:e.z.string().min(1),swiftCode:e.z.string().length(8),countryCode:e.z.string().length(2),accNo:e.z.string().min(1),version:e.z.string().optional().default("1.0")}),ce=e.z.discriminatedUnion("type",[se,ie]);class ue extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="BeneficiaryInfoError"}}class de{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}toJSONString(){return JSON.stringify(this.toJSON())}get isMobile(){return this.type===exports.BeneficiaryType.Mobile}get isBank(){return this.type===exports.BeneficiaryType.Bank}get displayName(){return this.accountName}}class le extends de{name;phoneNumber;mnoId;constructor(e,t,o){if(super(exports.BeneficiaryType.Mobile,t.countryCode),this.name=e,this.phoneNumber=t,!e?.trim())throw new ue("Name is required and cannot be empty",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(!t?.validate())throw new ue("Invalid phone number",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(r.MNOUtils.requiresExplicitMNO(t.countryCode)){if(!o)throw new ue(`MNO must be explicitly provided for phone numbers in ${t.countryCode} due to Mobile Number Portability`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});if(!r.MNOUtils.isValidMNOForCountry(o,t.countryCode)){const e=r.MNOUtils.getCountryMNOs(t.countryCode).map(e=>e.id);throw new ue(`Invalid MNO ${o} for country ${t.countryCode}. Valid MNOs: ${e.join(", ")}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,mnoId:o,operation:"constructor"})}this.mnoId=o}else{const e=r.MNOUtils.getMNOByPhoneNumber(t.e164Format,t.countryCode);if(!e?.id)throw new ue(`Failed to determine MNO for phone number ${t.e164Format}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});this.mnoId=e.id}}static from(e){try{return new le(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileBeneficiaryInfo:",e)}}static fromBeneficiaryDTO(e){if("Mobile"!==e.type)return;let t=e.accountNo;t.startsWith("+")||(t=`+${t}`);const o=r.PhoneNumber.from(t);if(!o)return void console.error(`Failed to parse phone number ${t}`);const a=o.countryCode;try{let t;if(r.MNOUtils.requiresExplicitMNO(a)){if(e.channel&&"string"==typeof e.channel){if(!r.MNOUtils.isValidMNOForCountry(e.channel,a))return void console.warn(`Invalid MNO ${e.channel} for country ${a}`);t=e.channel}}else if(t=r.MNOUtils.getMNOByPhoneNumber(o.e164Format,a)?.id,!t)return void console.warn(`Failed to auto-detect MNO for phone number ${o.e164Format}`);return le.from({name:e.displayName,phoneNumber:o,mnoId:t})}catch(e){return void console.error(`Failed to create MobileBeneficiaryInfo: ${e}`)}}static fromPayoutDTO(e){try{if(!r.CountryValidation.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=r.PhoneNumber.from(e.msisdn,{defaultCountry:e.countryCode});if(!t)return void console.error(`Failed to parse phone number: ${e.msisdn}`);let o;if(r.MNOUtils.requiresExplicitMNO(t.countryCode)){if(e.channel&&"string"==typeof e.channel){if(!r.MNOUtils.isValidMNOForCountry(e.channel,t.countryCode))return void console.warn(`Invalid MNO ${e.channel} for country ${t.countryCode} in PayoutDTO`);o=e.channel}}else if(o=r.MNOUtils.getMNOByPhoneNumber(t.e164Format,t.countryCode)?.id,!o)return void console.warn(`Failed to auto-detect MNO for phone number ${t.e164Format}`);return le.from({name:e.payeeName,phoneNumber:t,mnoId:o})}catch(t){return void console.error("Failed to create MobileBeneficiaryInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.name||!t.name.trim())return!1;let o;if("string"==typeof t.phoneNumber)o=r.PhoneNumber.from(t.phoneNumber);else if("object"==typeof t.phoneNumber){const e=t.phoneNumber;r.PhoneNumber.is(e)&&(o=r.PhoneNumber.from(e.e164Format))}if(!o)return!1;const a=t.mnoId;if("string"!=typeof a)return!1;if(!r.MNOUtils.isValidMNOForCountry(a,o.countryCode))return!1;if(r.MNOUtils.requiresExplicitMNO(o.countryCode))return!0;{const e=r.MNOUtils.getMNOByPhoneNumber(o.e164Format,o.countryCode);return e?.id===a}}validate(){try{return!!this.name?.trim()&&(!!this.phoneNumber?.validate()&&(!!r.MNOUtils.isValidMNOForCountry(this.mnoId,this.countryCode)&&(!!r.MNOUtils.requiresExplicitMNO(this.countryCode)||r.MNOUtils.validateMNOForPhoneNumber(this.phoneNumber.e164Format,this.mnoId,this.countryCode))))}catch{return!1}}getValidationDetails(){const e=[];if(this.name?.trim()||e.push("Name is required"),this.phoneNumber?.validate()||e.push("Phone number is invalid"),r.MNOUtils.isValidMNOForCountry(this.mnoId,this.countryCode)||e.push(`Invalid MNO ${this.mnoId} for country ${this.countryCode}`),!r.MNOUtils.requiresExplicitMNO(this.countryCode)){const t=r.MNOUtils.getMNOByPhoneNumber(this.phoneNumber.e164Format,this.countryCode);t?.id!==this.mnoId&&e.push("MNO doesn't match auto-detected value from phone number prefix")}return{isValid:0===e.length,errors:e,warnings:[]}}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(r.PhoneNumberFormat.E164)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){const e=r.MNOUtils.getMNOById(this.mnoId,this.countryCode);return e?.mobileMoneyService??e?.displayName??this.mnoId}toJSON(){return{type:"Mobile",name:this.name,phoneNumber:this.phoneNumber.e164Format,mnoId:this.mnoId,version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,o=se.safeParse(t);if(!o.success)return void console.error("Invalid MobileBeneficiaryInfoJSON:",o.error.flatten());const a=o.data,n=r.PhoneNumber.from(a.phoneNumber);if(!n?.validate())return void console.warn("Invalid phone number in JSON");if(!r.MNOUtils.isValidMNOForCountry(a.mnoId,n.countryCode))return void console.warn("Invalid MNO for country");if(!r.MNOUtils.requiresExplicitMNO(n.countryCode)){const e=r.MNOUtils.getMNOByPhoneNumber(n.e164Format,n.countryCode);if(e?.id!==a.mnoId)return void console.warn("MNO mismatch with auto-detected value")}return le.from({name:a.name,phoneNumber:n,mnoId:a.mnoId})}catch(e){return void console.error("Error parsing MobileBeneficiaryInfoJSON:",e)}}static fromJSONString(e){return le.fromJSON(e)}static isMobileBeneficiaryInfoJSON(e){return se.safeParse(e).success}}class me extends de{accName;bank;accNo;constructor(e,t,o){if(super(exports.BeneficiaryType.Bank,t.countryCode),this.accName=e,this.bank=t,this.accNo=o,!r.BankValidation.validateAccountName(e))throw new ue("Invalid account name",{operation:"constructor",countryCode:t.countryCode});if(!r.BankValidation.validateAccountNumber(o,t.countryCode))throw new ue("Invalid account number",{operation:"constructor",countryCode:t.countryCode})}static from(e){try{return new me(e.accName,e.bank,e.accNo)}catch(e){return void console.error("Failed to create BankBeneficiaryInfo:",e)}}static fromBeneficiaryDTO(e){if("Bank"!==e.type)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank beneficiaries");const o=r.BankValidation.getCountryFromSwiftCode(t);if(o)if(r.BankValidation.validateSwiftCode(t,o))try{const a=r.Bank.from(t,o);if(!a)throw new Error(`Bank with SWIFT code ${t} not found`);return me.from({accName:e.displayName,bank:a,accNo:e.accountNo})}catch(e){return void console.error(`Failed to create BankBeneficiaryInfo: ${e}`)}else console.error(`Invalid SWIFT code ${t} for country ${o}`);else console.error(`Could not identify country from SWIFT code: ${t}`)}static fromPayoutDTO(e){try{if(!r.CountryValidation.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=e.msisdn.trim().split(":");if(2!==t.length)return void console.error("Invalid PayoutDTO format for bank - expected 'swiftcode:accountno'");const[o,a]=t;if(!r.BankValidation.validateSwiftCode(o,e.countryCode))return void console.error(`Invalid SWIFT code ${o} for country ${e.countryCode}`);const n=r.Bank.from(o,e.countryCode);return n?me.from({accName:e.payeeName,bank:n,accNo:a}):void console.error(`Bank with SWIFT code ${o} not found`)}catch(t){return void console.error("Failed to create BankBeneficiaryInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.accName)return!1;if("string"!=typeof t.accNo)return!1;if(!t.bank||!r.Bank.is(t.bank))return!1;const o=t.accName,a=t.accNo,n=t.bank;return r.BankValidation.validateAccountName(o)&&r.BankValidation.validateAccountNumber(a,n.countryCode)}validate(){try{return r.BankValidation.validateAccountName(this.accName)&&r.BankValidation.validateAccountNumber(this.accNo,this.bank.countryCode)&&r.Bank.is(this.bank)}catch{return!1}}get accountName(){return this.accName}get accountNumber(){return this.accNo}get accountNameLabel(){return"Acc. Name"}get accountNumberLabel(){return"Bank Acc. No."}get channelLabel(){return"Bank"}get channelId(){return this.bank.swiftCode}get channelName(){return this.bank.shortName}toJSON(){return{type:"Bank",accName:this.accName,swiftCode:this.bank.swiftCode,countryCode:this.bank.countryCode,accNo:this.accNo,version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,o=ie.safeParse(t);if(!o.success)return void console.error("Invalid BankBeneficiaryInfoJSON:",o.error.flatten());const a=o.data;if(!r.CountryValidation.isISO2CountryCode(a.countryCode)||!r.BankValidation.validateSwiftCode(a.swiftCode,a.countryCode))return;const n=r.Bank.from(a.swiftCode,a.countryCode);if(!n)return;if(!r.BankValidation.validateAccountName(a.accName)||!r.BankValidation.validateAccountNumber(a.accNo,a.countryCode))return;return me.from({accName:a.accName,bank:n,accNo:a.accNo})}catch(e){return void console.error("Error parsing BankBeneficiaryInfoJSON:",e)}}static fromJSONString(e){return me.fromJSON(e)}static isBankBeneficiaryInfoJSON(e){return ie.safeParse(e).success}}const pe=e.z.object({data:ne.beneficiaryDTO,version:e.z.string().optional().default("1.0")});class he{data;constructor(e){this.data=ne.beneficiaryDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get displayName(){return this.data.displayName}get type(){return this.data.type}get createdAt(){return new Date(this.data.createdAt)}get updatedAt(){return new Date(this.data.updatedAt)}get info(){return this.data.type===exports.BeneficiaryType.Mobile?le.fromBeneficiaryDTO(this.data):this.data.type===exports.BeneficiaryType.Bank?me.fromBeneficiaryDTO(this.data):void 0}get accNo(){const e=this.info;return e?e.accountNumber:this.data.accountNo}get accName(){return this.data.displayName}get accNoLabel(){const e=this.info;return e instanceof le?"Phone Number":e instanceof me?"Bank Account Number":"Account Number"}get channelLabel(){const e=this.info;return e instanceof le?"Channel":e instanceof me?"Bank":"Channel"}get accNameLabel(){const e=this.info;return e instanceof le?"Full Name":e instanceof me?"Bank Account Name":"Display Name"}get channelName(){const e=this.info;return e instanceof le||e instanceof me?e.channelName:""}static from(e){try{return new he(e)}catch(e){return void console.error("Failed to create Beneficiary:",e)}}static create(e){return new he(e)}static createMany(e){return e.map(e=>new he(e))}static createSafe(e){try{return new he(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=ne.beneficiaryDTO.safeParse(e);if(!t.success)return!1;return null!==he.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&he.canConstruct(e.data))}toJSON(){return{data:{...this.data},version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=pe.safeParse(t);if(!r.success)return void console.error("Invalid BeneficiaryJSON:",r.error.flatten());const o=r.data;return he.from(o.data)}catch(e){return void console.error("Error parsing BeneficiaryJSON:",e)}}static fromJSONString(e){return he.fromJSON(e)}static isBeneficiaryJSON(e){return pe.safeParse(e).success}}class fe{canHandle(e){return"Mobile"===e.type&&le.is(e)}createInput(e){if(le.is(e))return{type:exports.BeneficiaryType.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Beneficiary Info")}}class ye{canHandle(e){return"Bank"===e.type&&me.is(e)}createInput(e){if(me.is(e))return{type:exports.BeneficiaryType.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Bank Beneficiary Info")}}class ge{handlers=[new fe,new ye];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 Ne=p().router({createBeneficiary:{method:"POST",path:"/",body:ne.beneficiaryInputDTO,responses:{201:ne.beneficiaryDTO}},editBeneficiary:{method:"PATCH",path:"/:id",body:ne.beneficiaryInputDTO,responses:{200:ne.beneficiaryDTO}},getBeneficiaries:{method:"GET",path:"/",query:e.z.object({orderByDesc:e.z.string()}),responses:{200:e.z.array(ne.beneficiaryDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:ne.beneficiaryDTO}},deleteBeneficiary:{method:"DELETE",path:"/:id",body:e.z.object({}),responses:{200:e.z.object({})}}});var be,we,ve;exports.PayoutChannel=void 0,(be=exports.PayoutChannel||(exports.PayoutChannel={})).MOBILE="Mobile",be.BANK="Bank",exports.PayoutStatus=void 0,(we=exports.PayoutStatus||(exports.PayoutStatus={})).CREATED="CREATED",we.PENDING="PENDING",we.PAID="PAID",we.FAILED="FAILED",we.REJECTED="REJECTED",we.REVERSED="REVERSED",we.QUEUED="QUEUED",exports.PayoutApprovalStatus=void 0,(ve=exports.PayoutApprovalStatus||(exports.PayoutApprovalStatus={})).PENDING="Pending",ve.APPROVED="Approved",ve.REJECTED="Rejected";const Se=e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string()}),Oe=e.z.nativeEnum(exports.PayoutStatus),Ae=e.z.nativeEnum(exports.PayoutApprovalStatus),Ce=e.z.object({channel:e.z.string(),msisdn:e.z.string(),amount:e.z.coerce.number(),description:e.z.string(),notes:e.z.string().nullish()}),Pe=Ce.extend({payeeName:e.z.string()}),Ie=Ce.extend({id:e.z.string(),profileId:e.z.string(),payeeName:e.z.string(),countryCode:e.z.string().default("TZ").refine(e=>r.CountryValidation.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>r.CurrencyValidation.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),channel:e.z.string(),status:Oe,statusMessage:e.z.string(),partnerReference:e.z.string().nullish(),createdAt:e.z.coerce.date(),updatedAt:e.z.coerce.date(),actionedAt:e.z.coerce.date().nullish(),approvalStatus:Ae.nullish(),createdBy:Se.nullish(),actionedBy:Se.nullish()}),ze=e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(100).default(10),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().nullish(),endDate:e.z.string().datetime().nullish(),payeeName:e.z.string().nullish(),msisdn:e.z.string().nullish(),profileId:e.z.string().nullish(),id:e.z.string().nullish(),partnerReference:e.z.string().nullish(),channel:e.z.string().nullish(),currencyCode:e.z.string().nullish(),status:Oe.nullish(),approvalStatus:Ae.nullish(),minAmount:e.z.number().min(0).nullish(),maxAmount:e.z.number().min(0).nullish(),search:e.z.string().nullish()}),_e={PayoutDTO:Ie,PayoutInputDTO:Pe,PayoutStatus:Oe,PayoutApprovalStatus:Ae,PayoutAuthorizer:Se,PayoutFilters:ze,PayoutURLQueryParams:e.z.object({page:e.z.string().transform(e=>parseInt(e)||1).optional(),limit:e.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().optional(),endDate:e.z.string().optional(),payeeName:e.z.string().optional(),msisdn:e.z.string().optional(),profileId:e.z.string().optional(),id:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:e.z.string().optional(),status:e.z.string().refine(e=>Object.values(exports.PayoutStatus).includes(e)).transform(e=>e).optional(),approvalStatus:e.z.string().refine(e=>Object.values(exports.PayoutApprovalStatus).includes(e)).transform(e=>e).optional(),minAmount:e.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:e.z.string().transform(e=>parseFloat(e)).optional(),search:e.z.string().optional()})},Ee=a.default.object({id:a.default.string(),profileId:a.default.string(),payeeName:a.default.string(),channel:a.default.string(),msisdn:a.default.string(),amount:a.default.number(),currencyCode:a.default.string(),countryCode:a.default.string(),description:a.default.string(),notes:a.default.string().nullish(),status:_e.PayoutStatus,statusMessage:a.default.string(),partnerReference:a.default.string().nullish(),createdAt:a.default.string(),updatedAt:a.default.string(),actionedAt:a.default.string().nullish(),approvalStatus:_e.PayoutApprovalStatus.nullish(),createdBy:_e.PayoutAuthorizer.nullish(),actionedBy:_e.PayoutAuthorizer.nullish(),version:a.default.string().optional().default("1.0")});class xe{data;constructor(e){this.data=_e.PayoutDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get payeeName(){return this.data.payeeName}get channel(){return this.data.channel}get msisdn(){return this.data.msisdn}get amount(){return r.Amount.from(this.data.amount,this.data.currencyCode)}get description(){return this.data.description}get notes(){return this.data.notes}get status(){return"Rejected"===this.data.approvalStatus?exports.PayoutStatus.REJECTED:"Approved"===this.data.approvalStatus?"FAILED"===this.data.status?exports.PayoutStatus.FAILED:exports.PayoutStatus.PAID:"Pending"===this.data.approvalStatus?exports.PayoutStatus.PENDING:this.data.status}get statusMessage(){return this.data.statusMessage}get partnerReference(){return this.data.partnerReference}get createdAt(){return this.data.createdAt}get updatedAt(){return this.data.updatedAt}get actionedAt(){return this.data.actionedAt}get approvalStatus(){return this.data.approvalStatus}get createdBy(){return this.data.createdBy}get actionedBy(){return this.data.actionedBy}get beneficiaryInfo(){return"TZ-BANK-B2C"===this.channel?me.fromPayoutDTO(this.data):le.fromPayoutDTO(this.data)}get contactInfo(){return this.beneficiaryInfo}static create(e){return new xe(e)}static createMany(e){return e.map(e=>new xe(e))}static createSafe(e){try{return new xe(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=_e.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==xe.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&xe.canConstruct(e.data))}toJSON(){return{id:this.data.id,profileId:this.data.profileId,payeeName:this.data.payeeName,channel:this.data.channel,msisdn:this.data.msisdn,amount:this.data.amount,currencyCode:this.data.currencyCode,countryCode:this.data.countryCode,description:this.data.description,notes:this.data.notes,status:this.data.status,statusMessage:this.data.statusMessage,partnerReference:this.data.partnerReference,createdAt:this.data.createdAt.toISOString(),updatedAt:this.data.updatedAt.toISOString(),actionedAt:this.data.actionedAt?.toISOString()??null,approvalStatus:this.data.approvalStatus,createdBy:this.data.createdBy,actionedBy:this.data.actionedBy,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,o=Ee.safeParse(t);if(!o.success)return void console.error("Invalid PayoutJSON:",o.error.flatten());const a=o.data,n=a.currencyCode;if(!r.CurrencyValidation.isCurrencyCode(n))return void console.error("Invalid currency code:",n);const s=a.countryCode;if(!r.CountryValidation.isISO2CountryCode(s))return void console.error("Invalid country code:",s);const i={id:a.id,profileId:a.profileId,payeeName:a.payeeName,channel:a.channel,msisdn:a.msisdn,amount:a.amount,currencyCode:n,countryCode:s,description:a.description,notes:a.notes,status:a.status,statusMessage:a.statusMessage,partnerReference:a.partnerReference,createdAt:new Date(a.createdAt),updatedAt:new Date(a.updatedAt),actionedAt:a.actionedAt?new Date(a.actionedAt):null,approvalStatus:a.approvalStatus,createdBy:a.createdBy,actionedBy:a.actionedBy};return xe.create(i)}catch(e){return void console.error("Error parsing PayoutJSON:",e)}}static isPayoutJSON(e){return Ee.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>xe.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing Payout JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}}const Re="MOBILE TRANSFER ",De="PAYOUT",Te="PAYOUT TO BANK",Be="TO_BANK",Me="PAYOUT TO MOBILE",Je="TO_MOMO",je=a.default.object({text:a.default.string(),version:a.default.string().optional().default("2.0")});class Fe{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 le.is(e)?Fe.generateMobilePayoutNarrationV2(e):me.is(e)?Fe.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${De.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:o}=e;return`${De.toUpperCase()} ${t.swiftCode.trim()} ${o.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(Re)&&(e=e.substring(16));try{if(e.startsWith(De)){const t=e.replace(De,"").trim().split(" ");if(t.length>=3){const e=t[0],o=t[1],a=t.slice(2).map(ke).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=r.BankValidation.getCountryFromSwiftCode(e);if(t){if(r.BankValidation.validateSwiftCode(e,t)){const n=r.Bank.from(e,t);if(o&&a&&n)return new me(a,n,o)}}}}}if(e.startsWith(Be)){const t=e.split("=>")[1].trim(),o=JSON.parse(t),a=o.account_number,n=o.account_name,s=o.swift_code,i=r.BankValidation.getCountryFromSwiftCode(s);if(!i)return;if(!r.BankValidation.validateSwiftCode(s,i))return;const c=r.Bank.from(s,i);if(a&&n&&c)return new me(n,c,a)}if(e.startsWith(Te)){const t=e.replace(Te,"").trim().split(" "),o=r.BankService.getInstance().searchBanks("TZ",t[0]),a=o.length>0?o[0]:void 0,n=t[1],s=t.slice(2).map(ke).join(" ");if(s&&n&&a)return new me(s,a,n)}}catch(e){return}};getMobileBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(Re)&&(e=e.substring(16));try{if(e.startsWith(De)){const t=e.replace(De,"").trim().split(" ");if(t.length>=2){const e=t[0],o=t.slice(1).map(ke).join(" ");if(e.startsWith("+")){const t=r.PhoneNumber.from(e);if(t&&o)return new le(o,t)}}}if(e.startsWith(Je)){const t=e.split("=>")[1].trim(),o=JSON.parse(t),a=r.TZMobileNumber.from(o.phone_number);let n=o.username;void 0===n&&(n="");let s=n.split(" ");if(s=s.filter(e=>e.trim().length>0),n=s.map(ke).join(" "),a&&n)return new le(n,a)}if(e.startsWith(Me)){const t=e.replace(Me,"").trim().split(" "),o=r.TZMobileNumber.from(t[0]),a=t.slice(1).map(ke).join(" ");if(o&&a)return new le(a,o)}}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=je.safeParse(t);if(!r.success)return void console.error("Invalid NarrationJSON:",r.error.flatten());const o=r.data;return new Fe(o.text)}catch(e){return void console.error("Error parsing NarrationJSON:",e)}}static isNarrationJSON(e){return je.safeParse(e).success}toJson(){return this.toJSON()}static fromJson(e){return Fe.fromJSON(e)}}function ke(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}const Ue={SUPPORTED_COUNTRY_CODES:["TZ","KE"],ERROR_MESSAGES:{INVALID_PHONE_NUMBER:"Invalid phone number",INELIGIBLE_FOR_PAYOUT:"The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",MOBILE_NUMBER_MNO_MISMATCH:"There is a mismatch between the phone number provided and the MNO used.",UNSUPPORTED_COUNTRY_BANK:"Only Tanzanian Banks are supported for now",UNSUPPORTED_COUNTRY_MOBILE:"Only Tanzanian mobile numbers are supported for now",NO_HANDLER_FOUND:"Cannot create payout input!"}};class $e{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}}class Le{static forBank(e,t){if(!Ue.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ue.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,t,o){if(!r.PhoneNumber.is(e))throw new Error(Ue.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!Ue.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ue.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!r.PhoneNumberFactory.checkPayoutEligibility(e))throw new Error(Ue.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const a=r.MNOUtils.getMNOById(t,e.countryCode);if(!a)throw new Error(Ue.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return a.id===r.TZMNOId.VODACOM?`${o.countryCode}-${r.TZMNOId.TIGO.toString().toUpperCase()}-B2C`:`${o.countryCode}-${a.id.toString().toUpperCase()}-B2C`}}class qe{canHandle(e,t,o){return e===exports.PayoutChannel.MOBILE&&le.is(t)&&o.countryCode===t.countryCode&&o.currencyCode===r.Country.from(t.countryCode)?.currencyCode}createInput(e,t){const o=e.receiver,a=$e.processNotes(e.notes),n=o.phoneNumber;return{channel:Le.forMobile(n,o.mnoId,t),msisdn:n.getWithFormat(r.PhoneNumberFormat.INTERNATIONAL_NUMERIC),description:a??Fe.generateDefaultPayoutNarration(o),payeeName:o.name,notes:a,amount:e.amount.numericValue}}}class Ve{canHandle(e,t,o){return e===exports.PayoutChannel.BANK&&me.is(t)&&o.countryCode===t.countryCode&&o.currencyCode===r.Country.from(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,o=$e.processNotes(e.notes);return{channel:Le.forBank(r,t),msisdn:`${r.bank.swiftCode}:${r.accNo}`,description:o??Fe.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:o,amount:e.amount.numericValue}}}class We{handlers=[new qe,new Ve];getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(Ue.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const Ge={bank:Le.forBank,mobile:Le.forMobile},He=p().router({getPayouts:{method:"GET",path:"",query:e.z.object({}),responses:{200:e.z.object({results:e.z.array(_e.PayoutDTO),total:e.z.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:e.z.object({rangeStart:e.z.number(),rangeEnd:e.z.number(),eager:e.z.string(),approvalStatus:_e.PayoutApprovalStatus,orderByDesc:e.z.string()}),responses:{200:e.z.object({results:e.z.array(_e.PayoutDTO),total:e.z.number()})}},postPayout:{method:"POST",path:"",body:_e.PayoutInputDTO,responses:{201:_e.PayoutDTO,400:n.schema}},approve:{method:"POST",path:"/:id/approve",body:e.z.object({action:e.z.enum(["Approve","Reject"]),notes:e.z.string().optional()}),responses:{201:_e.PayoutDTO,404:e.z.object({}),409:e.z.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:_e.PayoutDTO,404:e.z.object({})}}});class Qe extends _{static create(){return new Qe}static fromFilters(e){return(new Qe).applyFilters(e)}static fromUrlParams(e){try{const t=_e.PayoutURLQueryParams.parse(e),r=_e.PayoutFilters.parse(t);return Qe.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return Qe.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Qe.fromSearchParams(t)}static from(e){try{return null==e?new Qe:_.is(e)?new Qe(e.options):e instanceof URLSearchParams?Qe.fromSearchParams(e):this.isStringRecord(e)?Qe.fromUrlParams(e):Qe.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a PayoutQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereStatus(e){return this.where("status",e)}whereApprovalStatus(e){return this.where("approvalStatus",e)}whereChannel(e){return this.where("channel",e)}wherePending(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.PENDING)}whereApproved(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.APPROVED)}whereRejected(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.REJECTED)}wherePaid(){return this.whereStatus(exports.PayoutStatus.PAID)}whereFailed(){return this.whereStatus(exports.PayoutStatus.FAILED)}whereAmountBetween(e,t){return e.currencyCode!==t.currencyCode||e.numericValue>t.numericValue?this:this.whereBetween("amount",e.numericValue,t.numericValue).whereCurrencyCode(e.currencyCode)}wherePayee(e){return this.whereContains("payeeName",e)}whereMsisdn(e){return this.whereContains("msisdn",e)}whereProfileId(e){return this.where("profileId",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){if((e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.status&&this.whereStatus(e.status),e.approvalStatus&&this.whereApprovalStatus(e.approvalStatus),e.channel&&this.whereChannel(e.channel),e.payeeName&&this.wherePayee(e.payeeName),e.msisdn&&this.whereMsisdn(e.msisdn),e.profileId&&this.whereProfileId(e.profileId),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.id&&this.where("id",e.id),void 0!==e.minAmount||void 0!==e.maxAmount){const t=void 0!==e.minAmount&&null!==e.minAmount,o=void 0!==e.maxAmount&&null!==e.maxAmount,{currencyCode:a}=e;if(!a||!r.CurrencyValidation.isCurrencyCode(a))return console.warn("Amount filter requires a valid currency code"),this;if(t&&o){if(e.minAmount>e.maxAmount)return console.warn(`Invalid amount range: min (${e.minAmount}) > max (${e.maxAmount})`),this;const t=r.Amount.from(e.minAmount,a),o=r.Amount.from(e.maxAmount,a);t&&o&&this.whereAmountBetween(t,o)}else t?this.whereGreaterThanOrEqual("amount",e.minAmount).whereCurrencyCode(a):o&&this.whereLessThanOrEqual("amount",e.maxAmount).whereCurrencyCode(a)}return e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,payeeName:e.payeeName,msisdn:e.msisdn,profileId:e.profileId,id:e.id,partnerReference:e.partnerReference,channel:e.channel,status:this.isValidStatus(e.status)?e.status:void 0,approvalStatus:this.isValidApprovalStatus(e.approvalStatus)?e.approvalStatus:void 0,minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withApprovalStatus(e){const t=this.clone();return e&&t.whereApprovalStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}includeDefaultRelations(){return this.with("[createdBy,actionedBy]")}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.payeeName||e.msisdn||e.profileId||e.id||e.partnerReference||e.channel||e.status||e.approvalStatus||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.status&&e.push(`Status: ${t.status}`),t.approvalStatus&&e.push(`Approval: ${t.approvalStatus}`),t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.payeeName&&e.push(`Payee: ${t.payeeName}`),t.msisdn&&e.push(`MSISDN: ${t.msisdn}`),t.profileId&&e.push(`Profile: ${t.profileId}`),t.partnerReference&&e.push(`Ref: ${t.partnerReference}`),e}build(){return super.build()}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"payeeName":case"msisdn":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}return e}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidStatus(e){return Object.values(exports.PayoutStatus).includes(e)}isValidApprovalStatus(e){return Object.values(exports.PayoutApprovalStatus).includes(e)}}const Ke=e=>e.optional().transform(e=>e??void 0),Ye={walletDTO:e.z.object({id:e.z.string().min(1,{message:"Wallet ID is required."}),profileId:e.z.string().min(1,{message:"Profile ID is required."}),accountNo:e.z.string().min(1,{message:"Account number is required."}),accountName:e.z.string().min(1,{message:"Account name is required."}),channel:e.z.string().min(1,{message:"Channel is required."}),countryCode:e.z.string().default("TZ").refine(e=>r.CountryValidation.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>r.CurrencyValidation.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:e.z.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:e.z.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:e.z.object({id:e.z.string().optional(),profileId:e.z.string().optional(),accountNo:e.z.string().optional(),accountName:e.z.string().optional(),channel:e.z.string().optional(),countryCode:e.z.string().default("TZ").refine(e=>r.ISO2CountryCodesSet.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:e.z.string().default("TZS").refine(e=>{const t=r.Currency.from(e);return void 0!==t&&r.CurrencyCodesSet.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:e.z.object({accountNo:Ke(e.z.string()),debitOrCredit:e.z.string().min(1,"Transaction type is required"),tranRefNo:e.z.string().min(1,"Transaction reference is required"),narration:e.z.string().min(1,"Transaction description is required"),txnDate:e.z.coerce.date({errorMap:()=>({message:"Invalid transaction date format"})}),valueDate:e.z.coerce.date({errorMap:()=>({message:"Invalid value date format"})}),amountCredited:e.z.number().min(0,"Credited amount must be non-negative"),amountDebited:e.z.number().min(0,"Debited amount must be non-negative"),balance:e.z.number(),currencyCode:Ke(e.z.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})},Ze=a.default.object({id:a.default.string(),profileId:a.default.string(),accountNo:a.default.string(),accountName:a.default.string(),channel:a.default.string(),countryCode:a.default.string(),currencyCode:a.default.string(),createdAt:a.default.string(),updatedAt:a.default.string(),version:a.default.string().optional().default("1.0")});class Xe{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return Ye.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=Xe.schema.safeParse(e);if(t.success)return new Xe(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=Xe.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 Xe.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&&r.CountryValidation.isISO2CountryCode(t._countryCode)&&"string"==typeof t._currencyCode&&r.CurrencyValidation.isCurrencyCode(t._currencyCode)&&"string"==typeof t._createdAt&&"string"==typeof t._updatedAt}toJSON(){return{id:this._id,profileId:this._profileId,accountNo:this._accountNo,accountName:this._accountName,channel:this._channel,countryCode:this._countryCode,currencyCode:this._currencyCode,createdAt:this._createdAt,updatedAt:this._updatedAt,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Ze.safeParse(t);if(!r.success)return void console.error("Invalid WalletJSON:",r.error.flatten());const o=r.data;return Xe.create(o)}catch(e){return void console.error("Error parsing WalletJSON:",e)}}static isWalletJSON(e){return Ze.safeParse(e).success}}const et=a.default.object({accountNo:a.default.string().optional(),debitOrCredit:a.default.string(),tranRefNo:a.default.string(),narration:je,txnDate:a.default.string(),valueDate:a.default.string(),amountCredited:r.AmountJSONSchema,amountDebited:r.AmountJSONSchema,balance:r.AmountJSONSchema,currencyCode:a.default.string(),version:a.default.string().optional().default("2.0")});class tt{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return Ye.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 o=r.Currency.from(e.currencyCode);if(!o)throw new Error(`Currency not found for code: ${e.currencyCode}`);const a=r.Amount.from(e.amountCredited,o.code),n=r.Amount.from(e.amountDebited,o.code),s=r.Amount.from(e.balance,o.code);if(!a||!n||!s)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=a,this._amountDebited=n,this._balance=s}static create(e){const t="string"==typeof e.narration?new Fe(e.narration):e.narration,r={...e,narration:t.text},o=tt.schema.safeParse(r);if(o.success)try{const{narration:e,...r}=o.data;return new tt(r,t)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",o.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&&Fe.is(t._narration)&&t._txnDate instanceof Date&&t._valueDate instanceof Date&&r.Amount.is(t._amountCredited)&&r.Amount.is(t._amountDebited)&&r.Amount.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,o,a,n,s=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const n=r.Amount.fromJSON(e.amountCredited),i=r.Amount.fromJSON(e.amountDebited),c=r.Amount.fromJSON(e.balance);if(!n||!i||!c)return void console.error("Failed to deserialize Amount objects from JSON");t=n.numericValue,o=i.numericValue,a=c.numericValue,e.currencyCode||(s=n.currencyCode)}else if(t=Number(e.amountCredited),o=Number(e.amountDebited),a=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(o)||!Number.isFinite(a))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)n=e.narration;else if(Fe.is(e.narration))n=e.narration;else{if(!Fe.isNarrationJSON(e.narration))return void console.error("Invalid narration data");{const t=Fe.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");n=t}}return tt.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:n,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:o,balance:a,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,o=et.safeParse(t);if(!o.success)return void console.error("Invalid WalletStatementEntryJSON:",o.error.flatten());const a=o.data,n=Fe.fromJSON(a.narration);if(!n)return void console.warn("Failed to deserialize narration");const s=r.Amount.fromJSON(a.amountCredited),i=r.Amount.fromJSON(a.amountDebited),c=r.Amount.fromJSON(a.balance);return s&&i&&c?s.currencyCode!==a.currencyCode||i.currencyCode!==a.currencyCode||c.currencyCode!==a.currencyCode?void console.warn("Currency code mismatch"):tt.create({accountNo:a.accountNo,debitOrCredit:a.debitOrCredit,tranRefNo:a.tranRefNo,narration:n,txnDate:a.txnDate,valueDate:a.valueDate,amountCredited:s.numericValue,amountDebited:i.numericValue,balance:c.numericValue,currencyCode:a.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=p().router({getWallets:{method:"GET",path:"/",query:Ye.walletQuery,responses:{200:e.z.array(Xe.schema)}},getBalance:{method:"POST",path:"/balance",body:e.z.object({accountNo:e.z.string().optional()}),responses:{201:e.z.object({availableBalance:e.z.number()})}},getStatement:{method:"POST",path:"/statement",summary:"Get Wallet Statement",body:e.z.object({endDate:e.z.date(),startDate:e.z.date(),accountNo:e.z.string().optional()}),responses:{201:e.z.array(tt.schema)}}});class ot extends _{static create(){return new ot}static fromFilters(e){return(new ot).applyFilters(e)}static fromUrlParams(e){try{const t=Ye.walletQuery.parse(e);return ot.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 ot.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return ot.fromSearchParams(t)}static from(e){try{return null==e?new ot:_.is(e)?new ot(e.options):e instanceof URLSearchParams?ot.fromSearchParams(e):this.isStringRecord(e)?ot.fromUrlParams(e):ot.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}}const at={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)},nt=p().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:B.schema}}});exports.APIError=n,exports.AuthRepository=class extends C{constructor(e){super("auth",V,e)}async logIn(e,t){const r={type:"password",identity:e,password:t},o=await this.client.logIn({body:r});if(400===o.status)throw new n({message:"Invalid email or password",statusCode:400});if(201===o.status){const e=o.body.token,t=new G({token:e}),r=await t.getIdentity(),a=j.from(r);if(!a)throw new n({message:"Failed to construct login credentials",statusCode:502});const i=o.body.profile,c=B.from(i);if(!c)throw new n({message:"Failed to construct user profile",statusCode:502});let u;if(a.access.includes(s.Role.ViewRole))try{const t=new te({token:e});u=await t.getRole(a.roleId)}catch(e){console.warn("Failed to fetch role details:",e)}const d=q.from({logIn:a,companyProfile:c,role:u,token:e});if(!d)throw new n({message:"Failed to construct user session",statusCode:502});return d}throw new n({message:"An error occurred while trying to log in",statusCode:502})}async updatePassword(e,t){const r=await this.client.resetPassword({body:{currentPassword:e,newPassword:t}});if(200===r.status)return!0;if(400===r.status)throw new n({message:"Invalid current password",statusCode:400});throw new n({message:"An error occurred while trying to update password",statusCode:502})}async getAccessList(){const e=await this.client.access();if(200===e.status)return e.body;throw new Error(`Failed to get access list. Status: ${e.status}`)}},exports.BANK_NARR_PREFIX=Te,exports.BankBeneficiaryInfo=me,exports.BankBeneficiaryInfoJSONSchema=ie,exports.BaseRepository=C,exports.Beneficiary=he,exports.BeneficiaryDTOSchemas=ne,exports.BeneficiaryInfoJSONSchema=ce,exports.BeneficiaryJSONSchema=pe,exports.BeneficiaryRepository=class extends C{constructor(e){super("contact",Ne,e)}async create(e){const t=(new ge).resolve(e),r=await this.client.createBeneficiary({body:t}),o=this.handleResponse(r,201);return he.create(o)}async edit(e,t){const r=(new ge).resolve(t),o=await this.client.editBeneficiary({params:{id:e},body:r}),a=this.handleResponse(o,200);return he.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 he.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return he.create(r)}},exports.CompanyMembership=$,exports.CompanyMembershipJSONSchema=U,exports.ECOBANK_PREFIX=Re,exports.IdentityRepository=G,exports.LEGACY_BANK_NARR_PREFIX=Be,exports.LEGACY_MOBILE_NARR_PREFIX=Je,exports.LogIn=j,exports.LogInJSONSchema=J,exports.LogInSchemas=M,exports.MOBILE_NARR_PREFIX=Me,exports.MobileBeneficiaryInfo=le,exports.MobileBeneficiaryInfoJSONSchema=se,exports.NARR_V2_PREFIX=De,exports.Narration=Fe,exports.NarrationJSONSchema=je,exports.Pagination=R,exports.PaginationParamsSchema=E,exports.PaginationSchema=x,exports.Payout=xe,exports.PayoutDTOSchemas=_e,exports.PayoutInputFactory=We,exports.PayoutJSONSchema=Ee,exports.PayoutQuery=Qe,exports.PayoutRepository=class extends C{constructor(e){super("payout",He,e)}async getPayouts(e){try{const t=Qe.from(e),r=t.build(),o=await this.client.getPayouts({query:r}),a=this.handleResponse(o,200),n=t.toFilters(),s=new R(n.page??1,n.limit??10,a.total);return{results:xe.createMany(a.results),pagination:s}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getAllPayouts(e){try{const t=Qe.from(e).build();delete t.rangeStart,delete t.rangeEnd;const r=await this.client.getPayouts({query:t}),o=this.handleResponse(r,200);return xe.createMany(o)}catch(e){throw new Error(`Failed to fetch all payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=Qe.fromRequest(e);return this.getPayouts(t)}async pay(e){const{wallet:t,channel:o,receiver:a,amount:s,notes:i}=e,{min:c,max:u}=r.Amount.getTransactionLimits(s.currencyCode);if(s.lessThan(c)||s.greaterThan(u))throw new n({statusCode:400,message:`Please make sure the amount is between ${c.label} - ${u.label}`});const d=(new We).getPayoutInput({channel:o,receiver:a,amount:s,notes:i},t),l=await this.client.postPayout({body:d});if(201===l.status)return xe.create(l.body);if(400===l.status)throw new n(l.body);throw n.unknown()}async approve(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Approve",notes:e.notes}});if(201===t.status)return xe.create(t.body);if(404===t.status)throw new n({message:"Payout not found",statusCode:404});if(409===t.status)throw new n({message:"Payout already approved",statusCode:409});throw n.unknown()}async reject(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Reject",notes:e.notes}});if(201===t.status)return xe.create(t.body);if(404===t.status)throw new n({message:"Payout not found",statusCode:404});if(409===t.status)throw new n({message:"Payout already rejected",statusCode:409});throw n.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return xe.create(t.body);if(404===t.status)throw new n({message:"Payout not found",statusCode:404});throw n.unknown()}async count(e){const t=Qe.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}},exports.PermissionError=i,exports.Permissions=s,exports.Profile=B,exports.ProfileDTOSchemas=D,exports.ProfileJSONSchema=T,exports.ProfileRepository=class extends C{constructor(e){super("profile",nt,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=B.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}`)}},exports.QUERY_BUILDER_TYPE=z,exports.QueryBuilder=_,exports.Role=k,exports.RoleJSONSchema=F,exports.TeamManagementDTOSchemas=Y,exports.TeamMember=ee,exports.TeamMemberJSONSchema=X,exports.TeamMemberRepository=te,exports.User=q,exports.UserJSONSchema=L,exports.ValidatedBeneficiaryInputFactory=ge,exports.Wallet=Xe,exports.WalletDTOSchemas=Ye,exports.WalletJSONSchema=Ze,exports.WalletRepository=class extends C{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 o=t.body.availableBalance,a=r.Amount.from(o,e.wallet.currencyCode);if(a)return a}}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 o=t[0],a=await this.client.getBalance({body:{accountNo:e.accountNo}});if(201===a.status){const e=a.body.availableBalance,t=r.Amount.from(e,o.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=ot.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=Xe.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=ot.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),o=new Date(t.getFullYear(),t.getMonth()+1,0),a=e.range??{startDate:r,endDate:o};let n,s;if(e.wallet)n=e.wallet,s=e.wallet.accountNo;else{if(!e.accountNo)throw new Error("Either wallet or accountNo must be provided");{const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);n=t[0],s=e.accountNo}}const i={...a,accountNo:s},c=await this.client.getStatement({body:i});if(201===c.status){return c.body.map(e=>({...e,currencyCode:n.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}},exports.WalletStatementEntry=tt,exports.WalletStatementEntryJSONSchema=et,exports.WalletUtils=at,exports.contract=Ne,exports.createPaginatedResponse=function(e,t,r,o){return{results:e,pagination:new R(t,r,o)}},exports.createPaginatedResponseSchema=function(t){return e.z.object({results:e.z.array(t),pagination:x})},exports.createPayoutChannelCode=Ge,exports.emptyPaginatedResponse=function(e=1,t=10){return{results:[],pagination:new R(e,t,0)}},exports.isError=function(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message},exports.setGlobalTokenGetter=e=>{A=e};
1
+ "use strict";var e=require("zod"),t=require("uuid"),r=require("@temboplus/frontend-core");function o(e){return e&&e.__esModule?e:{default:e}}var a=o(e);class n extends Error{statusCode;error;details;constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,this.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return n.schema.safeParse(e).success}static unknown(e){return new n({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return e.z.object({message:e.z.string(),statusCode:e.z.number().int(),error:e.z.string().optional(),details:e.z.object({}).optional()})}}const s={Profile:{ViewCurrent:"profile.getCurrent",Update:"profile.update"},Beneficiary:{View:"contact.findById",List:"contact.findAll",Create:"contact.create",Update:"contact.update",Delete:"contact.delete"},Payment:{View:"payment.findById",List:"payment.findAll",Create:"payment.create"},Payout:{View:"payout.findById",List:"payout.findAll",Create:"payout.create",Approve:"payout.approve"},Transfer:{View:"transfer.findById",List:"transfer.findAll",Create:"transfer.create",Approve:"transfer.approve"},Wallet:{ViewBalance:"wallet.getBalance",ViewStatement:"wallet.getStatement"},Role:{ViewRoles:"role.findAll",ViewRole:"role.findById"},TeamManagement:{ViewMembers:"login.findAll",ViewMember:"login.findById",CreateMember:"login.create",UpdateMember:"login.update",ArchiveMember:"login.archive",UnArchiveMember:"login.unarchive",ResetPassword:"login.resetPassword"}};class i extends Error{requiredPermissions;constructor(e){super(e.message??`Missing required permissions: ${e.requiredPermissions.join(", ")}`),this.name="PermissionError",this.requiredPermissions=e.requiredPermissions}static is(t){const r=e.z.union([e.z.enum(Object.values(s.Profile)),e.z.enum(Object.values(s.Beneficiary)),e.z.enum(Object.values(s.Payment)),e.z.enum(Object.values(s.Payout)),e.z.enum(Object.values(s.Transfer)),e.z.enum(Object.values(s.Wallet))]);return e.z.object({name:e.z.literal("PermissionError").nullish(),message:e.z.string(),requiredPermissions:e.z.array(r)}).safeParse(t).success}}const c=e=>"function"==typeof(null==e?void 0:e.passthrough);e.z.object({name:e.z.literal("ZodError"),issues:e.z.array(e.z.object({path:e.z.array(e.z.union([e.z.string(),e.z.number()])),message:e.z.string().optional(),code:e.z.nativeEnum(e.z.ZodIssueCode)}).catchall(e.z.any()))});const u=Symbol("ContractNoBody"),d=e=>"method"in e&&"path"in e,l=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var o,a,n,s,i;return d(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:(s=null==t?void 0:t.baseHeaders,i=r.headers,c(s)?c(i)?s.merge(i):s:c(i)?i:Object.assign({},s,i)),strictStatusCodes:null!==(o=r.strictStatusCodes)&&void 0!==o?o: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!==(n=r.metadata)&&void 0!==n?n:{}}:r.metadata}]:[e,l(r,t)]})),m=Symbol("ContractPlainType"),p=()=>({router:(e,t)=>l(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>m,body:()=>m,type:()=>m,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>u}),h=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("&"):"",f=e=>e?Object.keys(e).flatMap(t=>y(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",y=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>y(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>y(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class g extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const N=async({route:e,path:t,method:r,headers:o,body:a,validateResponse:n,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:o,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!=n?n: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}},b=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 o of t)r(e,o);else r(e,t)}),t},v=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),w=(e,t,r,o,a)=>{const n=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:o.path,params:r}),s=((e,t=!1)=>{const r=t?h(e):f(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,a);return`${t}${n}${s}`},S=(e,t)=>{const r=Object.keys(e.responses);return async o=>{const a=((e,t,r)=>{const{query:o,params:a,body:n,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...m}=r||{},p={...t,...c};return{path:w(o,p.baseUrl,a,e,!!p.jsonQuery),clientArgs:p,route:e,body:n,query:o,extraInputArgs:m,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...i,...s}}})(e,t,o),n=await(e=>{const{path:t,clientArgs:r,route:o,body:a,query:n,extraInputArgs:s,headers:i,fetchOptions:c}=e,u=r.api||N,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&v(d),...v(i)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let m={route:o,path:t,method:o.method,headers:l,body:void 0,rawBody:a,rawQuery:n,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"!==o.method&&("contentType"in o&&"multipart/form-data"===o.contentType?m={...m,contentType:"multipart/form-data",body:a instanceof FormData?a:b(a)}:"contentType"in o&&"application/x-www-form-urlencoded"===o.contentType?m={...m,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...m.headers},body:"string"==typeof a?a:new URLSearchParams(a)}:null!=a&&(m={...m,contentType:"application/json",headers:{"content-type":"application/json",...m.headers},body:JSON.stringify(a)})),u({...m,...s})})(a);if(!t.throwOnUnknownStatus)return n;if(r.includes(n.status.toString()))return n;throw new g(n,r)}},O=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>d(r)?[e,S(r,t)]:[e,O(r,t)]));let A;class C{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(A){const e=A();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":t.v4()}};return O(this.contract,e)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;if(400===e.status){const t=a.default.object({statusCode:a.default.number(),message:a.default.string(),error:a.default.string(),details:a.default.record(a.default.string()).optional()}).safeParse(e.body);if(t.success)throw new n(t.data);throw new n({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===e.status)throw new n({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new n({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new n({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new n({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}var P,I;exports.FilterOperator=void 0,(P=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",P.NOT_EQUALS="neq",P.LESS_THAN="lt",P.LESS_THAN_OR_EQUAL="lte",P.GREATER_THAN="gt",P.GREATER_THAN_OR_EQUAL="gte",P.LIKE="like",P.LIKE_LOWER="likeLower",P.IS_NULL="isNull",P.IS_NOT_NULL="isNotNull",P.IN="in",exports.SortDirection=void 0,(I=exports.SortDirection||(exports.SortDirection={})).ASC="asc",I.DESC="desc";const z=Symbol("query-builder-type");class _{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}}[z]="query-builder";static is(e){return null!==e&&"object"==typeof e&&z in e&&"query-builder"===e[z]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.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=exports.SortDirection.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,exports.SortDirection.ASC)}orderByDesc(e){return this.orderBy(e,exports.SortDirection.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 exports.FilterOperator.IS_NULL:e[`${t.field}:isNull`]=1;break;case exports.FilterOperator.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case exports.FilterOperator.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case exports.FilterOperator.LIKE:e[`${t.field}:like`]=t.value;break;case exports.FilterOperator.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case exports.FilterOperator.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case exports.FilterOperator.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===exports.SortDirection.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 _(e)}}const E=e.z.object({page:e.z.coerce.number().int().min(1).default(1),limit:e.z.coerce.number().int().min(1).max(100).default(10)}),x=e.z.object({page:e.z.number().int().min(1),limit:e.z.number().int().min(1),total:e.z.number().int().min(0),totalPages:e.z.number().int().min(0),hasNext:e.z.boolean(),hasPrev:e.z.boolean()});class D{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 D(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new D(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}}}const R={profileDTOSchema:e.z.object({id:e.z.string(),firstName:e.z.string().nullish(),lastName:e.z.string().nullish(),displayName:e.z.string(),phone:e.z.string().nullish(),accountNo:e.z.string().min(1),email:e.z.string().email().nullish(),autoApprove:e.z.boolean().nullish()})},T=e.z.object({id:e.z.string(),firstName:e.z.string().nullable().optional(),lastName:e.z.string().nullable().optional(),displayName:e.z.string(),phone:e.z.string().nullable().optional(),accountNo:e.z.string(),email:e.z.string().nullable().optional(),autoApprove:e.z.boolean().nullable().optional(),version:e.z.string().optional().default("1.0")});class B{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return R.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 B({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 B.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?B.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 o=t._autoApprove;return null==o||"boolean"==typeof o}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=T.safeParse(t);if(!r.success)return void console.error("Invalid ProfileJSON:",r.error.flatten());const o=r.data;return B.from(o)}catch(e){return void console.error("Error parsing ProfileJSON:",e)}}static isProfileJSON(e){return T.safeParse(e).success}}const M={loginDTO:a.default.object({id:a.default.string().min(1,"ID is required"),profileId:a.default.string().min(1,"Profile ID is required"),name:a.default.string().min(1,"Name is required"),identity:a.default.string().email("Identity must be a valid email address"),type:a.default.string().min(1,"Type is required"),roleId:a.default.string().min(1,"Role ID is required"),isActive:a.default.boolean(),isArchived:a.default.boolean(),resetPassword:a.default.boolean(),createdAt:a.default.string().datetime("Invalid creation timestamp"),updatedAt:a.default.string().datetime("Invalid update timestamp"),access:a.default.array(a.default.string())})},J=e.z.object({id:e.z.string(),profileId:e.z.string(),name:e.z.string(),identity:e.z.string(),type:e.z.string(),roleId:e.z.string(),isActive:e.z.boolean(),isArchived:e.z.boolean(),resetPassword:e.z.boolean(),createdAt:e.z.string(),updatedAt:e.z.string(),access:e.z.array(e.z.string()),version:e.z.string().optional().default("1.0")});class j{_id;_profileId;_name;_identity;_type;_roleId;_isActive;_isArchived;_resetPassword;_createdAt;_updatedAt;_access;constructor(e,t,r,o,a,n,s,i,c,u,d,l){this._id=e,this._profileId=t,this._name=r,this._identity=o,this._type=a,this._roleId=n,this._isActive=s,this._isArchived=i,this._resetPassword=c,this._createdAt=u,this._updatedAt=d,this._access=l}static from(e){const t=M.loginDTO.parse(e);return new j(t.id,t.profileId,t.name,t.identity,t.type,t.roleId,t.isActive,t.isArchived,t.resetPassword,new Date(t.createdAt),new Date(t.updatedAt),t.access)}get id(){return this._id}get profileId(){return this._profileId}get name(){return this._name}get identity(){return this._identity}get type(){return this._type}get roleId(){return this._roleId}get isActive(){return this._isActive}get isArchived(){return this._isArchived}get resetPassword(){return this._resetPassword}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get access(){return this._access}toJSON(){return{id:this._id,profileId:this._profileId,name:this._name,identity:this._identity,type:this._type,roleId:this._roleId,isActive:this._isActive,isArchived:this._isArchived,resetPassword:this._resetPassword,createdAt:this._createdAt.toISOString(),updatedAt:this._updatedAt.toISOString(),access:[...this._access],version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=J.safeParse(t);if(!r.success)return void console.error("Invalid LogInJSON:",r.error.flatten());const o=r.data;return j.from({id:o.id,profileId:o.profileId,name:o.name,identity:o.identity,type:o.type,roleId:o.roleId,isActive:o.isActive,isArchived:o.isArchived,resetPassword:o.resetPassword,createdAt:o.createdAt,updatedAt:o.updatedAt,access:o.access})}catch(e){return void console.error("Error parsing LogInJSON:",e)}}static isLogInJSON(e){return J.safeParse(e).success}}const F=a.default.object({id:a.default.string(),name:a.default.string(),description:a.default.string().optional(),access:a.default.array(a.default.string()),createdAt:a.default.string(),updatedAt:a.default.string(),version:a.default.string().optional().default("1.0")});class k{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 k(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=F.safeParse(t);if(!r.success)return void console.error("Invalid RoleJSON:",r.error.flatten());const o=r.data;return k.from({id:o.id,name:o.name,description:o.description,access:o.access,createdAt:o.createdAt,updatedAt:o.updatedAt})}catch(e){return void console.error("Error parsing RoleJSON:",e)}}static isRoleJSON(e){return F.safeParse(e).success}}const U=a.default.object({companyProfile:T,role:F.optional(),version:a.default.string().optional().default("1.0")});class ${_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return B.is(e.companyProfile)?new $(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=U.safeParse(t);if(!r.success)return void console.error("Invalid CompanyMembershipJSON:",r.error.flatten());const o=r.data,a=B.fromJSON(o.companyProfile),n=o.role?k.fromJSON(o.role):void 0;return a?$.from({companyProfile:a,role:n}):void console.error("Failed to reconstruct Profile from CompanyMembershipJSON")}catch(e){return void console.error("Error parsing CompanyMembershipJSON:",e)}}static isCompanyMembershipJSON(e){return U.safeParse(e).success}}const L=a.default.object({logIn:J,companyProfile:T,role:F.optional(),token:a.default.string().min(1),version:a.default.string().optional().default("1.0")});class q{_logIn;_membership;_token;_permissionMap;constructor(e){this._logIn=e.logIn,this._membership=e.membership,this._token=e.token,this._permissionMap={},this._logIn.access.forEach(e=>{this._permissionMap[e]=!0})}static from(e){try{if(!e.logIn||!e.companyProfile||!e.token)return void console.error("Missing required User fields");if("string"!=typeof e.token||""===e.token.trim())return void console.error("Invalid token");const t=$.from({companyProfile:e.companyProfile,role:e.role});return t?new q({logIn:e.logIn,membership:t,token:e.token}):void console.error("Failed to create CompanyMembership")}catch(e){return void console.error("Error creating User:",e)}}get logIn(){return this._logIn}get membership(){return this._membership}get token(){return this._token}get id(){return this._logIn.id}get name(){return this._logIn.name}get identity(){return this._logIn.identity}get roleId(){return this._logIn.roleId}get resetPassword(){return this._logIn.resetPassword}get profile(){return this._membership.companyProfile}get role(){return this._membership.role}get access(){return this._logIn.access}can(e){return this._permissionMap[e]??!1}canAny(e){return e.some(e=>this.can(e))}canAll(e){return e.every(e=>this.can(e))}canManageTeam(){return this.can(s.TeamManagement.ViewMembers)}canViewRoles(){return this.can(s.Role.ViewRole)}toJSON(){return{logIn:this._logIn.toJSON(),companyProfile:this._membership.companyProfile.toJSON(),role:this._membership.role?.toJSON(),token:this._token,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=L.safeParse(t);if(!r.success)return void console.error("Invalid UserJSON:",r.error.flatten());const o=r.data,a=j.fromJSON(o.logIn),n=B.fromJSON(o.companyProfile),s=o.role?k.fromJSON(o.role):void 0;if(!a||!n)return void console.error("Failed to reconstruct nested objects from UserJSON");if(!o.token||""===o.token.trim())return void console.error("Invalid token in UserJSON");const i=$.from({companyProfile:n,role:s});return i?new q({logIn:a,membership:i,token:o.token}):void console.error("Failed to create CompanyMembership from UserJSON")}catch(e){return void console.error("Error parsing UserJSON:",e)}}static isUserJSON(e){return L.safeParse(e).success}}const V=p().router({logIn:{method:"POST",path:"/login",body:e.z.object({type:e.z.string().default("password"),identity:e.z.string().email(),password:e.z.string()}),responses:{201:e.z.object({profile:R.profileDTOSchema,token:e.z.string(),access:e.z.array(e.z.string()),resetPassword:e.z.boolean()}),400:e.z.object({})}},access:{method:"GET",path:"/access",responses:{200:e.z.string().array()}},resetPassword:{method:"PUT",path:"/password",body:e.z.object({currentPassword:e.z.string(),newPassword:e.z.string()}),responses:{}}}),W=p().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:M.loginDTO}}});class G extends C{constructor(e){super("login",W,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 H=e.z.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"),Q=e.z.object({id:e.z.string().min(1),name:e.z.string().min(1,"Role name is required"),description:e.z.string().optional(),access:e.z.array(e.z.string()),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),K=e.z.object({id:e.z.string().min(1),name:e.z.string().min(1,"Team member name is required"),identity:e.z.string().email("Invalid email address"),type:e.z.string().min(1,"Team member type is required"),profileId:e.z.string().min(1,"Profile ID is required"),roleId:e.z.string().min(1,"Role ID is required"),resetPassword:e.z.boolean(),isActive:e.z.boolean(),isArchived:e.z.boolean(),role:Q.optional(),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),Y={role:Q,teamMember:K,teamMemberQueryParams:e.z.object({id:e.z.string().min(1).optional(),name:e.z.string().min(1).optional(),identity:e.z.string().email("Invalid email address").optional(),type:e.z.string().min(1).optional(),profileId:e.z.string().min(1).optional(),roleId:e.z.string().min(1).optional(),resetPassword:e.z.number().optional(),isActive:e.z.number().optional(),isArchived:e.z.number().optional(),createdAt:e.z.string().datetime("Invalid creation timestamp").optional(),updatedAt:e.z.string().datetime("Invalid update timestamp").optional(),eager:e.z.string().optional()}),createTeamMemberRequest:e.z.object({name:e.z.string().min(1,"Team member name is required"),identity:e.z.string().email("Valid email address is required"),password:H.optional(),roleId:e.z.string().optional(),resetPassword:e.z.boolean().optional()}),updateTeamMemberRequest:e.z.object({name:e.z.string().min(1,"Team member name cannot be empty").optional(),roleId:e.z.string().min(1,"Role ID cannot be empty").optional(),password:H.optional(),resetPassword:e.z.boolean().optional(),isActive:e.z.boolean().optional()}),resetPasswordRequest:e.z.object({newPassword:H.optional(),sendNotification:e.z.boolean().optional()}),createTeamMemberResponse:e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string(),type:e.z.string(),profileId:e.z.string(),resetPassword:e.z.boolean(),roleId:e.z.string(),isActive:e.z.boolean(),isArchived:e.z.boolean(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime()}),password:H},Z=p().router({getTeamMembers:{method:"GET",path:"/login",query:Y.teamMemberQueryParams,responses:{200:e.z.array(Y.teamMember),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.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:e.z.object({id:e.z.string()}),query:Y.teamMemberQueryParams,responses:{200:Y.teamMember,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Get team member details",description:"Retrieve detailed information about a specific team member"},createTeamMember:{method:"POST",path:"/login",body:Y.createTeamMemberRequest,responses:{201:Y.createTeamMemberResponse,400:e.z.object({message:e.z.string().optional(),errors:e.z.array(e.z.string()).optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),409:e.z.object({message:e.z.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:e.z.object({id:e.z.string()}),body:Y.updateTeamMemberRequest,responses:{200:Y.teamMember,400:e.z.object({message:e.z.string().optional(),errors:e.z.array(e.z.string()).optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.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:e.z.object({id:e.z.string()}),body:e.z.object({}),responses:{200:Y.teamMember,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Archive team member",description:"Archive (soft delete) a team member account"},unArchiveTeamMember:{method:"POST",path:"/login/:id/unarchive",pathParams:e.z.object({id:e.z.string()}),body:e.z.object({}),responses:{200:Y.teamMember,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Unarchive team member",description:"Unarchive a previously archived team member account"},resetPassword:{method:"POST",path:"/login/:id/reset-password",pathParams:e.z.object({id:e.z.string()}),body:Y.resetPasswordRequest,responses:{200:e.z.object({success:e.z.boolean()}),400:e.z.object({message:e.z.string().optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.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:e.z.array(Y.role),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List all roles",description:"Retrieve a list of all available roles in the system"},getRole:{method:"GET",path:"/role/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:Y.role,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Get role details",description:"Retrieve detailed information about a specific role"}}),X=a.default.object({id:a.default.string(),name:a.default.string(),identity:a.default.string(),type:a.default.string(),profileId:a.default.string(),roleId:a.default.string(),resetPassword:a.default.boolean(),isActive:a.default.boolean(),isArchived:a.default.boolean(),role:F.optional(),createdAt:a.default.string(),updatedAt:a.default.string(),version:a.default.string().optional().default("1.0")});class ee{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 k(e.role)}catch(e){}}static from(e){try{return e?.id&&e?.name&&e?.identity&&e?.roleId?new ee(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 ee.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>ee.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=X.safeParse(t);if(!r.success)return void console.error("Invalid TeamMemberJSON:",r.error.flatten());const o=r.data,a=o.role?{id:o.role.id,name:o.role.name,description:o.role.description,access:o.role.access,createdAt:o.role.createdAt,updatedAt:o.role.updatedAt}:void 0;return ee.from({id:o.id,name:o.name,identity:o.identity,type:o.type,profileId:o.profileId,roleId:o.roleId,resetPassword:o.resetPassword,isActive:o.isActive,isArchived:o.isArchived,role:a,createdAt:o.createdAt,updatedAt:o.updatedAt})}catch(e){return void console.error("Error parsing TeamMemberJSON:",e)}}static isTeamMemberJSON(e){return X.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>ee.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 te extends C{constructor(e){super("admin",Z,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}),o=this.handleResponse(r,200),a=ee.from(o);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),o=ee.from(r);if(!o)throw new Error("Invalid team member data received from server");return o}async unArchiveTeamMember(e){const t=await this.client.unArchiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),o=ee.from(r);if(!o)throw new Error("Invalid team member data received from server");return o}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 ee.createMany(r)}async getTeamMember(e,t={eager:"role"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),o=this.handleResponse(r,200),a=ee.from(o);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=k.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),o=k.from(r);if(!o)throw new Error("Invalid role data received from server");return o}}var re;exports.BeneficiaryType=void 0,(re=exports.BeneficiaryType||(exports.BeneficiaryType={})).Bank="Bank",re.Mobile="Mobile";const oe=e.z.nativeEnum(exports.BeneficiaryType),ae=e.z.object({displayName:e.z.string().min(1,"Display name is required"),accountNo:e.z.string().min(1,"Account number is required"),channel:e.z.string().min(1,"Channel is required"),type:oe}),ne={beneficiaryDTO:e.z.object({id:e.z.string().min(1,"Beneficiary id is required"),profileId:e.z.string(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime()}).merge(ae),beneficiaryInputDTO:ae,beneficiaryType:oe},se=e.z.object({type:e.z.literal("Mobile"),name:e.z.string().min(1),phoneNumber:e.z.string().regex(/^\+[1-9]\d{6,14}$/),mnoId:e.z.string().min(1),version:e.z.string().optional().default("1.0")}),ie=e.z.object({type:e.z.literal("Bank"),accName:e.z.string().min(1),swiftCode:e.z.string().length(8),countryCode:e.z.string().length(2),accNo:e.z.string().min(1),version:e.z.string().optional().default("1.0")}),ce=e.z.discriminatedUnion("type",[se,ie]);class ue extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="BeneficiaryInfoError"}}class de{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}toJSONString(){return JSON.stringify(this.toJSON())}get isMobile(){return this.type===exports.BeneficiaryType.Mobile}get isBank(){return this.type===exports.BeneficiaryType.Bank}get displayName(){return this.accountName}}class le extends de{name;phoneNumber;mnoId;constructor(e,t,o){if(super(exports.BeneficiaryType.Mobile,t.countryCode),this.name=e,this.phoneNumber=t,!e?.trim())throw new ue("Name is required and cannot be empty",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(!t?.validate())throw new ue("Invalid phone number",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(r.MNOUtils.requiresExplicitMNO(t.countryCode)){if(!o)throw new ue(`MNO must be explicitly provided for phone numbers in ${t.countryCode} due to Mobile Number Portability`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});if(!r.MNOUtils.isValidMNOForCountry(o,t.countryCode)){const e=r.MNOUtils.getCountryMNOs(t.countryCode).map(e=>e.id);throw new ue(`Invalid MNO ${o} for country ${t.countryCode}. Valid MNOs: ${e.join(", ")}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,mnoId:o,operation:"constructor"})}this.mnoId=o}else{const e=r.MNOUtils.getMNOByPhoneNumber(t.e164Format,t.countryCode);if(!e?.id)throw new ue(`Failed to determine MNO for phone number ${t.e164Format}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});this.mnoId=e.id}}static from(e){try{return new le(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileBeneficiaryInfo:",e)}}static fromBeneficiaryDTO(e){if("Mobile"!==e.type)return;let t=e.accountNo;t.startsWith("+")||(t=`+${t}`);const o=r.PhoneNumber.from(t);if(!o)return void console.error(`Failed to parse phone number ${t}`);const a=o.countryCode;try{let t;if(r.MNOUtils.requiresExplicitMNO(a)){if(e.channel&&"string"==typeof e.channel){if(!r.MNOUtils.isValidMNOForCountry(e.channel,a))return void console.warn(`Invalid MNO ${e.channel} for country ${a}`);t=e.channel}}else if(t=r.MNOUtils.getMNOByPhoneNumber(o.e164Format,a)?.id,!t)return void console.warn(`Failed to auto-detect MNO for phone number ${o.e164Format}`);return le.from({name:e.displayName,phoneNumber:o,mnoId:t})}catch(e){return void console.error(`Failed to create MobileBeneficiaryInfo: ${e}`)}}static fromPayoutDTO(e){try{if(!r.CountryValidation.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=r.PhoneNumber.from(e.msisdn,{defaultCountry:e.countryCode});if(!t)return void console.error(`Failed to parse phone number: ${e.msisdn}`);let o;if(r.MNOUtils.requiresExplicitMNO(t.countryCode)){if(e.channel&&"string"==typeof e.channel){if(!r.MNOUtils.isValidMNOForCountry(e.channel,t.countryCode))return void console.warn(`Invalid MNO ${e.channel} for country ${t.countryCode} in PayoutDTO`);o=e.channel}}else if(o=r.MNOUtils.getMNOByPhoneNumber(t.e164Format,t.countryCode)?.id,!o)return void console.warn(`Failed to auto-detect MNO for phone number ${t.e164Format}`);return le.from({name:e.payeeName,phoneNumber:t,mnoId:o})}catch(t){return void console.error("Failed to create MobileBeneficiaryInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.name||!t.name.trim())return!1;let o;if("string"==typeof t.phoneNumber)o=r.PhoneNumber.from(t.phoneNumber);else if("object"==typeof t.phoneNumber){const e=t.phoneNumber;r.PhoneNumber.is(e)&&(o=r.PhoneNumber.from(e.e164Format))}if(!o)return!1;const a=t.mnoId;if("string"!=typeof a)return!1;if(!r.MNOUtils.isValidMNOForCountry(a,o.countryCode))return!1;if(r.MNOUtils.requiresExplicitMNO(o.countryCode))return!0;{const e=r.MNOUtils.getMNOByPhoneNumber(o.e164Format,o.countryCode);return e?.id===a}}validate(){try{return!!this.name?.trim()&&(!!this.phoneNumber?.validate()&&(!!r.MNOUtils.isValidMNOForCountry(this.mnoId,this.countryCode)&&(!!r.MNOUtils.requiresExplicitMNO(this.countryCode)||r.MNOUtils.validateMNOForPhoneNumber(this.phoneNumber.e164Format,this.mnoId,this.countryCode))))}catch{return!1}}getValidationDetails(){const e=[];if(this.name?.trim()||e.push("Name is required"),this.phoneNumber?.validate()||e.push("Phone number is invalid"),r.MNOUtils.isValidMNOForCountry(this.mnoId,this.countryCode)||e.push(`Invalid MNO ${this.mnoId} for country ${this.countryCode}`),!r.MNOUtils.requiresExplicitMNO(this.countryCode)){const t=r.MNOUtils.getMNOByPhoneNumber(this.phoneNumber.e164Format,this.countryCode);t?.id!==this.mnoId&&e.push("MNO doesn't match auto-detected value from phone number prefix")}return{isValid:0===e.length,errors:e,warnings:[]}}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(r.PhoneNumberFormat.E164)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){const e=r.MNOUtils.getMNOById(this.mnoId,this.countryCode);return e?.mobileMoneyService??e?.displayName??this.mnoId}toJSON(){return{type:"Mobile",name:this.name,phoneNumber:this.phoneNumber.e164Format,mnoId:this.mnoId,version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,o=se.safeParse(t);if(!o.success)return void console.error("Invalid MobileBeneficiaryInfoJSON:",o.error.flatten());const a=o.data,n=r.PhoneNumber.from(a.phoneNumber);if(!n?.validate())return void console.warn("Invalid phone number in JSON");if(!r.MNOUtils.isValidMNOForCountry(a.mnoId,n.countryCode))return void console.warn("Invalid MNO for country");if(!r.MNOUtils.requiresExplicitMNO(n.countryCode)){const e=r.MNOUtils.getMNOByPhoneNumber(n.e164Format,n.countryCode);if(e?.id!==a.mnoId)return void console.warn("MNO mismatch with auto-detected value")}return le.from({name:a.name,phoneNumber:n,mnoId:a.mnoId})}catch(e){return void console.error("Error parsing MobileBeneficiaryInfoJSON:",e)}}static fromJSONString(e){return le.fromJSON(e)}static isMobileBeneficiaryInfoJSON(e){return se.safeParse(e).success}}class me extends de{accName;bank;accNo;constructor(e,t,o){if(super(exports.BeneficiaryType.Bank,t.countryCode),this.accName=e,this.bank=t,this.accNo=o,!r.BankValidation.validateAccountName(e))throw new ue("Invalid account name",{operation:"constructor",countryCode:t.countryCode});if(!r.BankValidation.validateAccountNumber(o,t.countryCode))throw new ue("Invalid account number",{operation:"constructor",countryCode:t.countryCode})}static from(e){try{return new me(e.accName,e.bank,e.accNo)}catch(e){return void console.error("Failed to create BankBeneficiaryInfo:",e)}}static fromBeneficiaryDTO(e){if("Bank"!==e.type)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank beneficiaries");const o=r.BankValidation.getCountryFromSwiftCode(t);if(o)if(r.BankValidation.validateSwiftCode(t,o))try{const a=r.Bank.from(t,o);if(!a)throw new Error(`Bank with SWIFT code ${t} not found`);return me.from({accName:e.displayName,bank:a,accNo:e.accountNo})}catch(e){return void console.error(`Failed to create BankBeneficiaryInfo: ${e}`)}else console.error(`Invalid SWIFT code ${t} for country ${o}`);else console.error(`Could not identify country from SWIFT code: ${t}`)}static fromPayoutDTO(e){try{if(!r.CountryValidation.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=e.msisdn.trim().split(":");if(2!==t.length)return void console.error("Invalid PayoutDTO format for bank - expected 'swiftcode:accountno'");const[o,a]=t;if(!r.BankValidation.validateSwiftCode(o,e.countryCode))return void console.error(`Invalid SWIFT code ${o} for country ${e.countryCode}`);const n=r.Bank.from(o,e.countryCode);return n?me.from({accName:e.payeeName,bank:n,accNo:a}):void console.error(`Bank with SWIFT code ${o} not found`)}catch(t){return void console.error("Failed to create BankBeneficiaryInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.accName)return!1;if("string"!=typeof t.accNo)return!1;if(!t.bank||!r.Bank.is(t.bank))return!1;const o=t.accName,a=t.accNo,n=t.bank;return r.BankValidation.validateAccountName(o)&&r.BankValidation.validateAccountNumber(a,n.countryCode)}validate(){try{return r.BankValidation.validateAccountName(this.accName)&&r.BankValidation.validateAccountNumber(this.accNo,this.bank.countryCode)&&r.Bank.is(this.bank)}catch{return!1}}get accountName(){return this.accName}get accountNumber(){return this.accNo}get accountNameLabel(){return"Acc. Name"}get accountNumberLabel(){return"Bank Acc. No."}get channelLabel(){return"Bank"}get channelId(){return this.bank.swiftCode}get channelName(){return this.bank.shortName}toJSON(){return{type:"Bank",accName:this.accName,swiftCode:this.bank.swiftCode,countryCode:this.bank.countryCode,accNo:this.accNo,version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,o=ie.safeParse(t);if(!o.success)return void console.error("Invalid BankBeneficiaryInfoJSON:",o.error.flatten());const a=o.data;if(!r.CountryValidation.isISO2CountryCode(a.countryCode)||!r.BankValidation.validateSwiftCode(a.swiftCode,a.countryCode))return;const n=r.Bank.from(a.swiftCode,a.countryCode);if(!n)return;if(!r.BankValidation.validateAccountName(a.accName)||!r.BankValidation.validateAccountNumber(a.accNo,a.countryCode))return;return me.from({accName:a.accName,bank:n,accNo:a.accNo})}catch(e){return void console.error("Error parsing BankBeneficiaryInfoJSON:",e)}}static fromJSONString(e){return me.fromJSON(e)}static isBankBeneficiaryInfoJSON(e){return ie.safeParse(e).success}}const pe=e.z.object({data:ne.beneficiaryDTO,version:e.z.string().optional().default("1.0")});class he{data;constructor(e){this.data=ne.beneficiaryDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get displayName(){return this.data.displayName}get type(){return this.data.type}get createdAt(){return new Date(this.data.createdAt)}get updatedAt(){return new Date(this.data.updatedAt)}get info(){return this.data.type===exports.BeneficiaryType.Mobile?le.fromBeneficiaryDTO(this.data):this.data.type===exports.BeneficiaryType.Bank?me.fromBeneficiaryDTO(this.data):void 0}get accNo(){const e=this.info;return e?e.accountNumber:this.data.accountNo}get accName(){return this.data.displayName}get accNoLabel(){const e=this.info;return e instanceof le?"Phone Number":e instanceof me?"Bank Account Number":"Account Number"}get channelLabel(){const e=this.info;return e instanceof le?"Channel":e instanceof me?"Bank":"Channel"}get accNameLabel(){const e=this.info;return e instanceof le?"Full Name":e instanceof me?"Bank Account Name":"Display Name"}get channelName(){const e=this.info;return e instanceof le||e instanceof me?e.channelName:""}static from(e){try{return new he(e)}catch(e){return void console.error("Failed to create Beneficiary:",e)}}static create(e){return new he(e)}static createMany(e){return e.map(e=>new he(e))}static createSafe(e){try{return new he(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=ne.beneficiaryDTO.safeParse(e);if(!t.success)return!1;return null!==he.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&he.canConstruct(e.data))}toJSON(){return{data:{...this.data},version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=pe.safeParse(t);if(!r.success)return void console.error("Invalid BeneficiaryJSON:",r.error.flatten());const o=r.data;return he.from(o.data)}catch(e){return void console.error("Error parsing BeneficiaryJSON:",e)}}static fromJSONString(e){return he.fromJSON(e)}static isBeneficiaryJSON(e){return pe.safeParse(e).success}}class fe{canHandle(e){return"Mobile"===e.type&&le.is(e)}createInput(e){if(le.is(e))return{type:exports.BeneficiaryType.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Beneficiary Info")}}class ye{canHandle(e){return"Bank"===e.type&&me.is(e)}createInput(e){if(me.is(e))return{type:exports.BeneficiaryType.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Bank Beneficiary Info")}}class ge{handlers=[new fe,new ye];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 Ne=p().router({createBeneficiary:{method:"POST",path:"/",body:ne.beneficiaryInputDTO,responses:{201:ne.beneficiaryDTO}},editBeneficiary:{method:"PATCH",path:"/:id",body:ne.beneficiaryInputDTO,responses:{200:ne.beneficiaryDTO}},getBeneficiaries:{method:"GET",path:"/",query:e.z.object({orderByDesc:e.z.string()}),responses:{200:e.z.array(ne.beneficiaryDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:ne.beneficiaryDTO}},deleteBeneficiary:{method:"DELETE",path:"/:id",body:e.z.object({}),responses:{200:e.z.object({})}}});var be,ve,we;exports.PayoutChannel=void 0,(be=exports.PayoutChannel||(exports.PayoutChannel={})).MOBILE="Mobile",be.BANK="Bank",exports.PayoutStatus=void 0,(ve=exports.PayoutStatus||(exports.PayoutStatus={})).CREATED="CREATED",ve.PENDING="PENDING",ve.PAID="PAID",ve.FAILED="FAILED",ve.REJECTED="REJECTED",ve.REVERSED="REVERSED",ve.QUEUED="QUEUED",exports.PayoutApprovalStatus=void 0,(we=exports.PayoutApprovalStatus||(exports.PayoutApprovalStatus={})).PENDING="Pending",we.APPROVED="Approved",we.REJECTED="Rejected";const Se=e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string()}),Oe=e.z.nativeEnum(exports.PayoutStatus),Ae=e.z.nativeEnum(exports.PayoutApprovalStatus),Ce=e.z.object({channel:e.z.string(),msisdn:e.z.string(),amount:e.z.coerce.number(),description:e.z.string(),notes:e.z.string().nullish()}),Pe=Ce.extend({payeeName:e.z.string()}),Ie=Ce.extend({id:e.z.string(),profileId:e.z.string(),payeeName:e.z.string(),countryCode:e.z.string().default("TZ").refine(e=>r.CountryValidation.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>r.CurrencyValidation.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),channel:e.z.string(),status:Oe,statusMessage:e.z.string(),partnerReference:e.z.string().nullish(),createdAt:e.z.coerce.date(),updatedAt:e.z.coerce.date(),actionedAt:e.z.coerce.date().nullish(),approvalStatus:Ae.nullish(),createdBy:Se.nullish(),actionedBy:Se.nullish()}),ze=e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(100).default(10),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().nullish(),endDate:e.z.string().datetime().nullish(),payeeName:e.z.string().nullish(),msisdn:e.z.string().nullish(),profileId:e.z.string().nullish(),id:e.z.string().nullish(),partnerReference:e.z.string().nullish(),channel:e.z.string().nullish(),currencyCode:e.z.string().nullish(),status:Oe.nullish(),approvalStatus:Ae.nullish(),minAmount:e.z.number().min(0).nullish(),maxAmount:e.z.number().min(0).nullish(),search:e.z.string().nullish()}),_e={PayoutDTO:Ie,PayoutInputDTO:Pe,PayoutStatus:Oe,PayoutApprovalStatus:Ae,PayoutAuthorizer:Se,PayoutFilters:ze,PayoutURLQueryParams:e.z.object({page:e.z.string().transform(e=>parseInt(e)||1).optional(),limit:e.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().optional(),endDate:e.z.string().optional(),payeeName:e.z.string().optional(),msisdn:e.z.string().optional(),profileId:e.z.string().optional(),id:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:e.z.string().optional(),status:e.z.string().refine(e=>Object.values(exports.PayoutStatus).includes(e)).transform(e=>e).optional(),approvalStatus:e.z.string().refine(e=>Object.values(exports.PayoutApprovalStatus).includes(e)).transform(e=>e).optional(),minAmount:e.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:e.z.string().transform(e=>parseFloat(e)).optional(),search:e.z.string().optional()})},Ee=a.default.object({id:a.default.string(),profileId:a.default.string(),payeeName:a.default.string(),channel:a.default.string(),msisdn:a.default.string(),amount:a.default.number(),currencyCode:a.default.string(),countryCode:a.default.string(),description:a.default.string(),notes:a.default.string().nullish(),status:_e.PayoutStatus,statusMessage:a.default.string(),partnerReference:a.default.string().nullish(),createdAt:a.default.string(),updatedAt:a.default.string(),actionedAt:a.default.string().nullish(),approvalStatus:_e.PayoutApprovalStatus.nullish(),createdBy:_e.PayoutAuthorizer.nullish(),actionedBy:_e.PayoutAuthorizer.nullish(),version:a.default.string().optional().default("1.0")});class xe{data;constructor(e){this.data=_e.PayoutDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get payeeName(){return this.data.payeeName}get channel(){return this.data.channel}get msisdn(){return this.data.msisdn}get amount(){return r.Amount.from(this.data.amount,this.data.currencyCode)}get description(){return this.data.description}get notes(){return this.data.notes}get status(){return"Rejected"===this.data.approvalStatus?exports.PayoutStatus.REJECTED:"Approved"===this.data.approvalStatus?"FAILED"===this.data.status?exports.PayoutStatus.FAILED:exports.PayoutStatus.PAID:"Pending"===this.data.approvalStatus?exports.PayoutStatus.PENDING:this.data.status}get statusMessage(){return this.data.statusMessage}get partnerReference(){return this.data.partnerReference}get createdAt(){return this.data.createdAt}get updatedAt(){return this.data.updatedAt}get actionedAt(){return this.data.actionedAt}get approvalStatus(){return this.data.approvalStatus}get createdBy(){return this.data.createdBy}get actionedBy(){return this.data.actionedBy}get beneficiaryInfo(){return"TZ-BANK-B2C"===this.channel?me.fromPayoutDTO(this.data):le.fromPayoutDTO(this.data)}get contactInfo(){return this.beneficiaryInfo}static create(e){return new xe(e)}static createMany(e){return e.map(e=>new xe(e))}static createSafe(e){try{return new xe(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=_e.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==xe.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&xe.canConstruct(e.data))}toJSON(){return{id:this.data.id,profileId:this.data.profileId,payeeName:this.data.payeeName,channel:this.data.channel,msisdn:this.data.msisdn,amount:this.data.amount,currencyCode:this.data.currencyCode,countryCode:this.data.countryCode,description:this.data.description,notes:this.data.notes,status:this.data.status,statusMessage:this.data.statusMessage,partnerReference:this.data.partnerReference,createdAt:this.data.createdAt.toISOString(),updatedAt:this.data.updatedAt.toISOString(),actionedAt:this.data.actionedAt?.toISOString()??null,approvalStatus:this.data.approvalStatus,createdBy:this.data.createdBy,actionedBy:this.data.actionedBy,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,o=Ee.safeParse(t);if(!o.success)return void console.error("Invalid PayoutJSON:",o.error.flatten());const a=o.data,n=a.currencyCode;if(!r.CurrencyValidation.isCurrencyCode(n))return void console.error("Invalid currency code:",n);const s=a.countryCode;if(!r.CountryValidation.isISO2CountryCode(s))return void console.error("Invalid country code:",s);const i={id:a.id,profileId:a.profileId,payeeName:a.payeeName,channel:a.channel,msisdn:a.msisdn,amount:a.amount,currencyCode:n,countryCode:s,description:a.description,notes:a.notes,status:a.status,statusMessage:a.statusMessage,partnerReference:a.partnerReference,createdAt:new Date(a.createdAt),updatedAt:new Date(a.updatedAt),actionedAt:a.actionedAt?new Date(a.actionedAt):null,approvalStatus:a.approvalStatus,createdBy:a.createdBy,actionedBy:a.actionedBy};return xe.create(i)}catch(e){return void console.error("Error parsing PayoutJSON:",e)}}static isPayoutJSON(e){return Ee.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>xe.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing Payout JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}}const De="MOBILE TRANSFER ",Re="PAYOUT",Te="PAYOUT TO BANK",Be="TO_BANK",Me="PAYOUT TO MOBILE",Je="TO_MOMO",je=a.default.object({text:a.default.string(),version:a.default.string().optional().default("2.0")});class Fe{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 le.is(e)?Fe.generateMobilePayoutNarrationV2(e):me.is(e)?Fe.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${Re.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:o}=e;return`${Re.toUpperCase()} ${t.swiftCode.trim()} ${o.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(De)&&(e=e.substring(16));try{if(e.startsWith(Re)){const t=e.replace(Re,"").trim().split(" ");if(t.length>=3){const e=t[0],o=t[1],a=t.slice(2).map(ke).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=r.BankValidation.getCountryFromSwiftCode(e);if(t){if(r.BankValidation.validateSwiftCode(e,t)){const n=r.Bank.from(e,t);if(o&&a&&n)return new me(a,n,o)}}}}}if(e.startsWith(Be)){const t=e.split("=>")[1].trim(),o=JSON.parse(t),a=o.account_number,n=o.account_name,s=o.swift_code,i=r.BankValidation.getCountryFromSwiftCode(s);if(!i)return;if(!r.BankValidation.validateSwiftCode(s,i))return;const c=r.Bank.from(s,i);if(a&&n&&c)return new me(n,c,a)}if(e.startsWith(Te)){const t=e.replace(Te,"").trim().split(" "),o=r.BankService.getInstance().searchBanks("TZ",t[0]),a=o.length>0?o[0]:void 0,n=t[1],s=t.slice(2).map(ke).join(" ");if(s&&n&&a)return new me(s,a,n)}}catch(e){return}};getMobileBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(De)&&(e=e.substring(16));try{if(e.startsWith(Re)){const t=e.replace(Re,"").trim().split(" ");if(t.length>=2){const e=t[0],o=t.slice(1).map(ke).join(" ");if(e.startsWith("+")){const t=r.PhoneNumber.from(e);if(t&&o)return new le(o,t)}}}if(e.startsWith(Je)){const t=e.split("=>")[1].trim(),o=JSON.parse(t),a=r.TZMobileNumber.from(o.phone_number);let n=o.username;void 0===n&&(n="");let s=n.split(" ");if(s=s.filter(e=>e.trim().length>0),n=s.map(ke).join(" "),a&&n)return new le(n,a)}if(e.startsWith(Me)){const t=e.replace(Me,"").trim().split(" "),o=r.TZMobileNumber.from(t[0]),a=t.slice(1).map(ke).join(" ");if(o&&a)return new le(a,o)}}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=je.safeParse(t);if(!r.success)return void console.error("Invalid NarrationJSON:",r.error.flatten());const o=r.data;return new Fe(o.text)}catch(e){return void console.error("Error parsing NarrationJSON:",e)}}static isNarrationJSON(e){return je.safeParse(e).success}toJson(){return this.toJSON()}static fromJson(e){return Fe.fromJSON(e)}}function ke(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}const Ue={SUPPORTED_COUNTRY_CODES:["TZ","KE"],ERROR_MESSAGES:{INVALID_PHONE_NUMBER:"Invalid phone number",INELIGIBLE_FOR_PAYOUT:"The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",MOBILE_NUMBER_MNO_MISMATCH:"There is a mismatch between the phone number provided and the MNO used.",UNSUPPORTED_COUNTRY_BANK:"Only Tanzanian Banks are supported for now",UNSUPPORTED_COUNTRY_MOBILE:"Only Tanzanian mobile numbers are supported for now",NO_HANDLER_FOUND:"Cannot create payout input!"}};class $e{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}}class Le{static forBank(e,t){if(!Ue.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ue.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,t,o){if(!r.PhoneNumber.is(e))throw new Error(Ue.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!Ue.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ue.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!r.PhoneNumberFactory.checkPayoutEligibility(e))throw new Error(Ue.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const a=r.MNOUtils.getMNOById(t,e.countryCode);if(!a)throw new Error(Ue.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return a.id===r.TZMNOId.VODACOM?`${o.countryCode}-${r.TZMNOId.TIGO.toString().toUpperCase()}-B2C`:`${o.countryCode}-${a.id.toString().toUpperCase()}-B2C`}}class qe{canHandle(e,t,o){return e===exports.PayoutChannel.MOBILE&&le.is(t)&&o.countryCode===t.countryCode&&o.currencyCode===r.Country.from(t.countryCode)?.currencyCode}createInput(e,t){const o=e.receiver,a=$e.processNotes(e.notes),n=o.phoneNumber;return{channel:Le.forMobile(n,o.mnoId,t),msisdn:n.getWithFormat(r.PhoneNumberFormat.INTERNATIONAL_NUMERIC),description:a??Fe.generateDefaultPayoutNarration(o),payeeName:o.name,notes:a,amount:e.amount.numericValue}}}class Ve{canHandle(e,t,o){return e===exports.PayoutChannel.BANK&&me.is(t)&&o.countryCode===t.countryCode&&o.currencyCode===r.Country.from(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,o=$e.processNotes(e.notes);return{channel:Le.forBank(r,t),msisdn:`${r.bank.swiftCode}:${r.accNo}`,description:o??Fe.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:o,amount:e.amount.numericValue}}}class We{handlers=[new qe,new Ve];getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(Ue.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const Ge={bank:Le.forBank,mobile:Le.forMobile},He=p().router({getPayouts:{method:"GET",path:"",query:e.z.object({}),responses:{200:e.z.object({results:e.z.array(_e.PayoutDTO),total:e.z.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:e.z.object({rangeStart:e.z.number(),rangeEnd:e.z.number(),eager:e.z.string(),approvalStatus:_e.PayoutApprovalStatus,orderByDesc:e.z.string()}),responses:{200:e.z.object({results:e.z.array(_e.PayoutDTO),total:e.z.number()})}},postPayout:{method:"POST",path:"",body:_e.PayoutInputDTO,responses:{201:_e.PayoutDTO,400:n.schema}},approve:{method:"POST",path:"/:id/approve",body:e.z.object({action:e.z.enum(["Approve","Reject"]),notes:e.z.string().optional()}),responses:{201:_e.PayoutDTO,404:e.z.object({}),409:e.z.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:_e.PayoutDTO,404:e.z.object({})}}});class Qe extends _{static create(){return new Qe}static fromFilters(e){return(new Qe).applyFilters(e)}static fromUrlParams(e){try{const t=_e.PayoutURLQueryParams.parse(e),r=_e.PayoutFilters.parse(t);return Qe.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return Qe.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Qe.fromSearchParams(t)}static from(e){try{return null==e?new Qe:_.is(e)?new Qe(e.options):e instanceof URLSearchParams?Qe.fromSearchParams(e):this.isStringRecord(e)?Qe.fromUrlParams(e):Qe.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a PayoutQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereStatus(e){return this.where("status",e)}whereApprovalStatus(e){return this.where("approvalStatus",e)}whereChannel(e){return this.where("channel",e)}wherePending(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.PENDING)}whereApproved(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.APPROVED)}whereRejected(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.REJECTED)}wherePaid(){return this.whereStatus(exports.PayoutStatus.PAID)}whereFailed(){return this.whereStatus(exports.PayoutStatus.FAILED)}whereAmountBetween(e,t){return e.currencyCode!==t.currencyCode||e.numericValue>t.numericValue?this:this.whereBetween("amount",e.numericValue,t.numericValue).whereCurrencyCode(e.currencyCode)}wherePayee(e){return this.whereContains("payeeName",e)}whereMsisdn(e){return this.whereContains("msisdn",e)}whereProfileId(e){return this.where("profileId",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){if((e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.status&&this.whereStatus(e.status),e.approvalStatus&&this.whereApprovalStatus(e.approvalStatus),e.channel&&this.whereChannel(e.channel),e.payeeName&&this.wherePayee(e.payeeName),e.msisdn&&this.whereMsisdn(e.msisdn),e.profileId&&this.whereProfileId(e.profileId),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.id&&this.where("id",e.id),void 0!==e.minAmount||void 0!==e.maxAmount){const t=void 0!==e.minAmount&&null!==e.minAmount,o=void 0!==e.maxAmount&&null!==e.maxAmount,{currencyCode:a}=e;if(!a||!r.CurrencyValidation.isCurrencyCode(a))return console.warn("Amount filter requires a valid currency code"),this;if(t&&o){if(e.minAmount>e.maxAmount)return console.warn(`Invalid amount range: min (${e.minAmount}) > max (${e.maxAmount})`),this;const t=r.Amount.from(e.minAmount,a),o=r.Amount.from(e.maxAmount,a);t&&o&&this.whereAmountBetween(t,o)}else t?this.whereGreaterThanOrEqual("amount",e.minAmount).whereCurrencyCode(a):o&&this.whereLessThanOrEqual("amount",e.maxAmount).whereCurrencyCode(a)}return e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,payeeName:e.payeeName,msisdn:e.msisdn,profileId:e.profileId,id:e.id,partnerReference:e.partnerReference,channel:e.channel,status:this.isValidStatus(e.status)?e.status:void 0,approvalStatus:this.isValidApprovalStatus(e.approvalStatus)?e.approvalStatus:void 0,minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withApprovalStatus(e){const t=this.clone();return e&&t.whereApprovalStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}includeDefaultRelations(){return this.with("[createdBy,actionedBy]")}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.payeeName||e.msisdn||e.profileId||e.id||e.partnerReference||e.channel||e.status||e.approvalStatus||e.minAmount||e.maxAmount||e.search)}describeFilters(){const e=[],t=this.toFilters();if(t.sortBy){const r="asc"===t.sortOrder?"Ascending":"Descending";e.push({label:"Sort",value:`${this.formatSortField(t.sortBy)} (${r})`})}return t.startDate&&t.endDate?e.push({label:"Date Range",value:`${t.startDate} — ${t.endDate}`}):t.startDate?e.push({label:"From",value:t.startDate}):t.endDate&&e.push({label:"Until",value:t.endDate}),t.status&&e.push({label:"Status",value:t.status}),t.approvalStatus&&e.push({label:"Approval Status",value:t.approvalStatus}),t.channel&&e.push({label:"Channel",value:t.channel}),void 0!==t.minAmount&&void 0!==t.maxAmount?e.push({label:"Amount",value:`${t.minAmount} — ${t.maxAmount}`}):void 0!==t.minAmount?e.push({label:"Minimum Amount",value:String(t.minAmount)}):void 0!==t.maxAmount&&e.push({label:"Maximum Amount",value:String(t.maxAmount)}),t.search&&e.push({label:"Search",value:`"${t.search}"`}),t.payeeName&&e.push({label:"Beneficiary Name",value:t.payeeName}),t.msisdn&&e.push({label:"MSISDN",value:t.msisdn}),t.profileId&&e.push({label:"Profile",value:t.profileId}),t.partnerReference&&e.push({label:"Reference",value:t.partnerReference}),e}describeFiltersAsText(){return this.describeFilters().map(e=>`${e.label}: ${e.value}`)}formatSortField(e){return{createdAt:"Date Created",updatedAt:"Date Updated",amount:"Amount",payeeName:"Beneficiary Name",status:"Status"}[e]??e}build(){return super.build()}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"payeeName":case"msisdn":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}return e}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidStatus(e){return Object.values(exports.PayoutStatus).includes(e)}isValidApprovalStatus(e){return Object.values(exports.PayoutApprovalStatus).includes(e)}}const Ke=e=>e.optional().transform(e=>e??void 0),Ye={walletDTO:e.z.object({id:e.z.string().min(1,{message:"Wallet ID is required."}),profileId:e.z.string().min(1,{message:"Profile ID is required."}),accountNo:e.z.string().min(1,{message:"Account number is required."}),accountName:e.z.string().min(1,{message:"Account name is required."}),channel:e.z.string().min(1,{message:"Channel is required."}),countryCode:e.z.string().default("TZ").refine(e=>r.CountryValidation.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>r.CurrencyValidation.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:e.z.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:e.z.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:e.z.object({id:e.z.string().optional(),profileId:e.z.string().optional(),accountNo:e.z.string().optional(),accountName:e.z.string().optional(),channel:e.z.string().optional(),countryCode:e.z.string().default("TZ").refine(e=>r.ISO2CountryCodesSet.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:e.z.string().default("TZS").refine(e=>{const t=r.Currency.from(e);return void 0!==t&&r.CurrencyCodesSet.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:e.z.object({accountNo:Ke(e.z.string()),debitOrCredit:e.z.string().min(1,"Transaction type is required"),tranRefNo:e.z.string().min(1,"Transaction reference is required"),narration:e.z.string().min(1,"Transaction description is required"),txnDate:e.z.coerce.date({errorMap:()=>({message:"Invalid transaction date format"})}),valueDate:e.z.coerce.date({errorMap:()=>({message:"Invalid value date format"})}),amountCredited:e.z.number().min(0,"Credited amount must be non-negative"),amountDebited:e.z.number().min(0,"Debited amount must be non-negative"),balance:e.z.number(),currencyCode:Ke(e.z.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})},Ze=a.default.object({id:a.default.string(),profileId:a.default.string(),accountNo:a.default.string(),accountName:a.default.string(),channel:a.default.string(),countryCode:a.default.string(),currencyCode:a.default.string(),createdAt:a.default.string(),updatedAt:a.default.string(),version:a.default.string().optional().default("1.0")});class Xe{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return Ye.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=Xe.schema.safeParse(e);if(t.success)return new Xe(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=Xe.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 Xe.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&&r.CountryValidation.isISO2CountryCode(t._countryCode)&&"string"==typeof t._currencyCode&&r.CurrencyValidation.isCurrencyCode(t._currencyCode)&&"string"==typeof t._createdAt&&"string"==typeof t._updatedAt}toJSON(){return{id:this._id,profileId:this._profileId,accountNo:this._accountNo,accountName:this._accountName,channel:this._channel,countryCode:this._countryCode,currencyCode:this._currencyCode,createdAt:this._createdAt,updatedAt:this._updatedAt,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Ze.safeParse(t);if(!r.success)return void console.error("Invalid WalletJSON:",r.error.flatten());const o=r.data;return Xe.create(o)}catch(e){return void console.error("Error parsing WalletJSON:",e)}}static isWalletJSON(e){return Ze.safeParse(e).success}}const et=a.default.object({accountNo:a.default.string().optional(),debitOrCredit:a.default.string(),tranRefNo:a.default.string(),narration:je,txnDate:a.default.string(),valueDate:a.default.string(),amountCredited:r.AmountJSONSchema,amountDebited:r.AmountJSONSchema,balance:r.AmountJSONSchema,currencyCode:a.default.string(),version:a.default.string().optional().default("2.0")});class tt{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return Ye.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 o=r.Currency.from(e.currencyCode);if(!o)throw new Error(`Currency not found for code: ${e.currencyCode}`);const a=r.Amount.from(e.amountCredited,o.code),n=r.Amount.from(e.amountDebited,o.code),s=r.Amount.from(e.balance,o.code);if(!a||!n||!s)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=a,this._amountDebited=n,this._balance=s}static create(e){const t="string"==typeof e.narration?new Fe(e.narration):e.narration,r={...e,narration:t.text},o=tt.schema.safeParse(r);if(o.success)try{const{narration:e,...r}=o.data;return new tt(r,t)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",o.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&&Fe.is(t._narration)&&t._txnDate instanceof Date&&t._valueDate instanceof Date&&r.Amount.is(t._amountCredited)&&r.Amount.is(t._amountDebited)&&r.Amount.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,o,a,n,s=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const n=r.Amount.fromJSON(e.amountCredited),i=r.Amount.fromJSON(e.amountDebited),c=r.Amount.fromJSON(e.balance);if(!n||!i||!c)return void console.error("Failed to deserialize Amount objects from JSON");t=n.numericValue,o=i.numericValue,a=c.numericValue,e.currencyCode||(s=n.currencyCode)}else if(t=Number(e.amountCredited),o=Number(e.amountDebited),a=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(o)||!Number.isFinite(a))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)n=e.narration;else if(Fe.is(e.narration))n=e.narration;else{if(!Fe.isNarrationJSON(e.narration))return void console.error("Invalid narration data");{const t=Fe.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");n=t}}return tt.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:n,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:o,balance:a,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,o=et.safeParse(t);if(!o.success)return void console.error("Invalid WalletStatementEntryJSON:",o.error.flatten());const a=o.data,n=Fe.fromJSON(a.narration);if(!n)return void console.warn("Failed to deserialize narration");const s=r.Amount.fromJSON(a.amountCredited),i=r.Amount.fromJSON(a.amountDebited),c=r.Amount.fromJSON(a.balance);return s&&i&&c?s.currencyCode!==a.currencyCode||i.currencyCode!==a.currencyCode||c.currencyCode!==a.currencyCode?void console.warn("Currency code mismatch"):tt.create({accountNo:a.accountNo,debitOrCredit:a.debitOrCredit,tranRefNo:a.tranRefNo,narration:n,txnDate:a.txnDate,valueDate:a.valueDate,amountCredited:s.numericValue,amountDebited:i.numericValue,balance:c.numericValue,currencyCode:a.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=p().router({getWallets:{method:"GET",path:"/",query:Ye.walletQuery,responses:{200:e.z.array(Xe.schema)}},getBalance:{method:"POST",path:"/balance",body:e.z.object({accountNo:e.z.string().optional()}),responses:{201:e.z.object({availableBalance:e.z.number()})}},getStatement:{method:"POST",path:"/statement",summary:"Get Wallet Statement",body:e.z.object({endDate:e.z.date(),startDate:e.z.date(),accountNo:e.z.string().optional()}),responses:{201:e.z.array(tt.schema)}}});class ot extends _{static create(){return new ot}static fromFilters(e){return(new ot).applyFilters(e)}static fromUrlParams(e){try{const t=Ye.walletQuery.parse(e);return ot.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 ot.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return ot.fromSearchParams(t)}static from(e){try{return null==e?new ot:_.is(e)?new ot(e.options):e instanceof URLSearchParams?ot.fromSearchParams(e):this.isStringRecord(e)?ot.fromUrlParams(e):ot.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}}const at={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)},nt=p().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:B.schema}}});exports.APIError=n,exports.AuthRepository=class extends C{constructor(e){super("auth",V,e)}async logIn(e,t){const r={type:"password",identity:e,password:t},o=await this.client.logIn({body:r});if(400===o.status)throw new n({message:"Invalid email or password",statusCode:400});if(201===o.status){const e=o.body.token,t=new G({token:e}),r=await t.getIdentity(),a=j.from(r);if(!a)throw new n({message:"Failed to construct login credentials",statusCode:502});const i=o.body.profile,c=B.from(i);if(!c)throw new n({message:"Failed to construct user profile",statusCode:502});let u;if(a.access.includes(s.Role.ViewRole))try{const t=new te({token:e});u=await t.getRole(a.roleId)}catch(e){console.warn("Failed to fetch role details:",e)}const d=q.from({logIn:a,companyProfile:c,role:u,token:e});if(!d)throw new n({message:"Failed to construct user session",statusCode:502});return d}throw new n({message:"An error occurred while trying to log in",statusCode:502})}async updatePassword(e,t){const r=await this.client.resetPassword({body:{currentPassword:e,newPassword:t}});if(200===r.status)return!0;if(400===r.status)throw new n({message:"Invalid current password",statusCode:400});throw new n({message:"An error occurred while trying to update password",statusCode:502})}async getAccessList(){const e=await this.client.access();if(200===e.status)return e.body;throw new Error(`Failed to get access list. Status: ${e.status}`)}},exports.BANK_NARR_PREFIX=Te,exports.BankBeneficiaryInfo=me,exports.BankBeneficiaryInfoJSONSchema=ie,exports.BaseRepository=C,exports.Beneficiary=he,exports.BeneficiaryDTOSchemas=ne,exports.BeneficiaryInfoJSONSchema=ce,exports.BeneficiaryJSONSchema=pe,exports.BeneficiaryRepository=class extends C{constructor(e){super("contact",Ne,e)}async create(e){const t=(new ge).resolve(e),r=await this.client.createBeneficiary({body:t}),o=this.handleResponse(r,201);return he.create(o)}async edit(e,t){const r=(new ge).resolve(t),o=await this.client.editBeneficiary({params:{id:e},body:r}),a=this.handleResponse(o,200);return he.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 he.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return he.create(r)}},exports.CompanyMembership=$,exports.CompanyMembershipJSONSchema=U,exports.ECOBANK_PREFIX=De,exports.IdentityRepository=G,exports.LEGACY_BANK_NARR_PREFIX=Be,exports.LEGACY_MOBILE_NARR_PREFIX=Je,exports.LogIn=j,exports.LogInJSONSchema=J,exports.LogInSchemas=M,exports.MOBILE_NARR_PREFIX=Me,exports.MobileBeneficiaryInfo=le,exports.MobileBeneficiaryInfoJSONSchema=se,exports.NARR_V2_PREFIX=Re,exports.Narration=Fe,exports.NarrationJSONSchema=je,exports.Pagination=D,exports.PaginationParamsSchema=E,exports.PaginationSchema=x,exports.Payout=xe,exports.PayoutDTOSchemas=_e,exports.PayoutInputFactory=We,exports.PayoutJSONSchema=Ee,exports.PayoutQuery=Qe,exports.PayoutRepository=class extends C{constructor(e){super("payout",He,e)}async getPayouts(e){try{const t=Qe.from(e),r=t.build(),o=await this.client.getPayouts({query:r}),a=this.handleResponse(o,200),n=t.toFilters(),s=new D(n.page??1,n.limit??10,a.total);return{results:xe.createMany(a.results),pagination:s}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getAllPayouts(e){try{const t=Qe.from(e).build();delete t.rangeStart,delete t.rangeEnd;const r=await this.client.getPayouts({query:t}),o=this.handleResponse(r,200);return xe.createMany(o)}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=Qe.fromRequest(e);return this.getPayouts(t)}async pay(e){const{wallet:t,channel:o,receiver:a,amount:s,notes:i}=e,{min:c,max:u}=r.Amount.getTransactionLimits(s.currencyCode);if(s.lessThan(c)||s.greaterThan(u))throw new n({statusCode:400,message:`Please make sure the amount is between ${c.label} - ${u.label}`});const d=(new We).getPayoutInput({channel:o,receiver:a,amount:s,notes:i},t),l=await this.client.postPayout({body:d});if(201===l.status)return xe.create(l.body);if(400===l.status)throw new n(l.body);throw n.unknown()}async approve(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Approve",notes:e.notes}});if(201===t.status)return xe.create(t.body);if(404===t.status)throw new n({message:"Payout not found",statusCode:404});if(409===t.status)throw new n({message:"Payout already approved",statusCode:409});throw n.unknown()}async reject(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Reject",notes:e.notes}});if(201===t.status)return xe.create(t.body);if(404===t.status)throw new n({message:"Payout not found",statusCode:404});if(409===t.status)throw new n({message:"Payout already rejected",statusCode:409});throw n.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return xe.create(t.body);if(404===t.status)throw new n({message:"Payout not found",statusCode:404});throw n.unknown()}async count(e){const t=Qe.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}},exports.PermissionError=i,exports.Permissions=s,exports.Profile=B,exports.ProfileDTOSchemas=R,exports.ProfileJSONSchema=T,exports.ProfileRepository=class extends C{constructor(e){super("profile",nt,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=B.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}`)}},exports.QUERY_BUILDER_TYPE=z,exports.QueryBuilder=_,exports.Role=k,exports.RoleJSONSchema=F,exports.TeamManagementDTOSchemas=Y,exports.TeamMember=ee,exports.TeamMemberJSONSchema=X,exports.TeamMemberRepository=te,exports.User=q,exports.UserJSONSchema=L,exports.ValidatedBeneficiaryInputFactory=ge,exports.Wallet=Xe,exports.WalletDTOSchemas=Ye,exports.WalletJSONSchema=Ze,exports.WalletRepository=class extends C{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 o=t.body.availableBalance,a=r.Amount.from(o,e.wallet.currencyCode);if(a)return a}}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 o=t[0],a=await this.client.getBalance({body:{accountNo:e.accountNo}});if(201===a.status){const e=a.body.availableBalance,t=r.Amount.from(e,o.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=ot.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=Xe.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=ot.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),o=new Date(t.getFullYear(),t.getMonth()+1,0),a=e.range??{startDate:r,endDate:o};let n,s;if(e.wallet)n=e.wallet,s=e.wallet.accountNo;else{if(!e.accountNo)throw new Error("Either wallet or accountNo must be provided");{const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);n=t[0],s=e.accountNo}}const i={...a,accountNo:s},c=await this.client.getStatement({body:i});if(201===c.status){return c.body.map(e=>({...e,currencyCode:n.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}},exports.WalletStatementEntry=tt,exports.WalletStatementEntryJSONSchema=et,exports.WalletUtils=at,exports.contract=Ne,exports.createPaginatedResponse=function(e,t,r,o){return{results:e,pagination:new D(t,r,o)}},exports.createPaginatedResponseSchema=function(t){return e.z.object({results:e.z.array(t),pagination:x})},exports.createPayoutChannelCode=Ge,exports.emptyPaginatedResponse=function(e=1,t=10){return{results:[],pagination:new D(e,t,0)}},exports.isError=function(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message},exports.setGlobalTokenGetter=e=>{A=e};
2
2
  //# sourceMappingURL=index.cjs.js.map