@temboplus/tembo-dashboard 0.0.6 → 0.0.7

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