@temboplus/afloat 0.2.1-beta.0 → 0.2.1-beta.2
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 n(e){return e&&e.__esModule?e:{default:e}}var a=n(e);class o extends Error{statusCode;error;details;constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,this.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return o.schema.safeParse(e).success}static unknown(e){return new o({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return 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 n,a,o,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!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(a=r.validateResponseOnClient)&&void 0!==a?a:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(o=r.metadata)&&void 0!==o?o:{}}:r.metadata}]:[e,l(r,t)]})),p=Symbol("ContractPlainType"),h=()=>({router:(e,t)=>l(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>p,body:()=>p,type:()=>p,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>u}),m=e=>e?Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r;return r="string"==typeof t&&!["true","false","null"].includes(t.trim())&&isNaN(Number(t))?t:JSON.stringify(t),`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).join("&"):"",y=e=>e?Object.keys(e).flatMap(t=>f(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",f=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>f(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>f(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class 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:n,body:a,validateResponse:o,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:n,body:a}),c=i.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t={status:i.status,body:await i.json(),headers:i.headers},r=e.responses[t.status];return(null!=o?o:e.validateResponseOnClient)&&"function"==typeof(null==(u=r)?void 0:u.safeParse)?{...t,body:r.parse(t.body)}:t}var u;return(null==c?void 0:c.includes("text/"))?{status:i.status,body:await i.text(),headers:i.headers}:{status:i.status,body:await i.blob(),headers:i.headers}},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 n of t)r(e,n);else r(e,t)}),t},v=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),S=(e,t,r,n,a)=>{const o=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),s=((e,t=!1)=>{const r=t?m(e):y(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,a);return`${t}${o}${s}`},I=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const a=((e,t,r)=>{const{query:n,params:a,body:o,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...p}=r||{},h={...t,...c};return{path:S(n,h.baseUrl,a,e,!!h.jsonQuery),clientArgs:h,route:e,body:o,query:n,extraInputArgs:p,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...i,...s}}})(e,t,n),o=await(e=>{const{path:t,clientArgs:r,route:n,body:a,query:o,extraInputArgs:s,headers:i,fetchOptions:c}=e,u=r.api||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 p={route:n,path:t,method:n.method,headers:l,body:void 0,rawBody:a,rawQuery:o,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?p={...p,contentType:"multipart/form-data",body:a instanceof FormData?a:b(a)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?p={...p,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...p.headers},body:"string"==typeof a?a:new URLSearchParams(a)}:null!=a&&(p={...p,contentType:"application/json",headers:{"content-type":"application/json",...p.headers},body:JSON.stringify(a)})),u({...p,...s})})(a);if(!t.throwOnUnknownStatus)return o;if(r.includes(o.status.toString()))return o;throw new g(o,r)}},w=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>d(r)?[e,I(r,t)]:[e,w(r,t)]));let A;class _{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 w(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 o(t.data);throw new o({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===e.status)throw new o({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new o({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new o({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new o({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}var O,P;exports.FilterOperator=void 0,(O=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",O.NOT_EQUALS="neq",O.LESS_THAN="lt",O.LESS_THAN_OR_EQUAL="lte",O.GREATER_THAN="gt",O.GREATER_THAN_OR_EQUAL="gte",O.LIKE="like",O.LIKE_LOWER="likeLower",O.IS_NULL="isNull",O.IS_NOT_NULL="isNotNull",O.IN="in",exports.SortDirection=void 0,(P=exports.SortDirection||(exports.SortDirection={})).ASC="asc",P.DESC="desc";const C=Symbol("query-builder-type");class z{options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*"};constructor(e={}){this.options={filters:e.filters||[],sort:e.sort||[],includes:e.includes||[],groupBy:e.groupBy||[],join:e.join||[],page:e.page,limit:e.limit}}[C]="query-builder";static is(e){return null!==e&&"object"==typeof e&&C in e&&"query-builder"===e[C]}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 z(e)}}const B=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)}),D=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 E{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 E(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new E(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 T={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()})},x=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 R{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return T.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 R({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 R.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?R.create({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove}):void console.error("Missing required profile fields"):void console.error("Data is null or undefined")}catch(e){return void console.error("Error creating profile from object:",e)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t._id||"string"!=typeof t._displayName||"string"!=typeof t._accountNo)return!1;if(null!==t._firstName&&void 0!==t._firstName&&"string"!=typeof t._firstName)return!1;if(null!==t._lastName&&void 0!==t._lastName&&"string"!=typeof t._lastName)return!1;if(null!==t._email&&void 0!==t._email&&"string"!=typeof t._email)return!1;const r=t._phone;if(null!=r&&"string"!=typeof r)return!1;const n=t._autoApprove;return null==n||"boolean"==typeof n}toJSON(){return{id:this._id,firstName:this._firstName,lastName:this._lastName,displayName:this._displayName,phone:this._phone,accountNo:this._accountNo,email:this._email,autoApprove:this._autoApprove,_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=x.safeParse(t);if(!r.success)return void console.error("Invalid ProfileJSON:",r.error.flatten());const n=r.data;return R.from(n)}catch(e){return void console.error("Error parsing ProfileJSON:",e)}}static isProfileJSON(e){return x.safeParse(e).success}}const J={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())})},M=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;_permissionMap;constructor(e,t,r,n,a,o,s,i,c,u,d,l){this._id=e,this._profileId=t,this._name=r,this._identity=n,this._type=a,this._roleId=o,this._isActive=s,this._isArchived=i,this._resetPassword=c,this._createdAt=u,this._updatedAt=d,this._access=l,this._permissionMap={},this._access.forEach(e=>{this._permissionMap[e]=!0})}static from(e){const t=J.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}can(e){return this._permissionMap[e]??!1}canAny(e){return e.some(e=>this.can(e))}canAll(e){return e.every(e=>this.can(e))}toJSON(){return{id:this._id,profileId:this._profileId,name:this._name,identity:this._identity,type:this._type,roleId:this._roleId,isActive:this._isActive,isArchived:this._isArchived,resetPassword:this._resetPassword,createdAt:this._createdAt.toISOString(),updatedAt:this._updatedAt.toISOString(),access:[...this._access],_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=M.safeParse(t);if(!r.success)return void console.error("Invalid LogInJSON:",r.error.flatten());const n=r.data;return j.from({id:n.id,profileId:n.profileId,name:n.name,identity:n.identity,type:n.type,roleId:n.roleId,isActive:n.isActive,isArchived:n.isArchived,resetPassword:n.resetPassword,createdAt:n.createdAt,updatedAt:n.updatedAt,access:n.access})}catch(e){return void console.error("Error parsing LogInJSON:",e)}}static isLogInJSON(e){return M.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 n=r.data;return k.from({id:n.id,name:n.name,description:n.description,access:n.access,createdAt:n.createdAt,updatedAt:n.updatedAt})}catch(e){return void console.error("Error parsing RoleJSON:",e)}}static isRoleJSON(e){return F.safeParse(e).success}}const L=a.default.object({companyProfile:x,role:F.optional(),_version:a.default.string().optional().default("1.0")});class U{_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return R.is(e.companyProfile)?new U(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=L.safeParse(t);if(!r.success)return void console.error("Invalid CompanyMembershipJSON:",r.error.flatten());const n=r.data,a=R.fromJSON(n.companyProfile),o=n.role?k.fromJSON(n.role):void 0;return a?U.from({companyProfile:a,role:o}):void console.error("Failed to reconstruct Profile from CompanyMembershipJSON")}catch(e){return void console.error("Error parsing CompanyMembershipJSON:",e)}}static isCompanyMembershipJSON(e){return L.safeParse(e).success}}const $=a.default.object({logIn:M,companyProfile:x,role:F.optional(),_version:a.default.string().optional().default("1.0")});class q{_logIn;_membership;constructor(e){this._logIn=e.logIn,this._membership=e.membership}static from(e){try{if(!e.logIn||!e.companyProfile)return void console.error("Missing required User fields");const t=U.from({companyProfile:e.companyProfile,role:e.role});return t?new q({logIn:e.logIn,membership:t}):void console.error("Failed to create CompanyMembership")}catch(e){return void console.error("Error creating User:",e)}}get logIn(){return this._logIn}get login(){return this._logIn}get membership(){return this._membership}get id(){return this._logIn.id}get name(){return this._logIn.name}get identity(){return this._logIn.identity}get roleId(){return this._logIn.roleId}get resetPassword(){return this._logIn.resetPassword}get profile(){return this._membership.companyProfile}get role(){return this._membership.role}get access(){return this._logIn.access}toJSON(){return{logIn:this._logIn.toJSON(),companyProfile:this._membership.companyProfile.toJSON(),role:this._membership.role?.toJSON(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=$.safeParse(t);if(!r.success)return void console.error("Invalid UserJSON:",r.error.flatten());const n=r.data,a=j.fromJSON(n.logIn),o=R.fromJSON(n.companyProfile),s=n.role?k.fromJSON(n.role):void 0;if(!a||!o)return void console.error("Failed to reconstruct nested objects from UserJSON");const i=U.from({companyProfile:o,role:s});return i?new q({logIn:a,membership:i}):void console.error("Failed to create CompanyMembership from UserJSON")}catch(e){return void console.error("Error parsing UserJSON:",e)}}static isUserJSON(e){return $.safeParse(e).success}}const V={logInRequestDTO:e.z.object({type:e.z.string().default("password"),identity:e.z.string().email(),password:e.z.string()}),logInResponseDTO:e.z.object({profile:T.profileDTOSchema,token:e.z.string(),access:e.z.array(e.z.string()),resetPassword:e.z.boolean()}),accessResponseDTO:e.z.array(e.z.string()),resetPasswordRequestDTO:e.z.object({currentPassword:e.z.string(),newPassword:e.z.string()}),emptyResponseDTO:e.z.object({})},W=h().router({logIn:{method:"POST",path:"/login",body:V.logInRequestDTO,responses:{201:V.logInResponseDTO,400:V.emptyResponseDTO}},access:{method:"GET",path:"/access",responses:{200:V.accessResponseDTO}},resetPassword:{method:"PUT",path:"/password",body:V.resetPasswordRequestDTO,responses:{200:V.emptyResponseDTO,400:V.emptyResponseDTO}}}),H=h().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:J.loginDTO}}});class G extends _{constructor(e){super("login",H,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 Q=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"),K=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")}),Y=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:K.optional(),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),Z={role:K,teamMember:Y,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:Q.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:Q.optional(),resetPassword:e.z.boolean().optional(),isActive:e.z.boolean().optional()}),resetPasswordRequest:e.z.object({newPassword:Q.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:Q},X=h().router({getTeamMembers:{method:"GET",path:"/login",query:Z.teamMemberQueryParams,responses:{200:e.z.array(Z.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:Z.teamMemberQueryParams,responses:{200:Z.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:Z.createTeamMemberRequest,responses:{201:Z.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:Z.updateTeamMemberRequest,responses:{200:Z.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:Z.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:Z.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:Z.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(Z.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:Z.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"}}),ee=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 te{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 te(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 te.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>te.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=ee.safeParse(t);if(!r.success)return void console.error("Invalid TeamMemberJSON:",r.error.flatten());const n=r.data,a=n.role?{id:n.role.id,name:n.role.name,description:n.role.description,access:n.role.access,createdAt:n.role.createdAt,updatedAt:n.role.updatedAt}:void 0;return te.from({id:n.id,name:n.name,identity:n.identity,type:n.type,profileId:n.profileId,roleId:n.roleId,resetPassword:n.resetPassword,isActive:n.isActive,isArchived:n.isArchived,role:a,createdAt:n.createdAt,updatedAt:n.updatedAt})}catch(e){return void console.error("Error parsing TeamMemberJSON:",e)}}static isTeamMemberJSON(e){return ee.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>te.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 re extends _{constructor(e){super("admin",X,e)}async createTeamMember(e){const t=await this.client.createTeamMember({body:e});return this.handleResponse(t,201)}async updateTeamMember(e,t){const r=await this.client.updateTeamMember({params:{id:e},body:t}),n=this.handleResponse(r,200),a=te.from(n);if(!a)throw new Error("Invalid team member data received from server");return a}async archiveTeamMember(e){const t=await this.client.archiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),n=te.from(r);if(!n)throw new Error("Invalid team member data received from server");return n}async unArchiveTeamMember(e){const t=await this.client.unArchiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),n=te.from(r);if(!n)throw new Error("Invalid team member data received from server");return n}async resetTeamMemberPassword(e,t={}){const r=await this.client.resetPassword({params:{id:e},body:t});return this.handleResponse(r,200)}async getAllTeamMembers(e={eager:"role"}){const t=await this.client.getTeamMembers({query:e}),r=this.handleResponse(t,200);return te.createMany(r)}async getTeamMember(e,t={eager:"role"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),n=this.handleResponse(r,200),a=te.from(n);if(!a)throw new Error("Invalid team member data received from server");return a}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=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),n=k.from(r);if(!n)throw new Error("Invalid role data received from server");return n}}var ne;exports.BeneficiaryType=void 0,(ne=exports.BeneficiaryType||(exports.BeneficiaryType={})).Bank="Bank",ne.Mobile="Mobile";const ae=e.z.nativeEnum(exports.BeneficiaryType),oe=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:ae}),se={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(oe),beneficiaryInputDTO:oe,beneficiaryType:ae},ie=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")}),ce=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")}),ue=e.z.discriminatedUnion("type",[ie,ce]);class de extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="BeneficiaryError"}}class le{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 pe extends le{name;phoneNumber;mnoId;constructor(e,t,r){super(exports.BeneficiaryType.Mobile,t.countryCode),this.name=e,this.phoneNumber=t;const n=pe.resolveMnoId(t,r),a=pe.checkInputs(e,t,n);if(!a.isValid)throw new de(a.errors[0],{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format,mnoId:n});this.mnoId=n}static resolveMnoId(e,t){return r.MobileMoneyProviderHelpers.requiresExplicitProvider(e.countryCode)?t:r.MobileMoneyProviderHelpers.detectProviderByPhoneNumber(e)?.id}static checkInputs(e,t,n){const a=[];return e?.trim()||a.push("Name is required and cannot be empty"),t?.validate()||a.push("Invalid phone number"),n?r.MobileMoneyProviderHelpers.validateProviderForPhoneNumber(t,n)||a.push(`Invalid MNO ${n} for phone number ${t.e164Format}`):a.push(r.MobileMoneyProviderHelpers.requiresExplicitProvider(t.countryCode)?`MNO must be explicitly provided for phone numbers in ${t.countryCode}`:`Failed to determine MNO for phone number ${t.e164Format}`),{isValid:0===a.length,errors:a,warnings:[]}}static pickMnoIdFromDTO(e,t){if(r.MobileMoneyProviderHelpers.requiresExplicitProvider(e.countryCode)){if("string"!=typeof t)return;return r.MobileMoneyProviderHelpers.isProviderSupported(e.countryCode,t)?t:void console.warn(`Invalid MNO ${t} for country ${e.countryCode}`)}const n=r.MobileMoneyProviderHelpers.detectProviderByPhoneNumber(e);if(n)return n.id;console.warn(`Failed to auto-detect MNO for phone number ${e.e164Format}`)}static from(e){try{return new pe(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==exports.BeneficiaryType.Mobile)return;const t=e.accountNo.startsWith("+")?e.accountNo:`+${e.accountNo}`,n=r.PhoneNumber.from(t);if(!n)return void console.error(`Failed to parse phone number ${t}`);const a=pe.pickMnoIdFromDTO(n,e.channel);return a?pe.from({name:e.displayName,phoneNumber:n,mnoId:a}):void 0}static fromBeneficiaryDTO(e){return pe.fromInputDTO(e)}static fromPayoutDTO(e){if(!r.CountryHelpers.isISO2Code(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}`);const n=pe.pickMnoIdFromDTO(t,e.channel);return n?pe.from({name:e.payeeName,phoneNumber:t,mnoId:n}):void 0}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===exports.BeneficiaryType.Mobile&&(!("string"!=typeof t.name||!t.name.trim())&&(!!r.PhoneNumber.is(t.phoneNumber)&&("string"==typeof t.mnoId&&r.MobileMoneyProviderHelpers.isProviderSupported(t.phoneNumber.countryCode,t.mnoId))))}validate(){return pe.checkInputs(this.name,this.phoneNumber,this.mnoId).isValid}getValidationDetails(){return pe.checkInputs(this.name,this.phoneNumber,this.mnoId)}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.MobileMoneyProviderHelpers.findById(this.mnoId,this.countryCode);return e?.mobileMoneyServiceName??e?.displayName??this.mnoId}get mobileMoneyProvider(){return r.MobileMoneyProviderHelpers.findById(this.mnoId,this.countryCode)}toJSON(){return{type:"Mobile",name:this.name,phoneNumber:this.phoneNumber.e164Format,mnoId:this.mnoId,_version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,n=ie.safeParse(t);if(!n.success)return void console.error("Invalid MobileBeneficiaryJSON:",n.error.flatten());const a=r.PhoneNumber.from(n.data.phoneNumber);if(!a)return;return pe.from({name:n.data.name,phoneNumber:a,mnoId:n.data.mnoId})}catch(e){return void console.error("Error parsing MobileBeneficiaryJSON:",e)}}static fromJSONString(e){return pe.fromJSON(e)}static isJSON(e){return ie.safeParse(e).success}}class he extends le{accName;bank;accNo;constructor(e,t,r){super(exports.BeneficiaryType.Bank,t.countryCode),this.accName=e,this.bank=t,this.accNo=r;const n=he.checkInputs(e,t,r);if(!n.isValid)throw new de(n.errors[0],{operation:"constructor",countryCode:t.countryCode})}static checkInputs(e,t,n){const a=[];return r.BankHelpers.validateAccountName(e)||a.push("Invalid account name"),r.Bank.is(t)?r.BankHelpers.validateAccountNumber(n,t.countryCode)||a.push("Invalid account number"):a.push("Invalid bank reference"),{isValid:0===a.length,errors:a,warnings:[]}}static from(e){try{return new he(e.accName,e.bank,e.accNo)}catch(e){return void console.error("Failed to create BankBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==exports.BeneficiaryType.Bank)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank beneficiaries");const n=r.BankHelpers.getCountryFromSwiftCode(t);if(!n)return void console.error(`Could not identify country from SWIFT code: ${t}`);const a=r.Bank.fromBIC(t,n);if(a)return he.from({accName:e.displayName,bank:a,accNo:e.accountNo});console.error(`Bank with SWIFT code ${t} not found`)}static fromBeneficiaryDTO(e){return he.fromInputDTO(e)}static fromPayoutDTO(e){if(!r.CountryHelpers.isISO2Code(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=e.msisdn.trim().split(":");if(2!==t.length)return void console.error("Invalid PayoutDTO format for bank — expected 'swiftcode:accountno'");const[n,a]=t,o=r.Bank.fromBIC(n,e.countryCode);if(o)return he.from({accName:e.payeeName,bank:o,accNo:a});console.error(`Bank with SWIFT code ${n} not found`)}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===exports.BeneficiaryType.Bank&&("string"==typeof t.accName&&("string"==typeof t.accNo&&(!!r.Bank.is(t.bank)&&(r.BankHelpers.validateAccountName(t.accName)&&r.BankHelpers.validateAccountNumber(t.accNo,t.bank.countryCode)))))}validate(){return he.checkInputs(this.accName,this.bank,this.accNo).isValid}getValidationDetails(){return he.checkInputs(this.accName,this.bank,this.accNo)}get accountName(){return this.accName}get accountNumber(){return this.accNo}get accountNameLabel(){return"Acc. Name"}get accountNumberLabel(){return"Bank Acc. No."}get channelLabel(){return"Bank"}get channelId(){return this.bank.bic}get channelName(){return this.bank.shortName}toJSON(){return{type:"Bank",accName:this.accName,swiftCode:this.bank.bic,countryCode:this.bank.countryCode,accNo:this.accNo,_version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,n=ce.safeParse(t);if(!n.success)return void console.error("Invalid BankBeneficiaryJSON:",n.error.flatten());const a=n.data;if(!r.CountryHelpers.isISO2Code(a.countryCode))return;const o=r.Bank.fromBIC(a.swiftCode,a.countryCode);if(!o)return;return he.from({accName:a.accName,bank:o,accNo:a.accNo})}catch(e){return void console.error("Error parsing BankBeneficiaryJSON:",e)}}static fromJSONString(e){return he.fromJSON(e)}static isJSON(e){return ce.safeParse(e).success}}class me{static fromInputDTO(e){return me.fromDTO(e)}static fromBeneficiaryDTO(e){return me.fromDTO(e)}static fromPayoutDTO(e){return e.msisdn.includes(":")?he.fromPayoutDTO(e):pe.fromPayoutDTO(e)}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ue.safeParse(t);if(!r.success)return;return"Mobile"===r.data.type?pe.fromJSON(r.data):he.fromJSON(r.data)}catch{return}}static fromJSONString(e){return me.fromJSON(e)}static is(e){return pe.is(e)||he.is(e)}static isJSON(e){return ue.safeParse(e).success}static fromDTO(e){return e.type===exports.BeneficiaryType.Mobile?pe.fromInputDTO(e):he.fromInputDTO(e)}}const ye={fromInputDTO:e=>me.fromInputDTO(e),fromBeneficiaryDTO:e=>me.fromBeneficiaryDTO(e),fromPayoutDTO:e=>me.fromPayoutDTO(e),fromJSON:e=>me.fromJSON(e),fromJSONString:e=>me.fromJSONString(e),is:e=>me.is(e),isJSON:e=>me.isJSON(e)},fe=se.beneficiaryDTO.extend({_version:e.z.string().optional().default("1.0")});class ge{_id;_profileId;_displayName;_accountNo;_channel;_type;_createdAt;_updatedAt;_info;_infoComputed=!1;constructor(e){const t=se.beneficiaryDTO.parse(e);this._id=t.id,this._profileId=t.profileId,this._displayName=t.displayName,this._accountNo=t.accountNo,this._channel=t.channel,this._type=t.type,this._createdAt=t.createdAt,this._updatedAt=t.updatedAt}get id(){return this._id}get profileId(){return this._profileId}get displayName(){return this._displayName}get type(){return this._type}get createdAt(){return new Date(this._createdAt)}get updatedAt(){return new Date(this._updatedAt)}get info(){return this._infoComputed||(this._infoComputed=!0,this._info=me.fromBeneficiaryDTO(this.toDTO())),this._info}get accNo(){const e=this.info;return e?e.accountNumber:this._accountNo}get accName(){return this._displayName}get accNoLabel(){return this.type===exports.BeneficiaryType.Mobile?"Phone Number":this.type===exports.BeneficiaryType.Bank?"Bank Account Number":"Account Number"}get channelLabel(){return this.type===exports.BeneficiaryType.Mobile?"Channel":this.type===exports.BeneficiaryType.Bank?"Bank":"Channel"}get accNameLabel(){return this.type===exports.BeneficiaryType.Mobile?"Full Name":this.type===exports.BeneficiaryType.Bank?"Bank Account Name":"Display Name"}get channelName(){return this.info?.channelName??""}static from(e){try{return new ge(e)}catch(e){return void console.error("Failed to create Beneficiary:",e)}}static create(e){return new ge(e)}static createMany(e){return e.map(e=>new ge(e))}static createSafe(e){return ge.from(e)??null}static canConstruct(e){return se.beneficiaryDTO.safeParse(e).success}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("function"!=typeof t.toJSON)return!1;try{return fe.safeParse(t.toJSON()).success}catch{return!1}}toJSON(){return{...this.toDTO(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=t&&"object"==typeof t&&"data"in t?t.data:t,n=fe.safeParse(r);if(!n.success)return void console.error("Invalid BeneficiaryJSON:",n.error.flatten());const a=n.data,{_version:o,...s}=a;return ge.from(s)}catch(e){return void console.error("Error parsing BeneficiaryJSON:",e)}}static fromJSONString(e){return ge.fromJSON(e)}static isBeneficiaryJSON(e){return fe.safeParse(e).success}toDTO(){return{id:this._id,profileId:this._profileId,displayName:this._displayName,accountNo:this._accountNo,channel:this._channel,type:this._type,createdAt:this._createdAt,updatedAt:this._updatedAt}}}class Ne{canHandle(e){return"Mobile"===e.type&&pe.is(e)}createInput(e){if(pe.is(e))return{type:exports.BeneficiaryType.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile BeneficiaryInfo Info")}}class be{canHandle(e){return"Bank"===e.type&&he.is(e)}createInput(e){if(he.is(e))return{type:exports.BeneficiaryType.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Bank BeneficiaryInfo Info")}}class ve{handlers=[new Ne,new be];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 Se=h().router({createBeneficiary:{method:"POST",path:"/",body:se.beneficiaryInputDTO,responses:{201:se.beneficiaryDTO}},editBeneficiary:{method:"PATCH",path:"/:id",body:se.beneficiaryInputDTO,responses:{200:se.beneficiaryDTO}},getBeneficiaries:{method:"GET",path:"/",query:e.z.object({orderByDesc:e.z.string()}),responses:{200:e.z.array(se.beneficiaryDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:se.beneficiaryDTO}},deleteBeneficiary:{method:"DELETE",path:"/:id",body:e.z.object({}),responses:{200:e.z.object({})}}});var Ie,we,Ae;exports.PayoutChannel=void 0,(Ie=exports.PayoutChannel||(exports.PayoutChannel={})).MOBILE="Mobile",Ie.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,(Ae=exports.PayoutApprovalStatus||(exports.PayoutApprovalStatus={})).PENDING="Pending",Ae.APPROVED="Approved",Ae.REJECTED="Rejected";const _e=e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string()}),Oe=e.z.nativeEnum(exports.PayoutStatus),Pe=e.z.nativeEnum(exports.PayoutApprovalStatus),Ce=e.z.union([e.z.string(),e.z.array(e.z.string())]).transform(e=>(Array.isArray(e)?e:[e]).flatMap(e=>e.split(",")).map(e=>e.trim()).filter(e=>e.length>0)),ze=Ce.pipe(e.z.array(Oe)),Be=Ce.pipe(e.z.array(Pe)),De=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()}),Ee=De.extend({payeeName:e.z.string()}),Te=De.extend({id:e.z.string(),profileId:e.z.string(),payeeName:e.z.string(),countryCode:e.z.string().default("TZ").refine(e=>r.CountryHelpers.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>r.CurrencyHelpers.isCode(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:Pe.nullish(),createdById:e.z.string().nullish(),actionedById:e.z.string().nullish(),createdBy:_e.nullish(),actionedBy:_e.nullish()}),xe=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(),msisdnIn:Ce.nullish(),profileId:e.z.string().nullish(),id:e.z.string().nullish(),partnerReference:e.z.string().nullish(),channel:e.z.string().nullish(),channelIn:Ce.nullish(),currencyCode:e.z.string().nullish(),status:Oe.nullish(),statusIn:ze.nullish(),approvalStatus:Pe.nullish(),approvalStatusIn:Be.nullish(),createdById:e.z.string().nullish(),createdByIdIn:Ce.nullish(),actionedById:e.z.string().nullish(),actionedByIdIn:Ce.nullish(),minAmount:e.z.number().min(0).nullish(),maxAmount:e.z.number().min(0).nullish(),search:e.z.string().nullish()}),Re={PayoutDTO:Te,PayoutInputDTO:Ee,PayoutStatus:Oe,PayoutApprovalStatus:Pe,PayoutAuthorizer:_e,PayoutFilters:xe,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(),msisdnIn:Ce.optional(),profileId:e.z.string().optional(),id:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:e.z.string().optional(),channelIn:Ce.optional(),status:e.z.string().refine(e=>Object.values(exports.PayoutStatus).includes(e)).transform(e=>e).optional(),statusIn:ze.optional(),approvalStatus:e.z.string().refine(e=>Object.values(exports.PayoutApprovalStatus).includes(e)).transform(e=>e).optional(),approvalStatusIn:Be.optional(),createdById:e.z.string().optional(),createdByIdIn:Ce.optional(),actionedById:e.z.string().optional(),actionedByIdIn:Ce.optional(),minAmount:e.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:e.z.string().transform(e=>parseFloat(e)).optional(),search:e.z.string().optional()})},Je=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:Re.PayoutStatus,statusMessage:a.default.string(),partnerReference:a.default.string().nullish(),createdAt:a.default.string(),updatedAt:a.default.string(),actionedAt:a.default.string().nullish(),approvalStatus:Re.PayoutApprovalStatus.nullish(),createdById:a.default.string().nullish(),actionedById:a.default.string().nullish(),createdBy:Re.PayoutAuthorizer.nullish(),actionedBy:Re.PayoutAuthorizer.nullish(),_version:a.default.string().optional().default("1.0")});class Me{_id;_profileId;_payeeName;_channel;_msisdn;_amount;_currencyCode;_countryCode;_description;_notes;_status;_statusMessage;_partnerReference;_createdAt;_updatedAt;_actionedAt;_approvalStatus;_createdById;_actionedById;_createdBy;_actionedBy;constructor(e){const t=Re.PayoutDTO.parse(e);this._id=t.id,this._profileId=t.profileId,this._payeeName=t.payeeName,this._channel=t.channel,this._msisdn=t.msisdn,this._amount=t.amount,this._currencyCode=t.currencyCode,this._countryCode=t.countryCode,this._description=t.description,this._notes=t.notes,this._status=t.status,this._statusMessage=t.statusMessage,this._partnerReference=t.partnerReference,this._createdAt=t.createdAt,this._updatedAt=t.updatedAt,this._actionedAt=t.actionedAt,this._approvalStatus=t.approvalStatus,this._createdById=t.createdById,this._actionedById=t.actionedById,this._createdBy=t.createdBy,this._actionedBy=t.actionedBy}get id(){return this._id}get profileId(){return this._profileId}get payeeName(){return this._payeeName}get channel(){return this._channel}get msisdn(){return this._msisdn}get amount(){return r.Amount.from(this._amount,this._currencyCode)}get description(){return this._description}get notes(){return this._notes}get status(){return"Rejected"===this._approvalStatus?exports.PayoutStatus.REJECTED:"Approved"===this._approvalStatus?"FAILED"===this._status?exports.PayoutStatus.FAILED:exports.PayoutStatus.PAID:"Pending"===this._approvalStatus?exports.PayoutStatus.PENDING:this._status}get statusMessage(){return this._statusMessage}get partnerReference(){return this._partnerReference}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get actionedAt(){return this._actionedAt}get approvalStatus(){return this._approvalStatus}get createdById(){return this._createdById}get actionedById(){return this._actionedById}get createdBy(){return this._createdBy}get actionedBy(){return this._actionedBy}get beneficiaryInfo(){return me.fromPayoutDTO(this.toDTO())}get contactInfo(){return this.beneficiaryInfo}static create(e){return new Me(e)}static createMany(e){return e.map(e=>new Me(e))}static createSafe(e){try{return new Me(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=Re.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==Me.createSafe(t.data)}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("function"!=typeof t.toJSON)return!1;try{return Je.safeParse(t.toJSON()).success}catch{return!1}}toJSON(){return{id:this._id,profileId:this._profileId,payeeName:this._payeeName,channel:this._channel,msisdn:this._msisdn,amount:this._amount,currencyCode:this._currencyCode,countryCode:this._countryCode,description:this._description,notes:this._notes,status:this._status,statusMessage:this._statusMessage,partnerReference:this._partnerReference,createdAt:this._createdAt.toISOString(),updatedAt:this._updatedAt.toISOString(),actionedAt:this._actionedAt?.toISOString()??null,approvalStatus:this._approvalStatus,createdById:this._createdById,actionedById:this._actionedById,createdBy:this._createdBy,actionedBy:this._actionedBy,_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,n=Je.safeParse(t);if(!n.success)return void console.error("Invalid PayoutJSON:",n.error.flatten());const a=n.data,o=a.currencyCode;if(!r.CurrencyHelpers.isCode(o))return void console.error("Invalid currency code:",o);const s=a.countryCode;if(!r.CountryHelpers.isISO2Code(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:o,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,createdById:a.createdById,actionedById:a.actionedById,createdBy:a.createdBy,actionedBy:a.actionedBy};return Me.create(i)}catch(e){return void console.error("Error parsing PayoutJSON:",e)}}static isPayoutJSON(e){return Je.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>Me.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing Payout JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}toDTO(){return{id:this._id,profileId:this._profileId,payeeName:this._payeeName,channel:this._channel,msisdn:this._msisdn,amount:this._amount,currencyCode:this._currencyCode,countryCode:this._countryCode,description:this._description,notes:this._notes,status:this._status,statusMessage:this._statusMessage,partnerReference:this._partnerReference,createdAt:this._createdAt,updatedAt:this._updatedAt,actionedAt:this._actionedAt,approvalStatus:this._approvalStatus,createdById:this._createdById,actionedById:this._actionedById,createdBy:this._createdBy,actionedBy:this._actionedBy}}}const je="MOBILE TRANSFER ",Fe="PAYOUT",ke="PAYOUT TO BANK",Le="TO_BANK",Ue="PAYOUT TO MOBILE",$e="TO_MOMO",qe=a.default.object({text:a.default.string(),_version:a.default.string().optional().default("2.0")});class Ve{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 pe.is(e)?Ve.generateMobilePayoutNarrationV2(e):he.is(e)?Ve.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${Fe.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:n}=e;return`${Fe.toUpperCase()} ${t.bic.trim()} ${n.trim()} ${r.trim()}`.toUpperCase()}getBeneficiaryDetails=()=>{const e=this.getBankBeneficiaryDetails(),t=this.getMobileBeneficiaryDetails();return e||(t||void 0)};getBankBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(je)&&(e=e.substring(16));try{if(e.startsWith(Fe)){const t=e.replace(Fe,"").trim().split(" ");if(t.length>=3){const e=t[0],n=t[1],a=t.slice(2).map(We).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=r.BankHelpers.getCountryFromSwiftCode(e);if(t){if(r.BankHelpers.validateSwiftCode(e,t)){const o=r.Bank.fromBIC(e,t);if(n&&a&&o)return new he(a,o,n)}}}}}if(e.startsWith(Le)){const t=e.split("=>")[1].trim(),n=JSON.parse(t),a=n.account_number,o=n.account_name,s=n.swift_code,i=r.BankHelpers.getCountryFromSwiftCode(s);if(!i)return;if(!r.BankHelpers.validateSwiftCode(s,i))return;const c=r.Bank.fromBIC(s,i);if(a&&o&&c)return new he(o,c,a)}if(e.startsWith(ke)){const t=e.replace(ke,"").trim().split(" "),n=r.BankRegistry.getInstance().searchBanks("TZ",t[0]),a=n.length>0?n[0]:void 0,o=t[1],s=t.slice(2).map(We).join(" ");if(s&&o&&a)return new he(s,a,o)}}catch(e){return}};getMobileBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(je)&&(e=e.substring(16));try{if(e.startsWith(Fe)){const t=e.replace(Fe,"").trim().split(" ");if(t.length>=2){const e=t[0],n=t.slice(1).map(We).join(" ");if(e.startsWith("+")){const t=r.PhoneNumber.from(e);if(t&&n)return new pe(n,t)}}}if(e.startsWith($e)){const t=e.split("=>")[1].trim(),n=JSON.parse(t),a=r.PhoneNumber.from(n.phone_number,{defaultCountry:"TZ"});let o=n.username;void 0===o&&(o="");let s=o.split(" ");if(s=s.filter(e=>e.trim().length>0),o=s.map(We).join(" "),a&&o)return new pe(o,a)}if(e.startsWith(Ue)){const t=e.replace(Ue,"").trim().split(" "),n=r.PhoneNumber.from(t[0],{defaultCountry:"TZ"}),a=t.slice(1).map(We).join(" ");if(n&&a)return new pe(a,n)}}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=qe.safeParse(t);if(!r.success)return void console.error("Invalid NarrationJSON:",r.error.flatten());const n=r.data;return new Ve(n.text)}catch(e){return void console.error("Error parsing NarrationJSON:",e)}}static isNarrationJSON(e){return qe.safeParse(e).success}toJson(){return this.toJSON()}static fromJson(e){return Ve.fromJSON(e)}}function We(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}const He={SUPPORTED_COUNTRY_CODES:["TZ","KE"],ERROR_MESSAGES:{INVALID_PHONE_NUMBER:"Invalid phone number",INELIGIBLE_FOR_PAYOUT:"The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",MOBILE_NUMBER_MNO_MISMATCH:"There is a mismatch between the phone number provided and the MNO used.",UNSUPPORTED_COUNTRY_BANK:"Only TZ and KE banks are supported for now",UNSUPPORTED_COUNTRY_MOBILE:"Only TZ and KE mobile numbers are supported for now",NO_HANDLER_FOUND:"Cannot create payout input!"}};class Ge{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}static isPhoneEligibleForPayout(e){const t=e.getNumberType();return t===r.PhoneNumberType.MOBILE||t===r.PhoneNumberType.FIXED_LINE_OR_MOBILE}}class Qe{static forBank(e,t){if(!He.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(He.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,t,n){if(!r.PhoneNumber.is(e))throw new Error(He.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!He.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(He.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!Ge.isPhoneEligibleForPayout(e))throw new Error(He.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const a=r.MobileMoneyProviderHelpers.findById(t,e.countryCode);if(!a)throw new Error(He.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return"VODACOM"===a.id?`${n.countryCode}-TIGO-B2C`:`${n.countryCode}-${a.id}-B2C`}}class Ke{canHandle(e,t,n){return e===exports.PayoutChannel.MOBILE&&pe.is(t)&&n.countryCode===t.countryCode&&n.currencyCode===r.Country.fromCode(t.countryCode)?.currencyCode}createInput(e,t){const n=e.receiver,a=Ge.processNotes(e.notes),o=n.phoneNumber;return{channel:Qe.forMobile(o,n.mnoId,t),msisdn:o.getWithFormat(r.PhoneNumberFormat.INTERNATIONAL_NUMERIC),description:a??Ve.generateDefaultPayoutNarration(n),payeeName:n.name,notes:a,amount:e.amount.numericValue}}}class Ye{canHandle(e,t,n){return e===exports.PayoutChannel.BANK&&he.is(t)&&n.countryCode===t.countryCode&&n.currencyCode===r.Country.fromCode(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=Ge.processNotes(e.notes);return{channel:Qe.forBank(r,t),msisdn:`${r.bank.bic}:${r.accNo}`,description:n??Ve.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:n,amount:e.amount.numericValue}}}class Ze{handlers=[new Ke,new Ye];getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(He.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const Xe={bank:Qe.forBank.bind(Qe),mobile:Qe.forMobile.bind(Qe)},et=h().router({getPayouts:{method:"GET",path:"",query:e.z.object({}),responses:{200:e.z.object({results:e.z.array(Re.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:Re.PayoutApprovalStatus,orderByDesc:e.z.string()}),responses:{200:e.z.object({results:e.z.array(Re.PayoutDTO),total:e.z.number()})}},postPayout:{method:"POST",path:"",body:Re.PayoutInputDTO,responses:{201:Re.PayoutDTO,400:o.schema}},approve:{method:"POST",path:"/:id/approve",body:e.z.object({action:e.z.enum(["Approve","Reject"]),notes:e.z.string().optional()}),responses:{201:Re.PayoutDTO,400:o.schema,401:o.schema,404:e.z.object({}),409:e.z.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:Re.PayoutDTO,404:e.z.object({})}}}),tt=["approvalStatus","status","channel","msisdn","createdById","actionedById"];class rt extends z{static create(){return new rt}static fromFilters(e){return(new rt).applyFilters(e)}static fromUrlParams(e){try{const t=Re.PayoutURLQueryParams.parse(this.normalizeUrlParams(e)),r=Re.PayoutFilters.parse(t);return rt.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return rt.fromUrlParams(this.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return rt.fromSearchParams(t)}static from(e){try{return null==e?new rt:z.is(e)?new rt(e.options):e instanceof URLSearchParams?rt.fromSearchParams(e):this.isUrlParamsRecord(e)?rt.fromUrlParams(e):rt.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a PayoutQuery instance.")}}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static normalizeUrlParams(e){const t={...e};for(const e of tt){const r=e,n=`${e}In`,a=`${e}:in`,o=`${e}[]`,s=`${e}In[]`,i=t[r],c=rt.toStringList([t[n],t[a],t[o],t[s],Array.isArray(i)?i:void 0]);c.length>0&&(t[n]=c),Array.isArray(i)&&delete t[r],delete t[a],delete t[o],delete t[s]}return t}static toStringList(e){const t=Array.isArray(e)?e.flatMap(e=>rt.toStringList(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))}whereStatus(e){return this.where("status",e)}whereStatusIn(e){return this.whereInValues("status",e)}whereApprovalStatus(e){return this.where("approvalStatus",e)}whereApprovalStatusIn(e){return this.whereInValues("approvalStatus",e)}whereChannel(e){return this.where("channel",e)}whereChannelIn(e){return this.whereInValues("channel",e)}wherePending(){return this.whereApprovalStatus(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)}wherePayee(e){return this.whereContains("payeeName",e)}whereMsisdn(e){return this.whereContains("msisdn",e)}whereMsisdnIn(e){return this.whereInValues("msisdn",e)}whereProfileId(e){return this.where("profileId",e)}whereCreatedById(e){return this.where("createdById",e)}whereCreatedByIdIn(e){return this.whereInValues("createdById",e)}whereActionedById(e){return this.where("actionedById",e)}whereActionedByIdIn(e){return this.whereInValues("actionedById",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){if((e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.statusIn?.length?this.whereStatusIn(e.statusIn):e.status&&this.whereStatus(e.status),e.approvalStatusIn?.length?this.whereApprovalStatusIn(e.approvalStatusIn):e.approvalStatus&&this.whereApprovalStatus(e.approvalStatus),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.payeeName&&this.wherePayee(e.payeeName),e.msisdnIn?.length?this.whereMsisdnIn(e.msisdnIn):e.msisdn&&this.whereMsisdn(e.msisdn),e.profileId&&this.whereProfileId(e.profileId),e.createdByIdIn?.length?this.whereCreatedByIdIn(e.createdByIdIn):e.createdById&&this.whereCreatedById(e.createdById),e.actionedByIdIn?.length?this.whereActionedByIdIn(e.actionedByIdIn):e.actionedById&&this.whereActionedById(e.actionedById),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.id&&this.where("id",e.id),void 0!==e.minAmount||void 0!==e.maxAmount){const t=void 0!==e.minAmount&&null!==e.minAmount,n=void 0!==e.maxAmount&&null!==e.maxAmount,{currencyCode:a}=e,o=a||"TZS";if(!r.CurrencyHelpers.isCode(o))return console.warn("Amount filter requires a valid currency code"),this;if(t&&n){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,o),n=r.Amount.from(e.maxAmount,o);t&&n&&this.whereAmountBetween(t,n)}else t?this.whereGreaterThanOrEqual("amount",e.minAmount):n&&this.whereLessThanOrEqual("amount",e.maxAmount)}return e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,payeeName:e.payeeName,msisdn:e.msisdn,msisdnIn:e.msisdnIn,profileId:e.profileId,createdById:e.createdById,createdByIdIn:e.createdByIdIn,actionedById:e.actionedById,actionedByIdIn:e.actionedByIdIn,id:e.id,partnerReference:e.partnerReference,channel:e.channel,channelIn:e.channelIn,status:this.isValidStatus(e.status)?e.status:void 0,statusIn:this.getValidStatuses(e.statusIn),approvalStatus:this.isValidApprovalStatus(e.approvalStatus)?e.approvalStatus:void 0,approvalStatusIn:this.getValidApprovalStatuses(e.approvalStatusIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(Array.isArray(r)?r.length>0&&(t[e]=r.join(",")):t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withStatusIn(e){const t=this.clone();return e?.length&&t.whereStatusIn(e),t}withApprovalStatus(e){const t=this.clone();return e&&t.whereApprovalStatus(e),t}withApprovalStatusIn(e){const t=this.clone();return e?.length&&t.whereApprovalStatusIn(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}withChannelIn(e){const t=this.clone();return e?.length&&t.whereChannelIn(e),t}withMsisdnIn(e){const t=this.clone();return e?.length&&t.whereMsisdnIn(e),t}withCreatedById(e){const t=this.clone();return e&&t.whereCreatedById(e),t}withCreatedByIdIn(e){const t=this.clone();return e?.length&&t.whereCreatedByIdIn(e),t}withActionedById(e){const t=this.clone();return e&&t.whereActionedById(e),t}withActionedByIdIn(e){const t=this.clone();return e?.length&&t.whereActionedByIdIn(e),t}includeDefaultRelations(){return this.with("[createdBy,actionedBy]")}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.payeeName||e.msisdn||e.msisdnIn?.length||e.profileId||e.createdById||e.createdByIdIn?.length||e.actionedById||e.actionedByIdIn?.length||e.id||e.partnerReference||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.approvalStatus||e.approvalStatusIn?.length||e.minAmount||e.maxAmount||e.search)}describeFilters(e){const t=[],n=this.toFilters(),a=e?.formatDate??(e=>e);if(n.sortBy){const e="asc"===n.sortOrder?"Ascending":"Descending";t.push({label:"Sort",value:`${this.formatSortField(n.sortBy)} (${e})`})}if(n.startDate&&n.endDate?t.push({label:"Date Range",value:`${a(n.startDate)} — ${a(n.endDate)}`}):n.startDate?t.push({label:"From",value:a(n.startDate)}):n.endDate&&t.push({label:"Until",value:a(n.endDate)}),n.statusIn?.length?t.push({label:"Status",value:n.statusIn.join(", ")}):n.status&&t.push({label:"Status",value:n.status}),n.approvalStatusIn?.length?t.push({label:"Approval Status",value:n.approvalStatusIn.join(", ")}):n.approvalStatus&&t.push({label:"Approval Status",value:n.approvalStatus}),n.channelIn?.length?t.push({label:"Channel",value:n.channelIn.join(", ")}):n.channel&&t.push({label:"Channel",value:n.channel}),void 0!==n.minAmount&&void 0!==n.maxAmount){const e=Number(n.minAmount),a=Number(n.maxAmount);if(Number.isFinite(e)&&Number.isFinite(a)){const n=r.Amount.from(e,"TZS"),o=r.Amount.from(a,"TZS");n&&o&&t.push({label:"Amount Range",value:`${n.label} — ${o.label}`})}}else if(void 0!==n.minAmount){const e=Number(n.minAmount);if(Number.isFinite(e)){const n=r.Amount.from(e,"TZS");n&&t.push({label:"Minimum Amount",value:n.label})}}else if(void 0!==n.maxAmount){const e=Number(n.maxAmount);if(Number.isFinite(e)){const n=r.Amount.from(e,"TZS");n&&t.push({label:"Maximum Amount",value:n.label})}}return n.search&&t.push({label:"Search",value:`"${n.search}"`}),n.payeeName&&t.push({label:"Beneficiary Name",value:n.payeeName}),n.msisdnIn?.length?t.push({label:"MSISDN",value:n.msisdnIn.join(", ")}):n.msisdn&&t.push({label:"MSISDN",value:n.msisdn}),n.profileId&&t.push({label:"Profile",value:n.profileId}),n.createdByIdIn?.length?t.push({label:"Created By ID",value:n.createdByIdIn.join(", ")}):n.createdById&&t.push({label:"Created By ID",value:n.createdById}),n.actionedByIdIn?.length?t.push({label:"Actioned By ID",value:n.actionedByIdIn.join(", ")}):n.actionedById&&t.push({label:"Actioned By ID",value:n.actionedById}),n.partnerReference&&t.push({label:"Reference",value:n.partnerReference}),t}describeFiltersAsText(){return this.describeFilters().map(e=>`${e.label}: ${e.value}`)}formatSortField(e){return{createdAt:"Date Created",updatedAt:"Date Updated",amount:"Amount",payeeName:"Beneficiary Name",approvalStatus:"Approval Status",status:"Status",channel:"Channel",msisdn:"MSISDN",createdById:"Created By ID",actionedById:"Actioned By ID"}[e]??e}build(){return super.build()}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=rt.toStringList(t.value);r.length>0&&(e[`${t.field}In`]=r);continue}switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"payeeName":case"msisdn":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}}return e}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}whereInValues(e,t){const r=rt.toStringList(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=rt.toStringList(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidApprovalStatuses(e){const t=rt.toStringList(e).filter(e=>this.isValidApprovalStatus(e));return t.length>0?t:void 0}isValidStatus(e){return Object.values(exports.PayoutStatus).includes(e)}isValidApprovalStatus(e){return Object.values(exports.PayoutApprovalStatus).includes(e)}}const nt=e=>e.optional().transform(e=>e??void 0),at={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.CountryHelpers.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>r.CurrencyHelpers.isCode(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.fromCode(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:nt(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:nt(e.z.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})},ot=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 st{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return at.walletDTO}constructor(e){this._id=e.id,this._profileId=e.profileId,this._accountNo=e.accountNo,this._accountName=e.accountName,this._channel=e.channel,this._countryCode=e.countryCode,this._currencyCode=e.currencyCode,this._createdAt=e.createdAt,this._updatedAt=e.updatedAt}static create(e){const t=st.schema.safeParse(e);if(t.success)return new st(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=st.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 st.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.CountryHelpers.isISO2Code(t._countryCode)&&"string"==typeof t._currencyCode&&r.CurrencyHelpers.isCode(t._currencyCode)&&"string"==typeof t._createdAt&&"string"==typeof t._updatedAt}toJSON(){return{id:this._id,profileId:this._profileId,accountNo:this._accountNo,accountName:this._accountName,channel:this._channel,countryCode:this._countryCode,currencyCode:this._currencyCode,createdAt:this._createdAt,updatedAt:this._updatedAt,_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ot.safeParse(t);if(!r.success)return void console.error("Invalid WalletJSON:",r.error.flatten());const n=r.data;return st.create(n)}catch(e){return void console.error("Error parsing WalletJSON:",e)}}static isWalletJSON(e){return ot.safeParse(e).success}}const it=a.default.object({accountNo:a.default.string().optional(),debitOrCredit:a.default.string(),tranRefNo:a.default.string(),narration:qe,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 ct{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return at.statementEntry}constructor(e,t){this._accountNo=e.accountNo,this._debitOrCredit=e.debitOrCredit,this._tranRefNo=e.tranRefNo,this._narration=t,this._txnDate=e.txnDate,this._valueDate=e.valueDate,this._currencyCode=e.currencyCode;const n=r.Currency.fromCode(e.currencyCode);if(!n)throw new Error(`Currency not found for code: ${e.currencyCode}`);const a=r.Amount.from(e.amountCredited,n.code),o=r.Amount.from(e.amountDebited,n.code),s=r.Amount.from(e.balance,n.code);if(!a||!o||!s)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=a,this._amountDebited=o,this._balance=s}static create(e){const t="string"==typeof e.narration?new Ve(e.narration):e.narration,r={...e,narration:t.text},n=ct.schema.safeParse(r);if(n.success)try{const{narration:e,...r}=n.data;return new ct(r,t)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",n.error.flatten())}get accountNo(){return this._accountNo}get debitOrCredit(){return this._debitOrCredit}get tranRefNo(){return this._tranRefNo}get narration(){return this._narration}get txnDate(){return this._txnDate}get valueDate(){return this._valueDate}get amountCredited(){return this._amountCredited}get amountDebited(){return this._amountDebited}get balance(){return this._balance}get currencyCode(){return this._currencyCode}validate(){const e={accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.text,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode},t=ct.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&&Ve.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 ct.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,n,a,o,s=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const o=r.Amount.fromJSON(e.amountCredited),i=r.Amount.fromJSON(e.amountDebited),c=r.Amount.fromJSON(e.balance);if(!o||!i||!c)return void console.error("Failed to deserialize Amount objects from JSON");t=o.numericValue,n=i.numericValue,a=c.numericValue,e.currencyCode||(s=o.currencyCode)}else if(t=Number(e.amountCredited),n=Number(e.amountDebited),a=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(a))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)o=e.narration;else if(Ve.is(e.narration))o=e.narration;else{if(!Ve.isNarrationJSON(e.narration))return void console.error("Invalid narration data");{const t=Ve.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");o=t}}return ct.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:o,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:n,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,n=it.safeParse(t);if(!n.success)return void console.error("Invalid WalletStatementEntryJSON:",n.error.flatten());const a=n.data,o=Ve.fromJSON(a.narration);if(!o)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"):ct.create({accountNo:a.accountNo,debitOrCredit:a.debitOrCredit,tranRefNo:a.tranRefNo,narration:o,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 it.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>ct.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 ct.fromJSON(e)}static fromJsonArray(e){return ct.fromJSONArray(e)}static toJsonArray(e){return ct.toJSONArray(e)}}const ut=h().router({getWallets:{method:"GET",path:"/",query:at.walletQuery,responses:{200:e.z.array(st.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(ct.schema)}}});class dt extends z{static create(){return new dt}static fromFilters(e){return(new dt).applyFilters(e)}static fromUrlParams(e){try{const t=at.walletQuery.parse(e);return dt.fromFilters(t)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return dt.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return dt.fromSearchParams(t)}static from(e){try{return null==e?new dt:z.is(e)?new dt(e.options):e instanceof URLSearchParams?dt.fromSearchParams(e):this.isStringRecord(e)?dt.fromUrlParams(e):dt.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a WalletQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereId(e){return this.where("id",e)}whereProfileId(e){return this.where("profileId",e)}whereAccountNo(e){return this.where("accountNo",e)}whereAccountName(e){return this.whereContains("accountName",e)}whereChannel(e){return this.where("channel",e)}whereCountryCode(e){return this.where("countryCode",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){return e.id&&this.whereId(e.id),e.profileId&&this.whereProfileId(e.profileId),e.accountNo&&this.whereAccountNo(e.accountNo),e.accountName&&this.whereAccountName(e.accountName),e.channel&&this.whereChannel(e.channel),e.countryCode&&this.whereCountryCode(e.countryCode),e.currencyCode&&this.whereCurrencyCode(e.currencyCode),this}toFilters(){const e=this.extractFilterValues();return{id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,currencyCode:e.currencyCode}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withId(e){const t=this.clone();return t.whereId(e),t}withProfileId(e){const t=this.clone();return t.whereProfileId(e),t}withAccountNo(e){const t=this.clone();return t.whereAccountNo(e),t}withCountryCode(e){const t=this.clone();return t.whereCountryCode(e),t}withCurrencyCode(e){const t=this.clone();return t.whereCurrencyCode(e),t}hasFilters(){const e=this.toFilters();return!!(e.id||e.profileId||e.accountNo||e.accountName||e.channel||e.countryCode||e.currencyCode)}getActiveFilters(){const e=[],t=this.toFilters();return t.id&&e.push(`ID: ${t.id}`),t.profileId&&e.push(`Profile: ${t.profileId}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.accountName&&e.push(`Name: ${t.accountName}`),t.channel&&e.push(`Channel: ${t.channel}`),t.countryCode&&e.push(`Country: ${t.countryCode}`),t.currencyCode&&e.push(`Currency: ${t.currencyCode}`),e}build(){return super.build()}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)"eq"===t.operator?e[t.field]=t.value:"likeLower"===t.operator&&"string"==typeof t.value&&(e[t.field]=t.value.replace(/%/g,""));return e}}const lt={getUniqueCountries(e){const t=new Set;return e.forEach(e=>{e.countryCode&&t.add(e.countryCode)}),Array.from(t)},getWalletsByCountry:(e,t)=>e.filter(e=>e.countryCode===t)},pt=h().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:R.schema}}});exports.APIError=o,exports.AuthDTOSchemas=V,exports.AuthRepository=class extends _{constructor(e){super("auth",W,e)}async logIn(e,t){const r={type:"password",identity:e,password:t},n=await this.client.logIn({body:r});if(400===n.status)throw new o({message:"Invalid email or password",statusCode:400});if(201===n.status){const e=n.body.token,t=new G({token:e}),r=await t.getIdentity(),a=j.from(r);if(!a)throw new o({message:"Failed to construct login credentials",statusCode:502});const i=n.body.profile,c=R.from(i);if(!c)throw new o({message:"Failed to construct user profile",statusCode:502});let u;if(a.can(s.Role.ViewRole))try{const t=new re({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});if(!d)throw new o({message:"Failed to construct user session",statusCode:502});return{token:e,user:d}}throw new o({message:"An error occurred while trying to log in",statusCode:502})}async updatePassword(e,t){const r=await this.client.resetPassword({body:{currentPassword:e,newPassword:t}});if(200===r.status)return!0;if(400===r.status)throw new o({message:"Invalid current password",statusCode:400});throw new o({message:"An error occurred while trying to update password",statusCode:502})}async getAccessList(){const e=await this.client.access();if(200===e.status)return e.body;throw new Error(`Failed to get access list. Status: ${e.status}`)}},exports.BANK_NARR_PREFIX=ke,exports.BankBeneficiaryInfo=he,exports.BankBeneficiaryJSONSchema=ce,exports.BaseRepository=_,exports.Beneficiary=ge,exports.BeneficiaryDTOSchemas=se,exports.BeneficiaryError=de,exports.BeneficiaryInfo=ye,exports.BeneficiaryInfoFactory=me,exports.BeneficiaryInfoJSONSchema=ue,exports.BeneficiaryJSONSchema=fe,exports.BeneficiaryRepository=class extends _{constructor(e){super("contact",Se,e)}async create(e){const t=(new ve).resolve(e),r=await this.client.createBeneficiary({body:t}),n=this.handleResponse(r,201);return ge.create(n)}async edit(e,t){const r=(new ve).resolve(t),n=await this.client.editBeneficiary({params:{id:e},body:r}),a=this.handleResponse(n,200);return ge.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 ge.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return ge.create(r)}},exports.CompanyMembership=U,exports.CompanyMembershipJSONSchema=L,exports.ECOBANK_PREFIX=je,exports.IdentityRepository=G,exports.LEGACY_BANK_NARR_PREFIX=Le,exports.LEGACY_MOBILE_NARR_PREFIX=$e,exports.LogIn=j,exports.LogInJSONSchema=M,exports.LogInSchemas=J,exports.MOBILE_NARR_PREFIX=Ue,exports.MobileBeneficiaryInfo=pe,exports.MobileBeneficiaryJSONSchema=ie,exports.NARR_V2_PREFIX=Fe,exports.Narration=Ve,exports.NarrationJSONSchema=qe,exports.Pagination=E,exports.PaginationParamsSchema=B,exports.PaginationSchema=D,exports.Payout=Me,exports.PayoutDTOSchemas=Re,exports.PayoutInputFactory=Ze,exports.PayoutJSONSchema=Je,exports.PayoutQuery=rt,exports.PayoutRepository=class extends _{constructor(e){super("payout",et,e)}async getPayouts(e){try{const t=rt.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),a=this.handleResponse(n,200),o=t.toFilters(),s=new E(o.page??1,o.limit??10,a.total);return{results:Me.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=rt.from(e).build();delete t.rangeStart,delete t.rangeEnd;const r=await this.client.getPayouts({query:t}),n=this.handleResponse(r,200);return Me.createMany(n)}catch(e){throw console.log("error: ",e),new Error(`Failed to fetch all payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=rt.fromRequest(e);return this.getPayouts(t)}async pay(e){const{wallet:t,channel:n,receiver:a,amount:s,notes:i}=e,c=r.TemboCoverage.getTransactionLimits({countryCode:t.countryCode,currencyCode:s.currencyCode,direction:r.TransactionDirection.PAYOUT,channelType:n===exports.PayoutChannel.BANK?r.ChannelType.BANK:r.ChannelType.MOBILE_MONEY});if(!c)throw new o({statusCode:400,message:`Payout limits are not configured for ${t.countryCode} ${s.currencyCode} ${n} payouts`});const{min:u,max:d}=c;if(s.lessThan(u)||s.greaterThan(d))throw new o({statusCode:400,message:`Please make sure the amount is between ${u.label} - ${d.label}`});const l=(new Ze).getPayoutInput({channel:n,receiver:a,amount:s,notes:i},t),p=await this.client.postPayout({body:l});if(201===p.status)return Me.create(p.body);if(400===p.status)throw new o(p.body);throw o.unknown()}async approve(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Approve",notes:e.notes}});if(201===t.status)return Me.create(t.body);if(401===t.status)throw new o({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new o({message:"Payout not found",statusCode:404});if(409===t.status)throw new o({message:"Payout already approved",statusCode:409});throw o.unknown()}async reject(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Reject",notes:e.notes}});if(201===t.status)return Me.create(t.body);if(401===t.status)throw new o({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new o({message:"Payout not found",statusCode:404});if(409===t.status)throw new o({message:"Payout already rejected",statusCode:409});throw o.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return Me.create(t.body);if(404===t.status)throw new o({message:"Payout not found",statusCode:404});throw o.unknown()}async count(e){const t=rt.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=R,exports.ProfileDTOSchemas=T,exports.ProfileJSONSchema=x,exports.ProfileRepository=class extends _{constructor(e){super("profile",pt,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=R.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=C,exports.QueryBuilder=z,exports.Role=k,exports.RoleJSONSchema=F,exports.TeamManagementDTOSchemas=Z,exports.TeamMember=te,exports.TeamMemberJSONSchema=ee,exports.TeamMemberRepository=re,exports.User=q,exports.UserJSONSchema=$,exports.ValidatedBeneficiaryInputFactory=ve,exports.Wallet=st,exports.WalletDTOSchemas=at,exports.WalletJSONSchema=ot,exports.WalletRepository=class extends _{constructor(e){super("wallet",ut,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 n=t.body.availableBalance,a=r.Amount.from(n,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 n=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,n.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=dt.from(e).build(),r=await this.client.getWallets({query:t});if(200===r.status){const e=r.body;try{return e.map(e=>{const t=st.from(e);if(!t)throw new Error(`Invalid wallet data: ${JSON.stringify(e)}`);return t})}catch(e){throw console.error("[WalletRepository] Error processing wallet data:",e),new Error("Failed to process wallet data from API")}}throw new Error(`Failed to fetch wallets. Status: ${r.status}`)}async getByID(e){const t=dt.create().whereId(e),r=await this.getWallets(t);return r.length>0?r[0]:void 0}async getStatement(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");const t=new Date,r=new Date(t.getFullYear(),t.getMonth(),1),n=new Date(t.getFullYear(),t.getMonth()+1,0),a=e.range??{startDate:r,endDate:n};let o,s;if(e.wallet)o=e.wallet,s=e.wallet.accountNo;else{if(!e.accountNo)throw new Error("Either wallet or accountNo must be provided");{const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);o=t[0],s=e.accountNo}}const i={...a,accountNo:s},c=await this.client.getStatement({body:i});if(201===c.status){return c.body.map(e=>({...e,currencyCode:o.currencyCode})).reduce((e,t)=>{const r=ct.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=ct,exports.WalletStatementEntryJSONSchema=it,exports.WalletUtils=lt,exports.contract=Se,exports.createPaginatedResponse=function(e,t,r,n){return{results:e,pagination:new E(t,r,n)}},exports.createPaginatedResponseSchema=function(t){return e.z.object({results:e.z.array(t),pagination:D})},exports.createPayoutChannelCode=Xe,exports.emptyPaginatedResponse=function(e=1,t=10){return{results:[],pagination:new E(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 n(e){return e&&e.__esModule?e:{default:e}}var a=n(e);class o extends Error{statusCode;error;details;constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,this.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return o.schema.safeParse(e).success}static unknown(e){return new o({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return 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 n,a,o,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!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(a=r.validateResponseOnClient)&&void 0!==a?a:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(o=r.metadata)&&void 0!==o?o:{}}:r.metadata}]:[e,l(r,t)]})),p=Symbol("ContractPlainType"),h=()=>({router:(e,t)=>l(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>p,body:()=>p,type:()=>p,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>u}),m=e=>e?Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r;return r="string"==typeof t&&!["true","false","null"].includes(t.trim())&&isNaN(Number(t))?t:JSON.stringify(t),`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).join("&"):"",y=e=>e?Object.keys(e).flatMap(t=>f(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",f=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>f(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>f(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class 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:n,body:a,validateResponse:o,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:n,body:a}),c=i.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t={status:i.status,body:await i.json(),headers:i.headers},r=e.responses[t.status];return(null!=o?o:e.validateResponseOnClient)&&"function"==typeof(null==(u=r)?void 0:u.safeParse)?{...t,body:r.parse(t.body)}:t}var u;return(null==c?void 0:c.includes("text/"))?{status:i.status,body:await i.text(),headers:i.headers}:{status:i.status,body:await i.blob(),headers:i.headers}},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 n of t)r(e,n);else r(e,t)}),t},v=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),S=(e,t,r,n,a)=>{const o=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),s=((e,t=!1)=>{const r=t?m(e):y(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,a);return`${t}${o}${s}`},I=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const a=((e,t,r)=>{const{query:n,params:a,body:o,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...p}=r||{},h={...t,...c};return{path:S(n,h.baseUrl,a,e,!!h.jsonQuery),clientArgs:h,route:e,body:o,query:n,extraInputArgs:p,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...i,...s}}})(e,t,n),o=await(e=>{const{path:t,clientArgs:r,route:n,body:a,query:o,extraInputArgs:s,headers:i,fetchOptions:c}=e,u=r.api||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 p={route:n,path:t,method:n.method,headers:l,body:void 0,rawBody:a,rawQuery:o,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?p={...p,contentType:"multipart/form-data",body:a instanceof FormData?a:b(a)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?p={...p,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...p.headers},body:"string"==typeof a?a:new URLSearchParams(a)}:null!=a&&(p={...p,contentType:"application/json",headers:{"content-type":"application/json",...p.headers},body:JSON.stringify(a)})),u({...p,...s})})(a);if(!t.throwOnUnknownStatus)return o;if(r.includes(o.status.toString()))return o;throw new g(o,r)}},w=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>d(r)?[e,I(r,t)]:[e,w(r,t)]));let A;class _{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 w(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 o(t.data);throw new o({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===e.status)throw new o({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new o({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new o({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new o({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}var O,C;exports.FilterOperator=void 0,(O=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",O.NOT_EQUALS="neq",O.LESS_THAN="lt",O.LESS_THAN_OR_EQUAL="lte",O.GREATER_THAN="gt",O.GREATER_THAN_OR_EQUAL="gte",O.LIKE="like",O.LIKE_LOWER="likeLower",O.IS_NULL="isNull",O.IS_NOT_NULL="isNotNull",O.IN="in",exports.SortDirection=void 0,(C=exports.SortDirection||(exports.SortDirection={})).ASC="asc",C.DESC="desc";const P=Symbol("query-builder-type");class z{options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*"};constructor(e={}){this.options={filters:e.filters||[],sort:e.sort||[],includes:e.includes||[],groupBy:e.groupBy||[],join:e.join||[],page:e.page,limit:e.limit}}[P]="query-builder";static is(e){return null!==e&&"object"==typeof e&&P in e&&"query-builder"===e[P]}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 z(e)}}const B=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)}),T=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 E{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 E(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new E(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()})},x=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 R{_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 R({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 R.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?R.create({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove}):void console.error("Missing required profile fields"):void console.error("Data is null or undefined")}catch(e){return void console.error("Error creating profile from object:",e)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t._id||"string"!=typeof t._displayName||"string"!=typeof t._accountNo)return!1;if(null!==t._firstName&&void 0!==t._firstName&&"string"!=typeof t._firstName)return!1;if(null!==t._lastName&&void 0!==t._lastName&&"string"!=typeof t._lastName)return!1;if(null!==t._email&&void 0!==t._email&&"string"!=typeof t._email)return!1;const r=t._phone;if(null!=r&&"string"!=typeof r)return!1;const n=t._autoApprove;return null==n||"boolean"==typeof n}toJSON(){return{id:this._id,firstName:this._firstName,lastName:this._lastName,displayName:this._displayName,phone:this._phone,accountNo:this._accountNo,email:this._email,autoApprove:this._autoApprove,_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=x.safeParse(t);if(!r.success)return void console.error("Invalid ProfileJSON:",r.error.flatten());const n=r.data;return R.from(n)}catch(e){return void console.error("Error parsing ProfileJSON:",e)}}static isProfileJSON(e){return x.safeParse(e).success}}const J={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())})},M=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;_permissionMap;constructor(e,t,r,n,a,o,s,i,c,u,d,l){this._id=e,this._profileId=t,this._name=r,this._identity=n,this._type=a,this._roleId=o,this._isActive=s,this._isArchived=i,this._resetPassword=c,this._createdAt=u,this._updatedAt=d,this._access=l,this._permissionMap={},this._access.forEach(e=>{this._permissionMap[e]=!0})}static from(e){const t=J.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}can(e){return this._permissionMap[e]??!1}canAny(e){return e.some(e=>this.can(e))}canAll(e){return e.every(e=>this.can(e))}toJSON(){return{id:this._id,profileId:this._profileId,name:this._name,identity:this._identity,type:this._type,roleId:this._roleId,isActive:this._isActive,isArchived:this._isArchived,resetPassword:this._resetPassword,createdAt:this._createdAt.toISOString(),updatedAt:this._updatedAt.toISOString(),access:[...this._access],_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=M.safeParse(t);if(!r.success)return void console.error("Invalid LogInJSON:",r.error.flatten());const n=r.data;return j.from({id:n.id,profileId:n.profileId,name:n.name,identity:n.identity,type:n.type,roleId:n.roleId,isActive:n.isActive,isArchived:n.isArchived,resetPassword:n.resetPassword,createdAt:n.createdAt,updatedAt:n.updatedAt,access:n.access})}catch(e){return void console.error("Error parsing LogInJSON:",e)}}static isLogInJSON(e){return M.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 n=r.data;return k.from({id:n.id,name:n.name,description:n.description,access:n.access,createdAt:n.createdAt,updatedAt:n.updatedAt})}catch(e){return void console.error("Error parsing RoleJSON:",e)}}static isRoleJSON(e){return F.safeParse(e).success}}const L=a.default.object({companyProfile:x,role:F.optional(),_version:a.default.string().optional().default("1.0")});class U{_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return R.is(e.companyProfile)?new U(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=L.safeParse(t);if(!r.success)return void console.error("Invalid CompanyMembershipJSON:",r.error.flatten());const n=r.data,a=R.fromJSON(n.companyProfile),o=n.role?k.fromJSON(n.role):void 0;return a?U.from({companyProfile:a,role:o}):void console.error("Failed to reconstruct Profile from CompanyMembershipJSON")}catch(e){return void console.error("Error parsing CompanyMembershipJSON:",e)}}static isCompanyMembershipJSON(e){return L.safeParse(e).success}}const $=a.default.object({logIn:M,companyProfile:x,role:F.optional(),_version:a.default.string().optional().default("1.0")});class q{_logIn;_membership;constructor(e){this._logIn=e.logIn,this._membership=e.membership}static from(e){try{if(!e.logIn||!e.companyProfile)return void console.error("Missing required User fields");const t=U.from({companyProfile:e.companyProfile,role:e.role});return t?new q({logIn:e.logIn,membership:t}):void console.error("Failed to create CompanyMembership")}catch(e){return void console.error("Error creating User:",e)}}get logIn(){return this._logIn}get login(){return this._logIn}get membership(){return this._membership}get id(){return this._logIn.id}get name(){return this._logIn.name}get identity(){return this._logIn.identity}get roleId(){return this._logIn.roleId}get resetPassword(){return this._logIn.resetPassword}get profile(){return this._membership.companyProfile}get role(){return this._membership.role}get access(){return this._logIn.access}toJSON(){return{logIn:this._logIn.toJSON(),companyProfile:this._membership.companyProfile.toJSON(),role:this._membership.role?.toJSON(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=$.safeParse(t);if(!r.success)return void console.error("Invalid UserJSON:",r.error.flatten());const n=r.data,a=j.fromJSON(n.logIn),o=R.fromJSON(n.companyProfile),s=n.role?k.fromJSON(n.role):void 0;if(!a||!o)return void console.error("Failed to reconstruct nested objects from UserJSON");const i=U.from({companyProfile:o,role:s});return i?new q({logIn:a,membership:i}):void console.error("Failed to create CompanyMembership from UserJSON")}catch(e){return void console.error("Error parsing UserJSON:",e)}}static isUserJSON(e){return $.safeParse(e).success}}const V={logInRequestDTO:e.z.object({type:e.z.string().default("password"),identity:e.z.string().email(),password:e.z.string()}),logInResponseDTO:e.z.object({profile:D.profileDTOSchema,token:e.z.string(),access:e.z.array(e.z.string()),resetPassword:e.z.boolean()}),accessResponseDTO:e.z.array(e.z.string()),resetPasswordRequestDTO:e.z.object({currentPassword:e.z.string(),newPassword:e.z.string()}),emptyResponseDTO:e.z.object({})},W=h().router({logIn:{method:"POST",path:"/login",body:V.logInRequestDTO,responses:{201:V.logInResponseDTO,400:V.emptyResponseDTO}},access:{method:"GET",path:"/access",responses:{200:V.accessResponseDTO}},resetPassword:{method:"PUT",path:"/password",body:V.resetPasswordRequestDTO,responses:{200:V.emptyResponseDTO,400:V.emptyResponseDTO}}}),H=h().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:J.loginDTO}}});class G extends _{constructor(e){super("login",H,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 Q=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"),K=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")}),Z=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:K.optional(),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),Y={role:K,teamMember:Z,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:Q.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:Q.optional(),resetPassword:e.z.boolean().optional(),isActive:e.z.boolean().optional()}),resetPasswordRequest:e.z.object({newPassword:Q.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:Q},X=h().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"}}),ee=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 te{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 te(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 te.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>te.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=ee.safeParse(t);if(!r.success)return void console.error("Invalid TeamMemberJSON:",r.error.flatten());const n=r.data,a=n.role?{id:n.role.id,name:n.role.name,description:n.role.description,access:n.role.access,createdAt:n.role.createdAt,updatedAt:n.role.updatedAt}:void 0;return te.from({id:n.id,name:n.name,identity:n.identity,type:n.type,profileId:n.profileId,roleId:n.roleId,resetPassword:n.resetPassword,isActive:n.isActive,isArchived:n.isArchived,role:a,createdAt:n.createdAt,updatedAt:n.updatedAt})}catch(e){return void console.error("Error parsing TeamMemberJSON:",e)}}static isTeamMemberJSON(e){return ee.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>te.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 re extends _{constructor(e){super("admin",X,e)}async createTeamMember(e){const t=await this.client.createTeamMember({body:e});return this.handleResponse(t,201)}async updateTeamMember(e,t){const r=await this.client.updateTeamMember({params:{id:e},body:t}),n=this.handleResponse(r,200),a=te.from(n);if(!a)throw new Error("Invalid team member data received from server");return a}async archiveTeamMember(e){const t=await this.client.archiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),n=te.from(r);if(!n)throw new Error("Invalid team member data received from server");return n}async unArchiveTeamMember(e){const t=await this.client.unArchiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),n=te.from(r);if(!n)throw new Error("Invalid team member data received from server");return n}async resetTeamMemberPassword(e,t={}){const r=await this.client.resetPassword({params:{id:e},body:t});return this.handleResponse(r,200)}async getAllTeamMembers(e={eager:"role"}){const t=await this.client.getTeamMembers({query:e}),r=this.handleResponse(t,200);return te.createMany(r)}async getTeamMember(e,t={eager:"role"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),n=this.handleResponse(r,200),a=te.from(n);if(!a)throw new Error("Invalid team member data received from server");return a}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=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),n=k.from(r);if(!n)throw new Error("Invalid role data received from server");return n}}var ne;exports.BeneficiaryType=void 0,(ne=exports.BeneficiaryType||(exports.BeneficiaryType={})).Bank="Bank",ne.Mobile="Mobile";const ae=e.z.nativeEnum(exports.BeneficiaryType),oe=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:ae}),se={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(oe),beneficiaryInputDTO:oe,beneficiaryType:ae},ie=e.z.object({type:e.z.literal(exports.BeneficiaryType.Mobile),name:e.z.string().min(1),phoneNumber:r.E164PhoneNumberFormatSchema,mnoId:r.MobileMoneyProviderIdSchema,_version:e.z.string().optional().default("1.0")}),ce=e.z.object({type:e.z.literal(exports.BeneficiaryType.Bank),accName:e.z.string().min(1),swiftCode:e.z.union([r.TZBankSWIFTCodeSchema,r.KEBankSWIFTCodeSchema]),countryCode:r.ISO2CountryCodeSchema,accNo:e.z.string().min(1),_version:e.z.string().optional().default("1.0")}),ue=e.z.discriminatedUnion("type",[ie,ce]);class de extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="BeneficiaryError"}}class le{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 pe extends le{name;phoneNumber;mnoId;constructor(e,t,r){super(exports.BeneficiaryType.Mobile,t.countryCode),this.name=e,this.phoneNumber=t;const n=pe.resolveMnoId(t,r),a=pe.checkInputs(e,t,n);if(!a.isValid)throw new de(a.errors[0],{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format,mnoId:n});this.mnoId=n}static resolveMnoId(e,t){return r.MobileMoneyProviderHelpers.requiresExplicitProvider(e.countryCode)?t:r.MobileMoneyProviderHelpers.detectProviderByPhoneNumber(e)?.id}static checkInputs(e,t,n){const a=[];return e?.trim()||a.push("Name is required and cannot be empty"),t?.validate()||a.push("Invalid phone number"),n?r.MobileMoneyProviderHelpers.validateProviderForPhoneNumber(t,n)||a.push(`Invalid MNO ${n} for phone number ${t.e164Format}`):a.push(r.MobileMoneyProviderHelpers.requiresExplicitProvider(t.countryCode)?`MNO must be explicitly provided for phone numbers in ${t.countryCode}`:`Failed to determine MNO for phone number ${t.e164Format}`),{isValid:0===a.length,errors:a,warnings:[]}}static pickMnoIdFromDTO(e,t){if(r.MobileMoneyProviderHelpers.requiresExplicitProvider(e.countryCode)){if("string"!=typeof t)return;return r.MobileMoneyProviderHelpers.isProviderSupported(e.countryCode,t)?t:void console.warn(`Invalid MNO ${t} for country ${e.countryCode}`)}const n=r.MobileMoneyProviderHelpers.detectProviderByPhoneNumber(e);if(n)return n.id;console.warn(`Failed to auto-detect MNO for phone number ${e.e164Format}`)}static from(e){try{return new pe(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==exports.BeneficiaryType.Mobile)return;const t=e.accountNo.startsWith("+")?e.accountNo:`+${e.accountNo}`,n=r.PhoneNumber.from(t);if(!n)return void console.error(`Failed to parse phone number ${t}`);const a=pe.pickMnoIdFromDTO(n,e.channel);return a?pe.from({name:e.displayName,phoneNumber:n,mnoId:a}):void 0}static fromBeneficiaryDTO(e){return pe.fromInputDTO(e)}static fromPayoutDTO(e){if(!r.CountryHelpers.isISO2Code(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}`);const n=pe.pickMnoIdFromDTO(t,e.channel);return n?pe.from({name:e.payeeName,phoneNumber:t,mnoId:n}):void 0}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===exports.BeneficiaryType.Mobile&&(!("string"!=typeof t.name||!t.name.trim())&&(!!r.PhoneNumber.is(t.phoneNumber)&&("string"==typeof t.mnoId&&r.MobileMoneyProviderHelpers.isProviderSupported(t.phoneNumber.countryCode,t.mnoId))))}validate(){return pe.checkInputs(this.name,this.phoneNumber,this.mnoId).isValid}getValidationDetails(){return pe.checkInputs(this.name,this.phoneNumber,this.mnoId)}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.MobileMoneyProviderHelpers.findById(this.mnoId,this.countryCode);return e?.mobileMoneyServiceName??e?.displayName??this.mnoId}get mobileMoneyProvider(){return r.MobileMoneyProviderHelpers.findById(this.mnoId,this.countryCode)}toJSON(){return{type:exports.BeneficiaryType.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,n=ie.safeParse(t);if(!n.success)return void console.error("Invalid MobileBeneficiaryJSON:",n.error.flatten());const a=r.PhoneNumber.from(n.data.phoneNumber);if(!a)return;return pe.from({name:n.data.name,phoneNumber:a,mnoId:n.data.mnoId})}catch(e){return void console.error("Error parsing MobileBeneficiaryJSON:",e)}}static fromJSONString(e){return pe.fromJSON(e)}static isJSON(e){return ie.safeParse(e).success}}class he extends le{accName;bank;accNo;constructor(e,t,r){super(exports.BeneficiaryType.Bank,t.countryCode),this.accName=e,this.bank=t,this.accNo=r;const n=he.checkInputs(e,t,r);if(!n.isValid)throw new de(n.errors[0],{operation:"constructor",countryCode:t.countryCode})}static checkInputs(e,t,n){const a=[];return r.BankHelpers.validateAccountName(e)||a.push("Invalid account name"),r.Bank.is(t)?r.BankHelpers.validateAccountNumber(n,t.countryCode)||a.push("Invalid account number"):a.push("Invalid bank reference"),{isValid:0===a.length,errors:a,warnings:[]}}static from(e){try{return new he(e.accName,e.bank,e.accNo)}catch(e){return void console.error("Failed to create BankBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==exports.BeneficiaryType.Bank)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank beneficiaries");const n=r.BankHelpers.getCountryFromSwiftCode(t);if(!n)return void console.error(`Could not identify country from SWIFT code: ${t}`);const a=r.Bank.fromBIC(t,n);if(a)return he.from({accName:e.displayName,bank:a,accNo:e.accountNo});console.error(`Bank with SWIFT code ${t} not found`)}static fromBeneficiaryDTO(e){return he.fromInputDTO(e)}static fromPayoutDTO(e){if(!r.CountryHelpers.isISO2Code(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=e.msisdn.trim().split(":");if(2!==t.length)return void console.error("Invalid PayoutDTO format for bank — expected 'swiftcode:accountno'");const[n,a]=t,o=r.Bank.fromBIC(n,e.countryCode);if(o)return he.from({accName:e.payeeName,bank:o,accNo:a});console.error(`Bank with SWIFT code ${n} not found`)}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===exports.BeneficiaryType.Bank&&("string"==typeof t.accName&&("string"==typeof t.accNo&&(!!r.Bank.is(t.bank)&&(r.BankHelpers.validateAccountName(t.accName)&&r.BankHelpers.validateAccountNumber(t.accNo,t.bank.countryCode)))))}validate(){return he.checkInputs(this.accName,this.bank,this.accNo).isValid}getValidationDetails(){return he.checkInputs(this.accName,this.bank,this.accNo)}get accountName(){return this.accName}get accountNumber(){return this.accNo}get accountNameLabel(){return"Acc. Name"}get accountNumberLabel(){return"Bank Acc. No."}get channelLabel(){return"Bank"}get channelId(){return this.bank.bic}get channelName(){return this.bank.shortName}toJSON(){return{type:exports.BeneficiaryType.Bank,accName:this.accName,swiftCode:this.bank.bic,countryCode:this.bank.countryCode,accNo:this.accNo,_version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,n=ce.safeParse(t);if(!n.success)return void console.error("Invalid BankBeneficiaryJSON:",n.error.flatten());const a=n.data;if(!r.CountryHelpers.isISO2Code(a.countryCode))return;const o=r.Bank.fromBIC(a.swiftCode,a.countryCode);if(!o)return;return he.from({accName:a.accName,bank:o,accNo:a.accNo})}catch(e){return void console.error("Error parsing BankBeneficiaryJSON:",e)}}static fromJSONString(e){return he.fromJSON(e)}static isJSON(e){return ce.safeParse(e).success}}class me{static fromInputDTO(e){return me.fromDTO(e)}static fromBeneficiaryDTO(e){return me.fromDTO(e)}static fromPayoutDTO(e){return e.msisdn.includes(":")?he.fromPayoutDTO(e):pe.fromPayoutDTO(e)}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ue.safeParse(t);if(!r.success)return;return"Mobile"===r.data.type?pe.fromJSON(r.data):he.fromJSON(r.data)}catch{return}}static fromJSONString(e){return me.fromJSON(e)}static is(e){return pe.is(e)||he.is(e)}static isJSON(e){return ue.safeParse(e).success}static fromDTO(e){return e.type===exports.BeneficiaryType.Mobile?pe.fromInputDTO(e):he.fromInputDTO(e)}}const ye={fromInputDTO:e=>me.fromInputDTO(e),fromBeneficiaryDTO:e=>me.fromBeneficiaryDTO(e),fromPayoutDTO:e=>me.fromPayoutDTO(e),fromJSON:e=>me.fromJSON(e),fromJSONString:e=>me.fromJSONString(e),is:e=>me.is(e),isJSON:e=>me.isJSON(e)},fe=se.beneficiaryDTO.extend({_version:e.z.string().optional().default("1.0")});class ge{_id;_profileId;_displayName;_accountNo;_channel;_type;_createdAt;_updatedAt;_info;_infoComputed=!1;constructor(e){const t=se.beneficiaryDTO.parse(e);this._id=t.id,this._profileId=t.profileId,this._displayName=t.displayName,this._accountNo=t.accountNo,this._channel=t.channel,this._type=t.type,this._createdAt=t.createdAt,this._updatedAt=t.updatedAt}get id(){return this._id}get profileId(){return this._profileId}get displayName(){return this._displayName}get type(){return this._type}get createdAt(){return new Date(this._createdAt)}get updatedAt(){return new Date(this._updatedAt)}get info(){return this._infoComputed||(this._infoComputed=!0,this._info=me.fromBeneficiaryDTO(this.toDTO())),this._info}get accNo(){const e=this.info;return e?e.accountNumber:this._accountNo}get accName(){return this._displayName}get accNoLabel(){return this.type===exports.BeneficiaryType.Mobile?"Phone Number":this.type===exports.BeneficiaryType.Bank?"Bank Account Number":"Account Number"}get channelLabel(){return this.type===exports.BeneficiaryType.Mobile?"Channel":this.type===exports.BeneficiaryType.Bank?"Bank":"Channel"}get accNameLabel(){return this.type===exports.BeneficiaryType.Mobile?"Full Name":this.type===exports.BeneficiaryType.Bank?"Bank Account Name":"Display Name"}get channelName(){return this.info?.channelName??""}static from(e){try{return new ge(e)}catch(e){return void console.error("Failed to create Beneficiary:",e)}}static create(e){return new ge(e)}static createMany(e){return e.map(e=>new ge(e))}static createSafe(e){return ge.from(e)??null}static canConstruct(e){return se.beneficiaryDTO.safeParse(e).success}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("function"!=typeof t.toJSON)return!1;try{return fe.safeParse(t.toJSON()).success}catch{return!1}}toJSON(){return{...this.toDTO(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=t&&"object"==typeof t&&"data"in t?t.data:t,n=fe.safeParse(r);if(!n.success)return void console.error("Invalid BeneficiaryJSON:",n.error.flatten());const a=n.data,{_version:o,...s}=a;return ge.from(s)}catch(e){return void console.error("Error parsing BeneficiaryJSON:",e)}}static fromJSONString(e){return ge.fromJSON(e)}static isBeneficiaryJSON(e){return fe.safeParse(e).success}toDTO(){return{id:this._id,profileId:this._profileId,displayName:this._displayName,accountNo:this._accountNo,channel:this._channel,type:this._type,createdAt:this._createdAt,updatedAt:this._updatedAt}}}class Ne{canHandle(e){return"Mobile"===e.type&&pe.is(e)}createInput(e){if(pe.is(e))return{type:exports.BeneficiaryType.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile BeneficiaryInfo Info")}}class be{canHandle(e){return"Bank"===e.type&&he.is(e)}createInput(e){if(he.is(e))return{type:exports.BeneficiaryType.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Bank BeneficiaryInfo Info")}}class ve{handlers=[new Ne,new be];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 Se=h().router({createBeneficiary:{method:"POST",path:"/",body:se.beneficiaryInputDTO,responses:{201:se.beneficiaryDTO}},editBeneficiary:{method:"PATCH",path:"/:id",body:se.beneficiaryInputDTO,responses:{200:se.beneficiaryDTO}},getBeneficiaries:{method:"GET",path:"/",query:e.z.object({orderByDesc:e.z.string()}),responses:{200:e.z.array(se.beneficiaryDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:se.beneficiaryDTO}},deleteBeneficiary:{method:"DELETE",path:"/:id",body:e.z.object({}),responses:{200:e.z.object({})}}});var Ie,we,Ae;exports.PayoutChannel=void 0,(Ie=exports.PayoutChannel||(exports.PayoutChannel={})).MOBILE="Mobile",Ie.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,(Ae=exports.PayoutApprovalStatus||(exports.PayoutApprovalStatus={})).PENDING="Pending",Ae.APPROVED="Approved",Ae.REJECTED="Rejected";const _e=e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string()}),Oe=e.z.nativeEnum(exports.PayoutStatus),Ce=e.z.nativeEnum(exports.PayoutApprovalStatus),Pe=e.z.union([e.z.string(),e.z.array(e.z.string())]).transform(e=>(Array.isArray(e)?e:[e]).flatMap(e=>e.split(",")).map(e=>e.trim()).filter(e=>e.length>0)),ze=Pe.pipe(e.z.array(Oe)),Be=Pe.pipe(e.z.array(Ce)),Te=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()}),Ee=Te.extend({payeeName:e.z.string()}),De=Te.extend({id:e.z.string(),profileId:e.z.string(),payeeName:e.z.string(),countryCode:e.z.string().default("TZ").refine(e=>r.CountryHelpers.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>r.CurrencyHelpers.isCode(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:Ce.nullish(),createdById:e.z.string().nullish(),actionedById:e.z.string().nullish(),createdBy:_e.nullish(),actionedBy:_e.nullish()}),xe=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(),msisdnIn:Pe.nullish(),profileId:e.z.string().nullish(),id:e.z.string().nullish(),partnerReference:e.z.string().nullish(),channel:e.z.string().nullish(),channelIn:Pe.nullish(),currencyCode:e.z.string().nullish(),status:Oe.nullish(),statusIn:ze.nullish(),approvalStatus:Ce.nullish(),approvalStatusIn:Be.nullish(),createdById:e.z.string().nullish(),createdByIdIn:Pe.nullish(),actionedById:e.z.string().nullish(),actionedByIdIn:Pe.nullish(),minAmount:e.z.number().min(0).nullish(),maxAmount:e.z.number().min(0).nullish(),search:e.z.string().nullish()}),Re={PayoutDTO:De,PayoutInputDTO:Ee,PayoutStatus:Oe,PayoutApprovalStatus:Ce,PayoutAuthorizer:_e,PayoutFilters:xe,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(),msisdnIn:Pe.optional(),profileId:e.z.string().optional(),id:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:e.z.string().optional(),channelIn:Pe.optional(),status:e.z.string().refine(e=>Object.values(exports.PayoutStatus).includes(e)).transform(e=>e).optional(),statusIn:ze.optional(),approvalStatus:e.z.string().refine(e=>Object.values(exports.PayoutApprovalStatus).includes(e)).transform(e=>e).optional(),approvalStatusIn:Be.optional(),createdById:e.z.string().optional(),createdByIdIn:Pe.optional(),actionedById:e.z.string().optional(),actionedByIdIn:Pe.optional(),minAmount:e.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:e.z.string().transform(e=>parseFloat(e)).optional(),search:e.z.string().optional()})},Je=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:Re.PayoutStatus,statusMessage:a.default.string(),partnerReference:a.default.string().nullish(),createdAt:a.default.string(),updatedAt:a.default.string(),actionedAt:a.default.string().nullish(),approvalStatus:Re.PayoutApprovalStatus.nullish(),createdById:a.default.string().nullish(),actionedById:a.default.string().nullish(),createdBy:Re.PayoutAuthorizer.nullish(),actionedBy:Re.PayoutAuthorizer.nullish(),_version:a.default.string().optional().default("1.0")});class Me{_id;_profileId;_payeeName;_channel;_msisdn;_amount;_currencyCode;_countryCode;_description;_notes;_status;_statusMessage;_partnerReference;_createdAt;_updatedAt;_actionedAt;_approvalStatus;_createdById;_actionedById;_createdBy;_actionedBy;constructor(e){const t=Re.PayoutDTO.parse(e);this._id=t.id,this._profileId=t.profileId,this._payeeName=t.payeeName,this._channel=t.channel,this._msisdn=t.msisdn,this._amount=t.amount,this._currencyCode=t.currencyCode,this._countryCode=t.countryCode,this._description=t.description,this._notes=t.notes,this._status=t.status,this._statusMessage=t.statusMessage,this._partnerReference=t.partnerReference,this._createdAt=t.createdAt,this._updatedAt=t.updatedAt,this._actionedAt=t.actionedAt,this._approvalStatus=t.approvalStatus,this._createdById=t.createdById,this._actionedById=t.actionedById,this._createdBy=t.createdBy,this._actionedBy=t.actionedBy}get id(){return this._id}get profileId(){return this._profileId}get payeeName(){return this._payeeName}get channel(){return this._channel}get msisdn(){return this._msisdn}get amount(){return r.Amount.from(this._amount,this._currencyCode)}get description(){return this._description}get notes(){return this._notes}get status(){return"Rejected"===this._approvalStatus?exports.PayoutStatus.REJECTED:"Approved"===this._approvalStatus?"FAILED"===this._status?exports.PayoutStatus.FAILED:exports.PayoutStatus.PAID:"Pending"===this._approvalStatus?exports.PayoutStatus.PENDING:this._status}get statusMessage(){return this._statusMessage}get partnerReference(){return this._partnerReference}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get actionedAt(){return this._actionedAt}get approvalStatus(){return this._approvalStatus}get createdById(){return this._createdById}get actionedById(){return this._actionedById}get createdBy(){return this._createdBy}get actionedBy(){return this._actionedBy}get beneficiaryInfo(){return me.fromPayoutDTO(this.toDTO())}get contactInfo(){return this.beneficiaryInfo}static create(e){return new Me(e)}static createMany(e){return e.map(e=>new Me(e))}static createSafe(e){try{return new Me(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=Re.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==Me.createSafe(t.data)}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("function"!=typeof t.toJSON)return!1;try{return Je.safeParse(t.toJSON()).success}catch{return!1}}toJSON(){return{id:this._id,profileId:this._profileId,payeeName:this._payeeName,channel:this._channel,msisdn:this._msisdn,amount:this._amount,currencyCode:this._currencyCode,countryCode:this._countryCode,description:this._description,notes:this._notes,status:this._status,statusMessage:this._statusMessage,partnerReference:this._partnerReference,createdAt:this._createdAt.toISOString(),updatedAt:this._updatedAt.toISOString(),actionedAt:this._actionedAt?.toISOString()??null,approvalStatus:this._approvalStatus,createdById:this._createdById,actionedById:this._actionedById,createdBy:this._createdBy,actionedBy:this._actionedBy,_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,n=Je.safeParse(t);if(!n.success)return void console.error("Invalid PayoutJSON:",n.error.flatten());const a=n.data,o=a.currencyCode;if(!r.CurrencyHelpers.isCode(o))return void console.error("Invalid currency code:",o);const s=a.countryCode;if(!r.CountryHelpers.isISO2Code(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:o,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,createdById:a.createdById,actionedById:a.actionedById,createdBy:a.createdBy,actionedBy:a.actionedBy};return Me.create(i)}catch(e){return void console.error("Error parsing PayoutJSON:",e)}}static isPayoutJSON(e){return Je.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>Me.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing Payout JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}toDTO(){return{id:this._id,profileId:this._profileId,payeeName:this._payeeName,channel:this._channel,msisdn:this._msisdn,amount:this._amount,currencyCode:this._currencyCode,countryCode:this._countryCode,description:this._description,notes:this._notes,status:this._status,statusMessage:this._statusMessage,partnerReference:this._partnerReference,createdAt:this._createdAt,updatedAt:this._updatedAt,actionedAt:this._actionedAt,approvalStatus:this._approvalStatus,createdById:this._createdById,actionedById:this._actionedById,createdBy:this._createdBy,actionedBy:this._actionedBy}}}const je="MOBILE TRANSFER ",Fe="PAYOUT",ke="PAYOUT TO BANK",Le="TO_BANK",Ue="PAYOUT TO MOBILE",$e="TO_MOMO",qe=a.default.object({text:a.default.string(),_version:a.default.string().optional().default("2.0")});class Ve{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 pe.is(e)?Ve.generateMobilePayoutNarrationV2(e):he.is(e)?Ve.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${Fe.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:n}=e;return`${Fe.toUpperCase()} ${t.bic.trim()} ${n.trim()} ${r.trim()}`.toUpperCase()}getBeneficiaryDetails=()=>{const e=this.getBankBeneficiaryDetails(),t=this.getMobileBeneficiaryDetails();return e||(t||void 0)};getBankBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(je)&&(e=e.substring(16));try{if(e.startsWith(Fe)){const t=e.replace(Fe,"").trim().split(" ");if(t.length>=3){const e=t[0],n=t[1],a=t.slice(2).map(We).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=r.BankHelpers.getCountryFromSwiftCode(e);if(t){if(r.BankHelpers.validateSwiftCode(e,t)){const o=r.Bank.fromBIC(e,t);if(n&&a&&o)return new he(a,o,n)}}}}}if(e.startsWith(Le)){const t=e.split("=>")[1].trim(),n=JSON.parse(t),a=n.account_number,o=n.account_name,s=n.swift_code,i=r.BankHelpers.getCountryFromSwiftCode(s);if(!i)return;if(!r.BankHelpers.validateSwiftCode(s,i))return;const c=r.Bank.fromBIC(s,i);if(a&&o&&c)return new he(o,c,a)}if(e.startsWith(ke)){const t=e.replace(ke,"").trim().split(" "),n=r.BankRegistry.getInstance().searchBanks("TZ",t[0]),a=n.length>0?n[0]:void 0,o=t[1],s=t.slice(2).map(We).join(" ");if(s&&o&&a)return new he(s,a,o)}}catch(e){return}};getMobileBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(je)&&(e=e.substring(16));try{if(e.startsWith(Fe)){const t=e.replace(Fe,"").trim().split(" ");if(t.length>=2){const e=t[0],n=t.slice(1).map(We).join(" ");if(e.startsWith("+")){const t=r.PhoneNumber.from(e);if(t&&n)return new pe(n,t)}}}if(e.startsWith($e)){const t=e.split("=>")[1].trim(),n=JSON.parse(t),a=r.PhoneNumber.from(n.phone_number,{defaultCountry:"TZ"});let o=n.username;void 0===o&&(o="");let s=o.split(" ");if(s=s.filter(e=>e.trim().length>0),o=s.map(We).join(" "),a&&o)return new pe(o,a)}if(e.startsWith(Ue)){const t=e.replace(Ue,"").trim().split(" "),n=r.PhoneNumber.from(t[0],{defaultCountry:"TZ"}),a=t.slice(1).map(We).join(" ");if(n&&a)return new pe(a,n)}}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=qe.safeParse(t);if(!r.success)return void console.error("Invalid NarrationJSON:",r.error.flatten());const n=r.data;return new Ve(n.text)}catch(e){return void console.error("Error parsing NarrationJSON:",e)}}static isNarrationJSON(e){return qe.safeParse(e).success}toJson(){return this.toJSON()}static fromJson(e){return Ve.fromJSON(e)}}function We(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}const He={SUPPORTED_COUNTRY_CODES:["TZ","KE"],ERROR_MESSAGES:{INVALID_PHONE_NUMBER:"Invalid phone number",INELIGIBLE_FOR_PAYOUT:"The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",MOBILE_NUMBER_MNO_MISMATCH:"There is a mismatch between the phone number provided and the MNO used.",UNSUPPORTED_COUNTRY_BANK:"Only TZ and KE banks are supported for now",UNSUPPORTED_COUNTRY_MOBILE:"Only TZ and KE mobile numbers are supported for now",NO_HANDLER_FOUND:"Cannot create payout input!"}};class Ge{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}static isPhoneEligibleForPayout(e){const t=e.getNumberType();return t===r.PhoneNumberType.MOBILE||t===r.PhoneNumberType.FIXED_LINE_OR_MOBILE}}class Qe{static forBank(e,t){if(!He.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(He.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,t,n){if(!r.PhoneNumber.is(e))throw new Error(He.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!He.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(He.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!Ge.isPhoneEligibleForPayout(e))throw new Error(He.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const a=r.MobileMoneyProviderHelpers.findById(t,e.countryCode);if(!a)throw new Error(He.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return"VODACOM"===a.id?`${n.countryCode}-TIGO-B2C`:`${n.countryCode}-${a.id}-B2C`}}class Ke{canHandle(e,t,n){return e===exports.PayoutChannel.MOBILE&&pe.is(t)&&n.countryCode===t.countryCode&&n.currencyCode===r.Country.fromCode(t.countryCode)?.currencyCode}createInput(e,t){const n=e.receiver,a=Ge.processNotes(e.notes),o=n.phoneNumber;return{channel:Qe.forMobile(o,n.mnoId,t),msisdn:o.getWithFormat(r.PhoneNumberFormat.INTERNATIONAL_NUMERIC),description:a??Ve.generateDefaultPayoutNarration(n),payeeName:n.name,notes:a,amount:e.amount.numericValue}}}class Ze{canHandle(e,t,n){return e===exports.PayoutChannel.BANK&&he.is(t)&&n.countryCode===t.countryCode&&n.currencyCode===r.Country.fromCode(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=Ge.processNotes(e.notes);return{channel:Qe.forBank(r,t),msisdn:`${r.bank.bic}:${r.accNo}`,description:n??Ve.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:n,amount:e.amount.numericValue}}}class Ye{handlers=[new Ke,new Ze];getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(He.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const Xe={bank:Qe.forBank.bind(Qe),mobile:Qe.forMobile.bind(Qe)},et=h().router({getPayouts:{method:"GET",path:"",query:e.z.object({}),responses:{200:e.z.object({results:e.z.array(Re.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:Re.PayoutApprovalStatus,orderByDesc:e.z.string()}),responses:{200:e.z.object({results:e.z.array(Re.PayoutDTO),total:e.z.number()})}},postPayout:{method:"POST",path:"",body:Re.PayoutInputDTO,responses:{201:Re.PayoutDTO,400:o.schema}},approve:{method:"POST",path:"/:id/approve",body:e.z.object({action:e.z.enum(["Approve","Reject"]),notes:e.z.string().optional()}),responses:{201:Re.PayoutDTO,400:o.schema,401:o.schema,404:e.z.object({}),409:e.z.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:Re.PayoutDTO,404:e.z.object({})}}}),tt=["approvalStatus","status","channel","msisdn","createdById","actionedById"];class rt extends z{static create(){return new rt}static fromFilters(e){return(new rt).applyFilters(e)}static fromUrlParams(e){try{const t=Re.PayoutURLQueryParams.parse(this.normalizeUrlParams(e)),r=Re.PayoutFilters.parse(t);return rt.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return rt.fromUrlParams(this.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return rt.fromSearchParams(t)}static from(e){try{return null==e?new rt:z.is(e)?new rt(e.options):e instanceof URLSearchParams?rt.fromSearchParams(e):this.isUrlParamsRecord(e)?rt.fromUrlParams(e):rt.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a PayoutQuery instance.")}}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static normalizeUrlParams(e){const t={...e};for(const e of tt){const r=e,n=`${e}In`,a=`${e}:in`,o=`${e}[]`,s=`${e}In[]`,i=t[r],c=rt.toStringList([t[n],t[a],t[o],t[s],Array.isArray(i)?i:void 0]);c.length>0&&(t[n]=c),Array.isArray(i)&&delete t[r],delete t[a],delete t[o],delete t[s]}return t}static toStringList(e){const t=Array.isArray(e)?e.flatMap(e=>rt.toStringList(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))}whereStatus(e){return this.where("status",e)}whereStatusIn(e){return this.whereInValues("status",e)}whereApprovalStatus(e){return this.where("approvalStatus",e)}whereApprovalStatusIn(e){return this.whereInValues("approvalStatus",e)}whereChannel(e){return this.where("channel",e)}whereChannelIn(e){return this.whereInValues("channel",e)}wherePending(){return this.whereApprovalStatus(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)}wherePayee(e){return this.whereContains("payeeName",e)}whereMsisdn(e){return this.whereContains("msisdn",e)}whereMsisdnIn(e){return this.whereInValues("msisdn",e)}whereProfileId(e){return this.where("profileId",e)}whereCreatedById(e){return this.where("createdById",e)}whereCreatedByIdIn(e){return this.whereInValues("createdById",e)}whereActionedById(e){return this.where("actionedById",e)}whereActionedByIdIn(e){return this.whereInValues("actionedById",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){if((e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.statusIn?.length?this.whereStatusIn(e.statusIn):e.status&&this.whereStatus(e.status),e.approvalStatusIn?.length?this.whereApprovalStatusIn(e.approvalStatusIn):e.approvalStatus&&this.whereApprovalStatus(e.approvalStatus),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.payeeName&&this.wherePayee(e.payeeName),e.msisdnIn?.length?this.whereMsisdnIn(e.msisdnIn):e.msisdn&&this.whereMsisdn(e.msisdn),e.profileId&&this.whereProfileId(e.profileId),e.createdByIdIn?.length?this.whereCreatedByIdIn(e.createdByIdIn):e.createdById&&this.whereCreatedById(e.createdById),e.actionedByIdIn?.length?this.whereActionedByIdIn(e.actionedByIdIn):e.actionedById&&this.whereActionedById(e.actionedById),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.id&&this.where("id",e.id),void 0!==e.minAmount||void 0!==e.maxAmount){const t=void 0!==e.minAmount&&null!==e.minAmount,n=void 0!==e.maxAmount&&null!==e.maxAmount,{currencyCode:a}=e,o=a||"TZS";if(!r.CurrencyHelpers.isCode(o))return console.warn("Amount filter requires a valid currency code"),this;if(t&&n){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,o),n=r.Amount.from(e.maxAmount,o);t&&n&&this.whereAmountBetween(t,n)}else t?this.whereGreaterThanOrEqual("amount",e.minAmount):n&&this.whereLessThanOrEqual("amount",e.maxAmount)}return e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,payeeName:e.payeeName,msisdn:e.msisdn,msisdnIn:e.msisdnIn,profileId:e.profileId,createdById:e.createdById,createdByIdIn:e.createdByIdIn,actionedById:e.actionedById,actionedByIdIn:e.actionedByIdIn,id:e.id,partnerReference:e.partnerReference,channel:e.channel,channelIn:e.channelIn,status:this.isValidStatus(e.status)?e.status:void 0,statusIn:this.getValidStatuses(e.statusIn),approvalStatus:this.isValidApprovalStatus(e.approvalStatus)?e.approvalStatus:void 0,approvalStatusIn:this.getValidApprovalStatuses(e.approvalStatusIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(Array.isArray(r)?r.length>0&&(t[e]=r.join(",")):t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withStatusIn(e){const t=this.clone();return e?.length&&t.whereStatusIn(e),t}withApprovalStatus(e){const t=this.clone();return e&&t.whereApprovalStatus(e),t}withApprovalStatusIn(e){const t=this.clone();return e?.length&&t.whereApprovalStatusIn(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}withChannelIn(e){const t=this.clone();return e?.length&&t.whereChannelIn(e),t}withMsisdnIn(e){const t=this.clone();return e?.length&&t.whereMsisdnIn(e),t}withCreatedById(e){const t=this.clone();return e&&t.whereCreatedById(e),t}withCreatedByIdIn(e){const t=this.clone();return e?.length&&t.whereCreatedByIdIn(e),t}withActionedById(e){const t=this.clone();return e&&t.whereActionedById(e),t}withActionedByIdIn(e){const t=this.clone();return e?.length&&t.whereActionedByIdIn(e),t}includeDefaultRelations(){return this.with("[createdBy,actionedBy]")}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.payeeName||e.msisdn||e.msisdnIn?.length||e.profileId||e.createdById||e.createdByIdIn?.length||e.actionedById||e.actionedByIdIn?.length||e.id||e.partnerReference||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.approvalStatus||e.approvalStatusIn?.length||e.minAmount||e.maxAmount||e.search)}describeFilters(e){const t=[],n=this.toFilters(),a=e?.formatDate??(e=>e);if(n.sortBy){const e="asc"===n.sortOrder?"Ascending":"Descending";t.push({label:"Sort",value:`${this.formatSortField(n.sortBy)} (${e})`})}if(n.startDate&&n.endDate?t.push({label:"Date Range",value:`${a(n.startDate)} — ${a(n.endDate)}`}):n.startDate?t.push({label:"From",value:a(n.startDate)}):n.endDate&&t.push({label:"Until",value:a(n.endDate)}),n.statusIn?.length?t.push({label:"Status",value:n.statusIn.join(", ")}):n.status&&t.push({label:"Status",value:n.status}),n.approvalStatusIn?.length?t.push({label:"Approval Status",value:n.approvalStatusIn.join(", ")}):n.approvalStatus&&t.push({label:"Approval Status",value:n.approvalStatus}),n.channelIn?.length?t.push({label:"Channel",value:n.channelIn.join(", ")}):n.channel&&t.push({label:"Channel",value:n.channel}),void 0!==n.minAmount&&void 0!==n.maxAmount){const e=Number(n.minAmount),a=Number(n.maxAmount);if(Number.isFinite(e)&&Number.isFinite(a)){const n=r.Amount.from(e,"TZS"),o=r.Amount.from(a,"TZS");n&&o&&t.push({label:"Amount Range",value:`${n.label} — ${o.label}`})}}else if(void 0!==n.minAmount){const e=Number(n.minAmount);if(Number.isFinite(e)){const n=r.Amount.from(e,"TZS");n&&t.push({label:"Minimum Amount",value:n.label})}}else if(void 0!==n.maxAmount){const e=Number(n.maxAmount);if(Number.isFinite(e)){const n=r.Amount.from(e,"TZS");n&&t.push({label:"Maximum Amount",value:n.label})}}return n.search&&t.push({label:"Search",value:`"${n.search}"`}),n.payeeName&&t.push({label:"Beneficiary Name",value:n.payeeName}),n.msisdnIn?.length?t.push({label:"MSISDN",value:n.msisdnIn.join(", ")}):n.msisdn&&t.push({label:"MSISDN",value:n.msisdn}),n.profileId&&t.push({label:"Profile",value:n.profileId}),n.createdByIdIn?.length?t.push({label:"Created By ID",value:n.createdByIdIn.join(", ")}):n.createdById&&t.push({label:"Created By ID",value:n.createdById}),n.actionedByIdIn?.length?t.push({label:"Actioned By ID",value:n.actionedByIdIn.join(", ")}):n.actionedById&&t.push({label:"Actioned By ID",value:n.actionedById}),n.partnerReference&&t.push({label:"Reference",value:n.partnerReference}),t}describeFiltersAsText(){return this.describeFilters().map(e=>`${e.label}: ${e.value}`)}formatSortField(e){return{createdAt:"Date Created",updatedAt:"Date Updated",amount:"Amount",payeeName:"Beneficiary Name",approvalStatus:"Approval Status",status:"Status",channel:"Channel",msisdn:"MSISDN",createdById:"Created By ID",actionedById:"Actioned By ID"}[e]??e}build(){return super.build()}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=rt.toStringList(t.value);r.length>0&&(e[`${t.field}In`]=r);continue}switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"payeeName":case"msisdn":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}}return e}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}whereInValues(e,t){const r=rt.toStringList(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=rt.toStringList(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidApprovalStatuses(e){const t=rt.toStringList(e).filter(e=>this.isValidApprovalStatus(e));return t.length>0?t:void 0}isValidStatus(e){return Object.values(exports.PayoutStatus).includes(e)}isValidApprovalStatus(e){return Object.values(exports.PayoutApprovalStatus).includes(e)}}const nt=e=>e.optional().transform(e=>e??void 0),at={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.CountryHelpers.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>r.CurrencyHelpers.isCode(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.fromCode(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:nt(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:nt(e.z.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})},ot=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 st{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return at.walletDTO}constructor(e){this._id=e.id,this._profileId=e.profileId,this._accountNo=e.accountNo,this._accountName=e.accountName,this._channel=e.channel,this._countryCode=e.countryCode,this._currencyCode=e.currencyCode,this._createdAt=e.createdAt,this._updatedAt=e.updatedAt}static create(e){const t=st.schema.safeParse(e);if(t.success)return new st(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=st.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 st.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.CountryHelpers.isISO2Code(t._countryCode)&&"string"==typeof t._currencyCode&&r.CurrencyHelpers.isCode(t._currencyCode)&&"string"==typeof t._createdAt&&"string"==typeof t._updatedAt}toJSON(){return{id:this._id,profileId:this._profileId,accountNo:this._accountNo,accountName:this._accountName,channel:this._channel,countryCode:this._countryCode,currencyCode:this._currencyCode,createdAt:this._createdAt,updatedAt:this._updatedAt,_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ot.safeParse(t);if(!r.success)return void console.error("Invalid WalletJSON:",r.error.flatten());const n=r.data;return st.create(n)}catch(e){return void console.error("Error parsing WalletJSON:",e)}}static isWalletJSON(e){return ot.safeParse(e).success}}const it=a.default.object({accountNo:a.default.string().optional(),debitOrCredit:a.default.string(),tranRefNo:a.default.string(),narration:qe,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 ct{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return at.statementEntry}constructor(e,t){this._accountNo=e.accountNo,this._debitOrCredit=e.debitOrCredit,this._tranRefNo=e.tranRefNo,this._narration=t,this._txnDate=e.txnDate,this._valueDate=e.valueDate,this._currencyCode=e.currencyCode;const n=r.Currency.fromCode(e.currencyCode);if(!n)throw new Error(`Currency not found for code: ${e.currencyCode}`);const a=r.Amount.from(e.amountCredited,n.code),o=r.Amount.from(e.amountDebited,n.code),s=r.Amount.from(e.balance,n.code);if(!a||!o||!s)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=a,this._amountDebited=o,this._balance=s}static create(e){const t="string"==typeof e.narration?new Ve(e.narration):e.narration,r={...e,narration:t.text},n=ct.schema.safeParse(r);if(n.success)try{const{narration:e,...r}=n.data;return new ct(r,t)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",n.error.flatten())}get accountNo(){return this._accountNo}get debitOrCredit(){return this._debitOrCredit}get tranRefNo(){return this._tranRefNo}get narration(){return this._narration}get txnDate(){return this._txnDate}get valueDate(){return this._valueDate}get amountCredited(){return this._amountCredited}get amountDebited(){return this._amountDebited}get balance(){return this._balance}get currencyCode(){return this._currencyCode}validate(){const e={accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.text,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode},t=ct.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&&Ve.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 ct.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,n,a,o,s=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const o=r.Amount.fromJSON(e.amountCredited),i=r.Amount.fromJSON(e.amountDebited),c=r.Amount.fromJSON(e.balance);if(!o||!i||!c)return void console.error("Failed to deserialize Amount objects from JSON");t=o.numericValue,n=i.numericValue,a=c.numericValue,e.currencyCode||(s=o.currencyCode)}else if(t=Number(e.amountCredited),n=Number(e.amountDebited),a=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(a))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)o=e.narration;else if(Ve.is(e.narration))o=e.narration;else{if(!Ve.isNarrationJSON(e.narration))return void console.error("Invalid narration data");{const t=Ve.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");o=t}}return ct.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:o,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:n,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,n=it.safeParse(t);if(!n.success)return void console.error("Invalid WalletStatementEntryJSON:",n.error.flatten());const a=n.data,o=Ve.fromJSON(a.narration);if(!o)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"):ct.create({accountNo:a.accountNo,debitOrCredit:a.debitOrCredit,tranRefNo:a.tranRefNo,narration:o,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 it.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>ct.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 ct.fromJSON(e)}static fromJsonArray(e){return ct.fromJSONArray(e)}static toJsonArray(e){return ct.toJSONArray(e)}}const ut=h().router({getWallets:{method:"GET",path:"/",query:at.walletQuery,responses:{200:e.z.array(st.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(ct.schema)}}});class dt extends z{static create(){return new dt}static fromFilters(e){return(new dt).applyFilters(e)}static fromUrlParams(e){try{const t=at.walletQuery.parse(e);return dt.fromFilters(t)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return dt.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return dt.fromSearchParams(t)}static from(e){try{return null==e?new dt:z.is(e)?new dt(e.options):e instanceof URLSearchParams?dt.fromSearchParams(e):this.isStringRecord(e)?dt.fromUrlParams(e):dt.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a WalletQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereId(e){return this.where("id",e)}whereProfileId(e){return this.where("profileId",e)}whereAccountNo(e){return this.where("accountNo",e)}whereAccountName(e){return this.whereContains("accountName",e)}whereChannel(e){return this.where("channel",e)}whereCountryCode(e){return this.where("countryCode",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){return e.id&&this.whereId(e.id),e.profileId&&this.whereProfileId(e.profileId),e.accountNo&&this.whereAccountNo(e.accountNo),e.accountName&&this.whereAccountName(e.accountName),e.channel&&this.whereChannel(e.channel),e.countryCode&&this.whereCountryCode(e.countryCode),e.currencyCode&&this.whereCurrencyCode(e.currencyCode),this}toFilters(){const e=this.extractFilterValues();return{id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,currencyCode:e.currencyCode}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withId(e){const t=this.clone();return t.whereId(e),t}withProfileId(e){const t=this.clone();return t.whereProfileId(e),t}withAccountNo(e){const t=this.clone();return t.whereAccountNo(e),t}withCountryCode(e){const t=this.clone();return t.whereCountryCode(e),t}withCurrencyCode(e){const t=this.clone();return t.whereCurrencyCode(e),t}hasFilters(){const e=this.toFilters();return!!(e.id||e.profileId||e.accountNo||e.accountName||e.channel||e.countryCode||e.currencyCode)}getActiveFilters(){const e=[],t=this.toFilters();return t.id&&e.push(`ID: ${t.id}`),t.profileId&&e.push(`Profile: ${t.profileId}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.accountName&&e.push(`Name: ${t.accountName}`),t.channel&&e.push(`Channel: ${t.channel}`),t.countryCode&&e.push(`Country: ${t.countryCode}`),t.currencyCode&&e.push(`Currency: ${t.currencyCode}`),e}build(){return super.build()}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)"eq"===t.operator?e[t.field]=t.value:"likeLower"===t.operator&&"string"==typeof t.value&&(e[t.field]=t.value.replace(/%/g,""));return e}}const lt={getUniqueCountries(e){const t=new Set;return e.forEach(e=>{e.countryCode&&t.add(e.countryCode)}),Array.from(t)},getWalletsByCountry:(e,t)=>e.filter(e=>e.countryCode===t)},pt=h().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:R.schema}}});exports.APIError=o,exports.AuthDTOSchemas=V,exports.AuthRepository=class extends _{constructor(e){super("auth",W,e)}async logIn(e,t){const r={type:"password",identity:e,password:t},n=await this.client.logIn({body:r});if(400===n.status)throw new o({message:"Invalid email or password",statusCode:400});if(201===n.status){const e=n.body.token,t=new G({token:e}),r=await t.getIdentity(),a=j.from(r);if(!a)throw new o({message:"Failed to construct login credentials",statusCode:502});const i=n.body.profile,c=R.from(i);if(!c)throw new o({message:"Failed to construct user profile",statusCode:502});let u;if(a.can(s.Role.ViewRole))try{const t=new re({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});if(!d)throw new o({message:"Failed to construct user session",statusCode:502});return{token:e,user:d}}throw new o({message:"An error occurred while trying to log in",statusCode:502})}async updatePassword(e,t){const r=await this.client.resetPassword({body:{currentPassword:e,newPassword:t}});if(200===r.status)return!0;if(400===r.status)throw new o({message:"Invalid current password",statusCode:400});throw new o({message:"An error occurred while trying to update password",statusCode:502})}async getAccessList(){const e=await this.client.access();if(200===e.status)return e.body;throw new Error(`Failed to get access list. Status: ${e.status}`)}},exports.BANK_NARR_PREFIX=ke,exports.BankBeneficiaryInfo=he,exports.BankBeneficiaryJSONSchema=ce,exports.BaseRepository=_,exports.Beneficiary=ge,exports.BeneficiaryDTOSchemas=se,exports.BeneficiaryError=de,exports.BeneficiaryInfo=ye,exports.BeneficiaryInfoFactory=me,exports.BeneficiaryInfoJSONSchema=ue,exports.BeneficiaryJSONSchema=fe,exports.BeneficiaryRepository=class extends _{constructor(e){super("contact",Se,e)}async create(e){const t=(new ve).resolve(e),r=await this.client.createBeneficiary({body:t}),n=this.handleResponse(r,201);return ge.create(n)}async edit(e,t){const r=(new ve).resolve(t),n=await this.client.editBeneficiary({params:{id:e},body:r}),a=this.handleResponse(n,200);return ge.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 ge.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return ge.create(r)}},exports.CompanyMembership=U,exports.CompanyMembershipJSONSchema=L,exports.ECOBANK_PREFIX=je,exports.IdentityRepository=G,exports.LEGACY_BANK_NARR_PREFIX=Le,exports.LEGACY_MOBILE_NARR_PREFIX=$e,exports.LogIn=j,exports.LogInJSONSchema=M,exports.LogInSchemas=J,exports.MOBILE_NARR_PREFIX=Ue,exports.MobileBeneficiaryInfo=pe,exports.MobileBeneficiaryJSONSchema=ie,exports.NARR_V2_PREFIX=Fe,exports.Narration=Ve,exports.NarrationJSONSchema=qe,exports.Pagination=E,exports.PaginationParamsSchema=B,exports.PaginationSchema=T,exports.Payout=Me,exports.PayoutDTOSchemas=Re,exports.PayoutInputFactory=Ye,exports.PayoutJSONSchema=Je,exports.PayoutQuery=rt,exports.PayoutRepository=class extends _{constructor(e){super("payout",et,e)}async getPayouts(e){try{const t=rt.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),a=this.handleResponse(n,200),o=t.toFilters(),s=new E(o.page??1,o.limit??10,a.total);return{results:Me.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=rt.from(e).build();delete t.rangeStart,delete t.rangeEnd;const r=await this.client.getPayouts({query:t}),n=this.handleResponse(r,200);return Me.createMany(n)}catch(e){throw console.log("error: ",e),new Error(`Failed to fetch all payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=rt.fromRequest(e);return this.getPayouts(t)}async pay(e){const{wallet:t,channel:n,receiver:a,amount:s,notes:i}=e,c=r.TemboCoverage.getTransactionLimits({countryCode:t.countryCode,currencyCode:s.currencyCode,direction:r.TransactionDirection.PAYOUT,channelType:n===exports.PayoutChannel.BANK?r.ChannelType.BANK:r.ChannelType.MOBILE_MONEY});if(!c)throw new o({statusCode:400,message:`Payout limits are not configured for ${t.countryCode} ${s.currencyCode} ${n} payouts`});const{min:u,max:d}=c;if(s.lessThan(u)||s.greaterThan(d))throw new o({statusCode:400,message:`Please make sure the amount is between ${u.label} - ${d.label}`});const l=(new Ye).getPayoutInput({channel:n,receiver:a,amount:s,notes:i},t),p=await this.client.postPayout({body:l});if(201===p.status)return Me.create(p.body);if(400===p.status)throw new o(p.body);throw o.unknown()}async approve(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Approve",notes:e.notes}});if(201===t.status)return Me.create(t.body);if(401===t.status)throw new o({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new o({message:"Payout not found",statusCode:404});if(409===t.status)throw new o({message:"Payout already approved",statusCode:409});throw o.unknown()}async reject(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Reject",notes:e.notes}});if(201===t.status)return Me.create(t.body);if(401===t.status)throw new o({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new o({message:"Payout not found",statusCode:404});if(409===t.status)throw new o({message:"Payout already rejected",statusCode:409});throw o.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return Me.create(t.body);if(404===t.status)throw new o({message:"Payout not found",statusCode:404});throw o.unknown()}async count(e){const t=rt.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=R,exports.ProfileDTOSchemas=D,exports.ProfileJSONSchema=x,exports.ProfileRepository=class extends _{constructor(e){super("profile",pt,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=R.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=P,exports.QueryBuilder=z,exports.Role=k,exports.RoleJSONSchema=F,exports.TeamManagementDTOSchemas=Y,exports.TeamMember=te,exports.TeamMemberJSONSchema=ee,exports.TeamMemberRepository=re,exports.User=q,exports.UserJSONSchema=$,exports.ValidatedBeneficiaryInputFactory=ve,exports.Wallet=st,exports.WalletDTOSchemas=at,exports.WalletJSONSchema=ot,exports.WalletRepository=class extends _{constructor(e){super("wallet",ut,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 n=t.body.availableBalance,a=r.Amount.from(n,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 n=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,n.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=dt.from(e).build(),r=await this.client.getWallets({query:t});if(200===r.status){const e=r.body;try{return e.map(e=>{const t=st.from(e);if(!t)throw new Error(`Invalid wallet data: ${JSON.stringify(e)}`);return t})}catch(e){throw console.error("[WalletRepository] Error processing wallet data:",e),new Error("Failed to process wallet data from API")}}throw new Error(`Failed to fetch wallets. Status: ${r.status}`)}async getByID(e){const t=dt.create().whereId(e),r=await this.getWallets(t);return r.length>0?r[0]:void 0}async getStatement(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");const t=new Date,r=new Date(t.getFullYear(),t.getMonth(),1),n=new Date(t.getFullYear(),t.getMonth()+1,0),a=e.range??{startDate:r,endDate:n};let o,s;if(e.wallet)o=e.wallet,s=e.wallet.accountNo;else{if(!e.accountNo)throw new Error("Either wallet or accountNo must be provided");{const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);o=t[0],s=e.accountNo}}const i={...a,accountNo:s},c=await this.client.getStatement({body:i});if(201===c.status){return c.body.map(e=>({...e,currencyCode:o.currencyCode})).reduce((e,t)=>{const r=ct.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=ct,exports.WalletStatementEntryJSONSchema=it,exports.WalletUtils=lt,exports.contract=Se,exports.createPaginatedResponse=function(e,t,r,n){return{results:e,pagination:new E(t,r,n)}},exports.createPaginatedResponseSchema=function(t){return e.z.object({results:e.z.array(t),pagination:T})},exports.createPayoutChannelCode=Xe,exports.emptyPaginatedResponse=function(e=1,t=10){return{results:[],pagination:new E(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
|