@temboplus/tembo-dashboard 0.0.16 → 0.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import e,{z as t}from"zod";import{v4 as r}from"uuid";import{Amount as n,CurrencyValidation as s,BankValidation as o,Bank as i}from"@temboplus/frontend-core";class a 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 a.schema.safeParse(e).success}static unknown(e){return new a({message:null!=e?e:"An unknown error occurred",statusCode:502})}static get schema(){return t.object({message:t.string(),statusCode:t.number().int(),error:t.string().optional(),details:t.object({}).optional()})}}var c,l,u;!function(e){e.EQUALS="eq",e.NOT_EQUALS="neq",e.LESS_THAN="lt",e.LESS_THAN_OR_EQUAL="lte",e.GREATER_THAN="gt",e.GREATER_THAN_OR_EQUAL="gte",e.LIKE="like",e.LIKE_LOWER="likeLower",e.IS_NULL="isNull",e.IS_NOT_NULL="isNotNull",e.IN="in"}(c||(c={})),function(e){e.ASC="asc",e.DESC="desc"}(l||(l={}));const d=Symbol("query-builder-type");class h{constructor(e={}){this.options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8},this[u]="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&&d in e&&"query-builder"===e[d]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:c.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:c.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:c.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:c.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:c.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:c.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:c.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:c.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:c.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:c.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:c.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:c.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:c.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:c.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=l.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,l.ASC)}orderByDesc(e){return this.orderBy(e,l.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 c.IS_NULL:t[`${e.field}:isNull`]=1;break;case c.IS_NOT_NULL:t[`${e.field}:notNull`]=1;break;case c.IN:t[`${e.field}:in`]=Array.isArray(e.value)?e.value.join(","):e.value;break;case c.LIKE:t[`${e.field}:like`]=e.value;break;case c.LIKE_LOWER:t[`${e.field}:likeLower`]=e.value;break;case c.GREATER_THAN_OR_EQUAL:t[`${e.field}:gte`]=e.value;break;case c.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===l.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===c.GREATER_THAN_OR_EQUAL||e.operator===c.LESS_THAN_OR_EQUAL));if(r){const e=r.find(e=>e.operator===c.GREATER_THAN_OR_EQUAL),n=r.find(e=>e.operator===c.LESS_THAN_OR_EQUAL);e&&(t.startDate=e.value),n&&(t.endDate=n.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 h(e)}}u=d;const m=e=>"function"==typeof(null==e?void 0:e.passthrough);t.object({name:t.literal("ZodError"),issues:t.array(t.object({path:t.array(t.union([t.string(),t.number()])),message:t.string().optional(),code:t.nativeEnum(t.ZodIssueCode)}).catchall(t.any()))});const p=Symbol("ContractNoBody"),f=e=>"method"in e&&"path"in e,g=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,s,o,i,a;return f(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,m(i)?m(a)?i.merge(a):i:m(a)?a:Object.assign({},i,a)),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(s=r.validateResponseOnClient)&&void 0!==s?s:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(o=r.metadata)&&void 0!==o?o:{}}:r.metadata}]:[e,g(r,t)]})),y=Symbol("ContractPlainType"),A=()=>({router:(e,t)=>g(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>y,body:()=>y,type:()=>y,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>p}),v=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("&"):"",w=e=>e?Object.keys(e).flatMap(t=>E(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",E=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>E(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>E(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class b extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const I=async({route:e,path:t,method:r,headers:n,body:s,validateResponse:o,fetchOptions:i})=>{const a=await fetch(t,{...i,method:r,headers:n,body:s}),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!=o?o: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 n of t)r(e,n);else r(e,t)}),t},T=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),N=(e,t,r,n,s)=>{const o=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),i=((e,t=!1)=>{const r=t?v(e):w(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,s);return`${t}${o}${i}`},R=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const s=((e,t,r)=>{const{query:n,params:s,body:o,headers:i,extraHeaders:a,overrideClientOptions:c,fetchOptions:l,cache:u,next:d,...h}=r||{},m={...t,...c};return{path:N(n,m.baseUrl,s,e,!!m.jsonQuery),clientArgs:m,route:e,body:o,query:n,extraInputArgs:h,fetchOptions:{...u&&{cache:u},...d&&{next:d},...l},headers:{...a,...i}}})(e,t,n),o=await(e=>{const{path:t,clientArgs:r,route:n,body:s,query:o,extraInputArgs:i,headers:a,fetchOptions:c}=e,l=r.api||I,u=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),d={...u&&T(u),...T(a)};Object.keys(d).forEach(e=>{void 0===d[e]&&delete d[e]});let h={route:n,path:t,method:n.method,headers:d,body:void 0,rawBody:s,rawQuery:o,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?h={...h,contentType:"multipart/form-data",body:s instanceof FormData?s:C(s)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?h={...h,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...h.headers},body:"string"==typeof s?s:new URLSearchParams(s)}:null!=s&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(s)})),l({...h,...i})})(s);if(!t.throwOnUnknownStatus)return o;if(r.includes(o.status.toString()))return o;throw new b(o,r)}},S=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>f(r)?[e,R(r,t)]:[e,S(r,t)]));class F{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(/\/+$/,""):"",t=this.endpoint?this.endpoint.replace(/^\/+/,""):"",n={baseUrl:e?`${e}/${t}`:`https://gateway.temboplus.com/dashboard/${t}`,baseHeaders:{Authorization:`Bearer ${this.getToken()}`,"x-request-id":r()}};return S(this.contract,n)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(t,r){if(t.status===r)return t.body;if(400===t.status){const r=e.object({statusCode:e.number(),message:e.string(),error:e.string(),details:e.record(e.string()).optional()}).safeParse(t.body);if(r.success)throw new a(r.data);throw new a({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===t.status)throw new a({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===t.status)throw new a({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===t.status)throw new a({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new a({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}const D=e.object({page:e.number().int().positive(),limit:e.number().int().positive(),total:e.number().int().min(0),totalPages:e.number().int().min(0),hasNext:e.boolean(),hasPrev:e.boolean()}),P=e.object({balance:e.number(),availableBalance:e.number(),accountNumber:e.string(),accountName:e.string()}),O={pagination:D,transactionSummary:e.object({yesterday:e.number(),today:e.number(),thisMonth:e.number(),lastMonth:e.number()}),walletSummary:P};class L{constructor(e,t="TZS"){var r,s,o,i;this.currency=t,this.yesterday=null!==(r=n.from(e.yesterday,t))&&void 0!==r?r:n.from(0,t),this.today=null!==(s=n.from(e.today,t))&&void 0!==s?s:n.from(0,t),this.thisMonth=null!==(o=n.from(e.thisMonth,t))&&void 0!==o?o:n.from(0,t),this.lastMonth=null!==(i=n.from(e.lastMonth,t))&&void 0!==i?i:n.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 n.from(this.today.numericValue+this.yesterday.numericValue,this.currency)}static from(e,t="TZS"){return new L(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(!(n.isAmountJson(e.yesterday)&&n.isAmountJson(e.today)&&n.isAmountJson(e.thisMonth)&&n.isAmountJson(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=n.fromJson(e.yesterday),r=n.fromJson(e.today),s=n.fromJson(e.thisMonth),o=n.fromJson(e.lastMonth);if(!(t&&r&&s&&o))return void console.error("Failed to reconstruct Amount instances from JSON:",e);const i={yesterday:t.numericValue,today:r.numericValue,thisMonth:s.numericValue,lastMonth:o.numericValue};return new L(i,e.currency)}catch(e){return void console.error("Error creating TransactionSummary from JSON:",e)}}}class j{constructor(e){var t,r;let s="TZS";this.accountName=e.accountName,this.accountNumber=e.accountNumber,this.currency=s,this.availableBalance=null!==(t=n.from(e.availableBalance,s))&&void 0!==t?t:n.from(0,s),this.actualBalance=null!==(r=n.from(e.balance,s))&&void 0!==r?r:n.from(0,s)}hasSufficientBalance(e){return this.availableBalance.numericValue>=e}static from(e){return new j(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(!n.isAmountJson(e.availableBalance)||!n.isAmountJson(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const t=n.fromJson(e.availableBalance),r=n.fromJson(e.actualBalance);if(!t||!r)return void console.error("Failed to reconstruct Amount instances from JSON:",e);const s={accountName:e.accountName,accountNumber:e.accountNumber,availableBalance:t.numericValue,balance:r.numericValue};return new j(s)}catch(e){return void console.error("Error creating WalletInfo from JSON:",e)}}static createManyFromJson(e){return e.map(e=>j.fromJson(e)).filter(Boolean)}}const _={user:t.object({token:t.string(),identity:t.string(),name:t.string()}),loginRequest:t.object({type:t.string().default("password"),identity:t.string().email(),password:t.string()})},M=A().router({login:{method:"POST",path:"/auth/login",body:_.loginRequest,responses:{201:_.user,400:t.object({message:t.string().optional()}),401:t.object({message:t.string().optional()})},summary:"User login",description:"Authenticate user with email and password"}});class B{constructor(e){this.identity=e.identity,this.name=e.name}static from(e){return new B(e)}static fromJson(e){return B.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}}class x extends F{constructor(e){super("auth",M,e)}async login(e){const t={type:"password",identity:e.email,password:e.password},r=await this.client.login({body:t}),n=this.handleResponse(r,201),s=B.from(n);if(!s)throw new Error("Invalid user data received from server");return{user:s,token:n.token}}}var J,U;!function(e){e.PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",e.GENERIC_FAILURE="GENERIC_FAILURE",e.PAYMENT_REJECTED="PAYMENT_REJECTED",e.PENDING_ACK="PENDING_ACK"}(J||(J={})),function(e){e.AIRTEL="TZ-AIRTEL-C2B",e.TIGO="TZ-TIGO-C2B",e.HALOTEL="TZ-HALOTEL-C2B"}(U||(U={}));const $=t.nativeEnum(J),k=t.nativeEnum(U),q={collection:t.object({id:t.string().min(1),status:$,statusMessage:t.string(),accountNo:t.string().min(1),walletId:t.string(),transactionDate:t.string().datetime(),narration:t.string(),msisdn:t.string().min(1),channel:k,amount:t.number().min(0),serviceFee:t.string().optional(),postedAmount:t.string().optional(),reference:t.string(),partnerReference:t.string().nullable().optional(),transactionId:t.string().nullable().optional(),serviceFeeTransactionId:t.string().nullable().optional(),requestId:t.string().nullable().optional(),completedAt:t.string().datetime().nullable().optional(),createdAt:t.string().datetime(),updatedAt:t.string().datetime(),notes:t.string().optional(),currencyCode:t.string().default("TZS")}),collectionFilters:t.object({page:t.number().int().positive().default(1),limit:t.number().int().positive().max(100).default(20),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().datetime().optional(),endDate:t.string().datetime().optional(),msisdn:t.string().optional(),id:t.string().optional(),reference:t.string().optional(),accountNo:t.string().optional(),partnerReference:t.string().optional(),channel:k.optional(),status:$.optional(),minAmount:t.number().min(0).optional(),maxAmount:t.number().min(0).optional(),search:t.string().optional()}),collectionURLQueryParams:t.object({page:t.string().transform(e=>parseInt(e)||1).optional(),limit:t.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().optional(),endDate:t.string().optional(),msisdn:t.string().optional(),id:t.string().optional(),reference:t.string().optional(),accountNo:t.string().optional(),partnerReference:t.string().optional(),channel:t.string().refine(e=>Object.values(U).includes(e)).transform(e=>e).optional(),status:t.string().refine(e=>Object.values(J).includes(e)).transform(e=>e).optional(),minAmount:t.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.string().transform(e=>parseFloat(e)).optional(),search:t.string().optional()}),paymentStatus:$,paymentChannel:k},G=A().router({getCollections:{method:"GET",path:"/",query:t.object({}),responses:{200:t.object({results:t.array(q.collection),total:t.number()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"List collections",description:"Retrieve a paginated list of collections with optional filtering"},getCollection:{method:"GET",path:"/:id",pathParams:t.object({id:t.string()}),responses:{200:q.collection,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Get collection details",description:"Retrieve detailed information about a specific collection"},getSummary:{method:"GET",path:"/summary",responses:{200:t.object({yesterday:t.number(),today:t.number(),thisMonth:t.number(),lastMonth:t.number()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"Get collections summary",description:"Retrieve collection summary statistics for different time periods"},getWalletInfo:{method:"GET",path:"/balance",responses:{200:O.walletSummary,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"Get account balance",description:"Retrieve current account balance and summary information"}}),V={[J.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[J.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[J.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"},[J.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"}},H={[U.AIRTEL]:{networkOperator:"Airtel",serviceName:"Airtel Money",type:"mobile"},[U.TIGO]:{networkOperator:"Tigo",serviceName:"Tigo Pesa",type:"mobile"},[U.HALOTEL]:{networkOperator:"Halotel",serviceName:"HaloPesa",type:"mobile"}};class W{constructor(e){var t,r,o;let i="TZS";s.isCurrencyCode(e.currencyCode)&&(i=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=n.from(e.amount,i))&&void 0!==t?t:n.from(0,i),this.serviceFee=e.serviceFee?null!==(r=n.from(parseFloat(e.serviceFee),i))&&void 0!==r?r:n.from(0,i):void 0,this.postedAmount=e.postedAmount?null!==(o=n.from(parseFloat(e.postedAmount),i))&&void 0!==o?o:n.from(0,i):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===J.PENDING_ACK}isSuccessful(){return this.status===J.PAYMENT_ACCEPTED}isFailed(){return Object.entries(V).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.status)}getStatusInfo(){return V[this.status]}getChannelInfo(){return H[this.channel]}getProviderName(){return this.getChannelInfo().networkOperator}getServiceName(){return this.getChannelInfo().serviceName}isMobileCollection(){return e=this.channel,"mobile"===H[e].type;var e}isBankCollection(){return e=this.channel,"bank"===H[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 W(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=>W.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(!n.isAmountJson(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!n.isAmountJson(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!n.isAmountJson(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=n.fromJson(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let r,s;if(e.serviceFee){const t=n.fromJson(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);r=t.numericValue.toString()}if(e.postedAmount){const t=n.fromJson(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);s=t.numericValue.toString()}const o={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:r,postedAmount:s,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 W(o)}catch(e){return void console.error("Error creating Collection from JSON:",e)}}static createManyFromJson(e){return e.map(e=>W.fromJson(e)).filter(Boolean)}toJson(){var e,t,r,n;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!==(n=null===(r=this.completedAt)||void 0===r?void 0:r.toISOString())&&void 0!==n?n:null,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),notes:this.notes,currencyCode:this.currencyCode}}}class K extends h{static create(){return new K}static fromFilters(e){return(new K).applyFilters(e)}static fromUrlParams(e){try{const t=q.collectionURLQueryParams.parse(e),r=q.collectionFilters.parse(t);return K.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 K.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return K.fromSearchParams(t)}static from(e){try{return null==e?new K:h.is(e)?new K(e.options):e instanceof URLSearchParams?K.fromSearchParams(e):this.isStringRecord(e)?K.fromUrlParams(e):K.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(J.PENDING_ACK)}whereSuccessful(){return this.whereStatus(J.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("status",[J.PAYMENT_REJECTED,J.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(U).includes(e)}isValidStatus(e){return Object.values(J).includes(e)}}class Q extends F{constructor(e){super("collection",G,e)}async getCollections(e){try{const t=K.from(e),r=t.build(),n=await this.client.getCollections({query:r}),s=this.handleResponse(n,200),o=t.toFilters(),i={page:o.page,limit:o.limit,total:s.total,totalPages:s.total>0?Math.ceil(s.total/o.limit):0,hasNext:o.page*o.limit<s.total,hasPrev:o.page>1};return{collections:W.createMany(s.results),pagination:i}}catch(e){throw new Error(`Failed to fetch collections: ${e instanceof Error?e.message:"Unknown error"}`)}}async getCollectionsFromRequest(e){const t=K.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),n=W.from(r);if(!n)throw new Error("Invalid collection data received from server");return n}async getCollectionStats(){const e=await this.client.getSummary(),t=this.handleResponse(e,200),r=L.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=j.from(t);if(!r)throw new Error("Invalid wallet info received from server");return r}}var Y,Z,X;!function(e){e.PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",e.GENERIC_FAILURE="GENERIC_FAILURE",e.WALLET_DEBITED="WALLET_DEBITED",e.PAYMENT_REJECTED="PAYMENT_REJECTED",e.PENDING="PENDING",e.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",e.PENDING_ACK="PENDING_ACK",e.REVERSED="REVERSED",e.INVALID_SERVICE="INVALID_SERVICE",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.THIRDPARTY_FAILED="THIRDPARTY_FAILED"}(Y||(Y={})),function(e){e.AIRTEL="TZ-AIRTEL-B2C",e.VODACOM="TZ-VODACOM-B2C",e.TIGO="TZ-TIGO-B2C",e.HALOTEL="TZ-HALOTEL-B2C"}(Z||(Z={})),function(e){e.BANK="TZ-BANK-B2C"}(X||(X={}));const z=t.nativeEnum(Y),ee=t.nativeEnum(Z),te=t.nativeEnum(X),re=t.union([ee,te]),ne={payout:t.object({id:t.string().min(1),statusCode:t.string(),statusCodeText:z,statusDescription:t.string(),countryCode:t.string(),serviceCode:re,amount:t.number().min(0),serviceFee:t.string().optional(),postedAmount:t.string().optional(),walletId:t.string().optional(),msisdn:t.string().min(1),narration:t.string(),currencyCode:t.string(),recipientNames:t.string().optional(),transactionRef:t.string(),transactionDate:t.string().datetime(),externalId:t.string().nullable().optional(),cbaReferenceNo:t.string().optional(),beepTransactionId:t.string().optional(),receiptNumber:t.string().optional(),createdAt:t.string().datetime(),reversedTransactionId:t.string().nullable().optional(),transactionId:t.string(),serviceFeeTransactionId:t.string().optional(),isReconciled:t.number().optional(),requestId:t.string().optional(),notes:t.string().optional(),updatedAt:t.string().datetime().optional()}),payoutFilters:t.object({page:t.number().int().positive().default(1),limit:t.number().int().positive().max(100).default(20),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().datetime().optional(),endDate:t.string().datetime().optional(),msisdn:t.string().optional(),id:t.string().optional(),ref:t.string().optional(),channel:re.optional(),status:z.optional(),minAmount:t.number().min(0).optional(),maxAmount:t.number().min(0).optional(),search:t.string().optional()}),payoutURLQueryParams:t.object({page:t.string().transform(e=>parseInt(e)||1).optional(),limit:t.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().optional(),endDate:t.string().optional(),msisdn:t.string().optional(),id:t.string().optional(),ref:t.string().optional(),channel:t.string().refine(e=>Object.values(Z).includes(e)||e===X.BANK).transform(e=>e).optional(),status:t.string().refine(e=>Object.values(Y).includes(e)).transform(e=>e).optional(),minAmount:t.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.string().transform(e=>parseFloat(e)).optional(),search:t.string().optional()}),payoutStatus:z,payoutChannel:re,mobileChannel:ee,bankChannel:te,walletSummary:t.object({balance:t.number(),currency:t.string(),lastUpdated:t.string().datetime()}),transactionSummary:t.object({yesterday:t.number(),today:t.number(),thisMonth:t.number(),lastMonth:t.number()}),pagination:t.object({page:t.number(),limit:t.number(),total:t.number(),totalPages:t.number(),hasNext:t.boolean(),hasPrev:t.boolean()})},se=A().router({getPayouts:{method:"GET",path:"",query:ne.payoutURLQueryParams,responses:{200:t.object({results:t.array(ne.payout),total:t.number()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"List payouts",description:"Retrieve a paginated list of payouts with optional filtering"},getPayout:{method:"GET",path:"/:id",pathParams:t.object({id:t.string()}),responses:{200:ne.payout,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Get payout details",description:"Retrieve detailed information about a specific payout"},getPayoutSummary:{method:"GET",path:"/summary",responses:{200:O.transactionSummary,401:t.object({message:t.string().optional()}),403:t.object({message:t.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:O.walletSummary,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"Get account balance",description:"Retrieve current account balance and status information"}}),oe={[Y.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[Y.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[Y.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[Y.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"},[Y.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[Y.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"},[Y.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"},[Y.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"},[Y.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"},[Y.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"},[Y.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"}},ie={[Z.AIRTEL]:{networkOperator:"Airtel",serviceName:"Airtel Money"},[Z.VODACOM]:{networkOperator:"Vodacom",serviceName:"M-Pesa"},[Z.TIGO]:{networkOperator:"Tigo",serviceName:"Tigo Pesa"},[Z.HALOTEL]:{networkOperator:"Halotel",serviceName:"HaloPesa"}};function ae(e){return Object.values(Z).includes(e)}function ce(e){return e===X.BANK}function le(){return Object.entries(oe).filter(([e,t])=>"failed"===t.category).map(([e])=>e)}class ue{constructor(e){var t,r;let o="TZS";s.isCurrencyCode(e.currencyCode)&&(o=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=null!==(t=n.from(e.amount,o))&&void 0!==t?t:n.from(0,o),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!==(r=n.from(e.serviceFee,o))&&void 0!==r?r:n.from(0,o),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?n.from(parseFloat(e.postedAmount),o):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[Y.PENDING,Y.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===Y.PAYMENT_ACCEPTED}isFailed(){return le().includes(this.statusCodeText)}getStatusInfo(){return oe[this.statusCodeText]}getChannelInfo(){if(ae(this.serviceCode))return ie[this.serviceCode];if(ce(this.serviceCode)){const e=this.msisdn.split(":")[0];if(e&&o.validateSwiftCodeForAnyCountry(e)){const t=o.getCountryFromSwiftCode(e);if(t)try{return i.from(e,t)}catch(t){console.warn(`Failed to create Bank instance for SWIFT code ${e}:`,t)}}if(this.swiftCode&&o.validateSwiftCodeForAnyCountry(this.swiftCode)){const e=o.getCountryFromSwiftCode(this.swiftCode);if(e)try{return i.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 ae(this.serviceCode)&&e?e.networkOperator:i.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 ue(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=>ue.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(!n.isAmountJson(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!n.isAmountJson(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!n.isAmountJson(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=n.fromJson(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let r,s;if(e.serviceFee){const t=n.fromJson(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);r=t.numericValue}if(e.postedAmount){const t=n.fromJson(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);s=t.numericValue.toString()}const o={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:r,notes:e.notes,swiftCode:e.swiftCode,createdAt:e.createdAt,updatedAt:e.updatedAt,statusCode:e.statusCode,countryCode:e.countryCode,postedAmount:s,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 ue(o)}catch(e){return void console.error("Error creating Payout from JSON:",e)}}static createManyFromJson(e){return e.map(e=>ue.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 de extends h{static create(){return new de}static fromFilters(e){return(new de).applyFilters(e)}static fromUrlParams(e){try{const t=ne.payoutURLQueryParams.parse(e),r=ne.payoutFilters.parse(t);return de.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 de.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return de.fromSearchParams(t)}static from(e){return null==e?new de:h.is(e)?new de(e.options):e instanceof URLSearchParams?de.fromSearchParams(e):this.isStringRecord(e)?de.fromUrlParams(e):de.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",[Y.PENDING,Y.PENDING_ACK])}whereSuccessful(){return this.whereStatus(Y.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[Y.PAYMENT_REJECTED,Y.GENERIC_FAILURE,Y.AMOUNT_EXCEED_MAXIMUM,Y.INVALID_SERVICE,Y.INSUFFICIENT_BALANCE,Y.THIRDPARTY_FAILED,Y.WALLET_DEBITED,Y.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(Z))}whereBank(){return this.whereChannel(X.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(Z).includes(e)||e===X.BANK}isValidStatus(e){return Object.values(Y).includes(e)}}class he extends F{constructor(e){super("payout",se,e)}async getPayouts(e){try{const t=de.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),s=this.handleResponse(n,200),o=t.toFilters(),i={page:o.page,limit:o.limit,total:s.total,totalPages:s.total>0?Math.ceil(s.total/o.limit):0,hasNext:o.page*o.limit<s.total,hasPrev:o.page>1};return{payouts:ue.createMany(s.results),pagination:i}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=de.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),n=ue.from(r);if(!n)throw new Error("Invalid payout data received from server");return n}async getPayoutStats(){const e=await this.client.getPayoutSummary(),t=this.handleResponse(e,200),r=L.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=j.from(t);if(!r)throw new Error("Invalid wallet info received from server");return r}}export{a as APIError,_ as AuthDTOSchemas,x as AuthRepository,X as BANK_PAYOUT_CHANNEL,F as BaseRepository,H as CHANNEL_INFO,U as COLLECTION_CHANNEL,J as COLLECTION_STATUS,V as COLLECTION_STATUS_INFO,W as Collection,q as CollectionDTOSchemas,K as CollectionQuery,Q as CollectionRepository,O as CommonSchemas,c as FilterOperator,ie as MOBILE_CHANNEL_INFO,Z as MOBILE_PAYOUT_CHANNEL,Y as PAYOUT_STATUS,oe as PAYOUT_STATUS_INFO,ue as Payout,ne as PayoutDTOSchemas,de as PayoutQuery,he as PayoutRepository,d as QUERY_BUILDER_TYPE,h as QueryBuilder,l as SortDirection,L as TransactionSummary,B as User,j as WalletInfo,M as authContract,G as collectionContract,le as getFailedStatuses,ce as isBankChannel,ae as isMobileChannel,se as payoutContract};
1
+ import e,{z as t}from"zod";import{v4 as r}from"uuid";import{Amount as n,CurrencyValidation as o,BankValidation as s,Bank as a}from"@temboplus/frontend-core";class i 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 i.schema.safeParse(e).success}static unknown(e){return new i({message:null!=e?e:"An unknown error occurred",statusCode:502})}static get schema(){return t.object({message:t.string(),statusCode:t.number().int(),error:t.string().optional(),details:t.object({}).optional()})}}var c,u,l;!function(e){e.EQUALS="eq",e.NOT_EQUALS="neq",e.LESS_THAN="lt",e.LESS_THAN_OR_EQUAL="lte",e.GREATER_THAN="gt",e.GREATER_THAN_OR_EQUAL="gte",e.LIKE="like",e.LIKE_LOWER="likeLower",e.IS_NULL="isNull",e.IS_NOT_NULL="isNotNull",e.IN="in"}(c||(c={})),function(e){e.ASC="asc",e.DESC="desc"}(u||(u={}));const d=Symbol("query-builder-type");class m{constructor(e={}){this.options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8},this[l]="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&&d in e&&"query-builder"===e[d]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:c.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:c.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:c.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:c.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:c.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:c.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:c.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:c.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:c.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:c.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:c.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:c.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:c.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:c.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=u.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,u.ASC)}orderByDesc(e){return this.orderBy(e,u.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 c.IS_NULL:t[`${e.field}:isNull`]=1;break;case c.IS_NOT_NULL:t[`${e.field}:notNull`]=1;break;case c.IN:t[`${e.field}:in`]=Array.isArray(e.value)?e.value.join(","):e.value;break;case c.LIKE:t[`${e.field}:like`]=e.value;break;case c.LIKE_LOWER:t[`${e.field}:likeLower`]=e.value;break;case c.GREATER_THAN_OR_EQUAL:t[`${e.field}:gte`]=e.value;break;case c.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===u.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===c.GREATER_THAN_OR_EQUAL||e.operator===c.LESS_THAN_OR_EQUAL));if(r){const e=r.find(e=>e.operator===c.GREATER_THAN_OR_EQUAL),n=r.find(e=>e.operator===c.LESS_THAN_OR_EQUAL);e&&(t.startDate=e.value),n&&(t.endDate=n.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 m(e)}}l=d;const h=e=>"function"==typeof(null==e?void 0:e.passthrough);t.object({name:t.literal("ZodError"),issues:t.array(t.object({path:t.array(t.union([t.string(),t.number()])),message:t.string().optional(),code:t.nativeEnum(t.ZodIssueCode)}).catchall(t.any()))});const p=Symbol("ContractNoBody"),f=e=>"method"in e&&"path"in e,g=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,o,s,a,i;return f(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,h(a)?h(i)?a.merge(i):a:h(i)?i:Object.assign({},a,i)),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(o=r.validateResponseOnClient)&&void 0!==o?o: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,g(r,t)]})),y=Symbol("ContractPlainType"),v=()=>({router:(e,t)=>g(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>y,body:()=>y,type:()=>y,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>p}),A=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("&"):"",b=e=>e?Object.keys(e).flatMap(t=>w(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",w=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>w(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>w(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class E extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const C=async({route:e,path:t,method:r,headers:n,body:o,validateResponse:s,fetchOptions:a})=>{const i=await fetch(t,{...a,method:r,headers:n,body:o}),c=i.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t={status:i.status,body:await i.json(),headers:i.headers},r=e.responses[t.status];return(null!=s?s:e.validateResponseOnClient)&&"function"==typeof(null==(u=r)?void 0:u.safeParse)?{...t,body:r.parse(t.body)}:t}var u;return(null==c?void 0:c.includes("text/"))?{status:i.status,body:await i.text(),headers:i.headers}:{status:i.status,body:await i.blob(),headers:i.headers}},I=e=>{const t=new FormData,r=(e,r)=>{r instanceof File?t.append(e,r):t.append(e,JSON.stringify(r))};return Object.entries(e).forEach(([e,t])=>{if(Array.isArray(t))for(const n of t)r(e,n);else r(e,t)}),t},N=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),T=(e,t,r,n,o)=>{const s=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),a=((e,t=!1)=>{const r=t?A(e):b(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,o);return`${t}${s}${a}`},S=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const o=((e,t,r)=>{const{query:n,params:o,body:s,headers:a,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:l,next:d,...m}=r||{},h={...t,...c};return{path:T(n,h.baseUrl,o,e,!!h.jsonQuery),clientArgs:h,route:e,body:s,query:n,extraInputArgs:m,fetchOptions:{...l&&{cache:l},...d&&{next:d},...u},headers:{...i,...a}}})(e,t,n),s=await(e=>{const{path:t,clientArgs:r,route:n,body:o,query:s,extraInputArgs:a,headers:i,fetchOptions:c}=e,u=r.api||C,l=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),d={...l&&N(l),...N(i)};Object.keys(d).forEach(e=>{void 0===d[e]&&delete d[e]});let m={route:n,path:t,method:n.method,headers:d,body:void 0,rawBody:o,rawQuery:s,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?m={...m,contentType:"multipart/form-data",body:o instanceof FormData?o:I(o)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?m={...m,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...m.headers},body:"string"==typeof o?o:new URLSearchParams(o)}:null!=o&&(m={...m,contentType:"application/json",headers:{"content-type":"application/json",...m.headers},body:JSON.stringify(o)})),u({...m,...a})})(o);if(!t.throwOnUnknownStatus)return s;if(r.includes(s.status.toString()))return s;throw new E(s,r)}},D=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>f(r)?[e,S(r,t)]:[e,D(r,t)]));class R{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(){return this.getClientWithHeaders()}getClientWithHeaders(e){const t=this.root?this.root.replace(/\/+$/,""):"",n=this.endpoint?this.endpoint.replace(/^\/+/,""):"",o=t?`${t}/${n}`:`https://gateway.temboplus.com/dashboard/${n}`,s={Authorization:`Bearer ${this.getToken()}`,"x-request-id":r()},a={baseUrl:o,baseHeaders:e?Object.assign(Object.assign({},s),e):s};return D(this.contract,a)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(t,r){if(t.status===r)return t.body;if(400===t.status){const r=e.object({statusCode:e.number(),message:e.string(),error:e.string(),details:e.record(e.string()).optional()}).safeParse(t.body);if(r.success)throw new i(r.data);throw new i({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===t.status)throw new i({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===t.status)throw new i({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===t.status)throw new i({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new i({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}const O=e.object({page:e.number().int().positive(),limit:e.number().int().positive(),total:e.number().int().min(0),totalPages:e.number().int().min(0),hasNext:e.boolean(),hasPrev:e.boolean()}),F=e.object({balance:e.number(),availableBalance:e.number(),accountNumber:e.string(),accountName:e.string()}),P=e.object({yesterday:e.number(),today:e.number(),thisMonth:e.number(),lastMonth:e.number()});const j=e.string().nullish().transform(e=>{if(!e||""===e.trim())return null;try{return function(e){if(!e||""===e.trim())throw new Error("Date string cannot be empty");const[t,r]=e.trim().split(" ");if(!t||!r)throw new Error("Invalid date format. Expected 'YYYY-MM-DD HH:mm:ss'");const n=new Date(`${t}T${r}.000Z`);return new Date(n.getTime()-108e5).toISOString()}(e)}catch(e){throw new Error(`Failed to convert EAT date to UTC: ${e instanceof Error?e.message:"Unknown error"}`)}}),L=e.object({accountNo:e.string().nullish(),debitOrCredit:e.enum(["CR","DR"],{errorMap:()=>({message:"Transaction type must be either 'CR' (Credit) or 'DR' (Debit)"})}),tranRefNo:e.string().nullish(),narration:e.string().nullish(),txnDate:j,valueDate:j,amountCredited:e.union([e.number().min(0,"Credited amount cannot be negative"),e.string().transform(e=>{if(""===e.trim())return 0;const t=parseFloat(e);if(isNaN(t))throw new Error("Invalid credited amount format");return t})],{errorMap:()=>({message:"Credited amount must be a number or numeric string"})}),amountDebited:e.union([e.number().min(0,"Debited amount cannot be negative"),e.string().transform(e=>{if(""===e.trim())return 0;const t=parseFloat(e);if(isNaN(t))throw new Error("Invalid debited amount format");return t})],{errorMap:()=>({message:"Debited amount must be a number or numeric string"})}),balance:e.number({required_error:"Balance is required",invalid_type_error:"Balance must be a number"})}),M={pagination:O,transactionSummary:P,walletSummary:F,statementEntry:L};class x{constructor(e,t="TZS"){var r,o,s,a;this.currency=t,this.yesterday=null!==(r=n.from(e.yesterday,t))&&void 0!==r?r:n.from(0,t),this.today=null!==(o=n.from(e.today,t))&&void 0!==o?o:n.from(0,t),this.thisMonth=null!==(s=n.from(e.thisMonth,t))&&void 0!==s?s:n.from(0,t),this.lastMonth=null!==(a=n.from(e.lastMonth,t))&&void 0!==a?a:n.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 n.from(this.today.numericValue+this.yesterday.numericValue,this.currency)}static from(e,t="TZS"){return new x(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(!(n.isAmountJson(e.yesterday)&&n.isAmountJson(e.today)&&n.isAmountJson(e.thisMonth)&&n.isAmountJson(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=n.fromJson(e.yesterday),r=n.fromJson(e.today),o=n.fromJson(e.thisMonth),s=n.fromJson(e.lastMonth);if(!(t&&r&&o&&s))return void console.error("Failed to reconstruct Amount instances from JSON:",e);const a={yesterday:t.numericValue,today:r.numericValue,thisMonth:o.numericValue,lastMonth:s.numericValue};return new x(a,e.currency)}catch(e){return void console.error("Error creating TransactionSummary from JSON:",e)}}}class _{constructor(e){var t,r;let o="TZS";this.accountName=e.accountName,this.accountNumber=e.accountNumber,this.currency=o,this.availableBalance=null!==(t=n.from(e.availableBalance,o))&&void 0!==t?t:n.from(0,o),this.actualBalance=null!==(r=n.from(e.balance,o))&&void 0!==r?r:n.from(0,o)}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(!n.isAmountJson(e.availableBalance)||!n.isAmountJson(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const t=n.fromJson(e.availableBalance),r=n.fromJson(e.actualBalance);if(!t||!r)return void console.error("Failed to reconstruct Amount instances from JSON:",e);const o={accountName:e.accountName,accountNumber:e.accountNumber,availableBalance:t.numericValue,balance:r.numericValue};return new _(o)}catch(e){return void console.error("Error creating WalletInfo from JSON:",e)}}static createManyFromJson(e){return e.map(e=>_.fromJson(e)).filter(Boolean)}}class B{constructor(e,t="TZS"){var r,s,a;let i="TZS";o.isCurrencyCode(t)&&(i=t),this.accountNo=e.accountNo,this.debitOrCredit=e.debitOrCredit,this.tranRefNo=e.tranRefNo,this.narration=e.narration,this.txnDate=e.txnDate?new Date(e.txnDate):null,this.valueDate=e.valueDate?new Date(e.valueDate):null,this.currency=i;const c=this.parseAmountValue(e.amountCredited);this.amountCredited=c>0?null!==(r=n.from(c,i))&&void 0!==r?r:n.from(0,i):null;const u=this.parseAmountValue(e.amountDebited);this.amountDebited=u>0?null!==(s=n.from(u,i))&&void 0!==s?s:n.from(0,i):null,this.balance=null!==(a=n.from(e.balance,i))&&void 0!==a?a:n.from(0,i)}parseAmountValue(e){if("number"==typeof e)return e;if("string"==typeof e&&""!==e.trim()){const t=parseFloat(e);return isNaN(t)?0:t}return 0}isCredit(){return"CR"===this.debitOrCredit}isDebit(){return"DR"===this.debitOrCredit}getTransactionAmount(){return this.amountCredited||this.amountDebited}getTransactionValue(){const e=this.getTransactionAmount();return e?e.numericValue:0}static from(e,t="TZS"){console.log(M.statementEntry.safeParse(e).error);try{return!1===M.statementEntry.safeParse(e).success?void console.error("Missing required StatementEntry fields:",e):new B(e,t)}catch(e){return void console.error("Error creating StatementEntry:",e)}}static createMany(e,t="TZS"){return e.map(e=>B.from(e,t)).filter(Boolean)}toJson(){var e,t,r,n,o,s;return{accountNo:this.accountNo,debitOrCredit:this.debitOrCredit,tranRefNo:this.tranRefNo,narration:this.narration,txnDate:null===(e=this.txnDate)||void 0===e?void 0:e.toISOString(),valueDate:null===(t=this.valueDate)||void 0===t?void 0:t.toISOString(),amountCredited:null!==(n=null===(r=this.amountCredited)||void 0===r?void 0:r.toJson())&&void 0!==n?n:null,amountDebited:null!==(s=null===(o=this.amountDebited)||void 0===o?void 0:o.toJson())&&void 0!==s?s:null,balance:this.balance.toJson(),currency:this.currency}}static fromJson(e){try{if(!(null==e?void 0:e.accountNo)||!(null==e?void 0:e.tranRefNo)||!(null==e?void 0:e.balance))return void console.error("Missing required StatementEntry JSON fields:",e);if(!n.isAmountJson(e.balance))return void console.error("Invalid balance AmountJson structure:",e.balance);if(e.amountCredited&&!n.isAmountJson(e.amountCredited))return void console.error("Invalid amountCredited AmountJson structure:",e.amountCredited);if(e.amountDebited&&!n.isAmountJson(e.amountDebited))return void console.error("Invalid amountDebited AmountJson structure:",e.amountDebited);const t=n.fromJson(e.balance);if(!t)return void console.error("Failed to reconstruct balance Amount from JSON:",e.balance);let r=0;if(e.amountCredited){const t=n.fromJson(e.amountCredited);if(!t)return void console.error("Failed to reconstruct amountCredited Amount from JSON:",e.amountCredited);r=t.numericValue}let o=0;if(e.amountDebited){const t=n.fromJson(e.amountDebited);if(!t)return void console.error("Failed to reconstruct amountDebited Amount from JSON:",e.amountDebited);o=t.numericValue}const s={accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:e.narration,txnDate:e.txnDate?e.txnDate:null,valueDate:e.valueDate?e.valueDate:null,amountCredited:r,amountDebited:o,balance:t.numericValue};return new B(s,e.currency)}catch(e){return void console.error("Error creating StatementEntry from JSON:",e)}}static createManyFromJson(e){return e.map(e=>B.fromJson(e)).filter(Boolean)}static getTotalCredits(e){var t;const r=e.length>0?e[0].currency:"TZS",o=e.reduce((e,t)=>t.isCredit()&&t.amountCredited?e+t.amountCredited.numericValue:e,0);return null!==(t=n.from(o,r))&&void 0!==t?t:n.from(0,r)}static getTotalDebits(e){var t;const r=e.length>0?e[0].currency:"TZS",o=e.reduce((e,t)=>t.isDebit()&&t.amountDebited?e+t.amountDebited.numericValue:e,0);return null!==(t=n.from(o,r))&&void 0!==t?t:n.from(0,r)}static getNetChange(e){var t;const r=e.length>0?e[0].currency:"TZS",o=B.getTotalCredits(e).numericValue,s=B.getTotalDebits(e).numericValue;return null!==(t=n.from(o-s,r))&&void 0!==t?t:n.from(0,r)}}const J={user:t.object({token:t.string(),identity:t.string(),name:t.string()}),loginRequest:t.object({type:t.string().default("password"),identity:t.string().email(),password:t.string()})},U=v().router({login:{method:"POST",path:"/auth/login",body:J.loginRequest,responses:{201:J.user,400:t.object({message:t.string().optional()}),401:t.object({message:t.string().optional()})},summary:"User login",description:"Authenticate user with email and password"}});class k{constructor(e){this.identity=e.identity,this.name=e.name}static from(e){return new k(e)}static fromJson(e){return k.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}}class $ extends R{constructor(e){super("auth",U,e)}async login(e){const t={type:"password",identity:e.email,password:e.password},r=await this.client.login({body:t}),n=this.handleResponse(r,201),o=k.from(n);if(!o)throw new Error("Invalid user data received from server");return{user:o,token:n.token}}}var q,G;!function(e){e.PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",e.GENERIC_FAILURE="GENERIC_FAILURE",e.PAYMENT_REJECTED="PAYMENT_REJECTED",e.PENDING_ACK="PENDING_ACK"}(q||(q={})),function(e){e.AIRTEL="TZ-AIRTEL-C2B",e.TIGO="TZ-TIGO-C2B",e.HALOTEL="TZ-HALOTEL-C2B"}(G||(G={}));const V=t.nativeEnum(q),H=t.nativeEnum(G),W={collection:t.object({id:t.string().min(1),status:V,statusMessage:t.string(),accountNo:t.string().min(1),walletId:t.string(),transactionDate:t.string().datetime(),narration:t.string(),msisdn:t.string().min(1),channel:H,amount:t.number().min(0),serviceFee:t.string().optional(),postedAmount:t.string().optional(),reference:t.string(),partnerReference:t.string().nullable().optional(),transactionId:t.string().nullable().optional(),serviceFeeTransactionId:t.string().nullable().optional(),requestId:t.string().nullable().optional(),completedAt:t.string().datetime().nullable().optional(),createdAt:t.string().datetime(),updatedAt:t.string().datetime(),notes:t.string().optional(),currencyCode:t.string().default("TZS")}),collectionFilters:t.object({page:t.number().int().positive().default(1),limit:t.number().int().positive().max(100).default(20),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().datetime().optional(),endDate:t.string().datetime().optional(),msisdn:t.string().optional(),id:t.string().optional(),reference:t.string().optional(),accountNo:t.string().optional(),partnerReference:t.string().optional(),channel:H.optional(),status:V.optional(),minAmount:t.number().min(0).optional(),maxAmount:t.number().min(0).optional(),search:t.string().optional()}),collectionURLQueryParams:t.object({page:t.string().transform(e=>parseInt(e)||1).optional(),limit:t.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().optional(),endDate:t.string().optional(),msisdn:t.string().optional(),id:t.string().optional(),reference:t.string().optional(),accountNo:t.string().optional(),partnerReference:t.string().optional(),channel:t.string().refine(e=>Object.values(G).includes(e)).transform(e=>e).optional(),status:t.string().refine(e=>Object.values(q).includes(e)).transform(e=>e).optional(),minAmount:t.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.string().transform(e=>parseFloat(e)).optional(),search:t.string().optional()}),paymentStatus:V,paymentChannel:H},Y=v().router({getCollections:{method:"GET",path:"/",query:t.object({}),responses:{200:t.object({results:t.array(W.collection),total:t.number()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"List collections",description:"Retrieve a paginated list of collections with optional filtering"},getCollection:{method:"GET",path:"/:id",pathParams:t.object({id:t.string()}),responses:{200:W.collection,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Get collection details",description:"Retrieve detailed information about a specific collection"},getSummary:{method:"GET",path:"/summary",responses:{200:t.object({yesterday:t.number(),today:t.number(),thisMonth:t.number(),lastMonth:t.number()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"Get collections summary",description:"Retrieve collection summary statistics for different time periods"},getWalletInfo:{method:"GET",path:"/balance",responses:{200:M.walletSummary,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"Get account balance",description:"Retrieve current account balance and summary information"},getStatement:{method:"POST",path:"/collection-statement",body:t.object({startDate:t.string(),endDate:t.string()}),responses:{200:M.statementEntry,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"Get account statement"}}),Z={[q.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[q.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[q.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"},[q.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={[G.AIRTEL]:{networkOperator:"Airtel",serviceName:"Airtel Money",type:"mobile"},[G.TIGO]:{networkOperator:"Tigo",serviceName:"Tigo Pesa",type:"mobile"},[G.HALOTEL]:{networkOperator:"Halotel",serviceName:"HaloPesa",type:"mobile"}};class Q{constructor(e){var t,r,s;let a="TZS";o.isCurrencyCode(e.currencyCode)&&(a=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=n.from(e.amount,a))&&void 0!==t?t:n.from(0,a),this.serviceFee=e.serviceFee?null!==(r=n.from(parseFloat(e.serviceFee),a))&&void 0!==r?r:n.from(0,a):void 0,this.postedAmount=e.postedAmount?null!==(s=n.from(parseFloat(e.postedAmount),a))&&void 0!==s?s:n.from(0,a):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===q.PENDING_ACK}isSuccessful(){return this.status===q.PAYMENT_ACCEPTED}isFailed(){return Object.entries(Z).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.status)}getStatusInfo(){return Z[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 Q(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=>Q.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(!n.isAmountJson(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!n.isAmountJson(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!n.isAmountJson(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=n.fromJson(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let r,o;if(e.serviceFee){const t=n.fromJson(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);r=t.numericValue.toString()}if(e.postedAmount){const t=n.fromJson(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);o=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:r,postedAmount:o,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 Q(s)}catch(e){return void console.error("Error creating Collection from JSON:",e)}}static createManyFromJson(e){return e.map(e=>Q.fromJson(e)).filter(Boolean)}toJson(){var e,t,r,n;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!==(n=null===(r=this.completedAt)||void 0===r?void 0:r.toISOString())&&void 0!==n?n:null,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),notes:this.notes,currencyCode:this.currencyCode}}}class X extends m{static create(){return new X}static fromFilters(e){return(new X).applyFilters(e)}static fromUrlParams(e){try{const t=W.collectionURLQueryParams.parse(e),r=W.collectionFilters.parse(t);return X.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 X.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return X.fromSearchParams(t)}static from(e){try{return null==e?new X:m.is(e)?new X(e.options):e instanceof URLSearchParams?X.fromSearchParams(e):this.isStringRecord(e)?X.fromUrlParams(e):X.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(q.PENDING_ACK)}whereSuccessful(){return this.whereStatus(q.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("status",[q.PAYMENT_REJECTED,q.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(G).includes(e)}isValidStatus(e){return Object.values(q).includes(e)}}class z extends R{constructor(e){super("collection",Y,e)}async getCollections(e){try{const t=X.from(e),r=t.build(),n=await this.client.getCollections({query:r}),o=this.handleResponse(n,200),s=t.toFilters(),a={page:s.page,limit:s.limit,total:o.total,totalPages:o.total>0?Math.ceil(o.total/s.limit):0,hasNext:s.page*s.limit<o.total,hasPrev:s.page>1};return{collections:Q.createMany(o.results),pagination:a}}catch(e){throw new Error(`Failed to fetch collections: ${e instanceof Error?e.message:"Unknown error"}`)}}async getCollectionsFromRequest(e){const t=X.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),n=Q.from(r);if(!n)throw new Error("Invalid collection data received from server");return n}async getCollectionStats(){const e=await this.client.getSummary(),t=this.handleResponse(e,200),r=x.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}async getCollectionStatement(e){return(new ee).getCollectionStatement(e)}}class ee extends R{constructor(e){super("wallet",Y,{token:null==e?void 0:e.token,root:"https://api.temboplus.com/tembo/v1"})}async getCollectionStatement(e){const t=this.getClientWithHeaders({"x-account-id":"b1130ccb2373b1230a1f37b3","x-secret-key":"9OChe7Rf3pTOMMwMgYMrw//ugnLZsWmJyD6jo1vFO9Y="}),r=await t.getStatement({body:{startDate:e.startDate.toISOString(),endDate:e.endDate.toISOString()}}),n=this.handleResponse(r,200);if(!n)throw new Error("Invalid statement data received from server");return B.createMany(n)}}var te,re,ne;!function(e){e.PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",e.GENERIC_FAILURE="GENERIC_FAILURE",e.WALLET_DEBITED="WALLET_DEBITED",e.PAYMENT_REJECTED="PAYMENT_REJECTED",e.PENDING="PENDING",e.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",e.PENDING_ACK="PENDING_ACK",e.REVERSED="REVERSED",e.INVALID_SERVICE="INVALID_SERVICE",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.THIRDPARTY_FAILED="THIRDPARTY_FAILED"}(te||(te={})),function(e){e.AIRTEL="TZ-AIRTEL-B2C",e.VODACOM="TZ-VODACOM-B2C",e.TIGO="TZ-TIGO-B2C",e.HALOTEL="TZ-HALOTEL-B2C"}(re||(re={})),function(e){e.BANK="TZ-BANK-B2C"}(ne||(ne={}));const oe=t.nativeEnum(te),se=t.nativeEnum(re),ae=t.nativeEnum(ne),ie=t.union([se,ae]),ce={payout:t.object({id:t.string().min(1),statusCode:t.string(),statusCodeText:oe,statusDescription:t.string(),countryCode:t.string(),serviceCode:ie,amount:t.number().min(0),serviceFee:t.string().optional(),postedAmount:t.string().optional(),walletId:t.string().optional(),msisdn:t.string().min(1),narration:t.string(),currencyCode:t.string(),recipientNames:t.string().optional(),transactionRef:t.string(),transactionDate:t.string().datetime(),externalId:t.string().nullable().optional(),cbaReferenceNo:t.string().optional(),beepTransactionId:t.string().optional(),receiptNumber:t.string().optional(),createdAt:t.string().datetime(),reversedTransactionId:t.string().nullable().optional(),transactionId:t.string(),serviceFeeTransactionId:t.string().optional(),isReconciled:t.number().optional(),requestId:t.string().optional(),notes:t.string().optional(),updatedAt:t.string().datetime().optional()}),payoutFilters:t.object({page:t.number().int().positive().default(1),limit:t.number().int().positive().max(100).default(20),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().datetime().optional(),endDate:t.string().datetime().optional(),msisdn:t.string().optional(),id:t.string().optional(),ref:t.string().optional(),channel:ie.optional(),status:oe.optional(),minAmount:t.number().min(0).optional(),maxAmount:t.number().min(0).optional(),search:t.string().optional()}),payoutURLQueryParams:t.object({page:t.string().transform(e=>parseInt(e)||1).optional(),limit:t.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().optional(),endDate:t.string().optional(),msisdn:t.string().optional(),id:t.string().optional(),ref:t.string().optional(),channel:t.string().refine(e=>Object.values(re).includes(e)||e===ne.BANK).transform(e=>e).optional(),status:t.string().refine(e=>Object.values(te).includes(e)).transform(e=>e).optional(),minAmount:t.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.string().transform(e=>parseFloat(e)).optional(),search:t.string().optional()}),payoutStatus:oe,payoutChannel:ie,mobileChannel:se,bankChannel:ae,walletSummary:t.object({balance:t.number(),currency:t.string(),lastUpdated:t.string().datetime()}),transactionSummary:t.object({yesterday:t.number(),today:t.number(),thisMonth:t.number(),lastMonth:t.number()}),pagination:t.object({page:t.number(),limit:t.number(),total:t.number(),totalPages:t.number(),hasNext:t.boolean(),hasPrev:t.boolean()})},ue=v().router({getPayouts:{method:"GET",path:"",query:ce.payoutURLQueryParams,responses:{200:t.object({results:t.array(ce.payout),total:t.number()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"List payouts",description:"Retrieve a paginated list of payouts with optional filtering"},getPayout:{method:"GET",path:"/:id",pathParams:t.object({id:t.string()}),responses:{200:ce.payout,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Get payout details",description:"Retrieve detailed information about a specific payout"},getPayoutSummary:{method:"GET",path:"/summary",responses:{200:M.transactionSummary,401:t.object({message:t.string().optional()}),403:t.object({message:t.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:M.walletSummary,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"Get account balance",description:"Retrieve current account balance and status information"},getStatement:{method:"POST",path:"/collection-statement",body:t.object({startDate:t.string(),endDate:t.string()}),responses:{200:M.statementEntry,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()})},summary:"Get account statement"}}),le={[te.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[te.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[te.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[te.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"},[te.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[te.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"},[te.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"},[te.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"},[te.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"},[te.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"},[te.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"}},de={[re.AIRTEL]:{networkOperator:"Airtel",serviceName:"Airtel Money"},[re.VODACOM]:{networkOperator:"Vodacom",serviceName:"M-Pesa"},[re.TIGO]:{networkOperator:"Tigo",serviceName:"Tigo Pesa"},[re.HALOTEL]:{networkOperator:"Halotel",serviceName:"HaloPesa"}};function me(e){return Object.values(re).includes(e)}function he(e){return e===ne.BANK}function pe(){return Object.entries(le).filter(([e,t])=>"failed"===t.category).map(([e])=>e)}class fe{constructor(e){var t,r;let s="TZS";o.isCurrencyCode(e.currencyCode)&&(s=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=null!==(t=n.from(e.amount,s))&&void 0!==t?t:n.from(0,s),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!==(r=n.from(e.serviceFee,s))&&void 0!==r?r:n.from(0,s),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?n.from(parseFloat(e.postedAmount),s):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[te.PENDING,te.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===te.PAYMENT_ACCEPTED}isFailed(){return pe().includes(this.statusCodeText)}getStatusInfo(){return le[this.statusCodeText]}getChannelInfo(){if(me(this.serviceCode))return de[this.serviceCode];if(he(this.serviceCode)){const e=this.msisdn.split(":")[0];if(e&&s.validateSwiftCodeForAnyCountry(e)){const t=s.getCountryFromSwiftCode(e);if(t)try{return a.from(e,t)}catch(t){console.warn(`Failed to create Bank instance for SWIFT code ${e}:`,t)}}if(this.swiftCode&&s.validateSwiftCodeForAnyCountry(this.swiftCode)){const e=s.getCountryFromSwiftCode(this.swiftCode);if(e)try{return a.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 me(this.serviceCode)&&e?e.networkOperator:a.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 fe(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=>fe.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(!n.isAmountJson(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!n.isAmountJson(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!n.isAmountJson(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=n.fromJson(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let r,o;if(e.serviceFee){const t=n.fromJson(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);r=t.numericValue}if(e.postedAmount){const t=n.fromJson(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);o=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:r,notes:e.notes,swiftCode:e.swiftCode,createdAt:e.createdAt,updatedAt:e.updatedAt,statusCode:e.statusCode,countryCode:e.countryCode,postedAmount:o,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 fe(s)}catch(e){return void console.error("Error creating Payout from JSON:",e)}}static createManyFromJson(e){return e.map(e=>fe.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 ge extends m{static create(){return new ge}static fromFilters(e){return(new ge).applyFilters(e)}static fromUrlParams(e){try{const t=ce.payoutURLQueryParams.parse(e),r=ce.payoutFilters.parse(t);return ge.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 ge.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return ge.fromSearchParams(t)}static from(e){return null==e?new ge:m.is(e)?new ge(e.options):e instanceof URLSearchParams?ge.fromSearchParams(e):this.isStringRecord(e)?ge.fromUrlParams(e):ge.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",[te.PENDING,te.PENDING_ACK])}whereSuccessful(){return this.whereStatus(te.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[te.PAYMENT_REJECTED,te.GENERIC_FAILURE,te.AMOUNT_EXCEED_MAXIMUM,te.INVALID_SERVICE,te.INSUFFICIENT_BALANCE,te.THIRDPARTY_FAILED,te.WALLET_DEBITED,te.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(re))}whereBank(){return this.whereChannel(ne.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(re).includes(e)||e===ne.BANK}isValidStatus(e){return Object.values(te).includes(e)}}class ye extends R{constructor(e){super("payout",ue,e)}async getPayouts(e){try{const t=ge.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),o=this.handleResponse(n,200),s=t.toFilters(),a={page:s.page,limit:s.limit,total:o.total,totalPages:o.total>0?Math.ceil(o.total/s.limit):0,hasNext:s.page*s.limit<o.total,hasPrev:s.page>1};return{payouts:fe.createMany(o.results),pagination:a}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=ge.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),n=fe.from(r);if(!n)throw new Error("Invalid payout data received from server");return n}async getPayoutStats(){const e=await this.client.getPayoutSummary(),t=this.handleResponse(e,200),r=x.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}async getCollectionStatement(e){return(new ve).getCollectionStatement(e)}}class ve extends R{constructor(e){super("wallet",ue,{token:null==e?void 0:e.token,root:"https://api.temboplus.com/tembo/v1"})}async getCollectionStatement(e){const t=this.getClientWithHeaders({"x-account-id":"b1130ccb2373b1230a1f37b3","x-secret-key":"9OChe7Rf3pTOMMwMgYMrw//ugnLZsWmJyD6jo1vFO9Y="}),r=await t.getStatement({body:{startDate:e.startDate.toISOString(),endDate:e.endDate.toISOString()}}),n=this.handleResponse(r,200);if(!n)throw new Error("Invalid statement data received from server");return B.createMany(n)}}export{i as APIError,J as AuthDTOSchemas,$ as AuthRepository,ne as BANK_PAYOUT_CHANNEL,R as BaseRepository,K as CHANNEL_INFO,G as COLLECTION_CHANNEL,q as COLLECTION_STATUS,Z as COLLECTION_STATUS_INFO,Q as Collection,W as CollectionDTOSchemas,X as CollectionQuery,z as CollectionRepository,M as CommonSchemas,c as FilterOperator,de as MOBILE_CHANNEL_INFO,re as MOBILE_PAYOUT_CHANNEL,te as PAYOUT_STATUS,le as PAYOUT_STATUS_INFO,fe as Payout,ce as PayoutDTOSchemas,ge as PayoutQuery,ye as PayoutRepository,d as QUERY_BUILDER_TYPE,m as QueryBuilder,u as SortDirection,B as StatementEntry,x as TransactionSummary,k as User,_ as WalletInfo,U as authContract,Y as collectionContract,pe as getFailedStatuses,he as isBankChannel,me as isMobileChannel,ue as payoutContract,L as statementEntrySchema};
2
2
  //# sourceMappingURL=index.esm.js.map