Compare commits

..

108 Commits

Author SHA1 Message Date
Ahmed Bouhuolia
3f2ab6e8f0 feat(webapp): add socket to vite server proxy 2026-01-08 22:43:42 +02:00
Ahmed Bouhuolia
f0fae7d148 Merge pull request #894 from bigcapitalhq/fix-refund-credit-notes
fix(server): refund credit note gl entries
2026-01-08 00:29:47 +02:00
Ahmed Bouhuolia
e063597a80 fix(server): refund credit note gl entries 2026-01-08 00:27:43 +02:00
Ahmed Bouhuolia
9b3f6b22d1 Merge pull request #893 from bigcapitalhq/bugs-bashing-3
fix: bugs bashing
2026-01-04 01:27:19 +02:00
Ahmed Bouhuolia
0475ce136a fix: bugs bashing
- Added English translations for customer types in `customer.json`.
- Updated `Model.ts` to improve deletion logic by filtering dependent relations.
- Introduced `BillPaymentBillSyncSubscriber` to handle bill payment events.
- Enhanced `CreateBillPaymentService` and `EditBillPaymentService` to fetch entries after insertion/updating.
- Updated `SaleInvoiceCostGLEntries` to include item entry details in GL entries.
- Refactored various components in the webapp for consistency in naming conventions.
2026-01-04 01:24:10 +02:00
Ahmed Bouhuolia
987ad992a4 Merge pull request #892 from bigcapitalhq/darkmode-ui-bugs
fix: darkmode ui bugs
2026-01-03 18:26:21 +02:00
Ahmed Bouhuolia
ee92c2815b fix: darkmode ui bugs 2026-01-03 18:24:33 +02:00
Ahmed Bouhuolia
5767f1f603 Merge pull request #890 from bigcapitalhq/named-imports-hocs
fix: account transactions don't show up
2026-01-01 22:16:02 +02:00
Ahmed Bouhuolia
885d8014c2 fix: account transactions don't show up 2026-01-01 22:13:47 +02:00
Ahmed Bouhuolia
3ffab896ed Merge pull request #889 from bigcapitalhq/revert-888-named-imports-hocs
Revert "fix: account transactions don't show up"
2026-01-01 22:13:31 +02:00
Ahmed Bouhuolia
92a5086f1f Revert "fix: account transactions don't show up" 2026-01-01 22:13:08 +02:00
Ahmed Bouhuolia
1bf9038ddc Merge pull request #888 from bigcapitalhq/named-imports-hocs
fix: account transactions don't show up
2026-01-01 22:11:56 +02:00
Ahmed Bouhuolia
2736b76ced fix: account transactions don't show up 2026-01-01 22:09:51 +02:00
Ahmed Bouhuolia
9e921b074f Merge pull request #887 from bigcapitalhq/named-imports-hocs
refactor: HOCs named imports
2026-01-01 22:00:58 +02:00
Ahmed Bouhuolia
0f377e19f3 refactor: HOCs named imports 2026-01-01 21:58:42 +02:00
Ahmed Bouhuolia
5d872798ff Merge pull request #886 from bigcapitalhq/fix-credit-note-print
fix: credit note printing
2026-01-01 17:21:36 +02:00
Ahmed Bouhuolia
0ef78a19fe fix: credit note printing 2026-01-01 17:19:06 +02:00
Ahmed Bouhuolia
70b0a4833c Merge pull request #885 from bigcapitalhq/refund-credit-notes
fix: refund credit notes
2026-01-01 17:05:36 +02:00
Ahmed Bouhuolia
ead4fc9b97 fix: refund credit notes 2026-01-01 17:03:48 +02:00
Ahmed Bouhuolia
a91a7c612f Merge pull request #882 from bigcapitalhq/bugs-bashing2
Bug fixes, refactoring, and improvements
2025-12-31 01:01:08 +02:00
Ahmed Bouhuolia
339289be9f refactor(export): move PDF table template to shared package 2025-12-29 23:54:43 +02:00
Ahmed Bouhuolia
350d229e98 feat(transactions-locking): enable settings schema and add dark mode support 2025-12-29 23:35:34 +02:00
Ahmed Bouhuolia
8152a16fd5 Merge pull request #881 from bigcapitalhq/bugs-bashing
bugs bashing
2025-12-29 22:08:56 +02:00
Ahmed Bouhuolia
00aad6e35c wip 2025-12-29 22:06:49 +02:00
Ahmed Bouhuolia
30d8fdb4c0 fix: running compute item cost processor 2025-12-28 12:30:06 +02:00
Ahmed Bouhuolia
872fc661ce bugs bashing 2025-12-28 12:01:24 +02:00
Ahmed Bouhuolia
054cd1fae4 Merge pull request #880 from bigcapitalhq/fix-dark-mode-bank-transaction-drawer
fix: darkmode bank transaction drawer
2025-12-23 20:00:50 +02:00
Ahmed Bouhuolia
7cb169bce9 fix: darkmode bank transaction drawer 2025-12-23 19:57:31 +02:00
Ahmed Bouhuolia
f2663c4af3 Merge pull request #879 from bigcapitalhq/refactor-bound-formik-fields
refactor(webapp): bound Formik fields
2025-12-22 23:28:17 +02:00
Ahmed Bouhuolia
6fea7779da refactor(webapp): bound Formik fields 2025-12-22 23:25:43 +02:00
Ahmed Bouhuolia
c00af18327 Merge pull request #878 from bigcapitalhq/fix-match-bank-transactions
fix: match uncategorized bank transactions
2025-12-22 23:06:36 +02:00
Ahmed Bouhuolia
37f0f4e227 fix: match uncategorized bank transactions 2025-12-22 23:02:08 +02:00
Ahmed Bouhuolia
8662c5899e Merge pull request #877 from bigcapitalhq/fix-import-bank-transactions
fix: import bank transactions
2025-12-22 22:52:34 +02:00
Ahmed Bouhuolia
a9a7cd8617 fix: import bank transactions 2025-12-22 22:49:58 +02:00
Ahmed Bouhuolia
e50fc3b523 Merge pull request #876 from bigcapitalhq/refactor-date-input
refactor: date input field
2025-12-21 23:39:09 +02:00
Ahmed Bouhuolia
b294a72a26 refactor: date input field 2025-12-21 23:34:11 +02:00
Ahmed Bouhuolia
62ae49941b Merge pull request #875 from bigcapitalhq/fix-accounts-suggest-field
fix: accounts suggest field
2025-12-21 16:15:39 +02:00
Ahmed Bouhuolia
31f5cbf335 fix: accounts suggest field 2025-12-21 16:11:01 +02:00
Ahmed Bouhuolia
b22328cff9 Merge pull request #874 from bigcapitalhq/feature/20251218134811
fix: import module bugs
2025-12-18 21:25:34 +02:00
Ahmed Bouhuolia
58f609353c fix: import bugs 2025-12-18 21:21:54 +02:00
Ahmed Bouhuolia
8a2a8eed3b fix: import rows aggregator 2025-12-18 20:44:05 +02:00
Ahmed Bouhuolia
636d206b0e fix: bugs sprint 2025-12-18 13:48:12 +02:00
Ahmed Bouhuolia
63922c391a fix: formatted money attributes 2025-12-14 16:51:06 +02:00
Ahmed Bouhuolia
6ecfe1ff12 fix: remove the auth body background 2025-12-14 14:30:25 +02:00
Ahmed Bouhuolia
17651e0768 Merge pull request #871 from bigcapitalhq/fix-payment-link-base-url
fix: generated payment link base url
2025-12-14 13:29:09 +02:00
Ahmed Bouhuolia
151b623771 fix: generated payment link base url 2025-12-14 13:26:34 +02:00
Ahmed Bouhuolia
2d4459c2f9 fix: payment portal page 2025-12-14 13:06:44 +02:00
Ahmed Bouhuolia
3cbdc3ec96 Merge pull request #870 from bigcapitalhq/report-pdf-template
fix: reports pdf template
2025-12-12 23:42:02 +02:00
Ahmed Bouhuolia
3cfb5cdde8 fix: reports pdf template 2025-12-12 23:38:48 +02:00
Ahmed Bouhuolia
736f2c4109 Merge pull request #869 from bigcapitalhq/fix-passing-number-format-to-reports
fix: passing number format to reports
2025-12-11 00:25:57 +02:00
Ahmed Bouhuolia
2e21437056 fix: update pnpm-lock.yaml 2025-12-11 00:23:50 +02:00
Ahmed Bouhuolia
340b78d968 fix: passing number format to reports 2025-12-11 00:19:55 +02:00
Ahmed Bouhuolia
d006362be2 fix: transaction locking handling 2025-12-05 23:47:29 +02:00
Ahmed Bouhuolia
bc21dcb37e fix(webapp): add api key button 2025-12-05 15:14:31 +02:00
Ahmed Bouhuolia
578b0deb3e fix: sending mail jobs (#868) 2025-12-05 00:09:11 +02:00
Ahmed Bouhuolia
c3dc26a1e4 fix: sending mail jobs 2025-12-05 00:07:26 +02:00
Ahmed Bouhuolia
32d74b0413 feat: onboarding pages darkmode (#867) 2025-12-03 16:04:46 +02:00
allcontributors[bot]
71b1206f8a docs: add Daniel15 as a contributor for bug, and code (#865)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2025-12-02 01:42:54 +02:00
Ahmed Bouhuolia
cb1bcaae77 Merge pull request #864 from Daniel15/patch-3
fix: Stripe integration
2025-12-02 01:41:04 +02:00
Ahmed Bouhuolia
eb51646035 fix: stripe payment webhooks 2025-12-02 01:26:58 +02:00
Ahmed Bouhuolia
8f54754aba feat: add stripe payment webhooks controller 2025-12-01 13:24:19 +02:00
Daniel Lo Nigro
0f446f90ca Change stripe_checkout_session to POST 2025-11-30 16:01:04 -08:00
Daniel Lo Nigro
7cb67b257b Cast payment_integration_id to number 2025-11-30 15:59:29 -08:00
Daniel Lo Nigro
0a1fffb3a4 Correctly register PaymentIntegration as tenant model 2025-11-30 15:52:07 -08:00
Daniel Lo Nigro
b756f090ed Fix Stripe redirect_uri 2025-11-30 15:50:42 -08:00
Daniel Lo Nigro
f9e49727fc Fix Stripe API URLs in webapp 2025-11-30 15:35:27 -08:00
Ahmed Bouhuolia
66969753b1 fix: seeds file-system directory 2025-11-30 22:59:48 +02:00
Ahmed Bouhuolia
3648fb3ffc fix: cloud subscription flag 2025-11-30 22:38:00 +02:00
Ahmed Bouhuolia
e196d485cf fix: filter pdf templates by resource 2025-11-26 22:25:42 +02:00
Ahmed Bouhuolia
74e46364ac feat: theme preloading and dark mode 2025-11-26 21:27:42 +02:00
Ahmed Bouhuolia
8817be4813 Merge remote-tracking branch 'refs/remotes/origin/develop' into develop 2025-11-25 23:46:51 +02:00
Ahmed Bouhuolia
cd4816aa3b fix: printing sale receipts 2025-11-25 23:46:41 +02:00
Ahmed Bouhuolia
82a2c74182 Merge pull request #859 from bigcapitalhq/rate-quantity-must-be-required
fix: rate and quantity of entries must not be empty
2025-11-25 22:03:25 +02:00
Ahmed Bouhuolia
e231efb9de fix: rate and quantity of entries must not be empty 2025-11-25 22:02:09 +02:00
Ahmed Bouhuolia
65ffc31ec0 Merge pull request #858 from bigcapitalhq/migrate-from-cra-to-vite
feat: migrate from CRA to Vite for speed
2025-11-25 21:36:28 +02:00
Ahmed Bouhuolia
dc6cf13a3e fix: wdyr error with vite 2025-11-25 21:34:17 +02:00
Ahmed Bouhuolia
adfa8852db wip 2025-11-25 21:29:32 +02:00
Ahmed Bouhuolia
ff04c4b762 wip 2025-11-24 18:58:50 +02:00
Ahmed Bouhuolia
fe4bd88f9f wip 2025-11-24 14:58:58 +02:00
Ahmed Bouhuolia
caf232d928 feat: migrate from CRA to Vite for speed 2025-11-24 14:19:05 +02:00
Ahmed Bouhuolia
234b1804b3 Merge pull request #855 from Daniel15/Daniel15-patch-1
Update commands in contributing docs
2025-11-21 11:25:29 +02:00
Daniel Lo Nigro
98b3b551c1 Update commands in contributing docs 2025-11-20 21:08:40 -08:00
Ahmed Bouhuolia
ceed9e453f feat: bulk transcations delete (#844)
* feat: bulk transcations delete
2025-11-20 23:11:06 +02:00
Ahmed Bouhuolia
43faa45dcf wip 2025-11-20 23:06:35 +02:00
Ahmed Bouhuolia
56e00d254b wip 2025-11-20 17:41:16 +02:00
Ahmed Bouhuolia
d90b6ffbe7 wip 2025-11-19 23:42:06 +02:00
Ahmed Bouhuolia
5eafd23bf8 wip 2025-11-19 22:59:30 +02:00
Ahmed Bouhuolia
2b384b2f6f wip 2025-11-19 22:59:21 +02:00
Ahmed Bouhuolia
17bcc14231 wip 2025-11-17 22:26:33 +02:00
Ahmed Bouhuolia
2c64e1b8ab wip 2025-11-17 17:04:25 +02:00
Daniel Lo Nigro
6f50138260 Improve Stripe example (#851) 2025-11-17 14:23:51 +02:00
Andres Maqueo
0a7d687f91 fix: docker/redis/Dockerfile to reduce vulnerabilities (#845)
The following vulnerabilities are fixed with an upgrade:
- https://snyk.io/vuln/SNYK-DEBIAN10-SYSTEMD-3339153
- https://snyk.io/vuln/SNYK-DEBIAN10-SYSTEMD-3339153
- https://snyk.io/vuln/SNYK-DEBIAN10-OPENSSL-2426310
- https://snyk.io/vuln/SNYK-DEBIAN10-OPENSSL-2807585
- https://snyk.io/vuln/SNYK-DEBIAN10-OPENSSL-1569403

Co-authored-by: snyk-bot <snyk-bot@snyk.io>
2025-11-17 14:22:00 +02:00
Ahmed Bouhuolia
2383091b6e wip 2025-11-12 21:34:30 +02:00
Ahmed Bouhuolia
e2f5d4c66e Merge pull request #848 from Daniel15/patch-1
[docker] Change BANKING_CONNECT to BANK_FEED_ENABLED
2025-11-12 09:31:08 +02:00
Daniel Lo Nigro
ce70234ebd [docker] Change BANKING_CONNECT to BANK_FEED_ENABLED 2025-11-11 22:57:42 -08:00
Ahmed Bouhuolia
80abd1f66f fix: edit/create account 2025-11-07 22:20:06 +02:00
Ahmed Bouhuolia
a0bc9db9a6 feat: bulk transcations delete 2025-11-03 21:40:24 +02:00
Ahmed Bouhuolia
8161439365 Merge pull request #843 from bigcapitalhq/refactor-fast-fields
feat: refactor FastField fields to binded Formik fields
2025-11-03 00:29:26 +02:00
Ahmed Bouhuolia
46871c8113 feat: refactor FastField fields to binded Formik fields 2025-11-03 00:27:32 +02:00
Ahmed Bouhuolia
a4aee58f93 Merge pull request #842 from bigcapitalhq/fix-auto-increment-transactions
fix: auto increment serial transactions
2025-11-02 21:10:04 +02:00
Ahmed Bouhuolia
f64875404a fix: auto increment serial transactions 2025-11-02 21:08:28 +02:00
Ahmed Bouhuolia
cca116f6bb Merge pull request #841 from bigcapitalhq/only-inactive-accounts-filter
fix: only inactive accounts filter
2025-11-02 20:00:14 +02:00
Ahmed Bouhuolia
fdec94a3f7 fix: only inactive accounts filter 2025-11-02 19:58:26 +02:00
Ahmed Bouhuolia
c66299aacd feat: darkmode preferences screens (#840) 2025-11-02 17:01:52 +02:00
Ahmed Bouhuolia
77dc0778a3 feat: darkmode preferences screens 2025-11-02 16:43:47 +02:00
Ahmed Bouhuolia
a76445a6eb feat: api keys ui (#839)
* feat: api keys ui
2025-11-02 12:41:16 +02:00
Ahmed Bouhuolia
41143d8bbd feat: api endpoints throttle (#837)
* feat: api endpoints throttle
2025-10-30 22:06:05 +02:00
Ahmed Bouhuolia
844a050c9a Merge pull request #836 from bigcapitalhq/auth-pages-errors-handler
fix: auth pages errors handler
2025-10-30 19:29:41 +02:00
1191 changed files with 17200 additions and 14065 deletions

View File

@@ -168,6 +168,16 @@
"contributions": [ "contributions": [
"bug" "bug"
] ]
},
{
"login": "Daniel15",
"name": "Daniel Lo Nigro",
"avatar_url": "https://avatars.githubusercontent.com/u/91933?v=4",
"profile": "https://d.sb/",
"contributions": [
"bug",
"code"
]
} }
], ],
"contributorsPerLine": 7, "contributorsPerLine": 7,

View File

@@ -98,8 +98,18 @@ POSTHOG_API_KEY=
POSTHOG_HOST= POSTHOG_HOST=
# Stripe Payment # Stripe Payment
# Get the keys from the Stripe dashboard
# Starts with "sk_"
STRIPE_PAYMENT_SECRET_KEY= STRIPE_PAYMENT_SECRET_KEY=
# Starts with "pk_"
STRIPE_PAYMENT_PUBLISHABLE_KEY= STRIPE_PAYMENT_PUBLISHABLE_KEY=
# Get the client ID from https://dashboard.stripe.com/settings/connect/onboarding-options/oauth
# Starts with "ca_"
STRIPE_PAYMENT_CLIENT_ID= STRIPE_PAYMENT_CLIENT_ID=
# Configure the webhook here: https://dashboard.stripe.com/workbench/webhooks/
# Endpoint URL is https://example.com/api/webhooks/stripe (replace "example.com" with the correct domain)
# Select the "checkout.session.completed" and "account.updated" events
# Starts with "whsec_"
STRIPE_PAYMENT_WEBHOOKS_SECRET= STRIPE_PAYMENT_WEBHOOKS_SECRET=
STRIPE_PAYMENT_REDIRECT_URL= # Replace example.com with the correct domain
STRIPE_PAYMENT_REDIRECT_URL=https://example.com/preferences/payment-methods/stripe/callback

View File

@@ -54,7 +54,7 @@ pnpm install
- Run all required docker containers in the development, we already configured all containers under `docker-compose.yml`. - Run all required docker containers in the development, we already configured all containers under `docker-compose.yml`.
``` ```
docker-compose up -d docker compose up -d
``` ```
Wait some seconds, and hit `docker-compose ps` and you should see the same result below. Wait some seconds, and hit `docker-compose ps` and you should see the same result below.
@@ -75,7 +75,7 @@ pnpm run build:server
- Run the database migration for system database. - Run the database migration for system database.
``` ```
node packages/server/build/commands.js system:migrate:latest pnpm run system:migrate:latest
``` ```
And you should get something like that. And you should get something like that.
@@ -84,10 +84,10 @@ And you should get something like that.
Batch 1 run: 6 migrations Batch 1 run: 6 migrations
``` ```
- Next, start the webapp application. - Next, start the server.
``` ```
pnpm run dev:server pnpm run server:start
``` ```
**[`^top^`](#)** **[`^top^`](#)**
@@ -96,12 +96,6 @@ pnpm run dev:server
## Contribute to Frontend ## Contribute to Frontend
- Clone the `bigcapital` repository and cd into `bigcapital` directory.
```
git clone https://github.com/bigcapital/bigcapital.git && cd bigcaptial
```
- Install all npm dependencies of the monorepo, you don't have to change directory to the `frontend` package. just hit that command and will install all packages across all application. - Install all npm dependencies of the monorepo, you don't have to change directory to the `frontend` package. just hit that command and will install all packages across all application.
``` ```

View File

@@ -135,6 +135,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
<td align="center" valign="top" width="14.28%"><a href="https://myself.vercel.app/"><img src="https://avatars.githubusercontent.com/u/42431274?v=4?s=100" width="100px;" alt="Sachin Mittal"/><br /><sub><b>Sachin Mittal</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3Amittalsam98" title="Bug reports">🐛</a></td> <td align="center" valign="top" width="14.28%"><a href="https://myself.vercel.app/"><img src="https://avatars.githubusercontent.com/u/42431274?v=4?s=100" width="100px;" alt="Sachin Mittal"/><br /><sub><b>Sachin Mittal</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3Amittalsam98" title="Bug reports">🐛</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://www.camilooviedo.com/"><img src="https://avatars.githubusercontent.com/u/64604272?v=4?s=100" width="100px;" alt="Camilo Oviedo"/><br /><sub><b>Camilo Oviedo</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/commits?author=Champetaman" title="Code">💻</a></td> <td align="center" valign="top" width="14.28%"><a href="https://www.camilooviedo.com/"><img src="https://avatars.githubusercontent.com/u/64604272?v=4?s=100" width="100px;" alt="Camilo Oviedo"/><br /><sub><b>Camilo Oviedo</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/commits?author=Champetaman" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://nklmantey.com/"><img src="https://avatars.githubusercontent.com/u/90279429?v=4?s=100" width="100px;" alt="Mantey"/><br /><sub><b>Mantey</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3Anklmantey" title="Bug reports">🐛</a></td> <td align="center" valign="top" width="14.28%"><a href="https://nklmantey.com/"><img src="https://avatars.githubusercontent.com/u/90279429?v=4?s=100" width="100px;" alt="Mantey"/><br /><sub><b>Mantey</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3Anklmantey" title="Bug reports">🐛</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://d.sb/"><img src="https://avatars.githubusercontent.com/u/91933?v=4?s=100" width="100px;" alt="Daniel Lo Nigro"/><br /><sub><b>Daniel Lo Nigro</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3ADaniel15" title="Bug reports">🐛</a> <a href="https://github.com/bigcapitalhq/bigcapital/commits?author=Daniel15" title="Code">💻</a></td>
</tr> </tr>
</tbody> </tbody>
</table> </table>

View File

@@ -93,7 +93,7 @@ services:
- OPEN_EXCHANGE_RATE_APP_ID-${OPEN_EXCHANGE_RATE_APP_ID} - OPEN_EXCHANGE_RATE_APP_ID-${OPEN_EXCHANGE_RATE_APP_ID}
# Bank Sync # Bank Sync
- BANKING_CONNECT=${BANKING_CONNECT} - BANK_FEED_ENABLED=${BANK_FEED_ENABLED}
# Plaid # Plaid
- PLAID_ENV=${PLAID_ENV} - PLAID_ENV=${PLAID_ENV}
@@ -123,6 +123,13 @@ services:
- S3_ENDPOINT=${S3_ENDPOINT} - S3_ENDPOINT=${S3_ENDPOINT}
- S3_BUCKET=${S3_BUCKET} - S3_BUCKET=${S3_BUCKET}
# Stripe
- STRIPE_PAYMENT_SECRET_KEY=${STRIPE_PAYMENT_SECRET_KEY}
- STRIPE_PAYMENT_PUBLISHABLE_KEY=${STRIPE_PAYMENT_PUBLISHABLE_KEY}
- STRIPE_PAYMENT_CLIENT_ID=${STRIPE_PAYMENT_CLIENT_ID}
- STRIPE_PAYMENT_WEBHOOKS_SECRET=${STRIPE_PAYMENT_WEBHOOKS_SECRET}
- STRIPE_PAYMENT_REDIRECT_URL=${STRIPE_PAYMENT_REDIRECT_URL}
database_migration: database_migration:
container_name: bigcapital-database-migration container_name: bigcapital-database-migration
build: build:

View File

@@ -1,4 +1,4 @@
FROM redis:6.2.0 FROM redis:6.2.21
COPY redis.conf /usr/local/etc/redis/redis.conf COPY redis.conf /usr/local/etc/redis/redis.conf

View File

@@ -39,6 +39,7 @@
"@casl/ability": "^5.4.3", "@casl/ability": "^5.4.3",
"@lemonsqueezy/lemonsqueezy.js": "^2.2.0", "@lemonsqueezy/lemonsqueezy.js": "^2.2.0",
"@liaoliaots/nestjs-redis": "^10.0.0", "@liaoliaots/nestjs-redis": "^10.0.0",
"@nest-lab/throttler-storage-redis": "^1.1.0",
"@nestjs/bull": "^10.2.1", "@nestjs/bull": "^10.2.1",
"@nestjs/bullmq": "^10.2.2", "@nestjs/bullmq": "^10.2.2",
"@nestjs/cache-manager": "^2.2.2", "@nestjs/cache-manager": "^2.2.2",
@@ -166,6 +167,9 @@
"**/*.(t|j)s" "**/*.(t|j)s"
], ],
"coverageDirectory": "../coverage", "coverageDirectory": "../coverage",
"testEnvironment": "node" "testEnvironment": "node",
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/$1"
}
} }
} }

View File

@@ -0,0 +1,5 @@
import { registerAs } from '@nestjs/config';
export default registerAs('app', () => ({
baseUrl: process.env.BASE_URL,
}));

View File

@@ -0,0 +1,5 @@
import { registerAs } from '@nestjs/config';
export default registerAs('cloud', () => ({
hostedOnCloud: process.env.HOSTED_ON_BIGCAPITAL_CLOUD === 'true',
}));

View File

@@ -1,3 +1,4 @@
import app from './app';
import systemDatabase from './system-database'; import systemDatabase from './system-database';
import tenantDatabase from './tenant-database'; import tenantDatabase from './tenant-database';
import signup from './signup'; import signup from './signup';
@@ -14,9 +15,13 @@ import jwt from './jwt';
import mail from './mail'; import mail from './mail';
import loops from './loops'; import loops from './loops';
import bankfeed from './bankfeed'; import bankfeed from './bankfeed';
import throttle from './throttle';
import cloud from './cloud';
export const config = [ export const config = [
app,
systemDatabase, systemDatabase,
cloud,
tenantDatabase, tenantDatabase,
signup, signup,
gotenberg, gotenberg,
@@ -32,4 +37,5 @@ export const config = [
mail, mail,
loops, loops,
bankfeed, bankfeed,
throttle,
]; ];

View File

@@ -0,0 +1,14 @@
import { registerAs } from '@nestjs/config';
export default registerAs('throttle', () => ({
global: {
ttl: parseInt(process.env.THROTTLE_GLOBAL_TTL ?? '60000', 10),
limit: parseInt(process.env.THROTTLE_GLOBAL_LIMIT ?? '100', 10),
},
auth: {
ttl: parseInt(process.env.THROTTLE_AUTH_TTL ?? '60000', 10),
limit: parseInt(process.env.THROTTLE_AUTH_LIMIT ?? '10', 10),
},
}));

View File

@@ -0,0 +1,55 @@
import { IsArray, IsInt, ArrayNotEmpty, IsBoolean, IsOptional } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { parseBoolean } from '@/utils/parse-boolean';
export class BulkDeleteDto {
@IsArray()
@ArrayNotEmpty()
@IsInt({ each: true })
@ApiProperty({
description: 'Array of IDs to delete',
type: [Number],
example: [1, 2, 3],
})
ids: number[];
@IsOptional()
@IsBoolean()
@Transform(({ value, obj }) => parseBoolean(value ?? obj?.skip_undeletable, false))
@ApiPropertyOptional({
description: 'When true, undeletable items will be skipped and only deletable ones will be removed.',
type: Boolean,
default: false,
})
skipUndeletable?: boolean;
}
export class ValidateBulkDeleteResponseDto {
@ApiProperty({
description: 'Number of items that can be deleted',
example: 2,
})
deletableCount: number;
@ApiProperty({
description: 'Number of items that cannot be deleted',
example: 1,
})
nonDeletableCount: number;
@ApiProperty({
description: 'IDs of items that can be deleted',
type: [Number],
example: [1, 2],
})
deletableIds: number[];
@ApiProperty({
description: 'IDs of items that cannot be deleted',
type: [Number],
example: [3],
})
nonDeletableIds: number[];
}

View File

@@ -7,53 +7,46 @@ import {
} from '@nestjs/common'; } from '@nestjs/common';
import { type Observable } from 'rxjs'; import { type Observable } from 'rxjs';
import { map } from 'rxjs/operators'; import { map } from 'rxjs/operators';
import { mapKeysDeep } from '@/utils/deepdash';
export function camelToSnake<T = any>(value: T) { export function camelToSnake<T = any>(value: T): T {
if (value === null || value === undefined) { if (value === null || value === undefined) {
return value; return value;
} }
if (Array.isArray(value)) { return mapKeysDeep(
return value.map(camelToSnake); value,
(_value: string, key: any, parent: any, context: any) => {
if (Array.isArray(parent)) {
// tell mapKeysDeep to skip mapping inside this branch
context.skipChildren = true;
return key;
} }
if (typeof value === 'object' && !(value instanceof Date)) { return key
return Object.fromEntries(
Object.entries(value).map(([key, value]) => [
key
.split(/(?=[A-Z])/) .split(/(?=[A-Z])/)
.join('_') .join('_')
.toLowerCase(), .toLowerCase();
camelToSnake(value), },
]), ) as T;
);
}
return value;
} }
export function snakeToCamel<T = any>(value: T) { export function snakeToCamel<T = any>(value: T): T {
if (value === null || value === undefined) { if (value === null || value === undefined) {
return value; return value;
} }
return mapKeysDeep(
if (Array.isArray(value)) { value,
return value.map(snakeToCamel); (_value: string, key: any, parent: any, context: any) => {
if (Array.isArray(parent)) {
// tell mapKeysDeep to skip mapping inside this branch
context.skipChildren = true;
return key;
} }
const converted = key.replace(/([-_]\w)/g, (group) =>
const impl = (str: string) => {
const converted = str.replace(/([-_]\w)/g, (group) =>
group[1].toUpperCase(), group[1].toUpperCase(),
); );
return converted[0].toLowerCase() + converted.slice(1); return converted[0].toLowerCase() + converted.slice(1);
}; },
) as T;
if (typeof value === 'object' && !(value instanceof Date)) {
return Object.fromEntries(
Object.entries(value).map(([key, value]) => [
impl(key),
snakeToCamel(value),
]),
);
}
return value;
} }
export const DEFAULT_STRATEGY = { export const DEFAULT_STRATEGY = {

View File

@@ -1,4 +1,27 @@
// import { getTransactionsLockingSettingsSchema } from '@/api/controllers/TransactionsLocking/utils'; import { chain, mapKeys } from 'lodash';
const getTransactionsLockingSettingsSchema = (modules: string[]) => {
const moduleSchema = {
active: { type: 'boolean' },
lock_to_date: { type: 'date' },
unlock_from_date: { type: 'date' },
unlock_to_date: { type: 'date' },
lock_reason: { type: 'string' },
unlock_reason: { type: 'string' },
};
return chain(modules)
.map((module: string) => {
return mapKeys(moduleSchema, (value, key: string) => `${module}.${key}`);
})
.flattenDeep()
.reduce((result, value) => {
return {
...result,
...value,
};
}, {})
.value();
};
export const SettingsOptions = { export const SettingsOptions = {
organization: { organization: {
@@ -223,12 +246,12 @@ export const SettingsOptions = {
'locking-type': { 'locking-type': {
type: 'string', type: 'string',
}, },
// ...getTransactionsLockingSettingsSchema([ ...getTransactionsLockingSettingsSchema([
// 'all', 'all',
// 'sales', 'sales',
// 'purchases', 'purchases',
// 'financial', 'financial',
// ]), ]),
}, },
features: { features: {
'multi-warehouses': { 'multi-warehouses': {

View File

@@ -0,0 +1,36 @@
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.up = function (knex) {
return knex.schema.createTable('api_keys', (table) => {
table.increments();
table.string('key').notNullable().unique().index();
table.string('name');
table
.integer('user_id')
.unsigned()
.notNullable()
.index()
.references('id')
.inTable('users');
table
.bigInteger('tenant_id')
.unsigned()
.notNullable()
.index()
.references('id')
.inTable('tenants');
table.dateTime('expires_at').nullable().index();
table.dateTime('revoked_at').nullable().index();
table.timestamps();
});
};
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.down = function (knex) {
return knex.schema.dropTableIfExists('api_keys');
};

View File

@@ -3,6 +3,7 @@
"field.description": "Description", "field.description": "Description",
"field.slug": "Account slug", "field.slug": "Account slug",
"field.code": "Account code", "field.code": "Account code",
"field.code_hint": "Unique number to identify the account.",
"field.root_type": "Root type", "field.root_type": "Root type",
"field.normal": "Account normal", "field.normal": "Account normal",
"field.normal.credit": "Credit", "field.normal.credit": "Credit",
@@ -13,5 +14,6 @@
"field.balance": "Balance", "field.balance": "Balance",
"field.bank_balance": "Bank Balance", "field.bank_balance": "Bank Balance",
"field.parent_account": "Parent Account", "field.parent_account": "Parent Account",
"field.created_at": "Created at" "field.created_at": "Created at",
"field.account_hint": "Matches the account name or code."
} }

View File

@@ -0,0 +1,27 @@
{
"field.vendor": "Vendor",
"field.bill_number": "Bill No.",
"field.bill_date": "Date",
"field.due_date": "Due Date",
"field.reference_no": "Reference No.",
"field.exchange_rate": "Exchange Rate",
"field.note": "Note",
"field.open": "Open",
"field.entries": "Entries",
"field.item": "Item",
"field.item_hint": "Matches the item name or code.",
"field.rate": "Rate",
"field.quantity": "Quantity",
"field.description": "Line Description",
"field.amount": "Amount",
"field.payment_amount": "Payment Amount",
"field.status": "Status",
"field.status.paid": "Paid",
"field.status.partially-paid": "Partially Paid",
"field.status.overdue": "Overdue",
"field.status.unpaid": "Unpaid",
"field.status.opened": "Opened",
"field.status.draft": "Draft",
"field.created_at": "Created At"
}

View File

@@ -0,0 +1,15 @@
{
"field.vendor": "Vendor",
"field.payment_date": "Payment Date",
"field.payment_number": "Payment No.",
"field.payment_account": "Payment Account",
"field.exchange_rate": "Exchange Rate",
"field.note": "Note",
"field.reference": "Reference",
"field.entries": "Entries",
"field.entries.bill": "Bill",
"field.entries.payment_amount": "Payment Amount",
"field.payment_number_hint": "The payment number should be unique.",
"field.bill_hint": "Matches the bill number."
}

View File

@@ -0,0 +1,16 @@
{
"field.customer": "Customer",
"field.exchange_rate": "Exchange Rate",
"field.credit_note_date": "Credit Note Date",
"field.reference_no": "Reference No.",
"field.note": "Note",
"field.terms_conditions": "Terms & Conditions",
"field.credit_note_number": "Credit Note Number",
"field.open": "Open",
"field.entries": "Entries",
"field.item": "Item",
"field.rate": "Rate",
"field.quantity": "Quantity",
"field.description": "Description"
}

View File

@@ -0,0 +1,5 @@
{
"type.business": "Business",
"type.individual": "Individual"
}

View File

@@ -0,0 +1,21 @@
{
"field.customer": "Customer",
"field.estimate_date": "Estimate Date",
"field.expiration_date": "Expiration Date",
"field.estimate_number": "Estimate No.",
"field.reference_no": "Reference No.",
"field.exchange_rate": "Exchange Rate",
"field.currency": "Currency",
"field.note": "Note",
"field.terms_conditions": "Terms & Conditions",
"field.delivered": "Delivered",
"field.entries": "Entries",
"field.amount": "Amount",
"field.status": "Status",
"field.status.draft": "Draft",
"field.status.delivered": "Delivered",
"field.status.rejected": "Rejected",
"field.status.approved": "Approved",
"field.created_at": "Created At"
}

View File

@@ -26,6 +26,7 @@
"field.due_amount": "Due amount", "field.due_amount": "Due amount",
"field.delivered": "Delivered", "field.delivered": "Delivered",
"field.item_name": "Item Name", "field.item_name": "Item Name",
"field.item_hint": "Matches the item name or code.",
"field.rate": "Rate", "field.rate": "Rate",
"field.quantity": "Quantity", "field.quantity": "Quantity",
"field.description": "Description", "field.description": "Description",
@@ -38,5 +39,7 @@
"field.status.draft": "Draft", "field.status.draft": "Draft",
"field.created_at": "Created at", "field.created_at": "Created at",
"field.currency": "Currency", "field.currency": "Currency",
"field.entries": "Entries" "field.entries": "Entries",
"field.branch": "Branch",
"field.warehouse": "Warehouse"
} }

View File

@@ -17,6 +17,7 @@
"field.quantity_on_hand": "Quantity on Hand", "field.quantity_on_hand": "Quantity on Hand",
"field.note": "Note", "field.note": "Note",
"field.category": "Category", "field.category": "Category",
"field.category_hint": "Matches the category name.",
"field.active": "Active", "field.active": "Active",
"field.created_at": "Created At" "field.created_at": "Created At"
} }

View File

@@ -0,0 +1,17 @@
{
"field.customer": "Customer",
"field.payment_date": "Payment Date",
"field.amount": "Amount",
"field.reference_no": "Reference No.",
"field.deposit_account": "Deposit Account",
"field.payment_receive_no": "Payment No.",
"field.statement": "Statement",
"field.entries": "Entries",
"field.exchange_rate": "Exchange Rate",
"field.invoice": "Invoice",
"field.entries.payment_amount": "Payment Amount",
"field.created_at": "Created At",
"field.payment_no_hint": "The payment number should be unique.",
"field.invoice_hint": "Matches the invoice number."
}

View File

@@ -10,5 +10,21 @@
"paper.receipt_amount": "Receipt amount", "paper.receipt_amount": "Receipt amount",
"paper.total": "Total", "paper.total": "Total",
"paper.balance_due": "Balance Due", "paper.balance_due": "Balance Due",
"paper.payment_amount": "Payment Amount" "paper.payment_amount": "Payment Amount",
"field.receipt_date": "Receipt Date",
"field.customer": "Customer",
"field.deposit_account": "Deposit Account",
"field.exchange_rate": "Exchange Rate",
"field.receipt_number": "Receipt Number",
"field.reference_no": "Reference No.",
"field.closed": "Closed",
"field.entries": "Entries",
"field.statement": "Statement",
"field.receipt_message": "Receipt Message",
"field.amount": "Amount",
"field.status": "Status",
"field.status.draft": "Draft",
"field.status.closed": "Closed",
"field.created_at": "Created At"
} }

View File

@@ -2,5 +2,18 @@
"view.draft": "Draft", "view.draft": "Draft",
"view.published": "Published", "view.published": "Published",
"view.open": "Open", "view.open": "Open",
"view.closed": "Closed" "view.closed": "Closed",
"field.vendor": "Vendor",
"field.vendor_credit_number": "Vendor Credit No.",
"field.vendor_credit_date": "Vendor Credit Date",
"field.reference_no": "Reference No.",
"field.exchange_rate": "Exchange Rate",
"field.note": "Note",
"field.open": "Open",
"field.entries": "Entries",
"field.item": "Item",
"field.rate": "Rate",
"field.quantity": "Quantity",
"field.description": "Description"
} }

View File

@@ -11,6 +11,7 @@ class FsMigrations {
private sortDirsSeparately: boolean; private sortDirsSeparately: boolean;
private migrationsPaths: string[]; private migrationsPaths: string[];
private loadExtensions: string[]; private loadExtensions: string[];
private seedsDirectory: string;
/** /**
* Constructor method. * Constructor method.
@@ -30,6 +31,8 @@ class FsMigrations {
} }
this.migrationsPaths = migrationDirectories; this.migrationsPaths = migrationDirectories;
this.loadExtensions = loadExtensions || DEFAULT_LOAD_EXTENSIONS; this.loadExtensions = loadExtensions || DEFAULT_LOAD_EXTENSIONS;
// Store the seeds directory (first path is the seeds directory)
this.seedsDirectory = migrationDirectories[0] || '';
} }
/** /**
@@ -93,7 +96,10 @@ class FsMigrations {
* @returns {string} * @returns {string}
*/ */
public getMigration(migration: MigrateItem): string { public getMigration(migration: MigrateItem): string {
return importWebpackSeedModule(migration.file.replace('.ts', '')); return importWebpackSeedModule(
migration.file.replace('.ts', ''),
this.seedsDirectory,
);
} }
} }

View File

@@ -1,5 +1,6 @@
// @ts-nocheck // @ts-nocheck
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path';
/** /**
* Detarmines the module type of the given file path. * Detarmines the module type of the given file path.
@@ -35,8 +36,32 @@ export async function importFile(filepath: string): any {
/** /**
* *
* @param {string} moduleName * @param {string} moduleName
* @param {string} seedsDirectory - The seeds directory path from config
* @returns * @returns
*/ */
export async function importWebpackSeedModule(moduleName: string): any { export async function importWebpackSeedModule(
return import(`../../database/seeds/core/${moduleName}`); moduleName: string,
seedsDirectory: string,
): any {
// Convert the seeds directory to a relative path from this file's location
const utilsDir = __dirname;
const seedsDirAbsolute = path.isAbsolute(seedsDirectory)
? seedsDirectory
: path.resolve(process.cwd(), seedsDirectory);
// Get relative path from Utils.js location to seeds directory
const relativePath = path.relative(utilsDir, seedsDirAbsolute);
// Convert to forward slashes for import (works on all platforms)
const importPath = relativePath.split(path.sep).join('/');
// Construct the import path (add ./ prefix if not already present, or handle empty/current dir)
let finalPath = importPath;
if (!finalPath || finalPath === '.') {
finalPath = './';
} else if (!finalPath.startsWith('.')) {
finalPath = `./${finalPath}`;
}
return import(`${finalPath}/${moduleName}`);
} }

View File

@@ -8,6 +8,7 @@ import { ServiceErrorFilter } from './common/filters/service-error.filter';
import { ModelHasRelationsFilter } from './common/filters/model-has-relations.filter'; import { ModelHasRelationsFilter } from './common/filters/model-has-relations.filter';
import { ValidationPipe } from './common/pipes/ClassValidation.pipe'; import { ValidationPipe } from './common/pipes/ClassValidation.pipe';
import { ToJsonInterceptor } from './common/interceptors/to-json.interceptor'; import { ToJsonInterceptor } from './common/interceptors/to-json.interceptor';
import { NestExpressApplication } from '@nestjs/platform-express';
global.__public_dirname = path.join(__dirname, '..', 'public'); global.__public_dirname = path.join(__dirname, '..', 'public');
global.__static_dirname = path.join(__dirname, '../static'); global.__static_dirname = path.join(__dirname, '../static');
@@ -15,7 +16,10 @@ global.__views_dirname = path.join(global.__static_dirname, '/views');
global.__images_dirname = path.join(global.__static_dirname, '/images'); global.__images_dirname = path.join(global.__static_dirname, '/images');
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create<NestExpressApplication>(AppModule, {
rawBody: true,
});
app.set('query parser', 'extended');
app.setGlobalPrefix('/api'); app.setGlobalPrefix('/api');
// create and mount the middleware manually here // create and mount the middleware manually here

View File

@@ -48,14 +48,30 @@ export class PaginationQueryBuilder<
// No relations defined // No relations defined
return this.delete(); return this.delete();
} }
// Only check HasManyRelation and ManyToManyRelation relations, as BelongsToOneRelation are just
// foreign key references and shouldn't prevent deletion. Only dependent records should block deletion.
const dependentRelationNames = relationNames.filter((name) => {
const relation = relationMappings[name];
return relation && (
relation.relation === Model.HasManyRelation ||
relation.relation === Model.ManyToManyRelation
);
});
if (dependentRelationNames.length === 0) {
// No dependent relations defined, safe to delete
return this.delete();
}
const recordQuery = this.clone(); const recordQuery = this.clone();
relationNames.forEach((relationName: string) => { dependentRelationNames.forEach((relationName: string) => {
recordQuery.withGraphFetched(relationName); recordQuery.withGraphFetched(relationName);
}); });
const record = await recordQuery; const record = await recordQuery;
const hasRelations = relationNames.some((name) => { const hasRelations = dependentRelationNames.some((name) => {
const val = record[name]; const val = record[name];
return Array.isArray(val) ? val.length > 0 : val != null; return Array.isArray(val) ? val.length > 0 : val != null;
}); });

View File

@@ -7,15 +7,16 @@ import {
Get, Get,
Query, Query,
ParseIntPipe, ParseIntPipe,
Put,
} from '@nestjs/common'; } from '@nestjs/common';
import { AccountsApplication } from './AccountsApplication.service'; import { AccountsApplication } from './AccountsApplication.service';
import { CreateAccountDTO } from './CreateAccount.dto'; import { CreateAccountDTO } from './CreateAccount.dto';
import { EditAccountDTO } from './EditAccount.dto'; import { EditAccountDTO } from './EditAccount.dto';
import { IAccountsFilter } from './Accounts.types';
import { import {
ApiExtraModels, ApiExtraModels,
ApiOperation, ApiOperation,
ApiParam, ApiParam,
ApiQuery,
ApiResponse, ApiResponse,
ApiTags, ApiTags,
getSchemaPath, getSchemaPath,
@@ -24,17 +25,58 @@ import { AccountResponseDto } from './dtos/AccountResponse.dto';
import { AccountTypeResponseDto } from './dtos/AccountTypeResponse.dto'; import { AccountTypeResponseDto } from './dtos/AccountTypeResponse.dto';
import { GetAccountTransactionResponseDto } from './dtos/GetAccountTransactionResponse.dto'; import { GetAccountTransactionResponseDto } from './dtos/GetAccountTransactionResponse.dto';
import { GetAccountTransactionsQueryDto } from './dtos/GetAccountTransactionsQuery.dto'; import { GetAccountTransactionsQueryDto } from './dtos/GetAccountTransactionsQuery.dto';
import { GetAccountsQueryDto } from './dtos/GetAccountsQuery.dto';
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders'; import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
import {
BulkDeleteDto,
ValidateBulkDeleteResponseDto,
} from '@/common/dtos/BulkDelete.dto';
@Controller('accounts') @Controller('accounts')
@ApiTags('Accounts') @ApiTags('Accounts')
@ApiExtraModels(AccountResponseDto) @ApiExtraModels(AccountResponseDto)
@ApiExtraModels(AccountTypeResponseDto) @ApiExtraModels(AccountTypeResponseDto)
@ApiExtraModels(GetAccountTransactionResponseDto) @ApiExtraModels(GetAccountTransactionResponseDto)
@ApiExtraModels(ValidateBulkDeleteResponseDto)
@ApiCommonHeaders() @ApiCommonHeaders()
export class AccountsController { export class AccountsController {
constructor(private readonly accountsApplication: AccountsApplication) { } constructor(private readonly accountsApplication: AccountsApplication) { }
@Post('validate-bulk-delete')
@ApiOperation({
summary:
'Validates which accounts can be deleted and returns counts of deletable and non-deletable accounts.',
})
@ApiResponse({
status: 200,
description:
'Validation completed. Returns counts and IDs of deletable and non-deletable accounts.',
schema: {
$ref: getSchemaPath(ValidateBulkDeleteResponseDto),
},
})
async validateBulkDeleteAccounts(
@Body() bulkDeleteDto: BulkDeleteDto,
): Promise<ValidateBulkDeleteResponseDto> {
return this.accountsApplication.validateBulkDeleteAccounts(
bulkDeleteDto.ids,
);
}
@Post('bulk-delete')
@ApiOperation({ summary: 'Deletes multiple accounts in bulk.' })
@ApiResponse({
status: 200,
description: 'The accounts have been successfully deleted.',
})
async bulkDeleteAccounts(
@Body() bulkDeleteDto: BulkDeleteDto,
): Promise<void> {
return this.accountsApplication.bulkDeleteAccounts(bulkDeleteDto.ids, {
skipUndeletable: bulkDeleteDto.skipUndeletable ?? false,
});
}
@Post() @Post()
@ApiOperation({ summary: 'Create an account' }) @ApiOperation({ summary: 'Create an account' })
@ApiResponse({ @ApiResponse({
@@ -45,7 +87,7 @@ export class AccountsController {
return this.accountsApplication.createAccount(accountDTO); return this.accountsApplication.createAccount(accountDTO);
} }
@Post(':id') @Put(':id')
@ApiOperation({ summary: 'Edit the given account.' }) @ApiOperation({ summary: 'Edit the given account.' })
@ApiResponse({ @ApiResponse({
status: 200, status: 200,
@@ -178,7 +220,19 @@ export class AccountsController {
items: { $ref: getSchemaPath(AccountResponseDto) }, items: { $ref: getSchemaPath(AccountResponseDto) },
}, },
}) })
async getAccounts(@Query() filter: Partial<IAccountsFilter>) { @ApiQuery({
name: 'onlyInactive',
required: false,
type: Boolean,
description: 'Filter to show only inactive accounts',
})
@ApiQuery({
name: 'structure',
required: false,
type: String,
description: 'Structure type for the accounts list',
})
async getAccounts(@Query() filter: GetAccountsQueryDto) {
return this.accountsApplication.getAccounts(filter); return this.accountsApplication.getAccounts(filter);
} }
} }

View File

@@ -19,6 +19,8 @@ import { GetAccountsService } from './GetAccounts.service';
import { DynamicListModule } from '../DynamicListing/DynamicList.module'; import { DynamicListModule } from '../DynamicListing/DynamicList.module';
import { AccountsExportable } from './AccountsExportable.service'; import { AccountsExportable } from './AccountsExportable.service';
import { AccountsImportable } from './AccountsImportable.service'; import { AccountsImportable } from './AccountsImportable.service';
import { BulkDeleteAccountsService } from './BulkDeleteAccounts.service';
import { ValidateBulkDeleteAccountsService } from './ValidateBulkDeleteAccounts.service';
const models = [RegisterTenancyModel(BankAccount)]; const models = [RegisterTenancyModel(BankAccount)];
@@ -40,7 +42,9 @@ const models = [RegisterTenancyModel(BankAccount)];
GetAccountTransactionsService, GetAccountTransactionsService,
GetAccountsService, GetAccountsService,
AccountsExportable, AccountsExportable,
AccountsImportable AccountsImportable,
BulkDeleteAccountsService,
ValidateBulkDeleteAccountsService,
], ],
exports: [ exports: [
AccountRepository, AccountRepository,

View File

@@ -10,10 +10,14 @@ import { GetAccount } from './GetAccount.service';
import { ActivateAccount } from './ActivateAccount.service'; import { ActivateAccount } from './ActivateAccount.service';
import { GetAccountTypesService } from './GetAccountTypes.service'; import { GetAccountTypesService } from './GetAccountTypes.service';
import { GetAccountTransactionsService } from './GetAccountTransactions.service'; import { GetAccountTransactionsService } from './GetAccountTransactions.service';
import { IAccountsFilter, IAccountsTransactionsFilter } from './Accounts.types'; import { IAccountsTransactionsFilter } from './Accounts.types';
import { GetAccountsService } from './GetAccounts.service'; import { GetAccountsService } from './GetAccounts.service';
import { IFilterMeta } from '@/interfaces/Model'; import { IFilterMeta } from '@/interfaces/Model';
import { GetAccountTransactionResponseDto } from './dtos/GetAccountTransactionResponse.dto'; import { GetAccountTransactionResponseDto } from './dtos/GetAccountTransactionResponse.dto';
import { GetAccountsQueryDto } from './dtos/GetAccountsQuery.dto';
import { BulkDeleteAccountsService } from './BulkDeleteAccounts.service';
import { ValidateBulkDeleteAccountsService } from './ValidateBulkDeleteAccounts.service';
import { ValidateBulkDeleteResponseDto } from '@/common/dtos/BulkDelete.dto';
@Injectable() @Injectable()
export class AccountsApplication { export class AccountsApplication {
@@ -36,6 +40,8 @@ export class AccountsApplication {
private readonly getAccountService: GetAccount, private readonly getAccountService: GetAccount,
private readonly getAccountTransactionsService: GetAccountTransactionsService, private readonly getAccountTransactionsService: GetAccountTransactionsService,
private readonly getAccountsService: GetAccountsService, private readonly getAccountsService: GetAccountsService,
private readonly bulkDeleteAccountsService: BulkDeleteAccountsService,
private readonly validateBulkDeleteAccountsService: ValidateBulkDeleteAccountsService,
) { } ) { }
/** /**
@@ -108,11 +114,11 @@ export class AccountsApplication {
/** /**
* Retrieves the accounts list. * Retrieves the accounts list.
* @param {IAccountsFilter} filterDTO - Filter DTO. * @param {GetAccountsQueryDto} filterDTO - Filter DTO.
* @returns {Promise<{ accounts: IAccountResponse[]; filterMeta: IFilterMeta }>} * @returns {Promise<{ accounts: IAccountResponse[]; filterMeta: IFilterMeta }>}
*/ */
public getAccounts = ( public getAccounts = (
filterDTO: Partial<IAccountsFilter>, filterDTO: GetAccountsQueryDto,
): Promise<{ accounts: Account[]; filterMeta: IFilterMeta }> => { ): Promise<{ accounts: Account[]; filterMeta: IFilterMeta }> => {
return this.getAccountsService.getAccountsList(filterDTO); return this.getAccountsService.getAccountsList(filterDTO);
}; };
@@ -127,4 +133,28 @@ export class AccountsApplication {
): Promise<Array<GetAccountTransactionResponseDto>> => { ): Promise<Array<GetAccountTransactionResponseDto>> => {
return this.getAccountTransactionsService.getAccountsTransactions(filter); return this.getAccountTransactionsService.getAccountsTransactions(filter);
}; };
/**
* Validates which accounts can be deleted in bulk.
*/
public validateBulkDeleteAccounts = (
accountIds: number[],
): Promise<ValidateBulkDeleteResponseDto> => {
return this.validateBulkDeleteAccountsService.validateBulkDeleteAccounts(
accountIds,
);
};
/**
* Deletes multiple accounts in bulk.
*/
public bulkDeleteAccounts = (
accountIds: number[],
options?: { skipUndeletable?: boolean },
): Promise<void> => {
return this.bulkDeleteAccountsService.bulkDeleteAccounts(
accountIds,
options,
);
};
} }

View File

@@ -0,0 +1,41 @@
import { Injectable } from '@nestjs/common';
import { Knex } from 'knex';
import { PromisePool } from '@supercharge/promise-pool';
import { castArray, uniq } from 'lodash';
import { DeleteAccount } from './DeleteAccount.service';
@Injectable()
export class BulkDeleteAccountsService {
constructor(private readonly deleteAccountService: DeleteAccount) { }
/**
* Deletes multiple accounts.
* @param {number | Array<number>} accountIds - The account id or ids.
* @param {Knex.Transaction} trx - The transaction.
*/
async bulkDeleteAccounts(
accountIds: number | Array<number>,
options?: { skipUndeletable?: boolean },
trx?: Knex.Transaction,
): Promise<void> {
const { skipUndeletable = false } = options ?? {};
const accountsIds = uniq(castArray(accountIds));
const results = await PromisePool.withConcurrency(1)
.for(accountsIds)
.process(async (accountId: number) => {
try {
await this.deleteAccountService.deleteAccount(accountId);
} catch (error) {
if (!skipUndeletable) {
throw error;
}
}
});
if (!skipUndeletable && results.errors && results.errors.length > 0) {
throw results.errors[0].raw;
}
}
}

View File

@@ -115,7 +115,7 @@ export class CommandAccountValidators {
accountName: string, accountName: string,
notAccountId?: number, notAccountId?: number,
) { ) {
const foundAccount = await this.accountModel const foundAccount = await this.accountModel()
.query() .query()
.findOne('name', accountName) .findOne('name', accountName)
.onBuild((query) => { .onBuild((query) => {

View File

@@ -1,7 +1,7 @@
import { IsOptional, ToNumber } from '@/common/decorators/Validators';
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from '@nestjs/swagger';
import { import {
IsString, IsString,
IsOptional,
IsInt, IsInt,
MinLength, MinLength,
MaxLength, MaxLength,
@@ -65,7 +65,7 @@ export class CreateAccountDTO {
description?: string; description?: string;
@IsOptional() @IsOptional()
@IsInt() @ToNumber()
@ApiProperty({ @ApiProperty({
description: 'ID of the parent account', description: 'ID of the parent account',
example: 1, example: 1,

View File

@@ -50,8 +50,12 @@ export class DeleteAccount {
/** /**
* Deletes the account from the storage. * Deletes the account from the storage.
* @param {number} accountId * @param {number} accountId
* @param {Knex.Transaction} trx - Database transaction instance.
*/ */
public deleteAccount = async (accountId: number): Promise<void> => { public deleteAccount = async (
accountId: number,
trx?: Knex.Transaction,
): Promise<void> => {
// Retrieve account or not found service error. // Retrieve account or not found service error.
const oldAccount = await this.accountModel().query().findById(accountId); const oldAccount = await this.accountModel().query().findById(accountId);
@@ -82,6 +86,6 @@ export class DeleteAccount {
oldAccount, oldAccount,
trx, trx,
} as IAccountEventDeletedPayload); } as IAccountEventDeletedPayload);
}); }, trx);
}; };
} }

View File

@@ -1,11 +1,6 @@
import { IsString, MinLength, MaxLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from '@nestjs/swagger';
import { import { IsOptional, ToNumber } from '@/common/decorators/Validators';
IsString,
IsOptional,
IsInt,
MinLength,
MaxLength,
} from 'class-validator';
export class EditAccountDTO { export class EditAccountDTO {
@IsString() @IsString()
@@ -45,7 +40,7 @@ export class EditAccountDTO {
description?: string; description?: string;
@IsOptional() @IsOptional()
@IsInt() @ToNumber()
@ApiProperty({ @ApiProperty({
description: 'The parent account ID of the account', description: 'The parent account ID of the account',
example: 1, example: 1,

View File

@@ -85,8 +85,7 @@ export class EditAccount {
// Update the account on the storage. // Update the account on the storage.
const account = await this.accountModel() const account = await this.accountModel()
.query(trx) .query(trx)
.findById(accountId) .updateAndFetchById(accountId, { ...accountDTO });
.updateAndFetch({ ...accountDTO });
// Triggers `onAccountEdited` event. // Triggers `onAccountEdited` event.
// await this.eventEmitter.emitAsync(events.accounts.onEdited, { // await this.eventEmitter.emitAsync(events.accounts.onEdited, {

View File

@@ -8,6 +8,7 @@ import { Account } from './models/Account.model';
import { AccountRepository } from './repositories/Account.repository'; import { AccountRepository } from './repositories/Account.repository';
import { IFilterMeta } from '@/interfaces/Model'; import { IFilterMeta } from '@/interfaces/Model';
import { TenantModelProxy } from '../System/models/TenantBaseModel'; import { TenantModelProxy } from '../System/models/TenantBaseModel';
import { GetAccountsQueryDto } from './dtos/GetAccountsQuery.dto';
@Injectable() @Injectable()
export class GetAccountsService { export class GetAccountsService {
@@ -26,12 +27,12 @@ export class GetAccountsService {
* @returns {Promise<{ accounts: IAccountResponse[]; filterMeta: IFilterMeta }>} * @returns {Promise<{ accounts: IAccountResponse[]; filterMeta: IFilterMeta }>}
*/ */
public async getAccountsList( public async getAccountsList(
filterDto: Partial<IAccountsFilter>, filterDto: Partial<GetAccountsQueryDto>,
): Promise<{ accounts: Account[]; filterMeta: IFilterMeta }> { ): Promise<{ accounts: Account[]; filterMeta: IFilterMeta }> {
const parsedFilterDto = { const parsedFilterDto = {
sortOrder: 'desc', sortOrder: 'desc',
columnSortBy: 'created_at', columnSortBy: 'created_at',
inactiveMode: false, onlyInactive: false,
structure: IAccountsStructureType.Tree, structure: IAccountsStructureType.Tree,
...filterDto, ...filterDto,
}; };
@@ -48,7 +49,7 @@ export class GetAccountsService {
.query() .query()
.onBuild((builder) => { .onBuild((builder) => {
dynamicList.buildQuery()(builder); dynamicList.buildQuery()(builder);
builder.modify('inactiveMode', filter.inactiveMode); builder.modify('inactiveMode', filterDto.onlyInactive);
}); });
const accountsGraph = await this.accountRepository.getDependencyGraph(); const accountsGraph = await this.accountRepository.getDependencyGraph();
@@ -58,7 +59,6 @@ export class GetAccountsService {
new AccountTransformer(), new AccountTransformer(),
{ accountsGraph, structure: parsedFilterDto.structure }, { accountsGraph, structure: parsedFilterDto.structure },
); );
return { return {
accounts: transformedAccounts, accounts: transformedAccounts,
filterMeta: dynamicList.getResponseMeta(), filterMeta: dynamicList.getResponseMeta(),

View File

@@ -0,0 +1,63 @@
import { Injectable, Inject } from '@nestjs/common';
import { Knex } from 'knex';
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
import { DeleteAccount } from './DeleteAccount.service';
import { ModelHasRelationsError } from '@/common/exceptions/ModelHasRelations.exception';
@Injectable()
export class ValidateBulkDeleteAccountsService {
constructor(
private readonly deleteAccountService: DeleteAccount,
@Inject(TENANCY_DB_CONNECTION)
private readonly tenantKnex: () => Knex,
) {}
/**
* Validates which accounts from the provided IDs can be deleted.
* Uses the actual deleteAccount service to validate, ensuring the same validation logic.
* Uses a transaction that is always rolled back to ensure no database changes.
* @param {number[]} accountIds - Array of account IDs to validate
* @returns {Promise<{deletableCount: number, nonDeletableCount: number, deletableIds: number[], nonDeletableIds: number[]}>}
*/
public async validateBulkDeleteAccounts(accountIds: number[]): Promise<{
deletableCount: number;
nonDeletableCount: number;
deletableIds: number[];
nonDeletableIds: number[];
}> {
const trx = await this.tenantKnex().transaction({
isolationLevel: 'read uncommitted',
});
try {
const deletableIds: number[] = [];
const nonDeletableIds: number[] = [];
for (const accountId of accountIds) {
try {
await this.deleteAccountService.deleteAccount(accountId, trx);
deletableIds.push(accountId);
} catch (error) {
if (error instanceof ModelHasRelationsError) {
nonDeletableIds.push(accountId);
} else {
nonDeletableIds.push(accountId);
}
}
}
await trx.rollback();
return {
deletableCount: deletableIds.length,
nonDeletableCount: nonDeletableIds.length,
deletableIds,
nonDeletableIds,
};
} catch (error) {
await trx.rollback();
throw error;
}
}
}

View File

@@ -0,0 +1,27 @@
import { IsBoolean, IsEnum, IsOptional } from 'class-validator';
import { ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { parseBoolean } from '@/utils/parse-boolean';
import { IAccountsStructureType } from '../Accounts.types';
export class GetAccountsQueryDto {
@ApiPropertyOptional({
type: Boolean,
description: 'Filter to show only inactive accounts',
default: false,
})
@IsOptional()
@IsBoolean()
@Transform(({ value }) => parseBoolean(value, false))
onlyInactive?: boolean;
@ApiPropertyOptional({
enum: IAccountsStructureType,
description: 'Structure type for the accounts list',
default: IAccountsStructureType.Tree,
})
@IsOptional()
@IsEnum(IAccountsStructureType)
structure?: IAccountsStructureType;
}

View File

@@ -156,7 +156,7 @@ export const AccountMeta = {
minLength: 3, minLength: 3,
maxLength: 6, maxLength: 6,
unique: true, unique: true,
importHint: 'Unique number to identify the account.', importHint: 'account.field.code_hint',
}, },
accountType: { accountType: {
name: 'account.field.type', name: 'account.field.type',

View File

@@ -1,7 +1,7 @@
import { MiddlewareConsumer, Module, RequestMethod } from '@nestjs/common'; import { MiddlewareConsumer, Module, RequestMethod } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config'; import { ConfigModule, ConfigService } from '@nestjs/config';
import { EventEmitterModule } from '@nestjs/event-emitter'; import { EventEmitterModule } from '@nestjs/event-emitter';
import { APP_INTERCEPTOR } from '@nestjs/core'; import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { join } from 'path'; import { join } from 'path';
import { ServeStaticModule } from '@nestjs/serve-static'; import { ServeStaticModule } from '@nestjs/serve-static';
import { RedisModule } from '@liaoliaots/nestjs-redis'; import { RedisModule } from '@liaoliaots/nestjs-redis';
@@ -95,6 +95,8 @@ import { BankingCategorizeModule } from '../BankingCategorize/BankingCategorize.
import { TenantModelsInitializeModule } from '../Tenancy/TenantModelsInitialize.module'; import { TenantModelsInitializeModule } from '../Tenancy/TenantModelsInitialize.module';
import { BillLandedCostsModule } from '../BillLandedCosts/BillLandedCosts.module'; import { BillLandedCostsModule } from '../BillLandedCosts/BillLandedCosts.module';
import { SocketModule } from '../Socket/Socket.module'; import { SocketModule } from '../Socket/Socket.module';
import { ThrottlerGuard } from '@nestjs/throttler';
import { AppThrottleModule } from './AppThrottle.module';
@Module({ @Module({
imports: [ imports: [
@@ -126,6 +128,7 @@ import { SocketModule } from '../Socket/Socket.module';
], ],
}), }),
PassportModule, PassportModule,
AppThrottleModule,
BullModule.forRootAsync({ BullModule.forRootAsync({
imports: [ConfigModule], imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({ useFactory: async (configService: ConfigService) => ({
@@ -231,6 +234,10 @@ import { SocketModule } from '../Socket/Socket.module';
], ],
controllers: [AppController], controllers: [AppController],
providers: [ providers: [
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
{ {
provide: APP_INTERCEPTOR, provide: APP_INTERCEPTOR,
useClass: SerializeInterceptor, useClass: SerializeInterceptor,

View File

@@ -0,0 +1,48 @@
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { ThrottlerModule } from '@nestjs/throttler';
import { ThrottlerStorageRedisService } from '@nest-lab/throttler-storage-redis';
@Module({
imports: [
ThrottlerModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => {
const host = configService.get<string>('redis.host') || 'localhost';
const port = Number(configService.get<number>('redis.port') || 6379);
const password = configService.get<string>('redis.password');
const db = configService.get<number>('redis.db');
const globalTtl = configService.get<number>('throttle.global.ttl');
const globalLimit = configService.get<number>('throttle.global.limit');
const authTtl = configService.get<number>('throttle.auth.ttl');
const authLimit = configService.get<number>('throttle.auth.limit');
return {
throttlers: [
{
name: 'default',
ttl: globalTtl,
limit: globalLimit,
},
{
name: 'auth',
ttl: authTtl,
limit: authLimit,
},
],
storage: new ThrottlerStorageRedisService({
host,
port,
password,
db,
}),
};
},
}),
],
})
export class AppThrottleModule { }

View File

@@ -8,6 +8,7 @@ import {
Request, Request,
UseGuards, UseGuards,
} from '@nestjs/common'; } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { import {
ApiTags, ApiTags,
ApiOperation, ApiOperation,
@@ -28,6 +29,7 @@ import { SystemUser } from '../System/models/SystemUser';
@ApiTags('Auth') @ApiTags('Auth')
@ApiExcludeController() @ApiExcludeController()
@PublicRoute() @PublicRoute()
@Throttle({ auth: {} })
export class AuthController { export class AuthController {
constructor( constructor(
private readonly authApp: AuthenticationApplication, private readonly authApp: AuthenticationApplication,

View File

@@ -1,4 +1,4 @@
import { Controller, Post, Param, Get, Put } from '@nestjs/common'; import { Controller, Post, Param, Get, Put, Body } from '@nestjs/common';
import { GenerateApiKey } from './commands/GenerateApiKey.service'; import { GenerateApiKey } from './commands/GenerateApiKey.service';
import { GetApiKeysService } from './queries/GetApiKeys.service'; import { GetApiKeysService } from './queries/GetApiKeys.service';
import { import {
@@ -8,6 +8,8 @@ import {
ApiParam, ApiParam,
ApiExtraModels, ApiExtraModels,
getSchemaPath, getSchemaPath,
ApiBody,
ApiProperty,
} from '@nestjs/swagger'; } from '@nestjs/swagger';
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders'; import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
import { import {
@@ -16,6 +18,20 @@ import {
ApiKeyListResponseDto, ApiKeyListResponseDto,
ApiKeyListItemDto, ApiKeyListItemDto,
} from './dtos/ApiKey.dto'; } from './dtos/ApiKey.dto';
import { IsString, MaxLength } from 'class-validator';
import { IsOptional } from '@/common/decorators/Validators';
class GenerateApiKeyDto {
@IsOptional()
@IsString()
@MaxLength(255)
@ApiProperty({
description: 'Optional name for the API key',
required: false,
example: 'My API Key',
})
name?: string;
}
@Controller('api-keys') @Controller('api-keys')
@ApiTags('Api keys') @ApiTags('Api keys')
@@ -33,13 +49,14 @@ export class AuthApiKeysController {
@Post('generate') @Post('generate')
@ApiOperation({ summary: 'Generate a new API key' }) @ApiOperation({ summary: 'Generate a new API key' })
@ApiBody({ type: GenerateApiKeyDto })
@ApiResponse({ @ApiResponse({
status: 201, status: 201,
description: 'The generated API key', description: 'The generated API key',
type: ApiKeyResponseDto, type: ApiKeyResponseDto,
}) })
async generate() { async generate(@Body() body: GenerateApiKeyDto) {
return this.generateApiKeyService.generate(); return this.generateApiKeyService.generate(body.name);
} }
@Put(':id/revoke') @Put(':id/revoke')

View File

@@ -6,6 +6,7 @@ import {
} from '@nestjs/swagger'; } from '@nestjs/swagger';
import { GetAuthenticatedAccount } from './queries/GetAuthedAccount.service'; import { GetAuthenticatedAccount } from './queries/GetAuthedAccount.service';
import { Controller, Get, Post } from '@nestjs/common'; import { Controller, Get, Post } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { IgnoreTenantSeededRoute } from '../Tenancy/EnsureTenantIsSeeded.guards'; import { IgnoreTenantSeededRoute } from '../Tenancy/EnsureTenantIsSeeded.guards';
import { IgnoreTenantInitializedRoute } from '../Tenancy/EnsureTenantIsInitialized.guard'; import { IgnoreTenantInitializedRoute } from '../Tenancy/EnsureTenantIsInitialized.guard';
import { AuthenticationApplication } from './AuthApplication.sevice'; import { AuthenticationApplication } from './AuthApplication.sevice';
@@ -18,6 +19,7 @@ import { IgnoreUserVerifiedRoute } from './guards/EnsureUserVerified.guard';
@IgnoreTenantSeededRoute() @IgnoreTenantSeededRoute()
@IgnoreTenantInitializedRoute() @IgnoreTenantInitializedRoute()
@IgnoreUserVerifiedRoute() @IgnoreUserVerifiedRoute()
@Throttle({ auth: {} })
export class AuthedController { export class AuthedController {
constructor( constructor(
private readonly getAuthedAccountService: GetAuthenticatedAccount, private readonly getAuthedAccountService: GetAuthenticatedAccount,

View File

@@ -16,6 +16,7 @@ import {
import { defaultTo } from 'ramda'; import { defaultTo } from 'ramda';
import { ERRORS } from '../Auth.constants'; import { ERRORS } from '../Auth.constants';
import { hashPassword } from '../Auth.utils'; import { hashPassword } from '../Auth.utils';
import { ClsService } from 'nestjs-cls';
@Injectable() @Injectable()
export class AuthSignupService { export class AuthSignupService {
@@ -29,6 +30,7 @@ export class AuthSignupService {
private readonly configService: ConfigService, private readonly configService: ConfigService,
private readonly eventEmitter: EventEmitter2, private readonly eventEmitter: EventEmitter2,
private readonly tenantsManager: TenantsManagerService, private readonly tenantsManager: TenantsManagerService,
private readonly clsService: ClsService,
@Inject(SystemUser.name) @Inject(SystemUser.name)
private readonly systemUserModel: typeof SystemUser, private readonly systemUserModel: typeof SystemUser,
@@ -70,6 +72,11 @@ export class AuthSignupService {
tenantId: tenant.id, tenantId: tenant.id,
inviteAcceptedAt, inviteAcceptedAt,
}); });
// Set the user in the cls service.
this.clsService.set('tenantId', user.tenantId);
this.clsService.set('userId', user.id);
this.clsService.set('organizationId', tenant.organizationId);
// Triggers signed up event. // Triggers signed up event.
await this.eventEmitter.emitAsync(events.auth.signUp, { await this.eventEmitter.emitAsync(events.auth.signUp, {
signupDTO, signupDTO,

View File

@@ -15,9 +15,10 @@ export class GenerateApiKey {
/** /**
* Generates a new secure API key for the current tenant and system user. * Generates a new secure API key for the current tenant and system user.
* The key is saved in the database and returned (only the key and id for security). * The key is saved in the database and returned (only the key and id for security).
* @param {string} name - Optional name for the API key.
* @returns {Promise<{ key: string; id: number }>} The generated API key and its database id. * @returns {Promise<{ key: string; id: number }>} The generated API key and its database id.
*/ */
async generate() { async generate(name?: string) {
const tenant = await this.tenancyContext.getTenant(); const tenant = await this.tenancyContext.getTenant();
const user = await this.tenancyContext.getSystemUser(); const user = await this.tenancyContext.getSystemUser();
@@ -26,6 +27,7 @@ export class GenerateApiKey {
// Save the API key to the database // Save the API key to the database
const apiKeyRecord = await this.apiKeyModel.query().insert({ const apiKeyRecord = await this.apiKeyModel.query().insert({
key, key,
name,
tenantId: tenant.id, tenantId: tenant.id,
userId: user.id, userId: user.id,
createdAt: new Date(), createdAt: new Date(),

View File

@@ -29,6 +29,12 @@ export class ApiKeyListItemDto {
@ApiProperty({ example: 'My API Key', description: 'API key name' }) @ApiProperty({ example: 'My API Key', description: 'API key name' })
name?: string; name?: string;
@ApiProperty({
example: 'bc_1234...',
description: 'First 8 characters of the API key token',
})
token: string;
@ApiProperty({ @ApiProperty({
example: '2024-01-01T00:00:00.000Z', example: '2024-01-01T00:00:00.000Z',
description: 'Creation date', description: 'Creation date',

View File

@@ -1,7 +1,16 @@
import { Transformer } from '@/modules/Transformer/Transformer'; import { Transformer } from '@/modules/Transformer/Transformer';
export class GetApiKeysTransformer extends Transformer { export class GetApiKeysTransformer extends Transformer {
public includeAttributes = (): string[] => {
return ['token'];
};
public excludeAttributes = (): string[] => { public excludeAttributes = (): string[] => {
return ['tenantId']; return ['tenantId'];
}; };
public token(apiKey) {
return apiKey.key ? `${apiKey.key.substring(0, 8)}...` : '';
}
} }

View File

@@ -1,7 +1,7 @@
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { Knex } from 'knex'; import { Knex } from 'knex';
import * as yup from 'yup'; import * as yup from 'yup';
import uniqid from 'uniqid'; import * as uniqid from 'uniqid';
import { Importable } from '../../Import/Importable'; import { Importable } from '../../Import/Importable';
import { CreateUncategorizedTransactionService } from './CreateUncategorizedTransaction.service'; import { CreateUncategorizedTransactionService } from './CreateUncategorizedTransaction.service';
import { ImportableContext } from '../../Import/interfaces'; import { ImportableContext } from '../../Import/interfaces';
@@ -9,8 +9,10 @@ import { BankTransactionsSampleData } from '../../BankingTransactions/constants'
import { Account } from '@/modules/Accounts/models/Account.model'; import { Account } from '@/modules/Accounts/models/Account.model';
import { CreateUncategorizedTransactionDTO } from '../types/BankingCategorize.types'; import { CreateUncategorizedTransactionDTO } from '../types/BankingCategorize.types';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel'; import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { ImportableService } from '../../Import/decorators/Import.decorator';
import { UncategorizedBankTransaction } from '../../BankingTransactions/models/UncategorizedBankTransaction';
@Injectable() @Injectable()
@ImportableService({ name: UncategorizedBankTransaction.name })
export class UncategorizedTransactionsImportable extends Importable { export class UncategorizedTransactionsImportable extends Importable {
constructor( constructor(
private readonly createUncategorizedTransaction: CreateUncategorizedTransactionService, private readonly createUncategorizedTransaction: CreateUncategorizedTransactionService,

View File

@@ -1,6 +1,6 @@
import * as moment from 'moment'; import * as moment from 'moment';
import * as R from 'ramda'; import * as R from 'ramda';
import { isEmpty, sumBy } from 'lodash'; import { isEmpty, round, sumBy } from 'lodash';
import { ERRORS, MatchedTransactionPOJO } from './types'; import { ERRORS, MatchedTransactionPOJO } from './types';
import { ServiceError } from '../Items/ServiceError'; import { ServiceError } from '../Items/ServiceError';
@@ -22,18 +22,24 @@ export const sortClosestMatchTransactions = (
}; };
export const sumMatchTranasctions = (transactions: Array<any>) => { export const sumMatchTranasctions = (transactions: Array<any>) => {
return transactions.reduce( const total = transactions.reduce(
(total, item) => (sum, item) => {
total + const amount = parseFloat(item.amount) || 0;
(item.transactionNormal === 'debit' ? 1 : -1) * parseFloat(item.amount), const multiplier = item.transactionNormal === 'debit' ? 1 : -1;
return sum + multiplier * amount;
},
0 0
); );
// Round to 2 decimal places to avoid floating-point precision issues
return round(total, 2);
}; };
export const sumUncategorizedTransactions = ( export const sumUncategorizedTransactions = (
uncategorizedTransactions: Array<any> uncategorizedTransactions: Array<any>
) => { ) => {
return sumBy(uncategorizedTransactions, 'amount'); const total = sumBy(uncategorizedTransactions, 'amount');
// Round to 2 decimal places to avoid floating-point precision issues
return round(total, 2);
}; };
export const validateUncategorizedTransactionsNotMatched = ( export const validateUncategorizedTransactionsNotMatched = (

View File

@@ -100,7 +100,10 @@ export class MatchBankTransactions {
); );
// Validates the total given matching transcations whether is not equal // Validates the total given matching transcations whether is not equal
// uncategorized transaction amount. // uncategorized transaction amount.
if (totalUncategorizedTransactions !== totalMatchedTranasctions) { // Use tolerance-based comparison to handle floating-point precision issues
const tolerance = 0.01; // Allow 0.01 difference for floating-point precision
const difference = Math.abs(totalUncategorizedTransactions - totalMatchedTranasctions);
if (difference > tolerance) {
throw new ServiceError(ERRORS.TOTAL_MATCHING_TRANSACTIONS_INVALID); throw new ServiceError(ERRORS.TOTAL_MATCHING_TRANSACTIONS_INVALID);
} }
} }

View File

@@ -12,24 +12,30 @@ export class MatchTransactionsTypes {
private static registry: MatchTransactionsTypesRegistry; private static registry: MatchTransactionsTypesRegistry;
/** /**
* Consttuctor method. * Constructor method.
*/ */
constructor() { constructor(
private readonly getMatchedInvoicesService: GetMatchedTransactionsByInvoices,
private readonly getMatchedBillsService: GetMatchedTransactionsByBills,
private readonly getMatchedExpensesService: GetMatchedTransactionsByExpenses,
private readonly getMatchedManualJournalsService: GetMatchedTransactionsByManualJournals,
private readonly getMatchedCashflowService: GetMatchedTransactionsByCashflow,
) {
this.boot(); this.boot();
} }
get registered() { get registered() {
return [ return [
{ type: 'SaleInvoice', service: GetMatchedTransactionsByInvoices }, { type: 'SaleInvoice', service: this.getMatchedInvoicesService },
{ type: 'Bill', service: GetMatchedTransactionsByBills }, { type: 'Bill', service: this.getMatchedBillsService },
{ type: 'Expense', service: GetMatchedTransactionsByExpenses }, { type: 'Expense', service: this.getMatchedExpensesService },
{ {
type: 'ManualJournal', type: 'ManualJournal',
service: GetMatchedTransactionsByManualJournals, service: this.getMatchedManualJournalsService,
}, },
{ {
type: 'CashflowTransaction', type: 'CashflowTransaction',
service: GetMatchedTransactionsByCashflow, service: this.getMatchedCashflowService,
}, },
]; ];
} }
@@ -50,14 +56,13 @@ export class MatchTransactionsTypes {
* Boots all the registered importables. * Boots all the registered importables.
*/ */
public boot() { public boot() {
if (!MatchTransactionsTypes.registry) {
const instance = MatchTransactionsTypesRegistry.getInstance(); const instance = MatchTransactionsTypesRegistry.getInstance();
// Always register services to ensure they're available
this.registered.forEach((registered) => { this.registered.forEach((registered) => {
// const serviceInstanace = Container.get(registered.service); instance.register(registered.type, registered.service);
// instance.register(registered.type, serviceInstanace);
}); });
MatchTransactionsTypes.registry = instance; MatchTransactionsTypes.registry = instance;
} }
} }
}

View File

@@ -1,4 +1,4 @@
import { Type } from 'class-transformer'; import { Transform, Type } from 'class-transformer';
import { import {
IsBoolean, IsBoolean,
IsEnum, IsEnum,
@@ -7,6 +7,7 @@ import {
IsPositive, IsPositive,
} from 'class-validator'; } from 'class-validator';
import { ApiPropertyOptional } from '@nestjs/swagger'; import { ApiPropertyOptional } from '@nestjs/swagger';
import { parseBoolean } from '@/utils/parse-boolean';
export class NumberFormatQueryDto { export class NumberFormatQueryDto {
@ApiPropertyOptional({ @ApiPropertyOptional({
@@ -24,6 +25,7 @@ export class NumberFormatQueryDto {
example: false, example: false,
}) })
@IsBoolean() @IsBoolean()
@Transform(({ value }) => parseBoolean(value, false))
@IsOptional() @IsOptional()
readonly divideOn1000: boolean; readonly divideOn1000: boolean;
@@ -32,6 +34,7 @@ export class NumberFormatQueryDto {
example: true, example: true,
}) })
@IsBoolean() @IsBoolean()
@Transform(({ value }) => parseBoolean(value, false))
@IsOptional() @IsOptional()
readonly showZero: boolean; readonly showZero: boolean;

View File

@@ -0,0 +1,72 @@
export const UncategorizedBankTransactionMeta = {
defaultFilterField: 'createdAt',
defaultSort: {
sortOrder: 'DESC',
sortField: 'created_at',
},
importable: true,
fields: {
date: {
name: 'Date',
column: 'date',
fieldType: 'date',
},
payee: {
name: 'Payee',
column: 'payee',
fieldType: 'text',
},
description: {
name: 'Description',
column: 'description',
fieldType: 'text',
},
referenceNo: {
name: 'Reference No.',
column: 'reference_no',
fieldType: 'text',
},
amount: {
name: 'Amount',
column: 'Amount',
fieldType: 'numeric',
required: true,
},
account: {
name: 'Account',
column: 'account_id',
fieldType: 'relation',
to: { model: 'Account', to: 'id' },
},
createdAt: {
name: 'Created At',
column: 'createdAt',
fieldType: 'date',
importable: false,
},
},
fields2: {
date: {
name: 'Date',
fieldType: 'date',
required: true,
},
payee: {
name: 'Payee',
fieldType: 'text',
},
description: {
name: 'Description',
fieldType: 'text',
},
referenceNo: {
name: 'Reference No.',
fieldType: 'text',
},
amount: {
name: 'Amount',
fieldType: 'number',
required: true,
},
},
};

View File

@@ -2,7 +2,10 @@
import * as moment from 'moment'; import * as moment from 'moment';
import { Model } from 'objection'; import { Model } from 'objection';
import { TenantBaseModel } from '@/modules/System/models/TenantBaseModel'; import { TenantBaseModel } from '@/modules/System/models/TenantBaseModel';
import { UncategorizedBankTransactionMeta } from './UncategorizedBankTransaction.meta';
import { InjectModelMeta } from '@/modules/Tenancy/TenancyModels/decorators/InjectModelMeta.decorator';
@InjectModelMeta(UncategorizedBankTransactionMeta)
export class UncategorizedBankTransaction extends TenantBaseModel { export class UncategorizedBankTransaction extends TenantBaseModel {
readonly amount!: number; readonly amount!: number;
readonly date!: Date | string; readonly date!: Date | string;

View File

@@ -14,6 +14,7 @@ import { BranchesSettingsService } from '../Branches/BranchesSettings';
import { BillPaymentsController } from './BillPayments.controller'; import { BillPaymentsController } from './BillPayments.controller';
import { BillPaymentGLEntries } from './commands/BillPaymentGLEntries'; import { BillPaymentGLEntries } from './commands/BillPaymentGLEntries';
import { BillPaymentGLEntriesSubscriber } from './subscribers/BillPaymentGLEntriesSubscriber'; import { BillPaymentGLEntriesSubscriber } from './subscribers/BillPaymentGLEntriesSubscriber';
import { BillPaymentBillSyncSubscriber } from './subscribers/BillPaymentBillSyncSubscriber';
import { LedgerModule } from '../Ledger/Ledger.module'; import { LedgerModule } from '../Ledger/Ledger.module';
import { AccountsModule } from '../Accounts/Accounts.module'; import { AccountsModule } from '../Accounts/Accounts.module';
import { BillPaymentsExportable } from './queries/BillPaymentsExportable'; import { BillPaymentsExportable } from './queries/BillPaymentsExportable';
@@ -39,6 +40,7 @@ import { BillPaymentsPages } from './commands/BillPaymentsPages.service';
TenancyContext, TenancyContext,
BillPaymentGLEntries, BillPaymentGLEntries,
BillPaymentGLEntriesSubscriber, BillPaymentGLEntriesSubscriber,
BillPaymentBillSyncSubscriber,
BillPaymentsExportable, BillPaymentsExportable,
BillPaymentsImportable, BillPaymentsImportable,
GetBillPaymentsService, GetBillPaymentsService,

View File

@@ -103,11 +103,19 @@ export class CreateBillPaymentService {
} as IBillPaymentCreatingPayload); } as IBillPaymentCreatingPayload);
// Writes the bill payment graph to the storage. // Writes the bill payment graph to the storage.
const billPayment = await this.billPaymentModel() const insertedBillPayment = await this.billPaymentModel()
.query(trx) .query(trx)
.insertGraphAndFetch({ .insertGraphAndFetch({
...billPaymentObj, ...billPaymentObj,
}); });
// Fetch the bill payment with entries to ensure they're loaded for the subscriber.
const billPayment = await this.billPaymentModel()
.query(trx)
.withGraphFetched('entries')
.findById(insertedBillPayment.id)
.throwIfNotFound();
// Triggers `onBillPaymentCreated` event. // Triggers `onBillPaymentCreated` event.
await this.eventPublisher.emitAsync(events.billPayment.onCreated, { await this.eventPublisher.emitAsync(events.billPayment.onCreated, {
billPayment, billPayment,

View File

@@ -116,12 +116,20 @@ export class EditBillPayment {
} as IBillPaymentEditingPayload); } as IBillPaymentEditingPayload);
// Edits the bill payment transaction graph on the storage. // Edits the bill payment transaction graph on the storage.
const billPayment = await this.billPaymentModel() await this.billPaymentModel()
.query(trx) .query(trx)
.upsertGraphAndFetch({ .upsertGraph({
id: billPaymentId, id: billPaymentId,
...billPaymentObj, ...billPaymentObj,
}); });
// Fetch the bill payment with entries to ensure they're loaded for the subscriber.
const billPayment = await this.billPaymentModel()
.query(trx)
.withGraphFetched('entries')
.findById(billPaymentId)
.throwIfNotFound();
// Triggers `onBillPaymentEdited` event. // Triggers `onBillPaymentEdited` event.
await this.eventPublisher.emitAsync(events.billPayment.onEdited, { await this.eventPublisher.emitAsync(events.billPayment.onEdited, {
billPaymentId, billPaymentId,

View File

@@ -104,6 +104,12 @@ export class BillPaymentResponseDto {
@ApiProperty({ description: 'The formatted amount', example: '100.00 USD' }) @ApiProperty({ description: 'The formatted amount', example: '100.00 USD' })
formattedAmount: string; formattedAmount: string;
@ApiProperty({ description: 'The formatted total', example: '100.00 USD' })
formattedTotal: string;
@ApiProperty({ description: 'The formatted subtotal', example: '100.00 USD' })
formattedSubtotal: string;
@ApiProperty({ @ApiProperty({
description: 'The date when the payment was created', description: 'The date when the payment was created',
example: '2024-01-01T12:00:00Z', example: '2024-01-01T12:00:00Z',

View File

@@ -167,7 +167,7 @@ export const BillPaymentMeta = {
name: 'bill_payment.field.payment_number', name: 'bill_payment.field.payment_number',
fieldType: 'text', fieldType: 'text',
unique: true, unique: true,
importHint: 'The payment number should be unique.', importHint: 'bill_payment.field.payment_number_hint',
}, },
paymentAccountId: { paymentAccountId: {
name: 'bill_payment.field.payment_account', name: 'bill_payment.field.payment_account',
@@ -175,7 +175,7 @@ export const BillPaymentMeta = {
relationModel: 'Account', relationModel: 'Account',
relationImportMatch: ['name', 'code'], relationImportMatch: ['name', 'code'],
required: true, required: true,
importHint: 'Matches the account name or code.', importHint: 'account.field.account_hint',
}, },
exchangeRate: { exchangeRate: {
name: 'bill_payment.field.exchange_rate', name: 'bill_payment.field.exchange_rate',
@@ -203,7 +203,7 @@ export const BillPaymentMeta = {
relationModel: 'Bill', relationModel: 'Bill',
relationImportMatch: 'billNumber', relationImportMatch: 'billNumber',
required: true, required: true,
importHint: 'Matches the bill number.', importHint: 'bill_payment.field.bill_hint',
}, },
paymentAmount: { paymentAmount: {
name: 'bill_payment.field.entries.payment_amount', name: 'bill_payment.field.entries.payment_amount',
@@ -213,7 +213,7 @@ export const BillPaymentMeta = {
}, },
}, },
branchId: { branchId: {
name: 'Branch', name: 'invoice.field.branch',
fieldType: 'relation', fieldType: 'relation',
relationModel: 'Branch', relationModel: 'Branch',
relationImportMatch: ['name', 'code'], relationImportMatch: ['name', 'code'],

View File

@@ -13,6 +13,8 @@ export class BillPaymentTransformer extends Transformer {
'formattedPaymentDate', 'formattedPaymentDate',
'formattedCreatedAt', 'formattedCreatedAt',
'formattedAmount', 'formattedAmount',
'formattedTotal',
'formattedSubtotal',
'entries', 'entries',
'attachments', 'attachments',
]; ];
@@ -47,6 +49,29 @@ export class BillPaymentTransformer extends Transformer {
}); });
}; };
/**
* Retrieves the formatted total.
* @param {IBillPayment} billPayment
* @returns {string}
*/
protected formattedTotal = (billPayment: BillPayment): string => {
return this.formatNumber(billPayment.amount, {
currencyCode: billPayment.currencyCode,
money: true,
});
};
/**
* Retrieves the formatted subtotal.
* @param {IBillPayment} billPayment
* @returns {string}
*/
protected formattedSubtotal = (billPayment: BillPayment): string => {
return this.formatNumber(billPayment.amount, {
currencyCode: billPayment.currencyCode,
});
};
/** /**
* Retreives the bill payment entries. * Retreives the bill payment entries.
*/ */

View File

@@ -16,8 +16,6 @@ export class BillPaymentsExportable extends Exportable {
/** /**
* Retrieves the accounts data to exportable sheet. * Retrieves the accounts data to exportable sheet.
* @param {number} tenantId
* @returns
*/ */
public async exportable(query: any) { public async exportable(query: any) {
const filterQuery = (builder) => { const filterQuery = (builder) => {

View File

@@ -0,0 +1,80 @@
import {
IBillPaymentEventCreatedPayload,
IBillPaymentEventDeletedPayload,
IBillPaymentEventEditedPayload,
} from '../types/BillPayments.types';
import { BillPaymentBillSync } from '../commands/BillPaymentBillSync.service';
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { events } from '@/common/events/events';
@Injectable()
export class BillPaymentBillSyncSubscriber {
/**
* @param {BillPaymentBillSync} billPaymentBillSync - Bill payment bill sync service.
*/
constructor(private readonly billPaymentBillSync: BillPaymentBillSync) { }
/**
* Handle bill increment/decrement payment amount
* once created, edited or deleted.
*/
@OnEvent(events.billPayment.onCreated)
async handleBillIncrementPaymentOnceCreated({
billPayment,
trx,
}: IBillPaymentEventCreatedPayload) {
// Ensure entries are available - they should be included in insertGraphAndFetch
const entries = billPayment.entries || [];
await this.billPaymentBillSync.saveChangeBillsPaymentAmount(
entries.map((entry) => ({
billId: entry.billId,
paymentAmount: entry.paymentAmount,
})),
null,
trx,
);
}
/**
* Handle bill increment/decrement payment amount once edited.
*/
@OnEvent(events.billPayment.onEdited)
async handleBillIncrementPaymentOnceEdited({
billPayment,
oldBillPayment,
trx,
}: IBillPaymentEventEditedPayload) {
const entries = billPayment.entries || [];
const oldEntries = oldBillPayment?.entries || null;
await this.billPaymentBillSync.saveChangeBillsPaymentAmount(
entries.map((entry) => ({
billId: entry.billId,
paymentAmount: entry.paymentAmount,
})),
oldEntries,
trx,
);
}
/**
* Handle revert bills payment amount once bill payment deleted.
*/
@OnEvent(events.billPayment.onDeleted)
async handleBillDecrementPaymentAmount({
oldBillPayment,
trx,
}: IBillPaymentEventDeletedPayload) {
const oldEntries = oldBillPayment.entries || [];
await this.billPaymentBillSync.saveChangeBillsPaymentAmount(
oldEntries.map((entry) => ({
billId: entry.billId,
paymentAmount: 0,
})),
oldEntries,
trx,
);
}
}

View File

@@ -9,6 +9,8 @@ import { Injectable } from '@nestjs/common';
import { GetBillsService } from './queries/GetBills.service'; import { GetBillsService } from './queries/GetBills.service';
import { CreateBillDto, EditBillDto } from './dtos/Bill.dto'; import { CreateBillDto, EditBillDto } from './dtos/Bill.dto';
import { GetBillPaymentTransactionsService } from './queries/GetBillPayments'; import { GetBillPaymentTransactionsService } from './queries/GetBillPayments';
import { BulkDeleteBillsService } from './BulkDeleteBills.service';
import { ValidateBulkDeleteBillsService } from './ValidateBulkDeleteBills.service';
// import { GetBillPayments } from './queries/GetBillPayments'; // import { GetBillPayments } from './queries/GetBillPayments';
// import { GetBills } from './queries/GetBills'; // import { GetBills } from './queries/GetBills';
@@ -23,6 +25,8 @@ export class BillsApplication {
private openBillService: OpenBillService, private openBillService: OpenBillService,
private getBillsService: GetBillsService, private getBillsService: GetBillsService,
private getBillPaymentTransactionsService: GetBillPaymentTransactionsService, private getBillPaymentTransactionsService: GetBillPaymentTransactionsService,
private bulkDeleteBillsService: BulkDeleteBillsService,
private validateBulkDeleteBillsService: ValidateBulkDeleteBillsService,
) { } ) { }
/** /**
@@ -53,6 +57,25 @@ export class BillsApplication {
return this.deleteBillService.deleteBill(billId); return this.deleteBillService.deleteBill(billId);
} }
/**
* Deletes multiple bills.
* @param {number[]} billIds
*/
public bulkDeleteBills(
billIds: number[],
options?: { skipUndeletable?: boolean },
) {
return this.bulkDeleteBillsService.bulkDeleteBills(billIds, options);
}
/**
* Validates which bills can be deleted.
* @param {number[]} billIds
*/
public validateBulkDeleteBills(billIds: number[]) {
return this.validateBulkDeleteBillsService.validateBulkDeleteBills(billIds);
}
/** /**
* Retrieve bills data table list. * Retrieve bills data table list.
* @param {IBillsFilter} billsFilter - * @param {IBillsFilter} billsFilter -

View File

@@ -22,15 +22,52 @@ import { CreateBillDto, EditBillDto } from './dtos/Bill.dto';
import { BillResponseDto } from './dtos/BillResponse.dto'; import { BillResponseDto } from './dtos/BillResponse.dto';
import { PaginatedResponseDto } from '@/common/dtos/PaginatedResults.dto'; import { PaginatedResponseDto } from '@/common/dtos/PaginatedResults.dto';
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders'; import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
import {
BulkDeleteDto,
ValidateBulkDeleteResponseDto,
} from '@/common/dtos/BulkDelete.dto';
@Controller('bills') @Controller('bills')
@ApiTags('Bills') @ApiTags('Bills')
@ApiExtraModels(BillResponseDto) @ApiExtraModels(BillResponseDto)
@ApiExtraModels(PaginatedResponseDto) @ApiExtraModels(PaginatedResponseDto)
@ApiCommonHeaders() @ApiCommonHeaders()
@ApiExtraModels(ValidateBulkDeleteResponseDto)
export class BillsController { export class BillsController {
constructor(private billsApplication: BillsApplication) { } constructor(private billsApplication: BillsApplication) { }
@Post('validate-bulk-delete')
@ApiOperation({
summary: 'Validate which bills can be deleted and return the results.',
})
@ApiResponse({
status: 200,
description:
'Validation completed with counts and IDs of deletable and non-deletable bills.',
schema: {
$ref: getSchemaPath(ValidateBulkDeleteResponseDto),
},
})
validateBulkDeleteBills(
@Body() bulkDeleteDto: BulkDeleteDto,
): Promise<ValidateBulkDeleteResponseDto> {
return this.billsApplication.validateBulkDeleteBills(bulkDeleteDto.ids);
}
@Post('bulk-delete')
@ApiOperation({ summary: 'Deletes multiple bills.' })
@ApiResponse({
status: 200,
description: 'Bills deleted successfully',
})
bulkDeleteBills(
@Body() bulkDeleteDto: BulkDeleteDto,
): Promise<void> {
return this.billsApplication.bulkDeleteBills(bulkDeleteDto.ids, {
skipUndeletable: bulkDeleteDto.skipUndeletable ?? false,
});
}
@Post() @Post()
@ApiOperation({ summary: 'Create a new bill.' }) @ApiOperation({ summary: 'Create a new bill.' })
createBill(@Body() billDTO: CreateBillDto) { createBill(@Body() billDTO: CreateBillDto) {

View File

@@ -29,6 +29,8 @@ import { InventoryCostModule } from '../InventoryCost/InventoryCost.module';
import { BillsExportable } from './commands/BillsExportable'; import { BillsExportable } from './commands/BillsExportable';
import { BillsImportable } from './commands/BillsImportable'; import { BillsImportable } from './commands/BillsImportable';
import { GetBillPaymentTransactionsService } from './queries/GetBillPayments'; import { GetBillPaymentTransactionsService } from './queries/GetBillPayments';
import { BulkDeleteBillsService } from './BulkDeleteBills.service';
import { ValidateBulkDeleteBillsService } from './ValidateBulkDeleteBills.service';
@Module({ @Module({
imports: [ imports: [
@@ -63,6 +65,8 @@ import { GetBillPaymentTransactionsService } from './queries/GetBillPayments';
BillsExportable, BillsExportable,
BillsImportable, BillsImportable,
GetBillPaymentTransactionsService, GetBillPaymentTransactionsService,
BulkDeleteBillsService,
ValidateBulkDeleteBillsService,
], ],
controllers: [BillsController], controllers: [BillsController],
exports: [BillsExportable, BillsImportable], exports: [BillsExportable, BillsImportable],

View File

@@ -0,0 +1,36 @@
import { Injectable } from '@nestjs/common';
import { Knex } from 'knex';
import { PromisePool } from '@supercharge/promise-pool';
import { castArray, uniq } from 'lodash';
import { DeleteBill } from './commands/DeleteBill.service';
@Injectable()
export class BulkDeleteBillsService {
constructor(private readonly deleteBillService: DeleteBill) { }
async bulkDeleteBills(
billIds: number | Array<number>,
options?: { skipUndeletable?: boolean },
trx?: Knex.Transaction,
): Promise<void> {
const { skipUndeletable = false } = options ?? {};
const billsIds = uniq(castArray(billIds));
const results = await PromisePool.withConcurrency(1)
.for(billsIds)
.process(async (billId: number) => {
try {
await this.deleteBillService.deleteBill(billId);
} catch (error) {
if (!skipUndeletable) {
throw error;
}
}
});
if (!skipUndeletable && results.errors && results.errors.length > 0) {
throw results.errors[0].raw;
}
}
}

View File

@@ -0,0 +1,51 @@
import { Injectable, Inject } from '@nestjs/common';
import { Knex } from 'knex';
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
import { DeleteBill } from './commands/DeleteBill.service';
@Injectable()
export class ValidateBulkDeleteBillsService {
constructor(
private readonly deleteBillService: DeleteBill,
@Inject(TENANCY_DB_CONNECTION)
private readonly tenantKnex: () => Knex,
) { }
public async validateBulkDeleteBills(billIds: number[]): Promise<{
deletableCount: number;
nonDeletableCount: number;
deletableIds: number[];
nonDeletableIds: number[];
}> {
const trx = await this.tenantKnex().transaction({
isolationLevel: 'read uncommitted',
});
try {
const deletableIds: number[] = [];
const nonDeletableIds: number[] = [];
for (const billId of billIds) {
try {
await this.deleteBillService.deleteBill(billId, trx);
deletableIds.push(billId);
} catch (error) {
nonDeletableIds.push(billId);
}
}
await trx.rollback();
return {
deletableCount: deletableIds.length,
nonDeletableCount: nonDeletableIds.length,
deletableIds,
nonDeletableIds,
};
} catch (error) {
await trx.rollback();
throw error;
}
}
}

View File

@@ -29,9 +29,10 @@ export class DeleteBill {
/** /**
* Deletes the bill with associated entries. * Deletes the bill with associated entries.
* @param {number} billId * @param {number} billId
* @param {Knex.Transaction} trx - Database transaction instance.
* @return {void} * @return {void}
*/ */
public async deleteBill(billId: number) { public async deleteBill(billId: number, trx?: Knex.Transaction) {
// Retrieve the given bill or throw not found error. // Retrieve the given bill or throw not found error.
const oldBill = await this.billModel() const oldBill = await this.billModel()
.query() .query()
@@ -75,6 +76,6 @@ export class DeleteBill {
oldBill, oldBill,
trx, trx,
} as IBIllEventDeletedPayload); } as IBIllEventDeletedPayload);
}); }, trx);
} }
} }

View File

@@ -184,76 +184,76 @@ export const BillMeta = {
}, },
fields2: { fields2: {
billNumber: { billNumber: {
name: 'Bill No.', name: 'bill.field.bill_number',
fieldType: 'text', fieldType: 'text',
required: true, required: true,
}, },
referenceNo: { referenceNo: {
name: 'Reference No.', name: 'bill.field.reference_no',
fieldType: 'text', fieldType: 'text',
}, },
billDate: { billDate: {
name: 'Date', name: 'bill.field.bill_date',
fieldType: 'date', fieldType: 'date',
required: true, required: true,
}, },
dueDate: { dueDate: {
name: 'Due Date', name: 'bill.field.due_date',
fieldType: 'date', fieldType: 'date',
required: true, required: true,
}, },
vendorId: { vendorId: {
name: 'Vendor', name: 'bill.field.vendor',
fieldType: 'relation', fieldType: 'relation',
relationModel: 'Contact', relationModel: 'Contact',
relationImportMatch: 'displayName', relationImportMatch: 'displayName',
required: true, required: true,
}, },
exchangeRate: { exchangeRate: {
name: 'Exchange Rate', name: 'bill.field.exchange_rate',
fieldType: 'number', fieldType: 'number',
}, },
note: { note: {
name: 'Note', name: 'bill.field.note',
fieldType: 'text', fieldType: 'text',
}, },
open: { open: {
name: 'Open', name: 'bill.field.open',
fieldType: 'boolean', fieldType: 'boolean',
}, },
entries: { entries: {
name: 'Entries', name: 'bill.field.entries',
fieldType: 'collection', fieldType: 'collection',
collectionOf: 'object', collectionOf: 'object',
collectionMinLength: 1, collectionMinLength: 1,
required: true, required: true,
fields: { fields: {
itemId: { itemId: {
name: 'Item', name: 'bill.field.item',
fieldType: 'relation', fieldType: 'relation',
relationModel: 'Item', relationModel: 'Item',
relationImportMatch: ['name', 'code'], relationImportMatch: ['name', 'code'],
required: true, required: true,
importHint: 'Matches the item name or code.', importHint: 'bill.field.item_hint',
}, },
rate: { rate: {
name: 'Rate', name: 'bill.field.rate',
fieldType: 'number', fieldType: 'number',
required: true, required: true,
}, },
quantity: { quantity: {
name: 'Quantity', name: 'bill.field.quantity',
fieldType: 'number', fieldType: 'number',
required: true, required: true,
}, },
description: { description: {
name: 'Line Description', name: 'bill.field.description',
fieldType: 'text', fieldType: 'text',
}, },
}, },
}, },
branchId: { branchId: {
name: 'Branch', name: 'invoice.field.branch',
fieldType: 'relation', fieldType: 'relation',
relationModel: 'Branch', relationModel: 'Branch',
relationImportMatch: ['name', 'code'], relationImportMatch: ['name', 'code'],
@@ -261,7 +261,7 @@ export const BillMeta = {
required: true, required: true,
}, },
warehouseId: { warehouseId: {
name: 'Warehouse', name: 'invoice.field.warehouse',
fieldType: 'relation', fieldType: 'relation',
relationModel: 'Warehouse', relationModel: 'Warehouse',
relationImportMatch: ['name', 'code'], relationImportMatch: ['name', 'code'],

View File

@@ -94,6 +94,7 @@ export class BillTransformer extends Transformer {
protected formattedDueAmount = (bill: Bill): string => { protected formattedDueAmount = (bill: Bill): string => {
return this.formatNumber(bill.dueAmount, { return this.formatNumber(bill.dueAmount, {
currencyCode: bill.currencyCode, currencyCode: bill.currencyCode,
money: true,
}); });
}; };
@@ -169,6 +170,7 @@ export class BillTransformer extends Transformer {
protected totalFormatted = (bill: Bill): string => { protected totalFormatted = (bill: Bill): string => {
return this.formatNumber(bill.total, { return this.formatNumber(bill.total, {
currencyCode: bill.currencyCode, currencyCode: bill.currencyCode,
money: true,
}); });
}; };

View File

@@ -7,9 +7,13 @@ import { CreditNotesRefundsApplication } from './CreditNotesRefundsApplication.s
import { CreditNoteRefundsController } from './CreditNoteRefunds.controller'; import { CreditNoteRefundsController } from './CreditNoteRefunds.controller';
import { CreditNotesModule } from '../CreditNotes/CreditNotes.module'; import { CreditNotesModule } from '../CreditNotes/CreditNotes.module';
import { GetCreditNoteRefundsService } from './queries/GetCreditNoteRefunds.service'; import { GetCreditNoteRefundsService } from './queries/GetCreditNoteRefunds.service';
import { RefundCreditNoteGLEntries } from './commands/RefundCreditNoteGLEntries';
import { RefundCreditNoteGLEntriesSubscriber } from '../CreditNotes/subscribers/RefundCreditNoteGLEntriesSubscriber';
import { LedgerModule } from '../Ledger/Ledger.module';
import { AccountsModule } from '../Accounts/Accounts.module';
@Module({ @Module({
imports: [forwardRef(() => CreditNotesModule)], imports: [forwardRef(() => CreditNotesModule), LedgerModule, AccountsModule],
providers: [ providers: [
CreateRefundCreditNoteService, CreateRefundCreditNoteService,
DeleteRefundCreditNoteService, DeleteRefundCreditNoteService,
@@ -17,6 +21,8 @@ import { GetCreditNoteRefundsService } from './queries/GetCreditNoteRefunds.serv
RefundSyncCreditNoteBalanceService, RefundSyncCreditNoteBalanceService,
CreditNotesRefundsApplication, CreditNotesRefundsApplication,
GetCreditNoteRefundsService, GetCreditNoteRefundsService,
RefundCreditNoteGLEntries,
RefundCreditNoteGLEntriesSubscriber,
], ],
exports: [RefundSyncCreditNoteBalanceService], exports: [RefundSyncCreditNoteBalanceService],
controllers: [CreditNoteRefundsController], controllers: [CreditNoteRefundsController],

View File

@@ -1,5 +1,6 @@
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsOptional, IsPositive, IsString } from 'class-validator'; import { ToNumber, IsOptional } from '@/common/decorators/Validators';
import { IsDateString, IsNotEmpty, IsPositive, IsString } from 'class-validator';
import { IsDate } from 'class-validator'; import { IsDate } from 'class-validator';
import { IsNumber } from 'class-validator'; import { IsNumber } from 'class-validator';
@@ -10,8 +11,13 @@ export class CreditNoteRefundDto {
description: 'The id of the from account', description: 'The id of the from account',
example: 1, example: 1,
}) })
@ApiProperty({
description: 'The id of the from account',
example: 1,
})
fromAccountId: number; fromAccountId: number;
@ToNumber()
@IsNumber() @IsNumber()
@IsPositive() @IsPositive()
@IsNotEmpty() @IsNotEmpty()
@@ -21,6 +27,7 @@ export class CreditNoteRefundDto {
}) })
amount: number; amount: number;
@ToNumber()
@IsNumber() @IsNumber()
@IsOptional() @IsOptional()
@IsPositive() @IsPositive()
@@ -30,23 +37,23 @@ export class CreditNoteRefundDto {
}) })
exchangeRate?: number; exchangeRate?: number;
@IsOptional()
@IsString() @IsString()
@IsNotEmpty()
@ApiProperty({ @ApiProperty({
description: 'The reference number of the credit note refund', description: 'The reference number of the credit note refund',
example: '123456', example: '123456',
}) })
referenceNo: string; referenceNo: string;
@IsOptional()
@IsString() @IsString()
@IsNotEmpty()
@ApiProperty({ @ApiProperty({
description: 'The description of the credit note refund', description: 'The description of the credit note refund',
example: 'Credit note refund', example: 'Credit note refund',
}) })
description: string; description: string;
@IsDate() @IsDateString()
@IsNotEmpty() @IsNotEmpty()
@ApiProperty({ @ApiProperty({
description: 'The date of the credit note refund', description: 'The date of the credit note refund',
@@ -54,6 +61,7 @@ export class CreditNoteRefundDto {
}) })
date: Date; date: Date;
@ToNumber()
@IsNumber() @IsNumber()
@IsOptional() @IsOptional()
@ApiProperty({ @ApiProperty({

View File

@@ -0,0 +1,38 @@
import { Injectable } from '@nestjs/common';
import { Knex } from 'knex';
import { PromisePool } from '@supercharge/promise-pool';
import { castArray, uniq } from 'lodash';
import { DeleteCreditNoteService } from './commands/DeleteCreditNote.service';
@Injectable()
export class BulkDeleteCreditNotesService {
constructor(
private readonly deleteCreditNoteService: DeleteCreditNoteService,
) { }
async bulkDeleteCreditNotes(
creditNoteIds: number | Array<number>,
options?: { skipUndeletable?: boolean },
trx?: Knex.Transaction,
): Promise<void> {
const { skipUndeletable = false } = options ?? {};
const notesIds = uniq(castArray(creditNoteIds));
const results = await PromisePool.withConcurrency(1)
.for(notesIds)
.process(async (creditNoteId: number) => {
try {
await this.deleteCreditNoteService.deleteCreditNote(creditNoteId);
} catch (error) {
if (!skipUndeletable) {
throw error;
}
}
});
if (!skipUndeletable && results.errors && results.errors.length > 0) {
throw results.errors[0].raw;
}
}
}

View File

@@ -9,6 +9,8 @@ import { GetCreditNotesService } from './queries/GetCreditNotes.service';
import { CreateCreditNoteDto, EditCreditNoteDto } from './dtos/CreditNote.dto'; import { CreateCreditNoteDto, EditCreditNoteDto } from './dtos/CreditNote.dto';
import { GetCreditNoteState } from './queries/GetCreditNoteState.service'; import { GetCreditNoteState } from './queries/GetCreditNoteState.service';
import { GetCreditNoteService } from './queries/GetCreditNote.service'; import { GetCreditNoteService } from './queries/GetCreditNote.service';
import { BulkDeleteCreditNotesService } from './BulkDeleteCreditNotes.service';
import { ValidateBulkDeleteCreditNotesService } from './ValidateBulkDeleteCreditNotes.service';
@Injectable() @Injectable()
export class CreditNoteApplication { export class CreditNoteApplication {
@@ -20,7 +22,9 @@ export class CreditNoteApplication {
private readonly getCreditNotePdfService: GetCreditNotePdf, private readonly getCreditNotePdfService: GetCreditNotePdf,
private readonly getCreditNotesService: GetCreditNotesService, private readonly getCreditNotesService: GetCreditNotesService,
private readonly getCreditNoteStateService: GetCreditNoteState, private readonly getCreditNoteStateService: GetCreditNoteState,
private readonly getCreditNoteService: GetCreditNoteService private readonly getCreditNoteService: GetCreditNoteService,
private readonly bulkDeleteCreditNotesService: BulkDeleteCreditNotesService,
private readonly validateBulkDeleteCreditNotesService: ValidateBulkDeleteCreditNotesService,
) { } ) { }
/** /**
@@ -97,4 +101,30 @@ export class CreditNoteApplication {
getCreditNote(creditNoteId: number) { getCreditNote(creditNoteId: number) {
return this.getCreditNoteService.getCreditNote(creditNoteId); return this.getCreditNoteService.getCreditNote(creditNoteId);
} }
/**
* Deletes multiple credit notes.
* @param {number[]} creditNoteIds
* @returns {Promise<void>}
*/
bulkDeleteCreditNotes(
creditNoteIds: number[],
options?: { skipUndeletable?: boolean },
) {
return this.bulkDeleteCreditNotesService.bulkDeleteCreditNotes(
creditNoteIds,
options,
);
}
/**
* Validates which credit notes can be deleted.
* @param {number[]} creditNoteIds
* @returns {Promise<{deletableCount: number, nonDeletableCount: number, deletableIds: number[], nonDeletableIds: number[]}>}
*/
validateBulkDeleteCreditNotes(creditNoteIds: number[]) {
return this.validateBulkDeleteCreditNotesService.validateBulkDeleteCreditNotes(
creditNoteIds,
);
}
} }

View File

@@ -1,3 +1,4 @@
import { Response } from 'express';
import { import {
ApiTags, ApiTags,
ApiOperation, ApiOperation,
@@ -11,10 +12,12 @@ import {
Controller, Controller,
Delete, Delete,
Get, Get,
Headers,
Param, Param,
Post, Post,
Put, Put,
Query, Query,
Res,
} from '@nestjs/common'; } from '@nestjs/common';
import { CreditNoteApplication } from './CreditNoteApplication.service'; import { CreditNoteApplication } from './CreditNoteApplication.service';
import { ICreditNotesQueryDTO } from './types/CreditNotes.types'; import { ICreditNotesQueryDTO } from './types/CreditNotes.types';
@@ -22,11 +25,17 @@ import { CreateCreditNoteDto, EditCreditNoteDto } from './dtos/CreditNote.dto';
import { CreditNoteResponseDto } from './dtos/CreditNoteResponse.dto'; import { CreditNoteResponseDto } from './dtos/CreditNoteResponse.dto';
import { PaginatedResponseDto } from '@/common/dtos/PaginatedResults.dto'; import { PaginatedResponseDto } from '@/common/dtos/PaginatedResults.dto';
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders'; import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
import {
BulkDeleteDto,
ValidateBulkDeleteResponseDto,
} from '@/common/dtos/BulkDelete.dto';
import { AcceptType } from '@/constants/accept-type';
@Controller('credit-notes') @Controller('credit-notes')
@ApiTags('Credit Notes') @ApiTags('Credit Notes')
@ApiExtraModels(CreditNoteResponseDto) @ApiExtraModels(CreditNoteResponseDto)
@ApiExtraModels(PaginatedResponseDto) @ApiExtraModels(PaginatedResponseDto)
@ApiExtraModels(ValidateBulkDeleteResponseDto)
@ApiCommonHeaders() @ApiCommonHeaders()
export class CreditNotesController { export class CreditNotesController {
/** /**
@@ -60,8 +69,26 @@ export class CreditNotesController {
}, },
}) })
@ApiResponse({ status: 404, description: 'Credit note not found' }) @ApiResponse({ status: 404, description: 'Credit note not found' })
getCreditNote(@Param('id') creditNoteId: number) { async getCreditNote(
return this.creditNoteApplication.getCreditNote(creditNoteId); @Param('id') creditNoteId: number,
@Headers('accept') acceptHeader: string,
@Res({ passthrough: true }) res: Response,
) {
if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
const [pdfContent, filename] =
await this.creditNoteApplication.getCreditNotePdf(creditNoteId);
res.set({
'Content-Type': 'application/pdf',
'Content-Length': pdfContent.length,
'Content-Disposition': `attachment; filename="${filename}"`,
});
res.status(200).send(pdfContent);
} else {
const creditNote =
await this.creditNoteApplication.getCreditNote(creditNoteId);
return creditNote;
}
} }
@Get() @Get()
@@ -112,6 +139,39 @@ export class CreditNotesController {
return this.creditNoteApplication.openCreditNote(creditNoteId); return this.creditNoteApplication.openCreditNote(creditNoteId);
} }
@Post('validate-bulk-delete')
@ApiOperation({
summary:
'Validates which credit notes can be deleted and returns the results.',
})
@ApiResponse({
status: 200,
description:
'Validation completed with counts and IDs of deletable and non-deletable credit notes.',
schema: {
$ref: getSchemaPath(ValidateBulkDeleteResponseDto),
},
})
validateBulkDeleteCreditNotes(
@Body() bulkDeleteDto: BulkDeleteDto,
): Promise<ValidateBulkDeleteResponseDto> {
return this.creditNoteApplication.validateBulkDeleteCreditNotes(
bulkDeleteDto.ids,
);
}
@Post('bulk-delete')
@ApiOperation({ summary: 'Deletes multiple credit notes.' })
@ApiResponse({
status: 200,
description: 'Credit notes deleted successfully',
})
bulkDeleteCreditNotes(@Body() bulkDeleteDto: BulkDeleteDto): Promise<void> {
return this.creditNoteApplication.bulkDeleteCreditNotes(bulkDeleteDto.ids, {
skipUndeletable: bulkDeleteDto.skipUndeletable ?? false,
});
}
@Delete(':id') @Delete(':id')
@ApiOperation({ summary: 'Delete a credit note' }) @ApiOperation({ summary: 'Delete a credit note' })
@ApiParam({ name: 'id', description: 'Credit note ID', type: 'number' }) @ApiParam({ name: 'id', description: 'Credit note ID', type: 'number' })

View File

@@ -29,10 +29,13 @@ import { CreditNotesImportable } from './commands/CreditNotesImportable';
import { CreditNoteInventoryTransactionsSubscriber } from './subscribers/CreditNoteInventoryTransactionsSubscriber'; import { CreditNoteInventoryTransactionsSubscriber } from './subscribers/CreditNoteInventoryTransactionsSubscriber';
import { RefundSyncCreditNoteBalanceSubscriber } from './subscribers/RefundSyncCreditNoteBalanceSubscriber'; import { RefundSyncCreditNoteBalanceSubscriber } from './subscribers/RefundSyncCreditNoteBalanceSubscriber';
import { DeleteCustomerLinkedCreditSubscriber } from './subscribers/DeleteCustomerLinkedCreditSubscriber'; import { DeleteCustomerLinkedCreditSubscriber } from './subscribers/DeleteCustomerLinkedCreditSubscriber';
import { CreditNoteAutoSerialSubscriber } from './subscribers/CreditNoteAutoSerialSubscriber';
import { CreditNoteInventoryTransactions } from './commands/CreditNotesInventoryTransactions'; import { CreditNoteInventoryTransactions } from './commands/CreditNotesInventoryTransactions';
import { InventoryCostModule } from '../InventoryCost/InventoryCost.module'; import { InventoryCostModule } from '../InventoryCost/InventoryCost.module';
import { CreditNoteRefundsModule } from '../CreditNoteRefunds/CreditNoteRefunds.module'; import { CreditNoteRefundsModule } from '../CreditNoteRefunds/CreditNoteRefunds.module';
import { CreditNotesApplyInvoiceModule } from '../CreditNotesApplyInvoice/CreditNotesApplyInvoice.module'; import { CreditNotesApplyInvoiceModule } from '../CreditNotesApplyInvoice/CreditNotesApplyInvoice.module';
import { BulkDeleteCreditNotesService } from './BulkDeleteCreditNotes.service';
import { ValidateBulkDeleteCreditNotesService } from './ValidateBulkDeleteCreditNotes.service';
@Module({ @Module({
imports: [ imports: [
@@ -71,6 +74,9 @@ import { CreditNotesApplyInvoiceModule } from '../CreditNotesApplyInvoice/Credit
CreditNoteInventoryTransactionsSubscriber, CreditNoteInventoryTransactionsSubscriber,
RefundSyncCreditNoteBalanceSubscriber, RefundSyncCreditNoteBalanceSubscriber,
DeleteCustomerLinkedCreditSubscriber, DeleteCustomerLinkedCreditSubscriber,
CreditNoteAutoSerialSubscriber,
BulkDeleteCreditNotesService,
ValidateBulkDeleteCreditNotesService,
], ],
exports: [ exports: [
CreateCreditNoteService, CreateCreditNoteService,

View File

@@ -0,0 +1,54 @@
import { Injectable, Inject } from '@nestjs/common';
import { Knex } from 'knex';
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
import { DeleteCreditNoteService } from './commands/DeleteCreditNote.service';
@Injectable()
export class ValidateBulkDeleteCreditNotesService {
constructor(
private readonly deleteCreditNoteService: DeleteCreditNoteService,
@Inject(TENANCY_DB_CONNECTION)
private readonly tenantKnex: () => Knex,
) { }
public async validateBulkDeleteCreditNotes(creditNoteIds: number[]): Promise<{
deletableCount: number;
nonDeletableCount: number;
deletableIds: number[];
nonDeletableIds: number[];
}> {
const trx = await this.tenantKnex().transaction({
isolationLevel: 'read uncommitted',
});
try {
const deletableIds: number[] = [];
const nonDeletableIds: number[] = [];
for (const creditNoteId of creditNoteIds) {
try {
await this.deleteCreditNoteService.deleteCreditNote(
creditNoteId,
trx,
);
deletableIds.push(creditNoteId);
} catch (error) {
nonDeletableIds.push(creditNoteId);
}
}
await trx.rollback();
return {
deletableCount: deletableIds.length,
nonDeletableCount: nonDeletableIds.length,
deletableIds,
nonDeletableIds,
};
} catch (error) {
await trx.rollback();
throw error;
}
}
}

View File

@@ -49,9 +49,13 @@ export class DeleteCreditNoteService {
/** /**
* Deletes the given credit note transactions. * Deletes the given credit note transactions.
* @param {number} creditNoteId * @param {number} creditNoteId
* @param {Knex.Transaction} trx - Database transaction instance.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
public async deleteCreditNote(creditNoteId: number): Promise<void> { public async deleteCreditNote(
creditNoteId: number,
trx?: Knex.Transaction,
): Promise<void> {
// Retrieve the credit note or throw not found service error. // Retrieve the credit note or throw not found service error.
const oldCreditNote = await this.creditNoteModel() const oldCreditNote = await this.creditNoteModel()
.query() .query()
@@ -88,7 +92,7 @@ export class DeleteCreditNoteService {
creditNoteId, creditNoteId,
trx, trx,
} as ICreditNoteDeletedPayload); } as ICreditNoteDeletedPayload);
}); }, trx);
} }
/** /**

View File

@@ -164,73 +164,73 @@ export const CreditNoteMeta = {
}, },
fields2: { fields2: {
customerId: { customerId: {
name: 'Customer', name: 'credit_note.field.customer',
fieldType: 'relation', fieldType: 'relation',
relationModel: 'Contact', relationModel: 'Contact',
relationImportMatch: 'displayName', relationImportMatch: 'displayName',
required: true, required: true,
}, },
exchangeRate: { exchangeRate: {
name: 'Exchange Rate', name: 'credit_note.field.exchange_rate',
fieldType: 'number', fieldType: 'number',
}, },
creditNoteDate: { creditNoteDate: {
name: 'Credit Note Date', name: 'credit_note.field.credit_note_date',
fieldType: 'date', fieldType: 'date',
required: true, required: true,
}, },
referenceNo: { referenceNo: {
name: 'Reference No.', name: 'credit_note.field.reference_no',
fieldType: 'text', fieldType: 'text',
}, },
note: { note: {
name: 'Note', name: 'credit_note.field.note',
fieldType: 'text', fieldType: 'text',
}, },
termsConditions: { termsConditions: {
name: 'Terms & Conditions', name: 'credit_note.field.terms_conditions',
fieldType: 'text', fieldType: 'text',
}, },
creditNoteNumber: { creditNoteNumber: {
name: 'Credit Note Number', name: 'credit_note.field.credit_note_number',
fieldType: 'text', fieldType: 'text',
}, },
open: { open: {
name: 'Open', name: 'credit_note.field.open',
fieldType: 'boolean', fieldType: 'boolean',
}, },
entries: { entries: {
name: 'Entries', name: 'credit_note.field.entries',
fieldType: 'collection', fieldType: 'collection',
collectionOf: 'object', collectionOf: 'object',
collectionMinLength: 1, collectionMinLength: 1,
fields: { fields: {
itemId: { itemId: {
name: 'Item', name: 'credit_note.field.item',
fieldType: 'relation', fieldType: 'relation',
relationModel: 'Item', relationModel: 'Item',
relationImportMatch: ['name', 'code'], relationImportMatch: ['name', 'code'],
required: true, required: true,
importHint: 'Matches the item name or code.', importHint: 'invoice.field.item_hint',
}, },
rate: { rate: {
name: 'Rate', name: 'credit_note.field.rate',
fieldType: 'number', fieldType: 'number',
required: true, required: true,
}, },
quantity: { quantity: {
name: 'Quantity', name: 'credit_note.field.quantity',
fieldType: 'number', fieldType: 'number',
required: true, required: true,
}, },
description: { description: {
name: 'Description', name: 'credit_note.field.description',
fieldType: 'text', fieldType: 'text',
}, },
}, },
}, },
branchId: { branchId: {
name: 'Branch', name: 'invoice.field.branch',
fieldType: 'relation', fieldType: 'relation',
relationModel: 'Branch', relationModel: 'Branch',
relationImportMatch: ['name', 'code'], relationImportMatch: ['name', 'code'],
@@ -238,7 +238,7 @@ export const CreditNoteMeta = {
required: true, required: true,
}, },
warehouseId: { warehouseId: {
name: 'Warehouse', name: 'invoice.field.warehouse',
fieldType: 'relation', fieldType: 'relation',
relationModel: 'Warehouse', relationModel: 'Warehouse',
relationImportMatch: ['name', 'code'], relationImportMatch: ['name', 'code'],

View File

@@ -90,7 +90,7 @@ export class CreditNoteTransformer extends Transformer {
* @returns {string} * @returns {string}
*/ */
protected formattedSubtotal = (credit): string => { protected formattedSubtotal = (credit): string => {
return this.formatNumber(credit.amount, { money: false }); return this.formatNumber(credit.amount);
}; };
/** /**
@@ -130,7 +130,7 @@ export class CreditNoteTransformer extends Transformer {
* @returns {string} * @returns {string}
*/ */
protected adjustmentFormatted = (credit): string => { protected adjustmentFormatted = (credit): string => {
return this.formatMoney(credit.adjustment, { return this.formatNumber(credit.adjustment, {
currencyCode: credit.currencyCode, currencyCode: credit.currencyCode,
excerptZero: true, excerptZero: true,
}); });
@@ -156,6 +156,7 @@ export class CreditNoteTransformer extends Transformer {
protected totalFormatted = (credit): string => { protected totalFormatted = (credit): string => {
return this.formatNumber(credit.total, { return this.formatNumber(credit.total, {
currencyCode: credit.currencyCode, currencyCode: credit.currencyCode,
money: true,
}); });
}; };
@@ -167,6 +168,7 @@ export class CreditNoteTransformer extends Transformer {
protected totalLocalFormatted = (credit): string => { protected totalLocalFormatted = (credit): string => {
return this.formatNumber(credit.totalLocal, { return this.formatNumber(credit.totalLocal, {
currencyCode: credit.currencyCode, currencyCode: credit.currencyCode,
money: true,
}); });
}; };

View File

@@ -1,10 +1,10 @@
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { renderCreditNotePaperTemplateHtml } from '@bigcapital/pdf-templates';
import { GetCreditNoteService } from './GetCreditNote.service'; import { GetCreditNoteService } from './GetCreditNote.service';
import { CreditNoteBrandingTemplate } from './CreditNoteBrandingTemplate.service'; import { CreditNoteBrandingTemplate } from './CreditNoteBrandingTemplate.service';
import { transformCreditNoteToPdfTemplate } from '../utils'; import { transformCreditNoteToPdfTemplate } from '../utils';
import { CreditNote } from '../models/CreditNote'; import { CreditNote } from '../models/CreditNote';
import { ChromiumlyTenancy } from '@/modules/ChromiumlyTenancy/ChromiumlyTenancy.service'; import { ChromiumlyTenancy } from '@/modules/ChromiumlyTenancy/ChromiumlyTenancy.service';
import { TemplateInjectable } from '@/modules/TemplateInjectable/TemplateInjectable.service';
import { EventEmitter2 } from '@nestjs/event-emitter'; import { EventEmitter2 } from '@nestjs/event-emitter';
import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate'; import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate';
import { CreditNotePdfTemplateAttributes } from '../types/CreditNotes.types'; import { CreditNotePdfTemplateAttributes } from '../types/CreditNotes.types';
@@ -15,7 +15,6 @@ import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
export class GetCreditNotePdf { export class GetCreditNotePdf {
/** /**
* @param {ChromiumlyTenancy} chromiumlyTenancy - Chromiumly tenancy service. * @param {ChromiumlyTenancy} chromiumlyTenancy - Chromiumly tenancy service.
* @param {TemplateInjectable} templateInjectable - Template injectable service.
* @param {GetCreditNote} getCreditNoteService - Get credit note service. * @param {GetCreditNote} getCreditNoteService - Get credit note service.
* @param {CreditNoteBrandingTemplate} creditNoteBrandingTemplate - Credit note branding template service. * @param {CreditNoteBrandingTemplate} creditNoteBrandingTemplate - Credit note branding template service.
* @param {EventEmitter2} eventPublisher - Event publisher service. * @param {EventEmitter2} eventPublisher - Event publisher service.
@@ -24,7 +23,6 @@ export class GetCreditNotePdf {
*/ */
constructor( constructor(
private readonly chromiumlyTenancy: ChromiumlyTenancy, private readonly chromiumlyTenancy: ChromiumlyTenancy,
private readonly templateInjectable: TemplateInjectable,
private readonly getCreditNoteService: GetCreditNoteService, private readonly getCreditNoteService: GetCreditNoteService,
private readonly creditNoteBrandingTemplate: CreditNoteBrandingTemplate, private readonly creditNoteBrandingTemplate: CreditNoteBrandingTemplate,
private readonly eventPublisher: EventEmitter2, private readonly eventPublisher: EventEmitter2,
@@ -39,20 +37,37 @@ export class GetCreditNotePdf {
) { } ) { }
/** /**
* Retrieves sale invoice pdf content. * Retrieves credit note html content.
* @param {number} creditNoteId - Credit note id.
* @returns {Promise<string>}
*/
public async getCreditNoteHtml(creditNoteId: number): Promise<string> {
const brandingAttributes =
await this.getCreditNoteBrandingAttributes(creditNoteId);
// Map attributes to match the React component props
// The branding template returns companyLogoUri, but type may have companyLogo
const props = {
...brandingAttributes,
companyLogoUri:
(brandingAttributes as any).companyLogoUri ||
(brandingAttributes as any).companyLogo ||
'',
};
return renderCreditNotePaperTemplateHtml(props);
}
/**
* Retrieves credit note pdf content.
* @param {number} creditNoteId - Credit note id. * @param {number} creditNoteId - Credit note id.
* @returns {Promise<[Buffer, string]>} * @returns {Promise<[Buffer, string]>}
*/ */
public async getCreditNotePdf( public async getCreditNotePdf(
creditNoteId: number, creditNoteId: number,
): Promise<[Buffer, string]> { ): Promise<[Buffer, string]> {
const brandingAttributes =
await this.getCreditNoteBrandingAttributes(creditNoteId);
const htmlContent = await this.templateInjectable.render(
'modules/credit-note-standard',
brandingAttributes,
);
const filename = await this.getCreditNoteFilename(creditNoteId); const filename = await this.getCreditNoteFilename(creditNoteId);
const htmlContent = await this.getCreditNoteHtml(creditNoteId);
const document = const document =
await this.chromiumlyTenancy.convertHtmlContent(htmlContent); await this.chromiumlyTenancy.convertHtmlContent(htmlContent);

View File

@@ -5,7 +5,7 @@ import { ICreditNoteCreatedPayload } from '../types/CreditNotes.types';
import { events } from '@/common/events/events'; import { events } from '@/common/events/events';
@Injectable() @Injectable()
export default class CreditNoteAutoSerialSubscriber { export class CreditNoteAutoSerialSubscriber {
constructor( constructor(
private readonly creditNoteIncrementService: CreditNoteAutoIncrementService, private readonly creditNoteIncrementService: CreditNoteAutoIncrementService,
) { } ) { }

View File

@@ -10,8 +10,8 @@ export const InitialCurrencies = [
]; ];
export const ERRORS = { export const ERRORS = {
CURRENCY_NOT_FOUND: 'currency_not_found', CURRENCY_NOT_FOUND: 'CURRENCY_NOT_FOUND',
CURRENCY_CODE_EXISTS: 'currency_code_exists', CURRENCY_CODE_EXISTS: 'CURRENCY_CODE_EXISTS',
BASE_CURRENCY_INVALID: 'BASE_CURRENCY_INVALID', BASE_CURRENCY_INVALID: 'BASE_CURRENCY_INVALID',
CANNOT_DELETE_BASE_CURRENCY: 'CANNOT_DELETE_BASE_CURRENCY', CANNOT_DELETE_BASE_CURRENCY: 'CANNOT_DELETE_BASE_CURRENCY',
}; };

View File

@@ -0,0 +1,34 @@
import { Injectable } from '@nestjs/common';
import { castArray, uniq } from 'lodash';
import { PromisePool } from '@supercharge/promise-pool';
import { DeleteCustomer } from './commands/DeleteCustomer.service';
@Injectable()
export class BulkDeleteCustomersService {
constructor(private readonly deleteCustomerService: DeleteCustomer) {}
public async bulkDeleteCustomers(
customerIds: number[],
options?: { skipUndeletable?: boolean },
): Promise<void> {
const { skipUndeletable = false } = options ?? {};
const ids = uniq(castArray(customerIds));
const results = await PromisePool.withConcurrency(1)
.for(ids)
.process(async (customerId: number) => {
try {
await this.deleteCustomerService.deleteCustomer(customerId);
} catch (error) {
if (!skipUndeletable) {
throw error;
}
}
});
if (!skipUndeletable && results.errors && results.errors.length > 0) {
throw results.errors[0].raw ?? results.errors[0];
}
}
}

View File

@@ -24,6 +24,10 @@ import { CreateCustomerDto } from './dtos/CreateCustomer.dto';
import { EditCustomerDto } from './dtos/EditCustomer.dto'; import { EditCustomerDto } from './dtos/EditCustomer.dto';
import { CustomerResponseDto } from './dtos/CustomerResponse.dto'; import { CustomerResponseDto } from './dtos/CustomerResponse.dto';
import { GetCustomersQueryDto } from './dtos/GetCustomersQuery.dto'; import { GetCustomersQueryDto } from './dtos/GetCustomersQuery.dto';
import {
BulkDeleteCustomersDto,
ValidateBulkDeleteCustomersResponseDto,
} from './dtos/BulkDeleteCustomers.dto';
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders'; import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
@Controller('customers') @Controller('customers')
@@ -109,4 +113,37 @@ export class CustomersController {
openingBalanceDTO, openingBalanceDTO,
); );
} }
@Post('validate-bulk-delete')
@ApiOperation({
summary:
'Validates which customers can be deleted and returns counts of deletable and non-deletable customers.',
})
@ApiResponse({
status: 200,
description:
'Validation completed. Returns counts and IDs of deletable and non-deletable customers.',
schema: { $ref: getSchemaPath(ValidateBulkDeleteCustomersResponseDto) },
})
validateBulkDeleteCustomers(
@Body() bulkDeleteDto: BulkDeleteCustomersDto,
): Promise<ValidateBulkDeleteCustomersResponseDto> {
return this.customersApplication.validateBulkDeleteCustomers(
bulkDeleteDto.ids,
);
}
@Post('bulk-delete')
@ApiOperation({ summary: 'Deletes multiple customers in bulk.' })
@ApiResponse({
status: 200,
description: 'The customers have been successfully deleted.',
})
async bulkDeleteCustomers(
@Body() bulkDeleteDto: BulkDeleteCustomersDto,
): Promise<void> {
return this.customersApplication.bulkDeleteCustomers(bulkDeleteDto.ids, {
skipUndeletable: bulkDeleteDto.skipUndeletable ?? false,
});
}
} }

View File

@@ -16,6 +16,8 @@ import { CustomersExportable } from './CustomersExportable';
import { CustomersImportable } from './CustomersImportable'; import { CustomersImportable } from './CustomersImportable';
import { GetCustomers } from './queries/GetCustomers.service'; import { GetCustomers } from './queries/GetCustomers.service';
import { DynamicListModule } from '../DynamicListing/DynamicList.module'; import { DynamicListModule } from '../DynamicListing/DynamicList.module';
import { BulkDeleteCustomersService } from './BulkDeleteCustomers.service';
import { ValidateBulkDeleteCustomersService } from './ValidateBulkDeleteCustomers.service';
@Module({ @Module({
imports: [TenancyDatabaseModule, DynamicListModule], imports: [TenancyDatabaseModule, DynamicListModule],
@@ -37,6 +39,8 @@ import { DynamicListModule } from '../DynamicListing/DynamicList.module';
CustomersExportable, CustomersExportable,
CustomersImportable, CustomersImportable,
GetCustomers, GetCustomers,
BulkDeleteCustomersService,
ValidateBulkDeleteCustomersService,
], ],
}) })
export class CustomersModule {} export class CustomersModule {}

View File

@@ -12,6 +12,8 @@ import { CreateCustomerDto } from './dtos/CreateCustomer.dto';
import { EditCustomerDto } from './dtos/EditCustomer.dto'; import { EditCustomerDto } from './dtos/EditCustomer.dto';
import { GetCustomers } from './queries/GetCustomers.service'; import { GetCustomers } from './queries/GetCustomers.service';
import { GetCustomersQueryDto } from './dtos/GetCustomersQuery.dto'; import { GetCustomersQueryDto } from './dtos/GetCustomersQuery.dto';
import { BulkDeleteCustomersService } from './BulkDeleteCustomers.service';
import { ValidateBulkDeleteCustomersService } from './ValidateBulkDeleteCustomers.service';
@Injectable() @Injectable()
export class CustomersApplication { export class CustomersApplication {
@@ -22,6 +24,8 @@ export class CustomersApplication {
private deleteCustomerService: DeleteCustomer, private deleteCustomerService: DeleteCustomer,
private editOpeningBalanceService: EditOpeningBalanceCustomer, private editOpeningBalanceService: EditOpeningBalanceCustomer,
private getCustomersService: GetCustomers, private getCustomersService: GetCustomers,
private readonly bulkDeleteCustomersService: BulkDeleteCustomersService,
private readonly validateBulkDeleteCustomersService: ValidateBulkDeleteCustomersService,
) {} ) {}
/** /**
@@ -83,4 +87,20 @@ export class CustomersApplication {
public getCustomers = (filterDTO: GetCustomersQueryDto) => { public getCustomers = (filterDTO: GetCustomersQueryDto) => {
return this.getCustomersService.getCustomersList(filterDTO); return this.getCustomersService.getCustomersList(filterDTO);
}; };
public bulkDeleteCustomers = (
customerIds: number[],
options?: { skipUndeletable?: boolean },
) => {
return this.bulkDeleteCustomersService.bulkDeleteCustomers(
customerIds,
options,
);
};
public validateBulkDeleteCustomers = (customerIds: number[]) => {
return this.validateBulkDeleteCustomersService.validateBulkDeleteCustomers(
customerIds,
);
};
} }

View File

@@ -0,0 +1,61 @@
import { Inject, Injectable } from '@nestjs/common';
import { Knex } from 'knex';
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
import { DeleteCustomer } from './commands/DeleteCustomer.service';
import { ModelHasRelationsError } from '@/common/exceptions/ModelHasRelations.exception';
import { ServiceError } from '@/modules/Items/ServiceError';
@Injectable()
export class ValidateBulkDeleteCustomersService {
constructor(
private readonly deleteCustomerService: DeleteCustomer,
@Inject(TENANCY_DB_CONNECTION)
private readonly tenantKnex: () => Knex,
) {}
public async validateBulkDeleteCustomers(customerIds: number[]): Promise<{
deletableCount: number;
nonDeletableCount: number;
deletableIds: number[];
nonDeletableIds: number[];
}> {
const trx = await this.tenantKnex().transaction({
isolationLevel: 'read uncommitted',
});
try {
const deletableIds: number[] = [];
const nonDeletableIds: number[] = [];
for (const customerId of customerIds) {
try {
await this.deleteCustomerService.deleteCustomer(customerId, trx);
deletableIds.push(customerId);
} catch (error) {
if (
error instanceof ModelHasRelationsError ||
(error instanceof ServiceError &&
error.errorType === 'CUSTOMER_HAS_TRANSACTIONS')
) {
nonDeletableIds.push(customerId);
} else {
nonDeletableIds.push(customerId);
}
}
}
await trx.rollback();
return {
deletableCount: deletableIds.length,
nonDeletableCount: nonDeletableIds.length,
deletableIds,
nonDeletableIds,
};
} catch (error) {
await trx.rollback();
throw error;
}
}
}

View File

@@ -31,12 +31,13 @@ export class DeleteCustomer {
* @param {number} customerId - Customer ID. * @param {number} customerId - Customer ID.
* @return {Promise<void>} * @return {Promise<void>}
*/ */
public async deleteCustomer(customerId: number): Promise<void> { public async deleteCustomer(
customerId: number,
trx?: Knex.Transaction,
): Promise<void> {
// Retrieve the customer or throw not found service error. // Retrieve the customer or throw not found service error.
const oldCustomer = await this.customerModel() const query = this.customerModel().query(trx);
.query() const oldCustomer = await query.findById(customerId).throwIfNotFound();
.findById(customerId)
.throwIfNotFound();
// Triggers `onCustomerDeleting` event. // Triggers `onCustomerDeleting` event.
await this.eventPublisher.emitAsync(events.customers.onDeleting, { await this.eventPublisher.emitAsync(events.customers.onDeleting, {
@@ -45,10 +46,10 @@ export class DeleteCustomer {
} as ICustomerDeletingPayload); } as ICustomerDeletingPayload);
// Deletes the customer and associated entities under UOW transaction. // Deletes the customer and associated entities under UOW transaction.
return this.uow.withTransaction(async (trx: Knex.Transaction) => { return this.uow.withTransaction(async (transaction: Knex.Transaction) => {
// Delete the customer from the storage. // Delete the customer from the storage.
await this.customerModel() await this.customerModel()
.query(trx) .query(transaction)
.findById(customerId) .findById(customerId)
.deleteIfNoRelations({ .deleteIfNoRelations({
type: ERRORS.CUSTOMER_HAS_TRANSACTIONS, type: ERRORS.CUSTOMER_HAS_TRANSACTIONS,
@@ -58,8 +59,8 @@ export class DeleteCustomer {
await this.eventPublisher.emitAsync(events.customers.onDeleted, { await this.eventPublisher.emitAsync(events.customers.onDeleted, {
customerId, customerId,
oldCustomer, oldCustomer,
trx, trx: transaction,
} as ICustomerEventDeletedPayload); } as ICustomerEventDeletedPayload);
}); }, trx);
} }
} }

View File

@@ -0,0 +1,62 @@
import {
ArrayNotEmpty,
IsArray,
IsInt,
IsOptional,
IsBoolean,
} from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { parseBoolean } from '@/utils/parse-boolean';
export class BulkDeleteCustomersDto {
@IsArray()
@ArrayNotEmpty()
@IsInt({ each: true })
@ApiProperty({
description: 'Array of customer IDs to delete',
type: [Number],
example: [1, 2, 3],
})
ids: number[];
@IsOptional()
@IsBoolean()
@Transform(({ value, obj }) => parseBoolean(value ?? obj?.skip_undeletable, false))
@ApiPropertyOptional({
description:
'When true, undeletable customers will be skipped and only deletable ones removed.',
type: Boolean,
default: false,
})
skipUndeletable?: boolean;
}
export class ValidateBulkDeleteCustomersResponseDto {
@ApiProperty({
description: 'Number of customers that can be deleted',
example: 2,
})
deletableCount: number;
@ApiProperty({
description: 'Number of customers that cannot be deleted',
example: 1,
})
nonDeletableCount: number;
@ApiProperty({
description: 'IDs of customers that can be deleted',
type: [Number],
example: [1, 2],
})
deletableIds: number[];
@ApiProperty({
description: 'IDs of customers that cannot be deleted',
type: [Number],
example: [3],
})
nonDeletableIds: number[];
}

View File

@@ -0,0 +1,36 @@
import { Injectable } from '@nestjs/common';
import { Knex } from 'knex';
import { PromisePool } from '@supercharge/promise-pool';
import { castArray, uniq } from 'lodash';
import { DeleteExpense } from './commands/DeleteExpense.service';
@Injectable()
export class BulkDeleteExpensesService {
constructor(private readonly deleteExpenseService: DeleteExpense) { }
async bulkDeleteExpenses(
expenseIds: number | Array<number>,
options?: { skipUndeletable?: boolean },
trx?: Knex.Transaction,
): Promise<void> {
const { skipUndeletable = false } = options ?? {};
const expensesIds = uniq(castArray(expenseIds));
const results = await PromisePool.withConcurrency(1)
.for(expensesIds)
.process(async (expenseId: number) => {
try {
await this.deleteExpenseService.deleteExpense(expenseId);
} catch (error) {
if (!skipUndeletable) {
throw error;
}
}
});
if (!skipUndeletable && results.errors && results.errors.length > 0) {
throw results.errors[0].raw;
}
}
}

View File

@@ -21,14 +21,56 @@ import { CreateExpenseDto, EditExpenseDto } from './dtos/Expense.dto';
import { PaginatedResponseDto } from '@/common/dtos/PaginatedResults.dto'; import { PaginatedResponseDto } from '@/common/dtos/PaginatedResults.dto';
import { ExpenseResponseDto } from './dtos/ExpenseResponse.dto'; import { ExpenseResponseDto } from './dtos/ExpenseResponse.dto';
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders'; import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
import {
BulkDeleteDto,
ValidateBulkDeleteResponseDto,
} from '@/common/dtos/BulkDelete.dto';
@Controller('expenses') @Controller('expenses')
@ApiTags('Expenses') @ApiTags('Expenses')
@ApiExtraModels(PaginatedResponseDto, ExpenseResponseDto) @ApiExtraModels(
PaginatedResponseDto,
ExpenseResponseDto,
ValidateBulkDeleteResponseDto,
)
@ApiCommonHeaders() @ApiCommonHeaders()
export class ExpensesController { export class ExpensesController {
constructor(private readonly expensesApplication: ExpensesApplication) { } constructor(private readonly expensesApplication: ExpensesApplication) { }
@Post('validate-bulk-delete')
@ApiOperation({
summary: 'Validate which expenses can be deleted and return the results.',
})
@ApiResponse({
status: 200,
description:
'Validation completed with counts and IDs of deletable and non-deletable expenses.',
schema: {
$ref: getSchemaPath(ValidateBulkDeleteResponseDto),
},
})
public validateBulkDeleteExpenses(
@Body() bulkDeleteDto: BulkDeleteDto,
): Promise<ValidateBulkDeleteResponseDto> {
return this.expensesApplication.validateBulkDeleteExpenses(
bulkDeleteDto.ids,
);
}
@Post('bulk-delete')
@ApiOperation({ summary: 'Deletes multiple expenses.' })
@ApiResponse({
status: 200,
description: 'Expenses deleted successfully',
})
public bulkDeleteExpenses(
@Body() bulkDeleteDto: BulkDeleteDto,
) {
return this.expensesApplication.bulkDeleteExpenses(bulkDeleteDto.ids, {
skipUndeletable: bulkDeleteDto.skipUndeletable ?? false,
});
}
/** /**
* Create a new expense transaction. * Create a new expense transaction.
* @param {IExpenseCreateDTO} expenseDTO * @param {IExpenseCreateDTO} expenseDTO

View File

@@ -19,6 +19,8 @@ import { GetExpensesService } from './queries/GetExpenses.service';
import { DynamicListModule } from '../DynamicListing/DynamicList.module'; import { DynamicListModule } from '../DynamicListing/DynamicList.module';
import { ExpensesExportable } from './ExpensesExportable'; import { ExpensesExportable } from './ExpensesExportable';
import { ExpensesImportable } from './ExpensesImportable'; import { ExpensesImportable } from './ExpensesImportable';
import { BulkDeleteExpensesService } from './BulkDeleteExpenses.service';
import { ValidateBulkDeleteExpensesService } from './ValidateBulkDeleteExpenses.service';
@Module({ @Module({
imports: [LedgerModule, BranchesModule, DynamicListModule], imports: [LedgerModule, BranchesModule, DynamicListModule],
@@ -41,6 +43,8 @@ import { ExpensesImportable } from './ExpensesImportable';
GetExpensesService, GetExpensesService,
ExpensesExportable, ExpensesExportable,
ExpensesImportable, ExpensesImportable,
BulkDeleteExpensesService,
ValidateBulkDeleteExpensesService,
], ],
}) })
export class ExpensesModule {} export class ExpensesModule {}

View File

@@ -7,6 +7,8 @@ import { GetExpenseService } from './queries/GetExpense.service';
import { IExpensesFilter } from './interfaces/Expenses.interface'; import { IExpensesFilter } from './interfaces/Expenses.interface';
import { GetExpensesService } from './queries/GetExpenses.service'; import { GetExpensesService } from './queries/GetExpenses.service';
import { CreateExpenseDto, EditExpenseDto } from './dtos/Expense.dto'; import { CreateExpenseDto, EditExpenseDto } from './dtos/Expense.dto';
import { BulkDeleteExpensesService } from './BulkDeleteExpenses.service';
import { ValidateBulkDeleteExpensesService } from './ValidateBulkDeleteExpenses.service';
@Injectable() @Injectable()
export class ExpensesApplication { export class ExpensesApplication {
@@ -17,6 +19,8 @@ export class ExpensesApplication {
private readonly publishExpenseService: PublishExpense, private readonly publishExpenseService: PublishExpense,
private readonly getExpenseService: GetExpenseService, private readonly getExpenseService: GetExpenseService,
private readonly getExpensesService: GetExpensesService, private readonly getExpensesService: GetExpensesService,
private readonly bulkDeleteExpensesService: BulkDeleteExpensesService,
private readonly validateBulkDeleteExpensesService: ValidateBulkDeleteExpensesService,
) { } ) { }
/** /**
@@ -47,6 +51,30 @@ export class ExpensesApplication {
return this.deleteExpenseService.deleteExpense(expenseId); return this.deleteExpenseService.deleteExpense(expenseId);
} }
/**
* Deletes expenses in bulk.
* @param {number[]} expenseIds - Expense ids.
*/
public bulkDeleteExpenses(
expenseIds: number[],
options?: { skipUndeletable?: boolean },
) {
return this.bulkDeleteExpensesService.bulkDeleteExpenses(
expenseIds,
options,
);
}
/**
* Validates which expenses can be deleted.
* @param {number[]} expenseIds - Expense ids.
*/
public validateBulkDeleteExpenses(expenseIds: number[]) {
return this.validateBulkDeleteExpensesService.validateBulkDeleteExpenses(
expenseIds,
);
}
/** /**
* Publishes the given expense. * Publishes the given expense.
* @param {number} expenseId - Expense id. * @param {number} expenseId - Expense id.

View File

@@ -5,10 +5,10 @@ import { ExpensesSampleData } from './constants';
import { CreateExpense } from './commands/CreateExpense.service'; import { CreateExpense } from './commands/CreateExpense.service';
import { CreateExpenseDto } from './dtos/Expense.dto'; import { CreateExpenseDto } from './dtos/Expense.dto';
import { ImportableService } from '../Import/decorators/Import.decorator'; import { ImportableService } from '../Import/decorators/Import.decorator';
import { ManualJournal } from '../ManualJournals/models/ManualJournal'; import { Expense } from './models/Expense.model';
@Injectable() @Injectable()
@ImportableService({ name: ManualJournal.name }) @ImportableService({ name: Expense.name })
export class ExpensesImportable extends Importable { export class ExpensesImportable extends Importable {
constructor(private readonly createExpenseService: CreateExpense) { constructor(private readonly createExpenseService: CreateExpense) {
super(); super();

Some files were not shown because too many files have changed in this diff Show More