@temboplus/afloat 0.1.71 → 0.1.73

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.
Files changed (49) hide show
  1. package/dist/features/admin/admin.contract.d.ts +53 -53
  2. package/dist/features/admin/admin.repository.d.ts +5 -5
  3. package/dist/features/admin/index.d.ts +2 -2
  4. package/dist/features/auth/access/access.repository.d.ts +2 -2
  5. package/dist/features/auth/auth.manager.d.ts +2 -2
  6. package/dist/features/auth/auth.repository.d.ts +3 -3
  7. package/dist/features/auth/auth.store.d.ts +1 -1
  8. package/dist/features/auth/identity/identity.repository.d.ts +2 -2
  9. package/dist/features/auth/index.d.ts +5 -5
  10. package/dist/features/auth/profile/profile.repository.d.ts +3 -3
  11. package/dist/features/auth/storage/client-store.d.ts +2 -2
  12. package/dist/features/auth/storage/client-token-handler.d.ts +1 -1
  13. package/dist/features/contact/contact-input-handler.d.ts +2 -2
  14. package/dist/features/contact/contact.api-contract.d.ts +38 -38
  15. package/dist/features/contact/contact.dtos.d.ts +6 -6
  16. package/dist/features/contact/contact.repository.d.ts +4 -4
  17. package/dist/features/contact/index.d.ts +2 -2
  18. package/dist/features/payout/index.d.ts +3 -3
  19. package/dist/features/payout/payout-channel-handler.d.ts +3 -3
  20. package/dist/features/payout/payout.api-contract.d.ts +93 -93
  21. package/dist/features/payout/payout.dtos.d.ts +12 -12
  22. package/dist/features/payout/payout.repository.d.ts +5 -5
  23. package/dist/features/wallet/index.d.ts +4 -4
  24. package/dist/features/wallet/wallet-manager.session.d.ts +2 -2
  25. package/dist/features/wallet/wallet.contract.d.ts +7 -7
  26. package/dist/features/wallet/wallet.dtos.d.ts +14 -14
  27. package/dist/features/wallet/wallet.repository.d.ts +5 -5
  28. package/dist/features/wallet/wallet.utils.d.ts +1 -1
  29. package/dist/index.cjs.js +1 -1
  30. package/dist/index.cjs.js.map +1 -1
  31. package/dist/index.d.ts +7 -7
  32. package/dist/index.esm.js +1 -1
  33. package/dist/index.esm.js.map +1 -1
  34. package/dist/lib/api/base-repository.d.ts +1 -1
  35. package/dist/lib/api/index.d.ts +2 -2
  36. package/dist/lib/error/error.permission.d.ts +1 -1
  37. package/dist/lib/error/index.d.ts +3 -3
  38. package/dist/models/contact-info.model.d.ts +2 -2
  39. package/dist/models/contact.model.d.ts +2 -2
  40. package/dist/models/index.d.ts +11 -11
  41. package/dist/models/managed-user.model.d.ts +2 -2
  42. package/dist/models/narration.model.d.ts +1 -1
  43. package/dist/models/payout.model.d.ts +2 -2
  44. package/dist/models/profile.model.d.ts +1 -1
  45. package/dist/models/role.model.d.ts +1 -1
  46. package/dist/models/statement-entry.model.d.ts +2 -2
  47. package/dist/models/user.model.d.ts +1 -1
  48. package/dist/models/wallet.model.d.ts +1 -1
  49. package/package.json +4 -2
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- export * from "./lib/error/index";
2
- export * from "./models/index";
3
- export * from "./features/auth/index";
4
- export * from "./features/contact/index";
5
- export * from "./features/payout/index";
6
- export * from "./features/wallet/index";
7
- export * from "./features/admin/index";
1
+ export * from "./lib/error/index.js";
2
+ export * from "./models/index.js";
3
+ export * from "./features/auth/index.js";
4
+ export * from "./features/contact/index.js";
5
+ export * from "./features/payout/index.js";
6
+ export * from "./features/wallet/index.js";
7
+ export * from "./features/admin/index.js";
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import{z as e}from"zod";import{BankValidation as t,Bank as r,CountryValidation as n,MNOUtils as o,PhoneNumber as a,PhoneNumberFormat as s,CurrencyValidation as i,Amount as c,Currency as d,CurrencyCodesSet as l,ISO2CountryCodesSet as u,BankService as m,TZMobileNumber as h,Country as p,PhoneNumberFactory as y,TZMNOId as f}from"@temboplus/frontend-core";import{__rest as g}from"tslib";import{v4 as v}from"uuid";import{create as w,useStore as b}from"zustand";class N 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 N.schema.safeParse(e).success}static unknown(e){return new N({message:null!=e?e:"An unknown error occurred",statusCode:502})}static get schema(){return e.object({message:e.string(),statusCode:e.number().int(),error:e.string().optional(),details:e.object({}).optional()})}}const C={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 O 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.union([e.enum(Object.values(C.Profile)),e.enum(Object.values(C.Contact)),e.enum(Object.values(C.Payment)),e.enum(Object.values(C.Payout)),e.enum(Object.values(C.Transfer)),e.enum(Object.values(C.Wallet))]);return e.object({name:e.literal("PermissionError"),message:e.string(),requiredPermissions:e.array(r)}).safeParse(t).success}}function I(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message}var S;!function(e){e.Bank="Bank",e.Mobile="Mobile"}(S||(S={}));const A=e.nativeEnum(S),E=e.object({displayName:e.string().min(1,"Display name is required"),accountNo:e.string().min(1,"Account number is required"),channel:e.string().min(1,"Channel is required"),type:A}),D={contactDTO:e.object({id:e.string().min(1,"Contact id is required"),profileId:e.string(),createdAt:e.string().datetime(),updatedAt:e.string().datetime()}).merge(E),contactInputDTO:E,contactType:A};class P extends Error{constructor(e,t={}){super(e),this.context=t,this.name="ContactInfoError"}}class _{constructor(e,t){this.type=e,this.countryCode=t}}class j extends _{constructor(e,t,r){if(super(S.Mobile,t.countryCode),this.name=e,this.phoneNumber=t,!(null==e?void 0:e.trim()))throw new P("Name is required and cannot be empty",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(!(null==t?void 0:t.validate()))throw new P("Invalid phone number",{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format});if(o.requiresExplicitMNO(t.countryCode)){if(!r)throw new P(`MNO must be explicitly provided for phone numbers in ${t.countryCode} due to Mobile Number Portability`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});if(!o.isValidMNOForCountry(r,t.countryCode)){const e=o.getCountryMNOs(t.countryCode).map(e=>e.id);throw new P(`Invalid MNO ${r} for country ${t.countryCode}. Valid MNOs: ${e.join(", ")}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,mnoId:r,operation:"constructor"})}this.mnoId=r}else{const e=o.getMNOByPhoneNumber(t.e164Format,t.countryCode);if(!(null==e?void 0:e.id))throw new P(`Failed to determine MNO for phone number ${t.e164Format}`,{phoneNumber:t.e164Format,countryCode:t.countryCode,operation:"constructor"});this.mnoId=e.id}}static fromContactDTO(e){var t;if("Mobile"!==e.type)return;let r=e.accountNo;r.startsWith("+")||(r=`+${r}`);const n=a.from(r);if(!n)return void console.error(`Failed to parse phone number ${r}`);const s=n.countryCode;try{let r;if(o.requiresExplicitMNO(s)){if(e.channel&&"string"==typeof e.channel){if(!o.isValidMNOForCountry(e.channel,s))return void console.warn(`Invalid MNO ${e.channel} for country ${s}`);r=e.channel}}else if(r=null===(t=o.getMNOByPhoneNumber(n.e164Format,s))||void 0===t?void 0:t.id,!r)return void console.warn(`Failed to auto-detect MNO for phone number ${n.e164Format}`);return new j(e.displayName,n,r)}catch(e){return void console.error(`Failed to create MobileContactInfo: ${e}`)}}static fromPayoutDTO(e){var t;try{if(!n.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const r=a.from(e.msisdn,{defaultCountry:e.countryCode});if(!r)return void console.error(`Failed to parse phone number: ${e.msisdn}`);let s;if(o.requiresExplicitMNO(r.countryCode)){if(e.channel&&"string"==typeof e.channel){if(!o.isValidMNOForCountry(e.channel,r.countryCode))return void console.warn(`Invalid MNO ${e.channel} for country ${r.countryCode} in PayoutDTO`);s=e.channel}}else if(s=null===(t=o.getMNOByPhoneNumber(r.e164Format,r.countryCode))||void 0===t?void 0:t.id,!s)return void console.warn(`Failed to auto-detect MNO for phone number ${r.e164Format}`);return new j(e.payeeName,r,s)}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 t=e;if("string"!=typeof t.name||!t.name.trim())return!1;let r;if("string"==typeof t.phoneNumber)r=a.from(t.phoneNumber);else if("object"==typeof t.phoneNumber){const e=t.phoneNumber;a.is(e)&&(r=a.from(e.e164Format))}if(!r)return!1;const n=t.mnoId;if("string"!=typeof n)return!1;if(!o.isValidMNOForCountry(n,r.countryCode))return!1;if(o.requiresExplicitMNO(r.countryCode))return!0;{const e=o.getMNOByPhoneNumber(r.e164Format,r.countryCode);return(null==e?void 0:e.id)===n}}validate(){var e,t;try{return!!(null===(e=this.name)||void 0===e?void 0:e.trim())&&(!!(null===(t=this.phoneNumber)||void 0===t?void 0:t.validate())&&(!!o.isValidMNOForCountry(this.mnoId,this.countryCode)&&(!!o.requiresExplicitMNO(this.countryCode)||o.validateMNOForPhoneNumber(this.phoneNumber.e164Format,this.mnoId,this.countryCode))))}catch(e){return!1}}getValidationDetails(){var e,t;const r=[];if((null===(e=this.name)||void 0===e?void 0:e.trim())||r.push("Name is required"),(null===(t=this.phoneNumber)||void 0===t?void 0:t.validate())||r.push("Phone number is invalid"),o.isValidMNOForCountry(this.mnoId,this.countryCode)||r.push(`Invalid MNO ${this.mnoId} for country ${this.countryCode}`),!o.requiresExplicitMNO(this.countryCode)){const e=o.getMNOByPhoneNumber(this.phoneNumber.e164Format,this.countryCode);(null==e?void 0:e.id)!==this.mnoId&&r.push("MNO doesn't match auto-detected value from phone number prefix")}return{isValid:0===r.length,errors:r,warnings:[]}}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(s.E164)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){var e,t;const r=o.getMNOById(this.mnoId,this.countryCode);return null!==(t=null!==(e=null==r?void 0:r.mobileMoneyService)&&void 0!==e?e:null==r?void 0:r.displayName)&&void 0!==t?t:this.mnoId}}class T extends _{constructor(e,r,n){if(super(S.Bank,r.countryCode),this.accName=e,this.bank=r,this.accNo=n,!t.validateAccountName(e))throw new P("Invalid account name",{operation:"constructor",countryCode:r.countryCode});if(!t.validateAccountNumber(n,r.countryCode))throw new P("Invalid account number",{operation:"constructor",countryCode:r.countryCode})}static fromContactDTO(e){if("Bank"!==e.type)return;const n=e.channel;if(!n||"string"!=typeof n)return void console.error("SWIFT code is required for bank contacts");const o=t.getCountryFromSwiftCode(n);if(o)if(t.validateSwiftCode(n,o))try{const t=r.from(n,o);if(!t)throw new Error(`Bank with SWIFT code ${n} not found`);return new T(e.displayName,t,e.accountNo)}catch(e){return void console.error(`Failed to create BankContactInfo: ${e}`)}else console.error(`Invalid SWIFT code ${n} for country ${o}`);else console.error(`Could not identify country from SWIFT code: ${n}`)}static fromPayoutDTO(e){try{if(!n.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const o=e.msisdn.trim().split(":");if(2!==o.length)return void console.error("Invalid PayoutDTO format for bank - expected 'swiftcode:accountno'");const[a,s]=o;if(!t.validateSwiftCode(a,e.countryCode))return void console.error(`Invalid SWIFT code ${a} for country ${e.countryCode}`);const i=r.from(a,e.countryCode);return i?new T(e.payeeName,i,s):void console.error(`Bank with SWIFT code ${a} 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 n=e;if("string"!=typeof n.accName)return!1;if("string"!=typeof n.accNo)return!1;if(!n.bank||!r.is(n.bank))return!1;const o=n.accName,a=n.accNo,s=n.bank,i=t.validateAccountName(o),c=t.validateAccountNumber(a,s.countryCode);return i&&c}validate(){try{return t.validateAccountName(this.accName)&&t.validateAccountNumber(this.accNo,this.bank.countryCode)&&r.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 R{constructor(e){this.data=D.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===S.Mobile?j.fromContactDTO(this.data):this.data.type===S.Bank?T.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 j?"Phone Number":e instanceof T?"Bank Account Number":"Account Number"}get channelLabel(){const e=this.info;return e instanceof j?"Channel":e instanceof T?"Bank":"Channel"}get accNameLabel(){const e=this.info;return e instanceof j?"Full Name":e instanceof T?"Bank Account Name":"Display Name"}get channelName(){const e=this.info;return e instanceof j||e instanceof T?e.channelName:""}static create(e){return new R(e)}static createMany(e){return e.map(e=>new R(e))}static createSafe(e){try{return new R(e)}catch(e){return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=D.contactDTO.safeParse(e);if(!t.success)return!1;return null!==R.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&R.canConstruct(e.data))}toJSON(){return Object.assign({},this.data)}}var U,k,M;!function(e){e.MOBILE="Mobile",e.BANK="Bank"}(U||(U={})),function(e){e.CREATED="CREATED",e.PENDING="PENDING",e.PAID="PAID",e.FAILED="FAILED",e.REJECTED="REJECTED",e.REVERSED="REVERSED"}(k||(k={})),function(e){e.PENDING="Pending",e.APPROVED="Approved",e.REJECTED="Rejected"}(M||(M={}));const x=e.object({id:e.string(),name:e.string(),identity:e.string()}),B=e.nativeEnum(k),$=e.nativeEnum(M),J=e.object({channel:e.string(),msisdn:e.string(),amount:e.coerce.number(),description:e.string(),notes:e.string().nullish()}),W=J.extend({payeeName:e.string()}),F={PayoutDTO:J.extend({id:e.string(),profileId:e.string(),payeeName:e.string(),countryCode:e.string().default("TZ").refine(e=>n.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.string().default("TZS").refine(e=>i.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),channel:e.string(),status:B,statusMessage:e.string(),partnerReference:e.string().nullish(),createdAt:e.coerce.date(),updatedAt:e.coerce.date(),actionedAt:e.coerce.date().nullish(),approvalStatus:$.nullish(),createdBy:x.nullish(),actionedBy:x.nullish()}),PayoutInputDTO:W,PayoutStatus:B,PayoutApprovalStatus:$,PayoutAuthorizer:x};class q{constructor(e){this.data=F.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 c.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?k.REJECTED:"Approved"===this.data.approvalStatus?"FAILED"===this.data.status?k.FAILED:k.PAID:"Pending"===this.data.approvalStatus?k.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 actionedAt(){return this.data.actionedAt}get approvalStatus(){return this.data.approvalStatus}get createdBy(){return this.data.createdBy}get actionedBy(){return this.data.actionedBy}get contactInfo(){return"TZ-BANK-B2C"===this.channel?T.fromPayoutDTO(this.data):j.fromPayoutDTO(this.data)}static create(e){return new q(e)}static createMany(e){return e.map(e=>new q(e))}static createSafe(e){try{return new q(e)}catch(e){return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=F.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==q.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&q.canConstruct(e.data))}toJSON(){return Object.assign({},this.data)}}const z={profileDTOSchema:e.object({id:e.string(),firstName:e.string().nullish(),lastName:e.string().nullish(),displayName:e.string(),phone:e.string().nullish(),accountNo:e.string().min(1),email:e.string().email().nullish(),autoApprove:e.boolean().nullish()})};class L{static get schema(){return z.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 L({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 L.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 L.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?L.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 V{constructor(e){const{profile:t,token:r,access:n,resetPassword:o,name:a,identity:s}=e;this.profile=t,this.token=r,this.resetPassword=o,this.name=a,this.identity=s,this.access=n,this.accessMap={};for(const e of Object.values(C))"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 V.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(L.is(n))r=n;else{if("object"!=typeof n||null===n)return void console.error("Invalid profile format:",typeof n);if(r=L.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 V({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 G=e=>e.optional().transform(e=>null!=e?e:void 0),H={walletDTO:e.object({id:e.string().min(1,{message:"Wallet ID is required."}),profileId:e.string().min(1,{message:"Profile ID is required."}),accountNo:e.string().min(1,{message:"Account number is required."}),accountName:e.string().min(1,{message:"Account name is required."}),channel:e.string().min(1,{message:"Channel is required."}),countryCode:e.string().default("TZ").refine(e=>n.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.string().default("TZS").refine(e=>i.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:e.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:e.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:e.object({id:e.string().optional(),profileId:e.string().optional(),accountNo:e.string().optional(),accountName:e.string().optional(),channel:e.string().optional(),countryCode:e.string().default("TZ").refine(e=>u.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:e.string().default("TZS").refine(e=>{const t=d.from(e);return void 0!==t&&l.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:e.object({accountNo:G(e.string()),debitOrCredit:e.string().min(1,"Transaction type is required"),tranRefNo:e.string().min(1,"Transaction reference is required"),narration:e.string().min(1,"Transaction description is required"),txnDate:e.coerce.date({errorMap:()=>({message:"Invalid transaction date format"})}),valueDate:e.coerce.date({errorMap:()=>({message:"Invalid value date format"})}),amountCredited:e.number().min(0,"Credited amount must be non-negative"),amountDebited:e.number().min(0,"Debited amount must be non-negative"),balance:e.number(),currencyCode:G(e.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})};class Z{static get schema(){return H.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=Z.schema.safeParse(e);if(t.success)return new Z(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=Z.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 Z.from(t)}catch(e){return void console.error("Error parsing wallet JSON:",e)}}static from(e){if(e&&"object"==typeof e)return Z.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 t=e;return"string"==typeof t.id&&"string"==typeof t.profileId&&"string"==typeof t.accountNo&&"string"==typeof t.accountName&&"string"==typeof t.channel&&"string"==typeof t.countryCode&&n.isISO2CountryCode(t.countryCode)&&"string"==typeof t.currencyCode&&i.isCurrencyCode(t.currencyCode)&&"string"==typeof t.createdAt&&"string"==typeof t.updatedAt&&"function"==typeof t.toObject&&"function"==typeof t.validate}}const Y="MOBILE TRANSFER ",K="PAYOUT",Q="PAYOUT TO BANK",X="TO_BANK",ee="PAYOUT TO MOBILE",te="TO_MOMO";class re{constructor(e){this.getContactDetails=()=>{const e=this.getBankContactDetails(),t=this.getMobileContactDetails();return e||(t||void 0)},this.getBankContactDetails=()=>{let e=this.text.trim();e.startsWith(Y)&&(e=e.substring(16));try{if(e.startsWith(K)){const n=e.replace(K,"").trim().split(" ");if(n.length>=3){const e=n[0],o=n[1],a=n.slice(2).map(ne).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const n=t.getCountryFromSwiftCode(e);if(n){if(t.validateSwiftCode(e,n)){const t=r.from(e,n);if(o&&a&&t)return new T(a,t,o)}}}}}if(e.startsWith(X)){const n=e.split("=>")[1].trim(),o=JSON.parse(n),a=o.account_number,s=o.account_name,i=o.swift_code,c=t.getCountryFromSwiftCode(i);if(!c)return;if(!t.validateSwiftCode(i,c))return;const d=r.from(i,c);if(a&&s&&d)return new T(s,d,a)}if(e.startsWith(Q)){const t=e.replace(Q,"").trim().split(" "),r=m.getInstance().searchBanks("TZ",t[0]),n=r.length>0?r[0]:void 0,o=t[1],a=t.slice(2).map(ne).join(" ");if(a&&o&&n)return new T(a,n,o)}}catch(e){return}},this.getMobileContactDetails=()=>{let e=this.text.trim();e.startsWith(Y)&&(e=e.substring(16));try{if(e.startsWith(K)){const t=e.replace(K,"").trim().split(" ");if(t.length>=2){const e=t[0],r=t.slice(1).map(ne).join(" ");if(e.startsWith("+")){const t=h.from(e);if(t&&r)return new j(r,t)}}}if(e.startsWith(te)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=h.from(r.phone_number);let o=r.username;void 0===o&&(o="");let a=o.split(" ");if(a=a.filter(e=>e.trim().length>0),o=a.map(ne).join(" "),n&&o)return new j(o,n)}if(e.startsWith(ee)){const t=e.replace(ee,"").trim().split(" "),r=h.from(t[0]),n=t.slice(1).map(ne).join(" ");if(r&&n)return new j(n,r)}}catch(e){return}},this.text=e}get mediumText(){return this.text.length>50?this.text.substring(0,47)+"...":this.text}get shortText(){return this.text.length>35?this.text.substring(0,32)+"...":this.text}static generateDefaultPayoutNarration(e){return j.is(e)?re.generateMobilePayoutNarrationV2(e):T.is(e)?re.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${K.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:n}=e;return`${K.toUpperCase()} ${t.swiftCode.trim()} ${n.trim()} ${r.trim()}`.toUpperCase()}toJson(){return{text:this.text,version:"2.0"}}static fromJson(e){try{let t;return t="string"==typeof e?JSON.parse(e):e,t&&"object"==typeof t&&"string"==typeof t.text?new re(t.text):void console.warn("Invalid NarrationJson: missing or invalid text property")}catch(e){return void console.error("Error parsing NarrationJson:",e)}}static isNarrationJson(e){if(!e||"object"!=typeof e)return!1;return"string"==typeof e.text}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;try{return"string"==typeof t.text&&"function"==typeof t.getContactDetails&&"function"==typeof t.toJson}catch(e){return!1}}}function ne(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}class oe{static get schema(){return H.statementEntry}constructor(e,t){this._accountNo=e.accountNo,this._debitOrCredit=e.debitOrCredit,this._tranRefNo=e.tranRefNo,this._narration=t,this._txnDate=e.txnDate,this._valueDate=e.valueDate,this._currencyCode=e.currencyCode;const r=d.from(e.currencyCode);if(!r)throw new Error(`Currency not found for code: ${e.currencyCode}`);const n=c.from(e.amountCredited,r.code),o=c.from(e.amountDebited,r.code),a=c.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="string"==typeof e.narration?new re(e.narration):e.narration,r=Object.assign(Object.assign({},e),{narration:t.text}),n=oe.schema.safeParse(r);if(n.success)try{const e=n.data,{narration:r}=e,o=g(e,["narration"]);return new oe(o,t)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",n.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.toJson(),txnDate:this._txnDate.toISOString(),valueDate:this._valueDate.toISOString(),amountCredited:this._amountCredited.toJson(),amountDebited:this._amountDebited.toJson(),balance:this._balance.toJson(),currencyCode:this._currencyCode,version:"2.0"}}static fromJson(e){try{let t;if(t="string"==typeof e?JSON.parse(e):e,!(t&&"object"==typeof t&&"string"==typeof t.debitOrCredit&&"string"==typeof t.tranRefNo&&t.narration&&"string"==typeof t.txnDate&&"string"==typeof t.valueDate&&"string"==typeof t.currencyCode&&t.amountCredited&&t.amountDebited&&t.balance))return void console.warn("Invalid WalletStatementEntryJson: missing or invalid required properties");const r=re.fromJson(t.narration);if(!r)return void console.warn("Invalid WalletStatementEntryJson: failed to deserialize narration");const n=c.fromJson(t.amountCredited),o=c.fromJson(t.amountDebited),a=c.fromJson(t.balance);return n&&o&&a?n.currencyCode!==t.currencyCode||o.currencyCode!==t.currencyCode||a.currencyCode!==t.currencyCode?void console.warn("Invalid WalletStatementEntryJson: currency code mismatch"):oe.create({accountNo:t.accountNo,debitOrCredit:t.debitOrCredit,tranRefNo:t.tranRefNo,narration:r,txnDate:t.txnDate,valueDate:t.valueDate,amountCredited:n.numericValue,amountDebited:o.numericValue,balance:a.numericValue,currencyCode:t.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 t=e;return"string"==typeof t.debitOrCredit&&"string"==typeof t.tranRefNo&&re.isNarrationJson(t.narration)&&"string"==typeof t.txnDate&&"string"==typeof t.valueDate&&"string"==typeof t.currencyCode&&(void 0===t.accountNo||"string"==typeof t.accountNo)&&c.isAmountJson(t.amountCredited)&&c.isAmountJson(t.amountDebited)&&c.isAmountJson(t.balance)}validate(){const e={accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.text,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode},t=oe.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 t=e;try{return("string"==typeof t.accountNo||void 0===t.accountNo)&&"string"==typeof t.debitOrCredit&&"string"==typeof t.tranRefNo&&re.is(t.narration)&&t.txnDate instanceof Date&&t.valueDate instanceof Date&&c.is(t.amountCredited)&&c.is(t.amountDebited)&&c.is(t.balance)&&"string"==typeof t.currencyCode&&"function"==typeof t.toJson&&"function"==typeof t.validate}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return oe.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]}${this._narration})`}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=>oe.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.text,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 oe.fromJson(e)}static from(e){if(e&&"object"==typeof e)try{let t,r,n,o,a=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const o=c.fromJson(e.amountCredited),s=c.fromJson(e.amountDebited),i=c.fromJson(e.balance);if(!o||!s||!i)return void console.error("Failed to deserialize Amount objects from JSON");t=o.numericValue,r=s.numericValue,n=i.numericValue,e.currencyCode||(a=o.currencyCode)}else if(t=Number(e.amountCredited),r=Number(e.amountDebited),n=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)o=e.narration;else if(re.is(e.narration))o=e.narration;else{if(!re.isNarrationJson(e.narration))return void console.error("Invalid narration data");{const t=re.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");o=t}}return oe.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:o,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:r,balance:n,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 ae{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 ae(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 se{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 ie extends se{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 ae(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 ie(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=>ie.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 ce=e=>"function"==typeof(null==e?void 0:e.passthrough);e.object({name:e.literal("ZodError"),issues:e.array(e.object({path:e.array(e.union([e.string(),e.number()])),message:e.string().optional(),code:e.nativeEnum(e.ZodIssueCode)}).catchall(e.any()))});const de=Symbol("ContractNoBody"),le=e=>"method"in e&&"path"in e,ue=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,o,a,s,i;return le(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,ce(s)?ce(i)?s.merge(i):s:ce(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,ue(r,t)]})),me=Symbol("ContractPlainType"),he=()=>({router:(e,t)=>ue(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>me,body:()=>me,type:()=>me,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>de}),pe=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("&"):"",ye=e=>e?Object.keys(e).flatMap(t=>fe(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",fe=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>fe(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>fe(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class ge extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const ve=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}},we=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},be=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),Ne=(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?pe(e):ye(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,o);return`${t}${a}${s}`},Ce=(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:l,next:u,...m}=r||{},h={...t,...c};return{path:Ne(n,h.baseUrl,o,e,!!h.jsonQuery),clientArgs:h,route:e,body:a,query:n,extraInputArgs:m,fetchOptions:{...l&&{cache:l},...u&&{next:u},...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||ve,l=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),u={...l&&be(l),...be(i)};Object.keys(u).forEach(e=>{void 0===u[e]&&delete u[e]});let m={route:n,path:t,method:n.method,headers:u,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:we(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 ge(a,r)}},Oe=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>le(r)?[e,Ce(r,t)]:[e,Oe(r,t)]));function Ie(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 Se=e=>t=>{try{const r=e(t);return r instanceof Promise?r:{then:e=>Se(e)(r),catch(e){return this}}}catch(e){return{then(e){return this},catch:t=>Se(t)(e)}}},Ae=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?("production"!==(import.meta.env?import.meta.env.MODE:void 0)&&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 l=Se(a.serialize),u=()=>{const e=a.partialize({...n()});let t;const r=l({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),u()};const h=e((...e)=>{r(...e),u()},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 Se(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),u()}).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:Ie(()=>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 l=()=>{const e=a.partialize({...n()});return d.setItem(a.name,{state:e,version:a.version})},u=o.setState;o.setState=(e,t)=>{u(e,t),l()};const m=e((...e)=>{r(...e),l()},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 Se(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 l()}).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),Ee=w(Ae((e,t)=>({user:void 0,token:void 0,getUser:()=>{try{const e=t().user;if(e)return V.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:Ie(()=>"undefined"==typeof window?{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}:sessionStorage)})),De=()=>{if("undefined"!=typeof window)return Ee.getState().getToken()};class Pe{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=De();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":v()}};return Oe(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 N(e.body);if(401===e.status)throw new N({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new N({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new N({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new N({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}const _e=he().router({logIn:{method:"POST",path:"/login",body:e.object({type:e.string().default("password"),identity:e.string().email(),password:e.string()}),responses:{201:e.object({profile:z.profileDTOSchema,token:e.string(),access:e.array(e.string()),resetPassword:e.boolean()}),400:e.object({})}},access:{method:"GET",path:"/access",headers:e.object({token:e.string()}),responses:{200:e.string().array()}},resetPassword:{method:"PUT",path:"/password",body:e.object({currentPassword:e.string(),newPassword:e.string()}),responses:{}}}),je=he().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:e.object({name:e.string(),identity:e.string()})}}}),Te={400:e.object({statusCode:e.number(),message:e.string(),error:e.string(),details:e.record(e.string()).optional()})};class Re extends Pe{constructor(e){super("login",je,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 Ue extends Pe{constructor(e){super("auth",_e,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 N({message:"Invalid email or password",statusCode:400});if(201===n.status){const e=new Re({token:n.body.token}),t=await e.getIdentity(),r=V.from(Object.assign(Object.assign({},n.body),t));if(r)return r}throw new N({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 N({message:"Invalid current password",statusCode:400});throw new N({message:"An error occurred while trying to update password",statusCode:502})}}const ke={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)},Me=he().router({getWallets:{method:"GET",path:"/",query:H.walletQuery,responses:{200:e.array(Z.schema)}},getBalance:{method:"POST",path:"/balance",body:e.object({accountNo:e.string().optional()}),responses:{201:e.object({availableBalance:e.number()})}},getStatement:{method:"POST",path:"/statement",summary:"Get Wallet Statement",body:e.object({endDate:e.date(),startDate:e.date(),accountNo:e.string().optional()}),responses:{201:e.array(oe.schema)}}});class xe extends Pe{constructor(e){super("wallet",Me,e)}async getBalance(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");if(e.wallet){const t=await this.client.getBalance({body:{accountNo:e.wallet.accountNo}});if(201===t.status){const r=t.body.availableBalance,n=c.from(r,e.wallet.currencyCode);if(n)return n}}if(e.accountNo){const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);const r=t[0],n=await this.client.getBalance({body:{accountNo:e.accountNo}});if(201===n.status){const e=n.body.availableBalance,t=c.from(e,r.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}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=Z.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;if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");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};let s,i;if(e.wallet)s=e.wallet,i=e.wallet.accountNo;else{if(!e.accountNo)throw new Error("Either wallet or accountNo must be provided");{const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);s=t[0],i=e.accountNo}}const c=Object.assign(Object.assign({},a),{accountNo:i}),d=await this.client.getStatement({body:c});if(201===d.status){return d.body.map(e=>Object.assign(Object.assign({},e),{currencyCode:s.currencyCode})).reduce((e,t)=>{const r=oe.create(t);return r?e.push(r):console.warn("[WalletRepository] Skipping invalid statement entry:",t),e},[])}throw new Error(`Failed to fetch statement. Status: ${d.status}`)}}const Be=w()(Ae((e,t)=>({userId:"",wallets:[],selectedWalletId:"",selectedCountryCode:"TZ",lastSynced:new Date,isInitialized:!1,setWallets:r=>{const n=r.filter(e=>Z.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(!Z.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:Ie(()=>sessionStorage,{reviver:(e,t)=>{if("wallets"===e&&Array.isArray(t))return t.map(e=>{try{const t=Z.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 Z&&"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 $e{constructor(){this.repo=new xe}static get instance(){return this._instance||(this._instance=new $e),this._instance}isInitialized(){return Be.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.");Be.getState().setWallets(e)}catch(e){throw console.error("Failed to refresh wallets:",e),e}}getWallets(){const e=Be.getState();if(!e.isInitialized)throw new Error("Cannot get wallets: Wallet session not initialized.");return e.wallets}getCountries(){const e=this.getWallets();return ke.getUniqueCountries(e)}getWalletsByCountry(e){if(!this.isInitialized())throw new Error("Cannot get wallets by country: Wallet session not initialized.");return Be.getState()._getWalletsByCountry(e)}getSelectedWallet(){return Be.getState()._getSelectedWallet()}getSelectedCountryCode(){const e=Be.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 t=p.fromCode(e);if(!t)throw new Error(`Country.fromCode returned invalid result for code: ${e}`);return t}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=Be.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.");Be.getState().setSelectedCountry(e)}reset(){Be.getState().reset()}}class Je{constructor(){}static get instance(){return Je._instance||(Je._instance=new Je),Je._instance}get repo(){return new Ue({token:this.getUserToken()})}getUserToken(){return De()}get currentUser(){return(()=>{if("undefined"!=typeof window)return Ee.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=b(Ee,e=>e.user);try{return e?V.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 Ue,n=await r.logIn(e,t);this.clearSavedData(),Ee.getState().setUserAndToken(n,n.token);try{await $e.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(){Ee.getState().clearAuth();try{$e.instance.reset()}catch(e){console.warn("Failed to reset wallet session manager:",e)}}}Je._instance=null;const We=he().router({getAccessList:{method:"GET",path:"/access",responses:{200:e.string().array()}}});class Fe extends Pe{constructor(e){super("auth",We,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}`)}}const qe=he().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:L.schema}}});class ze extends Pe{constructor(e){super("profile",qe,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=L.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}`)}}const Le=he().router({createContact:{method:"POST",path:"/",body:D.contactInputDTO,responses:{201:D.contactDTO}},editContact:{method:"PATCH",path:"/:id",body:D.contactInputDTO,responses:{200:D.contactDTO}},getContacts:{method:"GET",path:"/",query:e.object({orderByDesc:e.string()}),responses:{200:e.array(D.contactDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:D.contactDTO}},deleteContact:{method:"DELETE",path:"/:id",body:e.object({}),responses:{200:e.object({})}}},{commonResponses:Te});class Ve{canHandle(e){return"Mobile"===e.type&&j.is(e)}createInput(e){if(j.is(e))return{type:S.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Contact Info")}}class Ge{canHandle(e){return"Bank"===e.type&&T.is(e)}createInput(e){if(T.is(e))return{type:S.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Contact Info")}}class He{constructor(){this.handlers=[new Ve,new Ge]}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)}}class Ze extends Pe{constructor(e){super("contact",Le,e)}async create(e){const t=(new He).resolve(e),r=await this.client.createContact({body:t}),n=this.handleResponse(r,201);return R.create(n)}async edit(e,t){const r=(new He).resolve(t),n=await this.client.editContact({params:{id:e},body:r}),o=this.handleResponse(n,200);return R.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 R.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return R.create(r)}}const Ye=he().router({getPayouts:{method:"GET",path:"",query:e.object({rangeStart:e.number(),rangeEnd:e.number(),eager:e.string(),approvalStatus:F.PayoutApprovalStatus.nullable().optional(),orderByDesc:e.string(),msisdn:e.string().optional()}),responses:{200:e.object({results:e.array(F.PayoutDTO),total:e.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:e.object({rangeStart:e.number(),rangeEnd:e.number(),eager:e.string(),approvalStatus:F.PayoutApprovalStatus,orderByDesc:e.string()}),responses:{200:e.object({results:e.array(F.PayoutDTO),total:e.number()})}},postPayout:{method:"POST",path:"",body:F.PayoutInputDTO,responses:{201:F.PayoutDTO,400:N.schema}},approve:{method:"POST",path:"/:id/approve",body:e.object({action:e.enum(["Approve","Reject"]),notes:e.string().optional()}),responses:{201:F.PayoutDTO,404:e.object({}),409:e.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:F.PayoutDTO,404:e.object({})}}}),Ke={SUPPORTED_COUNTRY_CODES:["TZ","KE"],ERROR_MESSAGES:{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 Qe{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}}class Xe{static forBank(e,t){if(!Ke.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ke.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,t,r){if(!a.is(e))throw new Error(Ke.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!Ke.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ke.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!y.checkPayoutEligibility(e))throw new Error(Ke.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const n=o.getMNOById(t,e.countryCode);if(!n)throw new Error(Ke.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return n.id===f.VODACOM?`${r.countryCode}-${f.TIGO.toString().toUpperCase()}-B2C`:`${r.countryCode}-${n.id.toString().toUpperCase()}-B2C`}}class et{canHandle(e,t,r){var n;return e===U.MOBILE&&j.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===(null===(n=p.from(t.countryCode))||void 0===n?void 0:n.currencyCode)}createInput(e,t){const r=e.receiver,n=Qe.processNotes(e.notes),o=r.phoneNumber;return{channel:Xe.forMobile(o,r.mnoId,t),msisdn:o.getWithFormat(s.INTERNATIONAL_NUMERIC),description:null!=n?n:re.generateDefaultPayoutNarration(r),payeeName:r.name,notes:n,amount:e.amount.numericValue}}}class tt{canHandle(e,t,r){var n;return e===U.BANK&&T.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===(null===(n=p.from(t.countryCode))||void 0===n?void 0:n.currencyCode)}createInput(e,t){const r=e.receiver,n=Qe.processNotes(e.notes);return{channel:Xe.forBank(r,t),msisdn:`${r.bank.swiftCode}:${r.accNo}`,description:null!=n?n:re.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:n,amount:e.amount.numericValue}}}class rt{constructor(){this.handlers=[new et,new tt]}getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(Ke.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const nt={bank:Xe.forBank,mobile:Xe.forMobile};class ot extends Pe{constructor(e){super("payout",Ye,e)}async getAll(e){var t,r;const n=null!==(t=null==e?void 0:e.rangeStart)&&void 0!==t?t:0,o=null!==(r=null==e?void 0:e.rangeEnd)&&void 0!==r?r:10,a=M.PENDING,s={rangeStart:n,rangeEnd:o,eager:"[createdBy,actionedBy]",orderByDesc:"createdAt"};if((null==e?void 0:e.pending)&&Object.assign(s,{approvalStatus:a}),(null==e?void 0:e.msisdn)&&Object.assign(s,{msisdn:e.msisdn}),o<=n)throw new N({message:"Invalid range: end-date must be greater than start-date",statusCode:400});const i=await this.client.getPayouts({query:s});if(200===i.status)return{results:q.createMany(i.body.results),total:i.body.total};throw N.unknown("An error occurred while fetching payouts")}async pay(e){const{min:t,max:r}=c.getTransactionLimits(e.amount.currencyCode);if(e.amount.lessThan(t)||e.amount.greaterThan(r))throw new N({statusCode:400,message:`Please make sure the amount is between ${t.label} - ${r.label}`});const n=$e.instance.getSelectedWallet();if(!n)throw new Error("You have not selected a wallet to process this payout");const o=(new rt).getPayoutInput(e,n),a=await this.client.postPayout({body:o});if(201===a.status)return q.create(a.body);if(400===a.status)throw new N(a.body);throw N.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 q.create(r.body);if(404===r.status)throw new N({message:"Payout not found",statusCode:404});if(409===r.status)throw new N({message:"Payout already approved",statusCode:409});throw N.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 q.create(r.body);if(404===r.status)throw new N({message:"Payout not found",statusCode:404});if(409===r.status)throw new N({message:"Payout already rejected",statusCode:409});throw N.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return q.create(t.body);if(404===t.status)throw new N({message:"Payout not found",statusCode:404});throw N.unknown()}}const at=e.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"),st=e.object({id:e.string().min(1),name:e.string().min(1,"Role name is required"),description:e.string().optional(),access:e.array(e.string()),createdAt:e.string().datetime("Invalid creation timestamp"),updatedAt:e.string().datetime("Invalid update timestamp")}),it=e.object({id:e.string().min(1),name:e.string().min(1,"User name is required"),identity:e.string().email("Invalid email address"),type:e.string().min(1,"User type is required"),profileId:e.string().min(1,"Profile ID is required"),roleId:e.string().min(1,"Role ID is required"),resetPassword:e.boolean(),isActive:e.boolean(),isArchived:e.boolean(),role:st.optional(),createdAt:e.string().datetime("Invalid creation timestamp"),updatedAt:e.string().datetime("Invalid update timestamp")}),ct={role:st,managedUser:it,managedUserQueryParams:e.object({id:e.string().min(1).optional(),name:e.string().min(1).optional(),identity:e.string().email("Invalid email address").optional(),type:e.string().min(1).optional(),profileId:e.string().min(1).optional(),roleId:e.string().min(1).optional(),resetPassword:e.number().optional(),isActive:e.number().optional(),isArchived:e.number().optional(),createdAt:e.string().datetime("Invalid creation timestamp").optional(),updatedAt:e.string().datetime("Invalid update timestamp").optional(),eager:e.string().optional()}),createUserRequest:e.object({name:e.string().min(1,"User name is required"),identity:e.string().email("Valid email address is required"),password:at.optional(),roleId:e.string().optional(),resetPassword:e.boolean().optional()}),updateUserRequest:e.object({name:e.string().min(1,"User name cannot be empty").optional(),roleId:e.string().min(1,"Role ID cannot be empty").optional(),password:at.optional(),resetPassword:e.boolean().optional(),isActive:e.boolean().optional()}),resetPasswordRequest:e.object({newPassword:at.optional(),sendNotification:e.boolean().optional()}),createUserResponse:e.object({id:e.string(),name:e.string(),identity:e.string(),type:e.string(),profileId:e.string(),roleId:e.string(),isActive:e.boolean(),isArchived:e.boolean(),createdAt:e.string().datetime()}),password:at},dt=he().router({getUsers:{method:"GET",path:"/login",query:ct.managedUserQueryParams,responses:{200:e.array(ct.managedUser),401:e.object({message:e.string().optional()}),403:e.object({message:e.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.object({id:e.string()}),query:ct.managedUserQueryParams,responses:{200:ct.managedUser,401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),404:e.object({message:e.string().optional()})},summary:"Get user account details",description:"Retrieve detailed information about a specific user account"},createUser:{method:"POST",path:"/login",body:ct.createUserRequest,responses:{201:ct.createUserResponse,400:e.object({message:e.string().optional(),errors:e.array(e.string()).optional()}),401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),409:e.object({message:e.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.object({id:e.string()}),body:ct.updateUserRequest,responses:{200:ct.managedUser,400:e.object({message:e.string().optional(),errors:e.array(e.string()).optional()}),401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),404:e.object({message:e.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.object({id:e.string()}),body:e.object({}),responses:{200:ct.managedUser,401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),404:e.object({message:e.string().optional()})},summary:"Archive user account",description:"Archive (soft delete) a user account"},unArchiveUser:{method:"POST",path:"/login/:id/unarchive",pathParams:e.object({id:e.string()}),body:e.object({}),responses:{200:ct.managedUser,401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),404:e.object({message:e.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.object({id:e.string()}),body:ct.resetPasswordRequest,responses:{200:e.object({success:e.boolean()}),400:e.object({message:e.string().optional()}),401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),404:e.object({message:e.string().optional()})},summary:"Reset user password",description:"Reset a user's password and optionally send notification"},getRoles:{method:"GET",path:"/role",responses:{200:e.array(ct.role),401:e.object({message:e.string().optional()}),403:e.object({message:e.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.object({id:e.string()}),responses:{200:ct.role,401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),404:e.object({message:e.string().optional()})},summary:"Get role details",description:"Retrieve detailed information about a specific role"}});class lt extends Pe{constructor(e){super("admin",dt,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=ie.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=ie.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=ie.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 ie.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=ie.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=ae.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=ae.from(r);if(!n)throw new Error("Invalid role data received from server");return n}}export{N as APIError,Fe as AccessRepository,Je as AfloatAuth,Ue as AuthRepository,Q as BANK_NARR_PREFIX,T as BankContactInfo,R as Contact,D as ContactDTOSchemas,Ze as ContactRepository,S as ContactType,Y as ECOBANK_PREFIX,Re as IdentityRepository,X as LEGACY_BANK_NARR_PREFIX,te as LEGACY_MOBILE_NARR_PREFIX,ee as MOBILE_NARR_PREFIX,ie as ManagedUser,j as MobileContactInfo,K as NARR_V2_PREFIX,re as Narration,q as Payout,M as PayoutApprovalStatus,U as PayoutChannel,F as PayoutDTOSchemas,rt as PayoutInputFactory,ot as PayoutRepository,k as PayoutStatus,O as PermissionError,C as Permissions,L as Profile,ze as ProfileRepository,ae as Role,V as User,se as UserEntity,ct as UserManagementDTOSchemas,lt as UserManagementRepository,Z as Wallet,H as WalletDTOSchemas,xe as WalletRepository,$e as WalletSessionManager,oe as WalletStatementEntry,ke as WalletUtils,nt as createPayoutChannelCode,I as isError,Be as walletsStore};
1
+ import{z as e}from"zod";import{MNOUtils as t,PhoneNumber as r,CountryValidation as n,PhoneNumberFormat as o,BankValidation as a,Bank as s,CurrencyValidation as i,Amount as c,Currency as d,CurrencyCodesSet as u,ISO2CountryCodesSet as l,BankService as m,TZMobileNumber as h,Country as p,PhoneNumberFactory as y,TZMNOId as f}from"@temboplus/frontend-core";import{create as g,useStore as w}from"zustand";import{v4 as b}from"uuid";class v extends Error{statusCode;error;details;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 v.schema.safeParse(e).success}static unknown(e){return new v({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return e.object({message:e.string(),statusCode:e.number().int(),error:e.string().optional(),details:e.object({}).optional()})}}const N={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 C extends Error{requiredPermissions;constructor(e){super(e.message??`Missing required permissions: ${e.requiredPermissions.join(", ")}`),this.name="PermissionError",this.requiredPermissions=e.requiredPermissions}static is(t){const r=e.union([e.enum(Object.values(N.Profile)),e.enum(Object.values(N.Contact)),e.enum(Object.values(N.Payment)),e.enum(Object.values(N.Payout)),e.enum(Object.values(N.Transfer)),e.enum(Object.values(N.Wallet))]);return e.object({name:e.literal("PermissionError"),message:e.string(),requiredPermissions:e.array(r)}).safeParse(t).success}}function O(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message}var I;!function(e){e.Bank="Bank",e.Mobile="Mobile"}(I||(I={}));const S=e.nativeEnum(I),A=e.object({displayName:e.string().min(1,"Display name is required"),accountNo:e.string().min(1,"Account number is required"),channel:e.string().min(1,"Channel is required"),type:S}),E={contactDTO:e.object({id:e.string().min(1,"Contact id is required"),profileId:e.string(),createdAt:e.string().datetime(),updatedAt:e.string().datetime()}).merge(A),contactInputDTO:A,contactType:S};class _ extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="ContactInfoError"}}class D{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}}class P extends D{name;phoneNumber;mnoId;constructor(e,r,n){if(super(I.Mobile,r.countryCode),this.name=e,this.phoneNumber=r,!e?.trim())throw new _("Name is required and cannot be empty",{operation:"constructor",countryCode:r.countryCode,phoneNumber:r.e164Format});if(!r?.validate())throw new _("Invalid phone number",{operation:"constructor",countryCode:r.countryCode,phoneNumber:r.e164Format});if(t.requiresExplicitMNO(r.countryCode)){if(!n)throw new _(`MNO must be explicitly provided for phone numbers in ${r.countryCode} due to Mobile Number Portability`,{phoneNumber:r.e164Format,countryCode:r.countryCode,operation:"constructor"});if(!t.isValidMNOForCountry(n,r.countryCode)){const e=t.getCountryMNOs(r.countryCode).map(e=>e.id);throw new _(`Invalid MNO ${n} for country ${r.countryCode}. Valid MNOs: ${e.join(", ")}`,{phoneNumber:r.e164Format,countryCode:r.countryCode,mnoId:n,operation:"constructor"})}this.mnoId=n}else{const e=t.getMNOByPhoneNumber(r.e164Format,r.countryCode);if(!e?.id)throw new _(`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;let n=e.accountNo;n.startsWith("+")||(n=`+${n}`);const o=r.from(n);if(!o)return void console.error(`Failed to parse phone number ${n}`);const a=o.countryCode;try{let r;if(t.requiresExplicitMNO(a)){if(e.channel&&"string"==typeof e.channel){if(!t.isValidMNOForCountry(e.channel,a))return void console.warn(`Invalid MNO ${e.channel} for country ${a}`);r=e.channel}}else if(r=t.getMNOByPhoneNumber(o.e164Format,a)?.id,!r)return void console.warn(`Failed to auto-detect MNO for phone number ${o.e164Format}`);return new P(e.displayName,o,r)}catch(e){return void console.error(`Failed to create MobileContactInfo: ${e}`)}}static fromPayoutDTO(e){try{if(!n.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const o=r.from(e.msisdn,{defaultCountry:e.countryCode});if(!o)return void console.error(`Failed to parse phone number: ${e.msisdn}`);let a;if(t.requiresExplicitMNO(o.countryCode)){if(e.channel&&"string"==typeof e.channel){if(!t.isValidMNOForCountry(e.channel,o.countryCode))return void console.warn(`Invalid MNO ${e.channel} for country ${o.countryCode} in PayoutDTO`);a=e.channel}}else if(a=t.getMNOByPhoneNumber(o.e164Format,o.countryCode)?.id,!a)return void console.warn(`Failed to auto-detect MNO for phone number ${o.e164Format}`);return new P(e.payeeName,o,a)}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 n=e;if("string"!=typeof n.name||!n.name.trim())return!1;let o;if("string"==typeof n.phoneNumber)o=r.from(n.phoneNumber);else if("object"==typeof n.phoneNumber){const e=n.phoneNumber;r.is(e)&&(o=r.from(e.e164Format))}if(!o)return!1;const a=n.mnoId;if("string"!=typeof a)return!1;if(!t.isValidMNOForCountry(a,o.countryCode))return!1;if(t.requiresExplicitMNO(o.countryCode))return!0;{const e=t.getMNOByPhoneNumber(o.e164Format,o.countryCode);return e?.id===a}}validate(){try{return!!this.name?.trim()&&(!!this.phoneNumber?.validate()&&(!!t.isValidMNOForCountry(this.mnoId,this.countryCode)&&(!!t.requiresExplicitMNO(this.countryCode)||t.validateMNOForPhoneNumber(this.phoneNumber.e164Format,this.mnoId,this.countryCode))))}catch{return!1}}getValidationDetails(){const e=[];if(this.name?.trim()||e.push("Name is required"),this.phoneNumber?.validate()||e.push("Phone number is invalid"),t.isValidMNOForCountry(this.mnoId,this.countryCode)||e.push(`Invalid MNO ${this.mnoId} for country ${this.countryCode}`),!t.requiresExplicitMNO(this.countryCode)){const r=t.getMNOByPhoneNumber(this.phoneNumber.e164Format,this.countryCode);r?.id!==this.mnoId&&e.push("MNO doesn't match auto-detected value from phone number prefix")}return{isValid:0===e.length,errors:e,warnings:[]}}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(o.E164)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){const e=t.getMNOById(this.mnoId,this.countryCode);return e?.mobileMoneyService??e?.displayName??this.mnoId}}class j extends D{accName;bank;accNo;constructor(e,t,r){if(super(I.Bank,t.countryCode),this.accName=e,this.bank=t,this.accNo=r,!a.validateAccountName(e))throw new _("Invalid account name",{operation:"constructor",countryCode:t.countryCode});if(!a.validateAccountNumber(r,t.countryCode))throw new _("Invalid account number",{operation:"constructor",countryCode:t.countryCode})}static fromContactDTO(e){if("Bank"!==e.type)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank contacts");const r=a.getCountryFromSwiftCode(t);if(r)if(a.validateSwiftCode(t,r))try{const n=s.from(t,r);if(!n)throw new Error(`Bank with SWIFT code ${t} not found`);return new j(e.displayName,n,e.accountNo)}catch(e){return void console.error(`Failed to create BankContactInfo: ${e}`)}else console.error(`Invalid SWIFT code ${t} for country ${r}`);else console.error(`Could not identify country from SWIFT code: ${t}`)}static fromPayoutDTO(e){try{if(!n.isISO2CountryCode(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=e.msisdn.trim().split(":");if(2!==t.length)return void console.error("Invalid PayoutDTO format for bank - expected 'swiftcode:accountno'");const[r,o]=t;if(!a.validateSwiftCode(r,e.countryCode))return void console.error(`Invalid SWIFT code ${r} for country ${e.countryCode}`);const i=s.from(r,e.countryCode);return i?new j(e.payeeName,i,o):void console.error(`Bank with SWIFT code ${r} 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 t=e;if("string"!=typeof t.accName)return!1;if("string"!=typeof t.accNo)return!1;if(!t.bank||!s.is(t.bank))return!1;const r=t.accName,n=t.accNo,o=t.bank,i=a.validateAccountName(r),c=a.validateAccountNumber(n,o.countryCode);return i&&c}validate(){try{return a.validateAccountName(this.accName)&&a.validateAccountNumber(this.accNo,this.bank.countryCode)&&s.is(this.bank)}catch{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 T{data;constructor(e){this.data=E.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===I.Mobile?P.fromContactDTO(this.data):this.data.type===I.Bank?j.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 j?"Bank Account Number":"Account Number"}get channelLabel(){const e=this.info;return e instanceof P?"Channel":e instanceof j?"Bank":"Channel"}get accNameLabel(){const e=this.info;return e instanceof P?"Full Name":e instanceof j?"Bank Account Name":"Display Name"}get channelName(){const e=this.info;return e instanceof P||e instanceof j?e.channelName:""}static create(e){return new T(e)}static createMany(e){return e.map(e=>new T(e))}static createSafe(e){try{return new T(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=E.contactDTO.safeParse(e);if(!t.success)return!1;return null!==T.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&T.canConstruct(e.data))}toJSON(){return{...this.data}}}var R,U,k;!function(e){e.MOBILE="Mobile",e.BANK="Bank"}(R||(R={})),function(e){e.CREATED="CREATED",e.PENDING="PENDING",e.PAID="PAID",e.FAILED="FAILED",e.REJECTED="REJECTED",e.REVERSED="REVERSED"}(U||(U={})),function(e){e.PENDING="Pending",e.APPROVED="Approved",e.REJECTED="Rejected"}(k||(k={}));const M=e.object({id:e.string(),name:e.string(),identity:e.string()}),x=e.nativeEnum(U),B=e.nativeEnum(k),$=e.object({channel:e.string(),msisdn:e.string(),amount:e.coerce.number(),description:e.string(),notes:e.string().nullish()}),J=$.extend({payeeName:e.string()}),W={PayoutDTO:$.extend({id:e.string(),profileId:e.string(),payeeName:e.string(),countryCode:e.string().default("TZ").refine(e=>n.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.string().default("TZS").refine(e=>i.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),channel:e.string(),status:x,statusMessage:e.string(),partnerReference:e.string().nullish(),createdAt:e.coerce.date(),updatedAt:e.coerce.date(),actionedAt:e.coerce.date().nullish(),approvalStatus:B.nullish(),createdBy:M.nullish(),actionedBy:M.nullish()}),PayoutInputDTO:J,PayoutStatus:x,PayoutApprovalStatus:B,PayoutAuthorizer:M};class F{data;constructor(e){this.data=W.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 c.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?U.REJECTED:"Approved"===this.data.approvalStatus?"FAILED"===this.data.status?U.FAILED:U.PAID:"Pending"===this.data.approvalStatus?U.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 actionedAt(){return this.data.actionedAt}get approvalStatus(){return this.data.approvalStatus}get createdBy(){return this.data.createdBy}get actionedBy(){return this.data.actionedBy}get contactInfo(){return"TZ-BANK-B2C"===this.channel?j.fromPayoutDTO(this.data):P.fromPayoutDTO(this.data)}static create(e){return new F(e)}static createMany(e){return e.map(e=>new F(e))}static createSafe(e){try{return new F(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=W.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==F.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&F.canConstruct(e.data))}toJSON(){return{...this.data}}}const q={profileDTOSchema:e.object({id:e.string(),firstName:e.string().nullish(),lastName:e.string().nullish(),displayName:e.string(),phone:e.string().nullish(),accountNo:e.string().min(1),email:e.string().email().nullish(),autoApprove:e.boolean().nullish()})};class z{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return q.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 z({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(){if(this._displayName&&""!==this._displayName.trim())return this._displayName;return`${this._firstName??""} ${this._lastName??""}`.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 z.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 z.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?z.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 L{name;identity;profile;token;resetPassword;access;accessMap;constructor(e){const{profile:t,token:r,access:n,resetPassword:o,name:a,identity:s}=e;this.profile=t,this.token=r,this.resetPassword=o,this.name=a,this.identity=s,this.access=n,this.accessMap={};for(const e of Object.values(N))"object"==typeof e?Object.values(e).forEach(e=>{this.accessMap[e]=n.includes(e)}):this.accessMap[e]=n.includes(e)}can(e){return this.accessMap[e]??!1}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 L.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(z.is(n))r=n;else{if("object"!=typeof n||null===n)return void console.error("Invalid profile format:",typeof n);if(r=z.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 L({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 V=e=>e.optional().transform(e=>e??void 0),G={walletDTO:e.object({id:e.string().min(1,{message:"Wallet ID is required."}),profileId:e.string().min(1,{message:"Profile ID is required."}),accountNo:e.string().min(1,{message:"Account number is required."}),accountName:e.string().min(1,{message:"Account name is required."}),channel:e.string().min(1,{message:"Channel is required."}),countryCode:e.string().default("TZ").refine(e=>n.isISO2CountryCode(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.string().default("TZS").refine(e=>i.isCurrencyCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:e.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:e.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:e.object({id:e.string().optional(),profileId:e.string().optional(),accountNo:e.string().optional(),accountName:e.string().optional(),channel:e.string().optional(),countryCode:e.string().default("TZ").refine(e=>l.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:e.string().default("TZS").refine(e=>{const t=d.from(e);return void 0!==t&&u.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:e.object({accountNo:V(e.string()),debitOrCredit:e.string().min(1,"Transaction type is required"),tranRefNo:e.string().min(1,"Transaction reference is required"),narration:e.string().min(1,"Transaction description is required"),txnDate:e.coerce.date({errorMap:()=>({message:"Invalid transaction date format"})}),valueDate:e.coerce.date({errorMap:()=>({message:"Invalid value date format"})}),amountCredited:e.number().min(0,"Credited amount must be non-negative"),amountDebited:e.number().min(0,"Debited amount must be non-negative"),balance:e.number(),currencyCode:V(e.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})};class H{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return G.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=H.schema.safeParse(e);if(t.success)return new H(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=H.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 H.from(t)}catch(e){return void console.error("Error parsing wallet JSON:",e)}}static from(e){if(e&&"object"==typeof e)return H.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 t=e;return"string"==typeof t.id&&"string"==typeof t.profileId&&"string"==typeof t.accountNo&&"string"==typeof t.accountName&&"string"==typeof t.channel&&"string"==typeof t.countryCode&&n.isISO2CountryCode(t.countryCode)&&"string"==typeof t.currencyCode&&i.isCurrencyCode(t.currencyCode)&&"string"==typeof t.createdAt&&"string"==typeof t.updatedAt&&"function"==typeof t.toObject&&"function"==typeof t.validate}}const Z="MOBILE TRANSFER ",Y="PAYOUT",K="PAYOUT TO BANK",Q="TO_BANK",X="PAYOUT TO MOBILE",ee="TO_MOMO";class te{text;constructor(e){this.text=e}get mediumText(){return this.text.length>50?this.text.substring(0,47)+"...":this.text}get shortText(){return this.text.length>35?this.text.substring(0,32)+"...":this.text}static generateDefaultPayoutNarration(e){return P.is(e)?te.generateMobilePayoutNarrationV2(e):j.is(e)?te.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${Y.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:n}=e;return`${Y.toUpperCase()} ${t.swiftCode.trim()} ${n.trim()} ${r.trim()}`.toUpperCase()}getContactDetails=()=>{const e=this.getBankContactDetails(),t=this.getMobileContactDetails();return e||(t||void 0)};getBankContactDetails=()=>{let e=this.text.trim();e.startsWith(Z)&&(e=e.substring(16));try{if(e.startsWith(Y)){const t=e.replace(Y,"").trim().split(" ");if(t.length>=3){const e=t[0],r=t[1],n=t.slice(2).map(re).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=a.getCountryFromSwiftCode(e);if(t){if(a.validateSwiftCode(e,t)){const o=s.from(e,t);if(r&&n&&o)return new j(n,o,r)}}}}}if(e.startsWith(Q)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=r.account_number,o=r.account_name,i=r.swift_code,c=a.getCountryFromSwiftCode(i);if(!c)return;if(!a.validateSwiftCode(i,c))return;const d=s.from(i,c);if(n&&o&&d)return new j(o,d,n)}if(e.startsWith(K)){const t=e.replace(K,"").trim().split(" "),r=m.getInstance().searchBanks("TZ",t[0]),n=r.length>0?r[0]:void 0,o=t[1],a=t.slice(2).map(re).join(" ");if(a&&o&&n)return new j(a,n,o)}}catch(e){return}};getMobileContactDetails=()=>{let e=this.text.trim();e.startsWith(Z)&&(e=e.substring(16));try{if(e.startsWith(Y)){const t=e.replace(Y,"").trim().split(" ");if(t.length>=2){const e=t[0],n=t.slice(1).map(re).join(" ");if(e.startsWith("+")){const t=r.from(e);if(t&&n)return new P(n,t)}}}if(e.startsWith(ee)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=h.from(r.phone_number);let o=r.username;void 0===o&&(o="");let a=o.split(" ");if(a=a.filter(e=>e.trim().length>0),o=a.map(re).join(" "),n&&o)return new P(o,n)}if(e.startsWith(X)){const t=e.replace(X,"").trim().split(" "),r=h.from(t[0]),n=t.slice(1).map(re).join(" ");if(r&&n)return new P(n,r)}}catch(e){return}};toJson(){return{text:this.text,version:"2.0"}}static fromJson(e){try{let t;return t="string"==typeof e?JSON.parse(e):e,t&&"object"==typeof t&&"string"==typeof t.text?new te(t.text):void console.warn("Invalid NarrationJson: missing or invalid text property")}catch(e){return void console.error("Error parsing NarrationJson:",e)}}static isNarrationJson(e){if(!e||"object"!=typeof e)return!1;return"string"==typeof e.text}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;try{return"string"==typeof t.text&&"function"==typeof t.getContactDetails&&"function"==typeof t.toJson}catch(e){return!1}}}function re(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}class ne{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return G.statementEntry}constructor(e,t){this._accountNo=e.accountNo,this._debitOrCredit=e.debitOrCredit,this._tranRefNo=e.tranRefNo,this._narration=t,this._txnDate=e.txnDate,this._valueDate=e.valueDate,this._currencyCode=e.currencyCode;const r=d.from(e.currencyCode);if(!r)throw new Error(`Currency not found for code: ${e.currencyCode}`);const n=c.from(e.amountCredited,r.code),o=c.from(e.amountDebited,r.code),a=c.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="string"==typeof e.narration?new te(e.narration):e.narration,r={...e,narration:t.text},n=ne.schema.safeParse(r);if(n.success)try{const{narration:e,...r}=n.data;return new ne(r,t)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",n.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.toJson(),txnDate:this._txnDate.toISOString(),valueDate:this._valueDate.toISOString(),amountCredited:this._amountCredited.toJson(),amountDebited:this._amountDebited.toJson(),balance:this._balance.toJson(),currencyCode:this._currencyCode,version:"2.0"}}static fromJson(e){try{let t;if(t="string"==typeof e?JSON.parse(e):e,!(t&&"object"==typeof t&&"string"==typeof t.debitOrCredit&&"string"==typeof t.tranRefNo&&t.narration&&"string"==typeof t.txnDate&&"string"==typeof t.valueDate&&"string"==typeof t.currencyCode&&t.amountCredited&&t.amountDebited&&t.balance))return void console.warn("Invalid WalletStatementEntryJson: missing or invalid required properties");const r=te.fromJson(t.narration);if(!r)return void console.warn("Invalid WalletStatementEntryJson: failed to deserialize narration");const n=c.fromJson(t.amountCredited),o=c.fromJson(t.amountDebited),a=c.fromJson(t.balance);return n&&o&&a?n.currencyCode!==t.currencyCode||o.currencyCode!==t.currencyCode||a.currencyCode!==t.currencyCode?void console.warn("Invalid WalletStatementEntryJson: currency code mismatch"):ne.create({accountNo:t.accountNo,debitOrCredit:t.debitOrCredit,tranRefNo:t.tranRefNo,narration:r,txnDate:t.txnDate,valueDate:t.valueDate,amountCredited:n.numericValue,amountDebited:o.numericValue,balance:a.numericValue,currencyCode:t.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 t=e;return"string"==typeof t.debitOrCredit&&"string"==typeof t.tranRefNo&&te.isNarrationJson(t.narration)&&"string"==typeof t.txnDate&&"string"==typeof t.valueDate&&"string"==typeof t.currencyCode&&(void 0===t.accountNo||"string"==typeof t.accountNo)&&c.isAmountJson(t.amountCredited)&&c.isAmountJson(t.amountDebited)&&c.isAmountJson(t.balance)}validate(){const e={accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.text,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode},t=ne.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 t=e;try{return("string"==typeof t.accountNo||void 0===t.accountNo)&&"string"==typeof t.debitOrCredit&&"string"==typeof t.tranRefNo&&te.is(t.narration)&&t.txnDate instanceof Date&&t.valueDate instanceof Date&&c.is(t.amountCredited)&&c.is(t.amountDebited)&&c.is(t.balance)&&"string"==typeof t.currencyCode&&"function"==typeof t.toJson&&"function"==typeof t.validate}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return ne.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]}${this._narration})`}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=>ne.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.text,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 ne.fromJson(e)}static from(e){if(e&&"object"==typeof e)try{let t,r,n,o,a=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const o=c.fromJson(e.amountCredited),s=c.fromJson(e.amountDebited),i=c.fromJson(e.balance);if(!o||!s||!i)return void console.error("Failed to deserialize Amount objects from JSON");t=o.numericValue,r=s.numericValue,n=i.numericValue,e.currencyCode||(a=o.currencyCode)}else if(t=Number(e.amountCredited),r=Number(e.amountDebited),n=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)o=e.narration;else if(te.is(e.narration))o=e.narration;else{if(!te.isNarrationJson(e.narration))return void console.error("Invalid narration data");{const t=te.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");o=t}}return ne.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:o,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:r,balance:n,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 oe{id;name;description;permissions;createdAt;updatedAt;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(!e?.id||!e?.name||!Array.isArray(e?.access))return;return new oe(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 ae{id;name;identity;profileId;permissions;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 se extends ae{type;roleId;resetPassword;isActive;isArchived;role;createdAt;updatedAt;constructor(e){if(super({id:e.id,name:e.name,identity:e.identity,profileId:e.profileId,permissions:e.role?.access??[]}),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 oe(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(){return this.role?.name??""}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 e?.id&&e?.name&&e?.identity&&e?.roleId?new se(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=>se.from(e)).filter(Boolean)}toJSON(){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:this.role?.toJSON(),createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}}function ie(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 ce=e=>t=>{try{const r=e(t);return r instanceof Promise?r:{then:e=>ce(e)(r),catch(e){return this}}}catch(e){return{then(e){return this},catch:t=>ce(t)(e)}}},de=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?("production"!==(import.meta.env?import.meta.env.MODE:void 0)&&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=ce(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 ce(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:ie(()=>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 ce(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),ue={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)},le=e=>"function"==typeof(null==e?void 0:e.passthrough);e.object({name:e.literal("ZodError"),issues:e.array(e.object({path:e.array(e.union([e.string(),e.number()])),message:e.string().optional(),code:e.nativeEnum(e.ZodIssueCode)}).catchall(e.any()))});const me=Symbol("ContractNoBody"),he=e=>"method"in e&&"path"in e,pe=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,o,a,s,i;return he(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,le(s)?le(i)?s.merge(i):s:le(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,pe(r,t)]})),ye=Symbol("ContractPlainType"),fe=()=>({router:(e,t)=>pe(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>ye,body:()=>ye,type:()=>ye,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>me}),ge=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("&"):"",we=e=>e?Object.keys(e).flatMap(t=>be(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",be=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>be(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>be(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class ve extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const Ne=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}},Ce=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},Oe=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),Ie=(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?ge(e):we(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,o);return`${t}${a}${s}`},Se=(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:Ie(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||Ne,u=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...u&&Oe(u),...Oe(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:Ce(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 ve(a,r)}},Ae=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>he(r)?[e,Se(r,t)]:[e,Ae(r,t)])),Ee=fe().router({getWallets:{method:"GET",path:"/",query:G.walletQuery,responses:{200:e.array(H.schema)}},getBalance:{method:"POST",path:"/balance",body:e.object({accountNo:e.string().optional()}),responses:{201:e.object({availableBalance:e.number()})}},getStatement:{method:"POST",path:"/statement",summary:"Get Wallet Statement",body:e.object({endDate:e.date(),startDate:e.date(),accountNo:e.string().optional()}),responses:{201:e.array(ne.schema)}}}),_e=g(de((e,t)=>({user:void 0,token:void 0,getUser:()=>{try{const e=t().user;if(e)return L.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:ie(()=>"undefined"==typeof window?{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}:sessionStorage)})),De=()=>{if("undefined"!=typeof window)return _e.getState().getToken()};class Pe{contract;endpoint;root;token;constructor(e,t,r){this.contract=t,this.endpoint=e,this.root=r?.root,this.token=r?.token}getToken(){if(this.token&&this.token.trim().length>0)return this.token;try{const e=De();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":b()}};return Ae(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 v(e.body);if(401===e.status)throw new v({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new v({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new v({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});throw new v({message:"We encountered an error trying to process your request. Please try again later",statusCode:520,error:"UNKNOWN_ERROR"})}}class je extends Pe{constructor(e){super("wallet",Ee,e)}async getBalance(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");if(e.wallet){const t=await this.client.getBalance({body:{accountNo:e.wallet.accountNo}});if(201===t.status){const r=t.body.availableBalance,n=c.from(r,e.wallet.currencyCode);if(n)return n}}if(e.accountNo){const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);const r=t[0],n=await this.client.getBalance({body:{accountNo:e.accountNo}});if(201===n.status){const e=n.body.availableBalance,t=c.from(e,r.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}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=H.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){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");const t=new Date,r=new Date(t.getFullYear(),t.getMonth(),1),n=new Date(t.getFullYear(),t.getMonth()+1,0),o=e.range??{startDate:r,endDate:n};let a,s;if(e.wallet)a=e.wallet,s=e.wallet.accountNo;else{if(!e.accountNo)throw new Error("Either wallet or accountNo must be provided");{const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);a=t[0],s=e.accountNo}}const i={...o,accountNo:s},c=await this.client.getStatement({body:i});if(201===c.status){return c.body.map(e=>({...e,currencyCode:a.currencyCode})).reduce((e,t)=>{const r=ne.create(t);return r?e.push(r):console.warn("[WalletRepository] Skipping invalid statement entry:",t),e},[])}throw new Error(`Failed to fetch statement. Status: ${c.status}`)}}const Te=g()(de((e,t)=>({userId:"",wallets:[],selectedWalletId:"",selectedCountryCode:"TZ",lastSynced:new Date,isInitialized:!1,setWallets:r=>{const n=r.filter(e=>H.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(!H.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:ie(()=>sessionStorage,{reviver:(e,t)=>{if("wallets"===e&&Array.isArray(t))return t.map(e=>{try{const t=H.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{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 H&&"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 Re{repo;static _instance;constructor(){this.repo=new je}static get instance(){return this._instance||(this._instance=new Re),this._instance}isInitialized(){return Te.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.");Te.getState().setWallets(e)}catch(e){throw console.error("Failed to refresh wallets:",e),e}}getWallets(){const e=Te.getState();if(!e.isInitialized)throw new Error("Cannot get wallets: Wallet session not initialized.");return e.wallets}getCountries(){const e=this.getWallets();return ue.getUniqueCountries(e)}getWalletsByCountry(e){if(!this.isInitialized())throw new Error("Cannot get wallets by country: Wallet session not initialized.");return Te.getState()._getWalletsByCountry(e)}getSelectedWallet(){return Te.getState()._getSelectedWallet()}getSelectedCountryCode(){const e=Te.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 t=p.fromCode(e);if(!t)throw new Error(`Country.fromCode returned invalid result for code: ${e}`);return t}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=Te.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.");Te.getState().setSelectedCountry(e)}reset(){Te.getState().reset()}}const Ue=fe().router({logIn:{method:"POST",path:"/login",body:e.object({type:e.string().default("password"),identity:e.string().email(),password:e.string()}),responses:{201:e.object({profile:q.profileDTOSchema,token:e.string(),access:e.array(e.string()),resetPassword:e.boolean()}),400:e.object({})}},access:{method:"GET",path:"/access",headers:e.object({token:e.string()}),responses:{200:e.string().array()}},resetPassword:{method:"PUT",path:"/password",body:e.object({currentPassword:e.string(),newPassword:e.string()}),responses:{}}}),ke=fe().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:e.object({name:e.string(),identity:e.string()})}}});class Me extends Pe{constructor(e){super("login",ke,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 xe extends Pe{constructor(e){super("auth",Ue,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 v({message:"Invalid email or password",statusCode:400});if(201===n.status){const e=new Me({token:n.body.token}),t=await e.getIdentity(),r=L.from({...n.body,...t});if(r)return r}throw new v({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 v({message:"Invalid current password",statusCode:400});throw new v({message:"An error occurred while trying to update password",statusCode:502})}}class Be{static _instance=null;constructor(){}static get instance(){return Be._instance||(Be._instance=new Be),Be._instance}get repo(){return new xe({token:this.getUserToken()})}getUserToken(){return De()}get currentUser(){return(()=>{if("undefined"!=typeof window)return _e.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=w(_e,e=>e.user);try{return e?L.fromJSON(e):void 0}catch(e){return void console.warn("Failed to deserialize user from hook:",e)}})()}checkPermission(e){return this.currentUser?.can(e)??!1}async logIn(e,t){if(!e||!t)throw new Error("Email and password are required");const r=new xe,n=await r.logIn(e,t);this.clearSavedData(),_e.getState().setUserAndToken(n,n.token);try{await Re.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(){return{hasUser:!!this.currentUser,hasToken:!!this.getUserToken(),isAuthenticated:this.isAuthenticated,userName:this.currentUser?.name||"Not logged in",tokenLength:this.getUserToken()?.length||0,managerInstance:"AfloatAuth singleton"}}clearSavedData(){_e.getState().clearAuth();try{Re.instance.reset()}catch(e){console.warn("Failed to reset wallet session manager:",e)}}}const $e=fe().router({getAccessList:{method:"GET",path:"/access",responses:{200:e.string().array()}}});class Je extends Pe{constructor(e){super("auth",$e,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}`)}}const We=fe().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:z.schema}}});class Fe extends Pe{constructor(e){super("profile",We,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=z.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}`)}}class qe{canHandle(e){return"Mobile"===e.type&&P.is(e)}createInput(e){if(P.is(e))return{type:I.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Contact Info")}}class ze{canHandle(e){return"Bank"===e.type&&j.is(e)}createInput(e){if(j.is(e))return{type:I.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile Contact Info")}}class Le{handlers=[new qe,new ze];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 Ve={400:e.object({statusCode:e.number(),message:e.string(),error:e.string(),details:e.record(e.string()).optional()})},Ge=fe().router({createContact:{method:"POST",path:"/",body:E.contactInputDTO,responses:{201:E.contactDTO}},editContact:{method:"PATCH",path:"/:id",body:E.contactInputDTO,responses:{200:E.contactDTO}},getContacts:{method:"GET",path:"/",query:e.object({orderByDesc:e.string()}),responses:{200:e.array(E.contactDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:E.contactDTO}},deleteContact:{method:"DELETE",path:"/:id",body:e.object({}),responses:{200:e.object({})}}},{commonResponses:Ve});class He extends Pe{constructor(e){super("contact",Ge,e)}async create(e){const t=(new Le).resolve(e),r=await this.client.createContact({body:t}),n=this.handleResponse(r,201);return T.create(n)}async edit(e,t){const r=(new Le).resolve(t),n=await this.client.editContact({params:{id:e},body:r}),o=this.handleResponse(n,200);return T.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 T.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return T.create(r)}}const Ze={SUPPORTED_COUNTRY_CODES:["TZ","KE"],ERROR_MESSAGES:{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 Ye{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}}class Ke{static forBank(e,t){if(!Ze.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ze.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,n,o){if(!r.is(e))throw new Error(Ze.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!Ze.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ze.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!y.checkPayoutEligibility(e))throw new Error(Ze.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const a=t.getMNOById(n,e.countryCode);if(!a)throw new Error(Ze.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return a.id===f.VODACOM?`${o.countryCode}-${f.TIGO.toString().toUpperCase()}-B2C`:`${o.countryCode}-${a.id.toString().toUpperCase()}-B2C`}}class Qe{canHandle(e,t,r){return e===R.MOBILE&&P.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===p.from(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=Ye.processNotes(e.notes),a=r.phoneNumber;return{channel:Ke.forMobile(a,r.mnoId,t),msisdn:a.getWithFormat(o.INTERNATIONAL_NUMERIC),description:n??te.generateDefaultPayoutNarration(r),payeeName:r.name,notes:n,amount:e.amount.numericValue}}}class Xe{canHandle(e,t,r){return e===R.BANK&&j.is(t)&&r.countryCode===t.countryCode&&r.currencyCode===p.from(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,n=Ye.processNotes(e.notes);return{channel:Ke.forBank(r,t),msisdn:`${r.bank.swiftCode}:${r.accNo}`,description:n??te.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:n,amount:e.amount.numericValue}}}class et{handlers=[new Qe,new Xe];getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(Ze.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const tt={bank:Ke.forBank,mobile:Ke.forMobile},rt=fe().router({getPayouts:{method:"GET",path:"",query:e.object({rangeStart:e.number(),rangeEnd:e.number(),eager:e.string(),approvalStatus:W.PayoutApprovalStatus.nullable().optional(),orderByDesc:e.string(),msisdn:e.string().optional()}),responses:{200:e.object({results:e.array(W.PayoutDTO),total:e.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:e.object({rangeStart:e.number(),rangeEnd:e.number(),eager:e.string(),approvalStatus:W.PayoutApprovalStatus,orderByDesc:e.string()}),responses:{200:e.object({results:e.array(W.PayoutDTO),total:e.number()})}},postPayout:{method:"POST",path:"",body:W.PayoutInputDTO,responses:{201:W.PayoutDTO,400:v.schema}},approve:{method:"POST",path:"/:id/approve",body:e.object({action:e.enum(["Approve","Reject"]),notes:e.string().optional()}),responses:{201:W.PayoutDTO,404:e.object({}),409:e.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:W.PayoutDTO,404:e.object({})}}});class nt extends Pe{constructor(e){super("payout",rt,e)}async getAll(e){const t=e?.rangeStart??0,r=e?.rangeEnd??10,n=k.PENDING,o={rangeStart:t,rangeEnd:r,eager:"[createdBy,actionedBy]",orderByDesc:"createdAt"};if(e?.pending&&Object.assign(o,{approvalStatus:n}),e?.msisdn&&Object.assign(o,{msisdn:e.msisdn}),r<=t)throw new v({message:"Invalid range: end-date must be greater than start-date",statusCode:400});const a=await this.client.getPayouts({query:o});if(200===a.status)return{results:F.createMany(a.body.results),total:a.body.total};throw v.unknown("An error occurred while fetching payouts")}async pay(e){const{min:t,max:r}=c.getTransactionLimits(e.amount.currencyCode);if(e.amount.lessThan(t)||e.amount.greaterThan(r))throw new v({statusCode:400,message:`Please make sure the amount is between ${t.label} - ${r.label}`});const n=Re.instance.getSelectedWallet();if(!n)throw new Error("You have not selected a wallet to process this payout");const o=(new et).getPayoutInput(e,n),a=await this.client.postPayout({body:o});if(201===a.status)return F.create(a.body);if(400===a.status)throw new v(a.body);throw v.unknown()}async approve(e,t){const r=await this.client.approve({params:{id:e},body:{action:"Approve",notes:t?.notes}});if(201===r.status)return F.create(r.body);if(404===r.status)throw new v({message:"Payout not found",statusCode:404});if(409===r.status)throw new v({message:"Payout already approved",statusCode:409});throw v.unknown()}async reject(e,t){const r=await this.client.approve({params:{id:e},body:{action:"Reject",notes:t?.notes}});if(201===r.status)return F.create(r.body);if(404===r.status)throw new v({message:"Payout not found",statusCode:404});if(409===r.status)throw new v({message:"Payout already rejected",statusCode:409});throw v.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return F.create(t.body);if(404===t.status)throw new v({message:"Payout not found",statusCode:404});throw v.unknown()}}const ot=e.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"),at=e.object({id:e.string().min(1),name:e.string().min(1,"Role name is required"),description:e.string().optional(),access:e.array(e.string()),createdAt:e.string().datetime("Invalid creation timestamp"),updatedAt:e.string().datetime("Invalid update timestamp")}),st=e.object({id:e.string().min(1),name:e.string().min(1,"User name is required"),identity:e.string().email("Invalid email address"),type:e.string().min(1,"User type is required"),profileId:e.string().min(1,"Profile ID is required"),roleId:e.string().min(1,"Role ID is required"),resetPassword:e.boolean(),isActive:e.boolean(),isArchived:e.boolean(),role:at.optional(),createdAt:e.string().datetime("Invalid creation timestamp"),updatedAt:e.string().datetime("Invalid update timestamp")}),it={role:at,managedUser:st,managedUserQueryParams:e.object({id:e.string().min(1).optional(),name:e.string().min(1).optional(),identity:e.string().email("Invalid email address").optional(),type:e.string().min(1).optional(),profileId:e.string().min(1).optional(),roleId:e.string().min(1).optional(),resetPassword:e.number().optional(),isActive:e.number().optional(),isArchived:e.number().optional(),createdAt:e.string().datetime("Invalid creation timestamp").optional(),updatedAt:e.string().datetime("Invalid update timestamp").optional(),eager:e.string().optional()}),createUserRequest:e.object({name:e.string().min(1,"User name is required"),identity:e.string().email("Valid email address is required"),password:ot.optional(),roleId:e.string().optional(),resetPassword:e.boolean().optional()}),updateUserRequest:e.object({name:e.string().min(1,"User name cannot be empty").optional(),roleId:e.string().min(1,"Role ID cannot be empty").optional(),password:ot.optional(),resetPassword:e.boolean().optional(),isActive:e.boolean().optional()}),resetPasswordRequest:e.object({newPassword:ot.optional(),sendNotification:e.boolean().optional()}),createUserResponse:e.object({id:e.string(),name:e.string(),identity:e.string(),type:e.string(),profileId:e.string(),roleId:e.string(),isActive:e.boolean(),isArchived:e.boolean(),createdAt:e.string().datetime()}),password:ot},ct=fe().router({getUsers:{method:"GET",path:"/login",query:it.managedUserQueryParams,responses:{200:e.array(it.managedUser),401:e.object({message:e.string().optional()}),403:e.object({message:e.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.object({id:e.string()}),query:it.managedUserQueryParams,responses:{200:it.managedUser,401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),404:e.object({message:e.string().optional()})},summary:"Get user account details",description:"Retrieve detailed information about a specific user account"},createUser:{method:"POST",path:"/login",body:it.createUserRequest,responses:{201:it.createUserResponse,400:e.object({message:e.string().optional(),errors:e.array(e.string()).optional()}),401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),409:e.object({message:e.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.object({id:e.string()}),body:it.updateUserRequest,responses:{200:it.managedUser,400:e.object({message:e.string().optional(),errors:e.array(e.string()).optional()}),401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),404:e.object({message:e.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.object({id:e.string()}),body:e.object({}),responses:{200:it.managedUser,401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),404:e.object({message:e.string().optional()})},summary:"Archive user account",description:"Archive (soft delete) a user account"},unArchiveUser:{method:"POST",path:"/login/:id/unarchive",pathParams:e.object({id:e.string()}),body:e.object({}),responses:{200:it.managedUser,401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),404:e.object({message:e.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.object({id:e.string()}),body:it.resetPasswordRequest,responses:{200:e.object({success:e.boolean()}),400:e.object({message:e.string().optional()}),401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),404:e.object({message:e.string().optional()})},summary:"Reset user password",description:"Reset a user's password and optionally send notification"},getRoles:{method:"GET",path:"/role",responses:{200:e.array(it.role),401:e.object({message:e.string().optional()}),403:e.object({message:e.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.object({id:e.string()}),responses:{200:it.role,401:e.object({message:e.string().optional()}),403:e.object({message:e.string().optional()}),404:e.object({message:e.string().optional()})},summary:"Get role details",description:"Retrieve detailed information about a specific role"}});class dt extends Pe{constructor(e){super("admin",ct,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=se.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=se.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=se.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 se.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=se.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=oe.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=oe.from(r);if(!n)throw new Error("Invalid role data received from server");return n}}export{v as APIError,Je as AccessRepository,Be as AfloatAuth,xe as AuthRepository,K as BANK_NARR_PREFIX,j as BankContactInfo,T as Contact,E as ContactDTOSchemas,He as ContactRepository,I as ContactType,Z as ECOBANK_PREFIX,Me as IdentityRepository,Q as LEGACY_BANK_NARR_PREFIX,ee as LEGACY_MOBILE_NARR_PREFIX,X as MOBILE_NARR_PREFIX,se as ManagedUser,P as MobileContactInfo,Y as NARR_V2_PREFIX,te as Narration,F as Payout,k as PayoutApprovalStatus,R as PayoutChannel,W as PayoutDTOSchemas,et as PayoutInputFactory,nt as PayoutRepository,U as PayoutStatus,C as PermissionError,N as Permissions,z as Profile,Fe as ProfileRepository,oe as Role,L as User,ae as UserEntity,it as UserManagementDTOSchemas,dt as UserManagementRepository,H as Wallet,G as WalletDTOSchemas,je as WalletRepository,Re as WalletSessionManager,ne as WalletStatementEntry,ue as WalletUtils,tt as createPayoutChannelCode,O as isError,Te as walletsStore};
2
2
  //# sourceMappingURL=index.esm.js.map