@temboplus/tembo-dashboard 0.1.3-beta.1 → 0.1.3-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("zod"),t=require("uuid"),r=require("@temboplus/frontend-core");function n(e){return e&&e.__esModule?e:{default:e}}var o,a,s,i=n(e);class u extends Error{constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,e.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return u.schema.safeParse(e).success}static unknown(e){return new u({message:null!=e?e:"An unknown error occurred",statusCode:502})}static get schema(){return e.z.object({message:e.z.string(),statusCode:e.z.number().int(),error:e.z.string().optional(),details:e.z.object({}).optional()})}}exports.FilterOperator=void 0,(o=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",o.NOT_EQUALS="neq",o.LESS_THAN="lt",o.LESS_THAN_OR_EQUAL="lte",o.GREATER_THAN="gt",o.GREATER_THAN_OR_EQUAL="gte",o.LIKE="like",o.LIKE_LOWER="likeLower",o.IS_NULL="isNull",o.IS_NOT_NULL="isNotNull",o.IN="in",exports.SortDirection=void 0,(a=exports.SortDirection||(exports.SortDirection={})).ASC="asc",a.DESC="desc";const c=Symbol("query-builder-type");class l{constructor(e={}){this.options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8},this[s]="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&&c in e&&"query-builder"===e[c]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN_OR_EQUAL,value:t})}whereBetween(e,t,r){return this.whereGreaterThanOrEqual(e,t).whereLessThanOrEqual(e,r)}whereDateBetween(e,t){return e&&this.whereGreaterThanOrEqual("createdAt",e),t&&this.whereLessThanOrEqual("createdAt",t),this}addSort(e){return this.options.sort=[...this.options.sort||[],e],this}orderBy(e,t=exports.SortDirection.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,exports.SortDirection.ASC)}orderByDesc(e){return this.orderBy(e,exports.SortDirection.DESC)}paginate(e,t){return this.options.page=e,this.options.limit=t,this}with(e){const t=Array.isArray(e)?e:[e];return this.options.includes=[...this.options.includes||[],...t],this}join(e){const t=Array.isArray(e)?e:[e];return this.options.join=[...this.options.join||[],...t],this}groupBy(e){const t=Array.isArray(e)?e:[e];return this.options.groupBy=[...this.options.groupBy||[],...t],this}count(e="*"){return this.options.count=e,this}countAs(e,t){return this.options.count=`${e} as ${t}`,this}build(){const e={};if(void 0!==this.options.page&&void 0!==this.options.limit){const t=(this.options.page-1)*this.options.limit,r=t+this.options.limit-1;e.rangeStart=t,e.rangeEnd=r}if(this.options.filters&&this.options.filters.length>0)for(const t of this.options.filters)switch(t.operator){case exports.FilterOperator.IS_NULL:e[`${t.field}:isNull`]=1;break;case exports.FilterOperator.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case exports.FilterOperator.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case exports.FilterOperator.LIKE:e[`${t.field}:like`]=t.value;break;case exports.FilterOperator.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case exports.FilterOperator.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case exports.FilterOperator.LESS_THAN_OR_EQUAL:e[`${t.field}:lte`]=t.value;break;default:e[`${t.field}:${t.operator}`]=t.value}if(this.options.sort&&this.options.sort.length>0){const t=[],r=[];for(const e of this.options.sort)e.direction===exports.SortDirection.ASC?t.push(e.field):r.push(e.field);t.length>0&&(e.orderBy=t.join(",")),r.length>0&&(e.orderByDesc=r.join(","))}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?e.eager=this.options.includes[0]:e.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(e.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(e.groupBy=this.options.groupBy.join(",")),this.options.count&&(e.count=this.options.count),e}clone(){return new(0,this.constructor)(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 l(e)}}s=c;const d=e=>"function"==typeof(null==e?void 0:e.passthrough);e.z.object({name:e.z.literal("ZodError"),issues:e.z.array(e.z.object({path:e.z.array(e.z.union([e.z.string(),e.z.number()])),message:e.z.string().optional(),code:e.z.nativeEnum(e.z.ZodIssueCode)}).catchall(e.z.any()))});const m=Symbol("ContractNoBody"),h=e=>"method"in e&&"path"in e,p=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,o,a,s,i;return h(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:(s=null==t?void 0:t.baseHeaders,i=r.headers,d(s)?d(i)?s.merge(i):s:d(i)?i:Object.assign({},s,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!==(a=r.metadata)&&void 0!==a?a:{}}:r.metadata}]:[e,p(r,t)]})),A=Symbol("ContractPlainType"),f=()=>({router:(e,t)=>p(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>A,body:()=>A,type:()=>A,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>m}),y=e=>e?Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r;return r="string"==typeof t&&!["true","false","null"].includes(t.trim())&&isNaN(Number(t))?t:JSON.stringify(t),`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).join("&"):"",g=e=>e?Object.keys(e).flatMap(t=>N(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",N=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>N(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>N(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class v extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const E=async({route:e,path:t,method:r,headers:n,body:o,validateResponse:a,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:n,body:o}),u=i.headers.get("content-type");if((null==u?void 0:u.includes("application/"))&&(null==u?void 0:u.includes("json"))){const t={status:i.status,body:await i.json(),headers:i.headers},r=e.responses[t.status];return(null!=a?a:e.validateResponseOnClient)&&"function"==typeof(null==(c=r)?void 0:c.safeParse)?{...t,body:r.parse(t.body)}:t}var c;return(null==u?void 0:u.includes("text/"))?{status:i.status,body:await i.text(),headers:i.headers}:{status:i.status,body:await i.blob(),headers:i.headers}},T=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},O=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),S=(e,t,r,n,o)=>{const a=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),s=((e,t=!1)=>{const r=t?y(e):g(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,o);return`${t}${a}${s}`},C=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const o=((e,t,r)=>{const{query:n,params:o,body:a,headers:s,extraHeaders:i,overrideClientOptions:u,fetchOptions:c,cache:l,next:d,...m}=r||{},h={...t,...u};return{path:S(n,h.baseUrl,o,e,!!h.jsonQuery),clientArgs:h,route:e,body:a,query:n,extraInputArgs:m,fetchOptions:{...l&&{cache:l},...d&&{next:d},...c},headers:{...i,...s}}})(e,t,n),a=await(e=>{const{path:t,clientArgs:r,route:n,body:o,query:a,extraInputArgs:s,headers:i,fetchOptions:u}=e,c=r.api||E,l=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),d={...l&&O(l),...O(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:a,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...u},...(null==u?void 0:u.signal)&&{signal:u.signal},...(null==u?void 0:u.cache)&&{cache:u.cache},...u&&"next"in u&&!!(null==u?void 0:u.next)&&{next:u.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?m={...m,contentType:"multipart/form-data",body:o instanceof FormData?o:T(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)})),c({...m,...s})})(o);if(!t.throwOnUnknownStatus)return a;if(r.includes(a.status.toString()))return a;throw new v(a,r)}},w=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>h(r)?[e,C(r,t)]:[e,w(r,t)])),I=i.default.object({statusCode:i.default.number().int(),reason:i.default.string().optional(),error:i.default.string().optional(),details:i.default.record(i.default.unknown()).optional(),message:i.default.string().optional()}),b=I.extend({statusCode:i.default.literal(400)}),D=I.extend({statusCode:i.default.literal(401)}),x=I.extend({statusCode:i.default.literal(403)}),L=I.extend({statusCode:i.default.literal(404)}),R=I.extend({statusCode:i.default.literal(500)}),P=i.default.object({page:i.default.number().int().positive(),limit:i.default.number().int().positive(),total:i.default.number().int().min(0),totalPages:i.default.number().int().min(0),hasNext:i.default.boolean(),hasPrev:i.default.boolean()}),F=i.default.object({balance:i.default.number(),availableBalance:i.default.number(),accountNumber:i.default.string(),accountName:i.default.string()}),_=i.default.object({yesterday:i.default.number(),today:i.default.number(),thisMonth:i.default.number(),lastMonth:i.default.number()});const z=i.default.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"}`)}}),U=i.default.object({accountNo:i.default.string().nullish(),debitOrCredit:i.default.enum(["CR","DR"],{errorMap:()=>({message:"Transaction type must be either 'CR' (Credit) or 'DR' (Debit)"})}),tranRefNo:i.default.string().nullish(),cbaRefNo:i.default.string().nullish(),narration:i.default.string().nullish(),txnDate:z,valueDate:z,amountCredited:i.default.union([i.default.number().min(0,"Credited amount cannot be negative"),i.default.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"})}).nullish(),amountDebited:i.default.union([i.default.number().min(0,"Debited amount cannot be negative"),i.default.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"})}).nullish(),balance:i.default.number({required_error:"Balance is required",invalid_type_error:"Balance must be a number"})}),B={apiError:I,validationError:b,unauthorizedError:D,forbiddenError:x,notFoundError:L,serverError:R,pagination:P,transactionSummary:_,walletSummary:F,statementEntry:U};class M{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 r=this.root?this.root.replace(/\/+$/,""):"",n=this.endpoint?this.endpoint.replace(/^\/+/,""):"",o=r?`${r}/${n}`:`https://gateway.temboplus.com/dashboard/${n}`,a={Authorization:`Bearer ${this.getToken()}`,"x-request-id":t.v4()},s={baseUrl:o,baseHeaders:e?Object.assign(Object.assign({},a),e):a};return w(this.contract,s)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;const r=B.apiError.safeParse(e.body),n=r.success?r.data:void 0,o=(t,r)=>{var o,a,s,i;return new u({message:null!==(o=null==n?void 0:n.message)&&void 0!==o?o:t,statusCode:null!==(a=null==n?void 0:n.statusCode)&&void 0!==a?a:e.status,error:null!==(i=null!==(s=null==n?void 0:n.error)&&void 0!==s?s:null==n?void 0:n.reason)&&void 0!==i?i:r,details:null==n?void 0:n.details})};if(400===e.status)throw o("Bad request","BAD_REQUEST");if(401===e.status)throw o("You are not authenticated to perform this action. Please login again","UNAUTHORIZED");if(403===e.status)throw o("You are not authorized to perform this action.","FORBIDDEN");if(404===e.status)throw o("The requested resource was not found.","NOT_FOUND");if(500===e.status)throw o("We encountered an error trying to process your request. Please try again later","SERVER_ERROR");throw o("We encountered an error trying to process your request. Please try again later","UNKNOWN_ERROR")}}class J{constructor(e,t="TZS"){var n,o,a,s;this.currency=t,this.yesterday=null!==(n=r.Amount.from(e.yesterday,t))&&void 0!==n?n:r.Amount.from(0,t),this.today=null!==(o=r.Amount.from(e.today,t))&&void 0!==o?o:r.Amount.from(0,t),this.thisMonth=null!==(a=r.Amount.from(e.thisMonth,t))&&void 0!==a?a:r.Amount.from(0,t),this.lastMonth=null!==(s=r.Amount.from(e.lastMonth,t))&&void 0!==s?s:r.Amount.from(0,t)}getMonthlyGrowthRate(){return 0===this.lastMonth.numericValue?this.thisMonth.numericValue>0?100:0:(this.thisMonth.numericValue-this.lastMonth.numericValue)/this.lastMonth.numericValue*100}getRecentTotal(){return r.Amount.from(this.today.numericValue+this.yesterday.numericValue,this.currency)}static from(e,t="TZS"){return new J(e,t)}toJSON(){return{yesterday:this.yesterday.toJSON(),today:this.today.toJSON(),thisMonth:this.thisMonth.toJSON(),lastMonth:this.lastMonth.toJSON(),currency:this.currency}}static fromJSON(e){try{if(!(r.Amount.isAmountJSON(e.yesterday)&&r.Amount.isAmountJSON(e.today)&&r.Amount.isAmountJSON(e.thisMonth)&&r.Amount.isAmountJSON(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=r.Amount.fromJSON(e.yesterday),n=r.Amount.fromJSON(e.today),o=r.Amount.fromJSON(e.thisMonth),a=r.Amount.fromJSON(e.lastMonth);if(!(t&&n&&o&&a))return void console.error("Failed to reconstruct Amount instances from JSON:",e);const s={yesterday:t.numericValue,today:n.numericValue,thisMonth:o.numericValue,lastMonth:a.numericValue};return new J(s,e.currency)}catch(e){return void console.error("Error creating TransactionSummary from JSON:",e)}}}class j{constructor(e){var t,n;let o="TZS";e.currencyCode&&r.CurrencyValidation.isCurrencyCode(e.currencyCode)&&(o=e.currencyCode),this.accountName=e.accountName,this.accountNo=e.accountNo,this.accountNumber=e.accountNo,this.currency=o,this.currencyCode=o,this.countryCode=e.countryCode,this.availableBalance=null!==(t=r.Amount.from(e.availableBalance,o))&&void 0!==t?t:r.Amount.from(0,o),this.currentBalance=null!==(n=r.Amount.from(e.currentBalance,o))&&void 0!==n?n:r.Amount.from(0,o),this.actualBalance=this.currentBalance,this.accountStatus=e.accountStatus,this.type=e.type}hasSufficientBalance(e){return this.availableBalance.numericValue>=e}static from(e){return new j(e)}toJSON(){return{accountName:this.accountName,accountNo:this.accountNo,accountNumber:this.accountNumber,availableBalance:this.availableBalance.toJSON(),currentBalance:this.currentBalance.toJSON(),actualBalance:this.actualBalance.toJSON(),accountStatus:this.accountStatus,type:this.type,currencyCode:this.currencyCode,countryCode:this.countryCode,currency:this.currency}}static fromJSON(e){var t;try{if(!r.Amount.isAmountJSON(e.availableBalance)||!r.Amount.isAmountJSON(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const n=r.Amount.fromJSON(e.availableBalance),o=null!==(t=e.currentBalance)&&void 0!==t?t:e.actualBalance;if(!r.Amount.isAmountJSON(o))return void console.error("Invalid currentBalance AmountJson structure in WalletInfo JSON:",e);const a=r.Amount.fromJSON(o);if(!n||!a)return void console.error("Failed to reconstruct Amount instances from JSON:",e);const s=e.accountNo||e.accountNumber;if(!s)return void console.error("Missing account number in WalletInfo JSON:",e);const i={accountName:e.accountName,accountNo:s,availableBalance:n.numericValue,currentBalance:a.numericValue,accountStatus:e.accountStatus||"UNKNOWN",type:e.type,currencyCode:e.currencyCode||e.currency,countryCode:e.countryCode};return new j(i)}catch(e){return void console.error("Error creating WalletInfo from JSON:",e)}}static createManyFromJson(e){return e.map(e=>j.fromJSON(e)).filter(Boolean)}}class V{constructor(e,t="TZS"){var n,o,a;let s="TZS";r.CurrencyValidation.isCurrencyCode(t)&&(s=t),this.accountNo=e.accountNo,this.debitOrCredit=e.debitOrCredit,this.tranRefNo=e.tranRefNo,this.cbaRefNo=e.cbaRefNo,this.narration=e.narration,this.txnDate=e.txnDate?new Date(e.txnDate):null,this.valueDate=e.valueDate?new Date(e.valueDate):null,this.currency=s;const i=e.amountCredited?this.parseAmountValue(e.amountCredited):null;this.amountCredited=null===i?null:i>0?null!==(n=r.Amount.from(i,s))&&void 0!==n?n:r.Amount.from(0,s):null;const u=e.amountDebited?this.parseAmountValue(e.amountDebited):null;this.amountDebited=null===u?null:u>0?null!==(o=r.Amount.from(u,s))&&void 0!==o?o:r.Amount.from(0,s):null,this.balance=null!==(a=r.Amount.from(e.balance,s))&&void 0!==a?a:r.Amount.from(0,s)}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"){try{return!1===B.statementEntry.safeParse(e).success?void console.error("Missing required StatementEntry fields:",e):new V(e,t)}catch(e){return void console.error("Error creating StatementEntry:",e)}}static createMany(e,t="TZS"){return e.map(e=>V.from(e,t)).filter(Boolean)}toJSON(){var e,t,r,n,o,a;return{accountNo:this.accountNo,debitOrCredit:this.debitOrCredit,tranRefNo:this.tranRefNo,cbaRefNo:this.cbaRefNo,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!==(a=null===(o=this.amountDebited)||void 0===o?void 0:o.toJSON())&&void 0!==a?a:null,balance:this.balance.toJSON(),currency:this.currency}}static fromJSON(e){try{if(!r.Amount.isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure:",e.balance);if(e.amountCredited&&!r.Amount.isAmountJSON(e.amountCredited))return void console.error("Invalid amountCredited AmountJson structure:",e.amountCredited);if(e.amountDebited&&!r.Amount.isAmountJSON(e.amountDebited))return void console.error("Invalid amountDebited AmountJson structure:",e.amountDebited);const t=r.Amount.fromJSON(e.balance);if(!t)return void console.error("Failed to reconstruct balance Amount from JSON:",e.balance);let n=0;if(e.amountCredited){const t=r.Amount.fromJSON(e.amountCredited);if(!t)return void console.error("Failed to reconstruct amountCredited Amount from JSON:",e.amountCredited);n=t.numericValue}let o=0;if(e.amountDebited){const t=r.Amount.fromJSON(e.amountDebited);if(!t)return void console.error("Failed to reconstruct amountDebited Amount from JSON:",e.amountDebited);o=t.numericValue}const a={accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,cbaRefNo:e.cbaRefNo,narration:e.narration,txnDate:e.txnDate?e.txnDate:null,valueDate:e.valueDate?e.valueDate:null,amountCredited:n,amountDebited:o,balance:t.numericValue};return new V(a,e.currency)}catch(e){return void console.error("Error creating StatementEntry from JSON:",e)}}static createManyFromJson(e){return e.map(e=>V.fromJSON(e)).filter(Boolean)}static getTotalCredits(e){var t;const n=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=r.Amount.from(o,n))&&void 0!==t?t:r.Amount.from(0,n)}static getTotalDebits(e){var t;const n=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=r.Amount.from(o,n))&&void 0!==t?t:r.Amount.from(0,n)}static getNetChange(e){var t;const n=e.length>0?e[0].currency:"TZS",o=V.getTotalCredits(e).numericValue,a=V.getTotalDebits(e).numericValue;return null!==(t=r.Amount.from(o-a,n))&&void 0!==t?t:r.Amount.from(0,n)}}const Y={AIRTEL:{key:"AIRTEL",networkOperator:"Airtel",serviceName:"Airtel Money"},VODACOM:{key:"VODACOM",networkOperator:"Vodacom",serviceName:"M-Pesa"},TIGO:{key:"TIGO",networkOperator:"Yas",serviceName:"Mixx by Yas"},HALOTEL:{key:"HALOTEL",networkOperator:"Halotel",serviceName:"HaloPesa"},SAFARICOM:{key:"SAFARICOM",networkOperator:"Safaricom",serviceName:"M-Pesa"}},$={user:e.z.object({token:e.z.string(),identity:e.z.string(),name:e.z.string()}),loginRequest:e.z.object({identity:e.z.string().email(),password:e.z.string()}),updatePassword:e.z.object({currentPassword:e.z.string(),newPassword:e.z.string()})},k=f().router({login:{method:"POST",path:"/login",body:$.loginRequest,responses:{201:$.user,400:B.validationError,401:B.unauthorizedError,500:B.serverError},summary:"User login",description:"Authenticate user with email and password"},updatePassword:{method:"POST",path:"/change-password",body:$.updatePassword,responses:{201:i.default.object({}),400:B.validationError,401:B.unauthorizedError,500:B.serverError},summary:"Update password",description:"Update user password"}});class q{constructor(e){this.identity=e.identity,this.name=e.name}static from(e){return new q(e)}static fromJson(e){return q.from(e)}toJson(){return{identity:this.identity,name:this.name}}get email(){return this.identity}getDisplayName(){return this.name||this.identity}isEmailIdentity(){return/^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i.test(this.identity)}getInitials(){return this.getDisplayName().split(" ").map(e=>e.charAt(0).toUpperCase()).slice(0,2).join("")}equals(e){return this.identity===e.identity&&this.name===e.name}}var H,G;exports.COLLECTION_STATUS=void 0,(H=exports.COLLECTION_STATUS||(exports.COLLECTION_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",H.GENERIC_FAILURE="GENERIC_FAILURE",H.PAYMENT_REJECTED="PAYMENT_REJECTED",H.PENDING_ACK="PENDING_ACK",H.PROVIDER_FAILED="PROVIDER_FAILED",exports.COLLECTION_CHANNEL=void 0,(G=exports.COLLECTION_CHANNEL||(exports.COLLECTION_CHANNEL={})).AIRTEL="TZ-AIRTEL-C2B",G.TIGO="TZ-TIGO-C2B",G.HALOTEL="TZ-HALOTEL-C2B",G.SAFARICOM="TZ-SAFARICOM-C2B";const W=e.z.nativeEnum(exports.COLLECTION_STATUS),K=e.z.nativeEnum(exports.COLLECTION_CHANNEL),Q={collection:e.z.object({id:e.z.string().min(1),status:W,statusMessage:e.z.string(),accountNo:e.z.string().min(1),walletId:e.z.string(),transactionDate:e.z.string().datetime(),narration:e.z.string(),msisdn:e.z.string().min(1),channel:K,amount:e.z.number().min(0),serviceFee:e.z.string().optional(),postedAmount:e.z.string().optional(),reference:e.z.string(),partnerReference:e.z.string().nullable().optional(),transactionId:e.z.string().nullable().optional(),serviceFeeTransactionId:e.z.string().nullable().optional(),requestId:e.z.string().nullable().optional(),completedAt:e.z.string().datetime().nullable().optional(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime(),notes:e.z.string().optional(),currencyCode:e.z.string().default("TZS")}),collectionFilters:e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(1e4).default(20),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().optional(),endDate:e.z.string().datetime().optional(),msisdn:e.z.string().optional(),id:e.z.string().optional(),reference:e.z.string().optional(),accountNo:e.z.string().optional(),walletId:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:K.optional(),status:W.optional(),minAmount:e.z.number().min(0).optional(),maxAmount:e.z.number().min(0).optional(),search:e.z.string().optional()}),collectionURLQueryParams:e.z.object({page:e.z.string().transform(e=>parseInt(e)||1).optional(),limit:e.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().optional(),endDate:e.z.string().optional(),msisdn:e.z.string().optional(),id:e.z.string().optional(),reference:e.z.string().optional(),accountNo:e.z.string().optional(),walletId:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:e.z.string().refine(e=>Object.values(exports.COLLECTION_CHANNEL).includes(e)).transform(e=>e).optional(),status:e.z.string().refine(e=>Object.values(exports.COLLECTION_STATUS).includes(e)).transform(e=>e).optional(),minAmount:e.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:e.z.string().transform(e=>parseFloat(e)).optional(),search:e.z.string().optional()}),paymentStatus:W,paymentChannel:K},Z=f().router({getCollections:{method:"GET",path:"/",query:Q.collectionURLQueryParams,responses:{200:e.z.object({results:e.z.array(Q.collection),total:e.z.number()}),401:B.unauthorizedError,403:B.forbiddenError,500:B.serverError},summary:"List collections",description:"Retrieve a paginated list of collections with optional filtering"},getCollection:{method:"GET",path:"/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:Q.collection,401:B.unauthorizedError,403:B.forbiddenError,404:B.notFoundError,500:B.serverError},summary:"Get collection details",description:"Retrieve detailed information about a specific collection"},getSummary:{method:"GET",path:"/summary",responses:{200:B.transactionSummary,401:B.unauthorizedError,403:B.forbiddenError,500:B.serverError},summary:"Get collections summary",description:"Retrieve collection summary statistics for different time periods"}}),X={[exports.COLLECTION_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[exports.COLLECTION_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.COLLECTION_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Please try again"},[exports.COLLECTION_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred during payment processing",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.COLLECTION_STATUS.PROVIDER_FAILED]:{label:"Provider Failed",description:"An error occurred on the telecom provider's side, and the payment request was not successfully processed",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an issue with the provider"}},ee={[exports.COLLECTION_CHANNEL.AIRTEL]:Y.AIRTEL,[exports.COLLECTION_CHANNEL.TIGO]:Y.TIGO,[exports.COLLECTION_CHANNEL.HALOTEL]:Y.HALOTEL,[exports.COLLECTION_CHANNEL.SAFARICOM]:Y.SAFARICOM};class te{constructor(e){var t,n,o;this._originalData=Object.assign({},e);let a="TZS";r.CurrencyValidation.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=r.Amount.from(e.amount,a))&&void 0!==t?t:r.Amount.from(0,a),this.serviceFee=e.serviceFee?null!==(n=r.Amount.from(parseFloat(e.serviceFee),a))&&void 0!==n?n:r.Amount.from(0,a):void 0,this.postedAmount=e.postedAmount?null!==(o=r.Amount.from(parseFloat(e.postedAmount),a))&&void 0!==o?o:r.Amount.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}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return this.status===exports.COLLECTION_STATUS.PENDING_ACK}isSuccessful(){return this.status===exports.COLLECTION_STATUS.PAYMENT_ACCEPTED}isFailed(){return Object.entries(X).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.status)}getStatusInfo(){return X[this.status]}getChannelInfo(){return ee[this.channel]}getProviderName(){return this.getChannelInfo().networkOperator}getServiceName(){return this.getChannelInfo().serviceName}isMobileCollection(){return e=this.channel,Object.values(exports.COLLECTION_CHANNEL).includes(e);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 te(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=>te.from(e)).filter(Boolean)}static fromJSON(e){try{if(!(null==e?void 0:e.id)||!(null==e?void 0:e.msisdn)||!(null==e?void 0:e.amount))return void console.error("Missing required Collection JSON fields:",e);if(!r.Amount.isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.Amount.isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.Amount.isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let n,o;if(e.serviceFee){const t=r.Amount.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);n=t.numericValue.toString()}if(e.postedAmount){const t=r.Amount.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);o=t.numericValue.toString()}const a={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:n,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 te(a)}catch(e){return void console.error("Error creating Collection from JSON:",e)}}static createManyFromJson(e){return e.map(e=>te.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 re extends l{static create(){return new re}static fromFilters(e){return(new re).applyFilters(e)}static fromUrlParams(e){try{const t=Q.collectionURLQueryParams.parse(e),r=Q.collectionFilters.parse(t);return re.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 re.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return re.fromSearchParams(t)}static from(e){try{return null==e?new re:l.is(e)?new re(e.options):e instanceof URLSearchParams?re.fromSearchParams(e):this.isStringRecord(e)?re.fromUrlParams(e):re.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a CollectionQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereStatus(e){return this.where("status",e)}whereChannel(e){return this.where("channel",e)}wherePending(){return this.whereStatus(exports.COLLECTION_STATUS.PENDING_ACK)}whereSuccessful(){return this.whereStatus(exports.COLLECTION_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("status",[exports.COLLECTION_STATUS.PAYMENT_REJECTED,exports.COLLECTION_STATUS.GENERIC_FAILURE])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereSender(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereWalletId(e){return this.whereContains("walletId",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.walletId&&this.whereWalletId(e.walletId),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,walletId:e.walletId,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.walletId||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.walletId&&e.push(`Wallet ID: ${t.walletId}`),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"walletId":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}return e}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidChannel(e){return Object.values(exports.COLLECTION_CHANNEL).includes(e)}isValidStatus(e){return Object.values(exports.COLLECTION_STATUS).includes(e)}}var ne,oe;exports.PAYOUT_STATUS=void 0,(ne=exports.PAYOUT_STATUS||(exports.PAYOUT_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",ne.GENERIC_FAILURE="GENERIC_FAILURE",ne.WALLET_DEBITED="WALLET_DEBITED",ne.PAYMENT_REJECTED="PAYMENT_REJECTED",ne.PENDING="PENDING",ne.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",ne.PENDING_ACK="PENDING_ACK",ne.REVERSED="REVERSED",ne.INVALID_SERVICE="INVALID_SERVICE",ne.INVALID_NUMBER="INVALID_NUMBER",ne.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",ne.THIRDPARTY_FAILED="THIRDPARTY_FAILED",ne.PROVIDER_FAILED="PROVIDER_FAILED",exports.MOBILE_PAYOUT_CHANNEL=void 0,(oe=exports.MOBILE_PAYOUT_CHANNEL||(exports.MOBILE_PAYOUT_CHANNEL={})).AIRTEL="TZ-AIRTEL-B2C",oe.VODACOM="TZ-VODACOM-B2C",oe.TIGO="TZ-TIGO-B2C",oe.HALOTEL="TZ-HALOTEL-B2C",oe.SAFARICOM="TZ-SAFARICOM-B2C",exports.BANK_PAYOUT_CHANNEL=void 0,(exports.BANK_PAYOUT_CHANNEL||(exports.BANK_PAYOUT_CHANNEL={})).BANK="TZ-BANK-B2C";const ae=e.z.nativeEnum(exports.PAYOUT_STATUS),se=e.z.nativeEnum(exports.MOBILE_PAYOUT_CHANNEL),ie=e.z.nativeEnum(exports.BANK_PAYOUT_CHANNEL),ue=e.z.union([se,ie]),ce={payout:e.z.object({id:e.z.string().min(1),statusCode:e.z.string(),statusCodeText:ae,statusDescription:e.z.string(),countryCode:e.z.string(),serviceCode:ue,amount:e.z.number().min(0),serviceFee:e.z.string().optional(),postedAmount:e.z.string().optional(),walletId:e.z.string().optional(),msisdn:e.z.string().min(1),narration:e.z.string(),currencyCode:e.z.string(),recipientNames:e.z.string().optional(),transactionRef:e.z.string(),transactionDate:e.z.string().datetime(),externalId:e.z.string().nullable().optional(),cbaReferenceNo:e.z.string().optional(),beepTransactionId:e.z.string().optional(),receiptNumber:e.z.string().optional(),createdAt:e.z.string().datetime(),reversedTransactionId:e.z.string().nullable().optional(),transactionId:e.z.string(),serviceFeeTransactionId:e.z.string().optional(),isReconciled:e.z.number().optional(),requestId:e.z.string().optional(),notes:e.z.string().optional(),updatedAt:e.z.string().datetime().optional()}),payoutFilters:e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(1e4).default(20),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().optional(),endDate:e.z.string().datetime().optional(),msisdn:e.z.string().optional(),accountNo:e.z.string().optional(),walletId:e.z.string().optional(),id:e.z.string().optional(),ref:e.z.string().optional(),channel:ue.optional(),status:ae.optional(),minAmount:e.z.number().min(0).optional(),maxAmount:e.z.number().min(0).optional(),search:e.z.string().optional()}),payoutURLQueryParams:e.z.object({page:e.z.string().transform(e=>parseInt(e)||1).optional(),limit:e.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().optional(),endDate:e.z.string().optional(),msisdn:e.z.string().optional(),accountNo:e.z.string().optional(),walletId:e.z.string().optional(),id:e.z.string().optional(),ref:e.z.string().optional(),channel:e.z.string().refine(e=>Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK).transform(e=>e).optional(),status:e.z.string().refine(e=>Object.values(exports.PAYOUT_STATUS).includes(e)).transform(e=>e).optional(),minAmount:e.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:e.z.string().transform(e=>parseFloat(e)).optional(),search:e.z.string().optional()}),payoutStatus:ae,payoutChannel:ue,mobileChannel:se,bankChannel:ie,walletSummary:e.z.object({balance:e.z.number(),currency:e.z.string(),lastUpdated:e.z.string().datetime()}),transactionSummary:e.z.object({yesterday:e.z.number(),today:e.z.number(),thisMonth:e.z.number(),lastMonth:e.z.number()}),pagination:e.z.object({page:e.z.number(),limit:e.z.number(),total:e.z.number(),totalPages:e.z.number(),hasNext:e.z.boolean(),hasPrev:e.z.boolean()})},le=f().router({getPayouts:{method:"GET",path:"",query:ce.payoutURLQueryParams,responses:{200:e.z.object({results:e.z.array(ce.payout),total:e.z.number()}),401:B.unauthorizedError,403:B.forbiddenError,500:B.serverError},summary:"List payouts",description:"Retrieve a paginated list of payouts with optional filtering"},getPayout:{method:"GET",path:"/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:ce.payout,401:B.unauthorizedError,403:B.forbiddenError,404:B.notFoundError,500:B.serverError},summary:"Get payout details",description:"Retrieve detailed information about a specific payout"},getPayoutSummary:{method:"GET",path:"/summary",responses:{200:B.transactionSummary,401:B.unauthorizedError,403:B.forbiddenError,500:B.serverError},summary:"Get payout summary",description:"Retrieve payout statistics including yesterday, today, this month, and last month totals"}}),de={[exports.PAYOUT_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[exports.PAYOUT_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.PAYOUT_STATUS.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[exports.PAYOUT_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Check payment details and try again"},[exports.PAYOUT_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE]:{label:"Insufficient Balance",description:"Insufficient funds are available to process the payment",category:"failed",color:"error",userFriendlyMessage:"Insufficient funds to complete the payment"},[exports.PAYOUT_STATUS.THIRDPARTY_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.PROVIDER_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM]:{label:"Amount Exceeds Limit",description:"Payment amount exceeds the maximum allowed limit",category:"failed",color:"error",userFriendlyMessage:"Payment amount exceeds the allowed limit"},[exports.PAYOUT_STATUS.WALLET_DEBITED]:{label:"Wallet Debited",description:"Wallet has been debited but payment is not yet complete",category:"failed",color:"error",userFriendlyMessage:"Payment incomplete - wallet debited but recipient may not have received funds"},[exports.PAYOUT_STATUS.REVERSED]:{label:"Payment Reversed",description:"Payment has been reversed and funds returned",category:"failed",color:"error",userFriendlyMessage:"Payment was reversed and funds have been returned"},[exports.PAYOUT_STATUS.INVALID_SERVICE]:{label:"Invalid Service",description:"The requested payment service is not valid or available",category:"failed",color:"error",userFriendlyMessage:"Selected payment service is not available"},[exports.PAYOUT_STATUS.INVALID_NUMBER]:{label:"Invalid Number",description:"The number used is either barred or invalid",category:"failed",color:"error",userFriendlyMessage:"Recipient’s number is invalid, inactive, or temporarily blocked."}},me={[exports.MOBILE_PAYOUT_CHANNEL.AIRTEL]:Y.AIRTEL,[exports.MOBILE_PAYOUT_CHANNEL.VODACOM]:Y.VODACOM,[exports.MOBILE_PAYOUT_CHANNEL.TIGO]:Y.TIGO,[exports.MOBILE_PAYOUT_CHANNEL.HALOTEL]:Y.HALOTEL,[exports.MOBILE_PAYOUT_CHANNEL.SAFARICOM]:Y.SAFARICOM};function he(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)}function pe(e){return e===exports.BANK_PAYOUT_CHANNEL.BANK}class Ae{constructor(e){var t,n;this._originalData=Object.assign({},e);let o="TZS";r.CurrencyValidation.isCurrencyCode(e.currencyCode)&&(o=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=null!==(t=r.Amount.from(e.amount,o))&&void 0!==t?t:r.Amount.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!==(n=r.Amount.from(e.serviceFee,o))&&void 0!==n?n:r.Amount.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?r.Amount.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}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===exports.PAYOUT_STATUS.PAYMENT_ACCEPTED}isFailed(){return Object.entries(de).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.statusCodeText)}getStatusInfo(){return de[this.statusCodeText]}getChannelInfo(){if(he(this.serviceCode))return me[this.serviceCode];if(pe(this.serviceCode)){const e=this.msisdn.split(":")[0];if(e&&r.BankValidation.validateSwiftCodeForAnyCountry(e)){const t=r.BankValidation.getCountryFromSwiftCode(e);if(t)try{return r.Bank.from(e,t)}catch(t){console.warn(`Failed to create Bank instance for SWIFT code ${e}:`,t)}}if(this.swiftCode&&r.BankValidation.validateSwiftCodeForAnyCountry(this.swiftCode)){const e=r.BankValidation.getCountryFromSwiftCode(this.swiftCode);if(e)try{return r.Bank.from(this.swiftCode,e)}catch(e){console.warn(`Failed to create Bank instance for SWIFT code ${this.swiftCode}:`,e)}}}}getAccountNumber(){try{if(he(this.serviceCode))return this.msisdn;if(pe(this.serviceCode)){return this.msisdn.split(":")[1]||this.msisdn}}catch(e){console.warn("failed to get the account number from payout msisdn: ",this.msisdn)}return this.msisdn}getProviderName(){const e=this.getChannelInfo();return he(this.serviceCode)&&e?e.networkOperator:r.Bank.is(e)?e.shortName:"Bank Transfer"}static from(e){try{return(null==e?void 0:e.id)&&(null==e?void 0:e.msisdn)&&void 0!==(null==e?void 0:e.amount)?new Ae(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=>Ae.from(e)).filter(Boolean)}static fromJSON(e){try{if(!(null==e?void 0:e.id)||!(null==e?void 0:e.msisdn)||!(null==e?void 0:e.amount))return void console.error("Missing required Payout JSON fields:",e);if(!r.Amount.isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.Amount.isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.Amount.isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let n,o;if(e.serviceFee){const t=r.Amount.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);n=t.numericValue}if(e.postedAmount){const t=r.Amount.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);o=t.numericValue.toString()}const a={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:n,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 Ae(a)}catch(e){return void console.error("Error creating Payout from JSON:",e)}}static createManyFromJson(e){return e.map(e=>Ae.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 fe extends l{static create(){return new fe}static fromFilters(e){return(new fe).applyFilters(e)}static fromUrlParams(e){try{const t=ce.payoutURLQueryParams.parse(e),r=ce.payoutFilters.parse(t);return fe.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 fe.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return fe.fromSearchParams(t)}static from(e){return null==e?new fe:l.is(e)?new fe(e.options):e instanceof URLSearchParams?fe.fromSearchParams(e):this.isStringRecord(e)?fe.fromUrlParams(e):fe.fromFilters(e)}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereStatus(e){return this.where("statusCodeText",e)}whereChannel(e){return this.where("serviceCode",e)}wherePending(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK])}whereSuccessful(){return this.whereStatus(exports.PAYOUT_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PAYMENT_REJECTED,exports.PAYOUT_STATUS.GENERIC_FAILURE,exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM,exports.PAYOUT_STATUS.INVALID_SERVICE,exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE,exports.PAYOUT_STATUS.THIRDPARTY_FAILED,exports.PAYOUT_STATUS.WALLET_DEBITED,exports.PAYOUT_STATUS.REVERSED])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereRecipient(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereWalletId(e){return this.whereContains("walletId",e)}whereReference(e){return this.whereContains("transactionRef",e)}whereMobile(){return this.whereIn("serviceCode",Object.values(exports.MOBILE_PAYOUT_CHANNEL))}whereBank(){return this.whereChannel(exports.BANK_PAYOUT_CHANNEL.BANK)}whereSearch(e){return this.where("search",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.status&&this.whereStatus(e.status),e.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereRecipient(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.walletId&&this.whereWalletId(e.walletId),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,accountNo:e.accountNo,walletId:e.walletId,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.accountNo||e.walletId||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.accountNo&&e.push(`Account: ${t.accountNo}`),t.walletId&&e.push(`Wallet ID: ${t.walletId}`),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"accountNo":case"walletId":case"transactionRef":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}return e}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidChannel(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK}isValidStatus(e){return Object.values(exports.PAYOUT_STATUS).includes(e)}}const ye={localTransferRequest:e.z.object({amount:e.z.number().int().positive(),from:e.z.string().min(1),to:e.z.string().min(1),description:e.z.string().min(1)}),localTransferResponse:e.z.object({transactionId:e.z.string(),from:e.z.string(),to:e.z.string(),transactionDate:e.z.string(),narration:e.z.string(),amount:e.z.number(),transactionRef:e.z.string()})},ge=f().router({localTransfer:{method:"POST",path:"/local-transfer",body:ye.localTransferRequest,responses:{201:ye.localTransferResponse,400:B.validationError,401:B.unauthorizedError,404:B.notFoundError,500:B.serverError},summary:"Local transfer",description:"Transfer funds locally between wallets."}});var Ne;exports.WALLET_TYPE=void 0,(Ne=exports.WALLET_TYPE||(exports.WALLET_TYPE={})).VENDOR="Vendor",Ne.DEFAULT_DISBURSEMENT="DEFAULT DISBURSEMENT",Ne.DEFAULT_COLLECTION="DEFAULT COLLECTION",Ne.COLLECTION="COLLECTION",Ne.DISBURSEMENT="DISBURSEMENT";const ve=e.z.nativeEnum(exports.WALLET_TYPE),Ee=e.z.object({id:e.z.string().min(1),accountNo:e.z.string().min(1),accountName:e.z.string().min(1),shadowAccountNo:e.z.string().nullish(),externalId:e.z.string().nullish(),reference:e.z.string().nullish(),type:e.z.string().min(1),vendorId:e.z.string().nullish(),balance:e.z.number(),minBalance:e.z.union([e.z.number(),e.z.string()]),approvalLimit:e.z.union([e.z.number(),e.z.string()]),currency:e.z.string().min(1),countryCode:e.z.string().min(1),createdAt:e.z.string().min(1),updatedAt:e.z.string().min(1)}),Te=e.z.object({availableBalance:e.z.number(),currentBalance:e.z.number(),accountStatus:e.z.string().min(1),accountNo:e.z.string().min(1),accountName:e.z.string().min(1)}),Oe={wallet:Ee,walletType:ve,walletPathParams:e.z.object({accountNo:e.z.string().min(1)}),walletBalance:Te,walletStatementQuery:e.z.object({startDate:e.z.string().regex(/^\d{4}-\d{2}-\d{2}$/),endDate:e.z.string().regex(/^\d{4}-\d{2}-\d{2}$/)})},Se=f().router({listWallets:{method:"GET",path:"",responses:{200:e.z.array(Oe.wallet),401:B.unauthorizedError,500:B.serverError},summary:"List wallets",description:"Retrieve all wallets linked to the account across supported currencies."},getWalletInfo:{method:"GET",path:"/:accountNo",pathParams:e.z.object({accountNo:e.z.string().min(1)}),responses:{200:Oe.wallet,401:B.unauthorizedError,500:B.serverError},summary:"Get wallet info",description:"Retrieve wallet metadata including balance, currency, and type for a specific wallet."},getWalletBalance:{method:"GET",path:"/:accountNo/balance",pathParams:Oe.walletPathParams,responses:{200:Oe.walletBalance,401:B.unauthorizedError,404:B.notFoundError,500:B.serverError},summary:"Get wallet balance",description:"Retrieve the current and available balance for a specific wallet account number."},getWalletStatement:{method:"GET",path:"/:accountNo/statement",pathParams:Oe.walletPathParams,query:Oe.walletStatementQuery,responses:{200:e.z.array(B.statementEntry),400:B.validationError,401:B.unauthorizedError,404:B.notFoundError,500:B.serverError},summary:"Get wallet statement",description:"Retrieve statement entries for a specific wallet within a date range."}});class Ce{constructor(e){var t,n,o;this._originalData=Object.assign({},e);let a="TZS";r.CurrencyValidation.isCurrencyCode(e.currency)?a=e.currency:"KSH"===e.currency&&(a="KES"),this.id=e.id,this.accountNo=e.accountNo,this.accountName=e.accountName,this.shadowAccountNo=e.shadowAccountNo,this.externalId=e.externalId,this.reference=e.reference,this.type=e.type,this.vendorId=e.vendorId,this.balance=null!==(t=r.Amount.from(e.balance,a))&&void 0!==t?t:r.Amount.from(0,a),this.minBalance=null!==(n=r.Amount.from(this.parseAmountValue(e.minBalance),a))&&void 0!==n?n:r.Amount.from(0,a),this.approvalLimit=null!==(o=r.Amount.from(this.parseAmountValue(e.approvalLimit),a))&&void 0!==o?o:r.Amount.from(0,a),this.currency=a,this.countryCode=e.countryCode,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}getOriginalData(){return this._originalData}parseAmountValue(e){if("number"==typeof e)return e;const t=parseFloat(e);return Number.isNaN(t)?0:t}isCollectionWallet(){return this.type.includes("COLLECTION")}isDisbursementWallet(){return this.type.includes("DISBURSEMENT")}isDefaultWallet(){return this.type.startsWith("DEFAULT")}static from(e){return new Ce(e)}static createMany(e){return e.map(e=>Ce.from(e))}toJSON(){return{id:this.id,accountNo:this.accountNo,accountName:this.accountName,shadowAccountNo:this.shadowAccountNo,externalId:this.externalId,reference:this.reference,type:this.type,vendorId:this.vendorId,balance:this.balance.toJSON(),minBalance:this.minBalance.toJSON(),approvalLimit:this.approvalLimit.toJSON(),currency:this.currency,countryCode:this.countryCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}static fromJSON(e){try{if(!r.Amount.isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure in Wallet JSON:",e);if(!r.Amount.isAmountJSON(e.minBalance)||!r.Amount.isAmountJSON(e.approvalLimit))return void console.error("Invalid wallet threshold AmountJson structure in Wallet JSON:",e);const t=r.Amount.fromJSON(e.balance),n=r.Amount.fromJSON(e.minBalance),o=r.Amount.fromJSON(e.approvalLimit);return t&&n&&o?new Ce({id:e.id,accountNo:e.accountNo,accountName:e.accountName,shadowAccountNo:e.shadowAccountNo,externalId:e.externalId,reference:e.reference,type:e.type,vendorId:e.vendorId,balance:t.numericValue,minBalance:n.numericValue,approvalLimit:o.numericValue,currency:e.currency,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt}):void console.error("Failed to reconstruct balance Amount from JSON:",e)}catch(e){return void console.error("Error creating Wallet from JSON:",e)}}}exports.APIError=u,exports.AuthDTOSchemas=$,exports.AuthRepository=class extends M{constructor(e){super("auth",k,e)}async login(e){const t={identity:e.email,password:e.password},r=await this.client.login({body:t}),n=this.handleResponse(r,201),o=q.from(n);if(!o)throw new Error("Invalid user data received from server");return{user:o,token:n.token}}async updatePassword(e){const t=await this.client.updatePassword({body:e});if(201!==t.status){if(400===t.status)throw new Error("Validation error");if(401===t.status)throw new Error("Unauthorized");throw new Error("Failed to update password")}return!0}},exports.BaseRepository=M,exports.COLLECTION_STATUS_INFO=X,exports.Collection=te,exports.CollectionDTOSchemas=Q,exports.CollectionQuery=re,exports.CollectionRepository=class extends M{constructor(e){super("collection",Z,e)}async getCollections(e){try{const t=re.from(e),r=t.build(),n=await this.client.getCollections({query:r}),o=this.handleResponse(n,200),a=t.toFilters(),s={page:a.page,limit:a.limit,total:o.total,totalPages:o.total>0?Math.ceil(o.total/a.limit):0,hasNext:a.page*a.limit<o.total,hasPrev:a.page>1};return{collections:te.createMany(o.results),pagination:s}}catch(e){throw new Error(`Failed to fetch collections: ${e instanceof Error?e.message:"Unknown error"}`)}}async getCollectionsFromRequest(e){const t=re.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),n=te.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=J.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}},exports.CommonSchemas=B,exports.MobileChannels=Y,exports.PAYOUT_STATUS_INFO=de,exports.Payout=Ae,exports.PayoutDTOSchemas=ce,exports.PayoutQuery=fe,exports.PayoutRepository=class extends M{constructor(e){super("payout",le,e)}async getPayouts(e){try{const t=fe.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),o=this.handleResponse(n,200),a=t.toFilters(),s={page:a.page,limit:a.limit,total:o.total,totalPages:o.total>0?Math.ceil(o.total/a.limit):0,hasNext:a.page*a.limit<o.total,hasPrev:a.page>1};return{payouts:Ae.createMany(o.results),pagination:s}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=fe.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),n=Ae.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=J.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}},exports.QUERY_BUILDER_TYPE=c,exports.QueryBuilder=l,exports.StatementEntry=V,exports.TransactionDTOSchemas=ye,exports.TransactionRepository=class extends M{constructor(e){super("transaction",ge,e)}async localTransfer(e){const t=await this.client.localTransfer({body:e});return this.handleResponse(t,201)}},exports.TransactionSummary=J,exports.User=q,exports.Wallet=Ce,exports.WalletDTOSchemas=Oe,exports.WalletInfo=j,exports.WalletRepository=class extends M{constructor(e){super("wallet",Se,e)}async listWallets(){const e=await this.client.listWallets(),t=this.handleResponse(e,200);return Ce.createMany(t)}async getWalletInfo(e){const t=await this.client.getWalletInfo({params:{accountNo:e}}),r=this.handleResponse(t,200);return Ce.from(r)}async getWalletBalance(e){const t=await this.client.getWalletBalance({params:{accountNo:e}}),r=this.handleResponse(t,200);return j.from(r)}async getWalletStatement(e){const t=await this.client.getWalletStatement({params:{accountNo:e.accountNo},query:{startDate:this.formatStatementDate(e.startDate),endDate:this.formatStatementDate(e.endDate)}}),r=this.handleResponse(t,200);return V.createMany(r)}formatStatementDate(e){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Error("Invalid statement date provided.");return e.toISOString().slice(0,10)}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return e;const t=new Date(e);if(Number.isNaN(t.getTime()))throw new Error(`Invalid statement date: ${e}`);return t.toISOString().slice(0,10)}},exports.authContract=k,exports.collectionContract=Z,exports.payoutContract=le,exports.statementEntrySchema=U,exports.transactionContract=ge,exports.walletContract=Se;
1
+ "use strict";var e=require("zod"),t=require("uuid"),r=require("@temboplus/frontend-core");function n(e){return e&&e.__esModule?e:{default:e}}var o,a,s,i=n(e);class c extends Error{constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,e.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return c.schema.safeParse(e).success}static unknown(e){return new c({message:null!=e?e:"An unknown error occurred",statusCode:502})}static get schema(){return e.z.object({message:e.z.string(),statusCode:e.z.number().int(),error:e.z.string().optional(),details:e.z.object({}).optional()})}}exports.FilterOperator=void 0,(o=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",o.NOT_EQUALS="neq",o.LESS_THAN="lt",o.LESS_THAN_OR_EQUAL="lte",o.GREATER_THAN="gt",o.GREATER_THAN_OR_EQUAL="gte",o.LIKE="like",o.LIKE_LOWER="likeLower",o.IS_NULL="isNull",o.IS_NOT_NULL="isNotNull",o.IN="in",exports.SortDirection=void 0,(a=exports.SortDirection||(exports.SortDirection={})).ASC="asc",a.DESC="desc";const u=Symbol("query-builder-type");class l{constructor(e={}){this.options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8},this[s]="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&&u in e&&"query-builder"===e[u]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN_OR_EQUAL,value:t})}whereBetween(e,t,r){return this.whereGreaterThanOrEqual(e,t).whereLessThanOrEqual(e,r)}whereDateBetween(e,t){return e&&this.whereGreaterThanOrEqual("createdAt",e),t&&this.whereLessThanOrEqual("createdAt",t),this}addSort(e){return this.options.sort=[...this.options.sort||[],e],this}orderBy(e,t=exports.SortDirection.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,exports.SortDirection.ASC)}orderByDesc(e){return this.orderBy(e,exports.SortDirection.DESC)}paginate(e,t){return this.options.page=e,this.options.limit=t,this}with(e){const t=Array.isArray(e)?e:[e];return this.options.includes=[...this.options.includes||[],...t],this}join(e){const t=Array.isArray(e)?e:[e];return this.options.join=[...this.options.join||[],...t],this}groupBy(e){const t=Array.isArray(e)?e:[e];return this.options.groupBy=[...this.options.groupBy||[],...t],this}count(e="*"){return this.options.count=e,this}countAs(e,t){return this.options.count=`${e} as ${t}`,this}build(){const e={};if(void 0!==this.options.page&&void 0!==this.options.limit){const t=(this.options.page-1)*this.options.limit,r=t+this.options.limit-1;e.rangeStart=t,e.rangeEnd=r}if(this.options.filters&&this.options.filters.length>0)for(const t of this.options.filters)switch(t.operator){case exports.FilterOperator.IS_NULL:e[`${t.field}:isNull`]=1;break;case exports.FilterOperator.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case exports.FilterOperator.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case exports.FilterOperator.LIKE:e[`${t.field}:like`]=t.value;break;case exports.FilterOperator.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case exports.FilterOperator.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case exports.FilterOperator.LESS_THAN_OR_EQUAL:e[`${t.field}:lte`]=t.value;break;default:e[`${t.field}:${t.operator}`]=t.value}if(this.options.sort&&this.options.sort.length>0){const t=[],r=[];for(const e of this.options.sort)e.direction===exports.SortDirection.ASC?t.push(e.field):r.push(e.field);t.length>0&&(e.orderBy=t.join(",")),r.length>0&&(e.orderByDesc=r.join(","))}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?e.eager=this.options.includes[0]:e.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(e.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(e.groupBy=this.options.groupBy.join(",")),this.options.count&&(e.count=this.options.count),e}clone(){return new(0,this.constructor)(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 l(e)}}s=u;const d=e=>"function"==typeof(null==e?void 0:e.passthrough);e.z.object({name:e.z.literal("ZodError"),issues:e.z.array(e.z.object({path:e.z.array(e.z.union([e.z.string(),e.z.number()])),message:e.z.string().optional(),code:e.z.nativeEnum(e.z.ZodIssueCode)}).catchall(e.z.any()))});const m=Symbol("ContractNoBody"),h=e=>"method"in e&&"path"in e,p=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,o,a,s,i;return h(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:(s=null==t?void 0:t.baseHeaders,i=r.headers,d(s)?d(i)?s.merge(i):s:d(i)?i:Object.assign({},s,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!==(a=r.metadata)&&void 0!==a?a:{}}:r.metadata}]:[e,p(r,t)]})),f=Symbol("ContractPlainType"),A=()=>({router:(e,t)=>p(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>f,body:()=>f,type:()=>f,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>m}),y=e=>e?Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r;return r="string"==typeof t&&!["true","false","null"].includes(t.trim())&&isNaN(Number(t))?t:JSON.stringify(t),`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).join("&"):"",g=e=>e?Object.keys(e).flatMap(t=>N(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",N=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>N(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>N(`${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 v=async({route:e,path:t,method:r,headers:n,body:o,validateResponse:a,fetchOptions:s})=>{const i=await fetch(t,{...s,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!=a?a: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}},T=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},O=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),S=(e,t,r,n,o)=>{const a=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),s=((e,t=!1)=>{const r=t?y(e):g(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,o);return`${t}${a}${s}`},C=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const o=((e,t,r)=>{const{query:n,params:o,body:a,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:l,next:d,...m}=r||{},h={...t,...c};return{path:S(n,h.baseUrl,o,e,!!h.jsonQuery),clientArgs:h,route:e,body:a,query:n,extraInputArgs:m,fetchOptions:{...l&&{cache:l},...d&&{next:d},...u},headers:{...i,...s}}})(e,t,n),a=await(e=>{const{path:t,clientArgs:r,route:n,body:o,query:a,extraInputArgs:s,headers:i,fetchOptions:c}=e,u=r.api||v,l=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),d={...l&&O(l),...O(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:a,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?m={...m,contentType:"multipart/form-data",body:o instanceof FormData?o:T(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,...s})})(o);if(!t.throwOnUnknownStatus)return a;if(r.includes(a.status.toString()))return a;throw new E(a,r)}},I=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>h(r)?[e,C(r,t)]:[e,I(r,t)])),w=i.default.object({statusCode:i.default.number().int(),reason:i.default.string().optional(),error:i.default.string().optional(),details:i.default.record(i.default.unknown()).optional(),message:i.default.string().optional()}),b=w.extend({statusCode:i.default.literal(400)}),D=w.extend({statusCode:i.default.literal(401)}),R=w.extend({statusCode:i.default.literal(403)}),L=w.extend({statusCode:i.default.literal(404)}),x=w.extend({statusCode:i.default.literal(500)}),F=i.default.object({page:i.default.number().int().positive(),limit:i.default.number().int().positive(),total:i.default.number().int().min(0),totalPages:i.default.number().int().min(0),hasNext:i.default.boolean(),hasPrev:i.default.boolean()}),P=i.default.object({balance:i.default.number(),availableBalance:i.default.number(),accountNumber:i.default.string(),accountName:i.default.string()}),_=i.default.object({yesterday:i.default.number(),today:i.default.number(),thisMonth:i.default.number(),lastMonth:i.default.number()});const z=i.default.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"}`)}}),U=i.default.object({accountNo:i.default.string().nullish(),debitOrCredit:i.default.enum(["CR","DR"],{errorMap:()=>({message:"Transaction type must be either 'CR' (Credit) or 'DR' (Debit)"})}),tranRefNo:i.default.string().nullish(),cbaRefNo:i.default.string().nullish(),narration:i.default.string().nullish(),txnDate:z,valueDate:z,amountCredited:i.default.union([i.default.number().min(0,"Credited amount cannot be negative"),i.default.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"})}).nullish(),amountDebited:i.default.union([i.default.number().min(0,"Debited amount cannot be negative"),i.default.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"})}).nullish(),balance:i.default.number({required_error:"Balance is required",invalid_type_error:"Balance must be a number"})}),B={apiError:w,validationError:b,unauthorizedError:D,forbiddenError:R,notFoundError:L,serverError:x,pagination:F,transactionSummary:_,walletSummary:P,statementEntry:U};class M{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 r=this.root?this.root.replace(/\/+$/,""):"",n=this.endpoint?this.endpoint.replace(/^\/+/,""):"",o=r?`${r}/${n}`:`https://gateway.temboplus.com/dashboard/${n}`,a={Authorization:`Bearer ${this.getToken()}`,"x-request-id":t.v4()},s={baseUrl:o,baseHeaders:e?Object.assign(Object.assign({},a),e):a};return I(this.contract,s)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;const r=B.apiError.safeParse(e.body),n=r.success?r.data:void 0,o=(t,r)=>{var o,a,s,i;return new c({message:null!==(o=null==n?void 0:n.message)&&void 0!==o?o:t,statusCode:null!==(a=null==n?void 0:n.statusCode)&&void 0!==a?a:e.status,error:null!==(i=null!==(s=null==n?void 0:n.error)&&void 0!==s?s:null==n?void 0:n.reason)&&void 0!==i?i:r,details:null==n?void 0:n.details})};if(400===e.status)throw o("Bad request","BAD_REQUEST");if(401===e.status)throw o("You are not authenticated to perform this action. Please login again","UNAUTHORIZED");if(403===e.status)throw o("You are not authorized to perform this action.","FORBIDDEN");if(404===e.status)throw o("The requested resource was not found.","NOT_FOUND");if(500===e.status)throw o("We encountered an error trying to process your request. Please try again later","SERVER_ERROR");throw o("We encountered an error trying to process your request. Please try again later","UNKNOWN_ERROR")}}class J{constructor(e,t="TZS"){var n,o,a,s;this.currency=t,this.yesterday=null!==(n=r.Amount.from(e.yesterday,t))&&void 0!==n?n:r.Amount.from(0,t),this.today=null!==(o=r.Amount.from(e.today,t))&&void 0!==o?o:r.Amount.from(0,t),this.thisMonth=null!==(a=r.Amount.from(e.thisMonth,t))&&void 0!==a?a:r.Amount.from(0,t),this.lastMonth=null!==(s=r.Amount.from(e.lastMonth,t))&&void 0!==s?s:r.Amount.from(0,t)}getMonthlyGrowthRate(){return 0===this.lastMonth.numericValue?this.thisMonth.numericValue>0?100:0:(this.thisMonth.numericValue-this.lastMonth.numericValue)/this.lastMonth.numericValue*100}getRecentTotal(){return r.Amount.from(this.today.numericValue+this.yesterday.numericValue,this.currency)}static from(e,t="TZS"){return new J(e,t)}toJSON(){return{yesterday:this.yesterday.toJSON(),today:this.today.toJSON(),thisMonth:this.thisMonth.toJSON(),lastMonth:this.lastMonth.toJSON(),currency:this.currency}}static fromJSON(e){try{if(!(r.Amount.isAmountJSON(e.yesterday)&&r.Amount.isAmountJSON(e.today)&&r.Amount.isAmountJSON(e.thisMonth)&&r.Amount.isAmountJSON(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=r.Amount.fromJSON(e.yesterday),n=r.Amount.fromJSON(e.today),o=r.Amount.fromJSON(e.thisMonth),a=r.Amount.fromJSON(e.lastMonth);if(!(t&&n&&o&&a))return void console.error("Failed to reconstruct Amount instances from JSON:",e);const s={yesterday:t.numericValue,today:n.numericValue,thisMonth:o.numericValue,lastMonth:a.numericValue};return new J(s,e.currency)}catch(e){return void console.error("Error creating TransactionSummary from JSON:",e)}}}class j{constructor(e){var t,n;let o="TZS";e.currencyCode&&r.CurrencyValidation.isCurrencyCode(e.currencyCode)&&(o=e.currencyCode),this.accountName=e.accountName,this.accountNo=e.accountNo,this.accountNumber=e.accountNo,this.currency=o,this.currencyCode=o,this.countryCode=e.countryCode,this.availableBalance=null!==(t=r.Amount.from(e.availableBalance,o))&&void 0!==t?t:r.Amount.from(0,o),this.currentBalance=null!==(n=r.Amount.from(e.currentBalance,o))&&void 0!==n?n:r.Amount.from(0,o),this.actualBalance=this.currentBalance,this.accountStatus=e.accountStatus,this.type=e.type}hasSufficientBalance(e){return this.availableBalance.numericValue>=e}static from(e){return new j(e)}toJSON(){return{accountName:this.accountName,accountNo:this.accountNo,accountNumber:this.accountNumber,availableBalance:this.availableBalance.toJSON(),currentBalance:this.currentBalance.toJSON(),actualBalance:this.actualBalance.toJSON(),accountStatus:this.accountStatus,type:this.type,currencyCode:this.currencyCode,countryCode:this.countryCode,currency:this.currency}}static fromJSON(e){var t;try{if(!r.Amount.isAmountJSON(e.availableBalance)||!r.Amount.isAmountJSON(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const n=r.Amount.fromJSON(e.availableBalance),o=null!==(t=e.currentBalance)&&void 0!==t?t:e.actualBalance;if(!r.Amount.isAmountJSON(o))return void console.error("Invalid currentBalance AmountJson structure in WalletInfo JSON:",e);const a=r.Amount.fromJSON(o);if(!n||!a)return void console.error("Failed to reconstruct Amount instances from JSON:",e);const s=e.accountNo||e.accountNumber;if(!s)return void console.error("Missing account number in WalletInfo JSON:",e);const i={accountName:e.accountName,accountNo:s,availableBalance:n.numericValue,currentBalance:a.numericValue,accountStatus:e.accountStatus||"UNKNOWN",type:e.type,currencyCode:e.currencyCode||e.currency,countryCode:e.countryCode};return new j(i)}catch(e){return void console.error("Error creating WalletInfo from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=j.fromJSON(r);if(!e)return;t.push(e)}return t}}class V{constructor(e,t="TZS"){var n,o,a;let s="TZS";r.CurrencyValidation.isCurrencyCode(t)&&(s=t),this.accountNo=e.accountNo,this.debitOrCredit=e.debitOrCredit,this.tranRefNo=e.tranRefNo,this.cbaRefNo=e.cbaRefNo,this.narration=e.narration,this.txnDate=e.txnDate?new Date(e.txnDate):null,this.valueDate=e.valueDate?new Date(e.valueDate):null,this.currency=s;const i=e.amountCredited?this.parseAmountValue(e.amountCredited):null;this.amountCredited=null===i?null:i>0?null!==(n=r.Amount.from(i,s))&&void 0!==n?n:r.Amount.from(0,s):null;const c=e.amountDebited?this.parseAmountValue(e.amountDebited):null;this.amountDebited=null===c?null:c>0?null!==(o=r.Amount.from(c,s))&&void 0!==o?o:r.Amount.from(0,s):null,this.balance=null!==(a=r.Amount.from(e.balance,s))&&void 0!==a?a:r.Amount.from(0,s)}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"){try{return!1===B.statementEntry.safeParse(e).success?void console.error("Missing required StatementEntry fields:",e):new V(e,t)}catch(e){return void console.error("Error creating StatementEntry:",e)}}static createMany(e,t="TZS"){const r=[];for(const n of e){const e=V.from(n,t);if(!e)return;r.push(e)}return r}toJSON(){var e,t,r,n,o,a;return{accountNo:this.accountNo,debitOrCredit:this.debitOrCredit,tranRefNo:this.tranRefNo,cbaRefNo:this.cbaRefNo,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!==(a=null===(o=this.amountDebited)||void 0===o?void 0:o.toJSON())&&void 0!==a?a:null,balance:this.balance.toJSON(),currency:this.currency}}static fromJSON(e){try{if(!r.Amount.isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure:",e.balance);if(e.amountCredited&&!r.Amount.isAmountJSON(e.amountCredited))return void console.error("Invalid amountCredited AmountJson structure:",e.amountCredited);if(e.amountDebited&&!r.Amount.isAmountJSON(e.amountDebited))return void console.error("Invalid amountDebited AmountJson structure:",e.amountDebited);const t=r.Amount.fromJSON(e.balance);if(!t)return void console.error("Failed to reconstruct balance Amount from JSON:",e.balance);let n=0;if(e.amountCredited){const t=r.Amount.fromJSON(e.amountCredited);if(!t)return void console.error("Failed to reconstruct amountCredited Amount from JSON:",e.amountCredited);n=t.numericValue}let o=0;if(e.amountDebited){const t=r.Amount.fromJSON(e.amountDebited);if(!t)return void console.error("Failed to reconstruct amountDebited Amount from JSON:",e.amountDebited);o=t.numericValue}const a={accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,cbaRefNo:e.cbaRefNo,narration:e.narration,txnDate:e.txnDate?e.txnDate:null,valueDate:e.valueDate?e.valueDate:null,amountCredited:n,amountDebited:o,balance:t.numericValue};return new V(a,e.currency)}catch(e){return void console.error("Error creating StatementEntry from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=V.fromJSON(r);if(!e)return;t.push(e)}return t}static getTotalCredits(e){var t;const n=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=r.Amount.from(o,n))&&void 0!==t?t:r.Amount.from(0,n)}static getTotalDebits(e){var t;const n=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=r.Amount.from(o,n))&&void 0!==t?t:r.Amount.from(0,n)}static getNetChange(e){var t;const n=e.length>0?e[0].currency:"TZS",o=V.getTotalCredits(e).numericValue,a=V.getTotalDebits(e).numericValue;return null!==(t=r.Amount.from(o-a,n))&&void 0!==t?t:r.Amount.from(0,n)}}const Y={AIRTEL:{key:"AIRTEL",networkOperator:"Airtel",serviceName:"Airtel Money"},VODACOM:{key:"VODACOM",networkOperator:"Vodacom",serviceName:"M-Pesa"},TIGO:{key:"TIGO",networkOperator:"Yas",serviceName:"Mixx by Yas"},HALOTEL:{key:"HALOTEL",networkOperator:"Halotel",serviceName:"HaloPesa"},SAFARICOM:{key:"SAFARICOM",networkOperator:"Safaricom",serviceName:"M-Pesa"}},$={user:e.z.object({token:e.z.string(),identity:e.z.string(),name:e.z.string()}),loginRequest:e.z.object({identity:e.z.string().email(),password:e.z.string()}),updatePassword:e.z.object({currentPassword:e.z.string(),newPassword:e.z.string()})},k=A().router({login:{method:"POST",path:"/login",body:$.loginRequest,responses:{201:$.user,400:B.validationError,401:B.unauthorizedError,500:B.serverError},summary:"User login",description:"Authenticate user with email and password"},updatePassword:{method:"POST",path:"/change-password",body:$.updatePassword,responses:{201:i.default.object({}),400:B.validationError,401:B.unauthorizedError,500:B.serverError},summary:"Update password",description:"Update user password"}});class q{constructor(e){this.identity=e.identity,this.name=e.name}static from(e){return new q(e)}static fromJson(e){return q.from(e)}toJson(){return{identity:this.identity,name:this.name}}get email(){return this.identity}getDisplayName(){return this.name||this.identity}isEmailIdentity(){return/^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i.test(this.identity)}getInitials(){return this.getDisplayName().split(" ").map(e=>e.charAt(0).toUpperCase()).slice(0,2).join("")}equals(e){return this.identity===e.identity&&this.name===e.name}}var H,G;exports.COLLECTION_STATUS=void 0,(H=exports.COLLECTION_STATUS||(exports.COLLECTION_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",H.GENERIC_FAILURE="GENERIC_FAILURE",H.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",H.PAYMENT_REJECTED="PAYMENT_REJECTED",H.PENDING_ACK="PENDING_ACK",H.PROVIDER_FAILED="PROVIDER_FAILED",exports.COLLECTION_CHANNEL=void 0,(G=exports.COLLECTION_CHANNEL||(exports.COLLECTION_CHANNEL={})).AIRTEL="TZ-AIRTEL-C2B",G.TIGO="TZ-TIGO-C2B",G.HALOTEL="TZ-HALOTEL-C2B",G.SAFARICOM="KE-SAFARICOM-C2B",G.VODACOM="TZ-VODACOM-C2B";const W=e.z.nativeEnum(exports.COLLECTION_STATUS),K=e.z.nativeEnum(exports.COLLECTION_CHANNEL),Q={collection:e.z.object({id:e.z.string().min(1),status:W,statusMessage:e.z.string(),accountNo:e.z.string().min(1),walletId:e.z.string(),transactionDate:e.z.string().datetime(),narration:e.z.string(),msisdn:e.z.string().min(1),channel:K,amount:e.z.number().min(0),serviceFee:e.z.string().optional(),postedAmount:e.z.string().optional(),reference:e.z.string(),partnerReference:e.z.string().nullable().optional(),payerName:e.z.string().nullable().optional(),payerReference:e.z.string().nullable().optional(),merchantName:e.z.string().nullable().optional(),merchantReference:e.z.string().nullable().optional(),transactionId:e.z.string().nullable().optional(),serviceFeeTransactionId:e.z.string().nullable().optional(),requestId:e.z.string().nullable().optional(),completedAt:e.z.string().datetime().nullable().optional(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime(),notes:e.z.string().optional(),currencyCode:e.z.string().default("TZS")}),collectionFilters:e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(1e4).default(20),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().optional(),endDate:e.z.string().datetime().optional(),msisdn:e.z.string().optional(),id:e.z.string().optional(),reference:e.z.string().optional(),accountNo:e.z.string().optional(),walletId:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:K.optional(),status:W.optional(),minAmount:e.z.number().min(0).optional(),maxAmount:e.z.number().min(0).optional(),search:e.z.string().optional()}),collectionURLQueryParams:e.z.object({page:e.z.string().transform(e=>parseInt(e)||1).optional(),limit:e.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().optional(),endDate:e.z.string().optional(),msisdn:e.z.string().optional(),id:e.z.string().optional(),reference:e.z.string().optional(),accountNo:e.z.string().optional(),walletId:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:e.z.string().refine(e=>Object.values(exports.COLLECTION_CHANNEL).includes(e)).transform(e=>e).optional(),status:e.z.string().refine(e=>Object.values(exports.COLLECTION_STATUS).includes(e)).transform(e=>e).optional(),minAmount:e.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:e.z.string().transform(e=>parseFloat(e)).optional(),search:e.z.string().optional()}),paymentStatus:W,paymentChannel:K},Z=A().router({getCollections:{method:"GET",path:"/",query:Q.collectionURLQueryParams,responses:{200:e.z.object({results:e.z.array(Q.collection),total:e.z.number()}),401:B.unauthorizedError,403:B.forbiddenError,500:B.serverError},summary:"List collections",description:"Retrieve a paginated list of collections with optional filtering"},getCollection:{method:"GET",path:"/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:Q.collection,401:B.unauthorizedError,403:B.forbiddenError,404:B.notFoundError,500:B.serverError},summary:"Get collection details",description:"Retrieve detailed information about a specific collection"},getSummary:{method:"GET",path:"/summary",responses:{200:B.transactionSummary,401:B.unauthorizedError,403:B.forbiddenError,500:B.serverError},summary:"Get collections summary",description:"Retrieve collection summary statistics for different time periods"}}),X={[exports.COLLECTION_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[exports.COLLECTION_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.COLLECTION_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Please try again"},[exports.COLLECTION_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred during payment processing",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.COLLECTION_STATUS.INSUFFICIENT_FUNDS]:{label:"Insufficient Funds",description:"The payer has insufficient funds to complete the payment",category:"failed",color:"error",userFriendlyMessage:"Insufficient funds to complete the payment"},[exports.COLLECTION_STATUS.PROVIDER_FAILED]:{label:"Provider Failed",description:"An error occurred on the telecom provider's side, and the payment request was not successfully processed",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an issue with the provider"}},ee={[exports.COLLECTION_CHANNEL.AIRTEL]:Y.AIRTEL,[exports.COLLECTION_CHANNEL.TIGO]:Y.TIGO,[exports.COLLECTION_CHANNEL.HALOTEL]:Y.HALOTEL,[exports.COLLECTION_CHANNEL.VODACOM]:Y.VODACOM,[exports.COLLECTION_CHANNEL.SAFARICOM]:Y.SAFARICOM};class te{constructor(e){var t,n,o;this._originalData=Object.assign({},e);let a="TZS";r.CurrencyValidation.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=r.Amount.from(e.amount,a))&&void 0!==t?t:r.Amount.from(0,a),this.serviceFee=e.serviceFee?null!==(n=r.Amount.from(parseFloat(e.serviceFee),a))&&void 0!==n?n:r.Amount.from(0,a):void 0,this.postedAmount=e.postedAmount?null!==(o=r.Amount.from(parseFloat(e.postedAmount),a))&&void 0!==o?o:r.Amount.from(0,a):void 0,this.reference=e.reference,this.partnerReference=e.partnerReference,this.payerName=e.payerName,this.payerReference=e.payerReference,this.merchantName=e.merchantName,this.merchantReference=e.merchantReference,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}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return this.status===exports.COLLECTION_STATUS.PENDING_ACK}isSuccessful(){return this.status===exports.COLLECTION_STATUS.PAYMENT_ACCEPTED}isFailed(){return Object.entries(X).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.status)}getStatusInfo(){return X[this.status]}getChannelInfo(){return ee[this.channel]}getProviderName(){return this.getChannelInfo().networkOperator}getServiceName(){return this.getChannelInfo().serviceName}isMobileCollection(){return e=this.channel,Object.values(exports.COLLECTION_CHANNEL).includes(e);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 te(e):void console.error("Missing required Collection fields:",e)}catch(e){return void console.error("Error creating Collection:",e)}}static createMany(e){const t=[];for(const r of e){const e=te.from(r);if(!e)return;t.push(e)}return t}static fromJSON(e){try{if(!(null==e?void 0:e.id)||!(null==e?void 0:e.msisdn)||!(null==e?void 0:e.amount))return void console.error("Missing required Collection JSON fields:",e);if(!r.Amount.isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.Amount.isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.Amount.isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let n,o;if(e.serviceFee){const t=r.Amount.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);n=t.numericValue.toString()}if(e.postedAmount){const t=r.Amount.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);o=t.numericValue.toString()}const a={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:n,postedAmount:o,reference:e.reference,partnerReference:e.partnerReference,payerName:e.payerName,payerReference:e.payerReference,merchantName:e.merchantName,merchantReference:e.merchantReference,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 te(a)}catch(e){return void console.error("Error creating Collection from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=te.fromJSON(r);if(!e)return;t.push(e)}return t}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,payerName:this.payerName,payerReference:this.payerReference,merchantName:this.merchantName,merchantReference:this.merchantReference,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 re extends l{static create(){return new re}static fromFilters(e){return(new re).applyFilters(e)}static fromUrlParams(e){try{const t=Q.collectionURLQueryParams.parse(e),r=Q.collectionFilters.parse(t);return re.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 re.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return re.fromSearchParams(t)}static from(e){try{return null==e?new re:l.is(e)?new re(e.options):e instanceof URLSearchParams?re.fromSearchParams(e):this.isStringRecord(e)?re.fromUrlParams(e):re.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a CollectionQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereStatus(e){return this.where("status",e)}whereChannel(e){return this.where("channel",e)}wherePending(){return this.whereStatus(exports.COLLECTION_STATUS.PENDING_ACK)}whereSuccessful(){return this.whereStatus(exports.COLLECTION_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("status",[exports.COLLECTION_STATUS.PAYMENT_REJECTED,exports.COLLECTION_STATUS.GENERIC_FAILURE,exports.COLLECTION_STATUS.INSUFFICIENT_FUNDS,exports.COLLECTION_STATUS.PROVIDER_FAILED])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereSender(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereWalletId(e){return this.whereContains("walletId",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.walletId&&this.whereWalletId(e.walletId),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,walletId:e.walletId,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.walletId||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.walletId&&e.push(`Wallet ID: ${t.walletId}`),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"walletId":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}return e}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidChannel(e){return Object.values(exports.COLLECTION_CHANNEL).includes(e)}isValidStatus(e){return Object.values(exports.COLLECTION_STATUS).includes(e)}}var ne,oe;exports.PAYOUT_STATUS=void 0,(ne=exports.PAYOUT_STATUS||(exports.PAYOUT_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",ne.GENERIC_FAILURE="GENERIC_FAILURE",ne.WALLET_DEBITED="WALLET_DEBITED",ne.PAYMENT_REJECTED="PAYMENT_REJECTED",ne.PENDING="PENDING",ne.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",ne.PENDING_ACK="PENDING_ACK",ne.REVERSED="REVERSED",ne.INVALID_SERVICE="INVALID_SERVICE",ne.INVALID_NUMBER="INVALID_NUMBER",ne.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",ne.THIRDPARTY_FAILED="THIRDPARTY_FAILED",ne.PROVIDER_FAILED="PROVIDER_FAILED",exports.MOBILE_PAYOUT_CHANNEL=void 0,(oe=exports.MOBILE_PAYOUT_CHANNEL||(exports.MOBILE_PAYOUT_CHANNEL={})).AIRTEL="TZ-AIRTEL-B2C",oe.VODACOM="TZ-VODACOM-B2C",oe.TIGO="TZ-TIGO-B2C",oe.HALOTEL="TZ-HALOTEL-B2C",oe.SAFARICOM="TZ-SAFARICOM-B2C",exports.BANK_PAYOUT_CHANNEL=void 0,(exports.BANK_PAYOUT_CHANNEL||(exports.BANK_PAYOUT_CHANNEL={})).BANK="TZ-BANK-B2C";const ae=e.z.nativeEnum(exports.PAYOUT_STATUS),se=e.z.nativeEnum(exports.MOBILE_PAYOUT_CHANNEL),ie=e.z.nativeEnum(exports.BANK_PAYOUT_CHANNEL),ce=e.z.union([se,ie]),ue={payout:e.z.object({id:e.z.string().min(1),statusCode:e.z.string(),statusCodeText:ae,statusDescription:e.z.string(),countryCode:e.z.string(),serviceCode:ce,amount:e.z.number().min(0),serviceFee:e.z.string().optional(),postedAmount:e.z.string().optional(),walletId:e.z.string().optional(),msisdn:e.z.string().min(1),narration:e.z.string(),currencyCode:e.z.string(),recipientNames:e.z.string().optional(),transactionRef:e.z.string(),transactionDate:e.z.string().datetime(),externalId:e.z.string().nullable().optional(),cbaReferenceNo:e.z.string().optional(),beepTransactionId:e.z.string().optional(),receiptNumber:e.z.string().optional(),createdAt:e.z.string().datetime(),reversedTransactionId:e.z.string().nullable().optional(),transactionId:e.z.string(),serviceFeeTransactionId:e.z.string().optional(),isReconciled:e.z.number().optional(),requestId:e.z.string().optional(),notes:e.z.string().optional(),updatedAt:e.z.string().datetime().optional()}),payoutFilters:e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(1e4).default(20),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().optional(),endDate:e.z.string().datetime().optional(),msisdn:e.z.string().optional(),accountNo:e.z.string().optional(),walletId:e.z.string().optional(),id:e.z.string().optional(),ref:e.z.string().optional(),channel:ce.optional(),status:ae.optional(),minAmount:e.z.number().min(0).optional(),maxAmount:e.z.number().min(0).optional(),search:e.z.string().optional()}),payoutURLQueryParams:e.z.object({page:e.z.string().transform(e=>parseInt(e)||1).optional(),limit:e.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().optional(),endDate:e.z.string().optional(),msisdn:e.z.string().optional(),accountNo:e.z.string().optional(),walletId:e.z.string().optional(),id:e.z.string().optional(),ref:e.z.string().optional(),channel:e.z.string().refine(e=>Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK).transform(e=>e).optional(),status:e.z.string().refine(e=>Object.values(exports.PAYOUT_STATUS).includes(e)).transform(e=>e).optional(),minAmount:e.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:e.z.string().transform(e=>parseFloat(e)).optional(),search:e.z.string().optional()}),payoutStatus:ae,payoutChannel:ce,mobileChannel:se,bankChannel:ie,walletSummary:e.z.object({balance:e.z.number(),currency:e.z.string(),lastUpdated:e.z.string().datetime()}),transactionSummary:e.z.object({yesterday:e.z.number(),today:e.z.number(),thisMonth:e.z.number(),lastMonth:e.z.number()}),pagination:e.z.object({page:e.z.number(),limit:e.z.number(),total:e.z.number(),totalPages:e.z.number(),hasNext:e.z.boolean(),hasPrev:e.z.boolean()})},le=A().router({getPayouts:{method:"GET",path:"",query:ue.payoutURLQueryParams,responses:{200:e.z.object({results:e.z.array(ue.payout),total:e.z.number()}),401:B.unauthorizedError,403:B.forbiddenError,500:B.serverError},summary:"List payouts",description:"Retrieve a paginated list of payouts with optional filtering"},getPayout:{method:"GET",path:"/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:ue.payout,401:B.unauthorizedError,403:B.forbiddenError,404:B.notFoundError,500:B.serverError},summary:"Get payout details",description:"Retrieve detailed information about a specific payout"},getPayoutSummary:{method:"GET",path:"/summary",responses:{200:B.transactionSummary,401:B.unauthorizedError,403:B.forbiddenError,500:B.serverError},summary:"Get payout summary",description:"Retrieve payout statistics including yesterday, today, this month, and last month totals"}}),de={[exports.PAYOUT_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[exports.PAYOUT_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.PAYOUT_STATUS.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[exports.PAYOUT_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Check payment details and try again"},[exports.PAYOUT_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE]:{label:"Insufficient Balance",description:"Insufficient funds are available to process the payment",category:"failed",color:"error",userFriendlyMessage:"Insufficient funds to complete the payment"},[exports.PAYOUT_STATUS.THIRDPARTY_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.PROVIDER_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM]:{label:"Amount Exceeds Limit",description:"Payment amount exceeds the maximum allowed limit",category:"failed",color:"error",userFriendlyMessage:"Payment amount exceeds the allowed limit"},[exports.PAYOUT_STATUS.WALLET_DEBITED]:{label:"Wallet Debited",description:"Wallet has been debited but payment is not yet complete",category:"failed",color:"error",userFriendlyMessage:"Payment incomplete - wallet debited but recipient may not have received funds"},[exports.PAYOUT_STATUS.REVERSED]:{label:"Payment Reversed",description:"Payment has been reversed and funds returned",category:"failed",color:"error",userFriendlyMessage:"Payment was reversed and funds have been returned"},[exports.PAYOUT_STATUS.INVALID_SERVICE]:{label:"Invalid Service",description:"The requested payment service is not valid or available",category:"failed",color:"error",userFriendlyMessage:"Selected payment service is not available"},[exports.PAYOUT_STATUS.INVALID_NUMBER]:{label:"Invalid Number",description:"The number used is either barred or invalid",category:"failed",color:"error",userFriendlyMessage:"Recipient’s number is invalid, inactive, or temporarily blocked."}},me={[exports.MOBILE_PAYOUT_CHANNEL.AIRTEL]:Y.AIRTEL,[exports.MOBILE_PAYOUT_CHANNEL.VODACOM]:Y.VODACOM,[exports.MOBILE_PAYOUT_CHANNEL.TIGO]:Y.TIGO,[exports.MOBILE_PAYOUT_CHANNEL.HALOTEL]:Y.HALOTEL,[exports.MOBILE_PAYOUT_CHANNEL.SAFARICOM]:Y.SAFARICOM};function he(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)}function pe(e){return e===exports.BANK_PAYOUT_CHANNEL.BANK}class fe{constructor(e){var t,n;this._originalData=Object.assign({},e);let o="TZS";r.CurrencyValidation.isCurrencyCode(e.currencyCode)&&(o=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=null!==(t=r.Amount.from(e.amount,o))&&void 0!==t?t:r.Amount.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!==(n=r.Amount.from(e.serviceFee,o))&&void 0!==n?n:r.Amount.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?r.Amount.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}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===exports.PAYOUT_STATUS.PAYMENT_ACCEPTED}isFailed(){return Object.entries(de).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.statusCodeText)}getStatusInfo(){return de[this.statusCodeText]}getChannelInfo(){if(he(this.serviceCode))return me[this.serviceCode];if(pe(this.serviceCode)){const e=this.msisdn.split(":")[0];if(e&&r.BankValidation.validateSwiftCodeForAnyCountry(e)){const t=r.BankValidation.getCountryFromSwiftCode(e);if(t)try{return r.Bank.from(e,t)}catch(t){console.warn(`Failed to create Bank instance for SWIFT code ${e}:`,t)}}if(this.swiftCode&&r.BankValidation.validateSwiftCodeForAnyCountry(this.swiftCode)){const e=r.BankValidation.getCountryFromSwiftCode(this.swiftCode);if(e)try{return r.Bank.from(this.swiftCode,e)}catch(e){console.warn(`Failed to create Bank instance for SWIFT code ${this.swiftCode}:`,e)}}}}getAccountNumber(){try{if(he(this.serviceCode))return this.msisdn;if(pe(this.serviceCode)){return this.msisdn.split(":")[1]||this.msisdn}}catch(e){console.warn("failed to get the account number from payout msisdn: ",this.msisdn)}return this.msisdn}getProviderName(){const e=this.getChannelInfo();return he(this.serviceCode)&&e?e.networkOperator:r.Bank.is(e)?e.shortName:"Bank Transfer"}static from(e){try{return(null==e?void 0:e.id)&&(null==e?void 0:e.msisdn)&&void 0!==(null==e?void 0:e.amount)?new fe(e):void console.error("Missing required Payout fields:",e)}catch(e){return void console.error("Error creating Payout:",e)}}static createMany(e){const t=[];for(const r of e){const e=fe.from(r);if(!e)return;t.push(e)}return t}static fromJSON(e){try{if(!(null==e?void 0:e.id)||!(null==e?void 0:e.msisdn)||!(null==e?void 0:e.amount))return void console.error("Missing required Payout JSON fields:",e);if(!r.Amount.isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.Amount.isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.Amount.isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let n,o;if(e.serviceFee){const t=r.Amount.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);n=t.numericValue}if(e.postedAmount){const t=r.Amount.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);o=t.numericValue.toString()}const a={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:n,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(a)}catch(e){return void console.error("Error creating Payout from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=fe.fromJSON(r);if(!e)return;t.push(e)}return t}toJSON(){var e,t,r;return{id:this.id,serviceCode:this.serviceCode,msisdn:this.msisdn,amount:this.amount.toJSON(),transactionDate:this.transactionDate.toISOString(),statusDescription:this.statusDescription,statusCodeText:this.statusCodeText,transactionId:this.transactionId,transactionRef:this.transactionRef,recipientNames:this.recipientNames,narration:this.narration,serviceFee:null===(e=this.serviceFee)||void 0===e?void 0:e.toJSON(),notes:this.notes,swiftCode:this.swiftCode,createdAt:this.createdAt.toISOString(),updatedAt:null===(t=this.updatedAt)||void 0===t?void 0:t.toISOString(),statusCode:this.statusCode,countryCode:this.countryCode,postedAmount:null===(r=this.postedAmount)||void 0===r?void 0:r.toJSON(),walletId:this.walletId,currencyCode:this.currencyCode,externalId:this.externalId,cbaReferenceNo:this.cbaReferenceNo,beepTransactionId:this.beepTransactionId,receiptNumber:this.receiptNumber,reversedTransactionId:this.reversedTransactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,isReconciled:this.isReconciled,requestId:this.requestId}}}class Ae extends l{static create(){return new Ae}static fromFilters(e){return(new Ae).applyFilters(e)}static fromUrlParams(e){try{const t=ue.payoutURLQueryParams.parse(e),r=ue.payoutFilters.parse(t);return Ae.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return Ae.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Ae.fromSearchParams(t)}static from(e){return null==e?new Ae:l.is(e)?new Ae(e.options):e instanceof URLSearchParams?Ae.fromSearchParams(e):this.isStringRecord(e)?Ae.fromUrlParams(e):Ae.fromFilters(e)}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereStatus(e){return this.where("statusCodeText",e)}whereChannel(e){return this.where("serviceCode",e)}wherePending(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK])}whereSuccessful(){return this.whereStatus(exports.PAYOUT_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PAYMENT_REJECTED,exports.PAYOUT_STATUS.GENERIC_FAILURE,exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM,exports.PAYOUT_STATUS.INVALID_SERVICE,exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE,exports.PAYOUT_STATUS.THIRDPARTY_FAILED,exports.PAYOUT_STATUS.WALLET_DEBITED,exports.PAYOUT_STATUS.REVERSED])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereRecipient(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereWalletId(e){return this.whereContains("walletId",e)}whereReference(e){return this.whereContains("transactionRef",e)}whereMobile(){return this.whereIn("serviceCode",Object.values(exports.MOBILE_PAYOUT_CHANNEL))}whereBank(){return this.whereChannel(exports.BANK_PAYOUT_CHANNEL.BANK)}whereSearch(e){return this.where("search",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.status&&this.whereStatus(e.status),e.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereRecipient(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.walletId&&this.whereWalletId(e.walletId),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,accountNo:e.accountNo,walletId:e.walletId,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.accountNo||e.walletId||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.accountNo&&e.push(`Account: ${t.accountNo}`),t.walletId&&e.push(`Wallet ID: ${t.walletId}`),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"accountNo":case"walletId":case"transactionRef":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}return e}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidChannel(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK}isValidStatus(e){return Object.values(exports.PAYOUT_STATUS).includes(e)}}const ye={localTransferRequest:e.z.object({amount:e.z.number().int().positive(),from:e.z.string().min(1),to:e.z.string().min(1),description:e.z.string().min(1)}),localTransferResponse:e.z.object({transactionId:e.z.string(),from:e.z.string(),to:e.z.string(),transactionDate:e.z.string(),narration:e.z.string(),amount:e.z.number(),transactionRef:e.z.string()})},ge=A().router({localTransfer:{method:"POST",path:"/local-transfer",body:ye.localTransferRequest,responses:{201:ye.localTransferResponse,400:B.validationError,401:B.unauthorizedError,404:B.notFoundError,500:B.serverError},summary:"Local transfer",description:"Transfer funds locally between wallets."}});var Ne;exports.WALLET_TYPE=void 0,(Ne=exports.WALLET_TYPE||(exports.WALLET_TYPE={})).VENDOR="Vendor",Ne.DEFAULT_DISBURSEMENT="DEFAULT DISBURSEMENT",Ne.DEFAULT_COLLECTION="DEFAULT COLLECTION",Ne.COLLECTION="COLLECTION",Ne.DISBURSEMENT="DISBURSEMENT";const Ee=e.z.nativeEnum(exports.WALLET_TYPE),ve=e.z.object({id:e.z.string().min(1),accountNo:e.z.string().min(1),accountName:e.z.string().min(1),shadowAccountNo:e.z.string().nullish(),externalId:e.z.string().nullish(),reference:e.z.string().nullish(),type:e.z.string().min(1),vendorId:e.z.string().nullish(),balance:e.z.number(),minBalance:e.z.union([e.z.number(),e.z.string()]),approvalLimit:e.z.union([e.z.number(),e.z.string()]),currency:e.z.string().min(1),countryCode:e.z.string().min(1),createdAt:e.z.string().min(1),updatedAt:e.z.string().min(1)}),Te=e.z.object({availableBalance:e.z.number(),currentBalance:e.z.number(),accountStatus:e.z.string().min(1),accountNo:e.z.string().min(1),accountName:e.z.string().min(1)}),Oe={wallet:ve,walletType:Ee,walletPathParams:e.z.object({accountNo:e.z.string().min(1)}),walletBalance:Te,walletStatementQuery:e.z.object({startDate:e.z.string().regex(/^\d{4}-\d{2}-\d{2}$/),endDate:e.z.string().regex(/^\d{4}-\d{2}-\d{2}$/)})},Se=A().router({listWallets:{method:"GET",path:"",responses:{200:e.z.array(Oe.wallet),401:B.unauthorizedError,500:B.serverError},summary:"List wallets",description:"Retrieve all wallets linked to the account across supported currencies."},getWalletInfo:{method:"GET",path:"/:accountNo",pathParams:e.z.object({accountNo:e.z.string().min(1)}),responses:{200:Oe.wallet,401:B.unauthorizedError,500:B.serverError},summary:"Get wallet info",description:"Retrieve wallet metadata including balance, currency, and type for a specific wallet."},getWalletBalance:{method:"GET",path:"/:accountNo/balance",pathParams:Oe.walletPathParams,responses:{200:Oe.walletBalance,401:B.unauthorizedError,404:B.notFoundError,500:B.serverError},summary:"Get wallet balance",description:"Retrieve the current and available balance for a specific wallet account number."},getWalletStatement:{method:"GET",path:"/:accountNo/statement",pathParams:Oe.walletPathParams,query:Oe.walletStatementQuery,responses:{200:e.z.array(B.statementEntry),400:B.validationError,401:B.unauthorizedError,404:B.notFoundError,500:B.serverError},summary:"Get wallet statement",description:"Retrieve statement entries for a specific wallet within a date range."}});class Ce{constructor(e){var t,n,o;this._originalData=Object.assign({},e);let a="TZS";r.CurrencyValidation.isCurrencyCode(e.currency)?a=e.currency:"KSH"===e.currency&&(a="KES"),this.id=e.id,this.accountNo=e.accountNo,this.accountName=e.accountName,this.shadowAccountNo=e.shadowAccountNo,this.externalId=e.externalId,this.reference=e.reference,this.type=e.type,this.vendorId=e.vendorId,this.balance=null!==(t=r.Amount.from(e.balance,a))&&void 0!==t?t:r.Amount.from(0,a),this.minBalance=null!==(n=r.Amount.from(this.parseAmountValue(e.minBalance),a))&&void 0!==n?n:r.Amount.from(0,a),this.approvalLimit=null!==(o=r.Amount.from(this.parseAmountValue(e.approvalLimit),a))&&void 0!==o?o:r.Amount.from(0,a),this.currency=a,this.countryCode=e.countryCode,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}getOriginalData(){return this._originalData}parseAmountValue(e){if("number"==typeof e)return e;const t=parseFloat(e);return Number.isNaN(t)?0:t}isCollectionWallet(){return this.type.includes("COLLECTION")}isDisbursementWallet(){return this.type.includes("DISBURSEMENT")}isDefaultWallet(){return this.type.startsWith("DEFAULT")}static from(e){return new Ce(e)}static createMany(e){const t=[];try{for(const r of e)t.push(Ce.from(r));return t}catch(e){return void console.error("Error creating Wallets:",e)}}toJSON(){return{id:this.id,accountNo:this.accountNo,accountName:this.accountName,shadowAccountNo:this.shadowAccountNo,externalId:this.externalId,reference:this.reference,type:this.type,vendorId:this.vendorId,balance:this.balance.toJSON(),minBalance:this.minBalance.toJSON(),approvalLimit:this.approvalLimit.toJSON(),currency:this.currency,countryCode:this.countryCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}static fromJSON(e){try{if(!r.Amount.isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure in Wallet JSON:",e);if(!r.Amount.isAmountJSON(e.minBalance)||!r.Amount.isAmountJSON(e.approvalLimit))return void console.error("Invalid wallet threshold AmountJson structure in Wallet JSON:",e);const t=r.Amount.fromJSON(e.balance),n=r.Amount.fromJSON(e.minBalance),o=r.Amount.fromJSON(e.approvalLimit);return t&&n&&o?new Ce({id:e.id,accountNo:e.accountNo,accountName:e.accountName,shadowAccountNo:e.shadowAccountNo,externalId:e.externalId,reference:e.reference,type:e.type,vendorId:e.vendorId,balance:t.numericValue,minBalance:n.numericValue,approvalLimit:o.numericValue,currency:e.currency,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt}):void console.error("Failed to reconstruct balance Amount from JSON:",e)}catch(e){return void console.error("Error creating Wallet from JSON:",e)}}}exports.APIError=c,exports.AuthDTOSchemas=$,exports.AuthRepository=class extends M{constructor(e){super("auth",k,e)}async login(e){const t={identity:e.email,password:e.password},r=await this.client.login({body:t}),n=this.handleResponse(r,201),o=q.from(n);if(!o)throw new Error("Invalid user data received from server");return{user:o,token:n.token}}async updatePassword(e){const t=await this.client.updatePassword({body:e});if(201!==t.status){if(400===t.status)throw new Error("Validation error");if(401===t.status)throw new Error("Unauthorized");throw new Error("Failed to update password")}return!0}},exports.BaseRepository=M,exports.COLLECTION_STATUS_INFO=X,exports.Collection=te,exports.CollectionDTOSchemas=Q,exports.CollectionQuery=re,exports.CollectionRepository=class extends M{constructor(e){super("collection",Z,e)}async getCollections(e){try{const t=re.from(e),r=t.build(),n=await this.client.getCollections({query:r}),o=this.handleResponse(n,200),a=t.toFilters(),s={page:a.page,limit:a.limit,total:o.total,totalPages:o.total>0?Math.ceil(o.total/a.limit):0,hasNext:a.page*a.limit<o.total,hasPrev:a.page>1},i=te.createMany(o.results);if(!i)throw new Error("Invalid collection data received from server");return{collections:i,pagination:s}}catch(e){throw new Error(`Failed to fetch collections: ${e instanceof Error?e.message:"Unknown error"}`)}}async getCollectionsFromRequest(e){const t=re.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),n=te.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=J.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}},exports.CommonSchemas=B,exports.MobileChannels=Y,exports.PAYOUT_STATUS_INFO=de,exports.Payout=fe,exports.PayoutDTOSchemas=ue,exports.PayoutQuery=Ae,exports.PayoutRepository=class extends M{constructor(e){super("payout",le,e)}async getPayouts(e){try{const t=Ae.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),o=this.handleResponse(n,200),a=t.toFilters(),s={page:a.page,limit:a.limit,total:o.total,totalPages:o.total>0?Math.ceil(o.total/a.limit):0,hasNext:a.page*a.limit<o.total,hasPrev:a.page>1},i=fe.createMany(o.results);if(!i)throw new Error("Invalid payout data received from server");return{payouts:i,pagination:s}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=Ae.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),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=J.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}},exports.QUERY_BUILDER_TYPE=u,exports.QueryBuilder=l,exports.StatementEntry=V,exports.TransactionDTOSchemas=ye,exports.TransactionRepository=class extends M{constructor(e){super("transaction",ge,e)}async localTransfer(e){const t=await this.client.localTransfer({body:e});return this.handleResponse(t,201)}},exports.TransactionSummary=J,exports.User=q,exports.Wallet=Ce,exports.WalletDTOSchemas=Oe,exports.WalletInfo=j,exports.WalletRepository=class extends M{constructor(e){super("wallet",Se,e)}async listWallets(){const e=await this.client.listWallets(),t=this.handleResponse(e,200),r=Ce.createMany(t);if(!r)throw new Error("Invalid wallet data received from server");return r}async getWalletInfo(e){const t=await this.client.getWalletInfo({params:{accountNo:e}}),r=this.handleResponse(t,200);return Ce.from(r)}async getWalletBalance(e){const t=await this.client.getWalletBalance({params:{accountNo:e}}),r=this.handleResponse(t,200);return j.from(r)}async getWalletStatement(e){const t=await this.client.getWalletStatement({params:{accountNo:e.accountNo},query:{startDate:this.formatStatementDate(e.startDate),endDate:this.formatStatementDate(e.endDate)}}),r=this.handleResponse(t,200),n=V.createMany(r);if(!n)throw new Error("Invalid statement entry data received from server");return n}formatStatementDate(e){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Error("Invalid statement date provided.");return e.toISOString().slice(0,10)}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return e;const t=new Date(e);if(Number.isNaN(t.getTime()))throw new Error(`Invalid statement date: ${e}`);return t.toISOString().slice(0,10)}},exports.authContract=k,exports.collectionContract=Z,exports.payoutContract=le,exports.statementEntrySchema=U,exports.transactionContract=ge,exports.walletContract=Se;
2
2
  //# sourceMappingURL=index.cjs.js.map