@temboplus/afloat 0.1.81 → 0.2.0-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +206 -90
- package/dist/index.cjs.js +2 -0
- package/dist/index.cjs.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.esm.js +2 -0
- package/dist/index.esm.js.map +1 -0
- package/dist/lib/api/base-repository.d.ts +177 -0
- package/dist/lib/api/index.d.ts +1 -0
- package/{esm/src/errors/api_error.d.ts → dist/lib/error/error.api.d.ts} +0 -1
- package/{script/npm/src/src/errors/permission_error.d.ts → dist/lib/error/error.permission.d.ts} +1 -2
- package/dist/lib/error/error.utils.d.ts +22 -0
- package/dist/lib/error/index.d.ts +3 -0
- package/dist/lib/query/index.d.ts +4 -0
- package/dist/lib/query/pagination/pagination.d.ts +73 -0
- package/dist/lib/query/pagination/pagination.schemas.d.ts +83 -0
- package/dist/lib/query/query.builder.d.ts +80 -0
- package/dist/lib/query/query.types.d.ts +36 -0
- package/{esm/src/features/auth/contract.d.ts → dist/modules/auth/auth.contract.d.ts} +16 -19
- package/dist/modules/auth/auth.repository.d.ts +83 -0
- package/dist/modules/auth/company-membership.model.d.ts +171 -0
- package/dist/modules/auth/index.d.ts +3 -0
- package/dist/modules/auth/user.model.d.ts +363 -0
- package/dist/modules/beneficiary/beneficiary-info.model.d.ts +218 -0
- package/dist/modules/beneficiary/beneficiary-input-handler.d.ts +16 -0
- package/dist/modules/beneficiary/beneficiary.api-contract.d.ts +203 -0
- package/dist/modules/beneficiary/beneficiary.dtos.d.ts +84 -0
- package/dist/modules/beneficiary/beneficiary.model.d.ts +450 -0
- package/dist/modules/beneficiary/beneficiary.repository.d.ts +116 -0
- package/dist/modules/beneficiary/index.d.ts +6 -0
- package/dist/modules/login/index.d.ts +4 -0
- package/dist/modules/login/login.api-contract.d.ts +51 -0
- package/dist/modules/login/login.dtos.d.ts +85 -0
- package/dist/modules/login/login.model.d.ts +168 -0
- package/dist/modules/login/login.repository.d.ts +58 -0
- package/{esm/src/models/permission.d.ts → dist/modules/login/permission.type.d.ts} +9 -10
- package/dist/modules/payout/index.d.ts +5 -0
- package/dist/modules/payout/payout-channel-handler.d.ts +83 -0
- package/{esm/src/features/payout/contract.d.ts → dist/modules/payout/payout.api-contract.d.ts} +350 -207
- package/dist/modules/payout/payout.dtos.d.ts +607 -0
- package/dist/modules/payout/payout.model.d.ts +383 -0
- package/dist/modules/payout/payout.query.d.ts +185 -0
- package/dist/modules/payout/payout.repository.d.ts +204 -0
- package/dist/modules/profile/index.d.ts +3 -0
- package/{script/npm/src/src/features/auth/profile/contract.d.ts → dist/modules/profile/profile.api-contract.d.ts} +8 -6
- package/dist/modules/profile/profile.dtos.d.ts +80 -0
- package/{script/npm/src/src/models/user/profile.d.ts → dist/modules/profile/profile.model.d.ts} +81 -52
- package/dist/modules/profile/profile.repository.d.ts +56 -0
- package/dist/modules/team-member/index.d.ts +4 -0
- package/dist/modules/team-member/role.model.d.ts +61 -0
- package/{esm/src/features/admin/contract.d.ts → dist/modules/team-member/team-member.contract.d.ts} +229 -154
- package/dist/modules/team-member/team-member.dtos.d.ts +261 -0
- package/dist/modules/team-member/team-member.model.d.ts +237 -0
- package/dist/modules/team-member/team-member.repository.d.ts +179 -0
- package/dist/modules/wallet/index.d.ts +6 -0
- package/dist/modules/wallet/narration.model.d.ts +225 -0
- package/dist/modules/wallet/statement-entry.model.d.ts +299 -0
- package/{script/npm/src/src/features/wallet/contract.d.ts → dist/modules/wallet/wallet.contract.d.ts} +17 -15
- package/dist/modules/wallet/wallet.dtos.d.ts +204 -0
- package/{esm/src/models/wallet/wallet.d.ts → dist/modules/wallet/wallet.model.d.ts} +34 -40
- package/dist/modules/wallet/wallet.query.d.ts +126 -0
- package/dist/modules/wallet/wallet.repository.d.ts +205 -0
- package/dist/modules/wallet/wallet.utils.d.ts +17 -0
- package/package.json +47 -22
- package/LICENSE +0 -7
- package/esm/mod.d.ts +0 -8
- package/esm/mod.d.ts.map +0 -1
- package/esm/mod.js +0 -7
- package/esm/package.json +0 -3
- package/esm/src/errors/api_error.d.ts.map +0 -1
- package/esm/src/errors/api_error.js +0 -90
- package/esm/src/errors/index.d.ts +0 -3
- package/esm/src/errors/index.d.ts.map +0 -1
- package/esm/src/errors/index.js +0 -2
- package/esm/src/errors/permission_error.d.ts +0 -48
- package/esm/src/errors/permission_error.d.ts.map +0 -1
- package/esm/src/errors/permission_error.js +0 -70
- package/esm/src/features/admin/contract.d.ts.map +0 -1
- package/esm/src/features/admin/contract.js +0 -210
- package/esm/src/features/admin/index.d.ts +0 -4
- package/esm/src/features/admin/index.d.ts.map +0 -1
- package/esm/src/features/admin/index.js +0 -3
- package/esm/src/features/admin/repository.d.ts +0 -114
- package/esm/src/features/admin/repository.d.ts.map +0 -1
- package/esm/src/features/admin/repository.js +0 -248
- package/esm/src/features/admin/schemas.d.ts +0 -146
- package/esm/src/features/admin/schemas.d.ts.map +0 -1
- package/esm/src/features/admin/schemas.js +0 -206
- package/esm/src/features/auth/access/contract.d.ts +0 -14
- package/esm/src/features/auth/access/contract.d.ts.map +0 -1
- package/esm/src/features/auth/access/contract.js +0 -14
- package/esm/src/features/auth/access/repository.d.ts +0 -11
- package/esm/src/features/auth/access/repository.d.ts.map +0 -1
- package/esm/src/features/auth/access/repository.js +0 -25
- package/esm/src/features/auth/contract.d.ts.map +0 -1
- package/esm/src/features/auth/contract.js +0 -43
- package/esm/src/features/auth/identity/contract.d.ts +0 -23
- package/esm/src/features/auth/identity/contract.d.ts.map +0 -1
- package/esm/src/features/auth/identity/contract.js +0 -17
- package/esm/src/features/auth/identity/repository.d.ts +0 -22
- package/esm/src/features/auth/identity/repository.d.ts.map +0 -1
- package/esm/src/features/auth/identity/repository.js +0 -30
- package/esm/src/features/auth/index.d.ts +0 -6
- package/esm/src/features/auth/index.d.ts.map +0 -1
- package/esm/src/features/auth/index.js +0 -5
- package/esm/src/features/auth/manager.d.ts +0 -105
- package/esm/src/features/auth/manager.d.ts.map +0 -1
- package/esm/src/features/auth/manager.js +0 -181
- package/esm/src/features/auth/profile/contract.d.ts +0 -37
- package/esm/src/features/auth/profile/contract.d.ts.map +0 -1
- package/esm/src/features/auth/profile/contract.js +0 -14
- package/esm/src/features/auth/profile/repository.d.ts +0 -11
- package/esm/src/features/auth/profile/repository.d.ts.map +0 -1
- package/esm/src/features/auth/profile/repository.js +0 -25
- package/esm/src/features/auth/repository.d.ts +0 -30
- package/esm/src/features/auth/repository.d.ts.map +0 -1
- package/esm/src/features/auth/repository.js +0 -69
- package/esm/src/features/auth/storage/client_store.d.ts +0 -30
- package/esm/src/features/auth/storage/client_store.d.ts.map +0 -1
- package/esm/src/features/auth/storage/client_store.js +0 -46
- package/esm/src/features/auth/storage/client_token_handler.d.ts +0 -32
- package/esm/src/features/auth/storage/client_token_handler.d.ts.map +0 -1
- package/esm/src/features/auth/storage/client_token_handler.js +0 -36
- package/esm/src/features/auth/storage/server_store.d.ts +0 -24
- package/esm/src/features/auth/storage/server_store.d.ts.map +0 -1
- package/esm/src/features/auth/storage/server_store.js +0 -34
- package/esm/src/features/auth/storage/server_token_handler.d.ts +0 -36
- package/esm/src/features/auth/storage/server_token_handler.d.ts.map +0 -1
- package/esm/src/features/auth/storage/server_token_handler.js +0 -115
- package/esm/src/features/auth/storage/types.d.ts +0 -42
- package/esm/src/features/auth/storage/types.d.ts.map +0 -1
- package/esm/src/features/auth/storage/types.js +0 -1
- package/esm/src/features/contact/contract.d.ts +0 -170
- package/esm/src/features/contact/contract.d.ts.map +0 -1
- package/esm/src/features/contact/contract.js +0 -49
- package/esm/src/features/contact/index.d.ts +0 -2
- package/esm/src/features/contact/index.d.ts.map +0 -1
- package/esm/src/features/contact/index.js +0 -1
- package/esm/src/features/contact/repository.d.ts +0 -58
- package/esm/src/features/contact/repository.d.ts.map +0 -1
- package/esm/src/features/contact/repository.js +0 -108
- package/esm/src/features/payout/contract.d.ts.map +0 -1
- package/esm/src/features/payout/contract.js +0 -75
- package/esm/src/features/payout/index.d.ts +0 -2
- package/esm/src/features/payout/index.d.ts.map +0 -1
- package/esm/src/features/payout/index.js +0 -1
- package/esm/src/features/payout/repository.d.ts +0 -67
- package/esm/src/features/payout/repository.d.ts.map +0 -1
- package/esm/src/features/payout/repository.js +0 -179
- package/esm/src/features/wallet/contract.d.ts +0 -137
- package/esm/src/features/wallet/contract.d.ts.map +0 -1
- package/esm/src/features/wallet/contract.js +0 -38
- package/esm/src/features/wallet/index.d.ts +0 -2
- package/esm/src/features/wallet/index.d.ts.map +0 -1
- package/esm/src/features/wallet/index.js +0 -1
- package/esm/src/features/wallet/repository.d.ts +0 -57
- package/esm/src/features/wallet/repository.d.ts.map +0 -1
- package/esm/src/features/wallet/repository.js +0 -93
- package/esm/src/models/contact/derivatives/contact.d.ts +0 -172
- package/esm/src/models/contact/derivatives/contact.d.ts.map +0 -1
- package/esm/src/models/contact/derivatives/contact.js +0 -266
- package/esm/src/models/contact/derivatives/contact_info.d.ts +0 -188
- package/esm/src/models/contact/derivatives/contact_info.d.ts.map +0 -1
- package/esm/src/models/contact/derivatives/contact_info.js +0 -255
- package/esm/src/models/contact/index.d.ts +0 -5
- package/esm/src/models/contact/index.d.ts.map +0 -1
- package/esm/src/models/contact/index.js +0 -4
- package/esm/src/models/contact/schemas.d.ts +0 -66
- package/esm/src/models/contact/schemas.d.ts.map +0 -1
- package/esm/src/models/contact/schemas.js +0 -64
- package/esm/src/models/contact/validation.d.ts +0 -37
- package/esm/src/models/contact/validation.d.ts.map +0 -1
- package/esm/src/models/contact/validation.js +0 -146
- package/esm/src/models/index.d.ts +0 -7
- package/esm/src/models/index.d.ts.map +0 -1
- package/esm/src/models/index.js +0 -6
- package/esm/src/models/payout/api.d.ts +0 -29
- package/esm/src/models/payout/api.d.ts.map +0 -1
- package/esm/src/models/payout/api.js +0 -1
- package/esm/src/models/payout/channel.d.ts +0 -58
- package/esm/src/models/payout/channel.d.ts.map +0 -1
- package/esm/src/models/payout/channel.js +0 -53
- package/esm/src/models/payout/derivatives/payout.d.ts +0 -158
- package/esm/src/models/payout/derivatives/payout.d.ts.map +0 -1
- package/esm/src/models/payout/derivatives/payout.js +0 -271
- package/esm/src/models/payout/index.d.ts +0 -7
- package/esm/src/models/payout/index.d.ts.map +0 -1
- package/esm/src/models/payout/index.js +0 -6
- package/esm/src/models/payout/narration.d.ts +0 -164
- package/esm/src/models/payout/narration.d.ts.map +0 -1
- package/esm/src/models/payout/narration.js +0 -308
- package/esm/src/models/payout/schemas.d.ts +0 -156
- package/esm/src/models/payout/schemas.d.ts.map +0 -1
- package/esm/src/models/payout/schemas.js +0 -105
- package/esm/src/models/payout/status.d.ts +0 -33
- package/esm/src/models/payout/status.d.ts.map +0 -1
- package/esm/src/models/payout/status.js +0 -34
- package/esm/src/models/permission.d.ts.map +0 -1
- package/esm/src/models/permission.js +0 -50
- package/esm/src/models/role.d.ts +0 -21
- package/esm/src/models/role.d.ts.map +0 -1
- package/esm/src/models/role.js +0 -73
- package/esm/src/models/user/authenticated-user.d.ts +0 -77
- package/esm/src/models/user/authenticated-user.d.ts.map +0 -1
- package/esm/src/models/user/authenticated-user.js +0 -226
- package/esm/src/models/user/index.d.ts +0 -4
- package/esm/src/models/user/index.d.ts.map +0 -1
- package/esm/src/models/user/index.js +0 -3
- package/esm/src/models/user/managed-user.d.ts +0 -108
- package/esm/src/models/user/managed-user.d.ts.map +0 -1
- package/esm/src/models/user/managed-user.js +0 -255
- package/esm/src/models/user/profile.d.ts +0 -161
- package/esm/src/models/user/profile.d.ts.map +0 -1
- package/esm/src/models/user/profile.js +0 -334
- package/esm/src/models/wallet/index.d.ts +0 -4
- package/esm/src/models/wallet/index.d.ts.map +0 -1
- package/esm/src/models/wallet/index.js +0 -3
- package/esm/src/models/wallet/schemas.d.ts +0 -95
- package/esm/src/models/wallet/schemas.d.ts.map +0 -1
- package/esm/src/models/wallet/schemas.js +0 -35
- package/esm/src/models/wallet/statement_entry.d.ts +0 -160
- package/esm/src/models/wallet/statement_entry.d.ts.map +0 -1
- package/esm/src/models/wallet/statement_entry.js +0 -255
- package/esm/src/models/wallet/wallet.d.ts.map +0 -1
- package/esm/src/models/wallet/wallet.js +0 -279
- package/esm/src/shared/base_repository.d.ts +0 -80
- package/esm/src/shared/base_repository.d.ts.map +0 -1
- package/esm/src/shared/base_repository.js +0 -153
- package/esm/src/shared/common_responses.d.ts +0 -13
- package/esm/src/shared/common_responses.d.ts.map +0 -1
- package/esm/src/shared/common_responses.js +0 -10
- package/esm/src/shared/index.d.ts +0 -3
- package/esm/src/shared/index.d.ts.map +0 -1
- package/esm/src/shared/index.js +0 -2
- package/esm/src/shared/token_required_repository.d.ts +0 -78
- package/esm/src/shared/token_required_repository.d.ts.map +0 -1
- package/esm/src/shared/token_required_repository.js +0 -128
- package/script/mod.d.ts +0 -8
- package/script/mod.d.ts.map +0 -1
- package/script/mod.js +0 -23
- package/script/npm/src/mod.d.ts +0 -8
- package/script/npm/src/mod.d.ts.map +0 -1
- package/script/npm/src/mod.js +0 -23
- package/script/npm/src/src/errors/api_error.d.ts +0 -63
- package/script/npm/src/src/errors/api_error.d.ts.map +0 -1
- package/script/npm/src/src/errors/api_error.js +0 -94
- package/script/npm/src/src/errors/index.d.ts +0 -3
- package/script/npm/src/src/errors/index.d.ts.map +0 -1
- package/script/npm/src/src/errors/index.js +0 -18
- package/script/npm/src/src/errors/permission_error.d.ts.map +0 -1
- package/script/npm/src/src/errors/permission_error.js +0 -74
- package/script/npm/src/src/features/admin/contract.d.ts +0 -842
- package/script/npm/src/src/features/admin/contract.d.ts.map +0 -1
- package/script/npm/src/src/features/admin/contract.js +0 -213
- package/script/npm/src/src/features/admin/index.d.ts +0 -4
- package/script/npm/src/src/features/admin/index.d.ts.map +0 -1
- package/script/npm/src/src/features/admin/index.js +0 -19
- package/script/npm/src/src/features/admin/repository.d.ts +0 -114
- package/script/npm/src/src/features/admin/repository.d.ts.map +0 -1
- package/script/npm/src/src/features/admin/repository.js +0 -252
- package/script/npm/src/src/features/admin/schemas.d.ts +0 -146
- package/script/npm/src/src/features/admin/schemas.d.ts.map +0 -1
- package/script/npm/src/src/features/admin/schemas.js +0 -209
- package/script/npm/src/src/features/auth/access/contract.d.ts +0 -14
- package/script/npm/src/src/features/auth/access/contract.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/access/contract.js +0 -17
- package/script/npm/src/src/features/auth/access/repository.d.ts +0 -11
- package/script/npm/src/src/features/auth/access/repository.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/access/repository.js +0 -29
- package/script/npm/src/src/features/auth/contract.d.ts +0 -112
- package/script/npm/src/src/features/auth/contract.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/contract.js +0 -46
- package/script/npm/src/src/features/auth/identity/contract.d.ts +0 -23
- package/script/npm/src/src/features/auth/identity/contract.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/identity/contract.js +0 -20
- package/script/npm/src/src/features/auth/identity/repository.d.ts +0 -22
- package/script/npm/src/src/features/auth/identity/repository.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/identity/repository.js +0 -34
- package/script/npm/src/src/features/auth/index.d.ts +0 -6
- package/script/npm/src/src/features/auth/index.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/index.js +0 -21
- package/script/npm/src/src/features/auth/manager.d.ts +0 -105
- package/script/npm/src/src/features/auth/manager.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/manager.js +0 -185
- package/script/npm/src/src/features/auth/profile/contract.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/profile/contract.js +0 -17
- package/script/npm/src/src/features/auth/profile/repository.d.ts +0 -11
- package/script/npm/src/src/features/auth/profile/repository.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/profile/repository.js +0 -29
- package/script/npm/src/src/features/auth/repository.d.ts +0 -30
- package/script/npm/src/src/features/auth/repository.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/repository.js +0 -73
- package/script/npm/src/src/features/auth/storage/client_store.d.ts +0 -30
- package/script/npm/src/src/features/auth/storage/client_store.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/storage/client_store.js +0 -51
- package/script/npm/src/src/features/auth/storage/client_token_handler.d.ts +0 -32
- package/script/npm/src/src/features/auth/storage/client_token_handler.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/storage/client_token_handler.js +0 -40
- package/script/npm/src/src/features/auth/storage/server_store.d.ts +0 -24
- package/script/npm/src/src/features/auth/storage/server_store.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/storage/server_store.js +0 -38
- package/script/npm/src/src/features/auth/storage/server_token_handler.d.ts +0 -36
- package/script/npm/src/src/features/auth/storage/server_token_handler.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/storage/server_token_handler.js +0 -119
- package/script/npm/src/src/features/auth/storage/types.d.ts +0 -42
- package/script/npm/src/src/features/auth/storage/types.d.ts.map +0 -1
- package/script/npm/src/src/features/auth/storage/types.js +0 -2
- package/script/npm/src/src/features/contact/contract.d.ts +0 -170
- package/script/npm/src/src/features/contact/contract.d.ts.map +0 -1
- package/script/npm/src/src/features/contact/contract.js +0 -52
- package/script/npm/src/src/features/contact/index.d.ts +0 -2
- package/script/npm/src/src/features/contact/index.d.ts.map +0 -1
- package/script/npm/src/src/features/contact/index.js +0 -17
- package/script/npm/src/src/features/contact/repository.d.ts +0 -58
- package/script/npm/src/src/features/contact/repository.d.ts.map +0 -1
- package/script/npm/src/src/features/contact/repository.js +0 -112
- package/script/npm/src/src/features/payout/contract.d.ts +0 -623
- package/script/npm/src/src/features/payout/contract.d.ts.map +0 -1
- package/script/npm/src/src/features/payout/contract.js +0 -78
- package/script/npm/src/src/features/payout/index.d.ts +0 -2
- package/script/npm/src/src/features/payout/index.d.ts.map +0 -1
- package/script/npm/src/src/features/payout/index.js +0 -17
- package/script/npm/src/src/features/payout/repository.d.ts +0 -67
- package/script/npm/src/src/features/payout/repository.d.ts.map +0 -1
- package/script/npm/src/src/features/payout/repository.js +0 -183
- package/script/npm/src/src/features/wallet/contract.d.ts.map +0 -1
- package/script/npm/src/src/features/wallet/contract.js +0 -41
- package/script/npm/src/src/features/wallet/index.d.ts +0 -2
- package/script/npm/src/src/features/wallet/index.d.ts.map +0 -1
- package/script/npm/src/src/features/wallet/index.js +0 -17
- package/script/npm/src/src/features/wallet/repository.d.ts +0 -57
- package/script/npm/src/src/features/wallet/repository.d.ts.map +0 -1
- package/script/npm/src/src/features/wallet/repository.js +0 -97
- package/script/npm/src/src/models/contact/derivatives/contact.d.ts +0 -172
- package/script/npm/src/src/models/contact/derivatives/contact.d.ts.map +0 -1
- package/script/npm/src/src/models/contact/derivatives/contact.js +0 -270
- package/script/npm/src/src/models/contact/derivatives/contact_info.d.ts +0 -188
- package/script/npm/src/src/models/contact/derivatives/contact_info.d.ts.map +0 -1
- package/script/npm/src/src/models/contact/derivatives/contact_info.js +0 -260
- package/script/npm/src/src/models/contact/index.d.ts +0 -5
- package/script/npm/src/src/models/contact/index.d.ts.map +0 -1
- package/script/npm/src/src/models/contact/index.js +0 -20
- package/script/npm/src/src/models/contact/schemas.d.ts +0 -66
- package/script/npm/src/src/models/contact/schemas.d.ts.map +0 -1
- package/script/npm/src/src/models/contact/schemas.js +0 -67
- package/script/npm/src/src/models/contact/validation.d.ts +0 -37
- package/script/npm/src/src/models/contact/validation.d.ts.map +0 -1
- package/script/npm/src/src/models/contact/validation.js +0 -153
- package/script/npm/src/src/models/index.d.ts +0 -7
- package/script/npm/src/src/models/index.d.ts.map +0 -1
- package/script/npm/src/src/models/index.js +0 -22
- package/script/npm/src/src/models/payout/api.d.ts +0 -29
- package/script/npm/src/src/models/payout/api.d.ts.map +0 -1
- package/script/npm/src/src/models/payout/api.js +0 -2
- package/script/npm/src/src/models/payout/channel.d.ts +0 -58
- package/script/npm/src/src/models/payout/channel.d.ts.map +0 -1
- package/script/npm/src/src/models/payout/channel.js +0 -56
- package/script/npm/src/src/models/payout/derivatives/payout.d.ts +0 -158
- package/script/npm/src/src/models/payout/derivatives/payout.d.ts.map +0 -1
- package/script/npm/src/src/models/payout/derivatives/payout.js +0 -275
- package/script/npm/src/src/models/payout/index.d.ts +0 -7
- package/script/npm/src/src/models/payout/index.d.ts.map +0 -1
- package/script/npm/src/src/models/payout/index.js +0 -22
- package/script/npm/src/src/models/payout/narration.d.ts +0 -164
- package/script/npm/src/src/models/payout/narration.d.ts.map +0 -1
- package/script/npm/src/src/models/payout/narration.js +0 -312
- package/script/npm/src/src/models/payout/schemas.d.ts +0 -156
- package/script/npm/src/src/models/payout/schemas.d.ts.map +0 -1
- package/script/npm/src/src/models/payout/schemas.js +0 -108
- package/script/npm/src/src/models/payout/status.d.ts +0 -33
- package/script/npm/src/src/models/payout/status.d.ts.map +0 -1
- package/script/npm/src/src/models/payout/status.js +0 -37
- package/script/npm/src/src/models/permission.d.ts +0 -55
- package/script/npm/src/src/models/permission.d.ts.map +0 -1
- package/script/npm/src/src/models/permission.js +0 -53
- package/script/npm/src/src/models/role.d.ts +0 -21
- package/script/npm/src/src/models/role.d.ts.map +0 -1
- package/script/npm/src/src/models/role.js +0 -77
- package/script/npm/src/src/models/user/authenticated-user.d.ts +0 -77
- package/script/npm/src/src/models/user/authenticated-user.d.ts.map +0 -1
- package/script/npm/src/src/models/user/authenticated-user.js +0 -230
- package/script/npm/src/src/models/user/index.d.ts +0 -4
- package/script/npm/src/src/models/user/index.d.ts.map +0 -1
- package/script/npm/src/src/models/user/index.js +0 -19
- package/script/npm/src/src/models/user/managed-user.d.ts +0 -108
- package/script/npm/src/src/models/user/managed-user.d.ts.map +0 -1
- package/script/npm/src/src/models/user/managed-user.js +0 -260
- package/script/npm/src/src/models/user/profile.d.ts.map +0 -1
- package/script/npm/src/src/models/user/profile.js +0 -338
- package/script/npm/src/src/models/wallet/index.d.ts +0 -4
- package/script/npm/src/src/models/wallet/index.d.ts.map +0 -1
- package/script/npm/src/src/models/wallet/index.js +0 -19
- package/script/npm/src/src/models/wallet/schemas.d.ts +0 -95
- package/script/npm/src/src/models/wallet/schemas.d.ts.map +0 -1
- package/script/npm/src/src/models/wallet/schemas.js +0 -38
- package/script/npm/src/src/models/wallet/statement_entry.d.ts +0 -160
- package/script/npm/src/src/models/wallet/statement_entry.d.ts.map +0 -1
- package/script/npm/src/src/models/wallet/statement_entry.js +0 -259
- package/script/npm/src/src/models/wallet/wallet.d.ts +0 -147
- package/script/npm/src/src/models/wallet/wallet.d.ts.map +0 -1
- package/script/npm/src/src/models/wallet/wallet.js +0 -283
- package/script/npm/src/src/shared/base_repository.d.ts +0 -80
- package/script/npm/src/src/shared/base_repository.d.ts.map +0 -1
- package/script/npm/src/src/shared/base_repository.js +0 -157
- package/script/npm/src/src/shared/common_responses.d.ts +0 -13
- package/script/npm/src/src/shared/common_responses.d.ts.map +0 -1
- package/script/npm/src/src/shared/common_responses.js +0 -13
- package/script/npm/src/src/shared/index.d.ts +0 -3
- package/script/npm/src/src/shared/index.d.ts.map +0 -1
- package/script/npm/src/src/shared/index.js +0 -18
- package/script/npm/src/src/shared/token_required_repository.d.ts +0 -78
- package/script/npm/src/src/shared/token_required_repository.d.ts.map +0 -1
- package/script/npm/src/src/shared/token_required_repository.js +0 -132
- package/script/package.json +0 -3
package/README.md
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
# @temboplus/afloat
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
This JavaScript/TypeScript package provides a central hub for shared utilities, logic, and data access mechanisms within the Temboplus-Afloat ecosystem.
|
|
3
|
+
A foundational JavaScript/TypeScript library for TemboPlus-Afloat projects, providing abstracted server communication, shared utilities, and standardized data models for consistent development.
|
|
6
4
|
|
|
7
5
|
## Key Features
|
|
8
6
|
|
|
@@ -10,130 +8,248 @@ This JavaScript/TypeScript package provides a central hub for shared utilities,
|
|
|
10
8
|
* Simplifies front-end development by abstracting all interactions with the server behind model-specific repositories
|
|
11
9
|
* Consuming projects only need to interact with these repositories, decoupling them from the underlying API implementation
|
|
12
10
|
|
|
13
|
-
* **
|
|
14
|
-
*
|
|
11
|
+
* **Authentication-Agnostic Repositories**
|
|
12
|
+
* The library does not own session state or export an auth singleton
|
|
13
|
+
* Consuming applications log in, store the returned token, and pass that token to repositories
|
|
15
14
|
|
|
16
15
|
* **Data Models**
|
|
17
16
|
* Defines standardized data structures and interfaces for consistent data representation throughout the Afloat ecosystem
|
|
18
17
|
|
|
19
|
-
* **Enhanced Maintainability**
|
|
20
|
-
* Centralizes common logic, making it easier to maintain and update across all consuming projects
|
|
21
|
-
* Reduces code duplication and improves consistency
|
|
22
|
-
|
|
23
18
|
* **Cross-Environment Compatibility**
|
|
24
19
|
* Works seamlessly in both client-side and server-side environments
|
|
25
|
-
* Supports both synchronous and asynchronous initialization patterns
|
|
26
20
|
|
|
27
21
|
## Usage
|
|
28
22
|
|
|
29
|
-
###
|
|
23
|
+
### Login
|
|
30
24
|
|
|
31
|
-
|
|
25
|
+
Use `AuthRepository.logIn(...)` for the unauthenticated login request. The returned `User` contains the token that should be stored by your app and passed to other repositories.
|
|
32
26
|
|
|
33
|
-
|
|
27
|
+
```typescript
|
|
28
|
+
import { AuthRepository } from "@temboplus/afloat";
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
const authRepo = new AuthRepository();
|
|
32
|
+
const user = await authRepo.logIn("user@example.com", "password123");
|
|
33
|
+
|
|
34
|
+
storeSession({
|
|
35
|
+
token: user.token,
|
|
36
|
+
user: user.toJSON(),
|
|
37
|
+
});
|
|
38
|
+
} catch (error) {
|
|
39
|
+
const message = error instanceof Error ? error.message : "Unknown error";
|
|
40
|
+
console.error("Login failed:", message);
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`AuthRepository` also has authenticated methods. Construct it with a token before calling those:
|
|
34
45
|
|
|
35
46
|
```typescript
|
|
36
|
-
import {
|
|
47
|
+
import { AuthRepository } from "@temboplus/afloat";
|
|
48
|
+
|
|
49
|
+
const authRepo = new AuthRepository({ token });
|
|
37
50
|
|
|
38
|
-
|
|
39
|
-
const
|
|
51
|
+
await authRepo.updatePassword("currentPassword", "newPassword");
|
|
52
|
+
const accessList = await authRepo.getAccessList();
|
|
53
|
+
```
|
|
40
54
|
|
|
41
|
-
|
|
42
|
-
console.log("User authenticated:", !!auth.currentUser);
|
|
55
|
+
### Repository Usage
|
|
43
56
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
57
|
+
Authenticated repositories share the same construction shape:
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
const repo = new SomeRepository({
|
|
61
|
+
token: "user-auth-token",
|
|
62
|
+
root: "https://api.afloat.money/v1", // optional
|
|
63
|
+
});
|
|
49
64
|
```
|
|
50
65
|
|
|
51
|
-
|
|
66
|
+
Use this shape for:
|
|
67
|
+
|
|
68
|
+
* `WalletRepository`
|
|
69
|
+
* `PayoutRepository`
|
|
70
|
+
* `BeneficiaryRepository`
|
|
71
|
+
* `ProfileRepository`
|
|
72
|
+
* `TeamMemberRepository`
|
|
73
|
+
* `IdentityRepository`
|
|
74
|
+
* `AuthRepository` when calling authenticated methods like `updatePassword` or `getAccessList`
|
|
52
75
|
|
|
53
|
-
|
|
76
|
+
The TypeScript constructors accept optional fields because the base repository supports a global token getter, but authenticated Afloat API calls still require a token. Passing `{ token }` explicitly is the recommended and documented integration path.
|
|
77
|
+
|
|
78
|
+
#### Wallet Example
|
|
54
79
|
|
|
55
80
|
```typescript
|
|
56
|
-
import {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
// Initialize server-side auth
|
|
69
|
-
const auth = await AfloatAuth.initializeServer(token);
|
|
70
|
-
|
|
71
|
-
// Now you can use auth for permission checks
|
|
72
|
-
const isAdmin = auth.checkPermission(Permissions.Payout.View);
|
|
73
|
-
|
|
74
|
-
// Continue with your handler logic...
|
|
75
|
-
} catch (error) {
|
|
76
|
-
console.error('Authentication error:', error);
|
|
77
|
-
return res.status(500).json({ error: 'Authentication failed' });
|
|
78
|
-
}
|
|
81
|
+
import { Permissions, WalletRepository } from "@temboplus/afloat";
|
|
82
|
+
|
|
83
|
+
const walletRepo = new WalletRepository({ token });
|
|
84
|
+
const [wallet] = await walletRepo.getWallets();
|
|
85
|
+
|
|
86
|
+
if (!wallet) {
|
|
87
|
+
throw new Error("No wallet available");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (user.can(Permissions.Wallet.ViewBalance)) {
|
|
91
|
+
const balance = await walletRepo.getBalance({ wallet });
|
|
92
|
+
console.log(balance.label);
|
|
79
93
|
}
|
|
94
|
+
|
|
95
|
+
const entries = await walletRepo.getStatement({
|
|
96
|
+
wallet,
|
|
97
|
+
range: {
|
|
98
|
+
startDate: new Date("2024-01-01"),
|
|
99
|
+
endDate: new Date("2024-01-31"),
|
|
100
|
+
},
|
|
101
|
+
});
|
|
80
102
|
```
|
|
81
103
|
|
|
82
|
-
|
|
104
|
+
#### Identity Example
|
|
105
|
+
|
|
106
|
+
`IdentityRepository` reads the authenticated `/login/me` data. It is not the login request itself, so it requires a token.
|
|
83
107
|
|
|
84
|
-
|
|
108
|
+
```typescript
|
|
109
|
+
import { IdentityRepository } from "@temboplus/afloat";
|
|
110
|
+
|
|
111
|
+
const identityRepo = new IdentityRepository({ token });
|
|
112
|
+
const identity = await identityRepo.getIdentity();
|
|
113
|
+
```
|
|
85
114
|
|
|
86
|
-
####
|
|
115
|
+
#### Server Route Example
|
|
87
116
|
|
|
88
117
|
```typescript
|
|
89
|
-
import {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
async
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
console.error('Error fetching balance:', error);
|
|
118
|
+
import { WalletRepository } from "@temboplus/afloat";
|
|
119
|
+
|
|
120
|
+
function extractBearerToken(req): string | undefined {
|
|
121
|
+
return req.headers.authorization?.replace(/^Bearer\s+/i, "");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
app.get("/api/wallets", async (req, res) => {
|
|
125
|
+
const token = extractBearerToken(req);
|
|
126
|
+
|
|
127
|
+
if (!token) {
|
|
128
|
+
return res.status(401).json({ error: "Unauthorized" });
|
|
101
129
|
}
|
|
130
|
+
|
|
131
|
+
const walletRepo = new WalletRepository({ token });
|
|
132
|
+
const wallets = await walletRepo.getWallets();
|
|
133
|
+
|
|
134
|
+
return res.json({ wallets });
|
|
135
|
+
});
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
## Architecture Overview
|
|
139
|
+
|
|
140
|
+
### Host Application Responsibilities
|
|
141
|
+
|
|
142
|
+
* Call `AuthRepository.logIn(...)` to create a session
|
|
143
|
+
* Store the returned token in your own state, cookie, storage, or server session
|
|
144
|
+
* Rehydrate `User` with `User.fromJSON(...)` when needed
|
|
145
|
+
* Pass `{ token }` to repositories before calling authenticated endpoints
|
|
146
|
+
* Check permissions with the returned `User` instance, for example `user.can(Permissions.Wallet.ViewBalance)`
|
|
147
|
+
|
|
148
|
+
### Library Responsibilities
|
|
149
|
+
|
|
150
|
+
* Provide typed repositories for Afloat API resources
|
|
151
|
+
* Attach the token and request ID headers to repository calls
|
|
152
|
+
* Convert API responses into domain models where repositories support it
|
|
153
|
+
* Surface API errors through `APIError` or repository-specific errors
|
|
154
|
+
|
|
155
|
+
## Best Practices
|
|
156
|
+
|
|
157
|
+
### Token Handling
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
import {
|
|
161
|
+
AuthRepository,
|
|
162
|
+
ProfileRepository,
|
|
163
|
+
WalletRepository,
|
|
164
|
+
} from "@temboplus/afloat";
|
|
165
|
+
|
|
166
|
+
const authRepo = new AuthRepository();
|
|
167
|
+
const user = await authRepo.logIn(email, password);
|
|
168
|
+
|
|
169
|
+
saveToken(user.token);
|
|
170
|
+
|
|
171
|
+
const walletRepo = new WalletRepository({ token: user.token });
|
|
172
|
+
const profileRepo = new ProfileRepository({ token: user.token });
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Permission Checks
|
|
176
|
+
|
|
177
|
+
```typescript
|
|
178
|
+
import { Permissions, PayoutRepository } from "@temboplus/afloat";
|
|
179
|
+
|
|
180
|
+
if (user.can(Permissions.Payout.Create)) {
|
|
181
|
+
const payoutRepo = new PayoutRepository({ token: user.token });
|
|
182
|
+
await payoutRepo.pay(input);
|
|
102
183
|
}
|
|
103
184
|
```
|
|
104
185
|
|
|
105
|
-
|
|
186
|
+
## Troubleshooting
|
|
187
|
+
|
|
188
|
+
### Common Issues
|
|
189
|
+
|
|
190
|
+
#### `AfloatAuth` Import Errors
|
|
191
|
+
|
|
192
|
+
**Problem**: `AfloatAuth` is undefined or cannot be imported.
|
|
193
|
+
|
|
194
|
+
**Solution**: Replace `AfloatAuth` usage with `AuthRepository.logIn(...)` plus application-owned session state.
|
|
106
195
|
|
|
107
196
|
```typescript
|
|
108
|
-
import {
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
197
|
+
import { AuthRepository } from "@temboplus/afloat";
|
|
198
|
+
|
|
199
|
+
const authRepo = new AuthRepository();
|
|
200
|
+
const user = await authRepo.logIn(email, password);
|
|
201
|
+
const token = user.token;
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
#### Repository Token Issues
|
|
205
|
+
|
|
206
|
+
**Problem**: Repository calls fail with authentication errors.
|
|
207
|
+
|
|
208
|
+
**Solution**: Ensure the token from login or the incoming request is passed into the repository.
|
|
209
|
+
|
|
210
|
+
```typescript
|
|
211
|
+
if (!extractedToken) {
|
|
212
|
+
throw new Error("Missing authentication token");
|
|
122
213
|
}
|
|
214
|
+
|
|
215
|
+
const repo = new WalletRepository({ token: extractedToken });
|
|
123
216
|
```
|
|
124
217
|
|
|
125
|
-
|
|
218
|
+
#### Identity Repository Confusion
|
|
126
219
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
220
|
+
**Problem**: `IdentityRepository` is used for login.
|
|
221
|
+
|
|
222
|
+
**Solution**: Use `AuthRepository.logIn(...)` for login. Use `IdentityRepository({ token }).getIdentity()` only after you have a token.
|
|
223
|
+
|
|
224
|
+
## API Reference
|
|
225
|
+
|
|
226
|
+
### Login and Auth
|
|
227
|
+
|
|
228
|
+
* `AuthRepository.logIn(email, password)` - Authenticate without an existing token and return a `User`
|
|
229
|
+
* `AuthRepository({ token }).updatePassword(current, next)` - Update the current user's password
|
|
230
|
+
* `AuthRepository({ token }).getAccessList()` - Fetch the current user's access list
|
|
231
|
+
* `User.token` - Token to pass into repositories
|
|
232
|
+
* `User.can(permission)` - Check a single permission
|
|
233
|
+
* `User.canAny(permissions)` - Check if the user has at least one permission
|
|
234
|
+
* `User.canAll(permissions)` - Check if the user has all permissions
|
|
235
|
+
|
|
236
|
+
### Authenticated Repositories
|
|
237
|
+
|
|
238
|
+
All authenticated repositories use:
|
|
239
|
+
|
|
240
|
+
```typescript
|
|
241
|
+
new RepositoryName({
|
|
242
|
+
token: "user-auth-token",
|
|
243
|
+
root: "custom-api-root", // optional
|
|
244
|
+
});
|
|
245
|
+
```
|
|
131
246
|
|
|
132
|
-
|
|
133
|
-
- Always use `await AfloatAuth.initializeServer(token)` for each request
|
|
134
|
-
- Pass the auth instance explicitly to repositories
|
|
135
|
-
- Implement proper error handling for authentication failures
|
|
247
|
+
Available repositories:
|
|
136
248
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
249
|
+
* `WalletRepository` - Wallet operations, balances, and statements
|
|
250
|
+
* `PayoutRepository` - Payout creation, approval, rejection, lookup, and counting
|
|
251
|
+
* `BeneficiaryRepository` - Beneficiary create, edit, remove, and lookup
|
|
252
|
+
* `ProfileRepository` - Current profile lookup
|
|
253
|
+
* `TeamMemberRepository` - Team member and role management
|
|
254
|
+
* `IdentityRepository` - Current `/login/me` identity data
|
|
255
|
+
* `AuthRepository` - Login without token; password and access-list operations with token
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var e=require("zod"),t=require("uuid"),r=require("@temboplus/frontend-core");function a(e){return e&&e.__esModule?e:{default:e}}var o=a(e);class n 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 n.schema.safeParse(e).success}static unknown(e){return new n({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return e.z.object({message:e.z.string(),statusCode:e.z.number().int(),error:e.z.string().optional(),details:e.z.object({}).optional()})}}const s={Profile:{ViewCurrent:"profile.getCurrent",Update:"profile.update"},Beneficiary:{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"},TeamManagement:{ViewMembers:"login.findAll",ViewMember:"login.findById",CreateMember:"login.create",UpdateMember:"login.update",ArchiveMember:"login.archive",UnArchiveMember:"login.unarchive",ResetPassword:"login.resetPassword"}};class i 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.z.union([e.z.enum(Object.values(s.Profile)),e.z.enum(Object.values(s.Beneficiary)),e.z.enum(Object.values(s.Payment)),e.z.enum(Object.values(s.Payout)),e.z.enum(Object.values(s.Transfer)),e.z.enum(Object.values(s.Wallet))]);return e.z.object({name:e.z.literal("PermissionError").nullish(),message:e.z.string(),requiredPermissions:e.z.array(r)}).safeParse(t).success}}const c=e=>"function"==typeof(null==e?void 0:e.passthrough);e.z.object({name:e.z.literal("ZodError"),issues:e.z.array(e.z.object({path:e.z.array(e.z.union([e.z.string(),e.z.number()])),message:e.z.string().optional(),code:e.z.nativeEnum(e.z.ZodIssueCode)}).catchall(e.z.any()))});const u=Symbol("ContractNoBody"),d=e=>"method"in e&&"path"in e,l=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var a,o,n,s,i;return d(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,c(s)?c(i)?s.merge(i):s:c(i)?i:Object.assign({},s,i)),strictStatusCodes:null!==(a=r.strictStatusCodes)&&void 0!==a?a: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!==(n=r.metadata)&&void 0!==n?n:{}}:r.metadata}]:[e,l(r,t)]})),p=Symbol("ContractPlainType"),m=()=>({router:(e,t)=>l(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>p,body:()=>p,type:()=>p,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>u}),h=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("&"):"",f=e=>e?Object.keys(e).flatMap(t=>y(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",y=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>y(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>y(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class g extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const b=async({route:e,path:t,method:r,headers:a,body:o,validateResponse:n,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:a,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!=n?n:e.validateResponseOnClient)&&"function"==typeof(null==(u=r)?void 0:u.safeParse)?{...t,body:r.parse(t.body)}:t}var u;return(null==c?void 0:c.includes("text/"))?{status:i.status,body:await i.text(),headers:i.headers}:{status:i.status,body:await i.blob(),headers:i.headers}},N=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 a of t)r(e,a);else r(e,t)}),t},v=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),w=(e,t,r,a,o)=>{const n=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:a.path,params:r}),s=((e,t=!1)=>{const r=t?h(e):f(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,o);return`${t}${n}${s}`},S=(e,t)=>{const r=Object.keys(e.responses);return async a=>{const o=((e,t,r)=>{const{query:a,params:o,body:n,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...p}=r||{},m={...t,...c};return{path:w(a,m.baseUrl,o,e,!!m.jsonQuery),clientArgs:m,route:e,body:n,query:a,extraInputArgs:p,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...i,...s}}})(e,t,a),n=await(e=>{const{path:t,clientArgs:r,route:a,body:o,query:n,extraInputArgs:s,headers:i,fetchOptions:c}=e,u=r.api||b,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&v(d),...v(i)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let p={route:a,path:t,method:a.method,headers:l,body:void 0,rawBody:o,rawQuery:n,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"!==a.method&&("contentType"in a&&"multipart/form-data"===a.contentType?p={...p,contentType:"multipart/form-data",body:o instanceof FormData?o:N(o)}:"contentType"in a&&"application/x-www-form-urlencoded"===a.contentType?p={...p,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...p.headers},body:"string"==typeof o?o:new URLSearchParams(o)}:null!=o&&(p={...p,contentType:"application/json",headers:{"content-type":"application/json",...p.headers},body:JSON.stringify(o)})),u({...p,...s})})(o);if(!t.throwOnUnknownStatus)return n;if(r.includes(n.status.toString()))return n;throw new g(n,r)}},A=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>d(r)?[e,S(r,t)]:[e,A(r,t)]));let O;class P{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;if(O){const e=O();if(e&&e.trim().length>0)return e}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":t.v4()}};return A(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){const t=o.default.object({statusCode:o.default.number(),message:o.default.string(),error:o.default.string(),details:o.default.record(o.default.string()).optional()}).safeParse(e.body);if(t.success)throw new n(t.data);throw new n({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}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"})}}var C,I;exports.FilterOperator=void 0,(C=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",C.NOT_EQUALS="neq",C.LESS_THAN="lt",C.LESS_THAN_OR_EQUAL="lte",C.GREATER_THAN="gt",C.GREATER_THAN_OR_EQUAL="gte",C.LIKE="like",C.LIKE_LOWER="likeLower",C.IS_NULL="isNull",C.IS_NOT_NULL="isNotNull",C.IN="in",exports.SortDirection=void 0,(I=exports.SortDirection||(exports.SortDirection={})).ASC="asc",I.DESC="desc";const z=Symbol("query-builder-type");class _{options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*"};constructor(e={}){this.options={filters:e.filters||[],sort:e.sort||[],includes:e.includes||[],groupBy:e.groupBy||[],join:e.join||[],page:e.page,limit:e.limit}}[z]="query-builder";static is(e){return null!==e&&"object"==typeof e&&z in e&&"query-builder"===e[z]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN_OR_EQUAL,value:t})}whereBetween(e,t,r){return this.whereGreaterThanOrEqual(e,t).whereLessThanOrEqual(e,r)}whereDateBetween(e,t){if(e){const t=e instanceof Date?e.toISOString():e;this.whereGreaterThanOrEqual("createdAt",t)}if(t){const e=t instanceof Date?t.toISOString():t;this.whereLessThanOrEqual("createdAt",e)}return this}addSort(e){return this.options.sort=[...this.options.sort||[],e],this}orderBy(e,t=exports.SortDirection.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,exports.SortDirection.ASC)}orderByDesc(e){return this.orderBy(e,exports.SortDirection.DESC)}paginate(e,t){return this.options.page=e,this.options.limit=t,this}with(e){const t=Array.isArray(e)?e:[e];return this.options.includes=[...this.options.includes||[],...t],this}join(e){const t=Array.isArray(e)?e:[e];return this.options.join=[...this.options.join||[],...t],this}groupBy(e){const t=Array.isArray(e)?e:[e];return this.options.groupBy=[...this.options.groupBy||[],...t],this}count(e="*"){return this.options.count=e,this}countAs(e,t){return this.options.count=`${e} as ${t}`,this}build(){const e={};if(void 0!==this.options.page&&void 0!==this.options.limit){const t=(this.options.page-1)*this.options.limit,r=t+this.options.limit-1;e.rangeStart=t,e.rangeEnd=r}if(this.options.filters&&this.options.filters.length>0)for(const t of this.options.filters)switch(t.operator){case exports.FilterOperator.IS_NULL:e[`${t.field}:isNull`]=1;break;case exports.FilterOperator.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case exports.FilterOperator.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case exports.FilterOperator.LIKE:e[`${t.field}:like`]=t.value;break;case exports.FilterOperator.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case exports.FilterOperator.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case exports.FilterOperator.LESS_THAN_OR_EQUAL:e[`${t.field}:lte`]=t.value;break;default:e[`${t.field}:${t.operator}`]=t.value}if(this.options.sort&&this.options.sort.length>0){const t=[],r=[];for(const e of this.options.sort)e.direction===exports.SortDirection.ASC?t.push(e.field):r.push(e.field);t.length>0&&(e.orderBy=t.join(",")),r.length>0&&(e.orderByDesc=r.join(","))}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?e.eager=this.options.includes[0]:e.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(e.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(e.groupBy=this.options.groupBy.join(",")),this.options.count&&(e.count=this.options.count),e}clone(){return new(0,this.constructor)({...this.options,filters:this.options.filters?[...this.options.filters]:[],sort:this.options.sort?[...this.options.sort]:[],includes:this.options.includes?[...this.options.includes]:[],groupBy:this.options.groupBy?[...this.options.groupBy]:[],join:this.options.join?[...this.options.join]:[]})}static create(e){return new _(e)}}const E=e.z.object({page:e.z.coerce.number().int().min(1).default(1),limit:e.z.coerce.number().int().min(1).max(100).default(10)}),x=e.z.object({page:e.z.number().int().min(1),limit:e.z.number().int().min(1),total:e.z.number().int().min(0),totalPages:e.z.number().int().min(0),hasNext:e.z.boolean(),hasPrev:e.z.boolean()});class T{page;limit;total;constructor(e,t,r){if(this.page=e,this.limit=t,this.total=r,e<1)throw new Error("Page must be >= 1");if(t<1)throw new Error("Limit must be >= 1");if(r<0)throw new Error("Total must be >= 0")}get totalPages(){return Math.ceil(this.total/this.limit)}get hasNext(){return this.page<this.totalPages}get hasPrev(){return this.page>1}get offset(){return(this.page-1)*this.limit}get isFirstPage(){return 1===this.page}get isLastPage(){return this.page===this.totalPages}nextPage(){return this.hasNext?new T(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new T(this.page-1,this.limit,this.total):null}toJSON(){return{page:this.page,limit:this.limit,total:this.total,totalPages:this.totalPages,hasNext:this.hasNext,hasPrev:this.hasPrev}}}const D={profileDTOSchema:e.z.object({id:e.z.string(),firstName:e.z.string().nullish(),lastName:e.z.string().nullish(),displayName:e.z.string(),phone:e.z.string().nullish(),accountNo:e.z.string().min(1),email:e.z.string().email().nullish(),autoApprove:e.z.boolean().nullish()})},R=e.z.object({id:e.z.string(),firstName:e.z.string().nullable().optional(),lastName:e.z.string().nullable().optional(),displayName:e.z.string(),phone:e.z.string().nullable().optional(),accountNo:e.z.string(),email:e.z.string().nullable().optional(),autoApprove:e.z.boolean().nullable().optional(),version:e.z.string().optional().default("1.0")});class B{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return D.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 B({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()}validate(){try{return B.schema.safeParse(this.toJSON()).success}catch(e){return console.error("Profile validation error:",e),!1}}static from(e){try{return e?"object"!=typeof e?void console.error("Data is not an object"):e.id&&e.accountNo&&e.displayName?B.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 a=t._autoApprove;return null==a||"boolean"==typeof a}toJSON(){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,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=R.safeParse(t);if(!r.success)return void console.error("Invalid ProfileJSON:",r.error.flatten());const a=r.data;return B.from(a)}catch(e){return void console.error("Error parsing ProfileJSON:",e)}}static isProfileJSON(e){return R.safeParse(e).success}}const J={loginDTO:o.default.object({id:o.default.string().min(1,"ID is required"),profileId:o.default.string().min(1,"Profile ID is required"),name:o.default.string().min(1,"Name is required"),identity:o.default.string().email("Identity must be a valid email address"),type:o.default.string().min(1,"Type is required"),roleId:o.default.string().min(1,"Role ID is required"),isActive:o.default.boolean(),isArchived:o.default.boolean(),resetPassword:o.default.boolean(),createdAt:o.default.string().datetime("Invalid creation timestamp"),updatedAt:o.default.string().datetime("Invalid update timestamp"),access:o.default.array(o.default.string())})},M=e.z.object({id:e.z.string(),profileId:e.z.string(),name:e.z.string(),identity:e.z.string(),type:e.z.string(),roleId:e.z.string(),isActive:e.z.boolean(),isArchived:e.z.boolean(),resetPassword:e.z.boolean(),createdAt:e.z.string(),updatedAt:e.z.string(),access:e.z.array(e.z.string()),version:e.z.string().optional().default("1.0")});class j{_id;_profileId;_name;_identity;_type;_roleId;_isActive;_isArchived;_resetPassword;_createdAt;_updatedAt;_access;constructor(e,t,r,a,o,n,s,i,c,u,d,l){this._id=e,this._profileId=t,this._name=r,this._identity=a,this._type=o,this._roleId=n,this._isActive=s,this._isArchived=i,this._resetPassword=c,this._createdAt=u,this._updatedAt=d,this._access=l}static from(e){const t=J.loginDTO.parse(e);return new j(t.id,t.profileId,t.name,t.identity,t.type,t.roleId,t.isActive,t.isArchived,t.resetPassword,new Date(t.createdAt),new Date(t.updatedAt),t.access)}get id(){return this._id}get profileId(){return this._profileId}get name(){return this._name}get identity(){return this._identity}get type(){return this._type}get roleId(){return this._roleId}get isActive(){return this._isActive}get isArchived(){return this._isArchived}get resetPassword(){return this._resetPassword}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get access(){return this._access}toJSON(){return{id:this._id,profileId:this._profileId,name:this._name,identity:this._identity,type:this._type,roleId:this._roleId,isActive:this._isActive,isArchived:this._isArchived,resetPassword:this._resetPassword,createdAt:this._createdAt.toISOString(),updatedAt:this._updatedAt.toISOString(),access:[...this._access],version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=M.safeParse(t);if(!r.success)return void console.error("Invalid LogInJSON:",r.error.flatten());const a=r.data;return j.from({id:a.id,profileId:a.profileId,name:a.name,identity:a.identity,type:a.type,roleId:a.roleId,isActive:a.isActive,isArchived:a.isArchived,resetPassword:a.resetPassword,createdAt:a.createdAt,updatedAt:a.updatedAt,access:a.access})}catch(e){return void console.error("Error parsing LogInJSON:",e)}}static isLogInJSON(e){return M.safeParse(e).success}}const k=o.default.object({id:o.default.string(),name:o.default.string(),description:o.default.string().optional(),access:o.default.array(o.default.string()),createdAt:o.default.string(),updatedAt:o.default.string(),version:o.default.string().optional().default("1.0")});class F{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 F(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(),version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=k.safeParse(t);if(!r.success)return void console.error("Invalid RoleJSON:",r.error.flatten());const a=r.data;return F.from({id:a.id,name:a.name,description:a.description,access:a.access,createdAt:a.createdAt,updatedAt:a.updatedAt})}catch(e){return void console.error("Error parsing RoleJSON:",e)}}static isRoleJSON(e){return k.safeParse(e).success}}const L=o.default.object({companyProfile:R,role:k.optional(),version:o.default.string().optional().default("1.0")});class U{_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return B.is(e.companyProfile)?new U(e):void console.error("Invalid company profile")}catch(e){return void console.error("Error creating CompanyMembership:",e)}}get companyProfile(){return this._companyProfile}get role(){return this._role}toJSON(){return{companyProfile:this._companyProfile.toJSON(),role:this._role?.toJSON(),version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=L.safeParse(t);if(!r.success)return void console.error("Invalid CompanyMembershipJSON:",r.error.flatten());const a=r.data,o=B.fromJSON(a.companyProfile),n=a.role?F.fromJSON(a.role):void 0;return o?U.from({companyProfile:o,role:n}):void console.error("Failed to reconstruct Profile from CompanyMembershipJSON")}catch(e){return void console.error("Error parsing CompanyMembershipJSON:",e)}}static isCompanyMembershipJSON(e){return L.safeParse(e).success}}const $=o.default.object({logIn:M,companyProfile:R,role:k.optional(),token:o.default.string().min(1),version:o.default.string().optional().default("1.0")});class q{_logIn;_membership;_token;_permissionMap;constructor(e){this._logIn=e.logIn,this._membership=e.membership,this._token=e.token,this._permissionMap={},this._logIn.access.forEach(e=>{this._permissionMap[e]=!0})}static from(e){try{if(!e.logIn||!e.companyProfile||!e.token)return void console.error("Missing required User fields");if("string"!=typeof e.token||""===e.token.trim())return void console.error("Invalid token");const t=U.from({companyProfile:e.companyProfile,role:e.role});return t?new q({logIn:e.logIn,membership:t,token:e.token}):void console.error("Failed to create CompanyMembership")}catch(e){return void console.error("Error creating User:",e)}}get logIn(){return this._logIn}get membership(){return this._membership}get token(){return this._token}get id(){return this._logIn.id}get name(){return this._logIn.name}get identity(){return this._logIn.identity}get roleId(){return this._logIn.roleId}get resetPassword(){return this._logIn.resetPassword}get profile(){return this._membership.companyProfile}get role(){return this._membership.role}get access(){return this._logIn.access}can(e){return this._permissionMap[e]??!1}canAny(e){return e.some(e=>this.can(e))}canAll(e){return e.every(e=>this.can(e))}canManageTeam(){return this.can(s.TeamManagement.ViewMembers)}canViewRoles(){return this.can(s.Role.ViewRole)}toJSON(){return{logIn:this._logIn.toJSON(),companyProfile:this._membership.companyProfile.toJSON(),role:this._membership.role?.toJSON(),token:this._token,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=$.safeParse(t);if(!r.success)return void console.error("Invalid UserJSON:",r.error.flatten());const a=r.data,o=j.fromJSON(a.logIn),n=B.fromJSON(a.companyProfile),s=a.role?F.fromJSON(a.role):void 0;if(!o||!n)return void console.error("Failed to reconstruct nested objects from UserJSON");if(!a.token||""===a.token.trim())return void console.error("Invalid token in UserJSON");const i=U.from({companyProfile:n,role:s});return i?new q({logIn:o,membership:i,token:a.token}):void console.error("Failed to create CompanyMembership from UserJSON")}catch(e){return void console.error("Error parsing UserJSON:",e)}}static isUserJSON(e){return $.safeParse(e).success}}const W=m().router({logIn:{method:"POST",path:"/login",body:e.z.object({type:e.z.string().default("password"),identity:e.z.string().email(),password:e.z.string()}),responses:{201:e.z.object({profile:D.profileDTOSchema,token:e.z.string(),access:e.z.array(e.z.string()),resetPassword:e.z.boolean()}),400:e.z.object({})}},access:{method:"GET",path:"/access",responses:{200:e.z.string().array()}},resetPassword:{method:"PUT",path:"/password",body:e.z.object({currentPassword:e.z.string(),newPassword:e.z.string()}),responses:{}}}),V=m().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:J.loginDTO}}});class H extends P{constructor(e){super("login",V,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}`)}}const G=e.z.string().min(8,"Password must be at least 8 characters long").max(128,"Password must not exceed 128 characters").regex(/[A-Z]/,"Password must contain at least one uppercase letter").regex(/[a-z]/,"Password must contain at least one lowercase letter").regex(/[0-9]/,"Password must contain at least one number").regex(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/,"Password must contain at least one special character (!@#$%^&*()_+-=[]{}|;:,.<>?)").refine(e=>![/(.)\1{2,}/,/123456|654321|abcdef|qwerty|password|admin|user/i,/^[0-9]+$/,/^[a-zA-Z]+$/].some(t=>t.test(e)),"Password contains weak patterns. Avoid repeated characters, common words, or simple sequences").refine(e=>!/(?:abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789)/i.test(e),"Password should not contain sequential characters").refine(e=>!/(?:qwer|wert|erty|rtyu|tyui|yuio|uiop|asdf|sdfg|dfgh|fghj|ghjk|hjkl|zxcv|xcvb|cvbn|vbnm)/i.test(e),"Password should not contain keyboard patterns"),Q=e.z.object({id:e.z.string().min(1),name:e.z.string().min(1,"Role name is required"),description:e.z.string().optional(),access:e.z.array(e.z.string()),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),K=e.z.object({id:e.z.string().min(1),name:e.z.string().min(1,"Team member name is required"),identity:e.z.string().email("Invalid email address"),type:e.z.string().min(1,"Team member type is required"),profileId:e.z.string().min(1,"Profile ID is required"),roleId:e.z.string().min(1,"Role ID is required"),resetPassword:e.z.boolean(),isActive:e.z.boolean(),isArchived:e.z.boolean(),role:Q.optional(),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),Z={role:Q,teamMember:K,teamMemberQueryParams:e.z.object({id:e.z.string().min(1).optional(),name:e.z.string().min(1).optional(),identity:e.z.string().email("Invalid email address").optional(),type:e.z.string().min(1).optional(),profileId:e.z.string().min(1).optional(),roleId:e.z.string().min(1).optional(),resetPassword:e.z.number().optional(),isActive:e.z.number().optional(),isArchived:e.z.number().optional(),createdAt:e.z.string().datetime("Invalid creation timestamp").optional(),updatedAt:e.z.string().datetime("Invalid update timestamp").optional(),eager:e.z.string().optional()}),createTeamMemberRequest:e.z.object({name:e.z.string().min(1,"Team member name is required"),identity:e.z.string().email("Valid email address is required"),password:G.optional(),roleId:e.z.string().optional(),resetPassword:e.z.boolean().optional()}),updateTeamMemberRequest:e.z.object({name:e.z.string().min(1,"Team member name cannot be empty").optional(),roleId:e.z.string().min(1,"Role ID cannot be empty").optional(),password:G.optional(),resetPassword:e.z.boolean().optional(),isActive:e.z.boolean().optional()}),resetPasswordRequest:e.z.object({newPassword:G.optional(),sendNotification:e.z.boolean().optional()}),createTeamMemberResponse:e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string(),type:e.z.string(),profileId:e.z.string(),resetPassword:e.z.boolean(),roleId:e.z.string(),isActive:e.z.boolean(),isArchived:e.z.boolean(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime()}),password:G},Y=m().router({getTeamMembers:{method:"GET",path:"/login",query:Z.teamMemberQueryParams,responses:{200:e.z.array(Z.teamMember),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List all team members",description:"Retrieve a list of all team member accounts in the system"},getTeamMember:{method:"GET",path:"/login/:id",pathParams:e.z.object({id:e.z.string()}),query:Z.teamMemberQueryParams,responses:{200:Z.teamMember,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Get team member details",description:"Retrieve detailed information about a specific team member"},createTeamMember:{method:"POST",path:"/login",body:Z.createTeamMemberRequest,responses:{201:Z.createTeamMemberResponse,400:e.z.object({message:e.z.string().optional(),errors:e.z.array(e.z.string()).optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),409:e.z.object({message:e.z.string().optional()})},summary:"Create new team member",description:"Create a new team member account with specified role and permissions"},updateTeamMember:{method:"PATCH",path:"/login/:id",pathParams:e.z.object({id:e.z.string()}),body:Z.updateTeamMemberRequest,responses:{200:Z.teamMember,400:e.z.object({message:e.z.string().optional(),errors:e.z.array(e.z.string()).optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Update team member",description:"Update team member information, role, status, or force password reset"},archiveTeamMember:{method:"POST",path:"/login/:id/archive",pathParams:e.z.object({id:e.z.string()}),body:e.z.object({}),responses:{200:Z.teamMember,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Archive team member",description:"Archive (soft delete) a team member account"},unArchiveTeamMember:{method:"POST",path:"/login/:id/unarchive",pathParams:e.z.object({id:e.z.string()}),body:e.z.object({}),responses:{200:Z.teamMember,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Unarchive team member",description:"Unarchive a previously archived team member account"},resetPassword:{method:"POST",path:"/login/:id/reset-password",pathParams:e.z.object({id:e.z.string()}),body:Z.resetPasswordRequest,responses:{200:e.z.object({success:e.z.boolean()}),400:e.z.object({message:e.z.string().optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Reset team member password",description:"Reset a team member's password and optionally send notification"},getRoles:{method:"GET",path:"/role",responses:{200:e.z.array(Z.role),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List all roles",description:"Retrieve a list of all available roles in the system"},getRole:{method:"GET",path:"/role/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:Z.role,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Get role details",description:"Retrieve detailed information about a specific role"}}),X=o.default.object({id:o.default.string(),name:o.default.string(),identity:o.default.string(),type:o.default.string(),profileId:o.default.string(),roleId:o.default.string(),resetPassword:o.default.boolean(),isActive:o.default.boolean(),isArchived:o.default.boolean(),role:k.optional(),createdAt:o.default.string(),updatedAt:o.default.string(),version:o.default.string().optional().default("1.0")});class ee{id;name;identity;type;profileId;roleId;resetPassword;isActive;isArchived;role;createdAt;updatedAt;permissions;constructor(e){if(this.id=e.id,this.name=e.name,this.identity=e.identity,this.type=e.type,this.profileId=e.profileId,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),this.permissions=new Set(e.role?.access??[]),e.role)try{this.role=new F(e.role)}catch(e){}}static from(e){try{return e?.id&&e?.name&&e?.identity&&e?.roleId?new ee(e):void console.error("Missing required TeamMember fields:",e)}catch(e){return void console.error("Error creating TeamMember:",e)}}static fromJson(e){try{const t=JSON.parse(e);return ee.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>ee.from(e)).filter(Boolean)}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))}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()}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(),version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=X.safeParse(t);if(!r.success)return void console.error("Invalid TeamMemberJSON:",r.error.flatten());const a=r.data,o=a.role?{id:a.role.id,name:a.role.name,description:a.role.description,access:a.role.access,createdAt:a.role.createdAt,updatedAt:a.role.updatedAt}:void 0;return ee.from({id:a.id,name:a.name,identity:a.identity,type:a.type,profileId:a.profileId,roleId:a.roleId,resetPassword:a.resetPassword,isActive:a.isActive,isArchived:a.isArchived,role:o,createdAt:a.createdAt,updatedAt:a.updatedAt})}catch(e){return void console.error("Error parsing TeamMemberJSON:",e)}}static isTeamMemberJSON(e){return X.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>ee.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing TeamMember JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}}class te extends P{constructor(e){super("admin",Y,e)}async createTeamMember(e){const t=await this.client.createTeamMember({body:e});return this.handleResponse(t,201)}async updateTeamMember(e,t){const r=await this.client.updateTeamMember({params:{id:e},body:t}),a=this.handleResponse(r,200),o=ee.from(a);if(!o)throw new Error("Invalid team member data received from server");return o}async archiveTeamMember(e){const t=await this.client.archiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),a=ee.from(r);if(!a)throw new Error("Invalid team member data received from server");return a}async unArchiveTeamMember(e){const t=await this.client.unArchiveTeamMember({params:{id:e}}),r=this.handleResponse(t,200),a=ee.from(r);if(!a)throw new Error("Invalid team member data received from server");return a}async resetTeamMemberPassword(e,t={}){const r=await this.client.resetPassword({params:{id:e},body:t});return this.handleResponse(r,200)}async getAllTeamMembers(e={eager:"role"}){const t=await this.client.getTeamMembers({query:e}),r=this.handleResponse(t,200);return ee.createMany(r)}async getTeamMember(e,t={eager:"role"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),a=this.handleResponse(r,200),o=ee.from(a);if(!o)throw new Error("Invalid team member data received from server");return o}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=F.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),a=F.from(r);if(!a)throw new Error("Invalid role data received from server");return a}}var re;exports.BeneficiaryType=void 0,(re=exports.BeneficiaryType||(exports.BeneficiaryType={})).Bank="Bank",re.Mobile="Mobile";const ae=e.z.nativeEnum(exports.BeneficiaryType),oe=e.z.object({displayName:e.z.string().min(1,"Display name is required"),accountNo:e.z.string().min(1,"Account number is required"),channel:e.z.string().min(1,"Channel is required"),type:ae}),ne={beneficiaryDTO:e.z.object({id:e.z.string().min(1,"Beneficiary id is required"),profileId:e.z.string(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime()}).merge(oe),beneficiaryInputDTO:oe,beneficiaryType:ae},se=e.z.object({type:e.z.literal("Mobile"),name:e.z.string().min(1),phoneNumber:e.z.string().regex(/^\+[1-9]\d{6,14}$/),mnoId:e.z.string().min(1),version:e.z.string().optional().default("1.0")}),ie=e.z.object({type:e.z.literal("Bank"),accName:e.z.string().min(1),swiftCode:e.z.string().length(8),countryCode:e.z.string().length(2),accNo:e.z.string().min(1),version:e.z.string().optional().default("1.0")}),ce=e.z.discriminatedUnion("type",[se,ie]);class ue extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="BeneficiaryError"}}class de{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}toJSONString(){return JSON.stringify(this.toJSON())}get isMobile(){return this.type===exports.BeneficiaryType.Mobile}get isBank(){return this.type===exports.BeneficiaryType.Bank}get displayName(){return this.accountName}}class le extends de{name;phoneNumber;mnoId;constructor(e,t,r){super(exports.BeneficiaryType.Mobile,t.countryCode),this.name=e,this.phoneNumber=t;const a=le.resolveMnoId(t,r),o=le.checkInputs(e,t,a);if(!o.isValid)throw new ue(o.errors[0],{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format,mnoId:a});this.mnoId=a}static resolveMnoId(e,t){return r.MobileMoneyProviderHelpers.requiresExplicitProvider(e.countryCode)?t:r.MobileMoneyProviderHelpers.detectProviderByPhoneNumber(e)?.id}static checkInputs(e,t,a){const o=[];return e?.trim()||o.push("Name is required and cannot be empty"),t?.validate()||o.push("Invalid phone number"),a?r.MobileMoneyProviderHelpers.validateProviderForPhoneNumber(t,a)||o.push(`Invalid MNO ${a} for phone number ${t.e164Format}`):o.push(r.MobileMoneyProviderHelpers.requiresExplicitProvider(t.countryCode)?`MNO must be explicitly provided for phone numbers in ${t.countryCode}`:`Failed to determine MNO for phone number ${t.e164Format}`),{isValid:0===o.length,errors:o,warnings:[]}}static pickMnoIdFromDTO(e,t){if(r.MobileMoneyProviderHelpers.requiresExplicitProvider(e.countryCode)){if("string"!=typeof t)return;return r.MobileMoneyProviderHelpers.isProviderSupported(e.countryCode,t)?t:void console.warn(`Invalid MNO ${t} for country ${e.countryCode}`)}const a=r.MobileMoneyProviderHelpers.detectProviderByPhoneNumber(e);if(a)return a.id;console.warn(`Failed to auto-detect MNO for phone number ${e.e164Format}`)}static from(e){try{return new le(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileBeneficiaryInfo:",e)}}static fromBeneficiaryDTO(e){if(e.type!==exports.BeneficiaryType.Mobile)return;const t=e.accountNo.startsWith("+")?e.accountNo:`+${e.accountNo}`,a=r.PhoneNumber.from(t);if(!a)return void console.error(`Failed to parse phone number ${t}`);const o=le.pickMnoIdFromDTO(a,e.channel);return o?le.from({name:e.displayName,phoneNumber:a,mnoId:o}):void 0}static fromPayoutDTO(e){if(!r.CountryHelpers.isISO2Code(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=r.PhoneNumber.from(e.msisdn,{defaultCountry:e.countryCode});if(!t)return void console.error(`Failed to parse phone number: ${e.msisdn}`);const a=le.pickMnoIdFromDTO(t,e.channel);return a?le.from({name:e.payeeName,phoneNumber:t,mnoId:a}):void 0}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===exports.BeneficiaryType.Mobile&&(!("string"!=typeof t.name||!t.name.trim())&&(!!r.PhoneNumber.is(t.phoneNumber)&&("string"==typeof t.mnoId&&r.MobileMoneyProviderHelpers.isProviderSupported(t.phoneNumber.countryCode,t.mnoId))))}validate(){return le.checkInputs(this.name,this.phoneNumber,this.mnoId).isValid}getValidationDetails(){return le.checkInputs(this.name,this.phoneNumber,this.mnoId)}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(r.PhoneNumberFormat.E164)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){const e=r.MobileMoneyProviderHelpers.findById(this.mnoId,this.countryCode);return e?.mobileMoneyServiceName??e?.displayName??this.mnoId}get mobileMoneyProvider(){return r.MobileMoneyProviderHelpers.findById(this.mnoId,this.countryCode)}toJSON(){return{type:"Mobile",name:this.name,phoneNumber:this.phoneNumber.e164Format,mnoId:this.mnoId,version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,a=se.safeParse(t);if(!a.success)return void console.error("Invalid MobileBeneficiaryJSON:",a.error.flatten());const o=r.PhoneNumber.from(a.data.phoneNumber);if(!o)return;return le.from({name:a.data.name,phoneNumber:o,mnoId:a.data.mnoId})}catch(e){return void console.error("Error parsing MobileBeneficiaryJSON:",e)}}static fromJSONString(e){return le.fromJSON(e)}static isJSON(e){return se.safeParse(e).success}}class pe extends de{accName;bank;accNo;constructor(e,t,r){super(exports.BeneficiaryType.Bank,t.countryCode),this.accName=e,this.bank=t,this.accNo=r;const a=pe.checkInputs(e,t,r);if(!a.isValid)throw new ue(a.errors[0],{operation:"constructor",countryCode:t.countryCode})}static checkInputs(e,t,a){const o=[];return r.BankHelpers.validateAccountName(e)||o.push("Invalid account name"),r.Bank.is(t)?r.BankHelpers.validateAccountNumber(a,t.countryCode)||o.push("Invalid account number"):o.push("Invalid bank reference"),{isValid:0===o.length,errors:o,warnings:[]}}static from(e){try{return new pe(e.accName,e.bank,e.accNo)}catch(e){return void console.error("Failed to create BankBeneficiaryInfo:",e)}}static fromBeneficiaryDTO(e){if(e.type!==exports.BeneficiaryType.Bank)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank beneficiaries");const a=r.BankHelpers.getCountryFromSwiftCode(t);if(!a)return void console.error(`Could not identify country from SWIFT code: ${t}`);const o=r.Bank.fromBIC(t,a);if(o)return pe.from({accName:e.displayName,bank:o,accNo:e.accountNo});console.error(`Bank with SWIFT code ${t} not found`)}static fromPayoutDTO(e){if(!r.CountryHelpers.isISO2Code(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[a,o]=t,n=r.Bank.fromBIC(a,e.countryCode);if(n)return pe.from({accName:e.payeeName,bank:n,accNo:o});console.error(`Bank with SWIFT code ${a} not found`)}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===exports.BeneficiaryType.Bank&&("string"==typeof t.accName&&("string"==typeof t.accNo&&(!!r.Bank.is(t.bank)&&(r.BankHelpers.validateAccountName(t.accName)&&r.BankHelpers.validateAccountNumber(t.accNo,t.bank.countryCode)))))}validate(){return pe.checkInputs(this.accName,this.bank,this.accNo).isValid}getValidationDetails(){return pe.checkInputs(this.accName,this.bank,this.accNo)}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.bic}get channelName(){return this.bank.shortName}toJSON(){return{type:"Bank",accName:this.accName,swiftCode:this.bank.bic,countryCode:this.bank.countryCode,accNo:this.accNo,version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,a=ie.safeParse(t);if(!a.success)return void console.error("Invalid BankBeneficiaryJSON:",a.error.flatten());const o=a.data;if(!r.CountryHelpers.isISO2Code(o.countryCode))return;const n=r.Bank.fromBIC(o.swiftCode,o.countryCode);if(!n)return;return pe.from({accName:o.accName,bank:n,accNo:o.accNo})}catch(e){return void console.error("Error parsing BankBeneficiaryJSON:",e)}}static fromJSONString(e){return pe.fromJSON(e)}static isJSON(e){return ie.safeParse(e).success}}const me={fromBeneficiaryDTO:e=>e.type===exports.BeneficiaryType.Mobile?le.fromBeneficiaryDTO(e):pe.fromBeneficiaryDTO(e),fromPayoutDTO:e=>e.msisdn.includes(":")?pe.fromPayoutDTO(e):le.fromPayoutDTO(e),fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ce.safeParse(t);if(!r.success)return;return"Mobile"===r.data.type?le.fromJSON(r.data):pe.fromJSON(r.data)}catch{return}},fromJSONString:e=>me.fromJSON(e),is:e=>le.is(e)||pe.is(e),isJSON:e=>ce.safeParse(e).success},he=e.z.object({data:ne.beneficiaryDTO,version:e.z.string().optional().default("1.0")});class fe{data;_info;_infoComputed=!1;constructor(e){this.data=ne.beneficiaryDTO.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._infoComputed||(this._infoComputed=!0,this.data.type===exports.BeneficiaryType.Mobile?this._info=le.fromBeneficiaryDTO(this.data):this.data.type===exports.BeneficiaryType.Bank&&(this._info=pe.fromBeneficiaryDTO(this.data))),this._info}get accNo(){const e=this.info;return e?e.accountNumber:this.data.accountNo}get accName(){return this.data.displayName}get accNoLabel(){return this.type===exports.BeneficiaryType.Mobile?"Phone Number":this.type===exports.BeneficiaryType.Bank?"Bank Account Number":"Account Number"}get channelLabel(){return this.type===exports.BeneficiaryType.Mobile?"Channel":this.type===exports.BeneficiaryType.Bank?"Bank":"Channel"}get accNameLabel(){return this.type===exports.BeneficiaryType.Mobile?"Full Name":this.type===exports.BeneficiaryType.Bank?"Bank Account Name":"Display Name"}get channelName(){return this.info?.channelName??""}static from(e){try{return new fe(e)}catch(e){return void console.error("Failed to create Beneficiary:",e)}}static create(e){return new fe(e)}static createMany(e){return e.map(e=>new fe(e))}static createSafe(e){return fe.from(e)??null}static canConstruct(e){return ne.beneficiaryDTO.safeParse(e).success}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&fe.canConstruct(e.data))}toJSON(){return{data:{...this.data},version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=he.safeParse(t);if(!r.success)return void console.error("Invalid BeneficiaryJSON:",r.error.flatten());const a=r.data;return fe.from(a.data)}catch(e){return void console.error("Error parsing BeneficiaryJSON:",e)}}static fromJSONString(e){return fe.fromJSON(e)}static isBeneficiaryJSON(e){return he.safeParse(e).success}}class ye{canHandle(e){return"Mobile"===e.type&&le.is(e)}createInput(e){if(le.is(e))return{type:exports.BeneficiaryType.Mobile,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile BeneficiaryInfo Info")}}class ge{canHandle(e){return"Bank"===e.type&&pe.is(e)}createInput(e){if(pe.is(e))return{type:exports.BeneficiaryType.Bank,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Bank BeneficiaryInfo Info")}}class be{handlers=[new ye,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)}}const Ne=m().router({createBeneficiary:{method:"POST",path:"/",body:ne.beneficiaryInputDTO,responses:{201:ne.beneficiaryDTO}},editBeneficiary:{method:"PATCH",path:"/:id",body:ne.beneficiaryInputDTO,responses:{200:ne.beneficiaryDTO}},getBeneficiaries:{method:"GET",path:"/",query:e.z.object({orderByDesc:e.z.string()}),responses:{200:e.z.array(ne.beneficiaryDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:ne.beneficiaryDTO}},deleteBeneficiary:{method:"DELETE",path:"/:id",body:e.z.object({}),responses:{200:e.z.object({})}}});var ve,we,Se;exports.PayoutChannel=void 0,(ve=exports.PayoutChannel||(exports.PayoutChannel={})).MOBILE="Mobile",ve.BANK="Bank",exports.PayoutStatus=void 0,(we=exports.PayoutStatus||(exports.PayoutStatus={})).CREATED="CREATED",we.PENDING="PENDING",we.PAID="PAID",we.FAILED="FAILED",we.REJECTED="REJECTED",we.REVERSED="REVERSED",we.QUEUED="QUEUED",exports.PayoutApprovalStatus=void 0,(Se=exports.PayoutApprovalStatus||(exports.PayoutApprovalStatus={})).PENDING="Pending",Se.APPROVED="Approved",Se.REJECTED="Rejected";const Ae=e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string()}),Oe=e.z.nativeEnum(exports.PayoutStatus),Pe=e.z.nativeEnum(exports.PayoutApprovalStatus),Ce=e.z.object({channel:e.z.string(),msisdn:e.z.string(),amount:e.z.coerce.number(),description:e.z.string(),notes:e.z.string().nullish()}),Ie=Ce.extend({payeeName:e.z.string()}),ze=Ce.extend({id:e.z.string(),profileId:e.z.string(),payeeName:e.z.string(),countryCode:e.z.string().default("TZ").refine(e=>r.CountryHelpers.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>r.CurrencyHelpers.isCode(e),{message:"Provided currency code is not a valid currency code."}),channel:e.z.string(),status:Oe,statusMessage:e.z.string(),partnerReference:e.z.string().nullish(),createdAt:e.z.coerce.date(),updatedAt:e.z.coerce.date(),actionedAt:e.z.coerce.date().nullish(),approvalStatus:Pe.nullish(),createdBy:Ae.nullish(),actionedBy:Ae.nullish()}),_e=e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(100).default(10),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().nullish(),endDate:e.z.string().datetime().nullish(),payeeName:e.z.string().nullish(),msisdn:e.z.string().nullish(),profileId:e.z.string().nullish(),id:e.z.string().nullish(),partnerReference:e.z.string().nullish(),channel:e.z.string().nullish(),currencyCode:e.z.string().nullish(),status:Oe.nullish(),approvalStatus:Pe.nullish(),minAmount:e.z.number().min(0).nullish(),maxAmount:e.z.number().min(0).nullish(),search:e.z.string().nullish()}),Ee={PayoutDTO:ze,PayoutInputDTO:Ie,PayoutStatus:Oe,PayoutApprovalStatus:Pe,PayoutAuthorizer:Ae,PayoutFilters:_e,PayoutURLQueryParams:e.z.object({page:e.z.string().transform(e=>parseInt(e)||1).optional(),limit:e.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().optional(),endDate:e.z.string().optional(),payeeName:e.z.string().optional(),msisdn:e.z.string().optional(),profileId:e.z.string().optional(),id:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:e.z.string().optional(),status:e.z.string().refine(e=>Object.values(exports.PayoutStatus).includes(e)).transform(e=>e).optional(),approvalStatus:e.z.string().refine(e=>Object.values(exports.PayoutApprovalStatus).includes(e)).transform(e=>e).optional(),minAmount:e.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:e.z.string().transform(e=>parseFloat(e)).optional(),search:e.z.string().optional()})},xe=o.default.object({id:o.default.string(),profileId:o.default.string(),payeeName:o.default.string(),channel:o.default.string(),msisdn:o.default.string(),amount:o.default.number(),currencyCode:o.default.string(),countryCode:o.default.string(),description:o.default.string(),notes:o.default.string().nullish(),status:Ee.PayoutStatus,statusMessage:o.default.string(),partnerReference:o.default.string().nullish(),createdAt:o.default.string(),updatedAt:o.default.string(),actionedAt:o.default.string().nullish(),approvalStatus:Ee.PayoutApprovalStatus.nullish(),createdBy:Ee.PayoutAuthorizer.nullish(),actionedBy:Ee.PayoutAuthorizer.nullish(),version:o.default.string().optional().default("1.0")});class Te{data;constructor(e){this.data=Ee.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 r.Amount.from(this.data.amount,this.data.currencyCode)}get description(){return this.data.description}get notes(){return this.data.notes}get status(){return"Rejected"===this.data.approvalStatus?exports.PayoutStatus.REJECTED:"Approved"===this.data.approvalStatus?"FAILED"===this.data.status?exports.PayoutStatus.FAILED:exports.PayoutStatus.PAID:"Pending"===this.data.approvalStatus?exports.PayoutStatus.PENDING:this.data.status}get statusMessage(){return this.data.statusMessage}get partnerReference(){return this.data.partnerReference}get createdAt(){return this.data.createdAt}get updatedAt(){return this.data.updatedAt}get actionedAt(){return this.data.actionedAt}get approvalStatus(){return this.data.approvalStatus}get createdBy(){return this.data.createdBy}get actionedBy(){return this.data.actionedBy}get beneficiaryInfo(){return"TZ-BANK-B2C"===this.channel?pe.fromPayoutDTO(this.data):le.fromPayoutDTO(this.data)}get contactInfo(){return this.beneficiaryInfo}static create(e){return new Te(e)}static createMany(e){return e.map(e=>new Te(e))}static createSafe(e){try{return new Te(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=Ee.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==Te.createSafe(t.data)}static is(e){return!(!e||"object"!=typeof e)&&("data"in e&&Te.canConstruct(e.data))}toJSON(){return{id:this.data.id,profileId:this.data.profileId,payeeName:this.data.payeeName,channel:this.data.channel,msisdn:this.data.msisdn,amount:this.data.amount,currencyCode:this.data.currencyCode,countryCode:this.data.countryCode,description:this.data.description,notes:this.data.notes,status:this.data.status,statusMessage:this.data.statusMessage,partnerReference:this.data.partnerReference,createdAt:this.data.createdAt.toISOString(),updatedAt:this.data.updatedAt.toISOString(),actionedAt:this.data.actionedAt?.toISOString()??null,approvalStatus:this.data.approvalStatus,createdBy:this.data.createdBy,actionedBy:this.data.actionedBy,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,a=xe.safeParse(t);if(!a.success)return void console.error("Invalid PayoutJSON:",a.error.flatten());const o=a.data,n=o.currencyCode;if(!r.CurrencyHelpers.isCode(n))return void console.error("Invalid currency code:",n);const s=o.countryCode;if(!r.CountryHelpers.isISO2Code(s))return void console.error("Invalid country code:",s);const i={id:o.id,profileId:o.profileId,payeeName:o.payeeName,channel:o.channel,msisdn:o.msisdn,amount:o.amount,currencyCode:n,countryCode:s,description:o.description,notes:o.notes,status:o.status,statusMessage:o.statusMessage,partnerReference:o.partnerReference,createdAt:new Date(o.createdAt),updatedAt:new Date(o.updatedAt),actionedAt:o.actionedAt?new Date(o.actionedAt):null,approvalStatus:o.approvalStatus,createdBy:o.createdBy,actionedBy:o.actionedBy};return Te.create(i)}catch(e){return void console.error("Error parsing PayoutJSON:",e)}}static isPayoutJSON(e){return xe.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>Te.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing Payout JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}}const De="MOBILE TRANSFER ",Re="PAYOUT",Be="PAYOUT TO BANK",Je="TO_BANK",Me="PAYOUT TO MOBILE",je="TO_MOMO",ke=o.default.object({text:o.default.string(),version:o.default.string().optional().default("2.0")});class Fe{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 le.is(e)?Fe.generateMobilePayoutNarrationV2(e):pe.is(e)?Fe.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${Re.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:a}=e;return`${Re.toUpperCase()} ${t.bic.trim()} ${a.trim()} ${r.trim()}`.toUpperCase()}getBeneficiaryDetails=()=>{const e=this.getBankBeneficiaryDetails(),t=this.getMobileBeneficiaryDetails();return e||(t||void 0)};getBankBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(De)&&(e=e.substring(16));try{if(e.startsWith(Re)){const t=e.replace(Re,"").trim().split(" ");if(t.length>=3){const e=t[0],a=t[1],o=t.slice(2).map(Le).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=r.BankHelpers.getCountryFromSwiftCode(e);if(t){if(r.BankHelpers.validateSwiftCode(e,t)){const n=r.Bank.fromBIC(e,t);if(a&&o&&n)return new pe(o,n,a)}}}}}if(e.startsWith(Je)){const t=e.split("=>")[1].trim(),a=JSON.parse(t),o=a.account_number,n=a.account_name,s=a.swift_code,i=r.BankHelpers.getCountryFromSwiftCode(s);if(!i)return;if(!r.BankHelpers.validateSwiftCode(s,i))return;const c=r.Bank.fromBIC(s,i);if(o&&n&&c)return new pe(n,c,o)}if(e.startsWith(Be)){const t=e.replace(Be,"").trim().split(" "),a=r.BankRegistry.getInstance().searchBanks("TZ",t[0]),o=a.length>0?a[0]:void 0,n=t[1],s=t.slice(2).map(Le).join(" ");if(s&&n&&o)return new pe(s,o,n)}}catch(e){return}};getMobileBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(De)&&(e=e.substring(16));try{if(e.startsWith(Re)){const t=e.replace(Re,"").trim().split(" ");if(t.length>=2){const e=t[0],a=t.slice(1).map(Le).join(" ");if(e.startsWith("+")){const t=r.PhoneNumber.from(e);if(t&&a)return new le(a,t)}}}if(e.startsWith(je)){const t=e.split("=>")[1].trim(),a=JSON.parse(t),o=r.PhoneNumber.from(a.phone_number,{defaultCountry:"TZ"});let n=a.username;void 0===n&&(n="");let s=n.split(" ");if(s=s.filter(e=>e.trim().length>0),n=s.map(Le).join(" "),o&&n)return new le(n,o)}if(e.startsWith(Me)){const t=e.replace(Me,"").trim().split(" "),a=r.PhoneNumber.from(t[0],{defaultCountry:"TZ"}),o=t.slice(1).map(Le).join(" ");if(a&&o)return new le(o,a)}}catch(e){return}};static is(e){if(!e||"object"!=typeof e)return!1;const t=e;try{return"string"==typeof t.text&&"function"==typeof t.getBeneficiaryDetails&&"function"==typeof t.toJson}catch(e){return!1}}toJSON(){return{text:this.text,version:"2.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ke.safeParse(t);if(!r.success)return void console.error("Invalid NarrationJSON:",r.error.flatten());const a=r.data;return new Fe(a.text)}catch(e){return void console.error("Error parsing NarrationJSON:",e)}}static isNarrationJSON(e){return ke.safeParse(e).success}toJson(){return this.toJSON()}static fromJson(e){return Fe.fromJSON(e)}}function Le(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}const Ue={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 TZ and KE banks are supported for now",UNSUPPORTED_COUNTRY_MOBILE:"Only TZ and KE mobile numbers are supported for now",NO_HANDLER_FOUND:"Cannot create payout input!"}};class $e{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}static isPhoneEligibleForPayout(e){const t=e.getNumberType();return t===r.PhoneNumberType.MOBILE||t===r.PhoneNumberType.FIXED_LINE_OR_MOBILE}}class qe{static forBank(e,t){if(!Ue.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ue.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_BANK);return`${t.countryCode}-BANK-B2C`}static forMobile(e,t,a){if(!r.PhoneNumber.is(e))throw new Error(Ue.ERROR_MESSAGES.INVALID_PHONE_NUMBER);if(!Ue.SUPPORTED_COUNTRY_CODES.includes(e.countryCode))throw new Error(Ue.ERROR_MESSAGES.UNSUPPORTED_COUNTRY_MOBILE);if(!$e.isPhoneEligibleForPayout(e))throw new Error(Ue.ERROR_MESSAGES.INELIGIBLE_FOR_PAYOUT);const o=r.MobileMoneyProviderHelpers.findById(t,e.countryCode);if(!o)throw new Error(Ue.ERROR_MESSAGES.MOBILE_NUMBER_MNO_MISMATCH);return"VODACOM"===o.id?`${a.countryCode}-TIGO-B2C`:`${a.countryCode}-${o.id}-B2C`}}class We{canHandle(e,t,a){return e===exports.PayoutChannel.MOBILE&&le.is(t)&&a.countryCode===t.countryCode&&a.currencyCode===r.Country.fromCode(t.countryCode)?.currencyCode}createInput(e,t){const a=e.receiver,o=$e.processNotes(e.notes),n=a.phoneNumber;return{channel:qe.forMobile(n,a.mnoId,t),msisdn:n.getWithFormat(r.PhoneNumberFormat.INTERNATIONAL_NUMERIC),description:o??Fe.generateDefaultPayoutNarration(a),payeeName:a.name,notes:o,amount:e.amount.numericValue}}}class Ve{canHandle(e,t,a){return e===exports.PayoutChannel.BANK&&pe.is(t)&&a.countryCode===t.countryCode&&a.currencyCode===r.Country.fromCode(t.countryCode)?.currencyCode}createInput(e,t){const r=e.receiver,a=$e.processNotes(e.notes);return{channel:qe.forBank(r,t),msisdn:`${r.bank.bic}:${r.accNo}`,description:a??Fe.generateDefaultPayoutNarration(r),payeeName:r.accName,notes:a,amount:e.amount.numericValue}}}class He{handlers=[new We,new Ve];getPayoutInput(e,t){const r=this.handlers.find(r=>r.canHandle(e.channel,e.receiver,t));if(!r)throw new Error(Ue.ERROR_MESSAGES.NO_HANDLER_FOUND);return r.createInput({receiver:e.receiver,amount:e.amount,notes:e.notes},t)}}const Ge={bank:qe.forBank.bind(qe),mobile:qe.forMobile.bind(qe)},Qe=m().router({getPayouts:{method:"GET",path:"",query:e.z.object({}),responses:{200:e.z.object({results:e.z.array(Ee.PayoutDTO),total:e.z.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:e.z.object({rangeStart:e.z.number(),rangeEnd:e.z.number(),eager:e.z.string(),approvalStatus:Ee.PayoutApprovalStatus,orderByDesc:e.z.string()}),responses:{200:e.z.object({results:e.z.array(Ee.PayoutDTO),total:e.z.number()})}},postPayout:{method:"POST",path:"",body:Ee.PayoutInputDTO,responses:{201:Ee.PayoutDTO,400:n.schema}},approve:{method:"POST",path:"/:id/approve",body:e.z.object({action:e.z.enum(["Approve","Reject"]),notes:e.z.string().optional()}),responses:{201:Ee.PayoutDTO,404:e.z.object({}),409:e.z.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:Ee.PayoutDTO,404:e.z.object({})}}});class Ke extends _{static create(){return new Ke}static fromFilters(e){return(new Ke).applyFilters(e)}static fromUrlParams(e){try{const t=Ee.PayoutURLQueryParams.parse(e),r=Ee.PayoutFilters.parse(t);return Ke.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return Ke.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Ke.fromSearchParams(t)}static from(e){try{return null==e?new Ke:_.is(e)?new Ke(e.options):e instanceof URLSearchParams?Ke.fromSearchParams(e):this.isStringRecord(e)?Ke.fromUrlParams(e):Ke.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a PayoutQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereStatus(e){return this.where("status",e)}whereApprovalStatus(e){return this.where("approvalStatus",e)}whereChannel(e){return this.where("channel",e)}wherePending(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.PENDING)}whereApproved(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.APPROVED)}whereRejected(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.REJECTED)}wherePaid(){return this.whereStatus(exports.PayoutStatus.PAID)}whereFailed(){return this.whereStatus(exports.PayoutStatus.FAILED)}whereAmountBetween(e,t){return e.currencyCode!==t.currencyCode||e.numericValue>t.numericValue?this:this.whereBetween("amount",e.numericValue,t.numericValue)}wherePayee(e){return this.whereContains("payeeName",e)}whereMsisdn(e){return this.whereContains("msisdn",e)}whereProfileId(e){return this.where("profileId",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){if((e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.status&&this.whereStatus(e.status),e.approvalStatus&&this.whereApprovalStatus(e.approvalStatus),e.channel&&this.whereChannel(e.channel),e.payeeName&&this.wherePayee(e.payeeName),e.msisdn&&this.whereMsisdn(e.msisdn),e.profileId&&this.whereProfileId(e.profileId),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.id&&this.where("id",e.id),void 0!==e.minAmount||void 0!==e.maxAmount){const t=void 0!==e.minAmount&&null!==e.minAmount,a=void 0!==e.maxAmount&&null!==e.maxAmount,{currencyCode:o}=e,n=o||"TZS";if(!r.CurrencyHelpers.isCode(n))return console.warn("Amount filter requires a valid currency code"),this;if(t&&a){if(e.minAmount>e.maxAmount)return console.warn(`Invalid amount range: min (${e.minAmount}) > max (${e.maxAmount})`),this;const t=r.Amount.from(e.minAmount,n),a=r.Amount.from(e.maxAmount,n);t&&a&&this.whereAmountBetween(t,a)}else t?this.whereGreaterThanOrEqual("amount",e.minAmount):a&&this.whereLessThanOrEqual("amount",e.maxAmount)}return e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,payeeName:e.payeeName,msisdn:e.msisdn,profileId:e.profileId,id:e.id,partnerReference:e.partnerReference,channel:e.channel,status:this.isValidStatus(e.status)?e.status:void 0,approvalStatus:this.isValidApprovalStatus(e.approvalStatus)?e.approvalStatus:void 0,minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withApprovalStatus(e){const t=this.clone();return e&&t.whereApprovalStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}includeDefaultRelations(){return this.with("[createdBy,actionedBy]")}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.payeeName||e.msisdn||e.profileId||e.id||e.partnerReference||e.channel||e.status||e.approvalStatus||e.minAmount||e.maxAmount||e.search)}describeFilters(e){const t=[],a=this.toFilters(),o=e?.formatDate??(e=>e);if(a.sortBy){const e="asc"===a.sortOrder?"Ascending":"Descending";t.push({label:"Sort",value:`${this.formatSortField(a.sortBy)} (${e})`})}if(a.startDate&&a.endDate?t.push({label:"Date Range",value:`${o(a.startDate)} — ${o(a.endDate)}`}):a.startDate?t.push({label:"From",value:o(a.startDate)}):a.endDate&&t.push({label:"Until",value:o(a.endDate)}),a.status&&t.push({label:"Status",value:a.status}),a.approvalStatus&&t.push({label:"Approval Status",value:a.approvalStatus}),a.channel&&t.push({label:"Channel",value:a.channel}),void 0!==a.minAmount&&void 0!==a.maxAmount){const e=Number(a.minAmount),o=Number(a.maxAmount);if(Number.isFinite(e)&&Number.isFinite(o)){const a=r.Amount.from(e,"TZS"),n=r.Amount.from(o,"TZS");a&&n&&t.push({label:"Amount Range",value:`${a.label} — ${n.label}`})}}else if(void 0!==a.minAmount){const e=Number(a.minAmount);if(Number.isFinite(e)){const a=r.Amount.from(e,"TZS");a&&t.push({label:"Minimum Amount",value:a.label})}}else if(void 0!==a.maxAmount){const e=Number(a.maxAmount);if(Number.isFinite(e)){const a=r.Amount.from(e,"TZS");a&&t.push({label:"Maximum Amount",value:a.label})}}return a.search&&t.push({label:"Search",value:`"${a.search}"`}),a.payeeName&&t.push({label:"Beneficiary Name",value:a.payeeName}),a.msisdn&&t.push({label:"MSISDN",value:a.msisdn}),a.profileId&&t.push({label:"Profile",value:a.profileId}),a.partnerReference&&t.push({label:"Reference",value:a.partnerReference}),t}describeFiltersAsText(){return this.describeFilters().map(e=>`${e.label}: ${e.value}`)}formatSortField(e){return{createdAt:"Date Created",updatedAt:"Date Updated",amount:"Amount",payeeName:"Beneficiary Name",status:"Status"}[e]??e}build(){return super.build()}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"payeeName":case"msisdn":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}return e}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidStatus(e){return Object.values(exports.PayoutStatus).includes(e)}isValidApprovalStatus(e){return Object.values(exports.PayoutApprovalStatus).includes(e)}}const Ze=e=>e.optional().transform(e=>e??void 0),Ye={walletDTO:e.z.object({id:e.z.string().min(1,{message:"Wallet ID is required."}),profileId:e.z.string().min(1,{message:"Profile ID is required."}),accountNo:e.z.string().min(1,{message:"Account number is required."}),accountName:e.z.string().min(1,{message:"Account name is required."}),channel:e.z.string().min(1,{message:"Channel is required."}),countryCode:e.z.string().default("TZ").refine(e=>r.CountryHelpers.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>r.CurrencyHelpers.isCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:e.z.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:e.z.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:e.z.object({id:e.z.string().optional(),profileId:e.z.string().optional(),accountNo:e.z.string().optional(),accountName:e.z.string().optional(),channel:e.z.string().optional(),countryCode:e.z.string().default("TZ").refine(e=>r.ISO2CountryCodesSet.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:e.z.string().default("TZS").refine(e=>{const t=r.Currency.fromCode(e);return void 0!==t&&r.CurrencyCodesSet.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:e.z.object({accountNo:Ze(e.z.string()),debitOrCredit:e.z.string().min(1,"Transaction type is required"),tranRefNo:e.z.string().min(1,"Transaction reference is required"),narration:e.z.string().min(1,"Transaction description is required"),txnDate:e.z.coerce.date({errorMap:()=>({message:"Invalid transaction date format"})}),valueDate:e.z.coerce.date({errorMap:()=>({message:"Invalid value date format"})}),amountCredited:e.z.number().min(0,"Credited amount must be non-negative"),amountDebited:e.z.number().min(0,"Debited amount must be non-negative"),balance:e.z.number(),currencyCode:Ze(e.z.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})},Xe=o.default.object({id:o.default.string(),profileId:o.default.string(),accountNo:o.default.string(),accountName:o.default.string(),channel:o.default.string(),countryCode:o.default.string(),currencyCode:o.default.string(),createdAt:o.default.string(),updatedAt:o.default.string(),version:o.default.string().optional().default("1.0")});class et{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return Ye.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=et.schema.safeParse(e);if(t.success)return new et(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)}validate(){const e=et.schema.safeParse(this.toJSON());return e.success||console.warn("Wallet instance validation failed:",e.error.flatten()),e.success}static from(e){if(e&&"object"==typeof e)return et.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&&r.CountryHelpers.isISO2Code(t._countryCode)&&"string"==typeof t._currencyCode&&r.CurrencyHelpers.isCode(t._currencyCode)&&"string"==typeof t._createdAt&&"string"==typeof t._updatedAt}toJSON(){return{id:this._id,profileId:this._profileId,accountNo:this._accountNo,accountName:this._accountName,channel:this._channel,countryCode:this._countryCode,currencyCode:this._currencyCode,createdAt:this._createdAt,updatedAt:this._updatedAt,version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Xe.safeParse(t);if(!r.success)return void console.error("Invalid WalletJSON:",r.error.flatten());const a=r.data;return et.create(a)}catch(e){return void console.error("Error parsing WalletJSON:",e)}}static isWalletJSON(e){return Xe.safeParse(e).success}}const tt=o.default.object({accountNo:o.default.string().optional(),debitOrCredit:o.default.string(),tranRefNo:o.default.string(),narration:ke,txnDate:o.default.string(),valueDate:o.default.string(),amountCredited:r.AmountJSONSchema,amountDebited:r.AmountJSONSchema,balance:r.AmountJSONSchema,currencyCode:o.default.string(),version:o.default.string().optional().default("2.0")});class rt{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return Ye.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 a=r.Currency.fromCode(e.currencyCode);if(!a)throw new Error(`Currency not found for code: ${e.currencyCode}`);const o=r.Amount.from(e.amountCredited,a.code),n=r.Amount.from(e.amountDebited,a.code),s=r.Amount.from(e.balance,a.code);if(!o||!n||!s)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=o,this._amountDebited=n,this._balance=s}static create(e){const t="string"==typeof e.narration?new Fe(e.narration):e.narration,r={...e,narration:t.text},a=rt.schema.safeParse(r);if(a.success)try{const{narration:e,...r}=a.data;return new rt(r,t)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",a.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}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=rt.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&&Fe.is(t._narration)&&t._txnDate instanceof Date&&t._valueDate instanceof Date&&r.Amount.is(t._amountCredited)&&r.Amount.is(t._amountDebited)&&r.Amount.is(t._balance)&&"string"==typeof t._currencyCode}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return rt.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 from(e){if(e&&"object"==typeof e)try{let t,a,o,n,s=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const n=r.Amount.fromJSON(e.amountCredited),i=r.Amount.fromJSON(e.amountDebited),c=r.Amount.fromJSON(e.balance);if(!n||!i||!c)return void console.error("Failed to deserialize Amount objects from JSON");t=n.numericValue,a=i.numericValue,o=c.numericValue,e.currencyCode||(s=n.currencyCode)}else if(t=Number(e.amountCredited),a=Number(e.amountDebited),o=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(a)||!Number.isFinite(o))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)n=e.narration;else if(Fe.is(e.narration))n=e.narration;else{if(!Fe.isNarrationJSON(e.narration))return void console.error("Invalid narration data");{const t=Fe.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");n=t}}return rt.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:n,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:a,balance:o,currencyCode:s})}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.")}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"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,a=tt.safeParse(t);if(!a.success)return void console.error("Invalid WalletStatementEntryJSON:",a.error.flatten());const o=a.data,n=Fe.fromJSON(o.narration);if(!n)return void console.warn("Failed to deserialize narration");const s=r.Amount.fromJSON(o.amountCredited),i=r.Amount.fromJSON(o.amountDebited),c=r.Amount.fromJSON(o.balance);return s&&i&&c?s.currencyCode!==o.currencyCode||i.currencyCode!==o.currencyCode||c.currencyCode!==o.currencyCode?void console.warn("Currency code mismatch"):rt.create({accountNo:o.accountNo,debitOrCredit:o.debitOrCredit,tranRefNo:o.tranRefNo,narration:n,txnDate:o.txnDate,valueDate:o.valueDate,amountCredited:s.numericValue,amountDebited:i.numericValue,balance:c.numericValue,currencyCode:o.currencyCode}):void console.warn("Failed to deserialize Amount objects")}catch(e){return void console.error("Error parsing WalletStatementEntryJSON:",e)}}static isWalletStatementEntryJSON(e){return tt.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>rt.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing WalletStatementEntry JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}toJson(){return this.toJSON()}static fromJson(e){return rt.fromJSON(e)}static fromJsonArray(e){return rt.fromJSONArray(e)}static toJsonArray(e){return rt.toJSONArray(e)}}const at=m().router({getWallets:{method:"GET",path:"/",query:Ye.walletQuery,responses:{200:e.z.array(et.schema)}},getBalance:{method:"POST",path:"/balance",body:e.z.object({accountNo:e.z.string().optional()}),responses:{201:e.z.object({availableBalance:e.z.number()})}},getStatement:{method:"POST",path:"/statement",summary:"Get Wallet Statement",body:e.z.object({endDate:e.z.date(),startDate:e.z.date(),accountNo:e.z.string().optional()}),responses:{201:e.z.array(rt.schema)}}});class ot extends _{static create(){return new ot}static fromFilters(e){return(new ot).applyFilters(e)}static fromUrlParams(e){try{const t=Ye.walletQuery.parse(e);return ot.fromFilters(t)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return ot.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return ot.fromSearchParams(t)}static from(e){try{return null==e?new ot:_.is(e)?new ot(e.options):e instanceof URLSearchParams?ot.fromSearchParams(e):this.isStringRecord(e)?ot.fromUrlParams(e):ot.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a WalletQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereId(e){return this.where("id",e)}whereProfileId(e){return this.where("profileId",e)}whereAccountNo(e){return this.where("accountNo",e)}whereAccountName(e){return this.whereContains("accountName",e)}whereChannel(e){return this.where("channel",e)}whereCountryCode(e){return this.where("countryCode",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){return e.id&&this.whereId(e.id),e.profileId&&this.whereProfileId(e.profileId),e.accountNo&&this.whereAccountNo(e.accountNo),e.accountName&&this.whereAccountName(e.accountName),e.channel&&this.whereChannel(e.channel),e.countryCode&&this.whereCountryCode(e.countryCode),e.currencyCode&&this.whereCurrencyCode(e.currencyCode),this}toFilters(){const e=this.extractFilterValues();return{id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,currencyCode:e.currencyCode}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withId(e){const t=this.clone();return t.whereId(e),t}withProfileId(e){const t=this.clone();return t.whereProfileId(e),t}withAccountNo(e){const t=this.clone();return t.whereAccountNo(e),t}withCountryCode(e){const t=this.clone();return t.whereCountryCode(e),t}withCurrencyCode(e){const t=this.clone();return t.whereCurrencyCode(e),t}hasFilters(){const e=this.toFilters();return!!(e.id||e.profileId||e.accountNo||e.accountName||e.channel||e.countryCode||e.currencyCode)}getActiveFilters(){const e=[],t=this.toFilters();return t.id&&e.push(`ID: ${t.id}`),t.profileId&&e.push(`Profile: ${t.profileId}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.accountName&&e.push(`Name: ${t.accountName}`),t.channel&&e.push(`Channel: ${t.channel}`),t.countryCode&&e.push(`Country: ${t.countryCode}`),t.currencyCode&&e.push(`Currency: ${t.currencyCode}`),e}build(){return super.build()}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)"eq"===t.operator?e[t.field]=t.value:"likeLower"===t.operator&&"string"==typeof t.value&&(e[t.field]=t.value.replace(/%/g,""));return e}}const nt={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)},st=m().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:B.schema}}});exports.APIError=n,exports.AuthRepository=class extends P{constructor(e){super("auth",W,e)}async logIn(e,t){const r={type:"password",identity:e,password:t},a=await this.client.logIn({body:r});if(400===a.status)throw new n({message:"Invalid email or password",statusCode:400});if(201===a.status){const e=a.body.token,t=new H({token:e}),r=await t.getIdentity(),o=j.from(r);if(!o)throw new n({message:"Failed to construct login credentials",statusCode:502});const i=a.body.profile,c=B.from(i);if(!c)throw new n({message:"Failed to construct user profile",statusCode:502});let u;if(o.access.includes(s.Role.ViewRole))try{const t=new te({token:e});u=await t.getRole(o.roleId)}catch(e){console.warn("Failed to fetch role details:",e)}const d=q.from({logIn:o,companyProfile:c,role:u,token:e});if(!d)throw new n({message:"Failed to construct user session",statusCode:502});return d}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})}async getAccessList(){const e=await this.client.access();if(200===e.status)return e.body;throw new Error(`Failed to get access list. Status: ${e.status}`)}},exports.BANK_NARR_PREFIX=Be,exports.BankBeneficiaryInfo=pe,exports.BankBeneficiaryJSONSchema=ie,exports.BaseRepository=P,exports.Beneficiary=fe,exports.BeneficiaryDTOSchemas=ne,exports.BeneficiaryError=ue,exports.BeneficiaryInfo=me,exports.BeneficiaryInfoJSONSchema=ce,exports.BeneficiaryJSONSchema=he,exports.BeneficiaryRepository=class extends P{constructor(e){super("contact",Ne,e)}async create(e){const t=(new be).resolve(e),r=await this.client.createBeneficiary({body:t}),a=this.handleResponse(r,201);return fe.create(a)}async edit(e,t){const r=(new be).resolve(t),a=await this.client.editBeneficiary({params:{id:e},body:r}),o=this.handleResponse(a,200);return fe.create(o)}async remove(e){const t=await this.client.deleteBeneficiary({params:{id:e}});this.handleResponse(t,200)}async getAll(){const e=await this.client.getBeneficiaries({query:{orderByDesc:"createdAt"}}),t=this.handleResponse(e,200);return fe.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return fe.create(r)}},exports.CompanyMembership=U,exports.CompanyMembershipJSONSchema=L,exports.ECOBANK_PREFIX=De,exports.IdentityRepository=H,exports.LEGACY_BANK_NARR_PREFIX=Je,exports.LEGACY_MOBILE_NARR_PREFIX=je,exports.LogIn=j,exports.LogInJSONSchema=M,exports.LogInSchemas=J,exports.MOBILE_NARR_PREFIX=Me,exports.MobileBeneficiaryInfo=le,exports.MobileBeneficiaryJSONSchema=se,exports.NARR_V2_PREFIX=Re,exports.Narration=Fe,exports.NarrationJSONSchema=ke,exports.Pagination=T,exports.PaginationParamsSchema=E,exports.PaginationSchema=x,exports.Payout=Te,exports.PayoutDTOSchemas=Ee,exports.PayoutInputFactory=He,exports.PayoutJSONSchema=xe,exports.PayoutQuery=Ke,exports.PayoutRepository=class extends P{constructor(e){super("payout",Qe,e)}async getPayouts(e){try{const t=Ke.from(e),r=t.build(),a=await this.client.getPayouts({query:r}),o=this.handleResponse(a,200),n=t.toFilters(),s=new T(n.page??1,n.limit??10,o.total);return{results:Te.createMany(o.results),pagination:s}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getAllPayouts(e){try{const t=Ke.from(e).build();delete t.rangeStart,delete t.rangeEnd;const r=await this.client.getPayouts({query:t}),a=this.handleResponse(r,200);return Te.createMany(a)}catch(e){throw console.log("error: ",e),new Error(`Failed to fetch all payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=Ke.fromRequest(e);return this.getPayouts(t)}async pay(e){const{wallet:t,channel:a,receiver:o,amount:s,notes:i}=e,c=r.TemboCoverage.getTransactionLimits({countryCode:t.countryCode,currencyCode:s.currencyCode,direction:r.TransactionDirection.PAYOUT,channelType:a===exports.PayoutChannel.BANK?r.ChannelType.BANK:r.ChannelType.MOBILE_MONEY});if(!c)throw new n({statusCode:400,message:`Payout limits are not configured for ${t.countryCode} ${s.currencyCode} ${a} payouts`});const{min:u,max:d}=c;if(s.lessThan(u)||s.greaterThan(d))throw new n({statusCode:400,message:`Please make sure the amount is between ${u.label} - ${d.label}`});const l=(new He).getPayoutInput({channel:a,receiver:o,amount:s,notes:i},t),p=await this.client.postPayout({body:l});if(201===p.status)return Te.create(p.body);if(400===p.status)throw new n(p.body);throw n.unknown()}async approve(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Approve",notes:e.notes}});if(201===t.status)return Te.create(t.body);if(404===t.status)throw new n({message:"Payout not found",statusCode:404});if(409===t.status)throw new n({message:"Payout already approved",statusCode:409});throw n.unknown()}async reject(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Reject",notes:e.notes}});if(201===t.status)return Te.create(t.body);if(404===t.status)throw new n({message:"Payout not found",statusCode:404});if(409===t.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 Te.create(t.body);if(404===t.status)throw new n({message:"Payout not found",statusCode:404});throw n.unknown()}async count(e){const t=Ke.from(e).build(),r=await this.client.getPayouts({query:t});return this.handleResponse(r,200).total}async exists(e){return await this.count(e)>0}},exports.PermissionError=i,exports.Permissions=s,exports.Profile=B,exports.ProfileDTOSchemas=D,exports.ProfileJSONSchema=R,exports.ProfileRepository=class extends P{constructor(e){super("profile",st,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=B.from(e.body);if(t)return t;throw new Error("Invalid profile data received from server")}throw new Error(`Failed to get current profile. Status: ${e.status}`)}},exports.QUERY_BUILDER_TYPE=z,exports.QueryBuilder=_,exports.Role=F,exports.RoleJSONSchema=k,exports.TeamManagementDTOSchemas=Z,exports.TeamMember=ee,exports.TeamMemberJSONSchema=X,exports.TeamMemberRepository=te,exports.User=q,exports.UserJSONSchema=$,exports.ValidatedBeneficiaryInputFactory=be,exports.Wallet=et,exports.WalletDTOSchemas=Ye,exports.WalletJSONSchema=Xe,exports.WalletRepository=class extends P{constructor(e){super("wallet",at,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 a=t.body.availableBalance,o=r.Amount.from(a,e.wallet.currencyCode);if(o)return o}}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 a=t[0],o=await this.client.getBalance({body:{accountNo:e.accountNo}});if(201===o.status){const e=o.body.availableBalance,t=r.Amount.from(e,a.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=ot.from(e).build(),r=await this.client.getWallets({query:t});if(200===r.status){const e=r.body;try{return e.map(e=>{const t=et.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: ${r.status}`)}async getByID(e){const t=ot.create().whereId(e),r=await this.getWallets(t);return r.length>0?r[0]:void 0}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),a=new Date(t.getFullYear(),t.getMonth()+1,0),o=e.range??{startDate:r,endDate:a};let n,s;if(e.wallet)n=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}`);n=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:n.currencyCode})).reduce((e,t)=>{const r=rt.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}`)}async exists(e){return(await this.getWallets(e)).length>0}async count(e){return(await this.getWallets(e)).length}},exports.WalletStatementEntry=rt,exports.WalletStatementEntryJSONSchema=tt,exports.WalletUtils=nt,exports.contract=Ne,exports.createPaginatedResponse=function(e,t,r,a){return{results:e,pagination:new T(t,r,a)}},exports.createPaginatedResponseSchema=function(t){return e.z.object({results:e.z.array(t),pagination:x})},exports.createPayoutChannelCode=Ge,exports.emptyPaginatedResponse=function(e=1,t=10){return{results:[],pagination:new T(e,t,0)}},exports.isError=function(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message},exports.setGlobalTokenGetter=e=>{O=e};
|
|
2
|
+
//# sourceMappingURL=index.cjs.js.map
|