@temboplus/afloat 0.1.56 → 0.1.57
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 +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/models/user.model.d.ts +18 -35
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("zod"),t=require("@temboplus/frontend-core"),r=require("uuid"),n=require("zustand");class o 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 o.schema.safeParse(e).success}static unknown(e){return new o({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()})}}const a={Profile:{ViewCurrent:"profile.getCurrent",Update:"profile.update"},Contact:{View:"contact.findById",List:"contact.findAll",Create:"contact.create",Update:"contact.update",Delete:"contact.delete"},Payment:{View:"payment.findById",List:"payment.findAll",Create:"payment.create"},Payout:{View:"payout.findById",List:"payout.findAll",Create:"payout.create",Approve:"payout.approve"},Transfer:{View:"transfer.findById",List:"transfer.findAll",Create:"transfer.create",Approve:"transfer.approve"},Wallet:{ViewBalance:"wallet.getBalance",ViewStatement:"wallet.getStatement"},Role:{ViewRoles:"role.findAll",ViewRole:"role.findById"},UserManagement:{ViewUsers:"login.findAll",ViewUser:"login.findById",CreateUser:"login.create",UpdateUser:"login.update",ArchiveUser:"login.archive",UnArchiveUser:"login.unarchive",ResetPassword:"login.resetPassword"}};class s extends Error{constructor(e){var t;super(null!==(t=e.message)&&void 0!==t?t:`Missing required permissions: ${e.requiredPermissions.join(", ")}`),this.name="PermissionError",this.requiredPermissions=e.requiredPermissions}static is(t){const r=e.z.union([e.z.enum(Object.values(a.Profile)),e.z.enum(Object.values(a.Contact)),e.z.enum(Object.values(a.Payment)),e.z.enum(Object.values(a.Payout)),e.z.enum(Object.values(a.Transfer)),e.z.enum(Object.values(a.Wallet))]);return e.z.object({name:e.z.literal("PermissionError"),message:e.z.string(),requiredPermissions:e.z.array(r)}).safeParse(t).success}}var i;exports.ContactType=void 0,(i=exports.ContactType||(exports.ContactType={})).Bank="Bank",i.Mobile="Mobile";const c=e.z.nativeEnum(exports.ContactType),d=e.z.object({displayName:e.z.string().min(1,"Display name is required"),accountNo:e.z.string().min(1,"Account number is required"),channel:e.z.string().min(1,"Channel is required"),countryCode:e.z.string().default("TZ"),type:c}),u={contactDTO:e.z.object({id:e.z.string().min(1,"Contact id is required"),profileId:e.z.string(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime()}).merge(d),contactInputDTO:d,contactType:c};class l extends Error{constructor(e,t={}){super(e),this.context=t,this.name="ContactInfoError"}}class m{constructor(e,t){this.type=e,this.countryCode=t}}class p extends m{constructor(e,r,n){if(super(exports.ContactType.Mobile,r.countryCode),this.name=e,this.phoneNumber=r,!(null==e?void 0:e.trim()))throw new l("Name is required and cannot be empty",{operation:"constructor",countryCode:r.countryCode,phoneNumber:r.e164Format});if(!(null==r?void 0:r.validate()))throw new l("Invalid phone number",{operation:"constructor",countryCode:r.countryCode,phoneNumber:r.e164Format});if(n){if(!t.MNOUtils.isValidMNOForCountry(n,r.countryCode)){const e=t.MNOUtils.getCountryMNOs(r.countryCode).map(e=>e.id);throw new l(`Invalid MNO ${n} for country ${r.countryCode}. Valid MNOs: ${e.join(", ")}`,{phoneNumber:r.e164Format,countryCode:r.countryCode,mnoId:n,operation:"constructor"})}if(!t.MNOUtils.requiresExplicitMNO(r.countryCode)&&!t.MNOUtils.validateMNOForPhoneNumber(r.e164Format,n,r.countryCode))throw new l(`MNO ${n} is not consistent with phone number ${r.e164Format}`,{phoneNumber:r.e164Format,countryCode:r.countryCode,mnoId:n,operation:"constructor"});this.mnoId=n}else{if(t.MNOUtils.requiresExplicitMNO(r.countryCode))throw new l(`MNO must be explicitly provided for phone numbers in ${r.countryCode} due to Mobile Number Portability`,{phoneNumber:r.e164Format,countryCode:r.countryCode,operation:"constructor"});const e=t.MNOUtils.getMNOByPhoneNumber(r.e164Format,r.countryCode);if(!(null==e?void 0:e.id))throw new l(`Failed to determine MNO for phone number ${r.e164Format}`,{phoneNumber:r.e164Format,countryCode:r.countryCode,operation:"constructor"});this.mnoId=e.id}}static fromContactDTO(e){if("Mobile"!==e.type)return;const r=e.accountNo,n=e.countryCode;if(!t.CountryValidation.isISO2CountryCode(n))return void console.error(`Invalid country code: ${n}`);const o=t.PhoneNumber.from(r,{defaultCountry:n});if(o)try{let r;if(e.channel&&"string"==typeof e.channel)if(t.MNOUtils.isValidMNOForCountry(e.channel,n))r=e.channel;else{if(!t.MNOUtils.requiresExplicitMNO(n)){const e=t.MNOUtils.getMNOByPhoneNumber(o.e164Format,n);(null==e?void 0:e.id)?r=e.id:console.warn(`Failed to auto-detect MNO for phone number ${o.e164Format}`)}console.warn(`Invalid MNO ${e.channel} for country ${n}`)}return new p(e.displayName,o,r)}catch(e){return void console.error(`Failed to create MobileContactInfo: ${e}`)}else console.error(`Failed to parse phone number ${r} for country ${n}`)}static fromPayoutDTO(e){try{if(!t.CountryValidation.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const r=t.PhoneNumber.from(e.msisdn,{defaultCountry:e.countryCode});if(!r)return void console.error(`Failed to parse phone number: ${e.msisdn}`);let n;return e.channel&&"string"==typeof e.channel&&(t.MNOUtils.isValidMNOForCountry(e.channel,e.countryCode)?n=e.channel:console.warn(`Invalid MNO ${e.channel} for country ${e.countryCode} in PayoutDTO`)),new p(e.payeeName,r,n)}catch(t){return void console.error("Failed to create MobileContactInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const r=e;if("string"!=typeof r.name||!r.name.trim())return!1;let n;if("string"==typeof r.phoneNumber)n=t.PhoneNumber.from(r.phoneNumber);else if("object"==typeof r.phoneNumber){const e=r.phoneNumber;t.PhoneNumber.is(e)&&(n=t.PhoneNumber.from(e.e164Format))}if(!n)return!1;const o=r.mnoId;if("string"!=typeof o)return!1;if(!t.MNOUtils.isValidMNOForCountry(o,n.countryCode))return!1;if(t.MNOUtils.requiresExplicitMNO(n.countryCode))return!0;{const e=t.MNOUtils.getMNOByPhoneNumber(n.e164Format,n.countryCode);return(null==e?void 0:e.id)===o}}validate(){var e,r;try{return!!(null===(e=this.name)||void 0===e?void 0:e.trim())&&(!!(null===(r=this.phoneNumber)||void 0===r?void 0:r.validate())&&(!!t.MNOUtils.isValidMNOForCountry(this.mnoId,this.countryCode)&&(!!t.MNOUtils.requiresExplicitMNO(this.countryCode)||t.MNOUtils.validateMNOForPhoneNumber(this.phoneNumber.e164Format,this.mnoId,this.countryCode))))}catch(e){return!1}}getValidationDetails(){var e,r;const n=[],o=[];if((null===(e=this.name)||void 0===e?void 0:e.trim())||n.push("Name is required"),(null===(r=this.phoneNumber)||void 0===r?void 0:r.validate())||n.push("Phone number is invalid"),t.MNOUtils.isValidMNOForCountry(this.mnoId,this.countryCode)||n.push(`Invalid MNO ${this.mnoId} for country ${this.countryCode}`),!t.MNOUtils.requiresExplicitMNO(this.countryCode)){const e=t.MNOUtils.getMNOByPhoneNumber(this.phoneNumber.e164Format,this.countryCode);(null==e?void 0:e.id)!==this.mnoId&&o.push("MNO doesn't match phone number prefix - possible data inconsistency")}return{isValid:0===n.length,errors:n,warnings:o}}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(t.PhoneNumberFormat.INTERNATIONAL_NUMERIC)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){var e,r;const n=t.MNOUtils.getMNOById(this.mnoId,this.countryCode);return null!==(r=null!==(e=null==n?void 0:n.mobileMoneyService)&&void 0!==e?e:null==n?void 0:n.displayName)&&void 0!==r?r:this.mnoId}}class h extends m{constructor(e,r,n){if(super(exports.ContactType.Bank,r.countryCode),this.accName=e,this.bank=r,this.accNo=n,!t.BankValidation.validateAccountName(e))throw new l("Invalid account name",{operation:"constructor",countryCode:r.countryCode});if(!t.BankValidation.validateAccountNumber(n,r.countryCode))throw new l("Invalid account number",{operation:"constructor",countryCode:r.countryCode})}static fromContactDTO(e){if("Bank"!==e.type)return;const r=e.channel,n=e.countryCode;if(t.CountryValidation.isISO2CountryCode(n))if(r&&"string"==typeof r)if(t.BankValidation.validateSwiftCode(r,n))try{const o=t.Bank.from(r,n);if(!o)throw new Error(`Bank with SWIFT code ${r} not found`);return new h(e.displayName,o,e.accountNo)}catch(e){return void console.error(`Failed to create BankContactInfo: ${e}`)}else console.error(`Invalid SWIFT code ${r} for country ${n}`);else console.error("SWIFT code is required for bank contacts");else console.error(`Invalid country code: ${n}`)}static fromPayoutDTO(e){try{if(!t.CountryValidation.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const r=e.msisdn.trim().split(":");if(2!==r.length)return void console.error("Invalid PayoutDTO format for bank - expected 'swiftcode:accountno'");const[n,o]=r;if(!t.BankValidation.validateSwiftCode(n,e.countryCode))return void console.error(`Invalid SWIFT code ${n} for country ${e.countryCode}`);const a=t.Bank.from(n,e.countryCode);return a?new h(e.payeeName,a,o):void console.error(`Bank with SWIFT code ${n} not found`)}catch(t){return void console.error("Failed to create BankContactInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const r=e;if("string"!=typeof r.accName)return!1;if("string"!=typeof r.accNo)return!1;if(!r.bank||!t.Bank.is(r.bank))return!1;const n=r.accName,o=r.accNo,a=r.bank,s=t.BankValidation.validateAccountName(n),i=t.BankValidation.validateAccountNumber(o,a.countryCode);return s&&i}validate(){try{return t.BankValidation.validateAccountName(this.accName)&&t.BankValidation.validateAccountNumber(this.accNo,this.bank.countryCode)&&t.Bank.is(this.bank)}catch(e){return!1}}get accountName(){return this.accName}get accountNumber(){return this.accNo}get accountNameLabel(){return"Acc. Name"}get accountNumberLabel(){return"Bank Acc. No."}get channelLabel(){return"Bank"}get channelId(){return this.bank.swiftCode}get channelName(){return this.bank.shortName}}class y{constructor(e){this.data=u.contactDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get displayName(){return this.data.displayName}get type(){return this.data.type}get createdAt(){return new Date(this.data.createdAt)}get updatedAt(){return new Date(this.data.updatedAt)}get info(){return this.data.type===exports.ContactType.Mobile?p.fromContactDTO(this.data):this.data.type===exports.ContactType.Bank?h.fromContactDTO(this.data):void 0}get accNo(){const e=this.info;return e?e.accountNumber:this.data.accountNo}get accName(){return this.data.displayName}get accNoLabel(){const e=this.info;return e instanceof p?"Phone Number":e instanceof h?"Bank Account Number":"Account Number"}get channelLabel(){const e=this.info;return e instanceof p?"Channel":e instanceof h?"Bank":"Channel"}get accNameLabel(){const e=this.info;return e instanceof p?"Full Name":e instanceof h?"Bank Account Name":"Display Name"}get countryCode(){const e=this.data.countryCode;if(t.CountryValidation.isISO2CountryCode(e))return e;throw new Error(`${this.data.countryCode} is not a valid ISO-2 country code`)}get channelName(){const e=this.info;return e instanceof p||e instanceof h?e.channelName:""}get country(){const e=t.Country.fromCode(this.countryCode);if(!e)throw new Error(`We could not find an associated country for the country code ${this.countryCode}`);return e}static create(e){return new y(e)}static createMany(e){return e.map(e=>new y(e))}static createSafe(e){try{return new y(e)}catch(e){return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=u.contactDTO.safeParse(e);if(!t.success)return!1;return null!==y.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&y.canConstruct(e.data))}toJSON(){return Object.assign({},this.data)}}var g,f,b;exports.PayoutChannel=void 0,(g=exports.PayoutChannel||(exports.PayoutChannel={})).MOBILE="Mobile",g.BANK="Bank",exports.PayoutStatus=void 0,(f=exports.PayoutStatus||(exports.PayoutStatus={})).CREATED="CREATED",f.PENDING="PENDING",f.PAID="PAID",f.FAILED="FAILED",f.REJECTED="REJECTED",f.REVERSED="REVERSED",exports.PayoutApprovalStatus=void 0,(b=exports.PayoutApprovalStatus||(exports.PayoutApprovalStatus={})).PENDING="Pending",b.APPROVED="Approved",b.REJECTED="Rejected";const v=e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string()}),w=e.z.nativeEnum(exports.PayoutStatus),C=e.z.nativeEnum(exports.PayoutApprovalStatus),N=e.z.object({channel:e.z.string(),msisdn:e.z.string(),amount:e.z.coerce.number(),description:e.z.string(),notes:e.z.string().nullish()}),z=N.extend({payeeName:e.z.string()}),O={PayoutDTO:N.extend({id:e.z.string(),profileId:e.z.string(),payeeName:e.z.string(),countryCode:e.z.string().default("TZ").refine(e=>t.CountryValidation.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>t.CurrencyValidation.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),channel:e.z.string(),status:w,statusMessage:e.z.string(),partnerReference:e.z.string().nullish(),createdAt:e.z.coerce.date(),updatedAt:e.z.coerce.date(),actionedAt:e.z.coerce.date().nullish(),approvalStatus:C.nullish(),createdBy:v.nullish(),actionedBy:v.nullish()}),PayoutInputDTO:z,PayoutStatus:w,PayoutApprovalStatus:C,PayoutAuthorizer:v};class I{constructor(e){this.data=O.PayoutDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get payeeName(){return this.data.payeeName}get channel(){return this.data.channel}get msisdn(){return this.data.msisdn}get amount(){return t.Amount.from(this.data.amount,this.data.currencyCode)}get description(){return this.data.description}get notes(){return this.data.notes}get status(){return"Rejected"===this.data.approvalStatus?exports.PayoutStatus.REJECTED:"Approved"===this.data.approvalStatus?"FAILED"===this.data.status?exports.PayoutStatus.FAILED:exports.PayoutStatus.PAID:"Pending"===this.data.approvalStatus?exports.PayoutStatus.PENDING:this.data.status}get statusMessage(){return this.data.statusMessage}get partnerReference(){return this.data.partnerReference}get createdAt(){return this.data.createdAt}get updatedAt(){return this.data.updatedAt}get approvalStatus(){return this.data.approvalStatus}get createdBy(){return this.data.createdBy}get actionedBy(){return this.data.actionedBy}get contactInfo(){const e=p.fromPayoutDTO(this.data),t=h.fromPayoutDTO(this.data);return e||t}static create(e){return new I(e)}static createMany(e){return e.map(e=>new I(e))}static createSafe(e){try{return new I(e)}catch(e){return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=O.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==I.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&I.canConstruct(e.data))}toJSON(){return Object.assign({},this.data)}}const A={profileDTOSchema:e.z.object({id:e.z.string(),firstName:e.z.string().nullish(),lastName:e.z.string().nullish(),displayName:e.z.string(),phone:e.z.string().nullish(),accountNo:e.z.string().min(1),email:e.z.string().email().nullish(),autoApprove:e.z.boolean().nullish()})};class S{static get schema(){return A.profileDTOSchema}constructor(e){this._id=e.id,this._firstName=e.firstName,this._lastName=e.lastName,this._displayName=e.displayName,this._phone=e.phone,this._accountNo=e.accountNo,this._email=e.email,this._autoApprove=e.autoApprove}static create(e){return new S({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove})}get id(){return this._id}get firstName(){return this._firstName}get lastName(){return this._lastName}get displayName(){return this._displayName}get phone(){return this._phone}get accountNo(){return this._accountNo}get email(){return this._email}get autoApprove(){return this._autoApprove}getName(){var e,t;if(this._displayName&&""!==this._displayName.trim())return this._displayName;return`${null!==(e=this._firstName)&&void 0!==e?e:""} ${null!==(t=this._lastName)&&void 0!==t?t:""}`.trim()}toObject(){return{id:this._id,firstName:this._firstName,lastName:this._lastName,displayName:this._displayName,phone:this._phone,accountNo:this._accountNo,email:this._email,autoApprove:this._autoApprove}}toJSON(){return JSON.stringify(this.toObject())}validate(){try{return S.schema.safeParse(this.toObject()).success}catch(e){return console.error("Profile validation error:",e),!1}}static fromJSON(e){try{const t=JSON.parse(e);return S.from(t)}catch(e){return void console.error("Error parsing profile JSON:",e)}}static from(e){try{return e?"object"!=typeof e?void console.error("Data is not an object"):e.id&&e.accountNo&&e.displayName?S.create({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove}):void console.error("Missing required profile fields"):void console.error("Data is null or undefined")}catch(e){return void console.error("Error creating profile from object:",e)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t._id||"string"!=typeof t._displayName||"string"!=typeof t._accountNo)return!1;if(null!==t._firstName&&void 0!==t._firstName&&"string"!=typeof t._firstName)return!1;if(null!==t._lastName&&void 0!==t._lastName&&"string"!=typeof t._lastName)return!1;if(null!==t._email&&void 0!==t._email&&"string"!=typeof t._email)return!1;const r=t._phone;if(null!=r&&"string"!=typeof r)return!1;const n=t._autoApprove;return null==n||"boolean"==typeof n}}class E{constructor(e){const{profile:t,token:r,access:n,resetPassword:o,name:s,identity:i}=e;this.profile=t,this.token=r,this.resetPassword=o,this.name=s,this.identity=i,this.permissionsMap={};for(const e of Object.values(a))"object"==typeof e?Object.values(e).forEach(e=>{this.permissionsMap[e]=n.includes(e)}):this.permissionsMap[e]=n.includes(e)}can(e){var t;return null!==(t=this.permissionsMap[e])&&void 0!==t&&t}getPermissions(){return Object.keys(this.permissionsMap).filter(e=>this.permissionsMap[e])}toObject(){return{profile:this.profile.toObject(),token:this.token,resetPassword:this.resetPassword,name:this.name,identity:this.identity,permissions:this.getPermissions()}}toJSON(){return JSON.stringify(this.toObject())}static fromJSON(e){try{return E.from(JSON.parse(e))}catch(e){return void console.error("Invalid JSON string:",e)}}static from(e){let t,r;if("string"==typeof e)try{t=JSON.parse(e)}catch(e){return void console.error("Invalid JSON string:",e)}else t=e;if(!t)return void console.error("Data is null or undefined.");let n=t.profile;if("string"==typeof n)try{n=JSON.parse(n)}catch(e){return void console.error("Failed to parse profile JSON string:",e)}if(S.is(n))r=n;else{if("object"!=typeof n||null===n)return void console.error("Invalid profile format:",typeof n);if(r=S.from(n),!r)return void console.error("Failed to create Profile from data:",n)}if(!t.token||"string"!=typeof t.token||!t.name||"string"!=typeof t.name||!t.identity||"string"!=typeof t.identity||!Array.isArray(t.permissions)&&!Array.isArray(t.access)||"boolean"!=typeof t.resetPassword)return void console.error("Missing or invalid required User fields:",{token:typeof t.token,name:typeof t.name,identity:typeof t.identity,permissions:Array.isArray(t.permissions),access:Array.isArray(t.access),resetPassword:typeof t.resetPassword});const o=t.access||t.permissions;return new E({profile:r,token:t.token,access:o,resetPassword:t.resetPassword,name:t.name,identity:t.identity})}}const P=e=>e.optional().transform(e=>null!=e?e:void 0),D={walletDTO:e.z.object({id:e.z.string().min(1,{message:"Wallet ID is required."}),profileId:e.z.string().min(1,{message:"Profile ID is required."}),accountNo:e.z.string().min(1,{message:"Account number is required."}),accountName:e.z.string().min(1,{message:"Account name is required."}),channel:e.z.string().min(1,{message:"Channel is required."}),countryCode:e.z.string().default("TZ").refine(e=>t.CountryValidation.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>t.CurrencyValidation.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:e.z.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:e.z.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:e.z.object({id:e.z.string().optional(),profileId:e.z.string().optional(),accountNo:e.z.string().optional(),accountName:e.z.string().optional(),channel:e.z.string().optional(),countryCode:e.z.string().default("TZ").refine(e=>t.ISO2CountryCodesSet.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:e.z.string().default("TZS").refine(e=>{const r=t.Currency.from(e);return void 0!==r&&t.CurrencyCodesSet.has(r.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:e.z.object({accountNo:P(e.z.string()),debitOrCredit:e.z.string().min(1,"Transaction type is required"),tranRefNo:e.z.string().min(1,"Transaction reference is required"),narration:e.z.string().min(1,"Transaction description is required"),txnDate:e.z.coerce.date({errorMap:()=>({message:"Invalid transaction date format"})}),valueDate:e.z.coerce.date({errorMap:()=>({message:"Invalid value date format"})}),amountCredited:e.z.number().min(0,"Credited amount must be non-negative"),amountDebited:e.z.number().min(0,"Debited amount must be non-negative"),balance:e.z.number(),currencyCode:P(e.z.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})};class _{static get schema(){return D.walletDTO}constructor(e){this._id=e.id,this._profileId=e.profileId,this._accountNo=e.accountNo,this._accountName=e.accountName,this._channel=e.channel,this._countryCode=e.countryCode,this._currencyCode=e.currencyCode,this._createdAt=e.createdAt,this._updatedAt=e.updatedAt}static create(e){const t=_.schema.safeParse(e);if(t.success)return new _(t.data);console.error("Wallet data validation failed:",t.error.flatten())}get id(){return this._id}get profileId(){return this._profileId}get accountNo(){return this._accountNo}get accountName(){return this._accountName}get channel(){return this._channel}get countryCode(){return this._countryCode}get currencyCode(){return this._currencyCode}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get createdAtDate(){return new Date(this._createdAt)}get updatedAtDate(){return new Date(this._updatedAt)}toObject(){return{id:this._id,profileId:this._profileId,accountNo:this._accountNo,accountName:this._accountName,channel:this._channel,countryCode:this._countryCode,createdAt:this._createdAt,updatedAt:this._updatedAt,currencyCode:this._currencyCode}}toJSON(){return JSON.stringify(this.toObject())}validate(){const e=_.schema.safeParse(this.toObject());return e.success||console.warn("Wallet instance validation failed:",e.error.flatten()),e.success}static fromJSON(e){try{const t=JSON.parse(e);return _.from(t)}catch(e){return void console.error("Error parsing wallet JSON:",e)}}static from(e){if(e&&"object"==typeof e)return _.create({id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt,currencyCode:e.currencyCode});console.error("Invalid data provided to Wallet.from: Input must be an object.")}static is(e){if(!e||"object"!=typeof e)return!1;const r=e;return"string"==typeof r.id&&"string"==typeof r.profileId&&"string"==typeof r.accountNo&&"string"==typeof r.accountName&&"string"==typeof r.channel&&"string"==typeof r.countryCode&&t.CountryValidation.isISO2CountryCode(r.countryCode)&&"string"==typeof r.currencyCode&&t.CurrencyValidation.isCurrencyCode(r.currencyCode)&&"string"==typeof r.createdAt&&"string"==typeof r.updatedAt&&"function"==typeof r.toObject&&"function"==typeof r.validate}}class T{static get schema(){return D.statementEntry}constructor(e){this._accountNo=e.accountNo,this._debitOrCredit=e.debitOrCredit,this._tranRefNo=e.tranRefNo,this._narration=e.narration,this._txnDate=e.txnDate,this._valueDate=e.valueDate,this._currencyCode=e.currencyCode;const r=t.Currency.from(e.currencyCode);if(!r)throw new Error(`Currency not found for code: ${e.currencyCode}`);const n=t.Amount.from(e.amountCredited,r.code),o=t.Amount.from(e.amountDebited,r.code),a=t.Amount.from(e.balance,r.code);if(!n||!o||!a)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=n,this._amountDebited=o,this._balance=a}static create(e){const t=T.schema.safeParse(e);if(t.success)try{return new T(t.data)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",t.error.flatten())}get accountNo(){return this._accountNo}get debitOrCredit(){return this._debitOrCredit}get tranRefNo(){return this._tranRefNo}get narration(){return this._narration}get txnDate(){return this._txnDate}get valueDate(){return this._valueDate}get amountCredited(){return this._amountCredited}get amountDebited(){return this._amountDebited}get balance(){return this._balance}get currencyCode(){return this._currencyCode}toJson(){return{accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration,txnDate:this._txnDate.toISOString(),valueDate:this._valueDate.toISOString(),amountCredited:this._amountCredited.toJson(),amountDebited:this._amountDebited.toJson(),balance:this._balance.toJson(),currencyCode:this._currencyCode,version:"1.0"}}static fromJson(e){try{let r;if(r="string"==typeof e?JSON.parse(e):e,!(r&&"object"==typeof r&&"string"==typeof r.debitOrCredit&&"string"==typeof r.tranRefNo&&"string"==typeof r.narration&&"string"==typeof r.txnDate&&"string"==typeof r.valueDate&&"string"==typeof r.currencyCode&&r.amountCredited&&r.amountDebited&&r.balance))return void console.warn("Invalid WalletStatementEntryJson: missing or invalid required properties");const n=t.Amount.fromJson(r.amountCredited),o=t.Amount.fromJson(r.amountDebited),a=t.Amount.fromJson(r.balance);return n&&o&&a?n.currencyCode!==r.currencyCode||o.currencyCode!==r.currencyCode||a.currencyCode!==r.currencyCode?void console.warn("Invalid WalletStatementEntryJson: currency code mismatch"):T.create({accountNo:r.accountNo,debitOrCredit:r.debitOrCredit,tranRefNo:r.tranRefNo,narration:r.narration,txnDate:r.txnDate,valueDate:r.valueDate,amountCredited:n.numericValue,amountDebited:o.numericValue,balance:a.numericValue,currencyCode:r.currencyCode}):void console.warn("Invalid WalletStatementEntryJson: failed to deserialize Amount objects")}catch(e){return void console.error("Error parsing WalletStatementEntryJson:",e)}}static isWalletStatementEntryJson(e){if(!e||"object"!=typeof e)return!1;const r=e;return"string"==typeof r.debitOrCredit&&"string"==typeof r.tranRefNo&&"string"==typeof r.narration&&"string"==typeof r.txnDate&&"string"==typeof r.valueDate&&"string"==typeof r.currencyCode&&(void 0===r.accountNo||"string"==typeof r.accountNo)&&t.Amount.isAmountJson(r.amountCredited)&&t.Amount.isAmountJson(r.amountDebited)&&t.Amount.isAmountJson(r.balance)}validate(){const e={accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode},t=T.schema.safeParse(e);return t.success||console.warn("WalletStatementEntry instance validation failed:",t.error.flatten()),t.success}static is(e){if(!e||"object"!=typeof e)return!1;const r=e;try{return("string"==typeof r.accountNo||void 0===r.accountNo)&&"string"==typeof r.debitOrCredit&&"string"==typeof r.tranRefNo&&"string"==typeof r.narration&&r.txnDate instanceof Date&&r.valueDate instanceof Date&&t.Amount.is(r.amountCredited)&&t.Amount.is(r.amountDebited)&&t.Amount.is(r.balance)&&"string"==typeof r.currencyCode&&"function"==typeof r.toJson&&"function"==typeof r.validate}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return T.create({accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode})}toString(){return`WalletStatementEntry(${this._tranRefNo}: ${this._debitOrCredit} ${this._amountCredited.isPositive()?this._amountCredited.label:this._amountDebited.label} on ${this._txnDate.toISOString().split("T")[0]})`}static toJsonArray(e){return e.map(e=>e.toJson())}static fromJsonArray(e){try{let t;return t="string"==typeof e?JSON.parse(e):e,Array.isArray(t)?t.map(e=>T.fromJson(e)).filter(e=>void 0!==e):(console.warn("fromJsonArray expects an array"),[])}catch(e){return console.error("Error parsing WalletStatementEntryJson array:",e),[]}}toObject(){return{accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.toJson(),amountDebited:this._amountDebited.toJson(),balance:this._balance.toJson(),currencyCode:this._currencyCode}}toJSON(){return JSON.stringify(this.toJson())}static fromJSON(e){return T.fromJson(e)}static from(e){if(e&&"object"==typeof e)try{let r,n,o,a=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const s=t.Amount.fromJson(e.amountCredited),i=t.Amount.fromJson(e.amountDebited),c=t.Amount.fromJson(e.balance);if(!s||!i||!c)return void console.error("Failed to deserialize Amount objects from JSON");r=s.numericValue,n=i.numericValue,o=c.numericValue,e.currencyCode||(a=s.currencyCode)}else if(r=Number(e.amountCredited),n=Number(e.amountDebited),o=Number(e.balance),!Number.isFinite(r)||!Number.isFinite(n)||!Number.isFinite(o))return void console.error("Invalid numeric values for amounts");return T.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:e.narration,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:r,amountDebited:n,balance:o,currencyCode:a})}catch(e){return void console.error("Error in WalletStatementEntry.from:",e)}else console.error("Invalid data provided to WalletStatementEntry.from: not an object or null.")}}class R{constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.permissions=new Set(e.access),this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}hasPermission(e){return this.permissions.has(e)}static from(e){try{if(!(null==e?void 0:e.id)||!(null==e?void 0:e.name)||!Array.isArray(null==e?void 0:e.access))return;return new R(e)}catch(e){return void console.error("Error creating Role:",e)}}toJSON(){return{id:this.id,name:this.name,description:this.description,access:Array.from(this.permissions),createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}}class j{constructor(e){this.id=e.id,this.name=e.name,this.identity=e.identity,this.profileId=e.profileId,this.permissions=new Set(e.permissions)}can(e){return this.permissions.has(e)}canAny(e){return e.some(e=>this.permissions.has(e))}canAll(e){return e.every(e=>this.permissions.has(e))}}class U extends j{constructor(e){var t,r;if(super({id:e.id,name:e.name,identity:e.identity,profileId:e.profileId,permissions:null!==(r=null===(t=e.role)||void 0===t?void 0:t.access)&&void 0!==r?r:[]}),this.type=e.type,this.roleId=e.roleId,this.resetPassword=e.resetPassword,this.isActive=e.isActive,this.isArchived=e.isArchived,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),e.role)try{this.role=new R(e.role)}catch(e){}}isAccountActive(){return this.isActive}isAccountArchived(){return this.isArchived}needsPasswordReset(){return this.resetPassword}getAccountStatus(){return this.isArchived?{status:"archived",label:"Archived",color:"default",description:"Account has been archived and is no longer accessible"}:this.isActive?this.resetPassword?{status:"password_reset_required",label:"Password Reset Required",color:"warning",description:"User must reset their password on next login"}:{status:"active",label:"Active",color:"success",description:"Account is active and ready to use"}:{status:"inactive",label:"Inactive",color:"error",description:"Account has been deactivated by an administrator"}}getRoleName(){var e,t;return null!==(t=null===(e=this.role)||void 0===e?void 0:e.name)&&void 0!==t?t:""}getCreatedDate(){return this.createdAt.toLocaleDateString()}getLastUpdateInfo(){const e=(new Date).getTime()-this.updatedAt.getTime(),t=Math.floor(e/864e5);return 0===t?"Today":1===t?"Yesterday":t<7?`${t} days ago`:t<30?`${Math.floor(t/7)} weeks ago`:this.updatedAt.toLocaleDateString()}static from(e){try{return(null==e?void 0:e.id)&&(null==e?void 0:e.name)&&(null==e?void 0:e.identity)&&(null==e?void 0:e.roleId)?new U(e):void console.error("Missing required ManagedUser fields:",e)}catch(e){return void console.error("Error creating ManagedUser:",e)}}static createMany(e){return e.map(e=>U.from(e)).filter(Boolean)}toJSON(){var e;return{id:this.id,name:this.name,identity:this.identity,type:this.type,profileId:this.profileId,roleId:this.roleId,resetPassword:this.resetPassword,isActive:this.isActive,isArchived:this.isArchived,role:null===(e=this.role)||void 0===e?void 0:e.toJSON(),createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}}const M=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 x=Symbol("ContractNoBody"),k=e=>"method"in e&&"path"in e,B=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,o,a,s,i;return k(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:(s=null==t?void 0:t.baseHeaders,i=r.headers,M(s)?M(i)?s.merge(i):s:M(i)?i:Object.assign({},s,i)),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(o=r.validateResponseOnClient)&&void 0!==o?o:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(a=r.metadata)&&void 0!==a?a:{}}:r.metadata}]:[e,B(r,t)]})),$=Symbol("ContractPlainType"),F=()=>({router:(e,t)=>B(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>$,body:()=>$,type:()=>$,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>x}),W=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("&"):"",q=e=>e?Object.keys(e).flatMap(t=>J(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",J=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>J(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>J(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class V extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const L=async({route:e,path:t,method:r,headers:n,body:o,validateResponse:a,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:n,body:o}),c=i.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t={status:i.status,body:await i.json(),headers:i.headers},r=e.responses[t.status];return(null!=a?a:e.validateResponseOnClient)&&"function"==typeof(null==(d=r)?void 0:d.safeParse)?{...t,body:r.parse(t.body)}:t}var d;return(null==c?void 0:c.includes("text/"))?{status:i.status,body:await i.text(),headers:i.headers}:{status:i.status,body:await i.blob(),headers:i.headers}},G=e=>{const t=new FormData,r=(e,r)=>{r instanceof File?t.append(e,r):t.append(e,JSON.stringify(r))};return Object.entries(e).forEach(([e,t])=>{if(Array.isArray(t))for(const n of t)r(e,n);else r(e,t)}),t},H=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),Z=(e,t,r,n,o)=>{const a=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),s=((e,t=!1)=>{const r=t?W(e):q(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,o);return`${t}${a}${s}`},Y=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const o=((e,t,r)=>{const{query:n,params:o,body:a,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:d,cache:u,next:l,...m}=r||{},p={...t,...c};return{path:Z(n,p.baseUrl,o,e,!!p.jsonQuery),clientArgs:p,route:e,body:a,query:n,extraInputArgs:m,fetchOptions:{...u&&{cache:u},...l&&{next:l},...d},headers:{...i,...s}}})(e,t,n),a=await(e=>{const{path:t,clientArgs:r,route:n,body:o,query:a,extraInputArgs:s,headers:i,fetchOptions:c}=e,d=r.api||L,u=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...u&&H(u),...H(i)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let m={route:n,path:t,method:n.method,headers:l,body:void 0,rawBody:o,rawQuery:a,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?m={...m,contentType:"multipart/form-data",body:o instanceof FormData?o:G(o)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?m={...m,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...m.headers},body:"string"==typeof o?o:new URLSearchParams(o)}:null!=o&&(m={...m,contentType:"application/json",headers:{"content-type":"application/json",...m.headers},body:JSON.stringify(o)})),d({...m,...s})})(o);if(!t.throwOnUnknownStatus)return a;if(r.includes(a.status.toString()))return a;throw new V(a,r)}},K=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>k(r)?[e,Y(r,t)]:[e,K(r,t)]));function Q(e,t){let r;try{r=e()}catch(e){return}return{getItem:e=>{var n;const o=e=>null===e?null:JSON.parse(e,null==t?void 0:t.reviver),a=null!=(n=r.getItem(e))?n:null;return a instanceof Promise?a.then(o):o(a)},setItem:(e,n)=>r.setItem(e,JSON.stringify(n,null==t?void 0:t.replacer)),removeItem:e=>r.removeItem(e)}}const X=e=>t=>{try{const r=e(t);return r instanceof Promise?r:{then:e=>X(e)(r),catch(e){return this}}}catch(e){return{then(e){return this},catch:t=>X(t)(e)}}},ee=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?(console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),((e,t)=>(r,n,o)=>{let a={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},s=!1;const i=new Set,c=new Set;let d;try{d=a.getStorage()}catch(e){}if(!d)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),r(...e)},n,o);const u=X(a.serialize),l=()=>{const e=a.partialize({...n()});let t;const r=u({state:e,version:a.version}).then(e=>d.setItem(a.name,e)).catch(e=>{t=e});if(t)throw t;return r},m=o.setState;o.setState=(e,t)=>{m(e,t),l()};const p=e((...e)=>{r(...e),l()},n,o);let h;const y=()=>{var e;if(!d)return;s=!1,i.forEach(e=>e(n()));const t=(null==(e=a.onRehydrateStorage)?void 0:e.call(a,n()))||void 0;return X(d.getItem.bind(d))(a.name).then(e=>{if(e)return a.deserialize(e)}).then(e=>{if(e){if("number"!=typeof e.version||e.version===a.version)return e.state;if(a.migrate)return a.migrate(e.state,e.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}}).then(e=>{var t;return h=a.merge(e,null!=(t=n())?t:p),r(h,!0),l()}).then(()=>{null==t||t(h,void 0),s=!0,c.forEach(e=>e(h))}).catch(e=>{null==t||t(void 0,e)})};return o.persist={setOptions:e=>{a={...a,...e},e.getStorage&&(d=e.getStorage())},clearStorage:()=>{null==d||d.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>y(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e)})},y(),h||p})(e,t)):((e,t)=>(r,n,o)=>{let a={storage:Q(()=>localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},s=!1;const i=new Set,c=new Set;let d=a.storage;if(!d)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),r(...e)},n,o);const u=()=>{const e=a.partialize({...n()});return d.setItem(a.name,{state:e,version:a.version})},l=o.setState;o.setState=(e,t)=>{l(e,t),u()};const m=e((...e)=>{r(...e),u()},n,o);let p;o.getInitialState=()=>m;const h=()=>{var e,t;if(!d)return;s=!1,i.forEach(e=>{var t;return e(null!=(t=n())?t:m)});const o=(null==(t=a.onRehydrateStorage)?void 0:t.call(a,null!=(e=n())?e:m))||void 0;return X(d.getItem.bind(d))(a.name).then(e=>{if(e){if("number"!=typeof e.version||e.version===a.version)return[!1,e.state];if(a.migrate)return[!0,a.migrate(e.state,e.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}return[!1,void 0]}).then(e=>{var t;const[o,s]=e;if(p=a.merge(s,null!=(t=n())?t:m),r(p,!0),o)return u()}).then(()=>{null==o||o(p,void 0),p=n(),s=!0,c.forEach(e=>e(p))}).catch(e=>{null==o||o(void 0,e)})};return o.persist={setOptions:e=>{a={...a,...e},e.storage&&(d=e.storage)},clearStorage:()=>{null==d||d.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>h(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e)})},a.skipHydration||h(),p||m})(e,t),te=n.create(ee((e,t)=>({user:void 0,token:void 0,getUser:()=>{try{const e=t().user;if(e)return E.fromJSON(e)}catch(e){console.warn("Failed to deserialize user from store:",e)}},setUser:t=>{try{e({user:t.toJSON()})}catch(e){console.error("Failed to serialize user to store:",e)}},getToken:()=>t().token,setToken:t=>e({token:t}),setUserAndToken:(t,r)=>{try{e({user:t.toJSON(),token:r})}catch(e){console.error("Failed to serialize user and token to store:",e)}},clearAuth:()=>e({user:void 0,token:void 0})}),{name:"auth-store",storage:Q(()=>"undefined"==typeof window?{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}:sessionStorage)})),re=()=>{if("undefined"!=typeof window)return te.getState().getToken()};class ne{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(){if(this.token&&this.token.trim().length>0)return this.token;try{const e=re();if(e&&e.trim().length>0)return e;console.warn(`No token available from global auth state for ${this.endpoint} repository`)}catch(e){console.warn(`No valid token available for ${this.endpoint} repository. Please provide a token directly in the constructor or ensure a user is logged in via AfloatAuth.instance.`)}return""}get client(){const e={baseUrl:this.root?`${this.root}/${this.endpoint}`:`https://api.afloat.money/v1/${this.endpoint}`,baseHeaders:{token:this.getToken(),"x-request-id":r.v4()}};return K(this.contract,e)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;if(400===e.status)throw new o(e.body);if(401===e.status)throw new o({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new o({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new o({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new o({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}const oe=F().router({logIn:{method:"POST",path:"/login",body:e.z.object({type:e.z.string().default("password"),identity:e.z.string().email(),password:e.z.string()}),responses:{201:e.z.object({profile:A.profileDTOSchema,token:e.z.string(),access:e.z.array(e.z.string()),resetPassword:e.z.boolean()}),400:e.z.object({})}},access:{method:"GET",path:"/access",headers:e.z.object({token:e.z.string()}),responses:{200:e.z.string().array()}},resetPassword:{method:"PUT",path:"/password",body:e.z.object({currentPassword:e.z.string(),newPassword:e.z.string()}),responses:{}}}),ae=F().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:e.z.object({name:e.z.string(),identity:e.z.string()})}}}),se={400:e.z.object({statusCode:e.z.number(),message:e.z.string(),error:e.z.string(),details:e.z.record(e.z.string()).optional()})};class ie extends ne{constructor(e){super("login",ae,e)}async getIdentity(){const e=await this.client.getUserCredentials();if(200===e.status)return e.body;throw new Error(`Failed to get user identity. Status: ${e.status}`)}}class ce extends ne{constructor(e){super("auth",oe,e)}async logIn(e,t){const r={type:"password",identity:e,password:t},n=await this.client.logIn({body:r});if(400===n.status)throw new o({message:"Invalid email or password",statusCode:400});if(201===n.status){const e=new ie({token:n.body.token}),t=await e.getIdentity(),r=E.from(Object.assign(Object.assign({},n.body),t));if(r)return r}throw new o({message:"An error occurred while trying to log in",statusCode:502})}async updatePassword(e,t){const r=await this.client.resetPassword({body:{currentPassword:e,newPassword:t}});if(200===r.status)return!0;if(400===r.status)throw new o({message:"Invalid current password",statusCode:400});throw new o({message:"An error occurred while trying to update password",statusCode:502})}}const de={getUniqueCountries(e){const t=new Set;return e.forEach(e=>{e.countryCode&&t.add(e.countryCode)}),Array.from(t)},getWalletsByCountry:(e,t)=>e.filter(e=>e.countryCode===t)},ue=F().router({getWallets:{method:"GET",path:"/",query:D.walletQuery,responses:{200:e.z.array(_.schema)}},getBalance:{method:"POST",path:"/balance",body:e.z.object({accountNo:e.z.string().optional()}),responses:{201:e.z.object({availableBalance:e.z.number()})}},getStatement:{method:"POST",path:"/statement",summary:"Get Wallet Statement",body:e.z.object({endDate:e.z.date(),startDate:e.z.date(),accountNo:e.z.string().optional()}),responses:{201:e.z.array(T.schema)}}});class le extends ne{constructor(e){super("wallet",ue,e)}async getBalance(e){const r=await this.client.getBalance({body:{accountNo:e.wallet.accountNo}});if(201===r.status){const n=r.body.availableBalance,o=t.Amount.from(n,e.wallet.currencyCode);if(o)return o}throw new Error(`Failed to fetch balance. Status: ${r.status}`)}async getWallets(e){const t=await this.client.getWallets({query:e});if(200===t.status){const e=t.body;try{return e.map(e=>{const t=_.from(e);if(!t)throw new Error(`Invalid wallet data: ${JSON.stringify(e)}`);return t})}catch(e){throw console.error("[WalletRepository] Error processing wallet data:",e),new Error("Failed to process wallet data from API")}}throw new Error(`Failed to fetch wallets. Status: ${t.status}`)}async getStatement(e){var t;const r=new Date,n=new Date(r.getFullYear(),r.getMonth(),1),o=new Date(r.getFullYear(),r.getMonth()+1,0),a=null!==(t=e.range)&&void 0!==t?t:{startDate:n,endDate:o},s=Object.assign(Object.assign({},a),{accountNo:e.wallet.accountNo}),i=await this.client.getStatement({body:s});if(201===i.status){return i.body.map(t=>Object.assign(Object.assign({},t),{currencyCode:e.wallet.currencyCode})).reduce((e,t)=>{const r=T.create(t);return r?e.push(r):console.warn("[WalletRepository] Skipping invalid statement entry:",t),e},[])}throw new Error(`Failed to fetch statement. Status: ${i.status}`)}}const me=n.create()(ee((e,t)=>({userId:"",wallets:[],selectedWalletId:"",selectedCountryCode:"TZ",lastSynced:new Date,isInitialized:!1,setWallets:r=>{const n=r.filter(e=>_.is(e));if(0===n.length)throw new Error("setWallets received an empty or invalid wallet list. User must have at least one valid wallet.");const o=t().selectedWalletId,a=t().isInitialized;let s;const i=n.some(e=>e.id===o);a&&i&&""!==o?(s=n.find(e=>e.id===o),s||(console.error("Inconsistency: currentWalletStillValid was true, but find failed."),s=n[0])):s=n[0],e({wallets:n,selectedWalletId:s.id,selectedCountryCode:s.countryCode,lastSynced:new Date,isInitialized:!0})},setSelectedWallet:r=>{if(!_.is(r))throw new Error("setSelectedWallet called with an invalid Wallet object.");if(!t().wallets.some(e=>e.id===r.id))throw new Error(`Attempted to select wallet (ID: ${r.id}) which is not present in the current wallet list.`);e({selectedWalletId:r.id,selectedCountryCode:r.countryCode})},setSelectedCountry:r=>{const n=t()._getWalletsByCountry(r);if(0===n.length)throw new Error(`Cannot select country ${r}: No wallets found for this country (check if code is valid or state is consistent).`);e({selectedCountryCode:r,selectedWalletId:n[0].id})},reset:()=>{e({userId:"",wallets:[],selectedWalletId:"",selectedCountryCode:"TZ",lastSynced:new Date,isInitialized:!1})},_getWalletsByCountry:e=>t().wallets.filter(t=>t.countryCode===e),_getSelectedWallet:()=>{const e=t();if(!e.isInitialized)throw new Error("Cannot get selected wallet: Wallet session not initialized.");if(""===e.selectedWalletId)throw new Error("Cannot get selected wallet: Selection is still placeholder (initialization incomplete?).");const r=e.wallets.find(t=>t.id===e.selectedWalletId);if(!r)throw console.error("Inconsistent state details:",{id:e.selectedWalletId,walletCount:e.wallets.length}),new Error(`Inconsistent state: Selected wallet ID '${e.selectedWalletId}' not found in wallet list.`);return r}}),{name:"wallet-session-storage",storage:Q(()=>sessionStorage,{reviver:(e,t)=>{if("wallets"===e&&Array.isArray(t))return t.map(e=>{try{const t=_.from(e);return t||void console.warn("Filtering out invalid wallet data during rehydration:",e)}catch(t){return void console.error("Error rehydrating Wallet instance from persisted data:",e,t)}}).filter(e=>void 0!==e);if("lastSynced"===e&&"string"==typeof t)try{const e=new Date(t);return isNaN(e.getTime())?new Date:e}catch(e){return new Date}return t},replacer:(e,t)=>"lastSynced"===e&&t instanceof Date?t.toISOString():"wallets"===e&&Array.isArray(t)?t.map(e=>e instanceof _&&"function"==typeof e.toObject?e.toObject():e):t}),partialize:e=>({userId:e.userId,wallets:e.wallets,selectedWalletId:e.selectedWalletId,selectedCountryCode:e.selectedCountryCode,lastSynced:e.lastSynced,isInitialized:e.isInitialized})}));class pe{constructor(){this.repo=new le}static get instance(){return this._instance||(this._instance=new pe),this._instance}isInitialized(){return me.getState().isInitialized}async initialize(e){if(!this.isInitialized()){if(!e)throw new Error("User must be authenticated to initialize wallet manager");await this.refreshWallets()}}async refreshWallets(){try{const e=await this.repo.getWallets();if(!e||0===e.length)throw new Error("User has no wallets associated with their account. Cannot proceed.");me.getState().setWallets(e)}catch(e){throw console.error("Failed to refresh wallets:",e),e}}getWallets(){const e=me.getState();if(!e.isInitialized)throw new Error("Cannot get wallets: Wallet session not initialized.");return e.wallets}getCountries(){const e=this.getWallets();return de.getUniqueCountries(e)}getWalletsByCountry(e){if(!this.isInitialized())throw new Error("Cannot get wallets by country: Wallet session not initialized.");return me.getState()._getWalletsByCountry(e)}getSelectedWallet(){return me.getState()._getSelectedWallet()}getSelectedCountryCode(){const e=me.getState();if(!e.isInitialized)throw new Error("Cannot get selected country code: Wallet session not initialized.");return e.selectedCountryCode}getSelectedCountry(){const e=this.getSelectedCountryCode();try{const r=t.Country.fromCode(e);if(!r)throw new Error(`Country.fromCode returned invalid result for code: ${e}`);return r}catch(t){throw console.error(`Failed to get Country object for code ${e}:`,t),new Error(`Failed to create Country object for selected code ${e}.`)}}changeWallet(e){if(!this.isInitialized())throw new Error("Cannot change wallet: Wallet session not initialized.");const t=me.getState(),r=t.wallets.find(t=>t.id===e);if(!r)throw new Error(`Cannot change wallet: Wallet with ID ${e} not found.`);t.setSelectedWallet(r)}changeCountry(e){if(!this.isInitialized())throw new Error("Cannot change country: Wallet session not initialized.");me.getState().setSelectedCountry(e)}reset(){me.getState().reset()}}class he{constructor(){}static get instance(){return he._instance||(he._instance=new he),he._instance}get repo(){return new ce({token:this.getUserToken()})}getUserToken(){return re()}get currentUser(){return(()=>{if("undefined"!=typeof window)return te.getState().getUser()})()}get isAuthenticated(){return!!this.currentUser&&!!this.getUserToken()}useCurrentUser(){return(()=>{if("undefined"==typeof window)throw new Error("useCurrentUser must only be used in a React component on the client side");const e=n.useStore(te,e=>e.user);try{return e?E.fromJSON(e):void 0}catch(e){return void console.warn("Failed to deserialize user from hook:",e)}})()}checkPermission(e){var t,r;return null!==(r=null===(t=this.currentUser)||void 0===t?void 0:t.can(e))&&void 0!==r&&r}async logIn(e,t){if(!e||!t)throw new Error("Email and password are required");const r=new ce,n=await r.logIn(e,t);this.clearSavedData(),te.getState().setUserAndToken(n,n.token);try{await pe.instance.initialize(n)}catch(e){throw console.warn("Failed to initialize wallet session manager:",e),e}return n}async resetPassword(e,t){if(!this.isAuthenticated)throw new Error("User must be authenticated to reset password");if(!e||!t)throw new Error("Current password and new password are required");return await this.repo.updatePassword(e,t),this.clearSavedData(),!0}logOut(){this.clearSavedData()}refresh(){this.clearSavedData()}getDebugInfo(){var e,t;return{hasUser:!!this.currentUser,hasToken:!!this.getUserToken(),isAuthenticated:this.isAuthenticated,userName:(null===(e=this.currentUser)||void 0===e?void 0:e.name)||"Not logged in",tokenLength:(null===(t=this.getUserToken())||void 0===t?void 0:t.length)||0,managerInstance:"AfloatAuth singleton"}}clearSavedData(){te.getState().clearAuth();try{pe.instance.reset()}catch(e){console.warn("Failed to reset wallet session manager:",e)}}}he._instance=null;const ye=F().router({getAccessList:{method:"GET",path:"/access",responses:{200:e.z.string().array()}}});const ge=F().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:S.schema}}});const fe=F().router({createContact:{method:"POST",path:"/",body:u.contactInputDTO,responses:{201:u.contactDTO}},editContact:{method:"PATCH",path:"/:id",body:u.contactInputDTO,responses:{200:u.contactDTO}},getContacts:{method:"GET",path:"/",query:e.z.object({orderByDesc:e.z.string()}),responses:{200:e.z.array(u.contactDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:u.contactDTO}},deleteContact:{method:"DELETE",path:"/:id",body:e.z.object({}),responses:{200:e.z.object({})}}},{commonResponses:se});class be{canHandle(e){return"Mobile"===e.type&&p.is(e)}createInput(e){if(p.is(e))return{type:exports.ContactType.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId,countryCode:e.countryCode};throw new Error("Expected Mobile Contact Info")}}class ve{canHandle(e){return"Bank"===e.type&&h.is(e)}createInput(e){if(h.is(e))return{type:exports.ContactType.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId,countryCode:e.countryCode};throw new Error("Expected Mobile Contact Info")}}class we{constructor(){this.handlers=[new be,new ve]}resolve(e){const t=this.handlers.find(t=>t.canHandle(e));if(!t)throw new Error("Please check your data and try again");return t.createInput(e)}}const Ce=F().router({getPayouts:{method:"GET",path:"",query:e.z.object({rangeStart:e.z.number(),rangeEnd:e.z.number(),eager:e.z.string(),approvalStatus:O.PayoutApprovalStatus.nullable().optional(),orderByDesc:e.z.string(),msisdn:e.z.string().optional()}),responses:{200:e.z.object({results:e.z.array(O.PayoutDTO),total:e.z.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:e.z.object({rangeStart:e.z.number(),rangeEnd:e.z.number(),eager:e.z.string(),approvalStatus:O.PayoutApprovalStatus,orderByDesc:e.z.string()}),responses:{200:e.z.object({results:e.z.array(O.PayoutDTO),total:e.z.number()})}},postPayout:{method:"POST",path:"",body:O.PayoutInputDTO,responses:{201:O.PayoutDTO,400:o.schema}},approve:{method:"POST",path:"/:id/approve",body:e.z.object({action:e.z.enum(["Approve","Reject"]),notes:e.z.string().optional()}),responses:{201:O.PayoutDTO,404:e.z.object({}),409:e.z.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:O.PayoutDTO,404:e.z.object({})}}}),Ne={SUPPORTED_COUNTRY_CODES:["TZ","KE"],NARRATION_PREFIXES:{BANK:"PAYOUT TO BANK",MOBILE:"PAYOUT TO MOBILE"},ERROR_MESSAGES:{INVALID_MOBILE_CONTACT:"Invalid mobile contact info",INVALID_BANK_CONTACT:"Invalid bank contact info",INVALID_PHONE_NUMBER:"Invalid phone number",INELIGIBLE_FOR_PAYOUT:"The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",MOBILE_NUMBER_MNO_MISMATCH:"There is a mismatch between the phone number provided and the MNO used.",UNSUPPORTED_COUNTRY_BANK:"Only Tanzanian Banks are supported for now",UNSUPPORTED_COUNTRY_MOBILE:"Only Tanzanian mobile numbers are supported for now",NO_HANDLER_FOUND:"Cannot create payout input!"}};class ze{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}}class Oe{static generateMobilePayoutNarration(e){if(!p.is(e))throw new Error(Ne.ERROR_MESSAGES.INVALID_MOBILE_CONTACT);const r=e.phoneNumber.getWithFormat(t.PhoneNumberFormat.E164).trim(),n=e.name.trim();return`${Ne.NARRATION_PREFIXES.MOBILE} ${r} ${n}`.toUpperCase()}static generateBankPayoutNarration(e){if(!h.is(e))throw new Error(Ne.ERROR_MESSAGES.INVALID_BANK_CONTACT);const t=e.bank.shortName.trim(),r=e.accNo.trim(),n=e.accName.trim();return`${Ne.NARRATION_PREFIXES.BANK} ${t} ${r} ${n}`.toUpperCase()}}class Ie{static forBank(e,t){if(!Ne.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ne.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,r,n){if(!t.PhoneNumber.is(e))throw new Error(Ne.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!Ne.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ne.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!t.PhoneNumberFactory.checkPayoutEligibility(e))throw new Error(Ne.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const o=t.MNOUtils.getMNOById(r,e.countryCode);if(!o)throw new Error(Ne.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return o.id===t.TZMNOId.VODACOM?`${n.countryCode}-${t.TZMNOId.TIGO.toString().toUpperCase()}-B2C`:`${n.countryCode}-${o.id.toString().toUpperCase()}-B2C`}}class Ae{canHandle(e,r,n){var o;return e===exports.PayoutChannel.MOBILE&&p.is(r)&&n.countryCode===r.countryCode&&n.currencyCode===(null===(o=t.Country.from(r.countryCode))||void 0===o?void 0:o.currencyCode)}createInput(e,r){const n=e.receiver,o=ze.processNotes(e.notes),a=n.phoneNumber;return{channel:Ie.forMobile(a,n.mnoId,r),msisdn:a.getWithFormat(t.PhoneNumberFormat.INTERNATIONAL_NUMERIC),description:null!=o?o:Oe.generateMobilePayoutNarration(n),payeeName:n.name,notes:o,amount:e.amount.numericValue}}}class Se{canHandle(e,r,n){var o;return e===exports.PayoutChannel.BANK&&h.is(r)&&n.countryCode===r.countryCode&&n.currencyCode===(null===(o=t.Country.from(r.countryCode))||void 0===o?void 0:o.currencyCode)}createInput(e,t){const r=e.receiver,n=ze.processNotes(e.notes);return{channel:Ie.forBank(r,t),msisdn:`${r.bank.swiftCode}:${r.accNo}`,description:null!=n?n:Oe.generateBankPayoutNarration(r),payeeName:r.accName,notes:n,amount:e.amount.numericValue}}}class Ee{constructor(){this.handlers=[new Ae,new Se]}getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(Ne.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const Pe=Oe,De={bank:Ie.forBank,mobile:Ie.forMobile};const _e=e=>{switch(e){case"TZS":return{defaultMin:1e3,defaultMax:1e6};case"KES":return{defaultMin:40,defaultMax:4e7};default:return{defaultMin:1,defaultMax:1e6}}},Te=e.z.string().min(8,"Password must be at least 8 characters long").max(128,"Password must not exceed 128 characters").regex(/[A-Z]/,"Password must contain at least one uppercase letter").regex(/[a-z]/,"Password must contain at least one lowercase letter").regex(/[0-9]/,"Password must contain at least one number").regex(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/,"Password must contain at least one special character (!@#$%^&*()_+-=[]{}|;:,.<>?)").refine(e=>![/(.)\1{2,}/,/123456|654321|abcdef|qwerty|password|admin|user/i,/^[0-9]+$/,/^[a-zA-Z]+$/].some(t=>t.test(e)),"Password contains weak patterns. Avoid repeated characters, common words, or simple sequences").refine(e=>!/(?:abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789)/i.test(e),"Password should not contain sequential characters").refine(e=>!/(?:qwer|wert|erty|rtyu|tyui|yuio|uiop|asdf|sdfg|dfgh|fghj|ghjk|hjkl|zxcv|xcvb|cvbn|vbnm)/i.test(e),"Password should not contain keyboard patterns"),Re=e.z.object({id:e.z.string().min(1),name:e.z.string().min(1,"Role name is required"),description:e.z.string().optional(),access:e.z.array(e.z.string()),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),je=e.z.object({id:e.z.string().min(1),name:e.z.string().min(1,"User name is required"),identity:e.z.string().email("Invalid email address"),type:e.z.string().min(1,"User type is required"),profileId:e.z.string().min(1,"Profile ID is required"),roleId:e.z.string().min(1,"Role ID is required"),resetPassword:e.z.boolean(),isActive:e.z.boolean(),isArchived:e.z.boolean(),role:Re.optional(),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),Ue={role:Re,managedUser:je,managedUserQueryParams:e.z.object({id:e.z.string().min(1).optional(),name:e.z.string().min(1).optional(),identity:e.z.string().email("Invalid email address").optional(),type:e.z.string().min(1).optional(),profileId:e.z.string().min(1).optional(),roleId:e.z.string().min(1).optional(),resetPassword:e.z.number().optional(),isActive:e.z.number().optional(),isArchived:e.z.number().optional(),createdAt:e.z.string().datetime("Invalid creation timestamp").optional(),updatedAt:e.z.string().datetime("Invalid update timestamp").optional(),eager:e.z.string().optional()}),createUserRequest:e.z.object({name:e.z.string().min(1,"User name is required"),identity:e.z.string().email("Valid email address is required"),password:Te.optional(),roleId:e.z.string().optional(),resetPassword:e.z.boolean().optional()}),updateUserRequest:e.z.object({name:e.z.string().min(1,"User name cannot be empty").optional(),roleId:e.z.string().min(1,"Role ID cannot be empty").optional(),password:Te.optional(),resetPassword:e.z.boolean().optional(),isActive:e.z.boolean().optional()}),resetPasswordRequest:e.z.object({newPassword:Te.optional(),sendNotification:e.z.boolean().optional()}),createUserResponse:e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string(),type:e.z.string(),profileId:e.z.string(),roleId:e.z.string(),isActive:e.z.boolean(),isArchived:e.z.boolean(),createdAt:e.z.string().datetime()}),password:Te},Me=F().router({getUsers:{method:"GET",path:"/login",query:Ue.managedUserQueryParams,responses:{200:e.z.array(Ue.managedUser),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List all user accounts",description:"Retrieve a list of all user accounts in the system"},getUser:{method:"GET",path:"/login/:id",pathParams:e.z.object({id:e.z.string()}),query:Ue.managedUserQueryParams,responses:{200:Ue.managedUser,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 user account details",description:"Retrieve detailed information about a specific user account"},createUser:{method:"POST",path:"/login",body:Ue.createUserRequest,responses:{201:Ue.createUserResponse,400:e.z.object({message:e.z.string().optional(),errors:e.z.array(e.z.string()).optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),409:e.z.object({message:e.z.string().optional()})},summary:"Create new user account",description:"Create a new user account with specified role and permissions"},updateUser:{method:"PATCH",path:"/login/:id",pathParams:e.z.object({id:e.z.string()}),body:Ue.updateUserRequest,responses:{200:Ue.managedUser,400:e.z.object({message:e.z.string().optional(),errors:e.z.array(e.z.string()).optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Update user account",description:"Update user account information, role, status, or force password reset"},archiveUser:{method:"POST",path:"/login/:id/archive",pathParams:e.z.object({id:e.z.string()}),body:e.z.object({}),responses:{200:Ue.managedUser,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Archive user account",description:"Archive (soft delete) a user account"},unArchiveUser:{method:"POST",path:"/login/:id/unarchive",pathParams:e.z.object({id:e.z.string()}),body:e.z.object({}),responses:{200:Ue.managedUser,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:"Un-archive user account",description:"Un-archive (soft delete) a user account"},resetPassword:{method:"POST",path:"/login/:id/reset-password",pathParams:e.z.object({id:e.z.string()}),body:Ue.resetPasswordRequest,responses:{200:e.z.object({success:e.z.boolean()}),400:e.z.object({message:e.z.string().optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Reset user password",description:"Reset a user's password and optionally send notification"},getRoles:{method:"GET",path:"/role",responses:{200:e.z.array(Ue.role),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List all roles",description:"Retrieve a list of all available roles in the system"},getRole:{method:"GET",path:"/role/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:Ue.role,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Get role details",description:"Retrieve detailed information about a specific role"}});exports.APIError=o,exports.AccessRepository=class extends ne{constructor(e){super("auth",ye,e)}async getAccessList(){const e=await this.client.getAccessList();if(200===e.status)return e.body;throw new Error(`Failed to get access list. Status: ${e.status}`)}},exports.AfloatAuth=he,exports.AuthRepository=ce,exports.BankContactInfo=h,exports.Contact=y,exports.ContactDTOSchemas=u,exports.ContactRepository=class extends ne{constructor(e){super("contact",fe,e)}async create(e){const t=(new we).resolve(e),r=await this.client.createContact({body:t}),n=this.handleResponse(r,201);return y.create(n)}async edit(e,t){const r=(new we).resolve(t),n=await this.client.editContact({params:{id:e},body:r}),o=this.handleResponse(n,200);return y.create(o)}async remove(e){const t=await this.client.deleteContact({params:{id:e}});this.handleResponse(t,200)}async getAll(){const e=await this.client.getContacts({query:{orderByDesc:"createdAt"}}),t=this.handleResponse(e,200);return y.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return y.create(r)}},exports.IdentityRepository=ie,exports.ManagedUser=U,exports.MobileContactInfo=p,exports.Payout=I,exports.PayoutDTOSchemas=O,exports.PayoutInputFactory=Ee,exports.PayoutRepository=class extends ne{constructor(e){super("payout",Ce,e)}async getAll(e){var t,r;const n=null!==(t=null==e?void 0:e.rangeStart)&&void 0!==t?t:0,a=null!==(r=null==e?void 0:e.rangeEnd)&&void 0!==r?r:10,s=exports.PayoutApprovalStatus.PENDING,i={rangeStart:n,rangeEnd:a,eager:"[createdBy,actionedBy]",orderByDesc:"createdAt"};if((null==e?void 0:e.pending)&&Object.assign(i,{approvalStatus:s}),(null==e?void 0:e.msisdn)&&Object.assign(i,{msisdn:e.msisdn}),a<=n)throw new o({message:"Invalid range: end-date must be greater than start-date",statusCode:400});const c=await this.client.getPayouts({query:i});if(200===c.status)return{results:I.createMany(c.body.results),total:c.body.total};throw o.unknown("An error occurred while fetching payouts")}async pay(e){const{defaultMin:r,defaultMax:n}=_e(e.amount.currencyCode);if(e.amount.numericValue<r||e.amount.numericValue>n){const a=t.Amount.from(r,e.amount.currencyCode),s=t.Amount.from(n,e.amount.currencyCode);throw new o({statusCode:400,message:`Please make sure the amount is between ${null==a?void 0:a.label} - ${null==s?void 0:s.label}`})}const a=pe.instance.getSelectedWallet();if(!a)throw new Error("You have not selected a wallet to process this payout");const s=(new Ee).getPayoutInput(e,a),i=await this.client.postPayout({body:s});if(201===i.status)return I.create(i.body);if(400===i.status)throw new o(i.body);throw o.unknown()}async approve(e,t){const r=await this.client.approve({params:{id:e},body:{action:"Approve",notes:null==t?void 0:t.notes}});if(201===r.status)return I.create(r.body);if(404===r.status)throw new o({message:"Payout not found",statusCode:404});if(409===r.status)throw new o({message:"Payout already approved",statusCode:409});throw o.unknown()}async reject(e,t){const r=await this.client.approve({params:{id:e},body:{action:"Reject",notes:null==t?void 0:t.notes}});if(201===r.status)return I.create(r.body);if(404===r.status)throw new o({message:"Payout not found",statusCode:404});if(409===r.status)throw new o({message:"Payout already rejected",statusCode:409});throw o.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return I.create(t.body);if(404===t.status)throw new o({message:"Payout not found",statusCode:404});throw o.unknown()}},exports.PayoutUtils=Pe,exports.PermissionError=s,exports.Permissions=a,exports.Profile=S,exports.ProfileRepository=class extends ne{constructor(e){super("profile",ge,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=S.from(e.body);if(t)return t;throw new Error("Invalid profile data received from server")}throw new Error(`Failed to get current profile. Status: ${e.status}`)}},exports.Role=R,exports.User=E,exports.UserEntity=j,exports.UserManagementDTOSchemas=Ue,exports.UserManagementRepository=class extends ne{constructor(e){super("admin",Me,e)}async createUser(e){const t=await this.client.createUser({body:e});return this.handleResponse(t,201)}async updateUser(e,t){const r=await this.client.updateUser({params:{id:e},body:t}),n=this.handleResponse(r,200),o=U.from(n);if(!o)throw new Error("Invalid user data received from server");return o}async archiveUser(e){const t=await this.client.archiveUser({params:{id:e}}),r=this.handleResponse(t,201),n=U.from(r);if(!n)throw new Error("Invalid user data received from server");return n}async unArchiveUser(e){const t=await this.client.unArchiveUser({params:{id:e}}),r=this.handleResponse(t,201),n=U.from(r);if(!n)throw new Error("Invalid user data received from server");return n}async resetUserPassword(e,t={}){const r=await this.client.resetPassword({params:{id:e},body:t});return this.handleResponse(r,201)}async getAllUsers(e={eager:"role"}){const t=await this.client.getUsers({query:e}),r=this.handleResponse(t,200);return U.createMany(r)}async getUser(e,t={eager:"role"}){const r=await this.client.getUser({params:{id:e},query:t}),n=this.handleResponse(r,200),o=U.from(n);if(!o)throw new Error("Invalid user data received from server");return o}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=R.from(e);if(!t)throw new Error("Invalid role data received from server");return t})}async getRole(e){const t=await this.client.getRole({params:{id:e}}),r=this.handleResponse(t,200),n=R.from(r);if(!n)throw new Error("Invalid role data received from server");return n}},exports.Wallet=_,exports.WalletDTOSchemas=D,exports.WalletRepository=le,exports.WalletSessionManager=pe,exports.WalletStatementEntry=T,exports.WalletUtils=de,exports.createPayoutChannelCode=De,exports.getDefaultConstraints=_e,exports.isError=function(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message},exports.walletsStore=me;
|
|
1
|
+
"use strict";var e=require("zod"),t=require("@temboplus/frontend-core"),r=require("uuid"),n=require("zustand");class o 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 o.schema.safeParse(e).success}static unknown(e){return new o({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()})}}const a={Profile:{ViewCurrent:"profile.getCurrent",Update:"profile.update"},Contact:{View:"contact.findById",List:"contact.findAll",Create:"contact.create",Update:"contact.update",Delete:"contact.delete"},Payment:{View:"payment.findById",List:"payment.findAll",Create:"payment.create"},Payout:{View:"payout.findById",List:"payout.findAll",Create:"payout.create",Approve:"payout.approve"},Transfer:{View:"transfer.findById",List:"transfer.findAll",Create:"transfer.create",Approve:"transfer.approve"},Wallet:{ViewBalance:"wallet.getBalance",ViewStatement:"wallet.getStatement"},Role:{ViewRoles:"role.findAll",ViewRole:"role.findById"},UserManagement:{ViewUsers:"login.findAll",ViewUser:"login.findById",CreateUser:"login.create",UpdateUser:"login.update",ArchiveUser:"login.archive",UnArchiveUser:"login.unarchive",ResetPassword:"login.resetPassword"}};class s extends Error{constructor(e){var t;super(null!==(t=e.message)&&void 0!==t?t:`Missing required permissions: ${e.requiredPermissions.join(", ")}`),this.name="PermissionError",this.requiredPermissions=e.requiredPermissions}static is(t){const r=e.z.union([e.z.enum(Object.values(a.Profile)),e.z.enum(Object.values(a.Contact)),e.z.enum(Object.values(a.Payment)),e.z.enum(Object.values(a.Payout)),e.z.enum(Object.values(a.Transfer)),e.z.enum(Object.values(a.Wallet))]);return e.z.object({name:e.z.literal("PermissionError"),message:e.z.string(),requiredPermissions:e.z.array(r)}).safeParse(t).success}}var i;exports.ContactType=void 0,(i=exports.ContactType||(exports.ContactType={})).Bank="Bank",i.Mobile="Mobile";const c=e.z.nativeEnum(exports.ContactType),d=e.z.object({displayName:e.z.string().min(1,"Display name is required"),accountNo:e.z.string().min(1,"Account number is required"),channel:e.z.string().min(1,"Channel is required"),countryCode:e.z.string().default("TZ"),type:c}),u={contactDTO:e.z.object({id:e.z.string().min(1,"Contact id is required"),profileId:e.z.string(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime()}).merge(d),contactInputDTO:d,contactType:c};class l extends Error{constructor(e,t={}){super(e),this.context=t,this.name="ContactInfoError"}}class m{constructor(e,t){this.type=e,this.countryCode=t}}class h extends m{constructor(e,r,n){if(super(exports.ContactType.Mobile,r.countryCode),this.name=e,this.phoneNumber=r,!(null==e?void 0:e.trim()))throw new l("Name is required and cannot be empty",{operation:"constructor",countryCode:r.countryCode,phoneNumber:r.e164Format});if(!(null==r?void 0:r.validate()))throw new l("Invalid phone number",{operation:"constructor",countryCode:r.countryCode,phoneNumber:r.e164Format});if(n){if(!t.MNOUtils.isValidMNOForCountry(n,r.countryCode)){const e=t.MNOUtils.getCountryMNOs(r.countryCode).map(e=>e.id);throw new l(`Invalid MNO ${n} for country ${r.countryCode}. Valid MNOs: ${e.join(", ")}`,{phoneNumber:r.e164Format,countryCode:r.countryCode,mnoId:n,operation:"constructor"})}if(!t.MNOUtils.requiresExplicitMNO(r.countryCode)&&!t.MNOUtils.validateMNOForPhoneNumber(r.e164Format,n,r.countryCode))throw new l(`MNO ${n} is not consistent with phone number ${r.e164Format}`,{phoneNumber:r.e164Format,countryCode:r.countryCode,mnoId:n,operation:"constructor"});this.mnoId=n}else{if(t.MNOUtils.requiresExplicitMNO(r.countryCode))throw new l(`MNO must be explicitly provided for phone numbers in ${r.countryCode} due to Mobile Number Portability`,{phoneNumber:r.e164Format,countryCode:r.countryCode,operation:"constructor"});const e=t.MNOUtils.getMNOByPhoneNumber(r.e164Format,r.countryCode);if(!(null==e?void 0:e.id))throw new l(`Failed to determine MNO for phone number ${r.e164Format}`,{phoneNumber:r.e164Format,countryCode:r.countryCode,operation:"constructor"});this.mnoId=e.id}}static fromContactDTO(e){if("Mobile"!==e.type)return;const r=e.accountNo,n=e.countryCode;if(!t.CountryValidation.isISO2CountryCode(n))return void console.error(`Invalid country code: ${n}`);const o=t.PhoneNumber.from(r,{defaultCountry:n});if(o)try{let r;if(e.channel&&"string"==typeof e.channel)if(t.MNOUtils.isValidMNOForCountry(e.channel,n))r=e.channel;else{if(!t.MNOUtils.requiresExplicitMNO(n)){const e=t.MNOUtils.getMNOByPhoneNumber(o.e164Format,n);(null==e?void 0:e.id)?r=e.id:console.warn(`Failed to auto-detect MNO for phone number ${o.e164Format}`)}console.warn(`Invalid MNO ${e.channel} for country ${n}`)}return new h(e.displayName,o,r)}catch(e){return void console.error(`Failed to create MobileContactInfo: ${e}`)}else console.error(`Failed to parse phone number ${r} for country ${n}`)}static fromPayoutDTO(e){try{if(!t.CountryValidation.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const r=t.PhoneNumber.from(e.msisdn,{defaultCountry:e.countryCode});if(!r)return void console.error(`Failed to parse phone number: ${e.msisdn}`);let n;return e.channel&&"string"==typeof e.channel&&(t.MNOUtils.isValidMNOForCountry(e.channel,e.countryCode)?n=e.channel:console.warn(`Invalid MNO ${e.channel} for country ${e.countryCode} in PayoutDTO`)),new h(e.payeeName,r,n)}catch(t){return void console.error("Failed to create MobileContactInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const r=e;if("string"!=typeof r.name||!r.name.trim())return!1;let n;if("string"==typeof r.phoneNumber)n=t.PhoneNumber.from(r.phoneNumber);else if("object"==typeof r.phoneNumber){const e=r.phoneNumber;t.PhoneNumber.is(e)&&(n=t.PhoneNumber.from(e.e164Format))}if(!n)return!1;const o=r.mnoId;if("string"!=typeof o)return!1;if(!t.MNOUtils.isValidMNOForCountry(o,n.countryCode))return!1;if(t.MNOUtils.requiresExplicitMNO(n.countryCode))return!0;{const e=t.MNOUtils.getMNOByPhoneNumber(n.e164Format,n.countryCode);return(null==e?void 0:e.id)===o}}validate(){var e,r;try{return!!(null===(e=this.name)||void 0===e?void 0:e.trim())&&(!!(null===(r=this.phoneNumber)||void 0===r?void 0:r.validate())&&(!!t.MNOUtils.isValidMNOForCountry(this.mnoId,this.countryCode)&&(!!t.MNOUtils.requiresExplicitMNO(this.countryCode)||t.MNOUtils.validateMNOForPhoneNumber(this.phoneNumber.e164Format,this.mnoId,this.countryCode))))}catch(e){return!1}}getValidationDetails(){var e,r;const n=[],o=[];if((null===(e=this.name)||void 0===e?void 0:e.trim())||n.push("Name is required"),(null===(r=this.phoneNumber)||void 0===r?void 0:r.validate())||n.push("Phone number is invalid"),t.MNOUtils.isValidMNOForCountry(this.mnoId,this.countryCode)||n.push(`Invalid MNO ${this.mnoId} for country ${this.countryCode}`),!t.MNOUtils.requiresExplicitMNO(this.countryCode)){const e=t.MNOUtils.getMNOByPhoneNumber(this.phoneNumber.e164Format,this.countryCode);(null==e?void 0:e.id)!==this.mnoId&&o.push("MNO doesn't match phone number prefix - possible data inconsistency")}return{isValid:0===n.length,errors:n,warnings:o}}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(t.PhoneNumberFormat.INTERNATIONAL_NUMERIC)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){var e,r;const n=t.MNOUtils.getMNOById(this.mnoId,this.countryCode);return null!==(r=null!==(e=null==n?void 0:n.mobileMoneyService)&&void 0!==e?e:null==n?void 0:n.displayName)&&void 0!==r?r:this.mnoId}}class p extends m{constructor(e,r,n){if(super(exports.ContactType.Bank,r.countryCode),this.accName=e,this.bank=r,this.accNo=n,!t.BankValidation.validateAccountName(e))throw new l("Invalid account name",{operation:"constructor",countryCode:r.countryCode});if(!t.BankValidation.validateAccountNumber(n,r.countryCode))throw new l("Invalid account number",{operation:"constructor",countryCode:r.countryCode})}static fromContactDTO(e){if("Bank"!==e.type)return;const r=e.channel,n=e.countryCode;if(t.CountryValidation.isISO2CountryCode(n))if(r&&"string"==typeof r)if(t.BankValidation.validateSwiftCode(r,n))try{const o=t.Bank.from(r,n);if(!o)throw new Error(`Bank with SWIFT code ${r} not found`);return new p(e.displayName,o,e.accountNo)}catch(e){return void console.error(`Failed to create BankContactInfo: ${e}`)}else console.error(`Invalid SWIFT code ${r} for country ${n}`);else console.error("SWIFT code is required for bank contacts");else console.error(`Invalid country code: ${n}`)}static fromPayoutDTO(e){try{if(!t.CountryValidation.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const r=e.msisdn.trim().split(":");if(2!==r.length)return void console.error("Invalid PayoutDTO format for bank - expected 'swiftcode:accountno'");const[n,o]=r;if(!t.BankValidation.validateSwiftCode(n,e.countryCode))return void console.error(`Invalid SWIFT code ${n} for country ${e.countryCode}`);const a=t.Bank.from(n,e.countryCode);return a?new p(e.payeeName,a,o):void console.error(`Bank with SWIFT code ${n} not found`)}catch(t){return void console.error("Failed to create BankContactInfo from PayoutDTO: ",e,t)}}static is(e){if(!e||"object"!=typeof e)return!1;const r=e;if("string"!=typeof r.accName)return!1;if("string"!=typeof r.accNo)return!1;if(!r.bank||!t.Bank.is(r.bank))return!1;const n=r.accName,o=r.accNo,a=r.bank,s=t.BankValidation.validateAccountName(n),i=t.BankValidation.validateAccountNumber(o,a.countryCode);return s&&i}validate(){try{return t.BankValidation.validateAccountName(this.accName)&&t.BankValidation.validateAccountNumber(this.accNo,this.bank.countryCode)&&t.Bank.is(this.bank)}catch(e){return!1}}get accountName(){return this.accName}get accountNumber(){return this.accNo}get accountNameLabel(){return"Acc. Name"}get accountNumberLabel(){return"Bank Acc. No."}get channelLabel(){return"Bank"}get channelId(){return this.bank.swiftCode}get channelName(){return this.bank.shortName}}class y{constructor(e){this.data=u.contactDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get displayName(){return this.data.displayName}get type(){return this.data.type}get createdAt(){return new Date(this.data.createdAt)}get updatedAt(){return new Date(this.data.updatedAt)}get info(){return this.data.type===exports.ContactType.Mobile?h.fromContactDTO(this.data):this.data.type===exports.ContactType.Bank?p.fromContactDTO(this.data):void 0}get accNo(){const e=this.info;return e?e.accountNumber:this.data.accountNo}get accName(){return this.data.displayName}get accNoLabel(){const e=this.info;return e instanceof h?"Phone Number":e instanceof p?"Bank Account Number":"Account Number"}get channelLabel(){const e=this.info;return e instanceof h?"Channel":e instanceof p?"Bank":"Channel"}get accNameLabel(){const e=this.info;return e instanceof h?"Full Name":e instanceof p?"Bank Account Name":"Display Name"}get countryCode(){const e=this.data.countryCode;if(t.CountryValidation.isISO2CountryCode(e))return e;throw new Error(`${this.data.countryCode} is not a valid ISO-2 country code`)}get channelName(){const e=this.info;return e instanceof h||e instanceof p?e.channelName:""}get country(){const e=t.Country.fromCode(this.countryCode);if(!e)throw new Error(`We could not find an associated country for the country code ${this.countryCode}`);return e}static create(e){return new y(e)}static createMany(e){return e.map(e=>new y(e))}static createSafe(e){try{return new y(e)}catch(e){return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=u.contactDTO.safeParse(e);if(!t.success)return!1;return null!==y.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&y.canConstruct(e.data))}toJSON(){return Object.assign({},this.data)}}var g,f,b;exports.PayoutChannel=void 0,(g=exports.PayoutChannel||(exports.PayoutChannel={})).MOBILE="Mobile",g.BANK="Bank",exports.PayoutStatus=void 0,(f=exports.PayoutStatus||(exports.PayoutStatus={})).CREATED="CREATED",f.PENDING="PENDING",f.PAID="PAID",f.FAILED="FAILED",f.REJECTED="REJECTED",f.REVERSED="REVERSED",exports.PayoutApprovalStatus=void 0,(b=exports.PayoutApprovalStatus||(exports.PayoutApprovalStatus={})).PENDING="Pending",b.APPROVED="Approved",b.REJECTED="Rejected";const v=e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string()}),w=e.z.nativeEnum(exports.PayoutStatus),C=e.z.nativeEnum(exports.PayoutApprovalStatus),N=e.z.object({channel:e.z.string(),msisdn:e.z.string(),amount:e.z.coerce.number(),description:e.z.string(),notes:e.z.string().nullish()}),z=N.extend({payeeName:e.z.string()}),O={PayoutDTO:N.extend({id:e.z.string(),profileId:e.z.string(),payeeName:e.z.string(),countryCode:e.z.string().default("TZ").refine(e=>t.CountryValidation.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>t.CurrencyValidation.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),channel:e.z.string(),status:w,statusMessage:e.z.string(),partnerReference:e.z.string().nullish(),createdAt:e.z.coerce.date(),updatedAt:e.z.coerce.date(),actionedAt:e.z.coerce.date().nullish(),approvalStatus:C.nullish(),createdBy:v.nullish(),actionedBy:v.nullish()}),PayoutInputDTO:z,PayoutStatus:w,PayoutApprovalStatus:C,PayoutAuthorizer:v};class I{constructor(e){this.data=O.PayoutDTO.parse(e)}get id(){return this.data.id}get profileId(){return this.data.profileId}get payeeName(){return this.data.payeeName}get channel(){return this.data.channel}get msisdn(){return this.data.msisdn}get amount(){return t.Amount.from(this.data.amount,this.data.currencyCode)}get description(){return this.data.description}get notes(){return this.data.notes}get status(){return"Rejected"===this.data.approvalStatus?exports.PayoutStatus.REJECTED:"Approved"===this.data.approvalStatus?"FAILED"===this.data.status?exports.PayoutStatus.FAILED:exports.PayoutStatus.PAID:"Pending"===this.data.approvalStatus?exports.PayoutStatus.PENDING:this.data.status}get statusMessage(){return this.data.statusMessage}get partnerReference(){return this.data.partnerReference}get createdAt(){return this.data.createdAt}get updatedAt(){return this.data.updatedAt}get approvalStatus(){return this.data.approvalStatus}get createdBy(){return this.data.createdBy}get actionedBy(){return this.data.actionedBy}get contactInfo(){const e=h.fromPayoutDTO(this.data),t=p.fromPayoutDTO(this.data);return e||t}static create(e){return new I(e)}static createMany(e){return e.map(e=>new I(e))}static createSafe(e){try{return new I(e)}catch(e){return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=O.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==I.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&I.canConstruct(e.data))}toJSON(){return Object.assign({},this.data)}}const S={profileDTOSchema:e.z.object({id:e.z.string(),firstName:e.z.string().nullish(),lastName:e.z.string().nullish(),displayName:e.z.string(),phone:e.z.string().nullish(),accountNo:e.z.string().min(1),email:e.z.string().email().nullish(),autoApprove:e.z.boolean().nullish()})};class A{static get schema(){return S.profileDTOSchema}constructor(e){this._id=e.id,this._firstName=e.firstName,this._lastName=e.lastName,this._displayName=e.displayName,this._phone=e.phone,this._accountNo=e.accountNo,this._email=e.email,this._autoApprove=e.autoApprove}static create(e){return new A({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove})}get id(){return this._id}get firstName(){return this._firstName}get lastName(){return this._lastName}get displayName(){return this._displayName}get phone(){return this._phone}get accountNo(){return this._accountNo}get email(){return this._email}get autoApprove(){return this._autoApprove}getName(){var e,t;if(this._displayName&&""!==this._displayName.trim())return this._displayName;return`${null!==(e=this._firstName)&&void 0!==e?e:""} ${null!==(t=this._lastName)&&void 0!==t?t:""}`.trim()}toObject(){return{id:this._id,firstName:this._firstName,lastName:this._lastName,displayName:this._displayName,phone:this._phone,accountNo:this._accountNo,email:this._email,autoApprove:this._autoApprove}}toJSON(){return JSON.stringify(this.toObject())}validate(){try{return A.schema.safeParse(this.toObject()).success}catch(e){return console.error("Profile validation error:",e),!1}}static fromJSON(e){try{const t=JSON.parse(e);return A.from(t)}catch(e){return void console.error("Error parsing profile JSON:",e)}}static from(e){try{return e?"object"!=typeof e?void console.error("Data is not an object"):e.id&&e.accountNo&&e.displayName?A.create({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove}):void console.error("Missing required profile fields"):void console.error("Data is null or undefined")}catch(e){return void console.error("Error creating profile from object:",e)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t._id||"string"!=typeof t._displayName||"string"!=typeof t._accountNo)return!1;if(null!==t._firstName&&void 0!==t._firstName&&"string"!=typeof t._firstName)return!1;if(null!==t._lastName&&void 0!==t._lastName&&"string"!=typeof t._lastName)return!1;if(null!==t._email&&void 0!==t._email&&"string"!=typeof t._email)return!1;const r=t._phone;if(null!=r&&"string"!=typeof r)return!1;const n=t._autoApprove;return null==n||"boolean"==typeof n}}class E{constructor(e){const{profile:t,token:r,access:n,resetPassword:o,name:s,identity:i}=e;this.profile=t,this.token=r,this.resetPassword=o,this.name=s,this.identity=i,this.access=n,this.accessMap={};for(const e of Object.values(a))"object"==typeof e?Object.values(e).forEach(e=>{this.accessMap[e]=n.includes(e)}):this.accessMap[e]=n.includes(e)}can(e){var t;return null!==(t=this.accessMap[e])&&void 0!==t&&t}toObject(){return{profile:this.profile.toObject(),token:this.token,resetPassword:this.resetPassword,name:this.name,identity:this.identity,access:this.access}}toJSON(){return JSON.stringify(this.toObject())}static fromJSON(e){try{return E.from(JSON.parse(e))}catch(e){return void console.error("Invalid JSON string:",e)}}static from(e){let t,r;if("string"==typeof e)try{t=JSON.parse(e)}catch(e){return void console.error("Invalid JSON string:",e)}else t=e;if(!t)return void console.error("Data is null or undefined.");let n=t.profile;if("string"==typeof n)try{n=JSON.parse(n)}catch(e){return void console.error("Failed to parse profile JSON string:",e)}if(A.is(n))r=n;else{if("object"!=typeof n||null===n)return void console.error("Invalid profile format:",typeof n);if(r=A.from(n),!r)return void console.error("Failed to create Profile from data:",n)}if(t.token&&"string"==typeof t.token&&t.name&&"string"==typeof t.name&&t.identity&&"string"==typeof t.identity&&Array.isArray(t.access)&&"boolean"==typeof t.resetPassword)return new E({profile:r,token:t.token,access:t.access,resetPassword:t.resetPassword,name:t.name,identity:t.identity});console.error("Missing or invalid required User fields:",{token:typeof t.token,name:typeof t.name,identity:typeof t.identity,access:Array.isArray(t.access),resetPassword:typeof t.resetPassword})}}const P=e=>e.optional().transform(e=>null!=e?e:void 0),D={walletDTO:e.z.object({id:e.z.string().min(1,{message:"Wallet ID is required."}),profileId:e.z.string().min(1,{message:"Profile ID is required."}),accountNo:e.z.string().min(1,{message:"Account number is required."}),accountName:e.z.string().min(1,{message:"Account name is required."}),channel:e.z.string().min(1,{message:"Channel is required."}),countryCode:e.z.string().default("TZ").refine(e=>t.CountryValidation.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>t.CurrencyValidation.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:e.z.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:e.z.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:e.z.object({id:e.z.string().optional(),profileId:e.z.string().optional(),accountNo:e.z.string().optional(),accountName:e.z.string().optional(),channel:e.z.string().optional(),countryCode:e.z.string().default("TZ").refine(e=>t.ISO2CountryCodesSet.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:e.z.string().default("TZS").refine(e=>{const r=t.Currency.from(e);return void 0!==r&&t.CurrencyCodesSet.has(r.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:e.z.object({accountNo:P(e.z.string()),debitOrCredit:e.z.string().min(1,"Transaction type is required"),tranRefNo:e.z.string().min(1,"Transaction reference is required"),narration:e.z.string().min(1,"Transaction description is required"),txnDate:e.z.coerce.date({errorMap:()=>({message:"Invalid transaction date format"})}),valueDate:e.z.coerce.date({errorMap:()=>({message:"Invalid value date format"})}),amountCredited:e.z.number().min(0,"Credited amount must be non-negative"),amountDebited:e.z.number().min(0,"Debited amount must be non-negative"),balance:e.z.number(),currencyCode:P(e.z.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})};class _{static get schema(){return D.walletDTO}constructor(e){this._id=e.id,this._profileId=e.profileId,this._accountNo=e.accountNo,this._accountName=e.accountName,this._channel=e.channel,this._countryCode=e.countryCode,this._currencyCode=e.currencyCode,this._createdAt=e.createdAt,this._updatedAt=e.updatedAt}static create(e){const t=_.schema.safeParse(e);if(t.success)return new _(t.data);console.error("Wallet data validation failed:",t.error.flatten())}get id(){return this._id}get profileId(){return this._profileId}get accountNo(){return this._accountNo}get accountName(){return this._accountName}get channel(){return this._channel}get countryCode(){return this._countryCode}get currencyCode(){return this._currencyCode}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get createdAtDate(){return new Date(this._createdAt)}get updatedAtDate(){return new Date(this._updatedAt)}toObject(){return{id:this._id,profileId:this._profileId,accountNo:this._accountNo,accountName:this._accountName,channel:this._channel,countryCode:this._countryCode,createdAt:this._createdAt,updatedAt:this._updatedAt,currencyCode:this._currencyCode}}toJSON(){return JSON.stringify(this.toObject())}validate(){const e=_.schema.safeParse(this.toObject());return e.success||console.warn("Wallet instance validation failed:",e.error.flatten()),e.success}static fromJSON(e){try{const t=JSON.parse(e);return _.from(t)}catch(e){return void console.error("Error parsing wallet JSON:",e)}}static from(e){if(e&&"object"==typeof e)return _.create({id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt,currencyCode:e.currencyCode});console.error("Invalid data provided to Wallet.from: Input must be an object.")}static is(e){if(!e||"object"!=typeof e)return!1;const r=e;return"string"==typeof r.id&&"string"==typeof r.profileId&&"string"==typeof r.accountNo&&"string"==typeof r.accountName&&"string"==typeof r.channel&&"string"==typeof r.countryCode&&t.CountryValidation.isISO2CountryCode(r.countryCode)&&"string"==typeof r.currencyCode&&t.CurrencyValidation.isCurrencyCode(r.currencyCode)&&"string"==typeof r.createdAt&&"string"==typeof r.updatedAt&&"function"==typeof r.toObject&&"function"==typeof r.validate}}class T{static get schema(){return D.statementEntry}constructor(e){this._accountNo=e.accountNo,this._debitOrCredit=e.debitOrCredit,this._tranRefNo=e.tranRefNo,this._narration=e.narration,this._txnDate=e.txnDate,this._valueDate=e.valueDate,this._currencyCode=e.currencyCode;const r=t.Currency.from(e.currencyCode);if(!r)throw new Error(`Currency not found for code: ${e.currencyCode}`);const n=t.Amount.from(e.amountCredited,r.code),o=t.Amount.from(e.amountDebited,r.code),a=t.Amount.from(e.balance,r.code);if(!n||!o||!a)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=n,this._amountDebited=o,this._balance=a}static create(e){const t=T.schema.safeParse(e);if(t.success)try{return new T(t.data)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",t.error.flatten())}get accountNo(){return this._accountNo}get debitOrCredit(){return this._debitOrCredit}get tranRefNo(){return this._tranRefNo}get narration(){return this._narration}get txnDate(){return this._txnDate}get valueDate(){return this._valueDate}get amountCredited(){return this._amountCredited}get amountDebited(){return this._amountDebited}get balance(){return this._balance}get currencyCode(){return this._currencyCode}toJson(){return{accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration,txnDate:this._txnDate.toISOString(),valueDate:this._valueDate.toISOString(),amountCredited:this._amountCredited.toJson(),amountDebited:this._amountDebited.toJson(),balance:this._balance.toJson(),currencyCode:this._currencyCode,version:"1.0"}}static fromJson(e){try{let r;if(r="string"==typeof e?JSON.parse(e):e,!(r&&"object"==typeof r&&"string"==typeof r.debitOrCredit&&"string"==typeof r.tranRefNo&&"string"==typeof r.narration&&"string"==typeof r.txnDate&&"string"==typeof r.valueDate&&"string"==typeof r.currencyCode&&r.amountCredited&&r.amountDebited&&r.balance))return void console.warn("Invalid WalletStatementEntryJson: missing or invalid required properties");const n=t.Amount.fromJson(r.amountCredited),o=t.Amount.fromJson(r.amountDebited),a=t.Amount.fromJson(r.balance);return n&&o&&a?n.currencyCode!==r.currencyCode||o.currencyCode!==r.currencyCode||a.currencyCode!==r.currencyCode?void console.warn("Invalid WalletStatementEntryJson: currency code mismatch"):T.create({accountNo:r.accountNo,debitOrCredit:r.debitOrCredit,tranRefNo:r.tranRefNo,narration:r.narration,txnDate:r.txnDate,valueDate:r.valueDate,amountCredited:n.numericValue,amountDebited:o.numericValue,balance:a.numericValue,currencyCode:r.currencyCode}):void console.warn("Invalid WalletStatementEntryJson: failed to deserialize Amount objects")}catch(e){return void console.error("Error parsing WalletStatementEntryJson:",e)}}static isWalletStatementEntryJson(e){if(!e||"object"!=typeof e)return!1;const r=e;return"string"==typeof r.debitOrCredit&&"string"==typeof r.tranRefNo&&"string"==typeof r.narration&&"string"==typeof r.txnDate&&"string"==typeof r.valueDate&&"string"==typeof r.currencyCode&&(void 0===r.accountNo||"string"==typeof r.accountNo)&&t.Amount.isAmountJson(r.amountCredited)&&t.Amount.isAmountJson(r.amountDebited)&&t.Amount.isAmountJson(r.balance)}validate(){const e={accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode},t=T.schema.safeParse(e);return t.success||console.warn("WalletStatementEntry instance validation failed:",t.error.flatten()),t.success}static is(e){if(!e||"object"!=typeof e)return!1;const r=e;try{return("string"==typeof r.accountNo||void 0===r.accountNo)&&"string"==typeof r.debitOrCredit&&"string"==typeof r.tranRefNo&&"string"==typeof r.narration&&r.txnDate instanceof Date&&r.valueDate instanceof Date&&t.Amount.is(r.amountCredited)&&t.Amount.is(r.amountDebited)&&t.Amount.is(r.balance)&&"string"==typeof r.currencyCode&&"function"==typeof r.toJson&&"function"==typeof r.validate}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return T.create({accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode})}toString(){return`WalletStatementEntry(${this._tranRefNo}: ${this._debitOrCredit} ${this._amountCredited.isPositive()?this._amountCredited.label:this._amountDebited.label} on ${this._txnDate.toISOString().split("T")[0]})`}static toJsonArray(e){return e.map(e=>e.toJson())}static fromJsonArray(e){try{let t;return t="string"==typeof e?JSON.parse(e):e,Array.isArray(t)?t.map(e=>T.fromJson(e)).filter(e=>void 0!==e):(console.warn("fromJsonArray expects an array"),[])}catch(e){return console.error("Error parsing WalletStatementEntryJson array:",e),[]}}toObject(){return{accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.toJson(),amountDebited:this._amountDebited.toJson(),balance:this._balance.toJson(),currencyCode:this._currencyCode}}toJSON(){return JSON.stringify(this.toJson())}static fromJSON(e){return T.fromJson(e)}static from(e){if(e&&"object"==typeof e)try{let r,n,o,a=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const s=t.Amount.fromJson(e.amountCredited),i=t.Amount.fromJson(e.amountDebited),c=t.Amount.fromJson(e.balance);if(!s||!i||!c)return void console.error("Failed to deserialize Amount objects from JSON");r=s.numericValue,n=i.numericValue,o=c.numericValue,e.currencyCode||(a=s.currencyCode)}else if(r=Number(e.amountCredited),n=Number(e.amountDebited),o=Number(e.balance),!Number.isFinite(r)||!Number.isFinite(n)||!Number.isFinite(o))return void console.error("Invalid numeric values for amounts");return T.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:e.narration,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:r,amountDebited:n,balance:o,currencyCode:a})}catch(e){return void console.error("Error in WalletStatementEntry.from:",e)}else console.error("Invalid data provided to WalletStatementEntry.from: not an object or null.")}}class R{constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.permissions=new Set(e.access),this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}hasPermission(e){return this.permissions.has(e)}static from(e){try{if(!(null==e?void 0:e.id)||!(null==e?void 0:e.name)||!Array.isArray(null==e?void 0:e.access))return;return new R(e)}catch(e){return void console.error("Error creating Role:",e)}}toJSON(){return{id:this.id,name:this.name,description:this.description,access:Array.from(this.permissions),createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}}class j{constructor(e){this.id=e.id,this.name=e.name,this.identity=e.identity,this.profileId=e.profileId,this.permissions=new Set(e.permissions)}can(e){return this.permissions.has(e)}canAny(e){return e.some(e=>this.permissions.has(e))}canAll(e){return e.every(e=>this.permissions.has(e))}}class U extends j{constructor(e){var t,r;if(super({id:e.id,name:e.name,identity:e.identity,profileId:e.profileId,permissions:null!==(r=null===(t=e.role)||void 0===t?void 0:t.access)&&void 0!==r?r:[]}),this.type=e.type,this.roleId=e.roleId,this.resetPassword=e.resetPassword,this.isActive=e.isActive,this.isArchived=e.isArchived,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),e.role)try{this.role=new R(e.role)}catch(e){}}isAccountActive(){return this.isActive}isAccountArchived(){return this.isArchived}needsPasswordReset(){return this.resetPassword}getAccountStatus(){return this.isArchived?{status:"archived",label:"Archived",color:"default",description:"Account has been archived and is no longer accessible"}:this.isActive?this.resetPassword?{status:"password_reset_required",label:"Password Reset Required",color:"warning",description:"User must reset their password on next login"}:{status:"active",label:"Active",color:"success",description:"Account is active and ready to use"}:{status:"inactive",label:"Inactive",color:"error",description:"Account has been deactivated by an administrator"}}getRoleName(){var e,t;return null!==(t=null===(e=this.role)||void 0===e?void 0:e.name)&&void 0!==t?t:""}getCreatedDate(){return this.createdAt.toLocaleDateString()}getLastUpdateInfo(){const e=(new Date).getTime()-this.updatedAt.getTime(),t=Math.floor(e/864e5);return 0===t?"Today":1===t?"Yesterday":t<7?`${t} days ago`:t<30?`${Math.floor(t/7)} weeks ago`:this.updatedAt.toLocaleDateString()}static from(e){try{return(null==e?void 0:e.id)&&(null==e?void 0:e.name)&&(null==e?void 0:e.identity)&&(null==e?void 0:e.roleId)?new U(e):void console.error("Missing required ManagedUser fields:",e)}catch(e){return void console.error("Error creating ManagedUser:",e)}}static createMany(e){return e.map(e=>U.from(e)).filter(Boolean)}toJSON(){var e;return{id:this.id,name:this.name,identity:this.identity,type:this.type,profileId:this.profileId,roleId:this.roleId,resetPassword:this.resetPassword,isActive:this.isActive,isArchived:this.isArchived,role:null===(e=this.role)||void 0===e?void 0:e.toJSON(),createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}}const x=e=>"function"==typeof(null==e?void 0:e.passthrough);e.z.object({name:e.z.literal("ZodError"),issues:e.z.array(e.z.object({path:e.z.array(e.z.union([e.z.string(),e.z.number()])),message:e.z.string().optional(),code:e.z.nativeEnum(e.z.ZodIssueCode)}).catchall(e.z.any()))});const M=Symbol("ContractNoBody"),k=e=>"method"in e&&"path"in e,B=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,o,a,s,i;return k(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:(s=null==t?void 0:t.baseHeaders,i=r.headers,x(s)?x(i)?s.merge(i):s:x(i)?i:Object.assign({},s,i)),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(o=r.validateResponseOnClient)&&void 0!==o?o:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(a=r.metadata)&&void 0!==a?a:{}}:r.metadata}]:[e,B(r,t)]})),$=Symbol("ContractPlainType"),F=()=>({router:(e,t)=>B(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>$,body:()=>$,type:()=>$,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>M}),W=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("&"):"",q=e=>e?Object.keys(e).flatMap(t=>J(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",J=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>J(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>J(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class V extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const L=async({route:e,path:t,method:r,headers:n,body:o,validateResponse:a,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:n,body:o}),c=i.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t={status:i.status,body:await i.json(),headers:i.headers},r=e.responses[t.status];return(null!=a?a:e.validateResponseOnClient)&&"function"==typeof(null==(d=r)?void 0:d.safeParse)?{...t,body:r.parse(t.body)}:t}var d;return(null==c?void 0:c.includes("text/"))?{status:i.status,body:await i.text(),headers:i.headers}:{status:i.status,body:await i.blob(),headers:i.headers}},G=e=>{const t=new FormData,r=(e,r)=>{r instanceof File?t.append(e,r):t.append(e,JSON.stringify(r))};return Object.entries(e).forEach(([e,t])=>{if(Array.isArray(t))for(const n of t)r(e,n);else r(e,t)}),t},H=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),Z=(e,t,r,n,o)=>{const a=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),s=((e,t=!1)=>{const r=t?W(e):q(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,o);return`${t}${a}${s}`},Y=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const o=((e,t,r)=>{const{query:n,params:o,body:a,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:d,cache:u,next:l,...m}=r||{},h={...t,...c};return{path:Z(n,h.baseUrl,o,e,!!h.jsonQuery),clientArgs:h,route:e,body:a,query:n,extraInputArgs:m,fetchOptions:{...u&&{cache:u},...l&&{next:l},...d},headers:{...i,...s}}})(e,t,n),a=await(e=>{const{path:t,clientArgs:r,route:n,body:o,query:a,extraInputArgs:s,headers:i,fetchOptions:c}=e,d=r.api||L,u=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...u&&H(u),...H(i)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let m={route:n,path:t,method:n.method,headers:l,body:void 0,rawBody:o,rawQuery:a,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?m={...m,contentType:"multipart/form-data",body:o instanceof FormData?o:G(o)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?m={...m,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...m.headers},body:"string"==typeof o?o:new URLSearchParams(o)}:null!=o&&(m={...m,contentType:"application/json",headers:{"content-type":"application/json",...m.headers},body:JSON.stringify(o)})),d({...m,...s})})(o);if(!t.throwOnUnknownStatus)return a;if(r.includes(a.status.toString()))return a;throw new V(a,r)}},K=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>k(r)?[e,Y(r,t)]:[e,K(r,t)]));function Q(e,t){let r;try{r=e()}catch(e){return}return{getItem:e=>{var n;const o=e=>null===e?null:JSON.parse(e,null==t?void 0:t.reviver),a=null!=(n=r.getItem(e))?n:null;return a instanceof Promise?a.then(o):o(a)},setItem:(e,n)=>r.setItem(e,JSON.stringify(n,null==t?void 0:t.replacer)),removeItem:e=>r.removeItem(e)}}const X=e=>t=>{try{const r=e(t);return r instanceof Promise?r:{then:e=>X(e)(r),catch(e){return this}}}catch(e){return{then(e){return this},catch:t=>X(t)(e)}}},ee=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?(console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),((e,t)=>(r,n,o)=>{let a={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},s=!1;const i=new Set,c=new Set;let d;try{d=a.getStorage()}catch(e){}if(!d)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),r(...e)},n,o);const u=X(a.serialize),l=()=>{const e=a.partialize({...n()});let t;const r=u({state:e,version:a.version}).then(e=>d.setItem(a.name,e)).catch(e=>{t=e});if(t)throw t;return r},m=o.setState;o.setState=(e,t)=>{m(e,t),l()};const h=e((...e)=>{r(...e),l()},n,o);let p;const y=()=>{var e;if(!d)return;s=!1,i.forEach(e=>e(n()));const t=(null==(e=a.onRehydrateStorage)?void 0:e.call(a,n()))||void 0;return X(d.getItem.bind(d))(a.name).then(e=>{if(e)return a.deserialize(e)}).then(e=>{if(e){if("number"!=typeof e.version||e.version===a.version)return e.state;if(a.migrate)return a.migrate(e.state,e.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}}).then(e=>{var t;return p=a.merge(e,null!=(t=n())?t:h),r(p,!0),l()}).then(()=>{null==t||t(p,void 0),s=!0,c.forEach(e=>e(p))}).catch(e=>{null==t||t(void 0,e)})};return o.persist={setOptions:e=>{a={...a,...e},e.getStorage&&(d=e.getStorage())},clearStorage:()=>{null==d||d.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>y(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e)})},y(),p||h})(e,t)):((e,t)=>(r,n,o)=>{let a={storage:Q(()=>localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},s=!1;const i=new Set,c=new Set;let d=a.storage;if(!d)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),r(...e)},n,o);const u=()=>{const e=a.partialize({...n()});return d.setItem(a.name,{state:e,version:a.version})},l=o.setState;o.setState=(e,t)=>{l(e,t),u()};const m=e((...e)=>{r(...e),u()},n,o);let h;o.getInitialState=()=>m;const p=()=>{var e,t;if(!d)return;s=!1,i.forEach(e=>{var t;return e(null!=(t=n())?t:m)});const o=(null==(t=a.onRehydrateStorage)?void 0:t.call(a,null!=(e=n())?e:m))||void 0;return X(d.getItem.bind(d))(a.name).then(e=>{if(e){if("number"!=typeof e.version||e.version===a.version)return[!1,e.state];if(a.migrate)return[!0,a.migrate(e.state,e.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}return[!1,void 0]}).then(e=>{var t;const[o,s]=e;if(h=a.merge(s,null!=(t=n())?t:m),r(h,!0),o)return u()}).then(()=>{null==o||o(h,void 0),h=n(),s=!0,c.forEach(e=>e(h))}).catch(e=>{null==o||o(void 0,e)})};return o.persist={setOptions:e=>{a={...a,...e},e.storage&&(d=e.storage)},clearStorage:()=>{null==d||d.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>p(),hasHydrated:()=>s,onHydrate:e=>(i.add(e),()=>{i.delete(e)}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e)})},a.skipHydration||p(),h||m})(e,t),te=n.create(ee((e,t)=>({user:void 0,token:void 0,getUser:()=>{try{const e=t().user;if(e)return E.fromJSON(e)}catch(e){console.warn("Failed to deserialize user from store:",e)}},setUser:t=>{try{e({user:t.toJSON()})}catch(e){console.error("Failed to serialize user to store:",e)}},getToken:()=>t().token,setToken:t=>e({token:t}),setUserAndToken:(t,r)=>{try{e({user:t.toJSON(),token:r})}catch(e){console.error("Failed to serialize user and token to store:",e)}},clearAuth:()=>e({user:void 0,token:void 0})}),{name:"auth-store",storage:Q(()=>"undefined"==typeof window?{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}:sessionStorage)})),re=()=>{if("undefined"!=typeof window)return te.getState().getToken()};class ne{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(){if(this.token&&this.token.trim().length>0)return this.token;try{const e=re();if(e&&e.trim().length>0)return e;console.warn(`No token available from global auth state for ${this.endpoint} repository`)}catch(e){console.warn(`No valid token available for ${this.endpoint} repository. Please provide a token directly in the constructor or ensure a user is logged in via AfloatAuth.instance.`)}return""}get client(){const e={baseUrl:this.root?`${this.root}/${this.endpoint}`:`https://api.afloat.money/v1/${this.endpoint}`,baseHeaders:{token:this.getToken(),"x-request-id":r.v4()}};return K(this.contract,e)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;if(400===e.status)throw new o(e.body);if(401===e.status)throw new o({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new o({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new o({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new o({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}const oe=F().router({logIn:{method:"POST",path:"/login",body:e.z.object({type:e.z.string().default("password"),identity:e.z.string().email(),password:e.z.string()}),responses:{201:e.z.object({profile:S.profileDTOSchema,token:e.z.string(),access:e.z.array(e.z.string()),resetPassword:e.z.boolean()}),400:e.z.object({})}},access:{method:"GET",path:"/access",headers:e.z.object({token:e.z.string()}),responses:{200:e.z.string().array()}},resetPassword:{method:"PUT",path:"/password",body:e.z.object({currentPassword:e.z.string(),newPassword:e.z.string()}),responses:{}}}),ae=F().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:e.z.object({name:e.z.string(),identity:e.z.string()})}}}),se={400:e.z.object({statusCode:e.z.number(),message:e.z.string(),error:e.z.string(),details:e.z.record(e.z.string()).optional()})};class ie extends ne{constructor(e){super("login",ae,e)}async getIdentity(){const e=await this.client.getUserCredentials();if(200===e.status)return e.body;throw new Error(`Failed to get user identity. Status: ${e.status}`)}}class ce extends ne{constructor(e){super("auth",oe,e)}async logIn(e,t){const r={type:"password",identity:e,password:t},n=await this.client.logIn({body:r});if(400===n.status)throw new o({message:"Invalid email or password",statusCode:400});if(201===n.status){const e=new ie({token:n.body.token}),t=await e.getIdentity(),r=E.from(Object.assign(Object.assign({},n.body),t));if(r)return r}throw new o({message:"An error occurred while trying to log in",statusCode:502})}async updatePassword(e,t){const r=await this.client.resetPassword({body:{currentPassword:e,newPassword:t}});if(200===r.status)return!0;if(400===r.status)throw new o({message:"Invalid current password",statusCode:400});throw new o({message:"An error occurred while trying to update password",statusCode:502})}}const de={getUniqueCountries(e){const t=new Set;return e.forEach(e=>{e.countryCode&&t.add(e.countryCode)}),Array.from(t)},getWalletsByCountry:(e,t)=>e.filter(e=>e.countryCode===t)},ue=F().router({getWallets:{method:"GET",path:"/",query:D.walletQuery,responses:{200:e.z.array(_.schema)}},getBalance:{method:"POST",path:"/balance",body:e.z.object({accountNo:e.z.string().optional()}),responses:{201:e.z.object({availableBalance:e.z.number()})}},getStatement:{method:"POST",path:"/statement",summary:"Get Wallet Statement",body:e.z.object({endDate:e.z.date(),startDate:e.z.date(),accountNo:e.z.string().optional()}),responses:{201:e.z.array(T.schema)}}});class le extends ne{constructor(e){super("wallet",ue,e)}async getBalance(e){const r=await this.client.getBalance({body:{accountNo:e.wallet.accountNo}});if(201===r.status){const n=r.body.availableBalance,o=t.Amount.from(n,e.wallet.currencyCode);if(o)return o}throw new Error(`Failed to fetch balance. Status: ${r.status}`)}async getWallets(e){const t=await this.client.getWallets({query:e});if(200===t.status){const e=t.body;try{return e.map(e=>{const t=_.from(e);if(!t)throw new Error(`Invalid wallet data: ${JSON.stringify(e)}`);return t})}catch(e){throw console.error("[WalletRepository] Error processing wallet data:",e),new Error("Failed to process wallet data from API")}}throw new Error(`Failed to fetch wallets. Status: ${t.status}`)}async getStatement(e){var t;const r=new Date,n=new Date(r.getFullYear(),r.getMonth(),1),o=new Date(r.getFullYear(),r.getMonth()+1,0),a=null!==(t=e.range)&&void 0!==t?t:{startDate:n,endDate:o},s=Object.assign(Object.assign({},a),{accountNo:e.wallet.accountNo}),i=await this.client.getStatement({body:s});if(201===i.status){return i.body.map(t=>Object.assign(Object.assign({},t),{currencyCode:e.wallet.currencyCode})).reduce((e,t)=>{const r=T.create(t);return r?e.push(r):console.warn("[WalletRepository] Skipping invalid statement entry:",t),e},[])}throw new Error(`Failed to fetch statement. Status: ${i.status}`)}}const me=n.create()(ee((e,t)=>({userId:"",wallets:[],selectedWalletId:"",selectedCountryCode:"TZ",lastSynced:new Date,isInitialized:!1,setWallets:r=>{const n=r.filter(e=>_.is(e));if(0===n.length)throw new Error("setWallets received an empty or invalid wallet list. User must have at least one valid wallet.");const o=t().selectedWalletId,a=t().isInitialized;let s;const i=n.some(e=>e.id===o);a&&i&&""!==o?(s=n.find(e=>e.id===o),s||(console.error("Inconsistency: currentWalletStillValid was true, but find failed."),s=n[0])):s=n[0],e({wallets:n,selectedWalletId:s.id,selectedCountryCode:s.countryCode,lastSynced:new Date,isInitialized:!0})},setSelectedWallet:r=>{if(!_.is(r))throw new Error("setSelectedWallet called with an invalid Wallet object.");if(!t().wallets.some(e=>e.id===r.id))throw new Error(`Attempted to select wallet (ID: ${r.id}) which is not present in the current wallet list.`);e({selectedWalletId:r.id,selectedCountryCode:r.countryCode})},setSelectedCountry:r=>{const n=t()._getWalletsByCountry(r);if(0===n.length)throw new Error(`Cannot select country ${r}: No wallets found for this country (check if code is valid or state is consistent).`);e({selectedCountryCode:r,selectedWalletId:n[0].id})},reset:()=>{e({userId:"",wallets:[],selectedWalletId:"",selectedCountryCode:"TZ",lastSynced:new Date,isInitialized:!1})},_getWalletsByCountry:e=>t().wallets.filter(t=>t.countryCode===e),_getSelectedWallet:()=>{const e=t();if(!e.isInitialized)throw new Error("Cannot get selected wallet: Wallet session not initialized.");if(""===e.selectedWalletId)throw new Error("Cannot get selected wallet: Selection is still placeholder (initialization incomplete?).");const r=e.wallets.find(t=>t.id===e.selectedWalletId);if(!r)throw console.error("Inconsistent state details:",{id:e.selectedWalletId,walletCount:e.wallets.length}),new Error(`Inconsistent state: Selected wallet ID '${e.selectedWalletId}' not found in wallet list.`);return r}}),{name:"wallet-session-storage",storage:Q(()=>sessionStorage,{reviver:(e,t)=>{if("wallets"===e&&Array.isArray(t))return t.map(e=>{try{const t=_.from(e);return t||void console.warn("Filtering out invalid wallet data during rehydration:",e)}catch(t){return void console.error("Error rehydrating Wallet instance from persisted data:",e,t)}}).filter(e=>void 0!==e);if("lastSynced"===e&&"string"==typeof t)try{const e=new Date(t);return isNaN(e.getTime())?new Date:e}catch(e){return new Date}return t},replacer:(e,t)=>"lastSynced"===e&&t instanceof Date?t.toISOString():"wallets"===e&&Array.isArray(t)?t.map(e=>e instanceof _&&"function"==typeof e.toObject?e.toObject():e):t}),partialize:e=>({userId:e.userId,wallets:e.wallets,selectedWalletId:e.selectedWalletId,selectedCountryCode:e.selectedCountryCode,lastSynced:e.lastSynced,isInitialized:e.isInitialized})}));class he{constructor(){this.repo=new le}static get instance(){return this._instance||(this._instance=new he),this._instance}isInitialized(){return me.getState().isInitialized}async initialize(e){if(!this.isInitialized()){if(!e)throw new Error("User must be authenticated to initialize wallet manager");await this.refreshWallets()}}async refreshWallets(){try{const e=await this.repo.getWallets();if(!e||0===e.length)throw new Error("User has no wallets associated with their account. Cannot proceed.");me.getState().setWallets(e)}catch(e){throw console.error("Failed to refresh wallets:",e),e}}getWallets(){const e=me.getState();if(!e.isInitialized)throw new Error("Cannot get wallets: Wallet session not initialized.");return e.wallets}getCountries(){const e=this.getWallets();return de.getUniqueCountries(e)}getWalletsByCountry(e){if(!this.isInitialized())throw new Error("Cannot get wallets by country: Wallet session not initialized.");return me.getState()._getWalletsByCountry(e)}getSelectedWallet(){return me.getState()._getSelectedWallet()}getSelectedCountryCode(){const e=me.getState();if(!e.isInitialized)throw new Error("Cannot get selected country code: Wallet session not initialized.");return e.selectedCountryCode}getSelectedCountry(){const e=this.getSelectedCountryCode();try{const r=t.Country.fromCode(e);if(!r)throw new Error(`Country.fromCode returned invalid result for code: ${e}`);return r}catch(t){throw console.error(`Failed to get Country object for code ${e}:`,t),new Error(`Failed to create Country object for selected code ${e}.`)}}changeWallet(e){if(!this.isInitialized())throw new Error("Cannot change wallet: Wallet session not initialized.");const t=me.getState(),r=t.wallets.find(t=>t.id===e);if(!r)throw new Error(`Cannot change wallet: Wallet with ID ${e} not found.`);t.setSelectedWallet(r)}changeCountry(e){if(!this.isInitialized())throw new Error("Cannot change country: Wallet session not initialized.");me.getState().setSelectedCountry(e)}reset(){me.getState().reset()}}class pe{constructor(){}static get instance(){return pe._instance||(pe._instance=new pe),pe._instance}get repo(){return new ce({token:this.getUserToken()})}getUserToken(){return re()}get currentUser(){return(()=>{if("undefined"!=typeof window)return te.getState().getUser()})()}get isAuthenticated(){return!!this.currentUser&&!!this.getUserToken()}useCurrentUser(){return(()=>{if("undefined"==typeof window)throw new Error("useCurrentUser must only be used in a React component on the client side");const e=n.useStore(te,e=>e.user);try{return e?E.fromJSON(e):void 0}catch(e){return void console.warn("Failed to deserialize user from hook:",e)}})()}checkPermission(e){var t,r;return null!==(r=null===(t=this.currentUser)||void 0===t?void 0:t.can(e))&&void 0!==r&&r}async logIn(e,t){if(!e||!t)throw new Error("Email and password are required");const r=new ce,n=await r.logIn(e,t);this.clearSavedData(),te.getState().setUserAndToken(n,n.token);try{await he.instance.initialize(n)}catch(e){throw console.warn("Failed to initialize wallet session manager:",e),e}return n}async resetPassword(e,t){if(!this.isAuthenticated)throw new Error("User must be authenticated to reset password");if(!e||!t)throw new Error("Current password and new password are required");return await this.repo.updatePassword(e,t),this.clearSavedData(),!0}logOut(){this.clearSavedData()}refresh(){this.clearSavedData()}getDebugInfo(){var e,t;return{hasUser:!!this.currentUser,hasToken:!!this.getUserToken(),isAuthenticated:this.isAuthenticated,userName:(null===(e=this.currentUser)||void 0===e?void 0:e.name)||"Not logged in",tokenLength:(null===(t=this.getUserToken())||void 0===t?void 0:t.length)||0,managerInstance:"AfloatAuth singleton"}}clearSavedData(){te.getState().clearAuth();try{he.instance.reset()}catch(e){console.warn("Failed to reset wallet session manager:",e)}}}pe._instance=null;const ye=F().router({getAccessList:{method:"GET",path:"/access",responses:{200:e.z.string().array()}}});const ge=F().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:A.schema}}});const fe=F().router({createContact:{method:"POST",path:"/",body:u.contactInputDTO,responses:{201:u.contactDTO}},editContact:{method:"PATCH",path:"/:id",body:u.contactInputDTO,responses:{200:u.contactDTO}},getContacts:{method:"GET",path:"/",query:e.z.object({orderByDesc:e.z.string()}),responses:{200:e.z.array(u.contactDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:u.contactDTO}},deleteContact:{method:"DELETE",path:"/:id",body:e.z.object({}),responses:{200:e.z.object({})}}},{commonResponses:se});class be{canHandle(e){return"Mobile"===e.type&&h.is(e)}createInput(e){if(h.is(e))return{type:exports.ContactType.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId,countryCode:e.countryCode};throw new Error("Expected Mobile Contact Info")}}class ve{canHandle(e){return"Bank"===e.type&&p.is(e)}createInput(e){if(p.is(e))return{type:exports.ContactType.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId,countryCode:e.countryCode};throw new Error("Expected Mobile Contact Info")}}class we{constructor(){this.handlers=[new be,new ve]}resolve(e){const t=this.handlers.find(t=>t.canHandle(e));if(!t)throw new Error("Please check your data and try again");return t.createInput(e)}}const Ce=F().router({getPayouts:{method:"GET",path:"",query:e.z.object({rangeStart:e.z.number(),rangeEnd:e.z.number(),eager:e.z.string(),approvalStatus:O.PayoutApprovalStatus.nullable().optional(),orderByDesc:e.z.string(),msisdn:e.z.string().optional()}),responses:{200:e.z.object({results:e.z.array(O.PayoutDTO),total:e.z.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:e.z.object({rangeStart:e.z.number(),rangeEnd:e.z.number(),eager:e.z.string(),approvalStatus:O.PayoutApprovalStatus,orderByDesc:e.z.string()}),responses:{200:e.z.object({results:e.z.array(O.PayoutDTO),total:e.z.number()})}},postPayout:{method:"POST",path:"",body:O.PayoutInputDTO,responses:{201:O.PayoutDTO,400:o.schema}},approve:{method:"POST",path:"/:id/approve",body:e.z.object({action:e.z.enum(["Approve","Reject"]),notes:e.z.string().optional()}),responses:{201:O.PayoutDTO,404:e.z.object({}),409:e.z.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:O.PayoutDTO,404:e.z.object({})}}}),Ne={SUPPORTED_COUNTRY_CODES:["TZ","KE"],NARRATION_PREFIXES:{BANK:"PAYOUT TO BANK",MOBILE:"PAYOUT TO MOBILE"},ERROR_MESSAGES:{INVALID_MOBILE_CONTACT:"Invalid mobile contact info",INVALID_BANK_CONTACT:"Invalid bank contact info",INVALID_PHONE_NUMBER:"Invalid phone number",INELIGIBLE_FOR_PAYOUT:"The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",MOBILE_NUMBER_MNO_MISMATCH:"There is a mismatch between the phone number provided and the MNO used.",UNSUPPORTED_COUNTRY_BANK:"Only Tanzanian Banks are supported for now",UNSUPPORTED_COUNTRY_MOBILE:"Only Tanzanian mobile numbers are supported for now",NO_HANDLER_FOUND:"Cannot create payout input!"}};class ze{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}}class Oe{static generateMobilePayoutNarration(e){if(!h.is(e))throw new Error(Ne.ERROR_MESSAGES.INVALID_MOBILE_CONTACT);const r=e.phoneNumber.getWithFormat(t.PhoneNumberFormat.E164).trim(),n=e.name.trim();return`${Ne.NARRATION_PREFIXES.MOBILE} ${r} ${n}`.toUpperCase()}static generateBankPayoutNarration(e){if(!p.is(e))throw new Error(Ne.ERROR_MESSAGES.INVALID_BANK_CONTACT);const t=e.bank.shortName.trim(),r=e.accNo.trim(),n=e.accName.trim();return`${Ne.NARRATION_PREFIXES.BANK} ${t} ${r} ${n}`.toUpperCase()}}class Ie{static forBank(e,t){if(!Ne.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ne.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,r,n){if(!t.PhoneNumber.is(e))throw new Error(Ne.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!Ne.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ne.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!t.PhoneNumberFactory.checkPayoutEligibility(e))throw new Error(Ne.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const o=t.MNOUtils.getMNOById(r,e.countryCode);if(!o)throw new Error(Ne.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return o.id===t.TZMNOId.VODACOM?`${n.countryCode}-${t.TZMNOId.TIGO.toString().toUpperCase()}-B2C`:`${n.countryCode}-${o.id.toString().toUpperCase()}-B2C`}}class Se{canHandle(e,r,n){var o;return e===exports.PayoutChannel.MOBILE&&h.is(r)&&n.countryCode===r.countryCode&&n.currencyCode===(null===(o=t.Country.from(r.countryCode))||void 0===o?void 0:o.currencyCode)}createInput(e,r){const n=e.receiver,o=ze.processNotes(e.notes),a=n.phoneNumber;return{channel:Ie.forMobile(a,n.mnoId,r),msisdn:a.getWithFormat(t.PhoneNumberFormat.INTERNATIONAL_NUMERIC),description:null!=o?o:Oe.generateMobilePayoutNarration(n),payeeName:n.name,notes:o,amount:e.amount.numericValue}}}class Ae{canHandle(e,r,n){var o;return e===exports.PayoutChannel.BANK&&p.is(r)&&n.countryCode===r.countryCode&&n.currencyCode===(null===(o=t.Country.from(r.countryCode))||void 0===o?void 0:o.currencyCode)}createInput(e,t){const r=e.receiver,n=ze.processNotes(e.notes);return{channel:Ie.forBank(r,t),msisdn:`${r.bank.swiftCode}:${r.accNo}`,description:null!=n?n:Oe.generateBankPayoutNarration(r),payeeName:r.accName,notes:n,amount:e.amount.numericValue}}}class Ee{constructor(){this.handlers=[new Se,new Ae]}getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(Ne.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const Pe=Oe,De={bank:Ie.forBank,mobile:Ie.forMobile};const _e=e=>{switch(e){case"TZS":return{defaultMin:1e3,defaultMax:1e6};case"KES":return{defaultMin:40,defaultMax:4e7};default:return{defaultMin:1,defaultMax:1e6}}},Te=e.z.string().min(8,"Password must be at least 8 characters long").max(128,"Password must not exceed 128 characters").regex(/[A-Z]/,"Password must contain at least one uppercase letter").regex(/[a-z]/,"Password must contain at least one lowercase letter").regex(/[0-9]/,"Password must contain at least one number").regex(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/,"Password must contain at least one special character (!@#$%^&*()_+-=[]{}|;:,.<>?)").refine(e=>![/(.)\1{2,}/,/123456|654321|abcdef|qwerty|password|admin|user/i,/^[0-9]+$/,/^[a-zA-Z]+$/].some(t=>t.test(e)),"Password contains weak patterns. Avoid repeated characters, common words, or simple sequences").refine(e=>!/(?:abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789)/i.test(e),"Password should not contain sequential characters").refine(e=>!/(?:qwer|wert|erty|rtyu|tyui|yuio|uiop|asdf|sdfg|dfgh|fghj|ghjk|hjkl|zxcv|xcvb|cvbn|vbnm)/i.test(e),"Password should not contain keyboard patterns"),Re=e.z.object({id:e.z.string().min(1),name:e.z.string().min(1,"Role name is required"),description:e.z.string().optional(),access:e.z.array(e.z.string()),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),je=e.z.object({id:e.z.string().min(1),name:e.z.string().min(1,"User name is required"),identity:e.z.string().email("Invalid email address"),type:e.z.string().min(1,"User type is required"),profileId:e.z.string().min(1,"Profile ID is required"),roleId:e.z.string().min(1,"Role ID is required"),resetPassword:e.z.boolean(),isActive:e.z.boolean(),isArchived:e.z.boolean(),role:Re.optional(),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),Ue={role:Re,managedUser:je,managedUserQueryParams:e.z.object({id:e.z.string().min(1).optional(),name:e.z.string().min(1).optional(),identity:e.z.string().email("Invalid email address").optional(),type:e.z.string().min(1).optional(),profileId:e.z.string().min(1).optional(),roleId:e.z.string().min(1).optional(),resetPassword:e.z.number().optional(),isActive:e.z.number().optional(),isArchived:e.z.number().optional(),createdAt:e.z.string().datetime("Invalid creation timestamp").optional(),updatedAt:e.z.string().datetime("Invalid update timestamp").optional(),eager:e.z.string().optional()}),createUserRequest:e.z.object({name:e.z.string().min(1,"User name is required"),identity:e.z.string().email("Valid email address is required"),password:Te.optional(),roleId:e.z.string().optional(),resetPassword:e.z.boolean().optional()}),updateUserRequest:e.z.object({name:e.z.string().min(1,"User name cannot be empty").optional(),roleId:e.z.string().min(1,"Role ID cannot be empty").optional(),password:Te.optional(),resetPassword:e.z.boolean().optional(),isActive:e.z.boolean().optional()}),resetPasswordRequest:e.z.object({newPassword:Te.optional(),sendNotification:e.z.boolean().optional()}),createUserResponse:e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string(),type:e.z.string(),profileId:e.z.string(),roleId:e.z.string(),isActive:e.z.boolean(),isArchived:e.z.boolean(),createdAt:e.z.string().datetime()}),password:Te},xe=F().router({getUsers:{method:"GET",path:"/login",query:Ue.managedUserQueryParams,responses:{200:e.z.array(Ue.managedUser),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List all user accounts",description:"Retrieve a list of all user accounts in the system"},getUser:{method:"GET",path:"/login/:id",pathParams:e.z.object({id:e.z.string()}),query:Ue.managedUserQueryParams,responses:{200:Ue.managedUser,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 user account details",description:"Retrieve detailed information about a specific user account"},createUser:{method:"POST",path:"/login",body:Ue.createUserRequest,responses:{201:Ue.createUserResponse,400:e.z.object({message:e.z.string().optional(),errors:e.z.array(e.z.string()).optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),409:e.z.object({message:e.z.string().optional()})},summary:"Create new user account",description:"Create a new user account with specified role and permissions"},updateUser:{method:"PATCH",path:"/login/:id",pathParams:e.z.object({id:e.z.string()}),body:Ue.updateUserRequest,responses:{200:Ue.managedUser,400:e.z.object({message:e.z.string().optional(),errors:e.z.array(e.z.string()).optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Update user account",description:"Update user account information, role, status, or force password reset"},archiveUser:{method:"POST",path:"/login/:id/archive",pathParams:e.z.object({id:e.z.string()}),body:e.z.object({}),responses:{200:Ue.managedUser,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Archive user account",description:"Archive (soft delete) a user account"},unArchiveUser:{method:"POST",path:"/login/:id/unarchive",pathParams:e.z.object({id:e.z.string()}),body:e.z.object({}),responses:{200:Ue.managedUser,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:"Un-archive user account",description:"Un-archive (soft delete) a user account"},resetPassword:{method:"POST",path:"/login/:id/reset-password",pathParams:e.z.object({id:e.z.string()}),body:Ue.resetPasswordRequest,responses:{200:e.z.object({success:e.z.boolean()}),400:e.z.object({message:e.z.string().optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Reset user password",description:"Reset a user's password and optionally send notification"},getRoles:{method:"GET",path:"/role",responses:{200:e.z.array(Ue.role),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List all roles",description:"Retrieve a list of all available roles in the system"},getRole:{method:"GET",path:"/role/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:Ue.role,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Get role details",description:"Retrieve detailed information about a specific role"}});exports.APIError=o,exports.AccessRepository=class extends ne{constructor(e){super("auth",ye,e)}async getAccessList(){const e=await this.client.getAccessList();if(200===e.status)return e.body;throw new Error(`Failed to get access list. Status: ${e.status}`)}},exports.AfloatAuth=pe,exports.AuthRepository=ce,exports.BankContactInfo=p,exports.Contact=y,exports.ContactDTOSchemas=u,exports.ContactRepository=class extends ne{constructor(e){super("contact",fe,e)}async create(e){const t=(new we).resolve(e),r=await this.client.createContact({body:t}),n=this.handleResponse(r,201);return y.create(n)}async edit(e,t){const r=(new we).resolve(t),n=await this.client.editContact({params:{id:e},body:r}),o=this.handleResponse(n,200);return y.create(o)}async remove(e){const t=await this.client.deleteContact({params:{id:e}});this.handleResponse(t,200)}async getAll(){const e=await this.client.getContacts({query:{orderByDesc:"createdAt"}}),t=this.handleResponse(e,200);return y.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return y.create(r)}},exports.IdentityRepository=ie,exports.ManagedUser=U,exports.MobileContactInfo=h,exports.Payout=I,exports.PayoutDTOSchemas=O,exports.PayoutInputFactory=Ee,exports.PayoutRepository=class extends ne{constructor(e){super("payout",Ce,e)}async getAll(e){var t,r;const n=null!==(t=null==e?void 0:e.rangeStart)&&void 0!==t?t:0,a=null!==(r=null==e?void 0:e.rangeEnd)&&void 0!==r?r:10,s=exports.PayoutApprovalStatus.PENDING,i={rangeStart:n,rangeEnd:a,eager:"[createdBy,actionedBy]",orderByDesc:"createdAt"};if((null==e?void 0:e.pending)&&Object.assign(i,{approvalStatus:s}),(null==e?void 0:e.msisdn)&&Object.assign(i,{msisdn:e.msisdn}),a<=n)throw new o({message:"Invalid range: end-date must be greater than start-date",statusCode:400});const c=await this.client.getPayouts({query:i});if(200===c.status)return{results:I.createMany(c.body.results),total:c.body.total};throw o.unknown("An error occurred while fetching payouts")}async pay(e){const{defaultMin:r,defaultMax:n}=_e(e.amount.currencyCode);if(e.amount.numericValue<r||e.amount.numericValue>n){const a=t.Amount.from(r,e.amount.currencyCode),s=t.Amount.from(n,e.amount.currencyCode);throw new o({statusCode:400,message:`Please make sure the amount is between ${null==a?void 0:a.label} - ${null==s?void 0:s.label}`})}const a=he.instance.getSelectedWallet();if(!a)throw new Error("You have not selected a wallet to process this payout");const s=(new Ee).getPayoutInput(e,a),i=await this.client.postPayout({body:s});if(201===i.status)return I.create(i.body);if(400===i.status)throw new o(i.body);throw o.unknown()}async approve(e,t){const r=await this.client.approve({params:{id:e},body:{action:"Approve",notes:null==t?void 0:t.notes}});if(201===r.status)return I.create(r.body);if(404===r.status)throw new o({message:"Payout not found",statusCode:404});if(409===r.status)throw new o({message:"Payout already approved",statusCode:409});throw o.unknown()}async reject(e,t){const r=await this.client.approve({params:{id:e},body:{action:"Reject",notes:null==t?void 0:t.notes}});if(201===r.status)return I.create(r.body);if(404===r.status)throw new o({message:"Payout not found",statusCode:404});if(409===r.status)throw new o({message:"Payout already rejected",statusCode:409});throw o.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return I.create(t.body);if(404===t.status)throw new o({message:"Payout not found",statusCode:404});throw o.unknown()}},exports.PayoutUtils=Pe,exports.PermissionError=s,exports.Permissions=a,exports.Profile=A,exports.ProfileRepository=class extends ne{constructor(e){super("profile",ge,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=A.from(e.body);if(t)return t;throw new Error("Invalid profile data received from server")}throw new Error(`Failed to get current profile. Status: ${e.status}`)}},exports.Role=R,exports.User=E,exports.UserEntity=j,exports.UserManagementDTOSchemas=Ue,exports.UserManagementRepository=class extends ne{constructor(e){super("admin",xe,e)}async createUser(e){const t=await this.client.createUser({body:e});return this.handleResponse(t,201)}async updateUser(e,t){const r=await this.client.updateUser({params:{id:e},body:t}),n=this.handleResponse(r,200),o=U.from(n);if(!o)throw new Error("Invalid user data received from server");return o}async archiveUser(e){const t=await this.client.archiveUser({params:{id:e}}),r=this.handleResponse(t,201),n=U.from(r);if(!n)throw new Error("Invalid user data received from server");return n}async unArchiveUser(e){const t=await this.client.unArchiveUser({params:{id:e}}),r=this.handleResponse(t,201),n=U.from(r);if(!n)throw new Error("Invalid user data received from server");return n}async resetUserPassword(e,t={}){const r=await this.client.resetPassword({params:{id:e},body:t});return this.handleResponse(r,201)}async getAllUsers(e={eager:"role"}){const t=await this.client.getUsers({query:e}),r=this.handleResponse(t,200);return U.createMany(r)}async getUser(e,t={eager:"role"}){const r=await this.client.getUser({params:{id:e},query:t}),n=this.handleResponse(r,200),o=U.from(n);if(!o)throw new Error("Invalid user data received from server");return o}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=R.from(e);if(!t)throw new Error("Invalid role data received from server");return t})}async getRole(e){const t=await this.client.getRole({params:{id:e}}),r=this.handleResponse(t,200),n=R.from(r);if(!n)throw new Error("Invalid role data received from server");return n}},exports.Wallet=_,exports.WalletDTOSchemas=D,exports.WalletRepository=le,exports.WalletSessionManager=he,exports.WalletStatementEntry=T,exports.WalletUtils=de,exports.createPayoutChannelCode=De,exports.getDefaultConstraints=_e,exports.isError=function(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message},exports.walletsStore=me;
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|