@cowris/paymentdb-client 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ MIT License
2
+
3
+ Cowris Payment Database Server
4
+
5
+ MIT License
6
+
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in all
16
+ copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,253 @@
1
+ # @cowris/paymentdb-client
2
+
3
+ A Prisma Client package for the Cowris PostgreSQL PaymentDB.
4
+
5
+ ## Description
6
+
7
+ This package provides a centralized Prisma client for the Cowris PostgreSQL PaymentDB. It simplifies database access and ensures consistency by sharing the Prisma configuration and client instance. It offers a simple interface to interact with the Payment database, allowing you to perform CRUD operations on payment and transaction data and related tables.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @cowris/paymentdb-client
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ### Import the Prisma Client:
18
+
19
+ **JavaScript**
20
+ ```javascript
21
+ const prisma = require('@cowris/paymentdb-client');
22
+
23
+ async function main() {
24
+ // Get all transactions
25
+ const allTransactions = await prisma.transaction.findMany();
26
+ console.log(allTransactions);
27
+
28
+ // Create a new payment account
29
+ const newAccount = await prisma.paymentAccount.create({
30
+ data: {
31
+ account_number: "1234567890",
32
+ email: "user@example.com",
33
+ currency_id: "usd-currency-id",
34
+ wallet_id: "wallet-uuid"
35
+ }
36
+ });
37
+
38
+ // Get account with transactions
39
+ const accountWithTransactions = await prisma.paymentAccount.findUnique({
40
+ where: { id: "account-id" },
41
+ include: {
42
+ transactions: true,
43
+ currency: true,
44
+ managed_wallets: true
45
+ }
46
+ });
47
+ }
48
+
49
+ main()
50
+ .catch((e) => {
51
+ throw e;
52
+ })
53
+ .finally(async () => {
54
+ await prisma.$disconnect();
55
+ });
56
+ ```
57
+
58
+ ## Ensure Database Connection
59
+
60
+ Make sure the microservice has the `PAYMENT_DATABASE_URL` environment variable set, pointing to the PostgreSQL database.
61
+
62
+ Example:
63
+ ```bash
64
+ PAYMENT_DATABASE_URL="postgresql://username:password@localhost:5432/paymentdb"
65
+ ```
66
+
67
+ ## Setup the database in microservice
68
+
69
+ Add this under scripts in package.json in the microservice:
70
+
71
+ ```json
72
+ {
73
+ "scripts": {
74
+ "setup-prisma:paymentdb": "node node_modules/@cowris/services-paymentdb/scripts/migrate.js || echo 'Migration failed. Please install the cowris paymentdb client. Run `npm install @cowris/services-paymentdb` to install it.'"
75
+ }
76
+ }
77
+ ```
78
+
79
+ ## File Structure
80
+
81
+ ```
82
+ @cowris/services-paymentdb/
83
+ ├── prisma/
84
+ │ ├── migrations/
85
+ │ ├── schema/
86
+ │ │ ├── account.prisma
87
+ │ │ ├── currency.prisma
88
+ │ │ ├── funding.prisma
89
+ │ │ ├── globalPaymentProvider.prisma
90
+ │ │ ├── managedWallet.prisma
91
+ │ │ ├── otp.prisma
92
+ │ │ ├── reversal.prisma
93
+ │ │ ├── transaction.prisma
94
+ │ │ ├── transfer.prisma
95
+ │ │ ├── withdrawal.prisma
96
+ │ │ └── schema.prisma // Main schema file
97
+ │ └── .env
98
+ ├── scripts/
99
+ │ └── migrate.js
100
+ ├── node_modules/
101
+ ├── package.json
102
+ ├── package-lock.json
103
+ └── index.js
104
+ ```
105
+
106
+ - `prisma/schema/`: Contains individual Prisma model files for different payment entities and the main schema.prisma file that combines them.
107
+ - `prisma/migrations/`: Stores Prisma migration files (if used).
108
+ - `prisma/.env`: Holds the database connection string (PAYMENT_DATABASE_URL).
109
+ - `scripts/migrate.js`: Migration script for database setup.
110
+ - `index.js`: Exports the Prisma client instance.
111
+
112
+ ## Schema Definition
113
+
114
+ The Prisma schema is defined in the `prisma/schema` directory. Each model has its own `.prisma` file, and `schema.prisma` imports and combines them.
115
+
116
+ ### Key Models
117
+
118
+ #### PaymentAccount
119
+ ```prisma
120
+ model PaymentAccount {
121
+ id String @id @default(uuid())
122
+ account_number String? @unique
123
+ email String?
124
+ currency_id String
125
+ currency Currency @relation(fields: [currency_id], references: [id])
126
+ wallet_id String @unique
127
+ managed_wallets ManagedWallet[]
128
+ transactions Transaction[]
129
+ }
130
+ ```
131
+
132
+ #### Transaction
133
+ ```prisma
134
+ model Transaction {
135
+ id String @id @unique @default(uuid())
136
+ account_id String
137
+ type String // funding, withdrawal, transfer, reversal
138
+ status String // initiated, pending, success, failed
139
+ metadata Json?
140
+ provider_id String?
141
+ reference_id String?
142
+ created_at DateTime @default(now())
143
+
144
+ account PaymentAccount @relation(fields: [account_id], references: [id])
145
+ // ... other relations
146
+ }
147
+ ```
148
+
149
+ ### Available Models
150
+
151
+ - **PaymentAccount**: Core account information with wallet associations
152
+ - **Transaction**: All payment transactions (funding, withdrawal, transfer, reversal)
153
+ - **Currency**: Supported currencies for payments
154
+ - **ManagedWallet**: Wallet management information
155
+ - **GlobalPaymentProvider**: Payment provider configurations
156
+ - **Funding**: Funding transaction details
157
+ - **Withdrawal**: Withdrawal transaction details
158
+ - **Transfer**: Transfer transaction details
159
+ - **Reversal**: Transaction reversal details
160
+ - **OTP**: One-time password management
161
+
162
+ ## Common Operations
163
+
164
+ ### Creating a Transaction
165
+
166
+ ```javascript
167
+ const transaction = await prisma.transaction.create({
168
+ data: {
169
+ account_id: "account-uuid",
170
+ type: "funding",
171
+ status: "initiated",
172
+ metadata: {
173
+ amount: 1000,
174
+ description: "Account funding"
175
+ },
176
+ provider_id: "provider-uuid"
177
+ }
178
+ });
179
+ ```
180
+
181
+ ### Querying Account Balance
182
+
183
+ ```javascript
184
+ const accountTransactions = await prisma.transaction.findMany({
185
+ where: {
186
+ account_id: "account-uuid",
187
+ status: "success"
188
+ },
189
+ include: {
190
+ funding_information: true,
191
+ withdrawal_information: true
192
+ }
193
+ });
194
+ ```
195
+
196
+ ### Managing Currencies
197
+
198
+ ```javascript
199
+ const supportedCurrencies = await prisma.currency.findMany({
200
+ where: {
201
+ is_active: true
202
+ }
203
+ });
204
+ ```
205
+
206
+ ## Updating the Schema
207
+
208
+ 1. **Modify Model Files:**
209
+ Make changes to the relevant `.prisma` files in the `prisma/schema` directory.
210
+
211
+ 2. **Generate Prisma Client:**
212
+ Run the following command in the package's root directory:
213
+ ```bash
214
+ npx prisma generate
215
+ ```
216
+
217
+ 3. **Publish a New Version:**
218
+ - Update the package version in `package.json`.
219
+ - Publish the updated package to your npm registry:
220
+ ```bash
221
+ npm publish --access public
222
+ ```
223
+
224
+ 4. **Update in Microservices:**
225
+ Update the package in each microservice:
226
+ ```bash
227
+ npm update @cowris/services-paymentdb
228
+ ```
229
+
230
+ ## Environment Variables
231
+
232
+ | Variable | Description | Required |
233
+ |----------|-------------|----------|
234
+ | `PAYMENT_DATABASE_URL` | PostgreSQL connection string for payment database | Yes |
235
+
236
+ ## Security Considerations
237
+
238
+ - **Database Credentials**: Do not hardcode database credentials. Use environment variables or secure credential management systems.
239
+ - **Transaction Security**: Ensure proper validation and authorization for all payment operations.
240
+ - **Data Encryption**: Sensitive payment data should be encrypted at rest and in transit.
241
+ - **Access Control**: Implement proper access controls for payment operations.
242
+
243
+ ## Contributing
244
+
245
+ Contributions are welcome. Please follow the standard pull request process and ensure all tests pass before submitting.
246
+
247
+ ## License
248
+
249
+ ISC License
250
+
251
+ ## Support
252
+
253
+ For issues and questions, please refer to the [GitHub repository](https://github.com/Cowristech/services-paymentdb).
package/index.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { PrismaClient } from './prisma/generated/paymentdb';
2
+
3
+
4
+ declare module '@cowris/paymentdb-client' {
5
+ export const prisma: PrismaClient;
6
+ }
package/index.js ADDED
@@ -0,0 +1,9 @@
1
+ const { PrismaClient } = require('./prisma/generated/paymentdb');
2
+
3
+ const prisma = new PrismaClient({
4
+ log: ['error', 'query', 'info', 'warn'],
5
+ });
6
+
7
+ module.exports = {
8
+ prisma,
9
+ };
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@cowris/paymentdb-client",
3
+ "version": "1.0.0",
4
+ "description": "This is a Prisma Client package for the Cowris PaymentDB. It provides a simple interface to interact with the Payment database, allowing you to perform CRUD operations on payment and transaction data and related tables.",
5
+ "main": "index.js",
6
+ "private": false,
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "scripts": {
11
+ "test": "echo \"Error: no test specified\" && exit 1"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/Cowristech/services-paymentdb.git"
16
+ },
17
+ "keywords": [],
18
+ "author": "",
19
+ "license": "ISC",
20
+ "type": "commonjs",
21
+ "bugs": {
22
+ "url": "https://github.com/Cowristech/services-paymentdb/issues"
23
+ },
24
+ "homepage": "https://github.com/Cowristech/services-paymentdb#readme",
25
+ "dependencies": {
26
+ "@prisma/client": "^6.6.0",
27
+ "dotenv": "^16.4.7",
28
+ "uuid": "^11.1.0"
29
+ },
30
+ "devDependencies": {
31
+ "prisma": "^6.6.0"
32
+ },
33
+ "peerDependencies": {
34
+ "@prisma/client": "^6.6.0",
35
+ "prisma": "^6.6.0"
36
+ },
37
+ "files": [
38
+ "index.js",
39
+ "index.d.ts",
40
+ "prisma",
41
+ "scripts"
42
+ ],
43
+ "prisma": {
44
+ "schema": "./prisma/schema"
45
+ }
46
+ }
@@ -0,0 +1,13 @@
1
+ model PaymentAccount {
2
+ id String @id @default(uuid())
3
+ account_number String? @unique
4
+ email String?
5
+ currency_id String
6
+ currency Currency @relation(fields: [currency_id], references: [id])
7
+ wallet_id String @unique
8
+ managed_wallets ManagedWallet[]
9
+ transactions Transaction[]
10
+
11
+ @@index([wallet_id], name: "wallet_id_index")
12
+ @@index([account_number], name: "wallet_account_number")
13
+ }
@@ -0,0 +1,12 @@
1
+ model Currency {
2
+ id String @id @default(uuid())
3
+ name String @unique
4
+ symbol String
5
+ code String?
6
+ country String
7
+ created_at DateTime @default(now())
8
+ updated_at DateTime @updatedAt
9
+
10
+ payment_providers GlobalPaymentProvider[]
11
+ accounts PaymentAccount[]
12
+ }
@@ -0,0 +1,24 @@
1
+ model SenderAccountInformation {
2
+ id String @id @default(uuid())
3
+ account_firstname String? @default("")
4
+ account_lastname String? @default("")
5
+ account_number String?
6
+ account_email String?
7
+ account_bank_name String?
8
+
9
+ funding Funding?
10
+ }
11
+
12
+ model Funding {
13
+ id String @id @default(uuid())
14
+ transaction_id String @unique
15
+ account_id String
16
+ status String
17
+ amount String
18
+ source_currency_id String?
19
+ destination_currency_id String
20
+ sender_account_information_id String? @unique
21
+
22
+ transaction Transaction?
23
+ sender_account_information SenderAccountInformation? @relation(fields: [sender_account_information_id], references: [id])
24
+ }
@@ -0,0 +1,9 @@
1
+ model GlobalPaymentProvider {
2
+ id String @id @default(uuid())
3
+ name String
4
+ supported_currencies Currency[]
5
+ created_at DateTime @default(now())
6
+ updated_at DateTime @updatedAt
7
+
8
+ transactions Transaction[]
9
+ }
@@ -0,0 +1,17 @@
1
+ model ManagedWallet {
2
+ id String @id @default(uuid())
3
+ account_id String
4
+ customer_name String?
5
+ wallet_identifier String?
6
+ account_number String?
7
+ email String?
8
+ balance String @default("0.00")
9
+ currency_id String
10
+ global_payment_provider_id String
11
+ type String
12
+ // Type can be either "static", "dynamic", "virtual-static", "virtual-dynamic"
13
+
14
+ created_at DateTime @default(now())
15
+ updated_at DateTime @updatedAt
16
+ payment_account PaymentAccount @relation(fields: [account_id], references: [id])
17
+ }
@@ -0,0 +1,11 @@
1
+ model Otp {
2
+ id String @id @default(uuid())
3
+ email String
4
+ otp String
5
+ created_at DateTime @default(now())
6
+ updated_at DateTime @default(now()) @updatedAt
7
+ expires_at DateTime
8
+
9
+ @@index([email], name: "otp_email_index")
10
+ @@index([otp], name: "otp_str_index")
11
+ }
@@ -0,0 +1,12 @@
1
+ model Reversal {
2
+ id String @id @default(uuid())
3
+ transaction_id String @unique
4
+ account_id String
5
+ source_currency_id String?
6
+ destination_currency_id String
7
+
8
+ amount String
9
+ status String
10
+
11
+ transaction Transaction?
12
+ }
@@ -0,0 +1,9 @@
1
+ generator client {
2
+ provider = "prisma-client-js"
3
+ output = "../generated/paymentdb"
4
+ }
5
+
6
+ datasource db {
7
+ provider = "postgresql"
8
+ url = env("PAYMENT_DATABASE_URL")
9
+ }
@@ -0,0 +1,27 @@
1
+ model Transaction {
2
+ id String @id @unique @default(uuid())
3
+ account_id String
4
+ funding_id String? @unique
5
+ withdrawal_id String? @unique
6
+ reversal_id String? @unique
7
+ transfer_id String? @unique
8
+
9
+ // Type can be funding, withdrawal, transfer, reversal
10
+ type String
11
+
12
+ // Status can be initiated, pending, success, failed
13
+ status String
14
+ metadata Json?
15
+ provider_id String?
16
+ reference_id String?
17
+ created_at DateTime @default(now())
18
+ upadated_at DateTime @default(now())
19
+
20
+ provider GlobalPaymentProvider? @relation(fields: [provider_id], references: [id])
21
+ account PaymentAccount @relation(fields: [account_id], references: [id])
22
+
23
+ transfer_infomation Transfer? @relation(fields: [transfer_id], references: [id])
24
+ funding_information Funding? @relation(fields: [funding_id], references: [id])
25
+ withdrawal_information Withdrawal? @relation(fields: [withdrawal_id], references: [id])
26
+ reversal_information Reversal? @relation(fields: [reversal_id], references: [id])
27
+ }
@@ -0,0 +1,25 @@
1
+ model TransferDestinationAccountDetails {
2
+ id String @id @default(uuid())
3
+ account_firstname String @default("")
4
+ account_lastname String @default("")
5
+ account_number String?
6
+ account_email String?
7
+ account_bank_name String?
8
+ Transfer Transfer?
9
+ }
10
+
11
+ model Transfer {
12
+ id String @id @default(uuid())
13
+ transaction_id String @unique
14
+ from_account_id String
15
+ to_account_id String?
16
+ destination_account_details_id String? @unique
17
+ source_currency_id String @unique
18
+ destination_currency_id String @unique
19
+ amount_in_source_currency String
20
+ amount_in_destination_currency String
21
+ status String
22
+
23
+ transaction Transaction?
24
+ destination_account_details TransferDestinationAccountDetails? @relation(fields: [destination_account_details_id], references: [id])
25
+ }
@@ -0,0 +1,25 @@
1
+ model WithdrawalDestinationAccountDetails {
2
+ id String @id @default(uuid())
3
+ account_firstname String @default("")
4
+ account_lastname String @default("")
5
+ account_number String?
6
+ account_email String?
7
+ account_bank_name String?
8
+ withdrawal Withdrawal?
9
+ }
10
+
11
+ model Withdrawal {
12
+ id String @id @default(uuid())
13
+ transaction_id String @unique
14
+ from_account_id String
15
+ amount_in_source_currency String
16
+ status String
17
+
18
+ destination_account_details_id String? @unique
19
+ source_currency_id String @unique
20
+ destination_currency_id String @unique
21
+ amount_in_destination_currency String
22
+
23
+ transaction Transaction?
24
+ destination_account_details WithdrawalDestinationAccountDetails? @relation(fields: [destination_account_details_id], references: [id])
25
+ }
@@ -0,0 +1,54 @@
1
+ require("dotenv").config();
2
+ const { execSync } = require("child_process");
3
+ const path = require("path");
4
+ const fs = require("fs");
5
+
6
+ // Get the absolute path to the schema inside node_modules
7
+ const packageRoot = path.resolve(__dirname, "..");
8
+ const schemaPath = path.join(packageRoot, "prisma/schema");
9
+
10
+ // Ensure the schema file exists
11
+ if (!fs.existsSync(schemaPath)) {
12
+ console.error(`❌ Prisma schema not found at expected path: ${schemaPath}`);
13
+ process.exit(1);
14
+ }
15
+
16
+ // Load the environment variables from the consuming microservice
17
+ require("dotenv").config({ path: path.resolve(process.cwd(), ".env") });
18
+
19
+ const DB_URL = process.env.PAYMENT_DATABASE_URL || "";
20
+ const environment = process.env.NODE_ENV || "development";
21
+
22
+ if (!DB_URL.includes("postgresql://") && !DB_URL.includes("postgresqls://")) {
23
+ console.error("❌ Invalid database URL. Provide a valid PostgreSQL connection string.");
24
+ process.exit(1);
25
+ }
26
+
27
+ const IS_PROD_DB = DB_URL.includes("prod") || environment === "production";
28
+ const IS_TEST_DB = DB_URL.includes("test") || environment === "test";
29
+ const IS_DEV_DB = DB_URL.includes("dev") || environment === "development";
30
+
31
+ if (IS_PROD_DB) {
32
+ console.error("❌ Migrations are not allowed in production databases.");
33
+ process.exit(1);
34
+ }
35
+
36
+ if (!IS_TEST_DB && !IS_DEV_DB) {
37
+ console.log("⚠️ Migrations are disabled for production databases.");
38
+ process.exit(0);
39
+ }
40
+
41
+ console.log("🚀 Running Prisma migrations using the package schema...");
42
+
43
+ try {
44
+ // Generate Prisma client using the correct schema path
45
+ execSync(`npx prisma generate --schema=${schemaPath}`, { stdio: "inherit" });
46
+
47
+ // Run migrations
48
+ execSync(`npx prisma migrate deploy --schema=${schemaPath}`, { stdio: "inherit" });
49
+
50
+ console.log("✅ Cowris PaymentDB Migrations applied successfully!");
51
+ } catch (error) {
52
+ console.error("❌ Migration failed:", error.message);
53
+ process.exit(1);
54
+ }