@temboplus/tembo-dashboard 0.0.14 → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("zod"),t=require("uuid"),r=require("@temboplus/frontend-core");function o(e){return e&&e.__esModule?e:{default:e}}var n,s,i,a=o(e);class c extends Error{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 c.schema.safeParse(e).success}static unknown(e){return new c({message:null!=e?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()})}}exports.FilterOperator=void 0,(n=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",n.NOT_EQUALS="neq",n.LESS_THAN="lt",n.LESS_THAN_OR_EQUAL="lte",n.GREATER_THAN="gt",n.GREATER_THAN_OR_EQUAL="gte",n.LIKE="like",n.LIKE_LOWER="likeLower",n.IS_NULL="isNull",n.IS_NOT_NULL="isNotNull",n.IN="in",exports.SortDirection=void 0,(s=exports.SortDirection||(exports.SortDirection={})).ASC="asc",s.DESC="desc";const l=Symbol("query-builder-type");class u{constructor(e={}){this.options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8},this[i]="query-builder",this.options={filters:e.filters||[],sort:e.sort||[],includes:e.includes||[],groupBy:e.groupBy||[],join:e.join||[],page:e.page,limit:e.limit}}static is(e){return null!==e&&"object"==typeof e&&l in e&&"query-builder"===e[l]}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(){var e;const t={};if(void 0!==this.options.page&&void 0!==this.options.limit){const e=(this.options.page-1)*this.options.limit,r=e+this.options.limit-1;t.rangeStart=e,t.rangeEnd=r}if(this.options.filters&&this.options.filters.length>0)for(const e of this.options.filters)switch(e.operator){case exports.FilterOperator.IS_NULL:t[`${e.field}:isNull`]=1;break;case exports.FilterOperator.IS_NOT_NULL:t[`${e.field}:notNull`]=1;break;case exports.FilterOperator.IN:t[`${e.field}:in`]=Array.isArray(e.value)?e.value.join(","):e.value;break;case exports.FilterOperator.LIKE:t[`${e.field}:like`]=e.value;break;case exports.FilterOperator.LIKE_LOWER:t[`${e.field}:likeLower`]=e.value;break;case exports.FilterOperator.GREATER_THAN_OR_EQUAL:t[`${e.field}:gte`]=e.value;break;case exports.FilterOperator.LESS_THAN_OR_EQUAL:t[`${e.field}:lte`]=e.value;break;default:t[`${e.field}:${e.operator}`]=e.value}if(this.options.sort&&this.options.sort.length>0){const e=[],r=[];for(const t of this.options.sort)t.direction===exports.SortDirection.ASC?e.push(t.field):r.push(t.field);e.length>0&&(t.orderBy=e.join(",")),r.length>0&&(t.orderByDesc=r.join(","))}const r=null===(e=this.options.filters)||void 0===e?void 0:e.filter(e=>"createdAt"===e.field&&(e.operator===exports.FilterOperator.GREATER_THAN_OR_EQUAL||e.operator===exports.FilterOperator.LESS_THAN_OR_EQUAL));if(r){const e=r.find(e=>e.operator===exports.FilterOperator.GREATER_THAN_OR_EQUAL),o=r.find(e=>e.operator===exports.FilterOperator.LESS_THAN_OR_EQUAL);e&&(t.startDate=e.value),o&&(t.endDate=o.value)}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?t.eager=this.options.includes[0]:t.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(t.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(t.groupBy=this.options.groupBy.join(",")),this.options.count&&(t.count=this.options.count),t}clone(){return new(0,this.constructor)(Object.assign(Object.assign({},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 u(e)}}i=l;const d=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 m=Symbol("ContractNoBody"),h=e=>"method"in e&&"path"in e,p=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var o,n,s,i,a;return h(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:(i=null==t?void 0:t.baseHeaders,a=r.headers,d(i)?d(a)?i.merge(a):i:d(a)?a:Object.assign({},i,a)),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!==(s=r.metadata)&&void 0!==s?s:{}}:r.metadata}]:[e,p(r,t)]})),A=Symbol("ContractPlainType"),f=()=>({router:(e,t)=>p(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>A,body:()=>A,type:()=>A,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>m}),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("&"):"",g=e=>e?Object.keys(e).flatMap(t=>T(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",T=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>T(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>T(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class v extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const E=async({route:e,path:t,method:r,headers:o,body:n,validateResponse:s,fetchOptions:i})=>{const a=await fetch(t,{...i,method:r,headers:o,body:n}),c=a.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t={status:a.status,body:await a.json(),headers:a.headers},r=e.responses[t.status];return(null!=s?s: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:a.status,body:await a.text(),headers:a.headers}:{status:a.status,body:await a.blob(),headers:a.headers}},C=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])),O=(e,t,r,o,n)=>{const s=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:o.path,params:r}),i=((e,t=!1)=>{const r=t?y(e):g(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,n);return`${t}${s}${i}`},S=(e,t)=>{const r=Object.keys(e.responses);return async o=>{const n=((e,t,r)=>{const{query:o,params:n,body:s,headers:i,extraHeaders:a,overrideClientOptions:c,fetchOptions:l,cache:u,next:d,...m}=r||{},h={...t,...c};return{path:O(o,h.baseUrl,n,e,!!h.jsonQuery),clientArgs:h,route:e,body:s,query:o,extraInputArgs:m,fetchOptions:{...u&&{cache:u},...d&&{next:d},...l},headers:{...a,...i}}})(e,t,o),s=await(e=>{const{path:t,clientArgs:r,route:o,body:n,query:s,extraInputArgs:i,headers:a,fetchOptions:c}=e,l=r.api||E,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(a)};Object.keys(d).forEach(e=>{void 0===d[e]&&delete d[e]});let m={route:o,path:t,method:o.method,headers:d,body:void 0,rawBody:n,rawQuery:s,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==o.method&&("contentType"in o&&"multipart/form-data"===o.contentType?m={...m,contentType:"multipart/form-data",body:n instanceof FormData?n:C(n)}:"contentType"in o&&"application/x-www-form-urlencoded"===o.contentType?m={...m,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...m.headers},body:"string"==typeof n?n:new URLSearchParams(n)}:null!=n&&(m={...m,contentType:"application/json",headers:{"content-type":"application/json",...m.headers},body:JSON.stringify(n)})),l({...m,...i})})(n);if(!t.throwOnUnknownStatus)return s;if(r.includes(s.status.toString()))return s;throw new v(s,r)}},w=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>h(r)?[e,S(r,t)]:[e,w(r,t)]));class I{constructor(e,t,r){this.contract=t,this.endpoint=e,this.root=null==r?void 0:r.root,this.token=null==r?void 0:r.token}getToken(){return this.token&&this.token.trim().length>0?this.token:""}get client(){const e=this.root?this.root.replace(/\/+$/,""):"",r=this.endpoint?this.endpoint.replace(/^\/+/,""):"",o={baseUrl:e?`${e}/${r}`:`https://gateway.temboplus.com/dashboard/${r}`,baseHeaders:{Authorization:`Bearer ${this.getToken()}`,"x-request-id":t.v4()}};return w(this.contract,o)}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 c(t.data);throw new c({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===e.status)throw new c({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new c({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new c({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new c({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}const b=a.default.object({page:a.default.number().int().positive(),limit:a.default.number().int().positive(),total:a.default.number().int().min(0),totalPages:a.default.number().int().min(0),hasNext:a.default.boolean(),hasPrev:a.default.boolean()}),x=a.default.object({balance:a.default.number(),availableBalance:a.default.number(),accountNumber:a.default.string(),accountName:a.default.string()}),L={pagination:b,transactionSummary:a.default.object({yesterday:a.default.number(),today:a.default.number(),thisMonth:a.default.number(),lastMonth:a.default.number()}),walletSummary:x};class P{constructor(e,t="TZS"){var o,n,s,i;this.currency=t,this.yesterday=null!==(o=r.Amount.from(e.yesterday,t))&&void 0!==o?o:r.Amount.from(0,t),this.today=null!==(n=r.Amount.from(e.today,t))&&void 0!==n?n:r.Amount.from(0,t),this.thisMonth=null!==(s=r.Amount.from(e.thisMonth,t))&&void 0!==s?s:r.Amount.from(0,t),this.lastMonth=null!==(i=r.Amount.from(e.lastMonth,t))&&void 0!==i?i:r.Amount.from(0,t)}getMonthlyGrowthRate(){return 0===this.lastMonth.numericValue?this.thisMonth.numericValue>0?100:0:(this.thisMonth.numericValue-this.lastMonth.numericValue)/this.lastMonth.numericValue*100}getRecentTotal(){return r.Amount.from(this.today.numericValue+this.yesterday.numericValue,this.currency)}static from(e,t="TZS"){return new P(e,t)}toJson(){return{yesterday:this.yesterday.toJson(),today:this.today.toJson(),thisMonth:this.thisMonth.toJson(),lastMonth:this.lastMonth.toJson(),currency:this.currency}}static fromJson(e){try{if(!(r.Amount.isAmountJson(e.yesterday)&&r.Amount.isAmountJson(e.today)&&r.Amount.isAmountJson(e.thisMonth)&&r.Amount.isAmountJson(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=r.Amount.fromJson(e.yesterday),o=r.Amount.fromJson(e.today),n=r.Amount.fromJson(e.thisMonth),s=r.Amount.fromJson(e.lastMonth);if(!(t&&o&&n&&s))return void console.error("Failed to reconstruct Amount instances from JSON:",e);const i={yesterday:t.numericValue,today:o.numericValue,thisMonth:n.numericValue,lastMonth:s.numericValue};return new P(i,e.currency)}catch(e){return void console.error("Error creating TransactionSummary from JSON:",e)}}}class _{constructor(e){var t,o;let n="TZS";this.accountName=e.accountName,this.accountNumber=e.accountNumber,this.currency=n,this.availableBalance=null!==(t=r.Amount.from(e.availableBalance,n))&&void 0!==t?t:r.Amount.from(0,n),this.actualBalance=null!==(o=r.Amount.from(e.balance,n))&&void 0!==o?o:r.Amount.from(0,n)}hasSufficientBalance(e){return this.availableBalance.numericValue>=e}static from(e){return new _(e)}toJson(){return{accountName:this.accountName,accountNumber:this.accountNumber,availableBalance:this.availableBalance.toJson(),actualBalance:this.actualBalance.toJson(),currency:this.currency}}static fromJson(e){try{if(!r.Amount.isAmountJson(e.availableBalance)||!r.Amount.isAmountJson(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const t=r.Amount.fromJson(e.availableBalance),o=r.Amount.fromJson(e.actualBalance);if(!t||!o)return void console.error("Failed to reconstruct Amount instances from JSON:",e);const n={accountName:e.accountName,accountNumber:e.accountNumber,availableBalance:t.numericValue,balance:o.numericValue};return new _(n)}catch(e){return void console.error("Error creating WalletInfo from JSON:",e)}}static createManyFromJson(e){return e.map(e=>_.fromJson(e)).filter(Boolean)}}const z={user:e.z.object({token:e.z.string(),identity:e.z.string(),name:e.z.string()}),loginRequest:e.z.object({type:e.z.string().default("password"),identity:e.z.string().email(),password:e.z.string()})},R=f().router({login:{method:"POST",path:"/auth/login",body:z.loginRequest,responses:{201:z.user,400:e.z.object({message:e.z.string().optional()}),401:e.z.object({message:e.z.string().optional()})},summary:"User login",description:"Authenticate user with email and password"}});class F{constructor(e){this.token=e.token,this.identity=e.identity,this.name=e.name}hasToken(){return!!this.token&&this.token.length>0}getDisplayName(){return this.name||this.identity}isEmailIdentity(){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.identity)}static from(e){try{return(null==e?void 0:e.token)&&(null==e?void 0:e.identity)&&(null==e?void 0:e.name)?new F(e):void console.error("Missing required User fields:",e)}catch(e){return void console.error("Error creating User:",e)}}static fromJson(e){try{if(!(null==e?void 0:e.token)||!(null==e?void 0:e.identity)||!(null==e?void 0:e.name))return void console.error("Missing required User JSON fields:",e);const t={token:e.token,identity:e.identity,name:e.name};return new F(t)}catch(e){return void console.error("Error creating User from JSON:",e)}}toJson(){return{token:this.token,identity:this.identity,name:this.name}}}var U,D;exports.COLLECTION_STATUS=void 0,(U=exports.COLLECTION_STATUS||(exports.COLLECTION_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",U.GENERIC_FAILURE="GENERIC_FAILURE",U.PAYMENT_REJECTED="PAYMENT_REJECTED",U.PENDING_ACK="PENDING_ACK",exports.COLLECTION_CHANNEL=void 0,(D=exports.COLLECTION_CHANNEL||(exports.COLLECTION_CHANNEL={})).AIRTEL="TZ-AIRTEL-C2B",D.TIGO="TZ-TIGO-C2B",D.HALOTEL="TZ-HALOTEL-C2B";const B=e.z.nativeEnum(exports.COLLECTION_STATUS),M=e.z.nativeEnum(exports.COLLECTION_CHANNEL),j={collection:e.z.object({id:e.z.string().min(1),status:B,statusMessage:e.z.string(),accountNo:e.z.string().min(1),walletId:e.z.string(),transactionDate:e.z.string().datetime(),narration:e.z.string(),msisdn:e.z.string().min(1),channel:M,amount:e.z.number().min(0),serviceFee:e.z.string().optional(),postedAmount:e.z.string().optional(),reference:e.z.string(),partnerReference:e.z.string().nullable().optional(),transactionId:e.z.string().nullable().optional(),serviceFeeTransactionId:e.z.string().nullable().optional(),requestId:e.z.string().nullable().optional(),completedAt:e.z.string().datetime().nullable().optional(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime(),notes:e.z.string().optional(),currencyCode:e.z.string().default("TZS")}),collectionFilters:e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(100).default(20),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().optional(),endDate:e.z.string().datetime().optional(),msisdn:e.z.string().optional(),id:e.z.string().optional(),reference:e.z.string().optional(),accountNo:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:M.optional(),status:B.optional(),minAmount:e.z.number().min(0).optional(),maxAmount:e.z.number().min(0).optional(),search:e.z.string().optional()}),collectionURLQueryParams: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(),msisdn:e.z.string().optional(),id:e.z.string().optional(),reference:e.z.string().optional(),accountNo:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:e.z.string().refine(e=>Object.values(exports.COLLECTION_CHANNEL).includes(e)).transform(e=>e).optional(),status:e.z.string().refine(e=>Object.values(exports.COLLECTION_STATUS).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()}),paymentStatus:B,paymentChannel:M},J=f().router({getCollections:{method:"GET",path:"/",query:e.z.object({}),responses:{200:e.z.object({results:e.z.array(j.collection),total:e.z.number()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List collections",description:"Retrieve a paginated list of collections with optional filtering"},getCollection:{method:"GET",path:"/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:j.collection,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 collection details",description:"Retrieve detailed information about a specific collection"},getSummary:{method:"GET",path:"/summary",responses:{200:e.z.object({yesterday:e.z.number(),today:e.z.number(),thisMonth:e.z.number(),lastMonth:e.z.number()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"Get collections summary",description:"Retrieve collection summary statistics for different time periods"},getWalletInfo:{method:"GET",path:"/balance",responses:{200:L.walletSummary,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"Get account balance",description:"Retrieve current account balance and summary information"}}),k={[exports.COLLECTION_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[exports.COLLECTION_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.COLLECTION_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Please try again"},[exports.COLLECTION_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred during payment processing",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"}},Y={[exports.COLLECTION_CHANNEL.AIRTEL]:{networkOperator:"Airtel",serviceName:"Airtel Money",type:"mobile"},[exports.COLLECTION_CHANNEL.TIGO]:{networkOperator:"Tigo",serviceName:"Tigo Pesa",type:"mobile"},[exports.COLLECTION_CHANNEL.HALOTEL]:{networkOperator:"Halotel",serviceName:"HaloPesa",type:"mobile"}};class ${constructor(e){var t,o,n;let s="TZS";r.CurrencyValidation.isCurrencyCode(e.currencyCode)&&(s=e.currencyCode),this.id=e.id,this.status=e.status,this.statusMessage=e.statusMessage,this.accountNo=e.accountNo,this.walletId=e.walletId,this.transactionDate=new Date(e.transactionDate),this.narration=e.narration,this.msisdn=e.msisdn,this.channel=e.channel,this.amount=null!==(t=r.Amount.from(e.amount,s))&&void 0!==t?t:r.Amount.from(0,s),this.serviceFee=e.serviceFee?null!==(o=r.Amount.from(parseFloat(e.serviceFee),s))&&void 0!==o?o:r.Amount.from(0,s):void 0,this.postedAmount=e.postedAmount?null!==(n=r.Amount.from(parseFloat(e.postedAmount),s))&&void 0!==n?n:r.Amount.from(0,s):void 0,this.reference=e.reference,this.partnerReference=e.partnerReference,this.transactionId=e.transactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.requestId=e.requestId,this.completedAt=e.completedAt?new Date(e.completedAt):null,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.notes=e.notes,this.currencyCode=e.currencyCode}isPending(){return this.status===exports.COLLECTION_STATUS.PENDING_ACK}isSuccessful(){return this.status===exports.COLLECTION_STATUS.PAYMENT_ACCEPTED}isFailed(){return Object.entries(k).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.status)}getStatusInfo(){return k[this.status]}getChannelInfo(){return Y[this.channel]}getProviderName(){return this.getChannelInfo().networkOperator}getServiceName(){return this.getChannelInfo().serviceName}isMobileCollection(){return e=this.channel,"mobile"===Y[e].type;var e}isBankCollection(){return e=this.channel,"bank"===Y[e].type;var e}static from(e){try{return(null==e?void 0:e.id)&&(null==e?void 0:e.msisdn)&&void 0!==(null==e?void 0:e.amount)?new $(e):void console.error("Missing required Collection fields:",e)}catch(e){return void console.error("Error creating Collection:",e)}}static createMany(e){return e.map(e=>$.from(e)).filter(Boolean)}static fromJson(e){try{if(!(null==e?void 0:e.id)||!(null==e?void 0:e.msisdn)||!(null==e?void 0:e.amount))return void console.error("Missing required Collection JSON fields:",e);if(!r.Amount.isAmountJson(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.Amount.isAmountJson(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.Amount.isAmountJson(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJson(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let o,n;if(e.serviceFee){const t=r.Amount.fromJson(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);o=t.numericValue.toString()}if(e.postedAmount){const t=r.Amount.fromJson(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);n=t.numericValue.toString()}const s={id:e.id,status:e.status,statusMessage:e.statusMessage,accountNo:e.accountNo,walletId:e.walletId,transactionDate:e.transactionDate,narration:e.narration,msisdn:e.msisdn,channel:e.channel,amount:t.numericValue,serviceFee:o,postedAmount:n,reference:e.reference,partnerReference:e.partnerReference,transactionId:e.transactionId,serviceFeeTransactionId:e.serviceFeeTransactionId,requestId:e.requestId,completedAt:e.completedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,notes:e.notes,currencyCode:e.currencyCode};return new $(s)}catch(e){return void console.error("Error creating Collection from JSON:",e)}}static createManyFromJson(e){return e.map(e=>$.fromJson(e)).filter(Boolean)}toJson(){var e,t,r,o;return{id:this.id,status:this.status,statusMessage:this.statusMessage,accountNo:this.accountNo,walletId:this.walletId,transactionDate:this.transactionDate.toISOString(),narration:this.narration,msisdn:this.msisdn,channel:this.channel,amount:this.amount.toJson(),serviceFee:null===(e=this.serviceFee)||void 0===e?void 0:e.toJson(),postedAmount:null===(t=this.postedAmount)||void 0===t?void 0:t.toJson(),reference:this.reference,partnerReference:this.partnerReference,transactionId:this.transactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,requestId:this.requestId,completedAt:null!==(o=null===(r=this.completedAt)||void 0===r?void 0:r.toISOString())&&void 0!==o?o:null,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),notes:this.notes,currencyCode:this.currencyCode}}}class q extends u{static create(){return new q}static fromFilters(e){return(new q).applyFilters(e)}static fromUrlParams(e){try{const t=j.collectionURLQueryParams.parse(e),r=j.collectionFilters.parse(t);return q.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 q.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return q.fromSearchParams(t)}static from(e){try{return null==e?new q:u.is(e)?new q(e.options):e instanceof URLSearchParams?q.fromSearchParams(e):this.isStringRecord(e)?q.fromUrlParams(e):q.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a CollectionQuery 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)}whereChannel(e){return this.where("channel",e)}wherePending(){return this.whereStatus(exports.COLLECTION_STATUS.PENDING_ACK)}whereSuccessful(){return this.whereStatus(exports.COLLECTION_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("status",[exports.COLLECTION_STATUS.PAYMENT_REJECTED,exports.COLLECTION_STATUS.GENERIC_FAILURE])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereSender(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereReference(e){return this.whereContains("reference",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",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.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereSender(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.reference&&this.whereReference(e.reference),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&&void 0!==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,msisdn:e.msisdn,id:e.id,reference:e.reference,accountNo:e.accountNo,partnerReference:e.partnerReference,channel:this.isValidChannel(e.channel)?e.channel:void 0,status:this.isValidStatus(e.status)?e.status: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}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.id||e.reference||e.accountNo||e.partnerReference||e.channel||e.status||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.status&&e.push(`Status: ${t.status}`),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.msisdn&&e.push(`Phone: ${t.msisdn}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.reference&&e.push(`Reference: ${t.reference}`),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"msisdn":case"reference":case"accountNo":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}isValidChannel(e){return Object.values(exports.COLLECTION_CHANNEL).includes(e)}isValidStatus(e){return Object.values(exports.COLLECTION_STATUS).includes(e)}}var H,G;exports.PAYOUT_STATUS=void 0,(H=exports.PAYOUT_STATUS||(exports.PAYOUT_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",H.GENERIC_FAILURE="GENERIC_FAILURE",H.WALLET_DEBITED="WALLET_DEBITED",H.PAYMENT_REJECTED="PAYMENT_REJECTED",H.PENDING="PENDING",H.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",H.PENDING_ACK="PENDING_ACK",H.REVERSED="REVERSED",H.INVALID_SERVICE="INVALID_SERVICE",H.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",H.THIRDPARTY_FAILED="THIRDPARTY_FAILED",exports.MOBILE_PAYOUT_CHANNEL=void 0,(G=exports.MOBILE_PAYOUT_CHANNEL||(exports.MOBILE_PAYOUT_CHANNEL={})).AIRTEL="TZ-AIRTEL-B2C",G.VODACOM="TZ-VODACOM-B2C",G.TIGO="TZ-TIGO-B2C",G.HALOTEL="TZ-HALOTEL-B2C",exports.BANK_PAYOUT_CHANNEL=void 0,(exports.BANK_PAYOUT_CHANNEL||(exports.BANK_PAYOUT_CHANNEL={})).BANK="TZ-BANK-B2C";const V=e.z.nativeEnum(exports.PAYOUT_STATUS),K=e.z.nativeEnum(exports.MOBILE_PAYOUT_CHANNEL),Q=e.z.nativeEnum(exports.BANK_PAYOUT_CHANNEL),W=e.z.union([K,Q]),Z={payout:e.z.object({id:e.z.string().min(1),statusCode:e.z.string(),statusCodeText:V,statusDescription:e.z.string(),countryCode:e.z.string(),serviceCode:W,amount:e.z.number().min(0),serviceFee:e.z.string().optional(),postedAmount:e.z.string().optional(),walletId:e.z.string().optional(),msisdn:e.z.string().min(1),narration:e.z.string(),currencyCode:e.z.string(),recipientNames:e.z.string().optional(),transactionRef:e.z.string(),transactionDate:e.z.string().datetime(),externalId:e.z.string().nullable().optional(),cbaReferenceNo:e.z.string().optional(),beepTransactionId:e.z.string().optional(),receiptNumber:e.z.string().optional(),createdAt:e.z.string().datetime(),reversedTransactionId:e.z.string().nullable().optional(),transactionId:e.z.string(),serviceFeeTransactionId:e.z.string().optional(),isReconciled:e.z.number().optional(),requestId:e.z.string().optional(),notes:e.z.string().optional(),updatedAt:e.z.string().datetime().optional()}),payoutFilters:e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(100).default(20),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().optional(),endDate:e.z.string().datetime().optional(),msisdn:e.z.string().optional(),id:e.z.string().optional(),ref:e.z.string().optional(),channel:W.optional(),status:V.optional(),minAmount:e.z.number().min(0).optional(),maxAmount:e.z.number().min(0).optional(),search:e.z.string().optional()}),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(),msisdn:e.z.string().optional(),id:e.z.string().optional(),ref:e.z.string().optional(),channel:e.z.string().refine(e=>Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK).transform(e=>e).optional(),status:e.z.string().refine(e=>Object.values(exports.PAYOUT_STATUS).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()}),payoutStatus:V,payoutChannel:W,mobileChannel:K,bankChannel:Q,walletSummary:e.z.object({balance:e.z.number(),currency:e.z.string(),lastUpdated:e.z.string().datetime()}),transactionSummary:e.z.object({yesterday:e.z.number(),today:e.z.number(),thisMonth:e.z.number(),lastMonth:e.z.number()}),pagination:e.z.object({page:e.z.number(),limit:e.z.number(),total:e.z.number(),totalPages:e.z.number(),hasNext:e.z.boolean(),hasPrev:e.z.boolean()})},X=f().router({getPayouts:{method:"GET",path:"",query:Z.payoutURLQueryParams,responses:{200:e.z.object({results:e.z.array(Z.payout),total:e.z.number()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List payouts",description:"Retrieve a paginated list of payouts with optional filtering"},getPayout:{method:"GET",path:"/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:Z.payout,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 payout details",description:"Retrieve detailed information about a specific payout"},getPayoutSummary:{method:"GET",path:"/summary",responses:{200:L.transactionSummary,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"Get payout summary",description:"Retrieve payout statistics including yesterday, today, this month, and last month totals"},getWalletInfo:{method:"GET",path:"/balance",responses:{200:L.walletSummary,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"Get account balance",description:"Retrieve current account balance and status information"}}),ee={[exports.PAYOUT_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[exports.PAYOUT_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.PAYOUT_STATUS.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[exports.PAYOUT_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Check payment details and try again"},[exports.PAYOUT_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE]:{label:"Insufficient Balance",description:"Insufficient funds are available to process the payment",category:"failed",color:"error",userFriendlyMessage:"Insufficient funds to complete the payment"},[exports.PAYOUT_STATUS.THIRDPARTY_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM]:{label:"Amount Exceeds Limit",description:"Payment amount exceeds the maximum allowed limit",category:"failed",color:"error",userFriendlyMessage:"Payment amount exceeds the allowed limit"},[exports.PAYOUT_STATUS.WALLET_DEBITED]:{label:"Wallet Debited",description:"Wallet has been debited but payment is not yet complete",category:"failed",color:"error",userFriendlyMessage:"Payment incomplete - wallet debited but recipient may not have received funds"},[exports.PAYOUT_STATUS.REVERSED]:{label:"Payment Reversed",description:"Payment has been reversed and funds returned",category:"failed",color:"error",userFriendlyMessage:"Payment was reversed and funds have been returned"},[exports.PAYOUT_STATUS.INVALID_SERVICE]:{label:"Invalid Service",description:"The requested payment service is not valid or available",category:"failed",color:"error",userFriendlyMessage:"Selected payment service is not available"}},te={[exports.MOBILE_PAYOUT_CHANNEL.AIRTEL]:{networkOperator:"Airtel",serviceName:"Airtel Money"},[exports.MOBILE_PAYOUT_CHANNEL.VODACOM]:{networkOperator:"Vodacom",serviceName:"M-Pesa"},[exports.MOBILE_PAYOUT_CHANNEL.TIGO]:{networkOperator:"Tigo",serviceName:"Tigo Pesa"},[exports.MOBILE_PAYOUT_CHANNEL.HALOTEL]:{networkOperator:"Halotel",serviceName:"HaloPesa"}};function re(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)}function oe(e){return e===exports.BANK_PAYOUT_CHANNEL.BANK}function ne(){return Object.entries(ee).filter(([e,t])=>"failed"===t.category).map(([e])=>e)}class se{constructor(e){var t,o;let n="TZS";r.CurrencyValidation.isCurrencyCode(e.currencyCode)&&(n=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=null!==(t=r.Amount.from(e.amount,n))&&void 0!==t?t:r.Amount.from(0,n),this.transactionDate=new Date(e.transactionDate),this.statusDescription=e.statusDescription,this.statusCodeText=e.statusCodeText,this.transactionId=e.transactionId,this.transactionRef=e.transactionRef,this.recipientNames=e.recipientNames,this.narration=e.narration,this.serviceFee=void 0===e.serviceFee?void 0:null!==(o=r.Amount.from(e.serviceFee,n))&&void 0!==o?o:r.Amount.from(0,n),this.notes=e.notes,this.swiftCode=e.swiftCode,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.statusCode=e.statusCode,this.countryCode=e.countryCode,this.postedAmount=e.postedAmount?r.Amount.from(parseFloat(e.postedAmount),n):void 0,this.walletId=e.walletId,this.currencyCode=e.currencyCode,this.externalId=e.externalId,this.cbaReferenceNo=e.cbaReferenceNo,this.beepTransactionId=e.beepTransactionId,this.receiptNumber=e.receiptNumber,this.reversedTransactionId=e.reversedTransactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.isReconciled=e.isReconciled,this.requestId=e.requestId}isPending(){return[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===exports.PAYOUT_STATUS.PAYMENT_ACCEPTED}isFailed(){return ne().includes(this.statusCodeText)}getStatusInfo(){return ee[this.statusCodeText]}getChannelInfo(){if(re(this.serviceCode))return te[this.serviceCode];if(oe(this.serviceCode)){const e=this.msisdn.split(":")[0];if(e&&r.BankValidation.validateSwiftCodeForAnyCountry(e)){const t=r.BankValidation.getCountryFromSwiftCode(e);if(t)try{return r.Bank.from(e,t)}catch(t){console.warn(`Failed to create Bank instance for SWIFT code ${e}:`,t)}}if(this.swiftCode&&r.BankValidation.validateSwiftCodeForAnyCountry(this.swiftCode)){const e=r.BankValidation.getCountryFromSwiftCode(this.swiftCode);if(e)try{return r.Bank.from(this.swiftCode,e)}catch(e){console.warn(`Failed to create Bank instance for SWIFT code ${this.swiftCode}:`,e)}}}}getProviderName(){const e=this.getChannelInfo();return re(this.serviceCode)&&e?e.networkOperator:r.Bank.is(e)?e.shortName:"Bank Transfer"}static from(e){try{return(null==e?void 0:e.id)&&(null==e?void 0:e.msisdn)&&void 0!==(null==e?void 0:e.amount)?new se(e):void console.error("Missing required Payout fields:",e)}catch(e){return void console.error("Error creating Payout:",e)}}static createMany(e){return e.map(e=>se.from(e)).filter(Boolean)}static fromJson(e){try{if(!(null==e?void 0:e.id)||!(null==e?void 0:e.msisdn)||!(null==e?void 0:e.amount))return void console.error("Missing required Payout JSON fields:",e);if(!r.Amount.isAmountJson(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.Amount.isAmountJson(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.Amount.isAmountJson(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJson(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let o,n;if(e.serviceFee){const t=r.Amount.fromJson(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);o=t.numericValue}if(e.postedAmount){const t=r.Amount.fromJson(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);n=t.numericValue.toString()}const s={id:e.id,serviceCode:e.serviceCode,msisdn:e.msisdn,amount:t.numericValue,transactionDate:e.transactionDate,statusDescription:e.statusDescription,statusCodeText:e.statusCodeText,transactionId:e.transactionId,transactionRef:e.transactionRef,recipientNames:e.recipientNames,narration:e.narration,serviceFee:o,notes:e.notes,swiftCode:e.swiftCode,createdAt:e.createdAt,updatedAt:e.updatedAt,statusCode:e.statusCode,countryCode:e.countryCode,postedAmount:n,walletId:e.walletId,currencyCode:e.currencyCode,externalId:e.externalId,cbaReferenceNo:e.cbaReferenceNo,beepTransactionId:e.beepTransactionId,receiptNumber:e.receiptNumber,reversedTransactionId:e.reversedTransactionId,serviceFeeTransactionId:e.serviceFeeTransactionId,isReconciled:e.isReconciled,requestId:e.requestId};return new se(s)}catch(e){return void console.error("Error creating Payout from JSON:",e)}}static createManyFromJson(e){return e.map(e=>se.fromJson(e)).filter(Boolean)}toJson(){var e,t;return{id:this.id,serviceCode:this.serviceCode,msisdn:this.msisdn,amount:this.amount.toJson(),transactionDate:this.transactionDate.toISOString(),statusDescription:this.statusDescription,statusCodeText:this.statusCodeText,transactionId:this.transactionId,transactionRef:this.transactionRef,recipientNames:this.recipientNames,narration:this.narration,serviceFee:null===(e=this.serviceFee)||void 0===e?void 0:e.toJson(),notes:this.notes,swiftCode:this.swiftCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),statusCode:this.statusCode,countryCode:this.countryCode,postedAmount:null===(t=this.postedAmount)||void 0===t?void 0:t.toJson(),walletId:this.walletId,currencyCode:this.currencyCode,externalId:this.externalId,cbaReferenceNo:this.cbaReferenceNo,beepTransactionId:this.beepTransactionId,receiptNumber:this.receiptNumber,reversedTransactionId:this.reversedTransactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,isReconciled:this.isReconciled,requestId:this.requestId}}}class ie extends u{static create(){return new ie}static fromFilters(e){return(new ie).applyFilters(e)}static fromUrlParams(e){try{const t=Z.payoutURLQueryParams.parse(e),r=Z.payoutFilters.parse(t);return ie.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 ie.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return ie.fromSearchParams(t)}static from(e){return null==e?new ie:u.is(e)?new ie(e.options):e instanceof URLSearchParams?ie.fromSearchParams(e):this.isStringRecord(e)?ie.fromUrlParams(e):ie.fromFilters(e)}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("statusCodeText",e)}whereChannel(e){return this.where("serviceCode",e)}wherePending(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK])}whereSuccessful(){return this.whereStatus(exports.PAYOUT_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PAYMENT_REJECTED,exports.PAYOUT_STATUS.GENERIC_FAILURE,exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM,exports.PAYOUT_STATUS.INVALID_SERVICE,exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE,exports.PAYOUT_STATUS.THIRDPARTY_FAILED,exports.PAYOUT_STATUS.WALLET_DEBITED,exports.PAYOUT_STATUS.REVERSED])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereRecipient(e){return this.whereContains("msisdn",e)}whereReference(e){return this.whereContains("transactionRef",e)}whereMobile(){return this.whereIn("serviceCode",Object.values(exports.MOBILE_PAYOUT_CHANNEL))}whereBank(){return this.whereChannel(exports.BANK_PAYOUT_CHANNEL.BANK)}whereSearch(e){return this.where("search",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.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereRecipient(e.msisdn),e.ref&&this.whereReference(e.ref),e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&void 0!==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,msisdn:e.msisdn,id:e.id,ref:e.transactionRef,channel:this.isValidChannel(e.serviceCode)?e.serviceCode:void 0,status:this.isValidStatus(e.statusCodeText)?e.statusCodeText: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}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.id||e.ref||e.channel||e.status||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.status&&e.push(`Status: ${t.status}`),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.msisdn&&e.push(`Recipient: ${t.msisdn}`),t.ref&&e.push(`Reference: ${t.ref}`),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"msisdn":case"transactionRef":"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}isValidChannel(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK}isValidStatus(e){return Object.values(exports.PAYOUT_STATUS).includes(e)}}exports.APIError=c,exports.AuthDTOSchemas=z,exports.AuthRepository=class extends I{constructor(e){super("auth",R,e)}async login(e){const t={type:e.type||"password",identity:e.identity,password:e.password},r=await this.client.login({body:t}),o=this.handleResponse(r,201),n=F.from(o);if(!n)throw new Error("Invalid user data received from server");return n}},exports.BaseRepository=I,exports.CHANNEL_INFO=Y,exports.COLLECTION_STATUS_INFO=k,exports.Collection=$,exports.CollectionDTOSchemas=j,exports.CollectionQuery=q,exports.CollectionRepository=class extends I{constructor(e){super("collection",J,e)}async getCollections(e){try{const t=q.from(e),r=t.build(),o=await this.client.getCollections({query:r}),n=this.handleResponse(o,200),s=t.toFilters(),i={page:s.page,limit:s.limit,total:n.total,totalPages:n.total>0?Math.ceil(n.total/s.limit):0,hasNext:s.page*s.limit<n.total,hasPrev:s.page>1};return{collections:$.createMany(n.results),pagination:i}}catch(e){throw new Error(`Failed to fetch collections: ${e instanceof Error?e.message:"Unknown error"}`)}}async getCollectionsFromRequest(e){const t=q.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),o=$.from(r);if(!o)throw new Error("Invalid collection data received from server");return o}async getCollectionStats(){const e=await this.client.getSummary(),t=this.handleResponse(e,200),r=P.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}async getWalletInfo(){const e=await this.client.getWalletInfo(),t=this.handleResponse(e,200),r=_.from(t);if(!r)throw new Error("Invalid wallet info received from server");return r}},exports.CommonSchemas=L,exports.MOBILE_CHANNEL_INFO=te,exports.PAYOUT_STATUS_INFO=ee,exports.Payout=se,exports.PayoutDTOSchemas=Z,exports.PayoutQuery=ie,exports.PayoutRepository=class extends I{constructor(e){super("payout",X,e)}async getPayouts(e){try{const t=ie.from(e),r=t.build(),o=await this.client.getPayouts({query:r}),n=this.handleResponse(o,200),s=t.toFilters(),i={page:s.page,limit:s.limit,total:n.total,totalPages:n.total>0?Math.ceil(n.total/s.limit):0,hasNext:s.page*s.limit<n.total,hasPrev:s.page>1};return{payouts:se.createMany(n.results),pagination:i}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=ie.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),o=se.from(r);if(!o)throw new Error("Invalid payout data received from server");return o}async getPayoutStats(){const e=await this.client.getPayoutSummary(),t=this.handleResponse(e,200),r=P.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}async getWalletInfo(){const e=await this.client.getWalletInfo(),t=this.handleResponse(e,200),r=_.from(t);if(!r)throw new Error("Invalid wallet info received from server");return r}},exports.QUERY_BUILDER_TYPE=l,exports.QueryBuilder=u,exports.TransactionSummary=P,exports.User=F,exports.WalletInfo=_,exports.authContract=R,exports.collectionContract=J,exports.getFailedStatuses=ne,exports.isBankChannel=oe,exports.isMobileChannel=re,exports.payoutContract=X;
1
+ "use strict";var e=require("zod"),t=require("uuid"),r=require("@temboplus/frontend-core");function o(e){return e&&e.__esModule?e:{default:e}}var n,s,a,i=o(e);class c extends Error{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 c.schema.safeParse(e).success}static unknown(e){return new c({message:null!=e?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()})}}exports.FilterOperator=void 0,(n=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",n.NOT_EQUALS="neq",n.LESS_THAN="lt",n.LESS_THAN_OR_EQUAL="lte",n.GREATER_THAN="gt",n.GREATER_THAN_OR_EQUAL="gte",n.LIKE="like",n.LIKE_LOWER="likeLower",n.IS_NULL="isNull",n.IS_NOT_NULL="isNotNull",n.IN="in",exports.SortDirection=void 0,(s=exports.SortDirection||(exports.SortDirection={})).ASC="asc",s.DESC="desc";const l=Symbol("query-builder-type");class u{constructor(e={}){this.options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8},this[a]="query-builder",this.options={filters:e.filters||[],sort:e.sort||[],includes:e.includes||[],groupBy:e.groupBy||[],join:e.join||[],page:e.page,limit:e.limit}}static is(e){return null!==e&&"object"==typeof e&&l in e&&"query-builder"===e[l]}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(){var e;const t={};if(void 0!==this.options.page&&void 0!==this.options.limit){const e=(this.options.page-1)*this.options.limit,r=e+this.options.limit-1;t.rangeStart=e,t.rangeEnd=r}if(this.options.filters&&this.options.filters.length>0)for(const e of this.options.filters)switch(e.operator){case exports.FilterOperator.IS_NULL:t[`${e.field}:isNull`]=1;break;case exports.FilterOperator.IS_NOT_NULL:t[`${e.field}:notNull`]=1;break;case exports.FilterOperator.IN:t[`${e.field}:in`]=Array.isArray(e.value)?e.value.join(","):e.value;break;case exports.FilterOperator.LIKE:t[`${e.field}:like`]=e.value;break;case exports.FilterOperator.LIKE_LOWER:t[`${e.field}:likeLower`]=e.value;break;case exports.FilterOperator.GREATER_THAN_OR_EQUAL:t[`${e.field}:gte`]=e.value;break;case exports.FilterOperator.LESS_THAN_OR_EQUAL:t[`${e.field}:lte`]=e.value;break;default:t[`${e.field}:${e.operator}`]=e.value}if(this.options.sort&&this.options.sort.length>0){const e=[],r=[];for(const t of this.options.sort)t.direction===exports.SortDirection.ASC?e.push(t.field):r.push(t.field);e.length>0&&(t.orderBy=e.join(",")),r.length>0&&(t.orderByDesc=r.join(","))}const r=null===(e=this.options.filters)||void 0===e?void 0:e.filter(e=>"createdAt"===e.field&&(e.operator===exports.FilterOperator.GREATER_THAN_OR_EQUAL||e.operator===exports.FilterOperator.LESS_THAN_OR_EQUAL));if(r){const e=r.find(e=>e.operator===exports.FilterOperator.GREATER_THAN_OR_EQUAL),o=r.find(e=>e.operator===exports.FilterOperator.LESS_THAN_OR_EQUAL);e&&(t.startDate=e.value),o&&(t.endDate=o.value)}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?t.eager=this.options.includes[0]:t.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(t.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(t.groupBy=this.options.groupBy.join(",")),this.options.count&&(t.count=this.options.count),t}clone(){return new(0,this.constructor)(Object.assign(Object.assign({},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 u(e)}}a=l;const d=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 m=Symbol("ContractNoBody"),h=e=>"method"in e&&"path"in e,p=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var o,n,s,a,i;return h(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:(a=null==t?void 0:t.baseHeaders,i=r.headers,d(a)?d(i)?a.merge(i):a:d(i)?i:Object.assign({},a,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!==(s=r.metadata)&&void 0!==s?s:{}}:r.metadata}]:[e,p(r,t)]})),A=Symbol("ContractPlainType"),f=()=>({router:(e,t)=>p(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>A,body:()=>A,type:()=>A,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>m}),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("&"):"",g=e=>e?Object.keys(e).flatMap(t=>T(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",T=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>T(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>T(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class v extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const E=async({route:e,path:t,method:r,headers:o,body:n,validateResponse:s,fetchOptions:a})=>{const i=await fetch(t,{...a,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!=s?s: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}},C=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])),O=(e,t,r,o,n)=>{const s=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:o.path,params:r}),a=((e,t=!1)=>{const r=t?y(e):g(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,n);return`${t}${s}${a}`},S=(e,t)=>{const r=Object.keys(e.responses);return async o=>{const n=((e,t,r)=>{const{query:o,params:n,body:s,headers:a,extraHeaders:i,overrideClientOptions:c,fetchOptions:l,cache:u,next:d,...m}=r||{},h={...t,...c};return{path:O(o,h.baseUrl,n,e,!!h.jsonQuery),clientArgs:h,route:e,body:s,query:o,extraInputArgs:m,fetchOptions:{...u&&{cache:u},...d&&{next:d},...l},headers:{...i,...a}}})(e,t,o),s=await(e=>{const{path:t,clientArgs:r,route:o,body:n,query:s,extraInputArgs:a,headers:i,fetchOptions:c}=e,l=r.api||E,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 m={route:o,path:t,method:o.method,headers:d,body:void 0,rawBody:n,rawQuery:s,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==o.method&&("contentType"in o&&"multipart/form-data"===o.contentType?m={...m,contentType:"multipart/form-data",body:n instanceof FormData?n:C(n)}:"contentType"in o&&"application/x-www-form-urlencoded"===o.contentType?m={...m,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...m.headers},body:"string"==typeof n?n:new URLSearchParams(n)}:null!=n&&(m={...m,contentType:"application/json",headers:{"content-type":"application/json",...m.headers},body:JSON.stringify(n)})),l({...m,...a})})(n);if(!t.throwOnUnknownStatus)return s;if(r.includes(s.status.toString()))return s;throw new v(s,r)}},w=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>h(r)?[e,S(r,t)]:[e,w(r,t)]));class I{constructor(e,t,r){this.contract=t,this.endpoint=e,this.root=null==r?void 0:r.root,this.token=null==r?void 0:r.token}getToken(){return this.token&&this.token.trim().length>0?this.token:""}get client(){const e=this.root?this.root.replace(/\/+$/,""):"",r=this.endpoint?this.endpoint.replace(/^\/+/,""):"",o={baseUrl:e?`${e}/${r}`:`https://gateway.temboplus.com/dashboard/${r}`,baseHeaders:{Authorization:`Bearer ${this.getToken()}`,"x-request-id":t.v4()}};return w(this.contract,o)}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=i.default.object({statusCode:i.default.number(),message:i.default.string(),error:i.default.string(),details:i.default.record(i.default.string()).optional()}).safeParse(e.body);if(t.success)throw new c(t.data);throw new c({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===e.status)throw new c({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new c({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new c({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new c({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}const b=i.default.object({page:i.default.number().int().positive(),limit:i.default.number().int().positive(),total:i.default.number().int().min(0),totalPages:i.default.number().int().min(0),hasNext:i.default.boolean(),hasPrev:i.default.boolean()}),x=i.default.object({balance:i.default.number(),availableBalance:i.default.number(),accountNumber:i.default.string(),accountName:i.default.string()}),L={pagination:b,transactionSummary:i.default.object({yesterday:i.default.number(),today:i.default.number(),thisMonth:i.default.number(),lastMonth:i.default.number()}),walletSummary:x};class P{constructor(e,t="TZS"){var o,n,s,a;this.currency=t,this.yesterday=null!==(o=r.Amount.from(e.yesterday,t))&&void 0!==o?o:r.Amount.from(0,t),this.today=null!==(n=r.Amount.from(e.today,t))&&void 0!==n?n:r.Amount.from(0,t),this.thisMonth=null!==(s=r.Amount.from(e.thisMonth,t))&&void 0!==s?s:r.Amount.from(0,t),this.lastMonth=null!==(a=r.Amount.from(e.lastMonth,t))&&void 0!==a?a:r.Amount.from(0,t)}getMonthlyGrowthRate(){return 0===this.lastMonth.numericValue?this.thisMonth.numericValue>0?100:0:(this.thisMonth.numericValue-this.lastMonth.numericValue)/this.lastMonth.numericValue*100}getRecentTotal(){return r.Amount.from(this.today.numericValue+this.yesterday.numericValue,this.currency)}static from(e,t="TZS"){return new P(e,t)}toJson(){return{yesterday:this.yesterday.toJson(),today:this.today.toJson(),thisMonth:this.thisMonth.toJson(),lastMonth:this.lastMonth.toJson(),currency:this.currency}}static fromJson(e){try{if(!(r.Amount.isAmountJson(e.yesterday)&&r.Amount.isAmountJson(e.today)&&r.Amount.isAmountJson(e.thisMonth)&&r.Amount.isAmountJson(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=r.Amount.fromJson(e.yesterday),o=r.Amount.fromJson(e.today),n=r.Amount.fromJson(e.thisMonth),s=r.Amount.fromJson(e.lastMonth);if(!(t&&o&&n&&s))return void console.error("Failed to reconstruct Amount instances from JSON:",e);const a={yesterday:t.numericValue,today:o.numericValue,thisMonth:n.numericValue,lastMonth:s.numericValue};return new P(a,e.currency)}catch(e){return void console.error("Error creating TransactionSummary from JSON:",e)}}}class _{constructor(e){var t,o;let n="TZS";this.accountName=e.accountName,this.accountNumber=e.accountNumber,this.currency=n,this.availableBalance=null!==(t=r.Amount.from(e.availableBalance,n))&&void 0!==t?t:r.Amount.from(0,n),this.actualBalance=null!==(o=r.Amount.from(e.balance,n))&&void 0!==o?o:r.Amount.from(0,n)}hasSufficientBalance(e){return this.availableBalance.numericValue>=e}static from(e){return new _(e)}toJson(){return{accountName:this.accountName,accountNumber:this.accountNumber,availableBalance:this.availableBalance.toJson(),actualBalance:this.actualBalance.toJson(),currency:this.currency}}static fromJson(e){try{if(!r.Amount.isAmountJson(e.availableBalance)||!r.Amount.isAmountJson(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const t=r.Amount.fromJson(e.availableBalance),o=r.Amount.fromJson(e.actualBalance);if(!t||!o)return void console.error("Failed to reconstruct Amount instances from JSON:",e);const n={accountName:e.accountName,accountNumber:e.accountNumber,availableBalance:t.numericValue,balance:o.numericValue};return new _(n)}catch(e){return void console.error("Error creating WalletInfo from JSON:",e)}}static createManyFromJson(e){return e.map(e=>_.fromJson(e)).filter(Boolean)}}const z={user:e.z.object({token:e.z.string(),identity:e.z.string(),name:e.z.string()}),loginRequest:e.z.object({type:e.z.string().default("password"),identity:e.z.string().email(),password:e.z.string()})},R=f().router({login:{method:"POST",path:"/auth/login",body:z.loginRequest,responses:{201:z.user,400:e.z.object({message:e.z.string().optional()}),401:e.z.object({message:e.z.string().optional()})},summary:"User login",description:"Authenticate user with email and password"}});class F{constructor(e){this.identity=e.identity,this.name=e.name}static from(e){return new F(e)}static fromJson(e){return F.from(e)}toJson(){return{identity:this.identity,name:this.name}}get email(){return this.identity}getDisplayName(){return this.name||this.identity}isEmailIdentity(){return/^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i.test(this.identity)}getInitials(){return this.getDisplayName().split(" ").map(e=>e.charAt(0).toUpperCase()).slice(0,2).join("")}equals(e){return this.identity===e.identity&&this.name===e.name}}var U,D;exports.COLLECTION_STATUS=void 0,(U=exports.COLLECTION_STATUS||(exports.COLLECTION_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",U.GENERIC_FAILURE="GENERIC_FAILURE",U.PAYMENT_REJECTED="PAYMENT_REJECTED",U.PENDING_ACK="PENDING_ACK",exports.COLLECTION_CHANNEL=void 0,(D=exports.COLLECTION_CHANNEL||(exports.COLLECTION_CHANNEL={})).AIRTEL="TZ-AIRTEL-C2B",D.TIGO="TZ-TIGO-C2B",D.HALOTEL="TZ-HALOTEL-C2B";const B=e.z.nativeEnum(exports.COLLECTION_STATUS),M=e.z.nativeEnum(exports.COLLECTION_CHANNEL),j={collection:e.z.object({id:e.z.string().min(1),status:B,statusMessage:e.z.string(),accountNo:e.z.string().min(1),walletId:e.z.string(),transactionDate:e.z.string().datetime(),narration:e.z.string(),msisdn:e.z.string().min(1),channel:M,amount:e.z.number().min(0),serviceFee:e.z.string().optional(),postedAmount:e.z.string().optional(),reference:e.z.string(),partnerReference:e.z.string().nullable().optional(),transactionId:e.z.string().nullable().optional(),serviceFeeTransactionId:e.z.string().nullable().optional(),requestId:e.z.string().nullable().optional(),completedAt:e.z.string().datetime().nullable().optional(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime(),notes:e.z.string().optional(),currencyCode:e.z.string().default("TZS")}),collectionFilters:e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(100).default(20),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().optional(),endDate:e.z.string().datetime().optional(),msisdn:e.z.string().optional(),id:e.z.string().optional(),reference:e.z.string().optional(),accountNo:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:M.optional(),status:B.optional(),minAmount:e.z.number().min(0).optional(),maxAmount:e.z.number().min(0).optional(),search:e.z.string().optional()}),collectionURLQueryParams: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(),msisdn:e.z.string().optional(),id:e.z.string().optional(),reference:e.z.string().optional(),accountNo:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:e.z.string().refine(e=>Object.values(exports.COLLECTION_CHANNEL).includes(e)).transform(e=>e).optional(),status:e.z.string().refine(e=>Object.values(exports.COLLECTION_STATUS).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()}),paymentStatus:B,paymentChannel:M},J=f().router({getCollections:{method:"GET",path:"/",query:e.z.object({}),responses:{200:e.z.object({results:e.z.array(j.collection),total:e.z.number()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List collections",description:"Retrieve a paginated list of collections with optional filtering"},getCollection:{method:"GET",path:"/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:j.collection,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 collection details",description:"Retrieve detailed information about a specific collection"},getSummary:{method:"GET",path:"/summary",responses:{200:e.z.object({yesterday:e.z.number(),today:e.z.number(),thisMonth:e.z.number(),lastMonth:e.z.number()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"Get collections summary",description:"Retrieve collection summary statistics for different time periods"},getWalletInfo:{method:"GET",path:"/balance",responses:{200:L.walletSummary,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"Get account balance",description:"Retrieve current account balance and summary information"}}),Y={[exports.COLLECTION_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[exports.COLLECTION_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.COLLECTION_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Please try again"},[exports.COLLECTION_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred during payment processing",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"}},k={[exports.COLLECTION_CHANNEL.AIRTEL]:{networkOperator:"Airtel",serviceName:"Airtel Money",type:"mobile"},[exports.COLLECTION_CHANNEL.TIGO]:{networkOperator:"Tigo",serviceName:"Tigo Pesa",type:"mobile"},[exports.COLLECTION_CHANNEL.HALOTEL]:{networkOperator:"Halotel",serviceName:"HaloPesa",type:"mobile"}};class ${constructor(e){var t,o,n;let s="TZS";r.CurrencyValidation.isCurrencyCode(e.currencyCode)&&(s=e.currencyCode),this.id=e.id,this.status=e.status,this.statusMessage=e.statusMessage,this.accountNo=e.accountNo,this.walletId=e.walletId,this.transactionDate=new Date(e.transactionDate),this.narration=e.narration,this.msisdn=e.msisdn,this.channel=e.channel,this.amount=null!==(t=r.Amount.from(e.amount,s))&&void 0!==t?t:r.Amount.from(0,s),this.serviceFee=e.serviceFee?null!==(o=r.Amount.from(parseFloat(e.serviceFee),s))&&void 0!==o?o:r.Amount.from(0,s):void 0,this.postedAmount=e.postedAmount?null!==(n=r.Amount.from(parseFloat(e.postedAmount),s))&&void 0!==n?n:r.Amount.from(0,s):void 0,this.reference=e.reference,this.partnerReference=e.partnerReference,this.transactionId=e.transactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.requestId=e.requestId,this.completedAt=e.completedAt?new Date(e.completedAt):null,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.notes=e.notes,this.currencyCode=e.currencyCode}isPending(){return this.status===exports.COLLECTION_STATUS.PENDING_ACK}isSuccessful(){return this.status===exports.COLLECTION_STATUS.PAYMENT_ACCEPTED}isFailed(){return Object.entries(Y).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.status)}getStatusInfo(){return Y[this.status]}getChannelInfo(){return k[this.channel]}getProviderName(){return this.getChannelInfo().networkOperator}getServiceName(){return this.getChannelInfo().serviceName}isMobileCollection(){return e=this.channel,"mobile"===k[e].type;var e}isBankCollection(){return e=this.channel,"bank"===k[e].type;var e}static from(e){try{return(null==e?void 0:e.id)&&(null==e?void 0:e.msisdn)&&void 0!==(null==e?void 0:e.amount)?new $(e):void console.error("Missing required Collection fields:",e)}catch(e){return void console.error("Error creating Collection:",e)}}static createMany(e){return e.map(e=>$.from(e)).filter(Boolean)}static fromJson(e){try{if(!(null==e?void 0:e.id)||!(null==e?void 0:e.msisdn)||!(null==e?void 0:e.amount))return void console.error("Missing required Collection JSON fields:",e);if(!r.Amount.isAmountJson(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.Amount.isAmountJson(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.Amount.isAmountJson(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJson(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let o,n;if(e.serviceFee){const t=r.Amount.fromJson(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);o=t.numericValue.toString()}if(e.postedAmount){const t=r.Amount.fromJson(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);n=t.numericValue.toString()}const s={id:e.id,status:e.status,statusMessage:e.statusMessage,accountNo:e.accountNo,walletId:e.walletId,transactionDate:e.transactionDate,narration:e.narration,msisdn:e.msisdn,channel:e.channel,amount:t.numericValue,serviceFee:o,postedAmount:n,reference:e.reference,partnerReference:e.partnerReference,transactionId:e.transactionId,serviceFeeTransactionId:e.serviceFeeTransactionId,requestId:e.requestId,completedAt:e.completedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,notes:e.notes,currencyCode:e.currencyCode};return new $(s)}catch(e){return void console.error("Error creating Collection from JSON:",e)}}static createManyFromJson(e){return e.map(e=>$.fromJson(e)).filter(Boolean)}toJson(){var e,t,r,o;return{id:this.id,status:this.status,statusMessage:this.statusMessage,accountNo:this.accountNo,walletId:this.walletId,transactionDate:this.transactionDate.toISOString(),narration:this.narration,msisdn:this.msisdn,channel:this.channel,amount:this.amount.toJson(),serviceFee:null===(e=this.serviceFee)||void 0===e?void 0:e.toJson(),postedAmount:null===(t=this.postedAmount)||void 0===t?void 0:t.toJson(),reference:this.reference,partnerReference:this.partnerReference,transactionId:this.transactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,requestId:this.requestId,completedAt:null!==(o=null===(r=this.completedAt)||void 0===r?void 0:r.toISOString())&&void 0!==o?o:null,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),notes:this.notes,currencyCode:this.currencyCode}}}class H extends u{static create(){return new H}static fromFilters(e){return(new H).applyFilters(e)}static fromUrlParams(e){try{const t=j.collectionURLQueryParams.parse(e),r=j.collectionFilters.parse(t);return H.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 H.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return H.fromSearchParams(t)}static from(e){try{return null==e?new H:u.is(e)?new H(e.options):e instanceof URLSearchParams?H.fromSearchParams(e):this.isStringRecord(e)?H.fromUrlParams(e):H.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a CollectionQuery 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)}whereChannel(e){return this.where("channel",e)}wherePending(){return this.whereStatus(exports.COLLECTION_STATUS.PENDING_ACK)}whereSuccessful(){return this.whereStatus(exports.COLLECTION_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("status",[exports.COLLECTION_STATUS.PAYMENT_REJECTED,exports.COLLECTION_STATUS.GENERIC_FAILURE])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereSender(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereReference(e){return this.whereContains("reference",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",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.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereSender(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.reference&&this.whereReference(e.reference),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&&void 0!==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,msisdn:e.msisdn,id:e.id,reference:e.reference,accountNo:e.accountNo,partnerReference:e.partnerReference,channel:this.isValidChannel(e.channel)?e.channel:void 0,status:this.isValidStatus(e.status)?e.status: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}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.id||e.reference||e.accountNo||e.partnerReference||e.channel||e.status||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.status&&e.push(`Status: ${t.status}`),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.msisdn&&e.push(`Phone: ${t.msisdn}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.reference&&e.push(`Reference: ${t.reference}`),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"msisdn":case"reference":case"accountNo":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}isValidChannel(e){return Object.values(exports.COLLECTION_CHANNEL).includes(e)}isValidStatus(e){return Object.values(exports.COLLECTION_STATUS).includes(e)}}var q,G;exports.PAYOUT_STATUS=void 0,(q=exports.PAYOUT_STATUS||(exports.PAYOUT_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",q.GENERIC_FAILURE="GENERIC_FAILURE",q.WALLET_DEBITED="WALLET_DEBITED",q.PAYMENT_REJECTED="PAYMENT_REJECTED",q.PENDING="PENDING",q.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",q.PENDING_ACK="PENDING_ACK",q.REVERSED="REVERSED",q.INVALID_SERVICE="INVALID_SERVICE",q.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",q.THIRDPARTY_FAILED="THIRDPARTY_FAILED",exports.MOBILE_PAYOUT_CHANNEL=void 0,(G=exports.MOBILE_PAYOUT_CHANNEL||(exports.MOBILE_PAYOUT_CHANNEL={})).AIRTEL="TZ-AIRTEL-B2C",G.VODACOM="TZ-VODACOM-B2C",G.TIGO="TZ-TIGO-B2C",G.HALOTEL="TZ-HALOTEL-B2C",exports.BANK_PAYOUT_CHANNEL=void 0,(exports.BANK_PAYOUT_CHANNEL||(exports.BANK_PAYOUT_CHANNEL={})).BANK="TZ-BANK-B2C";const V=e.z.nativeEnum(exports.PAYOUT_STATUS),K=e.z.nativeEnum(exports.MOBILE_PAYOUT_CHANNEL),Q=e.z.nativeEnum(exports.BANK_PAYOUT_CHANNEL),W=e.z.union([K,Q]),Z={payout:e.z.object({id:e.z.string().min(1),statusCode:e.z.string(),statusCodeText:V,statusDescription:e.z.string(),countryCode:e.z.string(),serviceCode:W,amount:e.z.number().min(0),serviceFee:e.z.string().optional(),postedAmount:e.z.string().optional(),walletId:e.z.string().optional(),msisdn:e.z.string().min(1),narration:e.z.string(),currencyCode:e.z.string(),recipientNames:e.z.string().optional(),transactionRef:e.z.string(),transactionDate:e.z.string().datetime(),externalId:e.z.string().nullable().optional(),cbaReferenceNo:e.z.string().optional(),beepTransactionId:e.z.string().optional(),receiptNumber:e.z.string().optional(),createdAt:e.z.string().datetime(),reversedTransactionId:e.z.string().nullable().optional(),transactionId:e.z.string(),serviceFeeTransactionId:e.z.string().optional(),isReconciled:e.z.number().optional(),requestId:e.z.string().optional(),notes:e.z.string().optional(),updatedAt:e.z.string().datetime().optional()}),payoutFilters:e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(100).default(20),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().optional(),endDate:e.z.string().datetime().optional(),msisdn:e.z.string().optional(),id:e.z.string().optional(),ref:e.z.string().optional(),channel:W.optional(),status:V.optional(),minAmount:e.z.number().min(0).optional(),maxAmount:e.z.number().min(0).optional(),search:e.z.string().optional()}),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(),msisdn:e.z.string().optional(),id:e.z.string().optional(),ref:e.z.string().optional(),channel:e.z.string().refine(e=>Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK).transform(e=>e).optional(),status:e.z.string().refine(e=>Object.values(exports.PAYOUT_STATUS).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()}),payoutStatus:V,payoutChannel:W,mobileChannel:K,bankChannel:Q,walletSummary:e.z.object({balance:e.z.number(),currency:e.z.string(),lastUpdated:e.z.string().datetime()}),transactionSummary:e.z.object({yesterday:e.z.number(),today:e.z.number(),thisMonth:e.z.number(),lastMonth:e.z.number()}),pagination:e.z.object({page:e.z.number(),limit:e.z.number(),total:e.z.number(),totalPages:e.z.number(),hasNext:e.z.boolean(),hasPrev:e.z.boolean()})},X=f().router({getPayouts:{method:"GET",path:"",query:Z.payoutURLQueryParams,responses:{200:e.z.object({results:e.z.array(Z.payout),total:e.z.number()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List payouts",description:"Retrieve a paginated list of payouts with optional filtering"},getPayout:{method:"GET",path:"/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:Z.payout,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 payout details",description:"Retrieve detailed information about a specific payout"},getPayoutSummary:{method:"GET",path:"/summary",responses:{200:L.transactionSummary,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"Get payout summary",description:"Retrieve payout statistics including yesterday, today, this month, and last month totals"},getWalletInfo:{method:"GET",path:"/balance",responses:{200:L.walletSummary,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"Get account balance",description:"Retrieve current account balance and status information"}}),ee={[exports.PAYOUT_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[exports.PAYOUT_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.PAYOUT_STATUS.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[exports.PAYOUT_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Check payment details and try again"},[exports.PAYOUT_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE]:{label:"Insufficient Balance",description:"Insufficient funds are available to process the payment",category:"failed",color:"error",userFriendlyMessage:"Insufficient funds to complete the payment"},[exports.PAYOUT_STATUS.THIRDPARTY_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM]:{label:"Amount Exceeds Limit",description:"Payment amount exceeds the maximum allowed limit",category:"failed",color:"error",userFriendlyMessage:"Payment amount exceeds the allowed limit"},[exports.PAYOUT_STATUS.WALLET_DEBITED]:{label:"Wallet Debited",description:"Wallet has been debited but payment is not yet complete",category:"failed",color:"error",userFriendlyMessage:"Payment incomplete - wallet debited but recipient may not have received funds"},[exports.PAYOUT_STATUS.REVERSED]:{label:"Payment Reversed",description:"Payment has been reversed and funds returned",category:"failed",color:"error",userFriendlyMessage:"Payment was reversed and funds have been returned"},[exports.PAYOUT_STATUS.INVALID_SERVICE]:{label:"Invalid Service",description:"The requested payment service is not valid or available",category:"failed",color:"error",userFriendlyMessage:"Selected payment service is not available"}},te={[exports.MOBILE_PAYOUT_CHANNEL.AIRTEL]:{networkOperator:"Airtel",serviceName:"Airtel Money"},[exports.MOBILE_PAYOUT_CHANNEL.VODACOM]:{networkOperator:"Vodacom",serviceName:"M-Pesa"},[exports.MOBILE_PAYOUT_CHANNEL.TIGO]:{networkOperator:"Tigo",serviceName:"Tigo Pesa"},[exports.MOBILE_PAYOUT_CHANNEL.HALOTEL]:{networkOperator:"Halotel",serviceName:"HaloPesa"}};function re(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)}function oe(e){return e===exports.BANK_PAYOUT_CHANNEL.BANK}function ne(){return Object.entries(ee).filter(([e,t])=>"failed"===t.category).map(([e])=>e)}class se{constructor(e){var t,o;let n="TZS";r.CurrencyValidation.isCurrencyCode(e.currencyCode)&&(n=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=null!==(t=r.Amount.from(e.amount,n))&&void 0!==t?t:r.Amount.from(0,n),this.transactionDate=new Date(e.transactionDate),this.statusDescription=e.statusDescription,this.statusCodeText=e.statusCodeText,this.transactionId=e.transactionId,this.transactionRef=e.transactionRef,this.recipientNames=e.recipientNames,this.narration=e.narration,this.serviceFee=void 0===e.serviceFee?void 0:null!==(o=r.Amount.from(e.serviceFee,n))&&void 0!==o?o:r.Amount.from(0,n),this.notes=e.notes,this.swiftCode=e.swiftCode,this.createdAt=new Date(e.createdAt),this.updatedAt=e.updatedAt?new Date(e.updatedAt):void 0,this.statusCode=e.statusCode,this.countryCode=e.countryCode,this.postedAmount=e.postedAmount?r.Amount.from(parseFloat(e.postedAmount),n):void 0,this.walletId=e.walletId,this.currencyCode=e.currencyCode,this.externalId=e.externalId,this.cbaReferenceNo=e.cbaReferenceNo,this.beepTransactionId=e.beepTransactionId,this.receiptNumber=e.receiptNumber,this.reversedTransactionId=e.reversedTransactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.isReconciled=e.isReconciled,this.requestId=e.requestId}isPending(){return[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===exports.PAYOUT_STATUS.PAYMENT_ACCEPTED}isFailed(){return ne().includes(this.statusCodeText)}getStatusInfo(){return ee[this.statusCodeText]}getChannelInfo(){if(re(this.serviceCode))return te[this.serviceCode];if(oe(this.serviceCode)){const e=this.msisdn.split(":")[0];if(e&&r.BankValidation.validateSwiftCodeForAnyCountry(e)){const t=r.BankValidation.getCountryFromSwiftCode(e);if(t)try{return r.Bank.from(e,t)}catch(t){console.warn(`Failed to create Bank instance for SWIFT code ${e}:`,t)}}if(this.swiftCode&&r.BankValidation.validateSwiftCodeForAnyCountry(this.swiftCode)){const e=r.BankValidation.getCountryFromSwiftCode(this.swiftCode);if(e)try{return r.Bank.from(this.swiftCode,e)}catch(e){console.warn(`Failed to create Bank instance for SWIFT code ${this.swiftCode}:`,e)}}}}getProviderName(){const e=this.getChannelInfo();return re(this.serviceCode)&&e?e.networkOperator:r.Bank.is(e)?e.shortName:"Bank Transfer"}static from(e){try{return(null==e?void 0:e.id)&&(null==e?void 0:e.msisdn)&&void 0!==(null==e?void 0:e.amount)?new se(e):void console.error("Missing required Payout fields:",e)}catch(e){return void console.error("Error creating Payout:",e)}}static createMany(e){return e.map(e=>se.from(e)).filter(Boolean)}static fromJson(e){try{if(!(null==e?void 0:e.id)||!(null==e?void 0:e.msisdn)||!(null==e?void 0:e.amount))return void console.error("Missing required Payout JSON fields:",e);if(!r.Amount.isAmountJson(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.Amount.isAmountJson(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.Amount.isAmountJson(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJson(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let o,n;if(e.serviceFee){const t=r.Amount.fromJson(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);o=t.numericValue}if(e.postedAmount){const t=r.Amount.fromJson(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);n=t.numericValue.toString()}const s={id:e.id,serviceCode:e.serviceCode,msisdn:e.msisdn,amount:t.numericValue,transactionDate:e.transactionDate,statusDescription:e.statusDescription,statusCodeText:e.statusCodeText,transactionId:e.transactionId,transactionRef:e.transactionRef,recipientNames:e.recipientNames,narration:e.narration,serviceFee:o,notes:e.notes,swiftCode:e.swiftCode,createdAt:e.createdAt,updatedAt:e.updatedAt,statusCode:e.statusCode,countryCode:e.countryCode,postedAmount:n,walletId:e.walletId,currencyCode:e.currencyCode,externalId:e.externalId,cbaReferenceNo:e.cbaReferenceNo,beepTransactionId:e.beepTransactionId,receiptNumber:e.receiptNumber,reversedTransactionId:e.reversedTransactionId,serviceFeeTransactionId:e.serviceFeeTransactionId,isReconciled:e.isReconciled,requestId:e.requestId};return new se(s)}catch(e){return void console.error("Error creating Payout from JSON:",e)}}static createManyFromJson(e){return e.map(e=>se.fromJson(e)).filter(Boolean)}toJson(){var e,t,r;return{id:this.id,serviceCode:this.serviceCode,msisdn:this.msisdn,amount:this.amount.toJson(),transactionDate:this.transactionDate.toISOString(),statusDescription:this.statusDescription,statusCodeText:this.statusCodeText,transactionId:this.transactionId,transactionRef:this.transactionRef,recipientNames:this.recipientNames,narration:this.narration,serviceFee:null===(e=this.serviceFee)||void 0===e?void 0:e.toJson(),notes:this.notes,swiftCode:this.swiftCode,createdAt:this.createdAt.toISOString(),updatedAt:null===(t=this.updatedAt)||void 0===t?void 0:t.toISOString(),statusCode:this.statusCode,countryCode:this.countryCode,postedAmount:null===(r=this.postedAmount)||void 0===r?void 0:r.toJson(),walletId:this.walletId,currencyCode:this.currencyCode,externalId:this.externalId,cbaReferenceNo:this.cbaReferenceNo,beepTransactionId:this.beepTransactionId,receiptNumber:this.receiptNumber,reversedTransactionId:this.reversedTransactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,isReconciled:this.isReconciled,requestId:this.requestId}}}class ae extends u{static create(){return new ae}static fromFilters(e){return(new ae).applyFilters(e)}static fromUrlParams(e){try{const t=Z.payoutURLQueryParams.parse(e),r=Z.payoutFilters.parse(t);return ae.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 ae.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return ae.fromSearchParams(t)}static from(e){return null==e?new ae:u.is(e)?new ae(e.options):e instanceof URLSearchParams?ae.fromSearchParams(e):this.isStringRecord(e)?ae.fromUrlParams(e):ae.fromFilters(e)}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("statusCodeText",e)}whereChannel(e){return this.where("serviceCode",e)}wherePending(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK])}whereSuccessful(){return this.whereStatus(exports.PAYOUT_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PAYMENT_REJECTED,exports.PAYOUT_STATUS.GENERIC_FAILURE,exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM,exports.PAYOUT_STATUS.INVALID_SERVICE,exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE,exports.PAYOUT_STATUS.THIRDPARTY_FAILED,exports.PAYOUT_STATUS.WALLET_DEBITED,exports.PAYOUT_STATUS.REVERSED])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereRecipient(e){return this.whereContains("msisdn",e)}whereReference(e){return this.whereContains("transactionRef",e)}whereMobile(){return this.whereIn("serviceCode",Object.values(exports.MOBILE_PAYOUT_CHANNEL))}whereBank(){return this.whereChannel(exports.BANK_PAYOUT_CHANNEL.BANK)}whereSearch(e){return this.where("search",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.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereRecipient(e.msisdn),e.ref&&this.whereReference(e.ref),e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&void 0!==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,msisdn:e.msisdn,id:e.id,ref:e.transactionRef,channel:this.isValidChannel(e.serviceCode)?e.serviceCode:void 0,status:this.isValidStatus(e.statusCodeText)?e.statusCodeText: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}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.id||e.ref||e.channel||e.status||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.status&&e.push(`Status: ${t.status}`),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.msisdn&&e.push(`Recipient: ${t.msisdn}`),t.ref&&e.push(`Reference: ${t.ref}`),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"msisdn":case"transactionRef":"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}isValidChannel(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK}isValidStatus(e){return Object.values(exports.PAYOUT_STATUS).includes(e)}}exports.APIError=c,exports.AuthDTOSchemas=z,exports.AuthRepository=class extends I{constructor(e){super("auth",R,e)}async login(e){const t={type:"password",identity:e.email,password:e.password},r=await this.client.login({body:t}),o=this.handleResponse(r,201),n=F.from(o);if(!n)throw new Error("Invalid user data received from server");return{user:n,token:o.token}}},exports.BaseRepository=I,exports.CHANNEL_INFO=k,exports.COLLECTION_STATUS_INFO=Y,exports.Collection=$,exports.CollectionDTOSchemas=j,exports.CollectionQuery=H,exports.CollectionRepository=class extends I{constructor(e){super("collection",J,e)}async getCollections(e){try{const t=H.from(e),r=t.build(),o=await this.client.getCollections({query:r}),n=this.handleResponse(o,200),s=t.toFilters(),a={page:s.page,limit:s.limit,total:n.total,totalPages:n.total>0?Math.ceil(n.total/s.limit):0,hasNext:s.page*s.limit<n.total,hasPrev:s.page>1};return{collections:$.createMany(n.results),pagination:a}}catch(e){throw new Error(`Failed to fetch collections: ${e instanceof Error?e.message:"Unknown error"}`)}}async getCollectionsFromRequest(e){const t=H.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),o=$.from(r);if(!o)throw new Error("Invalid collection data received from server");return o}async getCollectionStats(){const e=await this.client.getSummary(),t=this.handleResponse(e,200),r=P.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}async getWalletInfo(){const e=await this.client.getWalletInfo(),t=this.handleResponse(e,200),r=_.from(t);if(!r)throw new Error("Invalid wallet info received from server");return r}},exports.CommonSchemas=L,exports.MOBILE_CHANNEL_INFO=te,exports.PAYOUT_STATUS_INFO=ee,exports.Payout=se,exports.PayoutDTOSchemas=Z,exports.PayoutQuery=ae,exports.PayoutRepository=class extends I{constructor(e){super("payout",X,e)}async getPayouts(e){try{const t=ae.from(e),r=t.build(),o=await this.client.getPayouts({query:r}),n=this.handleResponse(o,200),s=t.toFilters(),a={page:s.page,limit:s.limit,total:n.total,totalPages:n.total>0?Math.ceil(n.total/s.limit):0,hasNext:s.page*s.limit<n.total,hasPrev:s.page>1};return{payouts:se.createMany(n.results),pagination:a}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=ae.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),o=se.from(r);if(!o)throw new Error("Invalid payout data received from server");return o}async getPayoutStats(){const e=await this.client.getPayoutSummary(),t=this.handleResponse(e,200),r=P.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}async getWalletInfo(){const e=await this.client.getWalletInfo(),t=this.handleResponse(e,200),r=_.from(t);if(!r)throw new Error("Invalid wallet info received from server");return r}},exports.QUERY_BUILDER_TYPE=l,exports.QueryBuilder=u,exports.TransactionSummary=P,exports.User=F,exports.WalletInfo=_,exports.authContract=R,exports.collectionContract=J,exports.getFailedStatuses=ne,exports.isBankChannel=oe,exports.isMobileChannel=re,exports.payoutContract=X;
2
2
  //# sourceMappingURL=index.cjs.js.map