@temboplus/afloat 0.1.77-beta.7 → 0.1.77-beta.8

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("zustand"),o=require("@temboplus/frontend-core");function n(e){return e&&e.__esModule?e:{default:e}}var a=n(e);class s 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 s.schema.safeParse(e).success}static unknown(e){return new s({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 i={Profile:{ViewCurrent:"profile.getCurrent",Update:"profile.update"},Contact:{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 c 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(i.Profile)),e.z.enum(Object.values(i.Contact)),e.z.enum(Object.values(i.Payment)),e.z.enum(Object.values(i.Payout)),e.z.enum(Object.values(i.Transfer)),e.z.enum(Object.values(i.Wallet))]);return e.z.object({name:e.z.literal("PermissionError").nullish(),message:e.z.string(),requiredPermissions:e.z.array(r)}).safeParse(t).success}}const l=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,h=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var o,n,a,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,l(s)?l(i)?s.merge(i):s:l(i)?i:Object.assign({},s,i)),strictStatusCodes:null!==(o=r.strictStatusCodes)&&void 0!==o?o:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(n=r.validateResponseOnClient)&&void 0!==n?n: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!==(a=r.metadata)&&void 0!==a?a:{}}:r.metadata}]:[e,h(r,t)]})),m=Symbol("ContractPlainType"),p=()=>({router:(e,t)=>h(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>m,body:()=>m,type:()=>m,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>u}),y=e=>e?Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r;return r="string"==typeof t&&!["true","false","null"].includes(t.trim())&&isNaN(Number(t))?t:JSON.stringify(t),`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).join("&"):"",f=e=>e?Object.keys(e).flatMap(t=>g(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",g=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>g(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>g(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class w extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const b=async({route:e,path:t,method:r,headers:o,body:n,validateResponse:a,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:o,body:n}),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!=a?a:e.validateResponseOnClient)&&"function"==typeof(null==(l=r)?void 0:l.safeParse)?{...t,body:r.parse(t.body)}:t}var l;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}},v=e=>{const t=new FormData,r=(e,r)=>{r instanceof File?t.append(e,r):t.append(e,JSON.stringify(r))};return Object.entries(e).forEach(([e,t])=>{if(Array.isArray(t))for(const o of t)r(e,o);else r(e,t)}),t},N=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),C=(e,t,r,o,n)=>{const a=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:o.path,params:r}),s=((e,t=!1)=>{const r=t?y(e):f(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,n);return`${t}${a}${s}`},A=(e,t)=>{const r=Object.keys(e.responses);return async o=>{const n=((e,t,r)=>{const{query:o,params:n,body:a,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:l,cache:u,next:d,...h}=r||{},m={...t,...c};return{path:C(o,m.baseUrl,n,e,!!m.jsonQuery),clientArgs:m,route:e,body:a,query:o,extraInputArgs:h,fetchOptions:{...u&&{cache:u},...d&&{next:d},...l},headers:{...i,...s}}})(e,t,o),a=await(e=>{const{path:t,clientArgs:r,route:o,body:n,query:a,extraInputArgs:s,headers:i,fetchOptions:c}=e,l=r.api||b,u=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),d={...u&&N(u),...N(i)};Object.keys(d).forEach(e=>{void 0===d[e]&&delete d[e]});let h={route:o,path:t,method:o.method,headers:d,body:void 0,rawBody:n,rawQuery:a,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==o.method&&("contentType"in o&&"multipart/form-data"===o.contentType?h={...h,contentType:"multipart/form-data",body:n instanceof FormData?n:v(n)}:"contentType"in o&&"application/x-www-form-urlencoded"===o.contentType?h={...h,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...h.headers},body:"string"==typeof n?n:new URLSearchParams(n)}:null!=n&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(n)})),l({...h,...s})})(n);if(!t.throwOnUnknownStatus)return a;if(r.includes(a.status.toString()))return a;throw new w(a,r)}},S=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>d(r)?[e,A(r,t)]:[e,S(r,t)]));function I(e,t){let r;try{r=e()}catch(e){return}return{getItem:e=>{var o;const n=e=>null===e?null:JSON.parse(e,null==t?void 0:t.reviver),a=null!=(o=r.getItem(e))?o:null;return a instanceof Promise?a.then(n):n(a)},setItem:(e,o)=>r.setItem(e,JSON.stringify(o,null==t?void 0:t.replacer)),removeItem:e=>r.removeItem(e)}}const O=e=>t=>{try{const r=e(t);return r instanceof Promise?r:{then:e=>O(e)(r),catch(e){return this}}}catch(e){return{then(e){return this},catch:t=>O(t)(e)}}},z=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?(console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),((e,t)=>(r,o,n)=>{let a={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},s=!1;const i=new Set,c=new Set;let l;try{l=a.getStorage()}catch(e){}if(!l)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),r(...e)},o,n);const u=O(a.serialize),d=()=>{const e=a.partialize({...o()});let t;const r=u({state:e,version:a.version}).then(e=>l.setItem(a.name,e)).catch(e=>{t=e});if(t)throw t;return r},h=n.setState;n.setState=(e,t)=>{h(e,t),d()};const m=e((...e)=>{r(...e),d()},o,n);let p;const y=()=>{var e;if(!l)return;s=!1,i.forEach(e=>e(o()));const t=(null==(e=a.onRehydrateStorage)?void 0:e.call(a,o()))||void 0;return O(l.getItem.bind(l))(a.name).then(e=>{if(e)return a.deserialize(e)}).then(e=>{if(e){if("number"!=typeof e.version||e.version===a.version)return e.state;if(a.migrate)return a.migrate(e.state,e.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}}).then(e=>{var t;return p=a.merge(e,null!=(t=o())?t:m),r(p,!0),d()}).then(()=>{null==t||t(p,void 0),s=!0,c.forEach(e=>e(p))}).catch(e=>{null==t||t(void 0,e)})};return n.persist={setOptions:e=>{a={...a,...e},e.getStorage&&(l=e.getStorage())},clearStorage:()=>{null==l||l.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>y(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e)})},y(),p||m})(e,t)):((e,t)=>(r,o,n)=>{let a={storage:I(()=>localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},s=!1;const i=new Set,c=new Set;let l=a.storage;if(!l)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),r(...e)},o,n);const u=()=>{const e=a.partialize({...o()});return l.setItem(a.name,{state:e,version:a.version})},d=n.setState;n.setState=(e,t)=>{d(e,t),u()};const h=e((...e)=>{r(...e),u()},o,n);let m;n.getInitialState=()=>h;const p=()=>{var e,t;if(!l)return;s=!1,i.forEach(e=>{var t;return e(null!=(t=o())?t:h)});const n=(null==(t=a.onRehydrateStorage)?void 0:t.call(a,null!=(e=o())?e:h))||void 0;return O(l.getItem.bind(l))(a.name).then(e=>{if(e){if("number"!=typeof e.version||e.version===a.version)return[!1,e.state];if(a.migrate)return[!0,a.migrate(e.state,e.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}return[!1,void 0]}).then(e=>{var t;const[n,s]=e;if(m=a.merge(s,null!=(t=o())?t:h),r(m,!0),n)return u()}).then(()=>{null==n||n(m,void 0),m=o(),s=!0,c.forEach(e=>e(m))}).catch(e=>{null==n||n(void 0,e)})};return n.persist={setOptions:e=>{a={...a,...e},e.storage&&(l=e.storage)},clearStorage:()=>{null==l||l.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>p(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e)})},a.skipHydration||p(),m||h})(e,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()})};class P{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return _.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 P({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()}toObject(){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}}toJSON(){return JSON.stringify(this.toObject())}validate(){try{return P.schema.safeParse(this.toObject()).success}catch(e){return console.error("Profile validation error:",e),!1}}static fromJSON(e){try{const t=JSON.parse(e);return P.from(t)}catch(e){return void console.error("Error parsing profile JSON:",e)}}static from(e){try{return e?"object"!=typeof e?void console.error("Data is not an object"):e.id&&e.accountNo&&e.displayName?P.create({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove}):void console.error("Missing required profile fields"):void console.error("Data is null or undefined")}catch(e){return void console.error("Error creating profile from object:",e)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t._id||"string"!=typeof t._displayName||"string"!=typeof t._accountNo)return!1;if(null!==t._firstName&&void 0!==t._firstName&&"string"!=typeof t._firstName)return!1;if(null!==t._lastName&&void 0!==t._lastName&&"string"!=typeof t._lastName)return!1;if(null!==t._email&&void 0!==t._email&&"string"!=typeof t._email)return!1;const r=t._phone;if(null!=r&&"string"!=typeof r)return!1;const o=t._autoApprove;return null==o||"boolean"==typeof o}}const E={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())})};class D{_id;_profileId;_name;_identity;_type;_roleId;_isActive;_isArchived;_resetPassword;_createdAt;_updatedAt;_access;constructor(e,t,r,o,n,a,s,i,c,l,u,d){this._id=e,this._profileId=t,this._name=r,this._identity=o,this._type=n,this._roleId=a,this._isActive=s,this._isArchived=i,this._resetPassword=c,this._createdAt=l,this._updatedAt=u,this._access=d}static from(e){const t=E.loginDTO.parse(e);return new D(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)}static fromJson(e){try{const t=JSON.parse(e);return D.from(t)}catch(e){return void console.error("Error parsing LogIn JSON:",e)}}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}toObject(){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]}}toJson(){return JSON.stringify(this.toObject())}}class R{_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return P.is(e.companyProfile)?new R(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}toObject(){return{companyProfile:this._companyProfile.toObject(),role:this._role?.toJSON()}}toJson(){return JSON.stringify(this.toObject())}}class T{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 T(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()}}}class x{_logIn;_membership;_token;_permissionMap;constructor(e){this._logIn=e.logIn,this._membership=e.membership,this._token=e.token,this._permissionMap={},this._logIn.access.forEach(e=>{this._permissionMap[e]=!0})}static from(e){try{if(!e.logIn||!e.companyProfile||!e.token)return void console.error("Missing required User fields");if("string"!=typeof e.token||""===e.token.trim())return void console.error("Invalid token");const t=R.from({companyProfile:e.companyProfile,role:e.role});return t?new x({logIn:e.logIn,membership:t,token:e.token}):void console.error("Failed to create CompanyMembership")}catch(e){return void console.error("Error creating User:",e)}}static fromJson(e){try{const t=JSON.parse(e),r=D.from(t.logIn),o=P.from(t.companyProfile||t.profile),n=t.role?T.from(t.role):void 0;return r&&o?x.from({logIn:r,companyProfile:o,role:n,token:t.token}):void console.error("Failed to reconstruct nested objects")}catch(e){return void console.error("Error parsing User JSON:",e)}}get logIn(){return this._logIn}get membership(){return this._membership}get token(){return this._token}get id(){return this._logIn.id}get name(){return this._logIn.name}get identity(){return this._logIn.identity}get roleId(){return this._logIn.roleId}get resetPassword(){return this._logIn.resetPassword}get profile(){return this._membership.companyProfile}get role(){return this._membership.role}get access(){return this._logIn.access}can(e){return this._permissionMap[e]??!1}canAny(e){return e.some(e=>this.can(e))}canAll(e){return e.every(e=>this.can(e))}canManageTeam(){return this.can(i.TeamManagement.ViewMembers)}canViewRoles(){return this.can(i.Role.ViewRole)}toObject(){return{logIn:this._logIn.toObject(),profile:this._membership.companyProfile.toObject(),role:this._membership.role?.toJSON(),token:this._token,access:[...this._logIn.access],resetPassword:this._logIn.resetPassword}}toJson(){return JSON.stringify(this.toObject())}}const j=r.create(z((e,t)=>({user:void 0,token:void 0,getUser:()=>{try{const e=t().user;if(e)return x.fromJson(e)}catch(e){console.warn("Failed to deserialize user from store:",e)}},setUser:t=>{try{e({user:t.toJson()})}catch(e){console.error("Failed to serialize user to store:",e)}},getToken:()=>t().token,setToken:t=>e({token:t}),setUserAndToken:(t,r)=>{try{e({user:t.toJson(),token:r})}catch(e){console.error("Failed to serialize user and token to store:",e)}},clearAuth:()=>e({user:void 0,token:void 0})}),{name:"auth-store",storage:I(()=>"undefined"==typeof window?{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}:sessionStorage)})),M=()=>{if("undefined"!=typeof window)return j.getState().getToken()};class F{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;try{const e=M();if(e&&e.trim().length>0)return e;console.warn(`No token available from global auth state for ${this.endpoint} repository`)}catch(e){console.warn(`No valid token available for ${this.endpoint} repository. Please provide a token directly in the constructor or ensure a user is logged in via AfloatAuth.instance.`)}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 S(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 s(t.data);throw new s({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===e.status)throw new s({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new s({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new s({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new s({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}var B,k;exports.FilterOperator=void 0,(B=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",B.NOT_EQUALS="neq",B.LESS_THAN="lt",B.LESS_THAN_OR_EQUAL="lte",B.GREATER_THAN="gt",B.GREATER_THAN_OR_EQUAL="gte",B.LIKE="like",B.LIKE_LOWER="likeLower",B.IS_NULL="isNull",B.IS_NOT_NULL="isNotNull",B.IN="in",exports.SortDirection=void 0,(k=exports.SortDirection||(exports.SortDirection={})).ASC="asc",k.DESC="desc";const U=Symbol("query-builder-type");class ${options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8};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}}[U]="query-builder";static is(e){return null!==e&&"object"==typeof e&&U in e&&"query-builder"===e[U]}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){return e&&this.whereGreaterThanOrEqual("createdAt",e),t&&this.whereLessThanOrEqual("createdAt",t),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(","))}const t=this.options.filters?.filter(e=>"createdAt"===e.field&&(e.operator===exports.FilterOperator.GREATER_THAN_OR_EQUAL||e.operator===exports.FilterOperator.LESS_THAN_OR_EQUAL));if(t){const r=t.find(e=>e.operator===exports.FilterOperator.GREATER_THAN_OR_EQUAL),o=t.find(e=>e.operator===exports.FilterOperator.LESS_THAN_OR_EQUAL);r&&(e.startDate=r.value),o&&(e.endDate=o.value)}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?e.eager=this.options.includes[0]:e.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(e.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(e.groupBy=this.options.groupBy.join(",")),this.options.count&&(e.count=this.options.count),e}clone(){return new(0,this.constructor)({...this.options,filters:this.options.filters?[...this.options.filters]:[],sort:this.options.sort?[...this.options.sort]:[],includes:this.options.includes?[...this.options.includes]:[],groupBy:this.options.groupBy?[...this.options.groupBy]:[],join:this.options.join?[...this.options.join]:[]})}static create(e){return new $(e)}}const L=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)}),q=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 W{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 W(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new W(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 J=e=>e.optional().transform(e=>e??void 0),V={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=>o.CountryValidation.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>o.CurrencyValidation.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:e.z.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:e.z.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:e.z.object({id:e.z.string().optional(),profileId:e.z.string().optional(),accountNo:e.z.string().optional(),accountName:e.z.string().optional(),channel:e.z.string().optional(),countryCode:e.z.string().default("TZ").refine(e=>o.ISO2CountryCodesSet.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:e.z.string().default("TZS").refine(e=>{const t=o.Currency.from(e);return void 0!==t&&o.CurrencyCodesSet.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:e.z.object({accountNo:J(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:J(e.z.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})};class G{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return V.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=G.schema.safeParse(e);if(t.success)return new G(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)}toObject(){return{id:this._id,profileId:this._profileId,accountNo:this._accountNo,accountName:this._accountName,channel:this._channel,countryCode:this._countryCode,createdAt:this._createdAt,updatedAt:this._updatedAt,currencyCode:this._currencyCode}}toJSON(){return JSON.stringify(this.toObject())}validate(){const e=G.schema.safeParse(this.toObject());return e.success||console.warn("Wallet instance validation failed:",e.error.flatten()),e.success}static fromJSON(e){try{const t=JSON.parse(e);return G.from(t)}catch(e){return void console.error("Error parsing wallet JSON:",e)}}static from(e){if(e&&"object"==typeof e)return G.create({id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt,currencyCode:e.currencyCode});console.error("Invalid data provided to Wallet.from: Input must be an object.")}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.profileId&&"string"==typeof t.accountNo&&"string"==typeof t.accountName&&"string"==typeof t.channel&&"string"==typeof t.countryCode&&o.CountryValidation.isISO2CountryCode(t.countryCode)&&"string"==typeof t.currencyCode&&o.CurrencyValidation.isCurrencyCode(t.currencyCode)&&"string"==typeof t.createdAt&&"string"==typeof t.updatedAt&&"function"==typeof t.toObject&&"function"==typeof t.validate}}const H={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)};var Q;exports.ContactType=void 0,(Q=exports.ContactType||(exports.ContactType={})).Bank="Bank",Q.Mobile="Mobile";const Z=e.z.nativeEnum(exports.ContactType),K=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:Z}),Y={contactDTO:e.z.object({id:e.z.string().min(1,"Contact id is required"),profileId:e.z.string(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime()}).merge(K),contactInputDTO:K,contactType:Z};class X extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="ContactInfoError"}}class ee{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}}class te extends ee{name;phoneNumber;mnoId;constructor(e,t,r){if(super(exports.ContactType.Mobile,t.countryCode),this.name=e,this.phoneNumber=t,!e?.trim())throw new X("Name is required and cannot be empty",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(!t?.validate())throw new X("Invalid phone number",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(o.MNOUtils.requiresExplicitMNO(t.countryCode)){if(!r)throw new X(`MNO must be explicitly provided for phone numbers in ${t.countryCode} due to Mobile Number Portability`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});if(!o.MNOUtils.isValidMNOForCountry(r,t.countryCode)){const e=o.MNOUtils.getCountryMNOs(t.countryCode).map(e=>e.id);throw new X(`Invalid MNO ${r} for country ${t.countryCode}. Valid MNOs: ${e.join(", ")}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,mnoId:r,operation:"constructor"})}this.mnoId=r}else{const e=o.MNOUtils.getMNOByPhoneNumber(t.e164Format,t.countryCode);if(!e?.id)throw new X(`Failed to determine MNO for phone number ${t.e164Format}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});this.mnoId=e.id}}static fromContactDTO(e){if("Mobile"!==e.type)return;let t=e.accountNo;t.startsWith("+")||(t=`+${t}`);const r=o.PhoneNumber.from(t);if(!r)return void console.error(`Failed to parse phone number ${t}`);const n=r.countryCode;try{let t;if(o.MNOUtils.requiresExplicitMNO(n)){if(e.channel&&"string"==typeof e.channel){if(!o.MNOUtils.isValidMNOForCountry(e.channel,n))return void console.warn(`Invalid MNO ${e.channel} for country ${n}`);t=e.channel}}else if(t=o.MNOUtils.getMNOByPhoneNumber(r.e164Format,n)?.id,!t)return void console.warn(`Failed to auto-detect MNO for phone number ${r.e164Format}`);return new te(e.displayName,r,t)}catch(e){return void console.error(`Failed to create MobileContactInfo: ${e}`)}}static fromPayoutDTO(e){try{if(!o.CountryValidation.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=o.PhoneNumber.from(e.msisdn,{defaultCountry:e.countryCode});if(!t)return void console.error(`Failed to parse phone number: ${e.msisdn}`);let r;if(o.MNOUtils.requiresExplicitMNO(t.countryCode)){if(e.channel&&"string"==typeof e.channel){if(!o.MNOUtils.isValidMNOForCountry(e.channel,t.countryCode))return void console.warn(`Invalid MNO ${e.channel} for country ${t.countryCode} in PayoutDTO`);r=e.channel}}else if(r=o.MNOUtils.getMNOByPhoneNumber(t.e164Format,t.countryCode)?.id,!r)return void console.warn(`Failed to auto-detect MNO for phone number ${t.e164Format}`);return new te(e.payeeName,t,r)}catch(t){return void console.error("Failed to create MobileContactInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.name||!t.name.trim())return!1;let r;if("string"==typeof t.phoneNumber)r=o.PhoneNumber.from(t.phoneNumber);else if("object"==typeof t.phoneNumber){const e=t.phoneNumber;o.PhoneNumber.is(e)&&(r=o.PhoneNumber.from(e.e164Format))}if(!r)return!1;const n=t.mnoId;if("string"!=typeof n)return!1;if(!o.MNOUtils.isValidMNOForCountry(n,r.countryCode))return!1;if(o.MNOUtils.requiresExplicitMNO(r.countryCode))return!0;{const e=o.MNOUtils.getMNOByPhoneNumber(r.e164Format,r.countryCode);return e?.id===n}}validate(){try{return!!this.name?.trim()&&(!!this.phoneNumber?.validate()&&(!!o.MNOUtils.isValidMNOForCountry(this.mnoId,this.countryCode)&&(!!o.MNOUtils.requiresExplicitMNO(this.countryCode)||o.MNOUtils.validateMNOForPhoneNumber(this.phoneNumber.e164Format,this.mnoId,this.countryCode))))}catch{return!1}}getValidationDetails(){const e=[];if(this.name?.trim()||e.push("Name is required"),this.phoneNumber?.validate()||e.push("Phone number is invalid"),o.MNOUtils.isValidMNOForCountry(this.mnoId,this.countryCode)||e.push(`Invalid MNO ${this.mnoId} for country ${this.countryCode}`),!o.MNOUtils.requiresExplicitMNO(this.countryCode)){const t=o.MNOUtils.getMNOByPhoneNumber(this.phoneNumber.e164Format,this.countryCode);t?.id!==this.mnoId&&e.push("MNO doesn't match auto-detected value from phone number prefix")}return{isValid:0===e.length,errors:e,warnings:[]}}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(o.PhoneNumberFormat.E164)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){const e=o.MNOUtils.getMNOById(this.mnoId,this.countryCode);return e?.mobileMoneyService??e?.displayName??this.mnoId}}class re extends ee{accName;bank;accNo;constructor(e,t,r){if(super(exports.ContactType.Bank,t.countryCode),this.accName=e,this.bank=t,this.accNo=r,!o.BankValidation.validateAccountName(e))throw new X("Invalid account name",{operation:"constructor",countryCode:t.countryCode});if(!o.BankValidation.validateAccountNumber(r,t.countryCode))throw new X("Invalid account number",{operation:"constructor",countryCode:t.countryCode})}static fromContactDTO(e){if("Bank"!==e.type)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank contacts");const r=o.BankValidation.getCountryFromSwiftCode(t);if(r)if(o.BankValidation.validateSwiftCode(t,r))try{const n=o.Bank.from(t,r);if(!n)throw new Error(`Bank with SWIFT code ${t} not found`);return new re(e.displayName,n,e.accountNo)}catch(e){return void console.error(`Failed to create BankContactInfo: ${e}`)}else console.error(`Invalid SWIFT code ${t} for country ${r}`);else console.error(`Could not identify country from SWIFT code: ${t}`)}static fromPayoutDTO(e){try{if(!o.CountryValidation.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=e.msisdn.trim().split(":");if(2!==t.length)return void console.error("Invalid PayoutDTO format for bank - expected 'swiftcode:accountno'");const[r,n]=t;if(!o.BankValidation.validateSwiftCode(r,e.countryCode))return void console.error(`Invalid SWIFT code ${r} for country ${e.countryCode}`);const a=o.Bank.from(r,e.countryCode);return a?new re(e.payeeName,a,n):void console.error(`Bank with SWIFT code ${r} not found`)}catch(t){return void console.error("Failed to create BankContactInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.accName)return!1;if("string"!=typeof t.accNo)return!1;if(!t.bank||!o.Bank.is(t.bank))return!1;const r=t.accName,n=t.accNo,a=t.bank,s=o.BankValidation.validateAccountName(r),i=o.BankValidation.validateAccountNumber(n,a.countryCode);return s&&i}validate(){try{return o.BankValidation.validateAccountName(this.accName)&&o.BankValidation.validateAccountNumber(this.accNo,this.bank.countryCode)&&o.Bank.is(this.bank)}catch{return!1}}get accountName(){return this.accName}get accountNumber(){return this.accNo}get accountNameLabel(){return"Acc. Name"}get accountNumberLabel(){return"Bank Acc. No."}get channelLabel(){return"Bank"}get channelId(){return this.bank.swiftCode}get channelName(){return this.bank.shortName}}const oe="MOBILE TRANSFER ",ne="PAYOUT",ae="PAYOUT TO BANK",se="TO_BANK",ie="PAYOUT TO MOBILE",ce="TO_MOMO";class le{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 te.is(e)?le.generateMobilePayoutNarrationV2(e):re.is(e)?le.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${ne.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:o}=e;return`${ne.toUpperCase()} ${t.swiftCode.trim()} ${o.trim()} ${r.trim()}`.toUpperCase()}getContactDetails=()=>{const e=this.getBankContactDetails(),t=this.getMobileContactDetails();return e||(t||void 0)};getBankContactDetails=()=>{let e=this.text.trim();e.startsWith(oe)&&(e=e.substring(16));try{if(e.startsWith(ne)){const t=e.replace(ne,"").trim().split(" ");if(t.length>=3){const e=t[0],r=t[1],n=t.slice(2).map(ue).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=o.BankValidation.getCountryFromSwiftCode(e);if(t){if(o.BankValidation.validateSwiftCode(e,t)){const a=o.Bank.from(e,t);if(r&&n&&a)return new re(n,a,r)}}}}}if(e.startsWith(se)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=r.account_number,a=r.account_name,s=r.swift_code,i=o.BankValidation.getCountryFromSwiftCode(s);if(!i)return;if(!o.BankValidation.validateSwiftCode(s,i))return;const c=o.Bank.from(s,i);if(n&&a&&c)return new re(a,c,n)}if(e.startsWith(ae)){const t=e.replace(ae,"").trim().split(" "),r=o.BankService.getInstance().searchBanks("TZ",t[0]),n=r.length>0?r[0]:void 0,a=t[1],s=t.slice(2).map(ue).join(" ");if(s&&a&&n)return new re(s,n,a)}}catch(e){return}};getMobileContactDetails=()=>{let e=this.text.trim();e.startsWith(oe)&&(e=e.substring(16));try{if(e.startsWith(ne)){const t=e.replace(ne,"").trim().split(" ");if(t.length>=2){const e=t[0],r=t.slice(1).map(ue).join(" ");if(e.startsWith("+")){const t=o.PhoneNumber.from(e);if(t&&r)return new te(r,t)}}}if(e.startsWith(ce)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=o.TZMobileNumber.from(r.phone_number);let a=r.username;void 0===a&&(a="");let s=a.split(" ");if(s=s.filter(e=>e.trim().length>0),a=s.map(ue).join(" "),n&&a)return new te(a,n)}if(e.startsWith(ie)){const t=e.replace(ie,"").trim().split(" "),r=o.TZMobileNumber.from(t[0]),n=t.slice(1).map(ue).join(" ");if(r&&n)return new te(n,r)}}catch(e){return}};toJson(){return{text:this.text,version:"2.0"}}static fromJson(e){try{let t;return t="string"==typeof e?JSON.parse(e):e,t&&"object"==typeof t&&"string"==typeof t.text?new le(t.text):void console.warn("Invalid NarrationJson: missing or invalid text property")}catch(e){return void console.error("Error parsing NarrationJson:",e)}}static isNarrationJson(e){if(!e||"object"!=typeof e)return!1;return"string"==typeof e.text}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;try{return"string"==typeof t.text&&"function"==typeof t.getContactDetails&&"function"==typeof t.toJson}catch(e){return!1}}}function ue(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}class de{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return V.statementEntry}constructor(e,t){this._accountNo=e.accountNo,this._debitOrCredit=e.debitOrCredit,this._tranRefNo=e.tranRefNo,this._narration=t,this._txnDate=e.txnDate,this._valueDate=e.valueDate,this._currencyCode=e.currencyCode;const r=o.Currency.from(e.currencyCode);if(!r)throw new Error(`Currency not found for code: ${e.currencyCode}`);const n=o.Amount.from(e.amountCredited,r.code),a=o.Amount.from(e.amountDebited,r.code),s=o.Amount.from(e.balance,r.code);if(!n||!a||!s)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=n,this._amountDebited=a,this._balance=s}static create(e){const t="string"==typeof e.narration?new le(e.narration):e.narration,r={...e,narration:t.text},o=de.schema.safeParse(r);if(o.success)try{const{narration:e,...r}=o.data;return new de(r,t)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",o.error.flatten())}get accountNo(){return this._accountNo}get debitOrCredit(){return this._debitOrCredit}get tranRefNo(){return this._tranRefNo}get narration(){return this._narration}get txnDate(){return this._txnDate}get valueDate(){return this._valueDate}get amountCredited(){return this._amountCredited}get amountDebited(){return this._amountDebited}get balance(){return this._balance}get currencyCode(){return this._currencyCode}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"}}static fromJson(e){try{let t;if(t="string"==typeof e?JSON.parse(e):e,!(t&&"object"==typeof t&&"string"==typeof t.debitOrCredit&&"string"==typeof t.tranRefNo&&t.narration&&"string"==typeof t.txnDate&&"string"==typeof t.valueDate&&"string"==typeof t.currencyCode&&t.amountCredited&&t.amountDebited&&t.balance))return void console.warn("Invalid WalletStatementEntryJson: missing or invalid required properties");const r=le.fromJson(t.narration);if(!r)return void console.warn("Invalid WalletStatementEntryJson: failed to deserialize narration");const n=o.Amount.fromJson(t.amountCredited),a=o.Amount.fromJson(t.amountDebited),s=o.Amount.fromJson(t.balance);return n&&a&&s?n.currencyCode!==t.currencyCode||a.currencyCode!==t.currencyCode||s.currencyCode!==t.currencyCode?void console.warn("Invalid WalletStatementEntryJson: currency code mismatch"):de.create({accountNo:t.accountNo,debitOrCredit:t.debitOrCredit,tranRefNo:t.tranRefNo,narration:r,txnDate:t.txnDate,valueDate:t.valueDate,amountCredited:n.numericValue,amountDebited:a.numericValue,balance:s.numericValue,currencyCode:t.currencyCode}):void console.warn("Invalid WalletStatementEntryJson: failed to deserialize Amount objects")}catch(e){return void console.error("Error parsing WalletStatementEntryJson:",e)}}static isWalletStatementEntryJson(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.debitOrCredit&&"string"==typeof t.tranRefNo&&le.isNarrationJson(t.narration)&&"string"==typeof t.txnDate&&"string"==typeof t.valueDate&&"string"==typeof t.currencyCode&&(void 0===t.accountNo||"string"==typeof t.accountNo)&&o.Amount.isAmountJson(t.amountCredited)&&o.Amount.isAmountJson(t.amountDebited)&&o.Amount.isAmountJson(t.balance)}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=de.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&&le.is(t.narration)&&t.txnDate instanceof Date&&t.valueDate instanceof Date&&o.Amount.is(t.amountCredited)&&o.Amount.is(t.amountDebited)&&o.Amount.is(t.balance)&&"string"==typeof t.currencyCode&&"function"==typeof t.toJson&&"function"==typeof t.validate}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return de.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 toJsonArray(e){return e.map(e=>e.toJson())}static fromJsonArray(e){try{let t;return t="string"==typeof e?JSON.parse(e):e,Array.isArray(t)?t.map(e=>de.fromJson(e)).filter(e=>void 0!==e):(console.warn("fromJsonArray expects an array"),[])}catch(e){return console.error("Error parsing WalletStatementEntryJson array:",e),[]}}toObject(){return{accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.text,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.toJson(),amountDebited:this._amountDebited.toJson(),balance:this._balance.toJson(),currencyCode:this._currencyCode}}toJSON(){return JSON.stringify(this.toJson())}static fromJSON(e){return de.fromJson(e)}static from(e){if(e&&"object"==typeof e)try{let t,r,n,a,s=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const a=o.Amount.fromJson(e.amountCredited),i=o.Amount.fromJson(e.amountDebited),c=o.Amount.fromJson(e.balance);if(!a||!i||!c)return void console.error("Failed to deserialize Amount objects from JSON");t=a.numericValue,r=i.numericValue,n=c.numericValue,e.currencyCode||(s=a.currencyCode)}else if(t=Number(e.amountCredited),r=Number(e.amountDebited),n=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)a=e.narration;else if(le.is(e.narration))a=e.narration;else{if(!le.isNarrationJson(e.narration))return void console.error("Invalid narration data");{const t=le.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");a=t}}return de.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:a,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:r,balance:n,currencyCode:s})}catch(e){return void console.error("Error in WalletStatementEntry.from:",e)}else console.error("Invalid data provided to WalletStatementEntry.from: not an object or null.")}}const he=p().router({getWallets:{method:"GET",path:"/",query:V.walletQuery,responses:{200:e.z.array(G.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(de.schema)}}});class me extends ${static create(){return new me}static fromFilters(e){return(new me).applyFilters(e)}static fromUrlParams(e){try{const t=V.walletQuery.parse(e);return me.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 me.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return me.fromSearchParams(t)}static from(e){try{return null==e?new me:$.is(e)?new me(e.options):e instanceof URLSearchParams?me.fromSearchParams(e):this.isStringRecord(e)?me.fromUrlParams(e):me.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}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)"eq"===t.operator?e[t.field]=t.value:"likeLower"===t.operator&&"string"==typeof t.value&&(e[t.field]=t.value.replace(/%/g,""));return e}}class pe extends F{constructor(e){super("wallet",he,e)}async getBalance(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");if(e.wallet){const t=await this.client.getBalance({body:{accountNo:e.wallet.accountNo}});if(201===t.status){const r=t.body.availableBalance,n=o.Amount.from(r,e.wallet.currencyCode);if(n)return n}}if(e.accountNo){const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);const r=t[0],n=await this.client.getBalance({body:{accountNo:e.accountNo}});if(201===n.status){const e=n.body.availableBalance,t=o.Amount.from(e,r.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=me.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=G.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=me.create().whereId(e),r=await this.getWallets(t);return r.length>0?r[0]:void 0}async getStatement(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");const t=new Date,r=new Date(t.getFullYear(),t.getMonth(),1),o=new Date(t.getFullYear(),t.getMonth()+1,0),n=e.range??{startDate:r,endDate:o};let a,s;if(e.wallet)a=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}`);a=t[0],s=e.accountNo}}const i={...n,accountNo:s},c=await this.client.getStatement({body:i});if(201===c.status){return c.body.map(e=>({...e,currencyCode:a.currencyCode})).reduce((e,t)=>{const r=de.create(t);return r?e.push(r):console.warn("[WalletRepository] Skipping invalid statement entry:",t),e},[])}throw new Error(`Failed to fetch statement. Status: ${c.status}`)}async exists(e){return(await this.getWallets(e)).length>0}async count(e){return(await this.getWallets(e)).length}}const ye=r.create()(z((e,t)=>({userId:"",wallets:[],selectedWalletId:"",selectedCountryCode:"TZ",lastSynced:new Date,isInitialized:!1,setWallets:r=>{const o=r.filter(e=>G.is(e));if(0===o.length)throw new Error("setWallets received an empty or invalid wallet list. User must have at least one valid wallet.");const n=t().selectedWalletId,a=t().isInitialized;let s;const i=o.some(e=>e.id===n);a&&i&&""!==n?(s=o.find(e=>e.id===n),s||(console.error("Inconsistency: currentWalletStillValid was true, but find failed."),s=o[0])):s=o[0],e({wallets:o,selectedWalletId:s.id,selectedCountryCode:s.countryCode,lastSynced:new Date,isInitialized:!0})},setSelectedWallet:r=>{if(!G.is(r))throw new Error("setSelectedWallet called with an invalid Wallet object.");if(!t().wallets.some(e=>e.id===r.id))throw new Error(`Attempted to select wallet (ID: ${r.id}) which is not present in the current wallet list.`);e({selectedWalletId:r.id,selectedCountryCode:r.countryCode})},setSelectedCountry:r=>{const o=t()._getWalletsByCountry(r);if(0===o.length)throw new Error(`Cannot select country ${r}: No wallets found for this country (check if code is valid or state is consistent).`);e({selectedCountryCode:r,selectedWalletId:o[0].id})},reset:()=>{e({userId:"",wallets:[],selectedWalletId:"",selectedCountryCode:"TZ",lastSynced:new Date,isInitialized:!1})},_getWalletsByCountry:e=>t().wallets.filter(t=>t.countryCode===e),_getSelectedWallet:()=>{const e=t();if(!e.isInitialized)throw new Error("Cannot get selected wallet: Wallet session not initialized.");if(""===e.selectedWalletId)throw new Error("Cannot get selected wallet: Selection is still placeholder (initialization incomplete?).");const r=e.wallets.find(t=>t.id===e.selectedWalletId);if(!r)throw console.error("Inconsistent state details:",{id:e.selectedWalletId,walletCount:e.wallets.length}),new Error(`Inconsistent state: Selected wallet ID '${e.selectedWalletId}' not found in wallet list.`);return r}}),{name:"wallet-session-storage",storage:I(()=>sessionStorage,{reviver:(e,t)=>{if("wallets"===e&&Array.isArray(t))return t.map(e=>{try{const t=G.from(e);return t||void console.warn("Filtering out invalid wallet data during rehydration:",e)}catch(t){return void console.error("Error rehydrating Wallet instance from persisted data:",e,t)}}).filter(e=>void 0!==e);if("lastSynced"===e&&"string"==typeof t)try{const e=new Date(t);return isNaN(e.getTime())?new Date:e}catch{return new Date}return t},replacer:(e,t)=>"lastSynced"===e&&t instanceof Date?t.toISOString():"wallets"===e&&Array.isArray(t)?t.map(e=>e instanceof G&&"function"==typeof e.toObject?e.toObject():e):t}),partialize:e=>({userId:e.userId,wallets:e.wallets,selectedWalletId:e.selectedWalletId,selectedCountryCode:e.selectedCountryCode,lastSynced:e.lastSynced,isInitialized:e.isInitialized})}));class fe{repo;static _instance;constructor(){this.repo=new pe}static get instance(){return this._instance||(this._instance=new fe),this._instance}isInitialized(){return ye.getState().isInitialized}async initialize(e){if(!this.isInitialized()){if(!e)throw new Error("User must be authenticated to initialize wallet manager");await this.refreshWallets()}}async refreshWallets(){try{const e=await this.repo.getWallets();if(!e||0===e.length)throw new Error("User has no wallets associated with their account. Cannot proceed.");ye.getState().setWallets(e)}catch(e){throw console.error("Failed to refresh wallets:",e),e}}getWallets(){const e=ye.getState();if(!e.isInitialized)throw new Error("Cannot get wallets: Wallet session not initialized.");return e.wallets}getCountries(){const e=this.getWallets();return H.getUniqueCountries(e)}getWalletsByCountry(e){if(!this.isInitialized())throw new Error("Cannot get wallets by country: Wallet session not initialized.");return ye.getState()._getWalletsByCountry(e)}getSelectedWallet(){return ye.getState()._getSelectedWallet()}getSelectedCountryCode(){const e=ye.getState();if(!e.isInitialized)throw new Error("Cannot get selected country code: Wallet session not initialized.");return e.selectedCountryCode}getSelectedCountry(){const e=this.getSelectedCountryCode();try{const t=o.Country.fromCode(e);if(!t)throw new Error(`Country.fromCode returned invalid result for code: ${e}`);return t}catch(t){throw console.error(`Failed to get Country object for code ${e}:`,t),new Error(`Failed to create Country object for selected code ${e}.`)}}changeWallet(e){if(!this.isInitialized())throw new Error("Cannot change wallet: Wallet session not initialized.");const t=ye.getState(),r=t.wallets.find(t=>t.id===e);if(!r)throw new Error(`Cannot change wallet: Wallet with ID ${e} not found.`);t.setSelectedWallet(r)}changeCountry(e){if(!this.isInitialized())throw new Error("Cannot change country: Wallet session not initialized.");ye.getState().setSelectedCountry(e)}reset(){ye.getState().reset()}}const ge=p().router({logIn:{method:"POST",path:"/login",body:e.z.object({type:e.z.string().default("password"),identity:e.z.string().email(),password:e.z.string()}),responses:{201:e.z.object({profile:_.profileDTOSchema,token:e.z.string(),access:e.z.array(e.z.string()),resetPassword:e.z.boolean()}),400:e.z.object({})}},access:{method:"GET",path:"/access",responses:{200:e.z.string().array()}},resetPassword:{method:"PUT",path:"/password",body:e.z.object({currentPassword:e.z.string(),newPassword:e.z.string()}),responses:{}}}),we=p().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:E.loginDTO}}});class be extends F{constructor(e){super("login",we,e)}async getIdentity(){const e=await this.client.getUserCredentials();if(200===e.status)return e.body;throw new Error(`Failed to get user identity. Status: ${e.status}`)}}const ve=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"),Ne=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")}),Ce=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:Ne.optional(),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),Ae={role:Ne,teamMember:Ce,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:ve.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:ve.optional(),resetPassword:e.z.boolean().optional(),isActive:e.z.boolean().optional()}),resetPasswordRequest:e.z.object({newPassword:ve.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:ve},Se=p().router({getTeamMembers:{method:"GET",path:"/login",query:Ae.teamMemberQueryParams,responses:{200:e.z.array(Ae.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:Ae.teamMemberQueryParams,responses:{200:Ae.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:Ae.createTeamMemberRequest,responses:{201:Ae.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:Ae.updateTeamMemberRequest,responses:{200:Ae.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:Ae.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:Ae.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:Ae.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(Ae.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:Ae.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"}});class Ie{id;name;identity;type;profileId;roleId;resetPassword;isActive;isArchived;role;createdAt;updatedAt;permissions;constructor(e){if(this.id=e.id,this.name=e.name,this.identity=e.identity,this.type=e.type,this.profileId=e.profileId,this.roleId=e.roleId,this.resetPassword=e.resetPassword,this.isActive=e.isActive,this.isArchived=e.isArchived,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.permissions=new Set(e.role?.access??[]),e.role)try{this.role=new T(e.role)}catch(e){}}static from(e){try{return e?.id&&e?.name&&e?.identity&&e?.roleId?new Ie(e):void console.error("Missing required TeamMember fields:",e)}catch(e){return void console.error("Error creating TeamMember:",e)}}static fromJson(e){try{const t=JSON.parse(e);return Ie.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>Ie.from(e)).filter(Boolean)}can(e){return this.permissions.has(e)}canAny(e){return e.some(e=>this.permissions.has(e))}canAll(e){return e.every(e=>this.permissions.has(e))}isAccountActive(){return this.isActive}isAccountArchived(){return this.isArchived}needsPasswordReset(){return this.resetPassword}getAccountStatus(){return this.isArchived?{status:"archived",label:"Archived",color:"default",description:"Account has been archived and is no longer accessible"}:this.isActive?this.resetPassword?{status:"password_reset_required",label:"Password Reset Required",color:"warning",description:"User must reset their password on next login"}:{status:"active",label:"Active",color:"success",description:"Account is active and ready to use"}:{status:"inactive",label:"Inactive",color:"error",description:"Account has been deactivated by an administrator"}}getRoleName(){return this.role?.name??""}getCreatedDate(){return this.createdAt.toLocaleDateString()}getLastUpdateInfo(){const e=(new Date).getTime()-this.updatedAt.getTime(),t=Math.floor(e/864e5);return 0===t?"Today":1===t?"Yesterday":t<7?`${t} days ago`:t<30?`${Math.floor(t/7)} weeks ago`:this.updatedAt.toLocaleDateString()}toObject(){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()}}toJson(){return JSON.stringify(this.toObject())}toJSON(){return this.toObject()}}class Oe extends F{constructor(e){super("admin",Se,e)}async createTeamMember(e){const t=await this.client.createTeamMember({body:e});return this.handleResponse(t,201)}async updateTeamMember(e,t){const r=await this.client.updateTeamMember({params:{id:e},body:t}),o=this.handleResponse(r,200),n=Ie.from(o);if(!n)throw new Error("Invalid team member data received from server");return n}async archiveTeamMember(e){const t=await this.client.archiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),o=Ie.from(r);if(!o)throw new Error("Invalid team member data received from server");return o}async unArchiveTeamMember(e){const t=await this.client.unArchiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),o=Ie.from(r);if(!o)throw new Error("Invalid team member data received from server");return o}async resetTeamMemberPassword(e,t={}){const r=await this.client.resetPassword({params:{id:e},body:t});return this.handleResponse(r,200)}async getAllTeamMembers(e={eager:"role"}){const t=await this.client.getTeamMembers({query:e}),r=this.handleResponse(t,200);return Ie.createMany(r)}async getTeamMember(e,t={eager:"role"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),o=this.handleResponse(r,200),n=Ie.from(o);if(!n)throw new Error("Invalid team member data received from server");return n}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=T.from(e);if(!t)throw new Error("Invalid role data received from server");return t})}async getRole(e){const t=await this.client.getRole({params:{id:e}}),r=this.handleResponse(t,200),o=T.from(r);if(!o)throw new Error("Invalid role data received from server");return o}}class ze extends F{constructor(e){super("auth",ge,e)}async logIn(e,t){const r={type:"password",identity:e,password:t},o=await this.client.logIn({body:r});if(400===o.status)throw new s({message:"Invalid email or password",statusCode:400});if(201===o.status){const e=o.body.token,t=new be({token:e}),r=await t.getIdentity(),n=D.from(r);if(!n)throw new s({message:"Failed to construct login credentials",statusCode:502});const a=o.body.profile,c=P.from(a);if(!c)throw new s({message:"Failed to construct user profile",statusCode:502});let l;if(n.access.includes(i.Role.ViewRole))try{const t=new Oe({token:e});l=await t.getRole(n.roleId)}catch(e){console.warn("Failed to fetch role details:",e)}const u=x.from({logIn:n,companyProfile:c,role:l,token:e});if(!u)throw new s({message:"Failed to construct user session",statusCode:502});return u}throw new s({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 s({message:"Invalid current password",statusCode:400});throw new s({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}`)}}class _e{static _instance=null;constructor(){}static get instance(){return _e._instance||(_e._instance=new _e),_e._instance}get repo(){return new ze({token:this.getUserToken()})}getUserToken(){return M()}get currentUser(){return(()=>{if("undefined"!=typeof window)return j.getState().getUser()})()}get isAuthenticated(){return!!this.currentUser&&!!this.getUserToken()}useCurrentUser(){return(()=>{if("undefined"==typeof window)throw new Error("useCurrentUser must only be used in a React component on the client side");const e=r.useStore(j,e=>e.user);try{return e?x.fromJson(e):void 0}catch(e){return void console.warn("Failed to deserialize user from hook:",e)}})()}checkPermission(e){return this.currentUser?.can(e)??!1}async logIn(e,t){if(!e||!t)throw new Error("Email and password are required");const r=new ze,o=await r.logIn(e,t);this.clearSavedData(),j.getState().setUserAndToken(o,o.token);try{await fe.instance.initialize(o)}catch(e){throw console.warn("Failed to initialize wallet session manager:",e),e}return o}async resetPassword(e,t){if(!this.isAuthenticated)throw new Error("User must be authenticated to reset password");if(!e||!t)throw new Error("Current password and new password are required");return await this.repo.updatePassword(e,t),this.clearSavedData(),!0}logOut(){this.clearSavedData()}refresh(){this.clearSavedData()}getDebugInfo(){return{hasUser:!!this.currentUser,hasToken:!!this.getUserToken(),isAuthenticated:this.isAuthenticated,userName:this.currentUser?.name||"Not logged in",tokenLength:this.getUserToken()?.length||0,managerInstance:"AfloatAuth singleton"}}clearSavedData(){j.getState().clearAuth();try{fe.instance.reset()}catch(e){console.warn("Failed to reset wallet session manager:",e)}}}class Pe{data;constructor(e){this.data=Y.contactDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get displayName(){return this.data.displayName}get type(){return this.data.type}get createdAt(){return new Date(this.data.createdAt)}get updatedAt(){return new Date(this.data.updatedAt)}get info(){return this.data.type===exports.ContactType.Mobile?te.fromContactDTO(this.data):this.data.type===exports.ContactType.Bank?re.fromContactDTO(this.data):void 0}get accNo(){const e=this.info;return e?e.accountNumber:this.data.accountNo}get accName(){return this.data.displayName}get accNoLabel(){const e=this.info;return e instanceof te?"Phone Number":e instanceof re?"Bank Account Number":"Account Number"}get channelLabel(){const e=this.info;return e instanceof te?"Channel":e instanceof re?"Bank":"Channel"}get accNameLabel(){const e=this.info;return e instanceof te?"Full Name":e instanceof re?"Bank Account Name":"Display Name"}get channelName(){const e=this.info;return e instanceof te||e instanceof re?e.channelName:""}static create(e){return new Pe(e)}static createMany(e){return e.map(e=>new Pe(e))}static createSafe(e){try{return new Pe(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=Y.contactDTO.safeParse(e);if(!t.success)return!1;return null!==Pe.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&Pe.canConstruct(e.data))}toJSON(){return{...this.data}}}class Ee{canHandle(e){return"Mobile"===e.type&&te.is(e)}createInput(e){if(te.is(e))return{type:exports.ContactType.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Contact Info")}}class De{canHandle(e){return"Bank"===e.type&&re.is(e)}createInput(e){if(re.is(e))return{type:exports.ContactType.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Contact Info")}}class Re{handlers=[new Ee,new De];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 Te=p().router({createContact:{method:"POST",path:"/",body:Y.contactInputDTO,responses:{201:Y.contactDTO}},editContact:{method:"PATCH",path:"/:id",body:Y.contactInputDTO,responses:{200:Y.contactDTO}},getContacts:{method:"GET",path:"/",query:e.z.object({orderByDesc:e.z.string()}),responses:{200:e.z.array(Y.contactDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:Y.contactDTO}},deleteContact:{method:"DELETE",path:"/:id",body:e.z.object({}),responses:{200:e.z.object({})}}});var xe,je,Me;exports.PayoutChannel=void 0,(xe=exports.PayoutChannel||(exports.PayoutChannel={})).MOBILE="Mobile",xe.BANK="Bank",exports.PayoutStatus=void 0,(je=exports.PayoutStatus||(exports.PayoutStatus={})).CREATED="CREATED",je.PENDING="PENDING",je.PAID="PAID",je.FAILED="FAILED",je.REJECTED="REJECTED",je.REVERSED="REVERSED",exports.PayoutApprovalStatus=void 0,(Me=exports.PayoutApprovalStatus||(exports.PayoutApprovalStatus={})).PENDING="Pending",Me.APPROVED="Approved",Me.REJECTED="Rejected";const Fe=e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string()}),Be=e.z.nativeEnum(exports.PayoutStatus),ke=e.z.nativeEnum(exports.PayoutApprovalStatus),Ue=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()}),$e=Ue.extend({payeeName:e.z.string()}),Le=Ue.extend({id:e.z.string(),profileId:e.z.string(),payeeName:e.z.string(),countryCode:e.z.string().default("TZ").refine(e=>o.CountryValidation.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>o.CurrencyValidation.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),channel:e.z.string(),status:Be,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:ke.nullish(),createdBy:Fe.nullish(),actionedBy:Fe.nullish()}),qe=e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(100).default(10),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().nullish(),endDate:e.z.string().datetime().nullish(),payeeName:e.z.string().nullish(),msisdn:e.z.string().nullish(),profileId:e.z.string().nullish(),id:e.z.string().nullish(),partnerReference:e.z.string().nullish(),channel:e.z.string().nullish(),currencyCode:e.z.string().nullish(),status:Be.nullish(),approvalStatus:ke.nullish(),minAmount:e.z.number().min(0).nullish(),maxAmount:e.z.number().min(0).nullish(),search:e.z.string().nullish()}),We={PayoutDTO:Le,PayoutInputDTO:$e,PayoutStatus:Be,PayoutApprovalStatus:ke,PayoutAuthorizer:Fe,PayoutFilters:qe,PayoutURLQueryParams:e.z.object({page:e.z.string().transform(e=>parseInt(e)||1).optional(),limit:e.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().optional(),endDate:e.z.string().optional(),payeeName:e.z.string().optional(),msisdn:e.z.string().optional(),profileId:e.z.string().optional(),id:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:e.z.string().optional(),status:e.z.string().refine(e=>Object.values(exports.PayoutStatus).includes(e)).transform(e=>e).optional(),approvalStatus:e.z.string().refine(e=>Object.values(exports.PayoutApprovalStatus).includes(e)).transform(e=>e).optional(),minAmount:e.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:e.z.string().transform(e=>parseFloat(e)).optional(),search:e.z.string().optional()})};class Je{data;constructor(e){this.data=We.PayoutDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get payeeName(){return this.data.payeeName}get channel(){return this.data.channel}get msisdn(){return this.data.msisdn}get amount(){return o.Amount.from(this.data.amount,this.data.currencyCode)}get description(){return this.data.description}get notes(){return this.data.notes}get status(){return"Rejected"===this.data.approvalStatus?exports.PayoutStatus.REJECTED:"Approved"===this.data.approvalStatus?"FAILED"===this.data.status?exports.PayoutStatus.FAILED:exports.PayoutStatus.PAID:"Pending"===this.data.approvalStatus?exports.PayoutStatus.PENDING:this.data.status}get statusMessage(){return this.data.statusMessage}get partnerReference(){return this.data.partnerReference}get createdAt(){return this.data.createdAt}get updatedAt(){return this.data.updatedAt}get actionedAt(){return this.data.actionedAt}get approvalStatus(){return this.data.approvalStatus}get createdBy(){return this.data.createdBy}get actionedBy(){return this.data.actionedBy}get contactInfo(){return"TZ-BANK-B2C"===this.channel?re.fromPayoutDTO(this.data):te.fromPayoutDTO(this.data)}static create(e){return new Je(e)}static createMany(e){return e.map(e=>new Je(e))}static createSafe(e){try{return new Je(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=We.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==Je.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&Je.canConstruct(e.data))}toJSON(){return{...this.data}}}const Ve={SUPPORTED_COUNTRY_CODES:["TZ","KE"],ERROR_MESSAGES:{INVALID_PHONE_NUMBER:"Invalid phone number",INELIGIBLE_FOR_PAYOUT:"The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",MOBILE_NUMBER_MNO_MISMATCH:"There is a mismatch between the phone number provided and the MNO used.",UNSUPPORTED_COUNTRY_BANK:"Only Tanzanian Banks are supported for now",UNSUPPORTED_COUNTRY_MOBILE:"Only Tanzanian mobile numbers are supported for now",NO_HANDLER_FOUND:"Cannot create payout input!"}};class Ge{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}}class He{static forBank(e,t){if(!Ve.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ve.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,t,r){if(!o.PhoneNumber.is(e))throw new Error(Ve.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!Ve.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ve.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!o.PhoneNumberFactory.checkPayoutEligibility(e))throw new Error(Ve.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const n=o.MNOUtils.getMNOById(t,e.countryCode);if(!n)throw new Error(Ve.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return n.id===o.TZMNOId.VODACOM?`${r.countryCode}-${o.TZMNOId.TIGO.toString().toUpperCase()}-B2C`:`${r.countryCode}-${n.id.toString().toUpperCase()}-B2C`}}class Qe{canHandle(e,t,r){return e===exports.PayoutChannel.MOBILE&&te.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===o.Country.from(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=Ge.processNotes(e.notes),a=r.phoneNumber;return{channel:He.forMobile(a,r.mnoId,t),msisdn:a.getWithFormat(o.PhoneNumberFormat.INTERNATIONAL_NUMERIC),description:n??le.generateDefaultPayoutNarration(r),payeeName:r.name,notes:n,amount:e.amount.numericValue}}}class Ze{canHandle(e,t,r){return e===exports.PayoutChannel.BANK&&re.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===o.Country.from(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,o=Ge.processNotes(e.notes);return{channel:He.forBank(r,t),msisdn:`${r.bank.swiftCode}:${r.accNo}`,description:o??le.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:o,amount:e.amount.numericValue}}}class Ke{handlers=[new Qe,new Ze];getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(Ve.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const Ye={bank:He.forBank,mobile:He.forMobile},Xe=p().router({getPayouts:{method:"GET",path:"",query:e.z.object({}),responses:{200:e.z.object({results:e.z.array(We.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:We.PayoutApprovalStatus,orderByDesc:e.z.string()}),responses:{200:e.z.object({results:e.z.array(We.PayoutDTO),total:e.z.number()})}},postPayout:{method:"POST",path:"",body:We.PayoutInputDTO,responses:{201:We.PayoutDTO,400:s.schema}},approve:{method:"POST",path:"/:id/approve",body:e.z.object({action:e.z.enum(["Approve","Reject"]),notes:e.z.string().optional()}),responses:{201:We.PayoutDTO,404:e.z.object({}),409:e.z.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:We.PayoutDTO,404:e.z.object({})}}});class et extends ${static create(){return new et}static fromFilters(e){return(new et).applyFilters(e)}static fromUrlParams(e){try{const t=We.PayoutURLQueryParams.parse(e),r=We.PayoutFilters.parse(t);return et.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return et.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return et.fromSearchParams(t)}static from(e){try{return null==e?new et:$.is(e)?new et(e.options):e instanceof URLSearchParams?et.fromSearchParams(e):this.isStringRecord(e)?et.fromUrlParams(e):et.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a PayoutQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereStatus(e){return this.where("status",e)}whereApprovalStatus(e){return this.where("approvalStatus",e)}whereChannel(e){return this.where("channel",e)}wherePending(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.PENDING)}whereApproved(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.APPROVED)}whereRejected(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.REJECTED)}wherePaid(){return this.whereStatus(exports.PayoutStatus.PAID)}whereFailed(){return this.whereStatus(exports.PayoutStatus.FAILED)}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}wherePayee(e){return this.whereContains("payeeName",e)}whereMsisdn(e){return this.whereContains("msisdn",e)}whereProfileId(e){return this.where("profileId",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.status&&this.whereStatus(e.status),e.approvalStatus&&this.whereApprovalStatus(e.approvalStatus),e.channel&&this.whereChannel(e.channel),e.payeeName&&this.wherePayee(e.payeeName),e.msisdn&&this.whereMsisdn(e.msisdn),e.profileId&&this.whereProfileId(e.profileId),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&e.minAmount&&void 0!==e.maxAmount&&e.maxAmount?this.whereAmountBetween(e.minAmount,e.maxAmount):void 0!==e.minAmount?this.whereGreaterThanOrEqual("amount",e.minAmount):void 0!==e.maxAmount&&this.whereLessThanOrEqual("amount",e.maxAmount)),e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,payeeName:e.payeeName,msisdn:e.msisdn,profileId:e.profileId,id:e.id,partnerReference:e.partnerReference,channel:e.channel,status:this.isValidStatus(e.status)?e.status:void 0,approvalStatus:this.isValidApprovalStatus(e.approvalStatus)?e.approvalStatus:void 0,minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withApprovalStatus(e){const t=this.clone();return e&&t.whereApprovalStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}includeDefaultRelations(){return this.with("[createdBy,actionedBy]")}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.payeeName||e.msisdn||e.profileId||e.id||e.partnerReference||e.channel||e.status||e.approvalStatus||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.status&&e.push(`Status: ${t.status}`),t.approvalStatus&&e.push(`Approval: ${t.approvalStatus}`),t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.payeeName&&e.push(`Payee: ${t.payeeName}`),t.msisdn&&e.push(`MSISDN: ${t.msisdn}`),t.profileId&&e.push(`Profile: ${t.profileId}`),t.partnerReference&&e.push(`Ref: ${t.partnerReference}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"payeeName":case"msisdn":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}return e}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidStatus(e){return Object.values(exports.PayoutStatus).includes(e)}isValidApprovalStatus(e){return Object.values(exports.PayoutApprovalStatus).includes(e)}}const tt=p().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:P.schema}}});exports.APIError=s,exports.AfloatAuth=_e,exports.AuthRepository=ze,exports.BANK_NARR_PREFIX=ae,exports.BankContactInfo=re,exports.BaseRepository=F,exports.CompanyMembership=R,exports.Contact=Pe,exports.ContactDTOSchemas=Y,exports.ContactRepository=class extends F{constructor(e){super("contact",Te,e)}async create(e){const t=(new Re).resolve(e),r=await this.client.createContact({body:t}),o=this.handleResponse(r,201);return Pe.create(o)}async edit(e,t){const r=(new Re).resolve(t),o=await this.client.editContact({params:{id:e},body:r}),n=this.handleResponse(o,200);return Pe.create(n)}async remove(e){const t=await this.client.deleteContact({params:{id:e}});this.handleResponse(t,200)}async getAll(){const e=await this.client.getContacts({query:{orderByDesc:"createdAt"}}),t=this.handleResponse(e,200);return Pe.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return Pe.create(r)}},exports.ECOBANK_PREFIX=oe,exports.IdentityRepository=be,exports.LEGACY_BANK_NARR_PREFIX=se,exports.LEGACY_MOBILE_NARR_PREFIX=ce,exports.LogIn=D,exports.LogInSchemas=E,exports.MOBILE_NARR_PREFIX=ie,exports.MobileContactInfo=te,exports.NARR_V2_PREFIX=ne,exports.Narration=le,exports.Pagination=W,exports.PaginationParamsSchema=L,exports.PaginationSchema=q,exports.Payout=Je,exports.PayoutDTOSchemas=We,exports.PayoutInputFactory=Ke,exports.PayoutQuery=et,exports.PayoutRepository=class extends F{constructor(e){super("payout",Xe,e)}async getPayouts(e){try{const t=et.from(e),r=t.build(),o=await this.client.getPayouts({query:r}),n=this.handleResponse(o,200),a=t.toFilters(),s=new W(a.page??1,a.limit??10,n.total);return{results:Je.createMany(n.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=et.from(e).build();delete t.page,delete t.limit;const r=await this.client.getPayouts({query:t}),o=this.handleResponse(r,200);return Je.createMany(o.results)}catch(e){throw new Error(`Failed to fetch all payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=et.fromRequest(e);return this.getPayouts(t)}async pay(e){const{min:t,max:r}=o.Amount.getTransactionLimits(e.amount.currencyCode);if(e.amount.lessThan(t)||e.amount.greaterThan(r))throw new s({statusCode:400,message:`Please make sure the amount is between ${t.label} - ${r.label}`});const n=fe.instance.getSelectedWallet();if(!n)throw new Error("You have not selected a wallet to process this payout");const a=(new Ke).getPayoutInput(e,n),i=await this.client.postPayout({body:a});if(201===i.status)return Je.create(i.body);if(400===i.status)throw new s(i.body);throw s.unknown()}async approve(e,t){const r=await this.client.approve({params:{id:e},body:{action:"Approve",notes:t?.notes}});if(201===r.status)return Je.create(r.body);if(404===r.status)throw new s({message:"Payout not found",statusCode:404});if(409===r.status)throw new s({message:"Payout already approved",statusCode:409});throw s.unknown()}async reject(e,t){const r=await this.client.approve({params:{id:e},body:{action:"Reject",notes:t?.notes}});if(201===r.status)return Je.create(r.body);if(404===r.status)throw new s({message:"Payout not found",statusCode:404});if(409===r.status)throw new s({message:"Payout already rejected",statusCode:409});throw s.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return Je.create(t.body);if(404===t.status)throw new s({message:"Payout not found",statusCode:404});throw s.unknown()}async count(e){const t=et.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=c,exports.Permissions=i,exports.Profile=P,exports.ProfileDTOSchemas=_,exports.ProfileRepository=class extends F{constructor(e){super("profile",tt,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=P.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=U,exports.QueryBuilder=$,exports.Role=T,exports.TeamManagementDTOSchemas=Ae,exports.TeamMember=Ie,exports.TeamMemberRepository=Oe,exports.User=x,exports.Wallet=G,exports.WalletDTOSchemas=V,exports.WalletRepository=pe,exports.WalletSessionManager=fe,exports.WalletStatementEntry=de,exports.WalletUtils=H,exports.createPaginatedResponse=function(e,t,r,o){return{results:e,pagination:new W(t,r,o)}},exports.createPaginatedResponseSchema=function(t){return e.z.object({results:e.z.array(t),pagination:q})},exports.createPayoutChannelCode=Ye,exports.emptyPaginatedResponse=function(e=1,t=10){return{results:[],pagination:new W(e,t,0)}},exports.isError=function(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message},exports.walletsStore=ye;
1
+ "use strict";var e=require("zod"),t=require("uuid"),r=require("zustand"),o=require("@temboplus/frontend-core");function n(e){return e&&e.__esModule?e:{default:e}}var a=n(e);class s 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 s.schema.safeParse(e).success}static unknown(e){return new s({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 i={Profile:{ViewCurrent:"profile.getCurrent",Update:"profile.update"},Contact:{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 c 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(i.Profile)),e.z.enum(Object.values(i.Contact)),e.z.enum(Object.values(i.Payment)),e.z.enum(Object.values(i.Payout)),e.z.enum(Object.values(i.Transfer)),e.z.enum(Object.values(i.Wallet))]);return e.z.object({name:e.z.literal("PermissionError").nullish(),message:e.z.string(),requiredPermissions:e.z.array(r)}).safeParse(t).success}}const l=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,h=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var o,n,a,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,l(s)?l(i)?s.merge(i):s:l(i)?i:Object.assign({},s,i)),strictStatusCodes:null!==(o=r.strictStatusCodes)&&void 0!==o?o:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(n=r.validateResponseOnClient)&&void 0!==n?n: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!==(a=r.metadata)&&void 0!==a?a:{}}:r.metadata}]:[e,h(r,t)]})),m=Symbol("ContractPlainType"),p=()=>({router:(e,t)=>h(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>m,body:()=>m,type:()=>m,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>u}),y=e=>e?Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r;return r="string"==typeof t&&!["true","false","null"].includes(t.trim())&&isNaN(Number(t))?t:JSON.stringify(t),`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).join("&"):"",f=e=>e?Object.keys(e).flatMap(t=>g(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",g=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>g(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>g(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class w extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const b=async({route:e,path:t,method:r,headers:o,body:n,validateResponse:a,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:o,body:n}),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!=a?a:e.validateResponseOnClient)&&"function"==typeof(null==(l=r)?void 0:l.safeParse)?{...t,body:r.parse(t.body)}:t}var l;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}},N=e=>{const t=new FormData,r=(e,r)=>{r instanceof File?t.append(e,r):t.append(e,JSON.stringify(r))};return Object.entries(e).forEach(([e,t])=>{if(Array.isArray(t))for(const o of t)r(e,o);else r(e,t)}),t},v=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),C=(e,t,r,o,n)=>{const a=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:o.path,params:r}),s=((e,t=!1)=>{const r=t?y(e):f(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,n);return`${t}${a}${s}`},A=(e,t)=>{const r=Object.keys(e.responses);return async o=>{const n=((e,t,r)=>{const{query:o,params:n,body:a,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:l,cache:u,next:d,...h}=r||{},m={...t,...c};return{path:C(o,m.baseUrl,n,e,!!m.jsonQuery),clientArgs:m,route:e,body:a,query:o,extraInputArgs:h,fetchOptions:{...u&&{cache:u},...d&&{next:d},...l},headers:{...i,...s}}})(e,t,o),a=await(e=>{const{path:t,clientArgs:r,route:o,body:n,query:a,extraInputArgs:s,headers:i,fetchOptions:c}=e,l=r.api||b,u=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),d={...u&&v(u),...v(i)};Object.keys(d).forEach(e=>{void 0===d[e]&&delete d[e]});let h={route:o,path:t,method:o.method,headers:d,body:void 0,rawBody:n,rawQuery:a,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==o.method&&("contentType"in o&&"multipart/form-data"===o.contentType?h={...h,contentType:"multipart/form-data",body:n instanceof FormData?n:N(n)}:"contentType"in o&&"application/x-www-form-urlencoded"===o.contentType?h={...h,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...h.headers},body:"string"==typeof n?n:new URLSearchParams(n)}:null!=n&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(n)})),l({...h,...s})})(n);if(!t.throwOnUnknownStatus)return a;if(r.includes(a.status.toString()))return a;throw new w(a,r)}},S=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>d(r)?[e,A(r,t)]:[e,S(r,t)]));function O(e,t){let r;try{r=e()}catch(e){return}return{getItem:e=>{var o;const n=e=>null===e?null:JSON.parse(e,null==t?void 0:t.reviver),a=null!=(o=r.getItem(e))?o:null;return a instanceof Promise?a.then(n):n(a)},setItem:(e,o)=>r.setItem(e,JSON.stringify(o,null==t?void 0:t.replacer)),removeItem:e=>r.removeItem(e)}}const I=e=>t=>{try{const r=e(t);return r instanceof Promise?r:{then:e=>I(e)(r),catch(e){return this}}}catch(e){return{then(e){return this},catch:t=>I(t)(e)}}},z=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?(console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),((e,t)=>(r,o,n)=>{let a={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},s=!1;const i=new Set,c=new Set;let l;try{l=a.getStorage()}catch(e){}if(!l)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),r(...e)},o,n);const u=I(a.serialize),d=()=>{const e=a.partialize({...o()});let t;const r=u({state:e,version:a.version}).then(e=>l.setItem(a.name,e)).catch(e=>{t=e});if(t)throw t;return r},h=n.setState;n.setState=(e,t)=>{h(e,t),d()};const m=e((...e)=>{r(...e),d()},o,n);let p;const y=()=>{var e;if(!l)return;s=!1,i.forEach(e=>e(o()));const t=(null==(e=a.onRehydrateStorage)?void 0:e.call(a,o()))||void 0;return I(l.getItem.bind(l))(a.name).then(e=>{if(e)return a.deserialize(e)}).then(e=>{if(e){if("number"!=typeof e.version||e.version===a.version)return e.state;if(a.migrate)return a.migrate(e.state,e.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}}).then(e=>{var t;return p=a.merge(e,null!=(t=o())?t:m),r(p,!0),d()}).then(()=>{null==t||t(p,void 0),s=!0,c.forEach(e=>e(p))}).catch(e=>{null==t||t(void 0,e)})};return n.persist={setOptions:e=>{a={...a,...e},e.getStorage&&(l=e.getStorage())},clearStorage:()=>{null==l||l.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>y(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e)})},y(),p||m})(e,t)):((e,t)=>(r,o,n)=>{let a={storage:O(()=>localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},s=!1;const i=new Set,c=new Set;let l=a.storage;if(!l)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),r(...e)},o,n);const u=()=>{const e=a.partialize({...o()});return l.setItem(a.name,{state:e,version:a.version})},d=n.setState;n.setState=(e,t)=>{d(e,t),u()};const h=e((...e)=>{r(...e),u()},o,n);let m;n.getInitialState=()=>h;const p=()=>{var e,t;if(!l)return;s=!1,i.forEach(e=>{var t;return e(null!=(t=o())?t:h)});const n=(null==(t=a.onRehydrateStorage)?void 0:t.call(a,null!=(e=o())?e:h))||void 0;return I(l.getItem.bind(l))(a.name).then(e=>{if(e){if("number"!=typeof e.version||e.version===a.version)return[!1,e.state];if(a.migrate)return[!0,a.migrate(e.state,e.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}return[!1,void 0]}).then(e=>{var t;const[n,s]=e;if(m=a.merge(s,null!=(t=o())?t:h),r(m,!0),n)return u()}).then(()=>{null==n||n(m,void 0),m=o(),s=!0,c.forEach(e=>e(m))}).catch(e=>{null==n||n(void 0,e)})};return n.persist={setOptions:e=>{a={...a,...e},e.storage&&(l=e.storage)},clearStorage:()=>{null==l||l.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>p(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e)})},a.skipHydration||p(),m||h})(e,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()})};class P{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return _.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 P({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()}toObject(){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}}toJSON(){return JSON.stringify(this.toObject())}validate(){try{return P.schema.safeParse(this.toObject()).success}catch(e){return console.error("Profile validation error:",e),!1}}static fromJSON(e){try{const t=JSON.parse(e);return P.from(t)}catch(e){return void console.error("Error parsing profile JSON:",e)}}static from(e){try{return e?"object"!=typeof e?void console.error("Data is not an object"):e.id&&e.accountNo&&e.displayName?P.create({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove}):void console.error("Missing required profile fields"):void console.error("Data is null or undefined")}catch(e){return void console.error("Error creating profile from object:",e)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t._id||"string"!=typeof t._displayName||"string"!=typeof t._accountNo)return!1;if(null!==t._firstName&&void 0!==t._firstName&&"string"!=typeof t._firstName)return!1;if(null!==t._lastName&&void 0!==t._lastName&&"string"!=typeof t._lastName)return!1;if(null!==t._email&&void 0!==t._email&&"string"!=typeof t._email)return!1;const r=t._phone;if(null!=r&&"string"!=typeof r)return!1;const o=t._autoApprove;return null==o||"boolean"==typeof o}}const E={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())})};class D{_id;_profileId;_name;_identity;_type;_roleId;_isActive;_isArchived;_resetPassword;_createdAt;_updatedAt;_access;constructor(e,t,r,o,n,a,s,i,c,l,u,d){this._id=e,this._profileId=t,this._name=r,this._identity=o,this._type=n,this._roleId=a,this._isActive=s,this._isArchived=i,this._resetPassword=c,this._createdAt=l,this._updatedAt=u,this._access=d}static from(e){const t=E.loginDTO.parse(e);return new D(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)}static fromJson(e){try{const t=JSON.parse(e);return D.from(t)}catch(e){return void console.error("Error parsing LogIn JSON:",e)}}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}toObject(){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]}}toJson(){return JSON.stringify(this.toObject())}}class R{_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return P.is(e.companyProfile)?new R(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}toObject(){return{companyProfile:this._companyProfile.toObject(),role:this._role?.toJSON()}}toJson(){return JSON.stringify(this.toObject())}}class T{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 T(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()}}}class x{_logIn;_membership;_token;_permissionMap;constructor(e){this._logIn=e.logIn,this._membership=e.membership,this._token=e.token,this._permissionMap={},this._logIn.access.forEach(e=>{this._permissionMap[e]=!0})}static from(e){try{if(!e.logIn||!e.companyProfile||!e.token)return void console.error("Missing required User fields");if("string"!=typeof e.token||""===e.token.trim())return void console.error("Invalid token");const t=R.from({companyProfile:e.companyProfile,role:e.role});return t?new x({logIn:e.logIn,membership:t,token:e.token}):void console.error("Failed to create CompanyMembership")}catch(e){return void console.error("Error creating User:",e)}}static fromJson(e){try{const t=JSON.parse(e),r=D.from(t.logIn),o=P.from(t.companyProfile||t.profile),n=t.role?T.from(t.role):void 0;return r&&o?x.from({logIn:r,companyProfile:o,role:n,token:t.token}):void console.error("Failed to reconstruct nested objects")}catch(e){return void console.error("Error parsing User JSON:",e)}}get logIn(){return this._logIn}get membership(){return this._membership}get token(){return this._token}get id(){return this._logIn.id}get name(){return this._logIn.name}get identity(){return this._logIn.identity}get roleId(){return this._logIn.roleId}get resetPassword(){return this._logIn.resetPassword}get profile(){return this._membership.companyProfile}get role(){return this._membership.role}get access(){return this._logIn.access}can(e){return this._permissionMap[e]??!1}canAny(e){return e.some(e=>this.can(e))}canAll(e){return e.every(e=>this.can(e))}canManageTeam(){return this.can(i.TeamManagement.ViewMembers)}canViewRoles(){return this.can(i.Role.ViewRole)}toObject(){return{logIn:this._logIn.toObject(),profile:this._membership.companyProfile.toObject(),role:this._membership.role?.toJSON(),token:this._token,access:[...this._logIn.access],resetPassword:this._logIn.resetPassword}}toJson(){return JSON.stringify(this.toObject())}}const j=r.create(z((e,t)=>({user:void 0,token:void 0,getUser:()=>{try{const e=t().user;if(e)return x.fromJson(e)}catch(e){console.warn("Failed to deserialize user from store:",e)}},setUser:t=>{try{e({user:t.toJson()})}catch(e){console.error("Failed to serialize user to store:",e)}},getToken:()=>t().token,setToken:t=>e({token:t}),setUserAndToken:(t,r)=>{try{e({user:t.toJson(),token:r})}catch(e){console.error("Failed to serialize user and token to store:",e)}},clearAuth:()=>e({user:void 0,token:void 0})}),{name:"auth-store",storage:O(()=>"undefined"==typeof window?{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}:sessionStorage)})),M=()=>{if("undefined"!=typeof window)return j.getState().getToken()};class F{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;try{const e=M();if(e&&e.trim().length>0)return e;console.warn(`No token available from global auth state for ${this.endpoint} repository`)}catch(e){console.warn(`No valid token available for ${this.endpoint} repository. Please provide a token directly in the constructor or ensure a user is logged in via AfloatAuth.instance.`)}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 S(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 s(t.data);throw new s({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===e.status)throw new s({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new s({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new s({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new s({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}var k,B;exports.FilterOperator=void 0,(k=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",k.NOT_EQUALS="neq",k.LESS_THAN="lt",k.LESS_THAN_OR_EQUAL="lte",k.GREATER_THAN="gt",k.GREATER_THAN_OR_EQUAL="gte",k.LIKE="like",k.LIKE_LOWER="likeLower",k.IS_NULL="isNull",k.IS_NOT_NULL="isNotNull",k.IN="in",exports.SortDirection=void 0,(B=exports.SortDirection||(exports.SortDirection={})).ASC="asc",B.DESC="desc";const U=Symbol("query-builder-type");class ${options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8};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}}[U]="query-builder";static is(e){return null!==e&&"object"==typeof e&&U in e&&"query-builder"===e[U]}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){return e&&this.whereGreaterThanOrEqual("createdAt",e),t&&this.whereLessThanOrEqual("createdAt",t),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(","))}const t=this.options.filters?.filter(e=>"createdAt"===e.field&&(e.operator===exports.FilterOperator.GREATER_THAN_OR_EQUAL||e.operator===exports.FilterOperator.LESS_THAN_OR_EQUAL));if(t){const r=t.find(e=>e.operator===exports.FilterOperator.GREATER_THAN_OR_EQUAL),o=t.find(e=>e.operator===exports.FilterOperator.LESS_THAN_OR_EQUAL);r&&(e.startDate=r.value),o&&(e.endDate=o.value)}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?e.eager=this.options.includes[0]:e.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(e.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(e.groupBy=this.options.groupBy.join(",")),this.options.count&&(e.count=this.options.count),e}clone(){return new(0,this.constructor)({...this.options,filters:this.options.filters?[...this.options.filters]:[],sort:this.options.sort?[...this.options.sort]:[],includes:this.options.includes?[...this.options.includes]:[],groupBy:this.options.groupBy?[...this.options.groupBy]:[],join:this.options.join?[...this.options.join]:[]})}static create(e){return new $(e)}}const L=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)}),J=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 q{page;limit;total;constructor(e,t,r){if(this.page=e,this.limit=t,this.total=r,e<1)throw new Error("Page must be >= 1");if(t<1)throw new Error("Limit must be >= 1");if(r<0)throw new Error("Total must be >= 0")}get totalPages(){return Math.ceil(this.total/this.limit)}get hasNext(){return this.page<this.totalPages}get hasPrev(){return this.page>1}get offset(){return(this.page-1)*this.limit}get isFirstPage(){return 1===this.page}get isLastPage(){return this.page===this.totalPages}nextPage(){return this.hasNext?new q(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new q(this.page-1,this.limit,this.total):null}toJSON(){return{page:this.page,limit:this.limit,total:this.total,totalPages:this.totalPages,hasNext:this.hasNext,hasPrev:this.hasPrev}}}const W=e=>e.optional().transform(e=>e??void 0),V={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=>o.CountryValidation.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>o.CurrencyValidation.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:e.z.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:e.z.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:e.z.object({id:e.z.string().optional(),profileId:e.z.string().optional(),accountNo:e.z.string().optional(),accountName:e.z.string().optional(),channel:e.z.string().optional(),countryCode:e.z.string().default("TZ").refine(e=>o.ISO2CountryCodesSet.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:e.z.string().default("TZS").refine(e=>{const t=o.Currency.from(e);return void 0!==t&&o.CurrencyCodesSet.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:e.z.object({accountNo:W(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:W(e.z.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})};class G{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return V.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=G.schema.safeParse(e);if(t.success)return new G(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)}toObject(){return{id:this._id,profileId:this._profileId,accountNo:this._accountNo,accountName:this._accountName,channel:this._channel,countryCode:this._countryCode,createdAt:this._createdAt,updatedAt:this._updatedAt,currencyCode:this._currencyCode}}toJSON(){return JSON.stringify(this.toObject())}validate(){const e=G.schema.safeParse(this.toObject());return e.success||console.warn("Wallet instance validation failed:",e.error.flatten()),e.success}static fromJSON(e){try{const t=JSON.parse(e);return G.from(t)}catch(e){return void console.error("Error parsing wallet JSON:",e)}}static from(e){if(e&&"object"==typeof e)return G.create({id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt,currencyCode:e.currencyCode});console.error("Invalid data provided to Wallet.from: Input must be an object.")}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.profileId&&"string"==typeof t.accountNo&&"string"==typeof t.accountName&&"string"==typeof t.channel&&"string"==typeof t.countryCode&&o.CountryValidation.isISO2CountryCode(t.countryCode)&&"string"==typeof t.currencyCode&&o.CurrencyValidation.isCurrencyCode(t.currencyCode)&&"string"==typeof t.createdAt&&"string"==typeof t.updatedAt&&"function"==typeof t.toObject&&"function"==typeof t.validate}}const H={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)};var Q;exports.ContactType=void 0,(Q=exports.ContactType||(exports.ContactType={})).Bank="Bank",Q.Mobile="Mobile";const Z=e.z.nativeEnum(exports.ContactType),K=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:Z}),Y={contactDTO:e.z.object({id:e.z.string().min(1,"Contact id is required"),profileId:e.z.string(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime()}).merge(K),contactInputDTO:K,contactType:Z};class X extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="ContactInfoError"}}class ee{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}toJSON(){return JSON.stringify(this.toObject())}}class te extends ee{name;phoneNumber;mnoId;constructor(e,t,r){if(super(exports.ContactType.Mobile,t.countryCode),this.name=e,this.phoneNumber=t,!e?.trim())throw new X("Name is required and cannot be empty",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(!t?.validate())throw new X("Invalid phone number",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(o.MNOUtils.requiresExplicitMNO(t.countryCode)){if(!r)throw new X(`MNO must be explicitly provided for phone numbers in ${t.countryCode} due to Mobile Number Portability`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});if(!o.MNOUtils.isValidMNOForCountry(r,t.countryCode)){const e=o.MNOUtils.getCountryMNOs(t.countryCode).map(e=>e.id);throw new X(`Invalid MNO ${r} for country ${t.countryCode}. Valid MNOs: ${e.join(", ")}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,mnoId:r,operation:"constructor"})}this.mnoId=r}else{const e=o.MNOUtils.getMNOByPhoneNumber(t.e164Format,t.countryCode);if(!e?.id)throw new X(`Failed to determine MNO for phone number ${t.e164Format}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});this.mnoId=e.id}}static from(e){try{return new te(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileContactInfo:",e)}}static fromContactDTO(e){if("Mobile"!==e.type)return;let t=e.accountNo;t.startsWith("+")||(t=`+${t}`);const r=o.PhoneNumber.from(t);if(!r)return void console.error(`Failed to parse phone number ${t}`);const n=r.countryCode;try{let t;if(o.MNOUtils.requiresExplicitMNO(n)){if(e.channel&&"string"==typeof e.channel){if(!o.MNOUtils.isValidMNOForCountry(e.channel,n))return void console.warn(`Invalid MNO ${e.channel} for country ${n}`);t=e.channel}}else if(t=o.MNOUtils.getMNOByPhoneNumber(r.e164Format,n)?.id,!t)return void console.warn(`Failed to auto-detect MNO for phone number ${r.e164Format}`);return te.from({name:e.displayName,phoneNumber:r,mnoId:t})}catch(e){return void console.error(`Failed to create MobileContactInfo: ${e}`)}}static fromPayoutDTO(e){try{if(!o.CountryValidation.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=o.PhoneNumber.from(e.msisdn,{defaultCountry:e.countryCode});if(!t)return void console.error(`Failed to parse phone number: ${e.msisdn}`);let r;if(o.MNOUtils.requiresExplicitMNO(t.countryCode)){if(e.channel&&"string"==typeof e.channel){if(!o.MNOUtils.isValidMNOForCountry(e.channel,t.countryCode))return void console.warn(`Invalid MNO ${e.channel} for country ${t.countryCode} in PayoutDTO`);r=e.channel}}else if(r=o.MNOUtils.getMNOByPhoneNumber(t.e164Format,t.countryCode)?.id,!r)return void console.warn(`Failed to auto-detect MNO for phone number ${t.e164Format}`);return te.from({name:e.payeeName,phoneNumber:t,mnoId:r})}catch(t){return void console.error("Failed to create MobileContactInfo from PayoutDTO: ",e,t)}}static fromJSON(e){try{const t=JSON.parse(e);let r;return"string"==typeof t.phoneNumber?r=o.PhoneNumber.from(t.phoneNumber):t.phoneNumber?.e164Format&&(r=o.PhoneNumber.from(t.phoneNumber.e164Format)),r?te.from({name:t.name,phoneNumber:r,mnoId:t.mnoId}):void console.error("Failed to parse phone number from JSON")}catch(e){return void console.error("Error parsing MobileContactInfo JSON:",e)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.name||!t.name.trim())return!1;let r;if("string"==typeof t.phoneNumber)r=o.PhoneNumber.from(t.phoneNumber);else if("object"==typeof t.phoneNumber){const e=t.phoneNumber;o.PhoneNumber.is(e)&&(r=o.PhoneNumber.from(e.e164Format))}if(!r)return!1;const n=t.mnoId;if("string"!=typeof n)return!1;if(!o.MNOUtils.isValidMNOForCountry(n,r.countryCode))return!1;if(o.MNOUtils.requiresExplicitMNO(r.countryCode))return!0;{const e=o.MNOUtils.getMNOByPhoneNumber(r.e164Format,r.countryCode);return e?.id===n}}validate(){try{return!!this.name?.trim()&&(!!this.phoneNumber?.validate()&&(!!o.MNOUtils.isValidMNOForCountry(this.mnoId,this.countryCode)&&(!!o.MNOUtils.requiresExplicitMNO(this.countryCode)||o.MNOUtils.validateMNOForPhoneNumber(this.phoneNumber.e164Format,this.mnoId,this.countryCode))))}catch{return!1}}getValidationDetails(){const e=[];if(this.name?.trim()||e.push("Name is required"),this.phoneNumber?.validate()||e.push("Phone number is invalid"),o.MNOUtils.isValidMNOForCountry(this.mnoId,this.countryCode)||e.push(`Invalid MNO ${this.mnoId} for country ${this.countryCode}`),!o.MNOUtils.requiresExplicitMNO(this.countryCode)){const t=o.MNOUtils.getMNOByPhoneNumber(this.phoneNumber.e164Format,this.countryCode);t?.id!==this.mnoId&&e.push("MNO doesn't match auto-detected value from phone number prefix")}return{isValid:0===e.length,errors:e,warnings:[]}}toObject(){return{type:this.type,name:this.name,phoneNumber:this.phoneNumber.e164Format,mnoId:this.mnoId,countryCode:this.countryCode}}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(o.PhoneNumberFormat.E164)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){const e=o.MNOUtils.getMNOById(this.mnoId,this.countryCode);return e?.mobileMoneyService??e?.displayName??this.mnoId}}class re extends ee{accName;bank;accNo;constructor(e,t,r){if(super(exports.ContactType.Bank,t.countryCode),this.accName=e,this.bank=t,this.accNo=r,!o.BankValidation.validateAccountName(e))throw new X("Invalid account name",{operation:"constructor",countryCode:t.countryCode});if(!o.BankValidation.validateAccountNumber(r,t.countryCode))throw new X("Invalid account number",{operation:"constructor",countryCode:t.countryCode})}static from(e){try{return new re(e.accName,e.bank,e.accNo)}catch(e){return void console.error("Failed to create BankContactInfo:",e)}}static fromContactDTO(e){if("Bank"!==e.type)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank contacts");const r=o.BankValidation.getCountryFromSwiftCode(t);if(r)if(o.BankValidation.validateSwiftCode(t,r))try{const n=o.Bank.from(t,r);if(!n)throw new Error(`Bank with SWIFT code ${t} not found`);return re.from({accName:e.displayName,bank:n,accNo:e.accountNo})}catch(e){return void console.error(`Failed to create BankContactInfo: ${e}`)}else console.error(`Invalid SWIFT code ${t} for country ${r}`);else console.error(`Could not identify country from SWIFT code: ${t}`)}static fromPayoutDTO(e){try{if(!o.CountryValidation.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=e.msisdn.trim().split(":");if(2!==t.length)return void console.error("Invalid PayoutDTO format for bank - expected 'swiftcode:accountno'");const[r,n]=t;if(!o.BankValidation.validateSwiftCode(r,e.countryCode))return void console.error(`Invalid SWIFT code ${r} for country ${e.countryCode}`);const a=o.Bank.from(r,e.countryCode);return a?re.from({accName:e.payeeName,bank:a,accNo:n}):void console.error(`Bank with SWIFT code ${r} not found`)}catch(t){return void console.error("Failed to create BankContactInfo from PayoutDTO: ",e,t)}}static fromJSON(e){try{const t=JSON.parse(e);let r;return t.bank&&"object"==typeof t.bank?r=o.Bank.from(t.bank.swiftCode,t.bank.countryCode):t.swiftCode&&t.countryCode&&(r=o.Bank.from(t.swiftCode,t.countryCode)),r?re.from({accName:t.accName,bank:r,accNo:t.accNo}):void console.error("Failed to reconstruct Bank from JSON")}catch(e){return void console.error("Error parsing BankContactInfo JSON:",e)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.accName)return!1;if("string"!=typeof t.accNo)return!1;if(!t.bank||!o.Bank.is(t.bank))return!1;const r=t.accName,n=t.accNo,a=t.bank,s=o.BankValidation.validateAccountName(r),i=o.BankValidation.validateAccountNumber(n,a.countryCode);return s&&i}validate(){try{return o.BankValidation.validateAccountName(this.accName)&&o.BankValidation.validateAccountNumber(this.accNo,this.bank.countryCode)&&o.Bank.is(this.bank)}catch{return!1}}toObject(){return{type:this.type,accName:this.accName,bank:this.bank.toObject(),accNo:this.accNo,countryCode:this.countryCode}}get accountName(){return this.accName}get accountNumber(){return this.accNo}get accountNameLabel(){return"Acc. Name"}get accountNumberLabel(){return"Bank Acc. No."}get channelLabel(){return"Bank"}get channelId(){return this.bank.swiftCode}get channelName(){return this.bank.shortName}}const oe="MOBILE TRANSFER ",ne="PAYOUT",ae="PAYOUT TO BANK",se="TO_BANK",ie="PAYOUT TO MOBILE",ce="TO_MOMO";class le{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 te.is(e)?le.generateMobilePayoutNarrationV2(e):re.is(e)?le.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${ne.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:o}=e;return`${ne.toUpperCase()} ${t.swiftCode.trim()} ${o.trim()} ${r.trim()}`.toUpperCase()}getContactDetails=()=>{const e=this.getBankContactDetails(),t=this.getMobileContactDetails();return e||(t||void 0)};getBankContactDetails=()=>{let e=this.text.trim();e.startsWith(oe)&&(e=e.substring(16));try{if(e.startsWith(ne)){const t=e.replace(ne,"").trim().split(" ");if(t.length>=3){const e=t[0],r=t[1],n=t.slice(2).map(ue).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=o.BankValidation.getCountryFromSwiftCode(e);if(t){if(o.BankValidation.validateSwiftCode(e,t)){const a=o.Bank.from(e,t);if(r&&n&&a)return new re(n,a,r)}}}}}if(e.startsWith(se)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=r.account_number,a=r.account_name,s=r.swift_code,i=o.BankValidation.getCountryFromSwiftCode(s);if(!i)return;if(!o.BankValidation.validateSwiftCode(s,i))return;const c=o.Bank.from(s,i);if(n&&a&&c)return new re(a,c,n)}if(e.startsWith(ae)){const t=e.replace(ae,"").trim().split(" "),r=o.BankService.getInstance().searchBanks("TZ",t[0]),n=r.length>0?r[0]:void 0,a=t[1],s=t.slice(2).map(ue).join(" ");if(s&&a&&n)return new re(s,n,a)}}catch(e){return}};getMobileContactDetails=()=>{let e=this.text.trim();e.startsWith(oe)&&(e=e.substring(16));try{if(e.startsWith(ne)){const t=e.replace(ne,"").trim().split(" ");if(t.length>=2){const e=t[0],r=t.slice(1).map(ue).join(" ");if(e.startsWith("+")){const t=o.PhoneNumber.from(e);if(t&&r)return new te(r,t)}}}if(e.startsWith(ce)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=o.TZMobileNumber.from(r.phone_number);let a=r.username;void 0===a&&(a="");let s=a.split(" ");if(s=s.filter(e=>e.trim().length>0),a=s.map(ue).join(" "),n&&a)return new te(a,n)}if(e.startsWith(ie)){const t=e.replace(ie,"").trim().split(" "),r=o.TZMobileNumber.from(t[0]),n=t.slice(1).map(ue).join(" ");if(r&&n)return new te(n,r)}}catch(e){return}};toJson(){return{text:this.text,version:"2.0"}}static fromJson(e){try{let t;return t="string"==typeof e?JSON.parse(e):e,t&&"object"==typeof t&&"string"==typeof t.text?new le(t.text):void console.warn("Invalid NarrationJson: missing or invalid text property")}catch(e){return void console.error("Error parsing NarrationJson:",e)}}static isNarrationJson(e){if(!e||"object"!=typeof e)return!1;return"string"==typeof e.text}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;try{return"string"==typeof t.text&&"function"==typeof t.getContactDetails&&"function"==typeof t.toJson}catch(e){return!1}}}function ue(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}class de{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return V.statementEntry}constructor(e,t){this._accountNo=e.accountNo,this._debitOrCredit=e.debitOrCredit,this._tranRefNo=e.tranRefNo,this._narration=t,this._txnDate=e.txnDate,this._valueDate=e.valueDate,this._currencyCode=e.currencyCode;const r=o.Currency.from(e.currencyCode);if(!r)throw new Error(`Currency not found for code: ${e.currencyCode}`);const n=o.Amount.from(e.amountCredited,r.code),a=o.Amount.from(e.amountDebited,r.code),s=o.Amount.from(e.balance,r.code);if(!n||!a||!s)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=n,this._amountDebited=a,this._balance=s}static create(e){const t="string"==typeof e.narration?new le(e.narration):e.narration,r={...e,narration:t.text},o=de.schema.safeParse(r);if(o.success)try{const{narration:e,...r}=o.data;return new de(r,t)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",o.error.flatten())}get accountNo(){return this._accountNo}get debitOrCredit(){return this._debitOrCredit}get tranRefNo(){return this._tranRefNo}get narration(){return this._narration}get txnDate(){return this._txnDate}get valueDate(){return this._valueDate}get amountCredited(){return this._amountCredited}get amountDebited(){return this._amountDebited}get balance(){return this._balance}get currencyCode(){return this._currencyCode}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"}}static fromJson(e){try{let t;if(t="string"==typeof e?JSON.parse(e):e,!(t&&"object"==typeof t&&"string"==typeof t.debitOrCredit&&"string"==typeof t.tranRefNo&&t.narration&&"string"==typeof t.txnDate&&"string"==typeof t.valueDate&&"string"==typeof t.currencyCode&&t.amountCredited&&t.amountDebited&&t.balance))return void console.warn("Invalid WalletStatementEntryJson: missing or invalid required properties");const r=le.fromJson(t.narration);if(!r)return void console.warn("Invalid WalletStatementEntryJson: failed to deserialize narration");const n=o.Amount.fromJson(t.amountCredited),a=o.Amount.fromJson(t.amountDebited),s=o.Amount.fromJson(t.balance);return n&&a&&s?n.currencyCode!==t.currencyCode||a.currencyCode!==t.currencyCode||s.currencyCode!==t.currencyCode?void console.warn("Invalid WalletStatementEntryJson: currency code mismatch"):de.create({accountNo:t.accountNo,debitOrCredit:t.debitOrCredit,tranRefNo:t.tranRefNo,narration:r,txnDate:t.txnDate,valueDate:t.valueDate,amountCredited:n.numericValue,amountDebited:a.numericValue,balance:s.numericValue,currencyCode:t.currencyCode}):void console.warn("Invalid WalletStatementEntryJson: failed to deserialize Amount objects")}catch(e){return void console.error("Error parsing WalletStatementEntryJson:",e)}}static isWalletStatementEntryJson(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.debitOrCredit&&"string"==typeof t.tranRefNo&&le.isNarrationJson(t.narration)&&"string"==typeof t.txnDate&&"string"==typeof t.valueDate&&"string"==typeof t.currencyCode&&(void 0===t.accountNo||"string"==typeof t.accountNo)&&o.Amount.isAmountJson(t.amountCredited)&&o.Amount.isAmountJson(t.amountDebited)&&o.Amount.isAmountJson(t.balance)}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=de.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&&le.is(t.narration)&&t.txnDate instanceof Date&&t.valueDate instanceof Date&&o.Amount.is(t.amountCredited)&&o.Amount.is(t.amountDebited)&&o.Amount.is(t.balance)&&"string"==typeof t.currencyCode&&"function"==typeof t.toJson&&"function"==typeof t.validate}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return de.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 toJsonArray(e){return e.map(e=>e.toJson())}static fromJsonArray(e){try{let t;return t="string"==typeof e?JSON.parse(e):e,Array.isArray(t)?t.map(e=>de.fromJson(e)).filter(e=>void 0!==e):(console.warn("fromJsonArray expects an array"),[])}catch(e){return console.error("Error parsing WalletStatementEntryJson array:",e),[]}}toObject(){return{accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.text,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.toJson(),amountDebited:this._amountDebited.toJson(),balance:this._balance.toJson(),currencyCode:this._currencyCode}}toJSON(){return JSON.stringify(this.toJson())}static fromJSON(e){return de.fromJson(e)}static from(e){if(e&&"object"==typeof e)try{let t,r,n,a,s=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const a=o.Amount.fromJson(e.amountCredited),i=o.Amount.fromJson(e.amountDebited),c=o.Amount.fromJson(e.balance);if(!a||!i||!c)return void console.error("Failed to deserialize Amount objects from JSON");t=a.numericValue,r=i.numericValue,n=c.numericValue,e.currencyCode||(s=a.currencyCode)}else if(t=Number(e.amountCredited),r=Number(e.amountDebited),n=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)a=e.narration;else if(le.is(e.narration))a=e.narration;else{if(!le.isNarrationJson(e.narration))return void console.error("Invalid narration data");{const t=le.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");a=t}}return de.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:a,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:r,balance:n,currencyCode:s})}catch(e){return void console.error("Error in WalletStatementEntry.from:",e)}else console.error("Invalid data provided to WalletStatementEntry.from: not an object or null.")}}const he=p().router({getWallets:{method:"GET",path:"/",query:V.walletQuery,responses:{200:e.z.array(G.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(de.schema)}}});class me extends ${static create(){return new me}static fromFilters(e){return(new me).applyFilters(e)}static fromUrlParams(e){try{const t=V.walletQuery.parse(e);return me.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 me.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return me.fromSearchParams(t)}static from(e){try{return null==e?new me:$.is(e)?new me(e.options):e instanceof URLSearchParams?me.fromSearchParams(e):this.isStringRecord(e)?me.fromUrlParams(e):me.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}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)"eq"===t.operator?e[t.field]=t.value:"likeLower"===t.operator&&"string"==typeof t.value&&(e[t.field]=t.value.replace(/%/g,""));return e}}class pe extends F{constructor(e){super("wallet",he,e)}async getBalance(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");if(e.wallet){const t=await this.client.getBalance({body:{accountNo:e.wallet.accountNo}});if(201===t.status){const r=t.body.availableBalance,n=o.Amount.from(r,e.wallet.currencyCode);if(n)return n}}if(e.accountNo){const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);const r=t[0],n=await this.client.getBalance({body:{accountNo:e.accountNo}});if(201===n.status){const e=n.body.availableBalance,t=o.Amount.from(e,r.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=me.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=G.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=me.create().whereId(e),r=await this.getWallets(t);return r.length>0?r[0]:void 0}async getStatement(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");const t=new Date,r=new Date(t.getFullYear(),t.getMonth(),1),o=new Date(t.getFullYear(),t.getMonth()+1,0),n=e.range??{startDate:r,endDate:o};let a,s;if(e.wallet)a=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}`);a=t[0],s=e.accountNo}}const i={...n,accountNo:s},c=await this.client.getStatement({body:i});if(201===c.status){return c.body.map(e=>({...e,currencyCode:a.currencyCode})).reduce((e,t)=>{const r=de.create(t);return r?e.push(r):console.warn("[WalletRepository] Skipping invalid statement entry:",t),e},[])}throw new Error(`Failed to fetch statement. Status: ${c.status}`)}async exists(e){return(await this.getWallets(e)).length>0}async count(e){return(await this.getWallets(e)).length}}const ye=r.create()(z((e,t)=>({userId:"",wallets:[],selectedWalletId:"",selectedCountryCode:"TZ",lastSynced:new Date,isInitialized:!1,setWallets:r=>{const o=r.filter(e=>G.is(e));if(0===o.length)throw new Error("setWallets received an empty or invalid wallet list. User must have at least one valid wallet.");const n=t().selectedWalletId,a=t().isInitialized;let s;const i=o.some(e=>e.id===n);a&&i&&""!==n?(s=o.find(e=>e.id===n),s||(console.error("Inconsistency: currentWalletStillValid was true, but find failed."),s=o[0])):s=o[0],e({wallets:o,selectedWalletId:s.id,selectedCountryCode:s.countryCode,lastSynced:new Date,isInitialized:!0})},setSelectedWallet:r=>{if(!G.is(r))throw new Error("setSelectedWallet called with an invalid Wallet object.");if(!t().wallets.some(e=>e.id===r.id))throw new Error(`Attempted to select wallet (ID: ${r.id}) which is not present in the current wallet list.`);e({selectedWalletId:r.id,selectedCountryCode:r.countryCode})},setSelectedCountry:r=>{const o=t()._getWalletsByCountry(r);if(0===o.length)throw new Error(`Cannot select country ${r}: No wallets found for this country (check if code is valid or state is consistent).`);e({selectedCountryCode:r,selectedWalletId:o[0].id})},reset:()=>{e({userId:"",wallets:[],selectedWalletId:"",selectedCountryCode:"TZ",lastSynced:new Date,isInitialized:!1})},_getWalletsByCountry:e=>t().wallets.filter(t=>t.countryCode===e),_getSelectedWallet:()=>{const e=t();if(!e.isInitialized)throw new Error("Cannot get selected wallet: Wallet session not initialized.");if(""===e.selectedWalletId)throw new Error("Cannot get selected wallet: Selection is still placeholder (initialization incomplete?).");const r=e.wallets.find(t=>t.id===e.selectedWalletId);if(!r)throw console.error("Inconsistent state details:",{id:e.selectedWalletId,walletCount:e.wallets.length}),new Error(`Inconsistent state: Selected wallet ID '${e.selectedWalletId}' not found in wallet list.`);return r}}),{name:"wallet-session-storage",storage:O(()=>sessionStorage,{reviver:(e,t)=>{if("wallets"===e&&Array.isArray(t))return t.map(e=>{try{const t=G.from(e);return t||void console.warn("Filtering out invalid wallet data during rehydration:",e)}catch(t){return void console.error("Error rehydrating Wallet instance from persisted data:",e,t)}}).filter(e=>void 0!==e);if("lastSynced"===e&&"string"==typeof t)try{const e=new Date(t);return isNaN(e.getTime())?new Date:e}catch{return new Date}return t},replacer:(e,t)=>"lastSynced"===e&&t instanceof Date?t.toISOString():"wallets"===e&&Array.isArray(t)?t.map(e=>e instanceof G&&"function"==typeof e.toObject?e.toObject():e):t}),partialize:e=>({userId:e.userId,wallets:e.wallets,selectedWalletId:e.selectedWalletId,selectedCountryCode:e.selectedCountryCode,lastSynced:e.lastSynced,isInitialized:e.isInitialized})}));class fe{repo;static _instance;constructor(){this.repo=new pe}static get instance(){return this._instance||(this._instance=new fe),this._instance}isInitialized(){return ye.getState().isInitialized}async initialize(e){if(!this.isInitialized()){if(!e)throw new Error("User must be authenticated to initialize wallet manager");await this.refreshWallets()}}async refreshWallets(){try{const e=await this.repo.getWallets();if(!e||0===e.length)throw new Error("User has no wallets associated with their account. Cannot proceed.");ye.getState().setWallets(e)}catch(e){throw console.error("Failed to refresh wallets:",e),e}}getWallets(){const e=ye.getState();if(!e.isInitialized)throw new Error("Cannot get wallets: Wallet session not initialized.");return e.wallets}getCountries(){const e=this.getWallets();return H.getUniqueCountries(e)}getWalletsByCountry(e){if(!this.isInitialized())throw new Error("Cannot get wallets by country: Wallet session not initialized.");return ye.getState()._getWalletsByCountry(e)}getSelectedWallet(){return ye.getState()._getSelectedWallet()}getSelectedCountryCode(){const e=ye.getState();if(!e.isInitialized)throw new Error("Cannot get selected country code: Wallet session not initialized.");return e.selectedCountryCode}getSelectedCountry(){const e=this.getSelectedCountryCode();try{const t=o.Country.fromCode(e);if(!t)throw new Error(`Country.fromCode returned invalid result for code: ${e}`);return t}catch(t){throw console.error(`Failed to get Country object for code ${e}:`,t),new Error(`Failed to create Country object for selected code ${e}.`)}}changeWallet(e){if(!this.isInitialized())throw new Error("Cannot change wallet: Wallet session not initialized.");const t=ye.getState(),r=t.wallets.find(t=>t.id===e);if(!r)throw new Error(`Cannot change wallet: Wallet with ID ${e} not found.`);t.setSelectedWallet(r)}changeCountry(e){if(!this.isInitialized())throw new Error("Cannot change country: Wallet session not initialized.");ye.getState().setSelectedCountry(e)}reset(){ye.getState().reset()}}const ge=p().router({logIn:{method:"POST",path:"/login",body:e.z.object({type:e.z.string().default("password"),identity:e.z.string().email(),password:e.z.string()}),responses:{201:e.z.object({profile:_.profileDTOSchema,token:e.z.string(),access:e.z.array(e.z.string()),resetPassword:e.z.boolean()}),400:e.z.object({})}},access:{method:"GET",path:"/access",responses:{200:e.z.string().array()}},resetPassword:{method:"PUT",path:"/password",body:e.z.object({currentPassword:e.z.string(),newPassword:e.z.string()}),responses:{}}}),we=p().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:E.loginDTO}}});class be extends F{constructor(e){super("login",we,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 Ne=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"),ve=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")}),Ce=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:ve.optional(),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),Ae={role:ve,teamMember:Ce,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:Ne.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:Ne.optional(),resetPassword:e.z.boolean().optional(),isActive:e.z.boolean().optional()}),resetPasswordRequest:e.z.object({newPassword:Ne.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:Ne},Se=p().router({getTeamMembers:{method:"GET",path:"/login",query:Ae.teamMemberQueryParams,responses:{200:e.z.array(Ae.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:Ae.teamMemberQueryParams,responses:{200:Ae.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:Ae.createTeamMemberRequest,responses:{201:Ae.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:Ae.updateTeamMemberRequest,responses:{200:Ae.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:Ae.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:Ae.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:Ae.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(Ae.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:Ae.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"}});class Oe{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 T(e.role)}catch(e){}}static from(e){try{return e?.id&&e?.name&&e?.identity&&e?.roleId?new Oe(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 Oe.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>Oe.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()}toObject(){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()}}toJson(){return JSON.stringify(this.toObject())}toJSON(){return this.toObject()}}class Ie extends F{constructor(e){super("admin",Se,e)}async createTeamMember(e){const t=await this.client.createTeamMember({body:e});return this.handleResponse(t,201)}async updateTeamMember(e,t){const r=await this.client.updateTeamMember({params:{id:e},body:t}),o=this.handleResponse(r,200),n=Oe.from(o);if(!n)throw new Error("Invalid team member data received from server");return n}async archiveTeamMember(e){const t=await this.client.archiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),o=Oe.from(r);if(!o)throw new Error("Invalid team member data received from server");return o}async unArchiveTeamMember(e){const t=await this.client.unArchiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),o=Oe.from(r);if(!o)throw new Error("Invalid team member data received from server");return o}async resetTeamMemberPassword(e,t={}){const r=await this.client.resetPassword({params:{id:e},body:t});return this.handleResponse(r,200)}async getAllTeamMembers(e={eager:"role"}){const t=await this.client.getTeamMembers({query:e}),r=this.handleResponse(t,200);return Oe.createMany(r)}async getTeamMember(e,t={eager:"role"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),o=this.handleResponse(r,200),n=Oe.from(o);if(!n)throw new Error("Invalid team member data received from server");return n}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=T.from(e);if(!t)throw new Error("Invalid role data received from server");return t})}async getRole(e){const t=await this.client.getRole({params:{id:e}}),r=this.handleResponse(t,200),o=T.from(r);if(!o)throw new Error("Invalid role data received from server");return o}}class ze extends F{constructor(e){super("auth",ge,e)}async logIn(e,t){const r={type:"password",identity:e,password:t},o=await this.client.logIn({body:r});if(400===o.status)throw new s({message:"Invalid email or password",statusCode:400});if(201===o.status){const e=o.body.token,t=new be({token:e}),r=await t.getIdentity(),n=D.from(r);if(!n)throw new s({message:"Failed to construct login credentials",statusCode:502});const a=o.body.profile,c=P.from(a);if(!c)throw new s({message:"Failed to construct user profile",statusCode:502});let l;if(n.access.includes(i.Role.ViewRole))try{const t=new Ie({token:e});l=await t.getRole(n.roleId)}catch(e){console.warn("Failed to fetch role details:",e)}const u=x.from({logIn:n,companyProfile:c,role:l,token:e});if(!u)throw new s({message:"Failed to construct user session",statusCode:502});return u}throw new s({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 s({message:"Invalid current password",statusCode:400});throw new s({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}`)}}class _e{static _instance=null;constructor(){}static get instance(){return _e._instance||(_e._instance=new _e),_e._instance}get repo(){return new ze({token:this.getUserToken()})}getUserToken(){return M()}get currentUser(){return(()=>{if("undefined"!=typeof window)return j.getState().getUser()})()}get isAuthenticated(){return!!this.currentUser&&!!this.getUserToken()}useCurrentUser(){return(()=>{if("undefined"==typeof window)throw new Error("useCurrentUser must only be used in a React component on the client side");const e=r.useStore(j,e=>e.user);try{return e?x.fromJson(e):void 0}catch(e){return void console.warn("Failed to deserialize user from hook:",e)}})()}checkPermission(e){return this.currentUser?.can(e)??!1}async logIn(e,t){if(!e||!t)throw new Error("Email and password are required");const r=new ze,o=await r.logIn(e,t);this.clearSavedData(),j.getState().setUserAndToken(o,o.token);try{await fe.instance.initialize(o)}catch(e){throw console.warn("Failed to initialize wallet session manager:",e),e}return o}async resetPassword(e,t){if(!this.isAuthenticated)throw new Error("User must be authenticated to reset password");if(!e||!t)throw new Error("Current password and new password are required");return await this.repo.updatePassword(e,t),this.clearSavedData(),!0}logOut(){this.clearSavedData()}refresh(){this.clearSavedData()}getDebugInfo(){return{hasUser:!!this.currentUser,hasToken:!!this.getUserToken(),isAuthenticated:this.isAuthenticated,userName:this.currentUser?.name||"Not logged in",tokenLength:this.getUserToken()?.length||0,managerInstance:"AfloatAuth singleton"}}clearSavedData(){j.getState().clearAuth();try{fe.instance.reset()}catch(e){console.warn("Failed to reset wallet session manager:",e)}}}class Pe{data;constructor(e){this.data=Y.contactDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get displayName(){return this.data.displayName}get type(){return this.data.type}get createdAt(){return new Date(this.data.createdAt)}get updatedAt(){return new Date(this.data.updatedAt)}get info(){return this.data.type===exports.ContactType.Mobile?te.fromContactDTO(this.data):this.data.type===exports.ContactType.Bank?re.fromContactDTO(this.data):void 0}get accNo(){const e=this.info;return e?e.accountNumber:this.data.accountNo}get accName(){return this.data.displayName}get accNoLabel(){const e=this.info;return e instanceof te?"Phone Number":e instanceof re?"Bank Account Number":"Account Number"}get channelLabel(){const e=this.info;return e instanceof te?"Channel":e instanceof re?"Bank":"Channel"}get accNameLabel(){const e=this.info;return e instanceof te?"Full Name":e instanceof re?"Bank Account Name":"Display Name"}get channelName(){const e=this.info;return e instanceof te||e instanceof re?e.channelName:""}static from(e){try{return new Pe(e)}catch(e){return void console.error("Failed to create Contact:",e)}}static create(e){return new Pe(e)}static createMany(e){return e.map(e=>new Pe(e))}static createSafe(e){try{return new Pe(e)}catch{return null}}static fromJSON(e){try{const t=JSON.parse(e);return Pe.from(t)}catch(e){return void console.error("Error parsing Contact JSON:",e)}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=Y.contactDTO.safeParse(e);if(!t.success)return!1;return null!==Pe.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&Pe.canConstruct(e.data))}toObject(){return{...this.data}}toJSON(){return JSON.stringify(this.toObject())}}class Ee{canHandle(e){return"Mobile"===e.type&&te.is(e)}createInput(e){if(te.is(e))return{type:exports.ContactType.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Contact Info")}}class De{canHandle(e){return"Bank"===e.type&&re.is(e)}createInput(e){if(re.is(e))return{type:exports.ContactType.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Contact Info")}}class Re{handlers=[new Ee,new De];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 Te=p().router({createContact:{method:"POST",path:"/",body:Y.contactInputDTO,responses:{201:Y.contactDTO}},editContact:{method:"PATCH",path:"/:id",body:Y.contactInputDTO,responses:{200:Y.contactDTO}},getContacts:{method:"GET",path:"/",query:e.z.object({orderByDesc:e.z.string()}),responses:{200:e.z.array(Y.contactDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:Y.contactDTO}},deleteContact:{method:"DELETE",path:"/:id",body:e.z.object({}),responses:{200:e.z.object({})}}});var xe,je,Me;exports.PayoutChannel=void 0,(xe=exports.PayoutChannel||(exports.PayoutChannel={})).MOBILE="Mobile",xe.BANK="Bank",exports.PayoutStatus=void 0,(je=exports.PayoutStatus||(exports.PayoutStatus={})).CREATED="CREATED",je.PENDING="PENDING",je.PAID="PAID",je.FAILED="FAILED",je.REJECTED="REJECTED",je.REVERSED="REVERSED",exports.PayoutApprovalStatus=void 0,(Me=exports.PayoutApprovalStatus||(exports.PayoutApprovalStatus={})).PENDING="Pending",Me.APPROVED="Approved",Me.REJECTED="Rejected";const Fe=e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string()}),ke=e.z.nativeEnum(exports.PayoutStatus),Be=e.z.nativeEnum(exports.PayoutApprovalStatus),Ue=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()}),$e=Ue.extend({payeeName:e.z.string()}),Le=Ue.extend({id:e.z.string(),profileId:e.z.string(),payeeName:e.z.string(),countryCode:e.z.string().default("TZ").refine(e=>o.CountryValidation.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>o.CurrencyValidation.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),channel:e.z.string(),status:ke,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:Be.nullish(),createdBy:Fe.nullish(),actionedBy:Fe.nullish()}),Je=e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(100).default(10),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().nullish(),endDate:e.z.string().datetime().nullish(),payeeName:e.z.string().nullish(),msisdn:e.z.string().nullish(),profileId:e.z.string().nullish(),id:e.z.string().nullish(),partnerReference:e.z.string().nullish(),channel:e.z.string().nullish(),currencyCode:e.z.string().nullish(),status:ke.nullish(),approvalStatus:Be.nullish(),minAmount:e.z.number().min(0).nullish(),maxAmount:e.z.number().min(0).nullish(),search:e.z.string().nullish()}),qe={PayoutDTO:Le,PayoutInputDTO:$e,PayoutStatus:ke,PayoutApprovalStatus:Be,PayoutAuthorizer:Fe,PayoutFilters:Je,PayoutURLQueryParams:e.z.object({page:e.z.string().transform(e=>parseInt(e)||1).optional(),limit:e.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().optional(),endDate:e.z.string().optional(),payeeName:e.z.string().optional(),msisdn:e.z.string().optional(),profileId:e.z.string().optional(),id:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:e.z.string().optional(),status:e.z.string().refine(e=>Object.values(exports.PayoutStatus).includes(e)).transform(e=>e).optional(),approvalStatus:e.z.string().refine(e=>Object.values(exports.PayoutApprovalStatus).includes(e)).transform(e=>e).optional(),minAmount:e.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:e.z.string().transform(e=>parseFloat(e)).optional(),search:e.z.string().optional()})};class We{data;constructor(e){this.data=qe.PayoutDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get payeeName(){return this.data.payeeName}get channel(){return this.data.channel}get msisdn(){return this.data.msisdn}get amount(){return o.Amount.from(this.data.amount,this.data.currencyCode)}get description(){return this.data.description}get notes(){return this.data.notes}get status(){return"Rejected"===this.data.approvalStatus?exports.PayoutStatus.REJECTED:"Approved"===this.data.approvalStatus?"FAILED"===this.data.status?exports.PayoutStatus.FAILED:exports.PayoutStatus.PAID:"Pending"===this.data.approvalStatus?exports.PayoutStatus.PENDING:this.data.status}get statusMessage(){return this.data.statusMessage}get partnerReference(){return this.data.partnerReference}get createdAt(){return this.data.createdAt}get updatedAt(){return this.data.updatedAt}get actionedAt(){return this.data.actionedAt}get approvalStatus(){return this.data.approvalStatus}get createdBy(){return this.data.createdBy}get actionedBy(){return this.data.actionedBy}get contactInfo(){return"TZ-BANK-B2C"===this.channel?re.fromPayoutDTO(this.data):te.fromPayoutDTO(this.data)}static create(e){return new We(e)}static createMany(e){return e.map(e=>new We(e))}static createSafe(e){try{return new We(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=qe.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==We.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&We.canConstruct(e.data))}toJSON(){return{...this.data}}}const Ve={SUPPORTED_COUNTRY_CODES:["TZ","KE"],ERROR_MESSAGES:{INVALID_PHONE_NUMBER:"Invalid phone number",INELIGIBLE_FOR_PAYOUT:"The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",MOBILE_NUMBER_MNO_MISMATCH:"There is a mismatch between the phone number provided and the MNO used.",UNSUPPORTED_COUNTRY_BANK:"Only Tanzanian Banks are supported for now",UNSUPPORTED_COUNTRY_MOBILE:"Only Tanzanian mobile numbers are supported for now",NO_HANDLER_FOUND:"Cannot create payout input!"}};class Ge{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}}class He{static forBank(e,t){if(!Ve.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ve.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,t,r){if(!o.PhoneNumber.is(e))throw new Error(Ve.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!Ve.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ve.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!o.PhoneNumberFactory.checkPayoutEligibility(e))throw new Error(Ve.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const n=o.MNOUtils.getMNOById(t,e.countryCode);if(!n)throw new Error(Ve.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return n.id===o.TZMNOId.VODACOM?`${r.countryCode}-${o.TZMNOId.TIGO.toString().toUpperCase()}-B2C`:`${r.countryCode}-${n.id.toString().toUpperCase()}-B2C`}}class Qe{canHandle(e,t,r){return e===exports.PayoutChannel.MOBILE&&te.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===o.Country.from(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=Ge.processNotes(e.notes),a=r.phoneNumber;return{channel:He.forMobile(a,r.mnoId,t),msisdn:a.getWithFormat(o.PhoneNumberFormat.INTERNATIONAL_NUMERIC),description:n??le.generateDefaultPayoutNarration(r),payeeName:r.name,notes:n,amount:e.amount.numericValue}}}class Ze{canHandle(e,t,r){return e===exports.PayoutChannel.BANK&&re.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===o.Country.from(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,o=Ge.processNotes(e.notes);return{channel:He.forBank(r,t),msisdn:`${r.bank.swiftCode}:${r.accNo}`,description:o??le.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:o,amount:e.amount.numericValue}}}class Ke{handlers=[new Qe,new Ze];getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(Ve.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const Ye={bank:He.forBank,mobile:He.forMobile},Xe=p().router({getPayouts:{method:"GET",path:"",query:e.z.object({}),responses:{200:e.z.object({results:e.z.array(qe.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:qe.PayoutApprovalStatus,orderByDesc:e.z.string()}),responses:{200:e.z.object({results:e.z.array(qe.PayoutDTO),total:e.z.number()})}},postPayout:{method:"POST",path:"",body:qe.PayoutInputDTO,responses:{201:qe.PayoutDTO,400:s.schema}},approve:{method:"POST",path:"/:id/approve",body:e.z.object({action:e.z.enum(["Approve","Reject"]),notes:e.z.string().optional()}),responses:{201:qe.PayoutDTO,404:e.z.object({}),409:e.z.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:qe.PayoutDTO,404:e.z.object({})}}});class et extends ${static create(){return new et}static fromFilters(e){return(new et).applyFilters(e)}static fromUrlParams(e){try{const t=qe.PayoutURLQueryParams.parse(e),r=qe.PayoutFilters.parse(t);return et.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return et.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return et.fromSearchParams(t)}static from(e){try{return null==e?new et:$.is(e)?new et(e.options):e instanceof URLSearchParams?et.fromSearchParams(e):this.isStringRecord(e)?et.fromUrlParams(e):et.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a PayoutQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereStatus(e){return this.where("status",e)}whereApprovalStatus(e){return this.where("approvalStatus",e)}whereChannel(e){return this.where("channel",e)}wherePending(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.PENDING)}whereApproved(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.APPROVED)}whereRejected(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.REJECTED)}wherePaid(){return this.whereStatus(exports.PayoutStatus.PAID)}whereFailed(){return this.whereStatus(exports.PayoutStatus.FAILED)}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}wherePayee(e){return this.whereContains("payeeName",e)}whereMsisdn(e){return this.whereContains("msisdn",e)}whereProfileId(e){return this.where("profileId",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.status&&this.whereStatus(e.status),e.approvalStatus&&this.whereApprovalStatus(e.approvalStatus),e.channel&&this.whereChannel(e.channel),e.payeeName&&this.wherePayee(e.payeeName),e.msisdn&&this.whereMsisdn(e.msisdn),e.profileId&&this.whereProfileId(e.profileId),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&e.minAmount&&void 0!==e.maxAmount&&e.maxAmount?this.whereAmountBetween(e.minAmount,e.maxAmount):void 0!==e.minAmount?this.whereGreaterThanOrEqual("amount",e.minAmount):void 0!==e.maxAmount&&this.whereLessThanOrEqual("amount",e.maxAmount)),e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,payeeName:e.payeeName,msisdn:e.msisdn,profileId:e.profileId,id:e.id,partnerReference:e.partnerReference,channel:e.channel,status:this.isValidStatus(e.status)?e.status:void 0,approvalStatus:this.isValidApprovalStatus(e.approvalStatus)?e.approvalStatus:void 0,minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withApprovalStatus(e){const t=this.clone();return e&&t.whereApprovalStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}includeDefaultRelations(){return this.with("[createdBy,actionedBy]")}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.payeeName||e.msisdn||e.profileId||e.id||e.partnerReference||e.channel||e.status||e.approvalStatus||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.status&&e.push(`Status: ${t.status}`),t.approvalStatus&&e.push(`Approval: ${t.approvalStatus}`),t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.payeeName&&e.push(`Payee: ${t.payeeName}`),t.msisdn&&e.push(`MSISDN: ${t.msisdn}`),t.profileId&&e.push(`Profile: ${t.profileId}`),t.partnerReference&&e.push(`Ref: ${t.partnerReference}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"payeeName":case"msisdn":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}return e}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidStatus(e){return Object.values(exports.PayoutStatus).includes(e)}isValidApprovalStatus(e){return Object.values(exports.PayoutApprovalStatus).includes(e)}}const tt=p().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:P.schema}}});exports.APIError=s,exports.AfloatAuth=_e,exports.AuthRepository=ze,exports.BANK_NARR_PREFIX=ae,exports.BankContactInfo=re,exports.BaseRepository=F,exports.CompanyMembership=R,exports.Contact=Pe,exports.ContactDTOSchemas=Y,exports.ContactRepository=class extends F{constructor(e){super("contact",Te,e)}async create(e){const t=(new Re).resolve(e),r=await this.client.createContact({body:t}),o=this.handleResponse(r,201);return Pe.create(o)}async edit(e,t){const r=(new Re).resolve(t),o=await this.client.editContact({params:{id:e},body:r}),n=this.handleResponse(o,200);return Pe.create(n)}async remove(e){const t=await this.client.deleteContact({params:{id:e}});this.handleResponse(t,200)}async getAll(){const e=await this.client.getContacts({query:{orderByDesc:"createdAt"}}),t=this.handleResponse(e,200);return Pe.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return Pe.create(r)}},exports.ECOBANK_PREFIX=oe,exports.IdentityRepository=be,exports.LEGACY_BANK_NARR_PREFIX=se,exports.LEGACY_MOBILE_NARR_PREFIX=ce,exports.LogIn=D,exports.LogInSchemas=E,exports.MOBILE_NARR_PREFIX=ie,exports.MobileContactInfo=te,exports.NARR_V2_PREFIX=ne,exports.Narration=le,exports.Pagination=q,exports.PaginationParamsSchema=L,exports.PaginationSchema=J,exports.Payout=We,exports.PayoutDTOSchemas=qe,exports.PayoutInputFactory=Ke,exports.PayoutQuery=et,exports.PayoutRepository=class extends F{constructor(e){super("payout",Xe,e)}async getPayouts(e){try{const t=et.from(e),r=t.build(),o=await this.client.getPayouts({query:r}),n=this.handleResponse(o,200),a=t.toFilters(),s=new q(a.page??1,a.limit??10,n.total);return{results:We.createMany(n.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=et.from(e).build();delete t.page,delete t.limit;const r=await this.client.getPayouts({query:t}),o=this.handleResponse(r,200);return We.createMany(o.results)}catch(e){throw new Error(`Failed to fetch all payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=et.fromRequest(e);return this.getPayouts(t)}async pay(e){const{min:t,max:r}=o.Amount.getTransactionLimits(e.amount.currencyCode);if(e.amount.lessThan(t)||e.amount.greaterThan(r))throw new s({statusCode:400,message:`Please make sure the amount is between ${t.label} - ${r.label}`});const n=fe.instance.getSelectedWallet();if(!n)throw new Error("You have not selected a wallet to process this payout");const a=(new Ke).getPayoutInput(e,n),i=await this.client.postPayout({body:a});if(201===i.status)return We.create(i.body);if(400===i.status)throw new s(i.body);throw s.unknown()}async approve(e,t){const r=await this.client.approve({params:{id:e},body:{action:"Approve",notes:t?.notes}});if(201===r.status)return We.create(r.body);if(404===r.status)throw new s({message:"Payout not found",statusCode:404});if(409===r.status)throw new s({message:"Payout already approved",statusCode:409});throw s.unknown()}async reject(e,t){const r=await this.client.approve({params:{id:e},body:{action:"Reject",notes:t?.notes}});if(201===r.status)return We.create(r.body);if(404===r.status)throw new s({message:"Payout not found",statusCode:404});if(409===r.status)throw new s({message:"Payout already rejected",statusCode:409});throw s.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return We.create(t.body);if(404===t.status)throw new s({message:"Payout not found",statusCode:404});throw s.unknown()}async count(e){const t=et.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=c,exports.Permissions=i,exports.Profile=P,exports.ProfileDTOSchemas=_,exports.ProfileRepository=class extends F{constructor(e){super("profile",tt,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=P.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=U,exports.QueryBuilder=$,exports.Role=T,exports.TeamManagementDTOSchemas=Ae,exports.TeamMember=Oe,exports.TeamMemberRepository=Ie,exports.User=x,exports.Wallet=G,exports.WalletDTOSchemas=V,exports.WalletRepository=pe,exports.WalletSessionManager=fe,exports.WalletStatementEntry=de,exports.WalletUtils=H,exports.createPaginatedResponse=function(e,t,r,o){return{results:e,pagination:new q(t,r,o)}},exports.createPaginatedResponseSchema=function(t){return e.z.object({results:e.z.array(t),pagination:J})},exports.createPayoutChannelCode=Ye,exports.emptyPaginatedResponse=function(e=1,t=10){return{results:[],pagination:new q(e,t,0)}},exports.isError=function(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message},exports.walletsStore=ye;
2
2
  //# sourceMappingURL=index.cjs.js.map