mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-15 12:20:31 +00:00
Compare commits
1 Commits
nestjs-dto
...
migrate-se
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a10b58a7c6 |
@@ -1,6 +1,3 @@
|
||||
# App
|
||||
APP_JWT_SECRET=123123
|
||||
|
||||
# Mail
|
||||
MAIL_HOST=
|
||||
MAIL_USERNAME=
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -6,5 +6,4 @@ node_modules/
|
||||
# Production env file
|
||||
.env
|
||||
|
||||
test-results/
|
||||
.qodo
|
||||
test-results/
|
||||
@@ -34,8 +34,6 @@
|
||||
</p>
|
||||
</p>
|
||||
|
||||
> We are currently in the process of migrating all server-side API endpoints to NestJS to establish a more solid architecture. Some endpoints in development mode may be temporarily do not work during this stabilization phase. However, this migration doesn't affect the production Docker images, which remain on the latest stable version.
|
||||
|
||||
# What's Bigcapital?
|
||||
|
||||
Bigcapital is a smart and open-source accounting and inventory software, Bigcapital keeps all business finances in right place and automates accounting processes to give the business powerful and intelligent financial statements and reports to help in making decisions.
|
||||
|
||||
@@ -41,8 +41,6 @@ services:
|
||||
context: ./docker/redis
|
||||
expose:
|
||||
- "6379"
|
||||
ports:
|
||||
- "6379:6379"
|
||||
volumes:
|
||||
- redis:/data
|
||||
deploy:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM redis:6.2.0
|
||||
FROM redis:4.0
|
||||
|
||||
COPY redis.conf /usr/local/etc/redis/redis.conf
|
||||
|
||||
|
||||
24
launch.json
24
launch.json
@@ -1,24 +0,0 @@
|
||||
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Debug Nest Framework",
|
||||
"runtimeExecutable": "npm",
|
||||
"runtimeArgs": [
|
||||
"run",
|
||||
"start:debug",
|
||||
"--",
|
||||
"--inspect-brk"
|
||||
],
|
||||
"autoAttachChildProcesses": true,
|
||||
"restart": true,
|
||||
"sourceMaps": true,
|
||||
"stopOnEntry": false,
|
||||
"console": "integratedTerminal"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
"server2:start": "lerna run start:dev --scope \"@bigcapital/server2\"",
|
||||
"test:watch": "lerna run test:watch",
|
||||
"test:e2e": "lerna run test:e2e",
|
||||
"start:debug": "lerna run start:debug",
|
||||
"prepare": "husky install"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# App
|
||||
APP_JWT_SECRET=123123
|
||||
|
||||
# Mail
|
||||
MAIL_HOST=
|
||||
MAIL_USERNAME=
|
||||
25
packages/server-nest/.eslintrc.js
Normal file
25
packages/server-nest/.eslintrc.js
Normal file
@@ -0,0 +1,25 @@
|
||||
module.exports = {
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
project: 'tsconfig.json',
|
||||
tsconfigRootDir: __dirname,
|
||||
sourceType: 'module',
|
||||
},
|
||||
plugins: ['@typescript-eslint/eslint-plugin'],
|
||||
extends: [
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:prettier/recommended',
|
||||
],
|
||||
root: true,
|
||||
env: {
|
||||
node: true,
|
||||
jest: true,
|
||||
},
|
||||
ignorePatterns: ['.eslintrc.js'],
|
||||
rules: {
|
||||
'@typescript-eslint/interface-name-prefix': 'off',
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
};
|
||||
56
packages/server-nest/.gitignore
vendored
Normal file
56
packages/server-nest/.gitignore
vendored
Normal file
@@ -0,0 +1,56 @@
|
||||
# compiled output
|
||||
/dist
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
# Tests
|
||||
/coverage
|
||||
/.nyc_output
|
||||
|
||||
# IDEs and editors
|
||||
/.idea
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
|
||||
# IDE - VSCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# temp directory
|
||||
.temp
|
||||
.tmp
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
1
packages/server-nest/README.md
Normal file
1
packages/server-nest/README.md
Normal file
@@ -0,0 +1 @@
|
||||
## @bigcapitalhq/server
|
||||
127
packages/server-nest/package.json
Normal file
127
packages/server-nest/package.json
Normal file
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"name": "@bigcapital/server2",
|
||||
"version": "0.0.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"start": "nest start",
|
||||
"start:dev": "nest start --watch",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"test:cov": "jest --coverage",
|
||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json --watchAll"
|
||||
},
|
||||
"dependencies": {
|
||||
"@bigcapital/email-components": "*",
|
||||
"@bigcapital/pdf-templates": "*",
|
||||
"@bigcapital/utils": "*",
|
||||
"@nestjs/bull": "^10.2.1",
|
||||
"@nestjs/bullmq": "^10.2.1",
|
||||
"@nestjs/cache-manager": "^2.2.2",
|
||||
"@nestjs/common": "^10.0.0",
|
||||
"@nestjs/config": "^3.2.3",
|
||||
"@nestjs/core": "^10.0.0",
|
||||
"@nestjs/event-emitter": "^2.0.4",
|
||||
"@nestjs/jwt": "^10.2.0",
|
||||
"@nestjs/passport": "^10.0.3",
|
||||
"@nestjs/platform-express": "^10.0.0",
|
||||
"@nestjs/swagger": "^7.4.2",
|
||||
"@nestjs/throttler": "^6.2.1",
|
||||
"@supercharge/promise-pool": "^3.2.0",
|
||||
"@types/nodemailer": "^6.4.17",
|
||||
"@types/passport-local": "^1.0.38",
|
||||
"@types/ramda": "^0.30.2",
|
||||
"accounting": "^0.4.1",
|
||||
"async": "^3.2.0",
|
||||
"axios": "^1.6.0",
|
||||
"bluebird": "^3.7.2",
|
||||
"bull": "^4.16.3",
|
||||
"bullmq": "^5.21.1",
|
||||
"cache-manager": "^6.1.1",
|
||||
"cache-manager-redis-store": "^3.0.1",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.1",
|
||||
"express-validator": "^7.2.0",
|
||||
"form-data": "^4.0.0",
|
||||
"fp-ts": "^2.16.9",
|
||||
"is-my-json-valid": "^2.20.5",
|
||||
"js-money": "^0.6.3",
|
||||
"knex": "^3.1.0",
|
||||
"lamda": "^0.4.1",
|
||||
"lodash": "^4.17.21",
|
||||
"moment": "^2.30.1",
|
||||
"mysql": "^2.18.1",
|
||||
"mysql2": "^3.11.3",
|
||||
"nestjs-cls": "^4.4.1",
|
||||
"nestjs-i18n": "^10.4.9",
|
||||
"nodemailer": "^6.3.0",
|
||||
"object-hash": "^2.0.3",
|
||||
"objection": "^3.1.5",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"passport-local": "^1.0.0",
|
||||
"plaid": "^10.3.0",
|
||||
"pluralize": "^8.0.0",
|
||||
"posthog-node": "^4.3.2",
|
||||
"pug": "^3.0.2",
|
||||
"ramda": "^0.30.1",
|
||||
"redis": "^4.7.0",
|
||||
"reflect-metadata": "^0.2.0",
|
||||
"rxjs": "^7.8.1",
|
||||
"serialize-interceptor": "^1.1.7",
|
||||
"strategy": "^1.1.1",
|
||||
"uniqid": "^5.2.0",
|
||||
"uuid": "^10.0.0",
|
||||
"yup": "^0.28.1",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^10.0.0",
|
||||
"@nestjs/schematics": "^10.0.0",
|
||||
"@nestjs/testing": "^10.0.0",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^29.5.2",
|
||||
"@types/node": "^20.3.1",
|
||||
"@types/supertest": "^6.0.0",
|
||||
"@types/yup": "^0.29.13",
|
||||
"@typescript-eslint/eslint-plugin": "^8.0.0",
|
||||
"@typescript-eslint/parser": "^8.0.0",
|
||||
"eslint": "^9.0.0",
|
||||
"eslint-config-prettier": "^9.0.0",
|
||||
"eslint-plugin-prettier": "^5.0.0",
|
||||
"jest": "^29.5.0",
|
||||
"prettier": "^3.0.0",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.0.0",
|
||||
"ts-jest": "^29.1.0",
|
||||
"ts-loader": "^9.4.3",
|
||||
"ts-node": "^10.9.1",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.1.3"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": [
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
||||
21
packages/server-nest/src/common/config/index.ts
Normal file
21
packages/server-nest/src/common/config/index.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import systemDatabase from './system-database';
|
||||
import tenantDatabase from './tenant-database';
|
||||
import signup from './signup';
|
||||
import gotenberg from './gotenberg';
|
||||
import plaid from './plaid';
|
||||
import lemonsqueezy from './lemonsqueezy';
|
||||
import s3 from './s3';
|
||||
import openExchange from './open-exchange';
|
||||
import posthog from './posthog';
|
||||
|
||||
export const config = [
|
||||
systemDatabase,
|
||||
tenantDatabase,
|
||||
signup,
|
||||
gotenberg,
|
||||
plaid,
|
||||
lemonsqueezy,
|
||||
s3,
|
||||
openExchange,
|
||||
posthog,
|
||||
];
|
||||
@@ -0,0 +1,9 @@
|
||||
import { registerAs } from '@nestjs/config';
|
||||
|
||||
export default registerAs('tenantDatabase', () => ({
|
||||
client: 'mysql',
|
||||
host: process.env.TENANT_DB_HOST || process.env.DB_HOST,
|
||||
port: process.env.TENANT_DB_PORT || process.env.DB_PORT || 5432,
|
||||
user: process.env.TENANT_DB_USER || process.env.DB_USER,
|
||||
password: process.env.TENANT_DB_PASSWORD || process.env.DB_PASSWORD,
|
||||
}));
|
||||
756
packages/server-nest/src/common/events/events.ts
Normal file
756
packages/server-nest/src/common/events/events.ts
Normal file
@@ -0,0 +1,756 @@
|
||||
export const events = {
|
||||
/**
|
||||
* Authentication service.
|
||||
*/
|
||||
auth: {
|
||||
signIn: 'onSignIn',
|
||||
signingIn: 'onSigningIn',
|
||||
|
||||
signUp: 'onSignUp',
|
||||
signingUp: 'onSigningUp',
|
||||
|
||||
signUpConfirming: 'signUpConfirming',
|
||||
signUpConfirmed: 'signUpConfirmed',
|
||||
|
||||
sendingResetPassword: 'onSendingResetPassword',
|
||||
sendResetPassword: 'onSendResetPassword',
|
||||
|
||||
resetPassword: 'onResetPassword',
|
||||
resetingPassword: 'onResetingPassword',
|
||||
},
|
||||
|
||||
/**
|
||||
* Invite users service.
|
||||
*/
|
||||
inviteUser: {
|
||||
acceptInvite: 'onUserAcceptInvite',
|
||||
sendInvite: 'onUserSendInvite',
|
||||
resendInvite: 'onUserInviteResend',
|
||||
checkInvite: 'onUserCheckInvite',
|
||||
sendInviteTenantSynced: 'onUserSendInviteTenantSynced',
|
||||
},
|
||||
|
||||
/**
|
||||
* Organization managment service.
|
||||
*/
|
||||
organization: {
|
||||
build: 'onOrganizationBuild',
|
||||
built: 'onOrganizationBuilt',
|
||||
|
||||
seeded: 'onOrganizationSeeded',
|
||||
|
||||
baseCurrencyUpdated: 'onOrganizationBaseCurrencyUpdated',
|
||||
},
|
||||
|
||||
/**
|
||||
* Organization subscription.
|
||||
*/
|
||||
subscription: {
|
||||
onSubscriptionCancel: 'onSubscriptionCancel',
|
||||
onSubscriptionCancelled: 'onSubscriptionCancelled',
|
||||
|
||||
onSubscriptionResume: 'onSubscriptionResume',
|
||||
onSubscriptionResumed: 'onSubscriptionResumed',
|
||||
|
||||
onSubscriptionPlanChange: 'onSubscriptionPlanChange',
|
||||
onSubscriptionPlanChanged: 'onSubscriptionPlanChanged',
|
||||
|
||||
onSubscriptionSubscribed: 'onSubscriptionSubscribed',
|
||||
|
||||
onSubscriptionPaymentSucceed: 'onSubscriptionPaymentSucceed',
|
||||
onSubscriptionPaymentFailed: 'onSubscriptionPaymentFailed',
|
||||
},
|
||||
|
||||
/**
|
||||
* Tenants managment service.
|
||||
*/
|
||||
tenantManager: {
|
||||
databaseCreated: 'onDatabaseCreated',
|
||||
tenantMigrated: 'onTenantMigrated',
|
||||
tenantSeeded: 'onTenantSeeded',
|
||||
},
|
||||
|
||||
/**
|
||||
* Accounts service.
|
||||
*/
|
||||
accounts: {
|
||||
onViewed: 'onAccountViewed',
|
||||
onListViewed: 'onAccountsListViewed',
|
||||
|
||||
onCreating: 'onAccountCreating',
|
||||
onCreated: 'onAccountCreated',
|
||||
|
||||
onEditing: 'onAccountEditing',
|
||||
onEdited: 'onAccountEdited',
|
||||
|
||||
onDelete: 'onAccountDelete',
|
||||
onDeleted: 'onAccountDeleted',
|
||||
|
||||
onBulkDeleted: 'onBulkDeleted',
|
||||
onBulkActivated: 'onAccountBulkActivated',
|
||||
|
||||
onActivated: 'onAccountActivated',
|
||||
},
|
||||
|
||||
/**
|
||||
* Manual journals service.
|
||||
*/
|
||||
manualJournals: {
|
||||
onCreating: 'onManualJournalCreating',
|
||||
onCreated: 'onManualJournalCreated',
|
||||
|
||||
onEditing: 'onManualJournalEditing',
|
||||
onEdited: 'onManualJournalEdited',
|
||||
|
||||
onDeleting: 'onManualJournalDeleting',
|
||||
onDeleted: 'onManualJournalDeleted',
|
||||
|
||||
onPublished: 'onManualJournalPublished',
|
||||
onPublishing: 'onManualJournalPublishing',
|
||||
},
|
||||
|
||||
/**
|
||||
* Expenses service.
|
||||
*/
|
||||
expenses: {
|
||||
onCreating: 'onExpenseCreating',
|
||||
onCreated: 'onExpenseCreated',
|
||||
|
||||
onEditing: 'onExpenseEditing',
|
||||
onEdited: 'onExpenseEdited',
|
||||
|
||||
onDeleting: 'onExpenseDeleting',
|
||||
onDeleted: 'onExpenseDeleted',
|
||||
|
||||
onPublishing: 'onExpensePublishing',
|
||||
onPublished: 'onExpensePublished',
|
||||
},
|
||||
|
||||
/**
|
||||
* Sales invoices service.
|
||||
*/
|
||||
saleInvoice: {
|
||||
onViewed: 'onSaleInvoiceItemViewed',
|
||||
onListViewed: 'onSaleInvoiceListViewed',
|
||||
|
||||
onPdfViewed: 'onSaleInvoicePdfViewed',
|
||||
|
||||
onCreate: 'onSaleInvoiceCreate',
|
||||
onCreating: 'onSaleInvoiceCreating',
|
||||
onCreated: 'onSaleInvoiceCreated',
|
||||
|
||||
onEdit: 'onSaleInvoiceEdit',
|
||||
onEditing: 'onSaleInvoiceEditing',
|
||||
onEdited: 'onSaleInvoiceEdited',
|
||||
|
||||
onDelete: 'onSaleInvoiceDelete',
|
||||
onDeleting: 'onSaleInvoiceDeleting',
|
||||
onDeleted: 'onSaleInvoiceDeleted',
|
||||
|
||||
onDelivering: 'onSaleInvoiceDelivering',
|
||||
onDeliver: 'onSaleInvoiceDeliver',
|
||||
onDelivered: 'onSaleInvoiceDelivered',
|
||||
|
||||
onPublish: 'onSaleInvoicePublish',
|
||||
onPublished: 'onSaleInvoicePublished',
|
||||
|
||||
onWriteoff: 'onSaleInvoiceWriteoff',
|
||||
onWrittenoff: 'onSaleInvoiceWrittenoff',
|
||||
onWrittenoffCancel: 'onSaleInvoiceWrittenoffCancel',
|
||||
onWrittenoffCanceled: 'onSaleInvoiceWrittenoffCanceled',
|
||||
|
||||
onNotifySms: 'onSaleInvoiceNotifySms',
|
||||
onNotifiedSms: 'onSaleInvoiceNotifiedSms',
|
||||
|
||||
onNotifyMail: 'onSaleInvoiceNotifyMail',
|
||||
onNotifyReminderMail: 'onSaleInvoiceNotifyReminderMail',
|
||||
|
||||
onPreMailSend: 'onSaleInvoicePreMailSend',
|
||||
onMailSend: 'onSaleInvoiceMailSend',
|
||||
onMailSent: 'onSaleInvoiceMailSent',
|
||||
|
||||
onMailReminderSend: 'onSaleInvoiceMailReminderSend',
|
||||
onMailReminderSent: 'onSaleInvoiceMailReminderSent',
|
||||
|
||||
onPublicLinkGenerating: 'onPublicSharableLinkGenerating',
|
||||
onPublicLinkGenerated: 'onPublicSharableLinkGenerated',
|
||||
},
|
||||
|
||||
/**
|
||||
* Sales estimates service.
|
||||
*/
|
||||
saleEstimate: {
|
||||
onPdfViewed: 'onSaleEstimatePdfViewed',
|
||||
|
||||
onCreating: 'onSaleEstimateCreating',
|
||||
onCreated: 'onSaleEstimateCreated',
|
||||
|
||||
onEditing: 'onSaleEstimateEditing',
|
||||
onEdited: 'onSaleEstimateEdited',
|
||||
|
||||
onDeleting: 'onSaleEstimatedDeleting',
|
||||
onDeleted: 'onSaleEstimatedDeleted',
|
||||
|
||||
onPublishing: 'onSaleEstimatedPublishing',
|
||||
onPublished: 'onSaleEstimatedPublished',
|
||||
|
||||
onNotifySms: 'onSaleEstimateNotifySms',
|
||||
onNotifiedSms: 'onSaleEstimateNotifiedSms',
|
||||
|
||||
onDelivering: 'onSaleEstimateDelivering',
|
||||
onDelivered: 'onSaleEstimateDelivered',
|
||||
|
||||
onConvertedToInvoice: 'onSaleEstimateConvertedToInvoice',
|
||||
|
||||
onApproving: 'onSaleEstimateApproving',
|
||||
onApproved: 'onSaleEstimateApproved',
|
||||
|
||||
onRejecting: 'onSaleEstimateRejecting',
|
||||
onRejected: 'onSaleEstimateRejected',
|
||||
|
||||
onNotifyMail: 'onSaleEstimateNotifyMail',
|
||||
|
||||
onPreMailSend: 'onSaleEstimatePreMailSend',
|
||||
onMailSend: 'onSaleEstimateMailSend',
|
||||
onMailSent: 'onSaleEstimateMailSend',
|
||||
|
||||
onViewed: 'onSaleEstimateViewed',
|
||||
},
|
||||
|
||||
/**
|
||||
* Sales receipts service.
|
||||
*/
|
||||
saleReceipt: {
|
||||
onPdfViewed: 'onSaleReceiptPdfViewed',
|
||||
|
||||
onCreating: 'onSaleReceiptsCreating',
|
||||
onCreated: 'onSaleReceiptsCreated',
|
||||
|
||||
onEditing: 'onSaleReceiptsEditing',
|
||||
onEdited: 'onSaleReceiptsEdited',
|
||||
|
||||
onDeleting: 'onSaleReceiptsDeleting',
|
||||
onDeleted: 'onSaleReceiptsDeleted',
|
||||
|
||||
onPublishing: 'onSaleReceiptPublishing',
|
||||
onPublished: 'onSaleReceiptPublished',
|
||||
|
||||
onClosed: 'onSaleReceiptClosed',
|
||||
onClosing: 'onSaleReceiptClosing',
|
||||
|
||||
onNotifySms: 'onSaleReceiptNotifySms',
|
||||
onNotifiedSms: 'onSaleReceiptNotifiedSms',
|
||||
|
||||
onPreMailSend: 'onSaleReceiptPreMailSend',
|
||||
onMailSend: 'onSaleReceiptMailSend',
|
||||
onMailSent: 'onSaleReceiptMailSent',
|
||||
},
|
||||
|
||||
/**
|
||||
* Payment receipts service.
|
||||
*/
|
||||
paymentReceive: {
|
||||
onPdfViewed: 'onPaymentReceivedPdfViewed',
|
||||
|
||||
onCreated: 'onPaymentReceiveCreated',
|
||||
onCreating: 'onPaymentReceiveCreating',
|
||||
|
||||
onEditing: 'onPaymentReceiveEditing',
|
||||
onEdited: 'onPaymentReceiveEdited',
|
||||
|
||||
onDeleting: 'onPaymentReceiveDeleting',
|
||||
onDeleted: 'onPaymentReceiveDeleted',
|
||||
|
||||
onPublishing: 'onPaymentReceivePublishing',
|
||||
onPublished: 'onPaymentReceivePublished',
|
||||
|
||||
onNotifySms: 'onPaymentReceiveNotifySms',
|
||||
onNotifiedSms: 'onPaymentReceiveNotifiedSms',
|
||||
|
||||
onPreMailSend: 'onPaymentReceivePreMailSend',
|
||||
onMailSend: 'onPaymentReceiveMailSend',
|
||||
onMailSent: 'onPaymentReceiveMailSent',
|
||||
},
|
||||
|
||||
/**
|
||||
* Bills service.
|
||||
*/
|
||||
bill: {
|
||||
onCreating: 'onBillCreating',
|
||||
onCreated: 'onBillCreated',
|
||||
|
||||
onEditing: 'onBillEditing',
|
||||
onEdited: 'onBillEdited',
|
||||
|
||||
onDeleting: 'onBillDeleting',
|
||||
onDeleted: 'onBillDeleted',
|
||||
|
||||
onPublishing: 'onBillPublishing',
|
||||
onPublished: 'onBillPublished',
|
||||
|
||||
onOpening: 'onBillOpening',
|
||||
onOpened: 'onBillOpened',
|
||||
},
|
||||
|
||||
/**
|
||||
* Bill payments service.
|
||||
*/
|
||||
billPayment: {
|
||||
onCreating: 'onBillPaymentCreating',
|
||||
onCreated: 'onBillPaymentCreated',
|
||||
|
||||
onEditing: 'onBillPaymentEditing',
|
||||
onEdited: 'onBillPaymentEdited',
|
||||
|
||||
onDeleted: 'onBillPaymentDeleted',
|
||||
onDeleting: 'onBillPaymentDeleting',
|
||||
|
||||
onPublishing: 'onBillPaymentPublishing',
|
||||
onPublished: 'onBillPaymentPublished',
|
||||
},
|
||||
|
||||
/**
|
||||
* Customers services.
|
||||
*/
|
||||
customers: {
|
||||
onCreating: 'onCustomerCreating',
|
||||
onCreated: 'onCustomerCreated',
|
||||
|
||||
onEdited: 'onCustomerEdited',
|
||||
onEditing: 'onCustomerEditing',
|
||||
|
||||
onDeleted: 'onCustomerDeleted',
|
||||
onDeleting: 'onCustomerDeleting',
|
||||
onBulkDeleted: 'onBulkDeleted',
|
||||
|
||||
onOpeningBalanceChanging: 'onCustomerOpeningBalanceChanging',
|
||||
onOpeningBalanceChanged: 'onCustomerOpeingBalanceChanged',
|
||||
|
||||
onActivating: 'onCustomerActivating',
|
||||
onActivated: 'onCustomerActivated',
|
||||
},
|
||||
|
||||
/**
|
||||
* Vendors services.
|
||||
*/
|
||||
vendors: {
|
||||
onCreated: 'onVendorCreated',
|
||||
onCreating: 'onVendorCreating',
|
||||
|
||||
onEdited: 'onVendorEdited',
|
||||
onEditing: 'onVendorEditing',
|
||||
|
||||
onDeleted: 'onVendorDeleted',
|
||||
onDeleting: 'onVendorDeleting',
|
||||
|
||||
onOpeningBalanceChanging: 'onVendorOpeingBalanceChanging',
|
||||
onOpeningBalanceChanged: 'onVendorOpeingBalanceChanged',
|
||||
|
||||
onActivating: 'onVendorActivating',
|
||||
onActivated: 'onVendorActivated',
|
||||
},
|
||||
|
||||
/**
|
||||
* Items service.
|
||||
*/
|
||||
item: {
|
||||
onViewed: 'onItemViewed',
|
||||
|
||||
onCreated: 'onItemCreated',
|
||||
onCreating: 'onItemCreating',
|
||||
|
||||
onEditing: 'onItemEditing',
|
||||
onEdited: 'onItemEdited',
|
||||
|
||||
onDeleted: 'onItemDeleted',
|
||||
onDeleting: 'onItemDeleting',
|
||||
|
||||
onActivating: 'onItemActivating',
|
||||
onActivated: 'onItemActivated',
|
||||
|
||||
onInactivating: 'onInactivating',
|
||||
onInactivated: 'onItemInactivated',
|
||||
},
|
||||
|
||||
/**
|
||||
* Item category service.
|
||||
*/
|
||||
itemCategory: {
|
||||
onCreated: 'onItemCategoryCreated',
|
||||
onEdited: 'onItemCategoryEdited',
|
||||
onDeleted: 'onItemCategoryDeleted',
|
||||
onBulkDeleted: 'onItemCategoryBulkDeleted',
|
||||
},
|
||||
|
||||
/**
|
||||
* Inventory service.
|
||||
*/
|
||||
inventory: {
|
||||
onInventoryTransactionsCreated: 'onInventoryTransactionsCreated',
|
||||
onInventoryTransactionsDeleted: 'onInventoryTransactionsDeleted',
|
||||
|
||||
onComputeItemCostJobScheduled: 'onComputeItemCostJobScheduled',
|
||||
onComputeItemCostJobStarted: 'onComputeItemCostJobStarted',
|
||||
onComputeItemCostJobCompleted: 'onComputeItemCostJobCompleted',
|
||||
|
||||
onInventoryCostEntriesWritten: 'onInventoryCostEntriesWritten',
|
||||
|
||||
onCostLotsGLEntriesBeforeWrite: 'onInventoryCostLotsGLEntriesBeforeWrite',
|
||||
onCostLotsGLEntriesWrite: 'onInventoryCostLotsGLEntriesWrite',
|
||||
},
|
||||
|
||||
/**
|
||||
* Inventory adjustment service.
|
||||
*/
|
||||
inventoryAdjustment: {
|
||||
onQuickCreating: 'onInventoryAdjustmentCreating',
|
||||
onQuickCreated: 'onInventoryAdjustmentQuickCreated',
|
||||
|
||||
onCreated: 'onInventoryAdjustmentCreated',
|
||||
|
||||
onDeleting: 'onInventoryAdjustmentDeleting',
|
||||
onDeleted: 'onInventoryAdjustmentDeleted',
|
||||
|
||||
onPublishing: 'onInventoryAdjustmentPublishing',
|
||||
onPublished: 'onInventoryAdjustmentPublished',
|
||||
},
|
||||
|
||||
/**
|
||||
* Bill landed cost.
|
||||
*/
|
||||
billLandedCost: {
|
||||
onCreate: 'onBillLandedCostCreate',
|
||||
onCreated: 'onBillLandedCostCreated',
|
||||
onDelete: 'onBillLandedCostDelete',
|
||||
onDeleted: 'onBillLandedCostDeleted',
|
||||
},
|
||||
|
||||
cashflow: {
|
||||
onOwnerContributionCreate: 'onCashflowOwnerContributionCreate',
|
||||
onOwnerContributionCreated: 'onCashflowOwnerContributionCreated',
|
||||
|
||||
onOtherIncomeCreate: 'onCashflowOtherIncomeCreate',
|
||||
onOtherIncomeCreated: 'onCashflowOtherIncomeCreated',
|
||||
|
||||
onTransactionCreating: 'onCashflowTransactionCreating',
|
||||
onTransactionCreated: 'onCashflowTransactionCreated',
|
||||
|
||||
onTransactionDeleting: 'onCashflowTransactionDeleting',
|
||||
onTransactionDeleted: 'onCashflowTransactionDeleted',
|
||||
|
||||
onTransactionCategorizing: 'onTransactionCategorizing',
|
||||
onTransactionCategorized: 'onCashflowTransactionCategorized',
|
||||
|
||||
onTransactionUncategorizedCreating: 'onTransactionUncategorizedCreating',
|
||||
onTransactionUncategorizedCreated: 'onTransactionUncategorizedCreated',
|
||||
|
||||
onTransactionUncategorizing: 'onTransactionUncategorizing',
|
||||
onTransactionUncategorized: 'onTransactionUncategorized',
|
||||
|
||||
onTransactionCategorizingAsExpense: 'onTransactionCategorizingAsExpense',
|
||||
onTransactionCategorizedAsExpense: 'onTransactionCategorizedAsExpense',
|
||||
},
|
||||
|
||||
/**
|
||||
* Roles service events.
|
||||
*/
|
||||
roles: {
|
||||
onCreate: 'onRoleCreate',
|
||||
onCreated: 'onRoleCreated',
|
||||
onEdit: 'onRoleEdit',
|
||||
onEdited: 'onRoleEdited',
|
||||
onDelete: 'onRoleDelete',
|
||||
onDeleted: 'onRoleDeleted',
|
||||
},
|
||||
|
||||
tenantUser: {
|
||||
onEdited: 'onTenantUserEdited',
|
||||
onDeleted: 'onTenantUserDeleted',
|
||||
onActivated: 'onTenantUserActivated',
|
||||
onInactivated: 'onTenantUserInactivated',
|
||||
},
|
||||
|
||||
/**
|
||||
* Credit note service.
|
||||
*/
|
||||
creditNote: {
|
||||
onPdfViewed: 'onCreditNotePdfViewed',
|
||||
|
||||
onCreate: 'onCreditNoteCreate',
|
||||
onCreating: 'onCreditNoteCreating',
|
||||
onCreated: 'onCreditNoteCreated',
|
||||
|
||||
onEditing: 'onCreditNoteEditing',
|
||||
onEdit: 'onCreditNoteEdit',
|
||||
onEdited: 'onCreditNoteEdited',
|
||||
|
||||
onDelete: 'onCreditNoteDelete',
|
||||
onDeleting: 'onCreditNoteDeleting',
|
||||
onDeleted: 'onCreditNoteDeleted',
|
||||
|
||||
onOpen: 'onCreditNoteOpen',
|
||||
onOpening: 'onCreditNoteOpening',
|
||||
onOpened: 'onCreditNoteOpened',
|
||||
|
||||
onRefundCreate: 'onCreditNoteRefundCreate',
|
||||
onRefundCreating: 'onCreditNoteRefundCreating',
|
||||
onRefundCreated: 'onCreditNoteRefundCreated',
|
||||
|
||||
onRefundDelete: 'onCreditNoteRefundDelete',
|
||||
onRefundDeleting: 'onCreditNoteRefundDeleting',
|
||||
onRefundDeleted: 'onCreditNoteRefundDeleted',
|
||||
|
||||
onApplyToInvoicesCreated: 'onCreditNoteApplyToInvoiceCreated',
|
||||
onApplyToInvoicesCreate: 'onCreditNoteApplyToInvoiceCreate',
|
||||
onApplyToInvoicesDeleted: 'onCreditNoteApplyToInvoiceDeleted',
|
||||
},
|
||||
|
||||
/**
|
||||
* Vendor credit service.
|
||||
*/
|
||||
vendorCredit: {
|
||||
onCreate: 'onVendorCreditCreate',
|
||||
onCreating: 'onVendorCreditCreating',
|
||||
onCreated: 'onVendorCreditCreated',
|
||||
|
||||
onEdit: 'onVendorCreditEdit',
|
||||
onEditing: 'onVendorCreditEditing',
|
||||
onEdited: 'onVendorCreditEdited',
|
||||
|
||||
onDelete: 'onVendorCreditDelete',
|
||||
onDeleting: 'onVendorCreditDeleting',
|
||||
onDeleted: 'onVendorCreditDeleted',
|
||||
|
||||
onOpen: 'onVendorCreditOpen',
|
||||
onOpened: 'onVendorCreditOpened',
|
||||
|
||||
onRefundCreating: 'onVendorCreditRefundCreating',
|
||||
onRefundCreate: 'onVendorCreditRefundCreate',
|
||||
onRefundCreated: 'onVendorCreditRefundCreated',
|
||||
|
||||
onRefundDelete: 'onVendorCreditRefundDelete',
|
||||
onRefundDeleting: 'onVendorCreditRefundDeleting',
|
||||
onRefundDeleted: 'onVendorCreditRefundDeleted',
|
||||
|
||||
onApplyToInvoicesCreated: 'onVendorCreditApplyToInvoiceCreated',
|
||||
onApplyToInvoicesCreate: 'onVendorCreditApplyToInvoiceCreate',
|
||||
onApplyToInvoicesDeleted: 'onVendorCreditApplyToInvoiceDeleted',
|
||||
},
|
||||
|
||||
transactionsLocking: {
|
||||
locked: 'onTransactionLockingLocked',
|
||||
lockCanceled: 'onTransactionLockingLockCanceled',
|
||||
partialUnlocked: 'onTransactionLockingPartialUnlocked',
|
||||
partialUnlockCanceled: 'onTransactionLockingPartialUnlockCanceled',
|
||||
},
|
||||
|
||||
warehouse: {
|
||||
onCreate: 'onWarehouseCreate',
|
||||
onCreated: 'onWarehouseCreated',
|
||||
|
||||
onEdit: 'onWarehouseEdit',
|
||||
onEdited: 'onWarehouseEdited',
|
||||
|
||||
onDelete: 'onWarehouseDelete',
|
||||
onDeleted: 'onWarehouseDeleted',
|
||||
|
||||
onActivate: 'onWarehouseActivate',
|
||||
onActivated: 'onWarehouseActivated',
|
||||
|
||||
onMarkPrimary: 'onWarehouseMarkPrimary',
|
||||
onMarkedPrimary: 'onWarehouseMarkedPrimary',
|
||||
},
|
||||
|
||||
warehouseTransfer: {
|
||||
onCreate: 'onWarehouseTransferCreate',
|
||||
onCreated: 'onWarehouseTransferCreated',
|
||||
|
||||
onEdit: 'onWarehouseTransferEdit',
|
||||
onEdited: 'onWarehouseTransferEdited',
|
||||
|
||||
onDelete: 'onWarehouseTransferDelete',
|
||||
onDeleted: 'onWarehouseTransferDeleted',
|
||||
|
||||
onInitiate: 'onWarehouseTransferInitiate',
|
||||
onInitiated: 'onWarehouseTransferInitated',
|
||||
|
||||
onTransfer: 'onWarehouseTransferInitiate',
|
||||
onTransferred: 'onWarehouseTransferTransferred',
|
||||
},
|
||||
|
||||
/**
|
||||
* Branches.
|
||||
*/
|
||||
branch: {
|
||||
onActivate: 'onBranchActivate',
|
||||
onActivated: 'onBranchActivated',
|
||||
|
||||
onMarkPrimary: 'onBranchMarkPrimary',
|
||||
onMarkedPrimary: 'onBranchMarkedPrimary',
|
||||
},
|
||||
|
||||
/**
|
||||
* Projects.
|
||||
*/
|
||||
project: {
|
||||
onCreate: 'onProjectCreate',
|
||||
onCreating: 'onProjectCreating',
|
||||
onCreated: 'onProjectCreated',
|
||||
|
||||
onEdit: 'onEditProject',
|
||||
onEditing: 'onEditingProject',
|
||||
onEdited: 'onEditedProject',
|
||||
|
||||
onEditStatus: 'onEditStatusProject',
|
||||
onEditingStatus: 'onEditingStatusProject',
|
||||
onEditedStatus: 'onEditedStatusProject',
|
||||
|
||||
onDelete: 'onDeleteProject',
|
||||
onDeleting: 'onDeletingProject',
|
||||
onDeleted: 'onDeletedProject',
|
||||
},
|
||||
|
||||
/**
|
||||
* Project Tasks.
|
||||
*/
|
||||
projectTask: {
|
||||
onCreate: 'onProjectTaskCreate',
|
||||
onCreating: 'onProjectTaskCreating',
|
||||
onCreated: 'onProjectTaskCreated',
|
||||
|
||||
onEdit: 'onProjectTaskEdit',
|
||||
onEditing: 'onProjectTaskEditing',
|
||||
onEdited: 'onProjectTaskEdited',
|
||||
|
||||
onDelete: 'onProjectTaskDelete',
|
||||
onDeleting: 'onProjectTaskDeleting',
|
||||
onDeleted: 'onProjectTaskDeleted',
|
||||
},
|
||||
|
||||
/**
|
||||
* Project Times.
|
||||
*/
|
||||
projectTime: {
|
||||
onCreate: 'onProjectTimeCreate',
|
||||
onCreating: 'onProjectTimeCreating',
|
||||
onCreated: 'onProjectTimeCreated',
|
||||
|
||||
onEdit: 'onProjectTimeEdit',
|
||||
onEditing: 'onProjectTimeEditing',
|
||||
onEdited: 'onProjectTimeEdited',
|
||||
|
||||
onDelete: 'onProjectTimeDelete',
|
||||
onDeleting: 'onProjectTimeDeleting',
|
||||
onDeleted: 'onProjectTimeDeleted',
|
||||
},
|
||||
|
||||
taxRates: {
|
||||
onCreating: 'onTaxRateCreating',
|
||||
onCreated: 'onTaxRateCreated',
|
||||
|
||||
onEditing: 'onTaxRateEditing',
|
||||
onEdited: 'onTaxRateEdited',
|
||||
|
||||
onDeleting: 'onTaxRateDeleting',
|
||||
onDeleted: 'onTaxRateDeleted',
|
||||
|
||||
onActivating: 'onTaxRateActivating',
|
||||
onActivated: 'onTaxRateActivated',
|
||||
|
||||
onInactivating: 'onTaxRateInactivating',
|
||||
onInactivated: 'onTaxRateInactivated',
|
||||
},
|
||||
|
||||
plaid: {
|
||||
onItemCreated: 'onPlaidItemCreated',
|
||||
onTransactionsSynced: 'onPlaidTransactionsSynced',
|
||||
},
|
||||
|
||||
// Bank rules.
|
||||
bankRules: {
|
||||
onCreating: 'onBankRuleCreating',
|
||||
onCreated: 'onBankRuleCreated',
|
||||
|
||||
onEditing: 'onBankRuleEditing',
|
||||
onEdited: 'onBankRuleEdited',
|
||||
|
||||
onDeleting: 'onBankRuleDeleting',
|
||||
onDeleted: 'onBankRuleDeleted',
|
||||
},
|
||||
|
||||
// Bank matching.
|
||||
bankMatch: {
|
||||
onMatching: 'onBankTransactionMatching',
|
||||
onMatched: 'onBankTransactionMatched',
|
||||
|
||||
onUnmatching: 'onBankTransactionUnmathcing',
|
||||
onUnmatched: 'onBankTransactionUnmathced',
|
||||
},
|
||||
|
||||
bankTransactions: {
|
||||
onExcluding: 'onBankTransactionExclude',
|
||||
onExcluded: 'onBankTransactionExcluded',
|
||||
|
||||
onUnexcluding: 'onBankTransactionUnexcluding',
|
||||
onUnexcluded: 'onBankTransactionUnexcluded',
|
||||
|
||||
onPendingRemoving: 'onBankTransactionPendingRemoving',
|
||||
onPendingRemoved: 'onBankTransactionPendingRemoved',
|
||||
},
|
||||
|
||||
bankAccount: {
|
||||
onDisconnecting: 'onBankAccountDisconnecting',
|
||||
onDisconnected: 'onBankAccountDisconnected',
|
||||
},
|
||||
|
||||
// Import files.
|
||||
import: {
|
||||
onImportCommitted: 'onImportFileCommitted',
|
||||
},
|
||||
|
||||
// Branding templates
|
||||
pdfTemplate: {
|
||||
onCreating: 'onPdfTemplateCreating',
|
||||
onCreated: 'onPdfTemplateCreated',
|
||||
|
||||
onEditing: 'onPdfTemplateEditing',
|
||||
onEdited: 'onPdfTemplatedEdited',
|
||||
|
||||
onDeleting: 'onPdfTemplateDeleting',
|
||||
onDeleted: 'onPdfTemplateDeleted',
|
||||
|
||||
onAssignedDefault: 'onPdfTemplateAssignedDefault',
|
||||
onAssigningDefault: 'onPdfTemplateAssigningDefault',
|
||||
},
|
||||
|
||||
// Payment method.
|
||||
paymentMethod: {
|
||||
onEditing: 'onPaymentMethodEditing',
|
||||
onEdited: 'onPaymentMethodEdited',
|
||||
|
||||
onDeleted: 'onPaymentMethodDeleted',
|
||||
},
|
||||
|
||||
// Payment methods integrations
|
||||
paymentIntegrationLink: {
|
||||
onPaymentIntegrationLink: 'onPaymentIntegrationLink',
|
||||
onPaymentIntegrationDeleteLink: 'onPaymentIntegrationDeleteLink',
|
||||
},
|
||||
|
||||
// Stripe Payment Integration
|
||||
stripeIntegration: {
|
||||
onAccountCreated: 'onStripeIntegrationAccountCreated',
|
||||
onAccountDeleted: 'onStripeIntegrationAccountDeleted',
|
||||
|
||||
onPaymentLinkCreated: 'onStripePaymentLinkCreated',
|
||||
onPaymentLinkInactivated: 'onStripePaymentLinkInactivated',
|
||||
|
||||
onOAuthCodeGranted: 'onStripeOAuthCodeGranted',
|
||||
},
|
||||
|
||||
// Stripe Payment Webhooks
|
||||
stripeWebhooks: {
|
||||
onCheckoutSessionCompleted: 'onStripeCheckoutSessionCompleted',
|
||||
onAccountUpdated: 'onStripeAccountUpdated',
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import {
|
||||
ExceptionFilter,
|
||||
Catch,
|
||||
ArgumentsHost,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
import { ServiceError } from '@/modules/Items/ServiceError';
|
||||
|
||||
@Catch(ServiceError)
|
||||
export class ServiceErrorFilter implements ExceptionFilter {
|
||||
catch(exception: ServiceError, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse<Response>();
|
||||
const status = exception.getStatus();
|
||||
|
||||
response.status(status).json({
|
||||
statusCode: status,
|
||||
errorType: exception.errorType,
|
||||
message: exception.message,
|
||||
payload: exception.payload,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -70,10 +70,7 @@ export class SerializeInterceptor implements NestInterceptor<any, any> {
|
||||
next: CallHandler<any>,
|
||||
): Observable<any> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
|
||||
// Transform both body and query parameters
|
||||
request.body = this.strategy.in(request.body);
|
||||
request.query = this.strategy.in(request.query);
|
||||
|
||||
// handle returns stream..
|
||||
return next.handle().pipe(map(this.strategy.out));
|
||||
21
packages/server-nest/src/i18n/en/test.json
Normal file
21
packages/server-nest/src/i18n/en/test.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"HELLO": "Hello",
|
||||
"PRODUCT": {
|
||||
"NEW": "New Product: {name}"
|
||||
},
|
||||
"ENGLISH": "English",
|
||||
"ARRAY": ["ONE", "TWO", "THREE"],
|
||||
"cat": "Cat",
|
||||
"cat_name": "Cat: {name}",
|
||||
"set-up-password": {
|
||||
"heading": "Hello, {username}",
|
||||
"title": "Forgot password",
|
||||
"followLink": "Please follow the link to set up your password"
|
||||
},
|
||||
"day_interval": {
|
||||
"one": "Every day",
|
||||
"other": "Every {count} days",
|
||||
"zero": "Never"
|
||||
},
|
||||
"nested": "We go shopping: $t(test.day_interval, {{\"count\": {count} }})"
|
||||
}
|
||||
174
packages/server-nest/src/interfaces/Account.ts
Normal file
174
packages/server-nest/src/interfaces/Account.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
import { Knex } from 'knex';
|
||||
|
||||
export interface IAccountDTO {
|
||||
name: string;
|
||||
code: string;
|
||||
description: string;
|
||||
accountType: string;
|
||||
parentAccountId?: number;
|
||||
active: boolean;
|
||||
bankBalance?: number;
|
||||
accountMask?: string;
|
||||
}
|
||||
|
||||
export interface IAccountCreateDTO extends IAccountDTO {
|
||||
currencyCode?: string;
|
||||
plaidAccountId?: string;
|
||||
plaidItemId?: string;
|
||||
}
|
||||
|
||||
export interface IAccountEditDTO extends IAccountDTO {}
|
||||
|
||||
export interface IAccount {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string;
|
||||
code: string;
|
||||
index: number;
|
||||
description: string;
|
||||
accountType: string;
|
||||
parentAccountId: number;
|
||||
active: boolean;
|
||||
predefined: boolean;
|
||||
amount: number;
|
||||
currencyCode: string;
|
||||
transactions?: any[];
|
||||
type?: any[];
|
||||
accountNormal: string;
|
||||
accountParentType: string;
|
||||
bankBalance: string;
|
||||
plaidItemId: number | null;
|
||||
lastFeedsUpdatedAt: Date;
|
||||
}
|
||||
|
||||
export enum AccountNormal {
|
||||
DEBIT = 'debit',
|
||||
CREDIT = 'credit',
|
||||
}
|
||||
|
||||
export interface IAccountsTransactionsFilter {
|
||||
accountId?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface IAccountTransaction {
|
||||
id?: number;
|
||||
|
||||
credit: number;
|
||||
debit: number;
|
||||
currencyCode: string;
|
||||
exchangeRate: number;
|
||||
|
||||
accountId: number;
|
||||
contactId?: number | null;
|
||||
date: string | Date;
|
||||
|
||||
referenceType: string;
|
||||
referenceTypeFormatted: string;
|
||||
referenceId: number;
|
||||
|
||||
referenceNumber?: string;
|
||||
|
||||
transactionNumber?: string;
|
||||
transactionType?: string;
|
||||
|
||||
note?: string;
|
||||
|
||||
index: number;
|
||||
indexGroup?: number;
|
||||
|
||||
costable?: boolean;
|
||||
|
||||
userId?: number;
|
||||
itemId?: number;
|
||||
branchId?: number;
|
||||
projectId?: number;
|
||||
|
||||
account?: IAccount;
|
||||
|
||||
taxRateId?: number;
|
||||
taxRate?: number;
|
||||
}
|
||||
export interface IAccountResponse extends IAccount {}
|
||||
|
||||
export enum IAccountsStructureType {
|
||||
Tree = 'tree',
|
||||
Flat = 'flat',
|
||||
}
|
||||
|
||||
export interface IAccountsFilter {
|
||||
stringifiedFilterRoles?: string;
|
||||
onlyInactive: boolean;
|
||||
structure?: IAccountsStructureType;
|
||||
}
|
||||
|
||||
export interface IAccountType {
|
||||
label: string;
|
||||
key: string;
|
||||
normal: string;
|
||||
rootType: string;
|
||||
childType: string;
|
||||
balanceSheet: boolean;
|
||||
incomeSheet: boolean;
|
||||
}
|
||||
|
||||
export interface IAccountsTypesService {
|
||||
getAccountsTypes(tenantId: number): Promise<IAccountType>;
|
||||
}
|
||||
|
||||
export interface IAccountEventCreatingPayload {
|
||||
tenantId: number;
|
||||
accountDTO: any;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
export interface IAccountEventCreatedPayload {
|
||||
tenantId: number;
|
||||
account: IAccount;
|
||||
accountId: number;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface IAccountEventEditedPayload {
|
||||
tenantId: number;
|
||||
account: IAccount;
|
||||
oldAccount: IAccount;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface IAccountEventDeletedPayload {
|
||||
tenantId: number;
|
||||
accountId: number;
|
||||
oldAccount: IAccount;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface IAccountEventDeletePayload {
|
||||
trx: Knex.Transaction;
|
||||
oldAccount: IAccount;
|
||||
tenantId: number;
|
||||
}
|
||||
|
||||
export interface IAccountEventActivatedPayload {
|
||||
tenantId: number;
|
||||
accountId: number;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export enum AccountAction {
|
||||
CREATE = 'Create',
|
||||
EDIT = 'Edit',
|
||||
DELETE = 'Delete',
|
||||
VIEW = 'View',
|
||||
TransactionsLocking = 'TransactionsLocking',
|
||||
}
|
||||
|
||||
export enum TaxRateAction {
|
||||
CREATE = 'Create',
|
||||
EDIT = 'Edit',
|
||||
DELETE = 'Delete',
|
||||
VIEW = 'View',
|
||||
}
|
||||
|
||||
export interface CreateAccountParams {
|
||||
ignoreUniqueName: boolean;
|
||||
}
|
||||
165
packages/server-nest/src/interfaces/Item.ts
Normal file
165
packages/server-nest/src/interfaces/Item.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { Knex } from 'knex';
|
||||
import { Item } from '@/modules/Items/models/Item';
|
||||
// import { AbilitySubject } from '@/interfaces';
|
||||
// import { IFilterRole } from '@/interfaces/DynamicFilter';
|
||||
|
||||
export interface IItem {
|
||||
id: number;
|
||||
name: string;
|
||||
type: string;
|
||||
code: string;
|
||||
|
||||
sellable: boolean;
|
||||
purchasable: boolean;
|
||||
|
||||
costPrice: number;
|
||||
sellPrice: number;
|
||||
currencyCode: string;
|
||||
|
||||
costAccountId: number;
|
||||
sellAccountId: number;
|
||||
inventoryAccountId: number;
|
||||
|
||||
sellDescription: string;
|
||||
purchaseDescription: string;
|
||||
|
||||
sellTaxRateId: number;
|
||||
purchaseTaxRateId: number;
|
||||
|
||||
quantityOnHand: number;
|
||||
|
||||
note: string;
|
||||
active: boolean;
|
||||
|
||||
categoryId: number;
|
||||
userId: number;
|
||||
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export class IItemDTO {
|
||||
@ApiProperty()
|
||||
name: string;
|
||||
|
||||
@ApiProperty()
|
||||
type: string;
|
||||
|
||||
@ApiProperty()
|
||||
code: string;
|
||||
|
||||
@ApiProperty()
|
||||
sellable: boolean;
|
||||
|
||||
@ApiProperty()
|
||||
purchasable: boolean;
|
||||
|
||||
@ApiProperty()
|
||||
costPrice: number;
|
||||
|
||||
@ApiProperty()
|
||||
sellPrice: number;
|
||||
|
||||
@ApiProperty()
|
||||
currencyCode: string;
|
||||
|
||||
@ApiProperty()
|
||||
costAccountId: number;
|
||||
|
||||
@ApiProperty()
|
||||
sellAccountId: number;
|
||||
|
||||
@ApiProperty()
|
||||
inventoryAccountId: number;
|
||||
|
||||
@ApiProperty()
|
||||
sellDescription: string;
|
||||
|
||||
@ApiProperty()
|
||||
purchaseDescription: string;
|
||||
|
||||
@ApiProperty()
|
||||
sellTaxRateId: number;
|
||||
|
||||
@ApiProperty()
|
||||
purchaseTaxRateId: number;
|
||||
|
||||
@ApiProperty()
|
||||
quantityOnHand: number;
|
||||
|
||||
@ApiProperty()
|
||||
note: string;
|
||||
|
||||
@ApiProperty()
|
||||
active: boolean;
|
||||
|
||||
@ApiProperty()
|
||||
categoryId: number;
|
||||
}
|
||||
|
||||
export interface IItemCreateDTO extends IItemDTO {}
|
||||
export interface IItemEditDTO extends IItemDTO {}
|
||||
|
||||
// export interface IItemsService {
|
||||
// getItem(tenantId: number, itemId: number): Promise<IItem>;
|
||||
// deleteItem(tenantId: number, itemId: number): Promise<void>;
|
||||
// editItem(tenantId: number, itemId: number, itemDTO: IItemDTO): Promise<IItem>;
|
||||
// newItem(tenantId: number, itemDTO: IItemDTO): Promise<IItem>;
|
||||
// itemsList(
|
||||
// tenantId: number,
|
||||
// itemsFilter: IItemsFilter,
|
||||
// ): Promise<{ items: IItem[] }>;
|
||||
// }
|
||||
|
||||
// export interface IItemsFilter extends IDynamicListFilterDTO {
|
||||
// stringifiedFilterRoles?: string;
|
||||
// page: number;
|
||||
// pageSize: number;
|
||||
// inactiveMode: boolean;
|
||||
// viewSlug?: string;
|
||||
// }
|
||||
|
||||
// export interface IItemsAutoCompleteFilter {
|
||||
// limit: number;
|
||||
// keyword: string;
|
||||
// filterRoles?: IFilterRole[];
|
||||
// columnSortBy: string;
|
||||
// sortOrder: string;
|
||||
// }
|
||||
|
||||
export interface IItemEventCreatedPayload {
|
||||
// tenantId: number;
|
||||
item: Item;
|
||||
itemId: number;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface IItemEventEditedPayload {
|
||||
item: Item;
|
||||
oldItem: Item;
|
||||
itemId: number;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface IItemEventDeletingPayload {
|
||||
// tenantId: number;
|
||||
trx: Knex.Transaction;
|
||||
oldItem: Item;
|
||||
}
|
||||
|
||||
export interface IItemEventDeletedPayload {
|
||||
// tenantId: number;
|
||||
itemId: number;
|
||||
oldItem: Item;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export enum ItemAction {
|
||||
CREATE = 'Create',
|
||||
EDIT = 'Edit',
|
||||
DELETE = 'Delete',
|
||||
VIEW = 'View',
|
||||
}
|
||||
|
||||
// export type ItemAbility = [ItemAction, AbilitySubject.Item];
|
||||
193
packages/server-nest/src/interfaces/Model.ts
Normal file
193
packages/server-nest/src/interfaces/Model.ts
Normal file
@@ -0,0 +1,193 @@
|
||||
export interface IModel {
|
||||
name: string;
|
||||
tableName: string;
|
||||
fields: { [key: string]: any };
|
||||
}
|
||||
|
||||
export interface IFilterMeta {
|
||||
sortOrder: string;
|
||||
sortBy: string;
|
||||
}
|
||||
|
||||
export interface IPaginationMeta {
|
||||
pageSize: number;
|
||||
page: number;
|
||||
}
|
||||
|
||||
export interface IModelMetaDefaultSort {
|
||||
sortOrder: ISortOrder;
|
||||
sortField: string;
|
||||
}
|
||||
|
||||
export type IModelColumnType =
|
||||
| 'text'
|
||||
| 'number'
|
||||
| 'enumeration'
|
||||
| 'boolean'
|
||||
| 'relation';
|
||||
|
||||
export type ISortOrder = 'DESC' | 'ASC';
|
||||
|
||||
export interface IModelMetaFieldCommon {
|
||||
name: string;
|
||||
column: string;
|
||||
columnable?: boolean;
|
||||
customQuery?: Function;
|
||||
required?: boolean;
|
||||
importHint?: string;
|
||||
importableRelationLabel?: string;
|
||||
order?: number;
|
||||
unique?: number;
|
||||
dataTransferObjectKey?: string;
|
||||
}
|
||||
|
||||
export interface IModelMetaFieldText {
|
||||
fieldType: 'text';
|
||||
minLength?: number;
|
||||
maxLength?: number;
|
||||
}
|
||||
export interface IModelMetaFieldBoolean {
|
||||
fieldType: 'boolean';
|
||||
}
|
||||
export interface IModelMetaFieldNumber {
|
||||
fieldType: 'number';
|
||||
min?: number;
|
||||
max?: number;
|
||||
}
|
||||
export interface IModelMetaFieldDate {
|
||||
fieldType: 'date';
|
||||
}
|
||||
export interface IModelMetaFieldUrl {
|
||||
fieldType: 'url';
|
||||
}
|
||||
export type IModelMetaField = IModelMetaFieldCommon &
|
||||
(
|
||||
| IModelMetaFieldText
|
||||
| IModelMetaFieldNumber
|
||||
| IModelMetaFieldBoolean
|
||||
| IModelMetaFieldDate
|
||||
| IModelMetaFieldUrl
|
||||
| IModelMetaEnumerationField
|
||||
| IModelMetaRelationField
|
||||
| IModelMetaCollectionField
|
||||
);
|
||||
|
||||
export interface IModelMetaEnumerationOption {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface IModelMetaEnumerationField {
|
||||
fieldType: 'enumeration';
|
||||
options: IModelMetaEnumerationOption[];
|
||||
}
|
||||
|
||||
export interface IModelMetaRelationFieldCommon {
|
||||
fieldType: 'relation';
|
||||
}
|
||||
|
||||
export interface IModelMetaRelationEnumerationField {
|
||||
relationType: 'enumeration';
|
||||
relationKey: string;
|
||||
relationEntityLabel: string;
|
||||
relationEntityKey: string;
|
||||
}
|
||||
|
||||
export interface IModelMetaFieldWithFields {
|
||||
fields: IModelMetaFieldCommon2 &
|
||||
(
|
||||
| IModelMetaFieldText
|
||||
| IModelMetaFieldNumber
|
||||
| IModelMetaFieldBoolean
|
||||
| IModelMetaFieldDate
|
||||
| IModelMetaFieldUrl
|
||||
| IModelMetaEnumerationField
|
||||
| IModelMetaRelationField
|
||||
);
|
||||
}
|
||||
|
||||
interface IModelMetaCollectionObjectField extends IModelMetaFieldWithFields {
|
||||
collectionOf: 'object';
|
||||
}
|
||||
|
||||
export interface IModelMetaCollectionFieldCommon {
|
||||
fieldType: 'collection';
|
||||
collectionMinLength?: number;
|
||||
collectionMaxLength?: number;
|
||||
}
|
||||
|
||||
export type IModelMetaCollectionField = IModelMetaCollectionFieldCommon &
|
||||
IModelMetaCollectionObjectField;
|
||||
|
||||
export type IModelMetaRelationField = IModelMetaRelationFieldCommon &
|
||||
IModelMetaRelationEnumerationField;
|
||||
|
||||
interface IModelPrintMeta {
|
||||
pageTitle: string;
|
||||
}
|
||||
|
||||
export interface IModelMeta {
|
||||
defaultFilterField: string;
|
||||
defaultSort: IModelMetaDefaultSort;
|
||||
|
||||
exportable?: boolean;
|
||||
exportFlattenOn?: string;
|
||||
|
||||
importable?: boolean;
|
||||
importAggregator?: string;
|
||||
importAggregateOn?: string;
|
||||
importAggregateBy?: string;
|
||||
|
||||
print?: IModelPrintMeta;
|
||||
|
||||
fields: Record<string, IModelMetaField>;
|
||||
fields2: Record<string, IModelMetaField2>;
|
||||
columns: Record<string, IModelMetaColumn>;
|
||||
}
|
||||
|
||||
// ----
|
||||
export interface IModelMetaFieldCommon2 {
|
||||
name: string;
|
||||
required?: boolean;
|
||||
importHint?: string;
|
||||
order?: number;
|
||||
unique?: number;
|
||||
features?: Array<any>;
|
||||
}
|
||||
|
||||
export interface IModelMetaRelationField2 {
|
||||
fieldType: 'relation';
|
||||
relationModel: string;
|
||||
importableRelationLabel: string | string[];
|
||||
}
|
||||
|
||||
export type IModelMetaField2 = IModelMetaFieldCommon2 &
|
||||
(
|
||||
| IModelMetaFieldText
|
||||
| IModelMetaFieldNumber
|
||||
| IModelMetaFieldBoolean
|
||||
| IModelMetaFieldDate
|
||||
| IModelMetaFieldUrl
|
||||
| IModelMetaEnumerationField
|
||||
| IModelMetaRelationField2
|
||||
| IModelMetaCollectionField
|
||||
);
|
||||
|
||||
export interface ImodelMetaColumnMeta {
|
||||
name: string;
|
||||
accessor?: string;
|
||||
exportable?: boolean;
|
||||
}
|
||||
|
||||
interface IModelMetaColumnText {
|
||||
type: 'text;';
|
||||
}
|
||||
|
||||
interface IModelMetaColumnCollection {
|
||||
type: 'collection';
|
||||
collectionOf: 'object';
|
||||
columns: { [key: string]: ImodelMetaColumnMeta & IModelMetaColumnText };
|
||||
}
|
||||
|
||||
export type IModelMetaColumn = ImodelMetaColumnMeta &
|
||||
(IModelMetaColumnText | IModelMetaColumnCollection);
|
||||
66
packages/server-nest/src/libs/chromiumly/ConvertUtils.ts
Normal file
66
packages/server-nest/src/libs/chromiumly/ConvertUtils.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import FormData from 'form-data';
|
||||
import { GotenbergUtils } from './GotenbergUtils';
|
||||
import { PageProperties } from './_types';
|
||||
|
||||
export class ConverterUtils {
|
||||
public static injectPageProperties(
|
||||
data: FormData,
|
||||
pageProperties: PageProperties
|
||||
): void {
|
||||
if (pageProperties.size) {
|
||||
GotenbergUtils.assert(
|
||||
pageProperties.size.width >= 1.0 && pageProperties.size.height >= 1.5,
|
||||
'size is smaller than the minimum printing requirements (i.e. 1.0 x 1.5 in)'
|
||||
);
|
||||
|
||||
data.append('paperWidth', pageProperties.size.width);
|
||||
data.append('paperHeight', pageProperties.size.height);
|
||||
}
|
||||
if (pageProperties.margins) {
|
||||
GotenbergUtils.assert(
|
||||
pageProperties.margins.top >= 0 &&
|
||||
pageProperties.margins.bottom >= 0 &&
|
||||
pageProperties.margins.left >= 0 &&
|
||||
pageProperties.margins.left >= 0,
|
||||
'negative margins are not allowed'
|
||||
);
|
||||
data.append('marginTop', pageProperties.margins.top);
|
||||
data.append('marginBottom', pageProperties.margins.bottom);
|
||||
data.append('marginLeft', pageProperties.margins.left);
|
||||
data.append('marginRight', pageProperties.margins.right);
|
||||
}
|
||||
if (pageProperties.preferCssPageSize) {
|
||||
data.append(
|
||||
'preferCssPageSize',
|
||||
String(pageProperties.preferCssPageSize)
|
||||
);
|
||||
}
|
||||
if (pageProperties.printBackground) {
|
||||
data.append('printBackground', String(pageProperties.printBackground));
|
||||
}
|
||||
if (pageProperties.landscape) {
|
||||
data.append('landscape', String(pageProperties.landscape));
|
||||
}
|
||||
if (pageProperties.scale) {
|
||||
GotenbergUtils.assert(
|
||||
pageProperties.scale >= 0.1 && pageProperties.scale <= 2.0,
|
||||
'scale is outside of [0.1 - 2] range'
|
||||
);
|
||||
data.append('scale', pageProperties.scale);
|
||||
}
|
||||
|
||||
if (pageProperties.nativePageRanges) {
|
||||
GotenbergUtils.assert(
|
||||
pageProperties.nativePageRanges.from > 0 &&
|
||||
pageProperties.nativePageRanges.to > 0 &&
|
||||
pageProperties.nativePageRanges.to >=
|
||||
pageProperties.nativePageRanges.from,
|
||||
'page ranges syntax error'
|
||||
);
|
||||
data.append(
|
||||
'nativePageRanges',
|
||||
`${pageProperties.nativePageRanges.from}-${pageProperties.nativePageRanges.to}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
24
packages/server-nest/src/libs/chromiumly/GotenbergUtils.ts
Normal file
24
packages/server-nest/src/libs/chromiumly/GotenbergUtils.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import FormData from 'form-data';
|
||||
import Axios from 'axios';
|
||||
|
||||
export class GotenbergUtils {
|
||||
public static assert(condition: boolean, message: string): asserts condition {
|
||||
if (!condition) {
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
|
||||
public static async fetch(endpoint: string, data: FormData): Promise<Buffer> {
|
||||
try {
|
||||
const response = await Axios.post(endpoint, data, {
|
||||
headers: {
|
||||
...data.getHeaders(),
|
||||
},
|
||||
responseType: 'arraybuffer', // This ensures you get a Buffer bac
|
||||
});
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
38
packages/server-nest/src/libs/chromiumly/HTMLConvert.ts
Normal file
38
packages/server-nest/src/libs/chromiumly/HTMLConvert.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { constants, createReadStream, PathLike, promises } from 'fs';
|
||||
import FormData from 'form-data';
|
||||
import { GotenbergUtils } from './GotenbergUtils';
|
||||
import { IConverter, PageProperties } from './_types';
|
||||
import { PdfFormat, ChromiumRoute } from './_types';
|
||||
import { ConverterUtils } from './ConvertUtils';
|
||||
import { Converter } from './Converter';
|
||||
|
||||
export class HtmlConverter extends Converter implements IConverter {
|
||||
constructor() {
|
||||
super(ChromiumRoute.HTML);
|
||||
}
|
||||
|
||||
async convert({
|
||||
html,
|
||||
properties,
|
||||
pdfFormat,
|
||||
}: {
|
||||
html: PathLike;
|
||||
properties?: PageProperties;
|
||||
pdfFormat?: PdfFormat;
|
||||
}): Promise<Buffer> {
|
||||
try {
|
||||
await promises.access(html, constants.R_OK);
|
||||
const data = new FormData();
|
||||
if (pdfFormat) {
|
||||
data.append('pdfFormat', pdfFormat);
|
||||
}
|
||||
data.append('index.html', createReadStream(html));
|
||||
if (properties) {
|
||||
ConverterUtils.injectPageProperties(data, properties);
|
||||
}
|
||||
return GotenbergUtils.fetch(this.endpoint, data);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
38
packages/server-nest/src/libs/chromiumly/UrlConvert.ts
Normal file
38
packages/server-nest/src/libs/chromiumly/UrlConvert.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import FormData from 'form-data';
|
||||
import { IConverter, PageProperties, PdfFormat, ChromiumRoute } from './_types';
|
||||
import { ConverterUtils } from './ConvertUtils';
|
||||
import { Converter } from './Converter';
|
||||
import { GotenbergUtils } from './GotenbergUtils';
|
||||
|
||||
export class UrlConverter extends Converter implements IConverter {
|
||||
constructor() {
|
||||
super(ChromiumRoute.URL);
|
||||
}
|
||||
|
||||
async convert({
|
||||
url,
|
||||
properties,
|
||||
pdfFormat,
|
||||
}: {
|
||||
url: string;
|
||||
properties?: PageProperties;
|
||||
pdfFormat?: PdfFormat;
|
||||
}): Promise<Buffer> {
|
||||
try {
|
||||
const _url = new URL(url);
|
||||
const data = new FormData();
|
||||
|
||||
if (pdfFormat) {
|
||||
data.append('pdfFormat', pdfFormat);
|
||||
}
|
||||
data.append('url', _url.href);
|
||||
|
||||
if (properties) {
|
||||
ConverterUtils.injectPageProperties(data, properties);
|
||||
}
|
||||
return GotenbergUtils.fetch(this.endpoint, data);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
172
packages/server-nest/src/libs/logic-evaluation/Lexer.js
Normal file
172
packages/server-nest/src/libs/logic-evaluation/Lexer.js
Normal file
@@ -0,0 +1,172 @@
|
||||
|
||||
const OperationType = {
|
||||
LOGIC: 'LOGIC',
|
||||
STRING: 'STRING',
|
||||
COMPARISON: 'COMPARISON',
|
||||
MATH: 'MATH',
|
||||
};
|
||||
|
||||
export class Lexer {
|
||||
// operation table
|
||||
static get optable() {
|
||||
return {
|
||||
'=': OperationType.LOGIC,
|
||||
'&': OperationType.LOGIC,
|
||||
'|': OperationType.LOGIC,
|
||||
'?': OperationType.LOGIC,
|
||||
':': OperationType.LOGIC,
|
||||
|
||||
'\'': OperationType.STRING,
|
||||
'"': OperationType.STRING,
|
||||
|
||||
'!': OperationType.COMPARISON,
|
||||
'>': OperationType.COMPARISON,
|
||||
'<': OperationType.COMPARISON,
|
||||
|
||||
'(': OperationType.MATH,
|
||||
')': OperationType.MATH,
|
||||
'+': OperationType.MATH,
|
||||
'-': OperationType.MATH,
|
||||
'*': OperationType.MATH,
|
||||
'/': OperationType.MATH,
|
||||
'%': OperationType.MATH,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
* @param {*} expression -
|
||||
*/
|
||||
constructor(expression) {
|
||||
this.currentIndex = 0;
|
||||
this.input = expression;
|
||||
this.tokenList = [];
|
||||
}
|
||||
|
||||
getTokens() {
|
||||
let tok;
|
||||
do {
|
||||
// read current token, so step should be -1
|
||||
tok = this.pickNext(-1);
|
||||
const pos = this.currentIndex;
|
||||
switch (Lexer.optable[tok]) {
|
||||
case OperationType.LOGIC:
|
||||
// == && || ===
|
||||
this.readLogicOpt(tok);
|
||||
break;
|
||||
|
||||
case OperationType.STRING:
|
||||
this.readString(tok);
|
||||
break;
|
||||
|
||||
case OperationType.COMPARISON:
|
||||
this.readCompare(tok);
|
||||
break;
|
||||
|
||||
case OperationType.MATH:
|
||||
this.receiveToken();
|
||||
break;
|
||||
|
||||
default:
|
||||
this.readValue(tok);
|
||||
}
|
||||
|
||||
// if the pos not changed, this loop will go into a infinite loop, every step of while loop,
|
||||
// we must move the pos forward
|
||||
// so here we should throw error, for example `1 & 2`
|
||||
if (pos === this.currentIndex && tok !== undefined) {
|
||||
const err = new Error(`unkonw token ${tok} from input string ${this.input}`);
|
||||
err.name = 'UnknowToken';
|
||||
throw err;
|
||||
}
|
||||
} while (tok !== undefined)
|
||||
|
||||
return this.tokenList;
|
||||
}
|
||||
|
||||
/**
|
||||
* read next token, the index param can set next step, default go foward 1 step
|
||||
*
|
||||
* @param index next postion
|
||||
*/
|
||||
pickNext(index = 0) {
|
||||
return this.input[index + this.currentIndex + 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Store token into result tokenList, and move the pos index
|
||||
*
|
||||
* @param index
|
||||
*/
|
||||
receiveToken(index = 1) {
|
||||
const tok = this.input.slice(this.currentIndex, this.currentIndex + index).trim();
|
||||
// skip empty string
|
||||
if (tok) {
|
||||
this.tokenList.push(tok);
|
||||
}
|
||||
|
||||
this.currentIndex += index;
|
||||
}
|
||||
|
||||
// ' or "
|
||||
readString(tok) {
|
||||
let next;
|
||||
let index = 0;
|
||||
do {
|
||||
next = this.pickNext(index);
|
||||
index += 1;
|
||||
} while (next !== tok && next !== undefined);
|
||||
this.receiveToken(index + 1);
|
||||
}
|
||||
|
||||
// > or < or >= or <= or !==
|
||||
// tok in (>, <, !)
|
||||
readCompare(tok) {
|
||||
if (this.pickNext() !== '=') {
|
||||
this.receiveToken(1);
|
||||
return;
|
||||
}
|
||||
// !==
|
||||
if (tok === '!' && this.pickNext(1) === '=') {
|
||||
this.receiveToken(3);
|
||||
return;
|
||||
}
|
||||
this.receiveToken(2);
|
||||
}
|
||||
|
||||
// === or ==
|
||||
// && ||
|
||||
readLogicOpt(tok) {
|
||||
if (this.pickNext() === tok) {
|
||||
// ===
|
||||
if (tok === '=' && this.pickNext(1) === tok) {
|
||||
return this.receiveToken(3);
|
||||
}
|
||||
// == && ||
|
||||
return this.receiveToken(2);
|
||||
}
|
||||
// handle as &&
|
||||
// a ? b : c is equal to a && b || c
|
||||
if (tok === '?' || tok === ':') {
|
||||
return this.receiveToken(1);
|
||||
}
|
||||
}
|
||||
|
||||
readValue(tok) {
|
||||
if (!tok) {
|
||||
return;
|
||||
}
|
||||
|
||||
let index = 0;
|
||||
while (!Lexer.optable[tok] && tok !== undefined) {
|
||||
tok = this.pickNext(index);
|
||||
index += 1;
|
||||
}
|
||||
this.receiveToken(index);
|
||||
}
|
||||
}
|
||||
|
||||
export default function token(expression) {
|
||||
const lexer = new Lexer(expression);
|
||||
return lexer.getTokens();
|
||||
}
|
||||
159
packages/server-nest/src/libs/logic-evaluation/Parser.js
Normal file
159
packages/server-nest/src/libs/logic-evaluation/Parser.js
Normal file
@@ -0,0 +1,159 @@
|
||||
export const OPERATION = {
|
||||
'!': 5,
|
||||
'*': 4,
|
||||
'/': 4,
|
||||
'%': 4,
|
||||
'+': 3,
|
||||
'-': 3,
|
||||
'>': 2,
|
||||
'<': 2,
|
||||
'>=': 2,
|
||||
'<=': 2,
|
||||
'===': 2,
|
||||
'!==': 2,
|
||||
'==': 2,
|
||||
'!=': 2,
|
||||
'&&': 1,
|
||||
'||': 1,
|
||||
'?': 1,
|
||||
':': 1,
|
||||
};
|
||||
|
||||
// export interface Node {
|
||||
// left: Node | string | null;
|
||||
// right: Node | string | null;
|
||||
// operation: string;
|
||||
// grouped?: boolean;
|
||||
// };
|
||||
|
||||
export default class Parser {
|
||||
|
||||
constructor(token) {
|
||||
this.index = -1;
|
||||
this.blockLevel = 0;
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return {Node | string} =-
|
||||
*/
|
||||
parse() {
|
||||
let tok;
|
||||
let root = {
|
||||
left: null,
|
||||
right: null,
|
||||
operation: null,
|
||||
};
|
||||
|
||||
do {
|
||||
tok = this.parseStatement();
|
||||
|
||||
if (tok === null || tok === undefined) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (root.left === null) {
|
||||
root.left = tok;
|
||||
root.operation = this.nextToken();
|
||||
|
||||
if (!root.operation) {
|
||||
return tok;
|
||||
}
|
||||
|
||||
root.right = this.parseStatement();
|
||||
} else {
|
||||
if (typeof tok !== 'string') {
|
||||
throw new Error('operation must be string, but get ' + JSON.stringify(tok));
|
||||
}
|
||||
root = this.addNode(tok, this.parseStatement(), root);
|
||||
}
|
||||
} while (tok);
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
nextToken() {
|
||||
this.index += 1;
|
||||
return this.token[this.index];
|
||||
}
|
||||
|
||||
prevToken() {
|
||||
return this.token[this.index - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} operation
|
||||
* @param {Node|String|null} right
|
||||
* @param {Node} root
|
||||
*/
|
||||
addNode(operation, right, root) {
|
||||
let pre = root;
|
||||
|
||||
if (this.compare(pre.operation, operation) < 0 && !pre.grouped) {
|
||||
|
||||
while (pre.right !== null &&
|
||||
typeof pre.right !== 'string' &&
|
||||
this.compare(pre.right.operation, operation) < 0 && !pre.right.grouped) {
|
||||
pre = pre.right;
|
||||
}
|
||||
|
||||
pre.right = {
|
||||
operation,
|
||||
left: pre.right,
|
||||
right,
|
||||
};
|
||||
return root;
|
||||
}
|
||||
return {
|
||||
left: pre,
|
||||
right,
|
||||
operation,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {String} a
|
||||
* @param {String} b
|
||||
*/
|
||||
compare(a, b) {
|
||||
if (!OPERATION.hasOwnProperty(a) || !OPERATION.hasOwnProperty(b)) {
|
||||
throw new Error(`unknow operation ${a} or ${b}`);
|
||||
}
|
||||
return OPERATION[a] - OPERATION[b];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string | Node | null
|
||||
*/
|
||||
parseStatement() {
|
||||
const token = this.nextToken();
|
||||
if (token === '(') {
|
||||
this.blockLevel += 1;
|
||||
const node = this.parse();
|
||||
this.blockLevel -= 1;
|
||||
|
||||
if (typeof node !== 'string') {
|
||||
node.grouped = true;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
if (token === ')') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (token === '!') {
|
||||
return { left: null, operation: token, right: this.parseStatement() }
|
||||
}
|
||||
|
||||
// 3 > -12 or -12 + 10
|
||||
if (token === '-' && (OPERATION[this.prevToken()] > 0 || this.prevToken() === undefined)) {
|
||||
return { left: '0', operation: token, right: this.parseStatement(), grouped: true };
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { OPERATION } from './Parser';
|
||||
|
||||
export default class QueryParser {
|
||||
|
||||
constructor(tree, queries) {
|
||||
this.tree = tree;
|
||||
this.queries = queries;
|
||||
this.query = null;
|
||||
}
|
||||
|
||||
setQuery(query) {
|
||||
this.query = query.clone();
|
||||
}
|
||||
|
||||
parse() {
|
||||
return this.parseNode(this.tree);
|
||||
}
|
||||
|
||||
parseNode(node) {
|
||||
if (typeof node === 'string') {
|
||||
const nodeQuery = this.getQuery(node);
|
||||
return (query) => { nodeQuery(query); };
|
||||
}
|
||||
if (OPERATION[node.operation] === undefined) {
|
||||
throw new Error(`unknow expression ${node.operation}`);
|
||||
}
|
||||
const leftQuery = this.getQuery(node.left);
|
||||
const rightQuery = this.getQuery(node.right);
|
||||
|
||||
switch (node.operation) {
|
||||
case '&&':
|
||||
case 'AND':
|
||||
default:
|
||||
return (nodeQuery) => nodeQuery.where((query) => {
|
||||
query.where((q) => { leftQuery(q); });
|
||||
query.andWhere((q) => { rightQuery(q); });
|
||||
});
|
||||
case '||':
|
||||
case 'OR':
|
||||
return (nodeQuery) => nodeQuery.where((query) => {
|
||||
query.where((q) => { leftQuery(q); });
|
||||
query.orWhere((q) => { rightQuery(q); });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
getQuery(node) {
|
||||
if (typeof node !== 'string' && node !== null) {
|
||||
return this.parseNode(node);
|
||||
}
|
||||
const value = parseFloat(node);
|
||||
|
||||
if (!isNaN(value)) {
|
||||
if (typeof this.queries[node] === 'undefined') {
|
||||
throw new Error(`unknow query under index ${node}`);
|
||||
}
|
||||
return this.queries[node];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
29
packages/server-nest/src/main.ts
Normal file
29
packages/server-nest/src/main.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { ClsMiddleware } from 'nestjs-cls';
|
||||
import './utils/moment-mysql';
|
||||
import { AppModule } from './modules/App/App.module';
|
||||
import { ServiceErrorFilter } from './common/filters/service-error.filter';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
app.setGlobalPrefix('/api');
|
||||
|
||||
// create and mount the middleware manually here
|
||||
app.use(new ClsMiddleware({}).use);
|
||||
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('Bigcapital')
|
||||
.setDescription('Financial accounting software')
|
||||
.setVersion('1.0')
|
||||
.addTag('cats')
|
||||
.build();
|
||||
|
||||
const documentFactory = () => SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('swagger', app, documentFactory);
|
||||
|
||||
app.useGlobalFilters(new ServiceErrorFilter());
|
||||
|
||||
await app.listen(process.env.PORT ?? 3000);
|
||||
}
|
||||
bootstrap();
|
||||
43
packages/server-nest/src/models/Model.ts
Normal file
43
packages/server-nest/src/models/Model.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { QueryBuilder, Model } from 'objection';
|
||||
|
||||
interface PaginationResult<M extends Model> {
|
||||
results: M[];
|
||||
pagination: {
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
};
|
||||
}
|
||||
|
||||
export type PaginationQueryBuilderType<M extends Model> = QueryBuilder<
|
||||
M,
|
||||
PaginationResult<M>
|
||||
>;
|
||||
|
||||
class PaginationQueryBuilder<M extends Model, R = M[]> extends QueryBuilder<
|
||||
M,
|
||||
R
|
||||
> {
|
||||
pagination(page: number, pageSize: number): PaginationQueryBuilderType<M> {
|
||||
const query = super.page(page, pageSize);
|
||||
|
||||
return query.runAfter(({ results, total }) => {
|
||||
return {
|
||||
results,
|
||||
pagination: {
|
||||
total,
|
||||
page: page + 1,
|
||||
pageSize,
|
||||
},
|
||||
};
|
||||
}) as unknown as PaginationQueryBuilderType<M>;
|
||||
}
|
||||
}
|
||||
|
||||
export class BaseModel extends Model {
|
||||
public readonly id: number;
|
||||
public readonly tableName: string;
|
||||
|
||||
QueryBuilderType!: PaginationQueryBuilder<this>;
|
||||
static QueryBuilder = PaginationQueryBuilder;
|
||||
}
|
||||
@@ -1,30 +1,30 @@
|
||||
export const OtherExpensesAccount = {
|
||||
name: 'Other Expenses',
|
||||
slug: 'other-expenses',
|
||||
accountType: 'other-expense',
|
||||
account_type: 'other-expense',
|
||||
code: '40011',
|
||||
description: '',
|
||||
active: true,
|
||||
active: 1,
|
||||
index: 1,
|
||||
predefined: true,
|
||||
predefined: 1,
|
||||
};
|
||||
|
||||
export const TaxPayableAccount = {
|
||||
name: 'Tax Payable',
|
||||
slug: 'tax-payable',
|
||||
accountType: 'tax-payable',
|
||||
account_type: 'tax-payable',
|
||||
code: '20006',
|
||||
description: '',
|
||||
active: true,
|
||||
active: 1,
|
||||
index: 1,
|
||||
predefined: true,
|
||||
predefined: 1,
|
||||
};
|
||||
|
||||
export const UnearnedRevenueAccount = {
|
||||
name: 'Unearned Revenue',
|
||||
slug: 'unearned-revenue',
|
||||
accountType: 'other-current-liability',
|
||||
parentAccountId: null,
|
||||
account_type: 'other-current-liability',
|
||||
parent_account_id: null,
|
||||
code: '50005',
|
||||
active: true,
|
||||
index: 1,
|
||||
@@ -34,8 +34,8 @@ export const UnearnedRevenueAccount = {
|
||||
export const PrepardExpenses = {
|
||||
name: 'Prepaid Expenses',
|
||||
slug: 'prepaid-expenses',
|
||||
accountType: 'other-current-asset',
|
||||
parentAccountId: null,
|
||||
account_type: 'other-current-asset',
|
||||
parent_account_id: null,
|
||||
code: '100010',
|
||||
active: true,
|
||||
index: 1,
|
||||
@@ -45,8 +45,8 @@ export const PrepardExpenses = {
|
||||
export const StripeClearingAccount = {
|
||||
name: 'Stripe Clearing',
|
||||
slug: 'stripe-clearing',
|
||||
accountType: 'other-current-asset',
|
||||
parentAccountId: null,
|
||||
account_type: 'other-current-asset',
|
||||
parent_account_id: null,
|
||||
code: '100020',
|
||||
active: true,
|
||||
index: 1,
|
||||
@@ -56,7 +56,7 @@ export const StripeClearingAccount = {
|
||||
export const DiscountExpenseAccount = {
|
||||
name: 'Discount',
|
||||
slug: 'discount',
|
||||
accountType: 'other-income',
|
||||
account_type: 'other-income',
|
||||
code: '40008',
|
||||
active: true,
|
||||
index: 1,
|
||||
@@ -66,7 +66,7 @@ export const DiscountExpenseAccount = {
|
||||
export const PurchaseDiscountAccount = {
|
||||
name: 'Purchase Discount',
|
||||
slug: 'purchase-discount',
|
||||
accountType: 'other-expense',
|
||||
account_type: 'other-expense',
|
||||
code: '40009',
|
||||
active: true,
|
||||
index: 1,
|
||||
@@ -76,7 +76,7 @@ export const PurchaseDiscountAccount = {
|
||||
export const OtherChargesAccount = {
|
||||
name: 'Other Charges',
|
||||
slug: 'other-charges',
|
||||
accountType: 'other-income',
|
||||
account_type: 'other-income',
|
||||
code: '40010',
|
||||
active: true,
|
||||
index: 1,
|
||||
@@ -87,7 +87,7 @@ export const SeedAccounts = [
|
||||
{
|
||||
name: 'Bank Account',
|
||||
slug: 'bank-account',
|
||||
accountType: 'bank',
|
||||
account_type: 'bank',
|
||||
code: '10001',
|
||||
description: '',
|
||||
active: 1,
|
||||
@@ -0,0 +1,72 @@
|
||||
import {
|
||||
Controller,
|
||||
Post,
|
||||
Body,
|
||||
Param,
|
||||
Delete,
|
||||
Get,
|
||||
Query,
|
||||
ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { AccountsApplication } from './AccountsApplication.service';
|
||||
import { CreateAccountDTO } from './CreateAccount.dto';
|
||||
import { EditAccountDTO } from './EditAccount.dto';
|
||||
import { PublicRoute } from '../Auth/Jwt.guard';
|
||||
import { IAccountsFilter, IAccountsTransactionsFilter } from './Accounts.types';
|
||||
// import { IAccountsFilter, IAccountsTransactionsFilter } from './Accounts.types';
|
||||
// import { ZodValidationPipe } from '@/common/pipes/ZodValidation.pipe';
|
||||
|
||||
@Controller('accounts')
|
||||
@PublicRoute()
|
||||
export class AccountsController {
|
||||
constructor(private readonly accountsApplication: AccountsApplication) {}
|
||||
|
||||
@Post()
|
||||
async createAccount(@Body() accountDTO: CreateAccountDTO) {
|
||||
return this.accountsApplication.createAccount(accountDTO);
|
||||
}
|
||||
|
||||
@Post(':id')
|
||||
async editAccount(
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() accountDTO: EditAccountDTO,
|
||||
) {
|
||||
return this.accountsApplication.editAccount(id, accountDTO);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
async deleteAccount(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.accountsApplication.deleteAccount(id);
|
||||
}
|
||||
|
||||
@Post(':id/activate')
|
||||
async activateAccount(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.accountsApplication.activateAccount(id);
|
||||
}
|
||||
|
||||
@Post(':id/inactivate')
|
||||
async inactivateAccount(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.accountsApplication.inactivateAccount(id);
|
||||
}
|
||||
|
||||
@Get('types')
|
||||
async getAccountTypes() {
|
||||
return this.accountsApplication.getAccountTypes();
|
||||
}
|
||||
|
||||
@Get('transactions')
|
||||
async getAccountTransactions(@Query() filter: IAccountsTransactionsFilter) {
|
||||
return this.accountsApplication.getAccountsTransactions(filter);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
async getAccount(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.accountsApplication.getAccount(id);
|
||||
}
|
||||
|
||||
@Get()
|
||||
async getAccounts(@Query() filter: IAccountsFilter) {
|
||||
return this.accountsApplication.getAccounts(filter);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -15,15 +15,12 @@ import { GetAccountTypesService } from './GetAccountTypes.service';
|
||||
import { GetAccountTransactionsService } from './GetAccountTransactions.service';
|
||||
import { RegisterTenancyModel } from '../Tenancy/TenancyModels/Tenancy.module';
|
||||
import { BankAccount } from '../BankingTransactions/models/BankAccount';
|
||||
import { GetAccountsService } from './GetAccounts.service';
|
||||
import { DynamicListModule } from '../DynamicListing/DynamicList.module';
|
||||
import { AccountsExportable } from './AccountsExportable.service';
|
||||
import { AccountsImportable } from './AccountsImportable.service';
|
||||
// import { GetAccountsService } from './GetAccounts.service';
|
||||
|
||||
const models = [RegisterTenancyModel(BankAccount)];
|
||||
|
||||
@Module({
|
||||
imports: [TenancyDatabaseModule, DynamicListModule, ...models],
|
||||
imports: [TenancyDatabaseModule],
|
||||
controllers: [AccountsController],
|
||||
providers: [
|
||||
AccountsApplication,
|
||||
@@ -38,16 +35,8 @@ const models = [RegisterTenancyModel(BankAccount)];
|
||||
ActivateAccount,
|
||||
GetAccountTypesService,
|
||||
GetAccountTransactionsService,
|
||||
GetAccountsService,
|
||||
AccountsExportable,
|
||||
AccountsImportable
|
||||
],
|
||||
exports: [
|
||||
AccountRepository,
|
||||
CreateAccountService,
|
||||
...models,
|
||||
AccountsExportable,
|
||||
AccountsImportable
|
||||
],
|
||||
exports: [AccountRepository, CreateAccountService, ...models],
|
||||
})
|
||||
export class AccountsModule {}
|
||||
@@ -41,7 +41,6 @@ export interface IAccountEventCreatingPayload {
|
||||
accountDTO: any;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface IAccountEventCreatedPayload {
|
||||
account: Account;
|
||||
accountId: number;
|
||||
@@ -20,16 +20,6 @@ import { IFilterMeta } from '@/interfaces/Model';
|
||||
|
||||
@Injectable()
|
||||
export class AccountsApplication {
|
||||
/**
|
||||
* @param {CreateAccountService} createAccountService - The create account service.
|
||||
* @param {EditAccount} editAccountService - The edit account service.
|
||||
* @param {DeleteAccount} deleteAccountService - The delete account service.
|
||||
* @param {ActivateAccount} activateAccountService - The activate account service.
|
||||
* @param {GetAccountTypesService} getAccountTypesService - The get account types service.
|
||||
* @param {GetAccount} getAccountService - The get account service.
|
||||
* @param {GetAccountTransactionsService} getAccountTransactionsService - The get account transactions service.
|
||||
* @param {GetAccountsService} getAccountsService - The get accounts service.
|
||||
*/
|
||||
constructor(
|
||||
private readonly createAccountService: CreateAccountService,
|
||||
private readonly editAccountService: EditAccount,
|
||||
@@ -115,7 +105,7 @@ export class AccountsApplication {
|
||||
* @returns {Promise<{ accounts: IAccountResponse[]; filterMeta: IFilterMeta }>}
|
||||
*/
|
||||
public getAccounts = (
|
||||
filterDTO: Partial<IAccountsFilter>,
|
||||
filterDTO: IAccountsFilter,
|
||||
): Promise<{ accounts: Account[]; filterMeta: IFilterMeta }> => {
|
||||
return this.getAccountsService.getAccountsList(filterDTO);
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import { AccountsApplication } from './AccountsApplication.service';
|
||||
// import { Exportable } from '../Export/Exportable';
|
||||
// import { IAccountsFilter, IAccountsStructureType } from '@/interfaces';
|
||||
// import { EXPORT_SIZE_LIMIT } from '../Export/constants';
|
||||
|
||||
// @Service()
|
||||
// export class AccountsExportable extends Exportable {
|
||||
// @Inject()
|
||||
// private accountsApplication: AccountsApplication;
|
||||
|
||||
// /**
|
||||
// * Retrieves the accounts data to exportable sheet.
|
||||
// * @param {number} tenantId
|
||||
// * @returns
|
||||
// */
|
||||
// public exportable(tenantId: number, query: IAccountsFilter) {
|
||||
// const parsedQuery = {
|
||||
// sortOrder: 'desc',
|
||||
// columnSortBy: 'created_at',
|
||||
// inactiveMode: false,
|
||||
// ...query,
|
||||
// structure: IAccountsStructureType.Flat,
|
||||
// pageSize: EXPORT_SIZE_LIMIT,
|
||||
// page: 1,
|
||||
// } as IAccountsFilter;
|
||||
|
||||
// return this.accountsApplication
|
||||
// .getAccounts(tenantId, parsedQuery)
|
||||
// .then((output) => output.accounts);
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,45 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import { Knex } from 'knex';
|
||||
// import { IAccountCreateDTO } from '@/interfaces';
|
||||
// import { CreateAccount } from './CreateAccount.service';
|
||||
// import { Importable } from '../Import/Importable';
|
||||
// import { AccountsSampleData } from './AccountsImportable.SampleData';
|
||||
|
||||
// @Service()
|
||||
// export class AccountsImportable extends Importable {
|
||||
// @Inject()
|
||||
// private createAccountService: CreateAccount;
|
||||
|
||||
// /**
|
||||
// * Importing to account service.
|
||||
// * @param {number} tenantId
|
||||
// * @param {IAccountCreateDTO} createAccountDTO
|
||||
// * @returns
|
||||
// */
|
||||
// public importable(
|
||||
// tenantId: number,
|
||||
// createAccountDTO: IAccountCreateDTO,
|
||||
// trx?: Knex.Transaction
|
||||
// ) {
|
||||
// return this.createAccountService.createAccount(
|
||||
// tenantId,
|
||||
// createAccountDTO,
|
||||
// trx
|
||||
// );
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Concurrrency controlling of the importing process.
|
||||
// * @returns {number}
|
||||
// */
|
||||
// public get concurrency() {
|
||||
// return 1;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Retrieves the sample data that used to download accounts sample sheet.
|
||||
// */
|
||||
// public sampleData(): any[] {
|
||||
// return AccountsSampleData;
|
||||
// }
|
||||
// }
|
||||
@@ -6,33 +6,26 @@ import { AccountRepository } from './repositories/Account.repository';
|
||||
import { UnitOfWork } from '../Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { events } from '@/common/events/events';
|
||||
import { TenantModelProxy } from '../System/models/TenantBaseModel';
|
||||
|
||||
@Injectable()
|
||||
export class ActivateAccount {
|
||||
/**
|
||||
* @param {EventEmitter2} eventEmitter - The event emitter.
|
||||
* @param {UnitOfWork} uow - The unit of work.
|
||||
* @param {AccountRepository} accountRepository - The account repository.
|
||||
* @param {TenantModelProxy<typeof Account>} accountModel - The account model.
|
||||
*/
|
||||
constructor(
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
private readonly uow: UnitOfWork,
|
||||
private readonly accountRepository: AccountRepository,
|
||||
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: TenantModelProxy<typeof Account>,
|
||||
private readonly accountModel: typeof Account,
|
||||
private readonly accountRepository: AccountRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Activates/Inactivates the given account.
|
||||
* @param {number} accountId - The account id.
|
||||
* @param {boolean} activate - Activate or inactivate the account.
|
||||
* @param {number} accountId
|
||||
* @param {boolean} activate
|
||||
*/
|
||||
public activateAccount = async (accountId: number, activate?: boolean) => {
|
||||
// Retrieve the given account or throw not found error.
|
||||
const oldAccount = await this.accountModel()
|
||||
const oldAccount = await this.accountModel
|
||||
.query()
|
||||
.findById(accountId)
|
||||
.throwIfNotFound();
|
||||
@@ -9,13 +9,12 @@ import { AccountRepository } from './repositories/Account.repository';
|
||||
import { AccountTypesUtils } from './utils/AccountType.utils';
|
||||
import { CreateAccountDTO } from './CreateAccount.dto';
|
||||
import { EditAccountDTO } from './EditAccount.dto';
|
||||
import { TenantModelProxy } from '../System/models/TenantBaseModel';
|
||||
|
||||
@Injectable({ scope: Scope.REQUEST })
|
||||
export class CommandAccountValidators {
|
||||
constructor(
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: TenantModelProxy<typeof Account>,
|
||||
private readonly accountModel: typeof Account,
|
||||
private readonly accountRepository: AccountRepository,
|
||||
) {}
|
||||
|
||||
@@ -67,7 +66,7 @@ export class CommandAccountValidators {
|
||||
accountId: number,
|
||||
notAccountId?: number,
|
||||
) {
|
||||
const parentAccount = await this.accountModel()
|
||||
const parentAccount = await this.accountModel
|
||||
.query()
|
||||
.findById(accountId)
|
||||
.onBuild((query) => {
|
||||
@@ -90,7 +89,7 @@ export class CommandAccountValidators {
|
||||
accountCode: string,
|
||||
notAccountId?: number,
|
||||
) {
|
||||
const account = await this.accountModel()
|
||||
const account = await this.accountModel
|
||||
.query()
|
||||
.where('code', accountCode)
|
||||
.onBuild((query) => {
|
||||
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
IsString,
|
||||
IsOptional,
|
||||
IsInt,
|
||||
MinLength,
|
||||
MaxLength,
|
||||
IsBoolean,
|
||||
} from 'class-validator';
|
||||
|
||||
export class CreateAccountDTO {
|
||||
@IsString()
|
||||
@MinLength(3)
|
||||
@MaxLength(255) // Assuming DATATYPES_LENGTH.STRING is 255
|
||||
name: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(3)
|
||||
@MaxLength(6)
|
||||
code?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
currencyCode?: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(3)
|
||||
@MaxLength(255) // Assuming DATATYPES_LENGTH.STRING is 255
|
||||
accountType: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(65535) // Assuming DATATYPES_LENGTH.TEXT is 65535
|
||||
description?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
parentAccountId?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
active?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
plaidAccountId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
plaidItemId?: string;
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { kebabCase } from 'lodash';
|
||||
import { Knex } from 'knex';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import {
|
||||
// IAccount,
|
||||
// IAccountEventCreatedPayload,
|
||||
// IAccountCreateDTO,
|
||||
IAccountEventCreatingPayload,
|
||||
CreateAccountParams,
|
||||
IAccountEventCreatedPayload,
|
||||
} from './Accounts.types';
|
||||
import { CommandAccountValidators } from './CommandAccountValidators.service';
|
||||
import { Account } from './models/Account.model';
|
||||
@@ -13,21 +16,12 @@ import { UnitOfWork } from '../Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { TenancyContext } from '../Tenancy/TenancyContext.service';
|
||||
import { events } from '@/common/events/events';
|
||||
import { CreateAccountDTO } from './CreateAccount.dto';
|
||||
import { PartialModelObject } from 'objection';
|
||||
import { TenantModelProxy } from '../System/models/TenantBaseModel';
|
||||
|
||||
@Injectable()
|
||||
export class CreateAccountService {
|
||||
/**
|
||||
* @param {TenantModelProxy<typeof Account>} accountModel - The account model proxy.
|
||||
* @param {EventEmitter2} eventEmitter - The event emitter.
|
||||
* @param {UnitOfWork} uow - The unit of work.
|
||||
* @param {CommandAccountValidators} validator - The command account validators.
|
||||
* @param {TenancyContext} tenancyContext - The tenancy context.
|
||||
*/
|
||||
constructor(
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: TenantModelProxy<typeof Account>,
|
||||
private readonly accountModel: typeof Account,
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
private readonly uow: UnitOfWork,
|
||||
private readonly validator: CommandAccountValidators,
|
||||
@@ -86,7 +80,7 @@ export class CreateAccountService {
|
||||
private transformDTOToModel = (
|
||||
createAccountDTO: CreateAccountDTO,
|
||||
baseCurrency: string,
|
||||
): PartialModelObject<Account> => {
|
||||
) => {
|
||||
return {
|
||||
...createAccountDTO,
|
||||
slug: kebabCase(createAccountDTO.name),
|
||||
@@ -129,17 +123,15 @@ export class CreateAccountService {
|
||||
} as IAccountEventCreatingPayload);
|
||||
|
||||
// Inserts account to the storage.
|
||||
const account = await this.accountModel()
|
||||
.query()
|
||||
.insert({
|
||||
...accountInputModel,
|
||||
});
|
||||
const account = await this.accountModel.query().insert({
|
||||
...accountInputModel,
|
||||
});
|
||||
// Triggers `onAccountCreated` event.
|
||||
await this.eventEmitter.emitAsync(events.accounts.onCreated, {
|
||||
account,
|
||||
accountId: account.id,
|
||||
trx,
|
||||
} as IAccountEventCreatedPayload);
|
||||
// await this.eventEmitter.emitAsync(events.accounts.onCreated, {
|
||||
// account,
|
||||
// accountId: account.id,
|
||||
// trx,
|
||||
// } as IAccountEventCreatedPayload);
|
||||
|
||||
return account;
|
||||
}, trx);
|
||||
@@ -7,14 +7,11 @@ import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { UnitOfWork } from '../Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { events } from '@/common/events/events';
|
||||
import { IAccountEventDeletedPayload } from './Accounts.types';
|
||||
import { TenantModelProxy } from '../System/models/TenantBaseModel';
|
||||
|
||||
@Injectable()
|
||||
export class DeleteAccount {
|
||||
constructor(
|
||||
@Inject(Account.name)
|
||||
private accountModel: TenantModelProxy<typeof Account>,
|
||||
|
||||
@Inject(Account.name) private accountModel: typeof Account,
|
||||
private eventEmitter: EventEmitter2,
|
||||
private uow: UnitOfWork,
|
||||
private validator: CommandAccountValidators,
|
||||
@@ -41,10 +38,10 @@ export class DeleteAccount {
|
||||
? parentAccountId
|
||||
: [parentAccountId];
|
||||
|
||||
await this.accountModel()
|
||||
await this.accountModel
|
||||
.query(trx)
|
||||
.whereIn('parent_account_id', accountsIds)
|
||||
.patch({ parentAccountId: null });
|
||||
.patch({ parent_account_id: null });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -53,7 +50,7 @@ export class DeleteAccount {
|
||||
*/
|
||||
public deleteAccount = async (accountId: number): Promise<void> => {
|
||||
// Retrieve account or not found service error.
|
||||
const oldAccount = await this.accountModel().query().findById(accountId);
|
||||
const oldAccount = await this.accountModel.query().findById(accountId);
|
||||
|
||||
// Authorize before delete account.
|
||||
await this.authorize(accountId, oldAccount);
|
||||
@@ -70,7 +67,7 @@ export class DeleteAccount {
|
||||
await this.unassociateChildrenAccountsFromParent(accountId, trx);
|
||||
|
||||
// Deletes account by the given id.
|
||||
await this.accountModel().query(trx).deleteById(accountId);
|
||||
await this.accountModel.query(trx).deleteById(accountId);
|
||||
|
||||
// Triggers `onAccountDeleted` event.
|
||||
await this.eventEmitter.emitAsync(events.accounts.onDeleted, {
|
||||
34
packages/server-nest/src/modules/Accounts/EditAccount.dto.ts
Normal file
34
packages/server-nest/src/modules/Accounts/EditAccount.dto.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
IsString,
|
||||
IsOptional,
|
||||
IsInt,
|
||||
MinLength,
|
||||
MaxLength,
|
||||
} from 'class-validator';
|
||||
|
||||
export class EditAccountDTO {
|
||||
@IsString()
|
||||
@MinLength(3)
|
||||
@MaxLength(255) // Assuming DATATYPES_LENGTH.STRING is 255
|
||||
name: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(3)
|
||||
@MaxLength(6)
|
||||
code?: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(3)
|
||||
@MaxLength(255) // Assuming DATATYPES_LENGTH.STRING is 255
|
||||
accountType: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(65535) // Assuming DATATYPES_LENGTH.TEXT is 65535
|
||||
description?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
parentAccountId?: number;
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { UnitOfWork } from '../Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { events } from '@/common/events/events';
|
||||
import { EditAccountDTO } from './EditAccount.dto';
|
||||
import { TenantModelProxy } from '../System/models/TenantBaseModel';
|
||||
|
||||
@Injectable()
|
||||
export class EditAccount {
|
||||
@@ -16,7 +15,7 @@ export class EditAccount {
|
||||
private readonly validator: CommandAccountValidators,
|
||||
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: TenantModelProxy<typeof Account>,
|
||||
private readonly accountModel: typeof Account,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -67,7 +66,7 @@ export class EditAccount {
|
||||
accountDTO: EditAccountDTO,
|
||||
): Promise<Account> {
|
||||
// Retrieve the old account or throw not found service error.
|
||||
const oldAccount = await this.accountModel()
|
||||
const oldAccount = await this.accountModel
|
||||
.query()
|
||||
.findById(accountId)
|
||||
.throwIfNotFound();
|
||||
@@ -83,7 +82,7 @@ export class EditAccount {
|
||||
accountDTO,
|
||||
});
|
||||
// Update the account on the storage.
|
||||
const account = await this.accountModel()
|
||||
const account = await this.accountModel
|
||||
.query(trx)
|
||||
.findById(accountId)
|
||||
.updateAndFetch({ ...accountDTO });
|
||||
@@ -5,13 +5,12 @@ import { AccountRepository } from './repositories/Account.repository';
|
||||
import { TransformerInjectable } from '../Transformer/TransformerInjectable.service';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { events } from '@/common/events/events';
|
||||
import { TenantModelProxy } from '../System/models/TenantBaseModel';
|
||||
|
||||
@Injectable()
|
||||
export class GetAccount {
|
||||
constructor(
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: TenantModelProxy<typeof Account>,
|
||||
private readonly accountModel: typeof Account,
|
||||
private readonly accountRepository: AccountRepository,
|
||||
private readonly transformer: TransformerInjectable,
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
@@ -23,7 +22,7 @@ export class GetAccount {
|
||||
*/
|
||||
public getAccount = async (accountId: number) => {
|
||||
// Find the given account or throw not found error.
|
||||
const account = await this.accountModel()
|
||||
const account = await this.accountModel
|
||||
.query()
|
||||
.findById(accountId)
|
||||
.withGraphFetched('plaidItem')
|
||||
@@ -7,7 +7,6 @@ import { AccountTransaction } from './models/AccountTransaction.model';
|
||||
import { Account } from './models/Account.model';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { TransformerInjectable } from '../Transformer/TransformerInjectable.service';
|
||||
import { TenantModelProxy } from '../System/models/TenantBaseModel';
|
||||
|
||||
@Injectable()
|
||||
export class GetAccountTransactionsService {
|
||||
@@ -15,12 +14,10 @@ export class GetAccountTransactionsService {
|
||||
private readonly transformer: TransformerInjectable,
|
||||
|
||||
@Inject(AccountTransaction.name)
|
||||
private readonly accountTransaction: TenantModelProxy<
|
||||
typeof AccountTransaction
|
||||
>,
|
||||
private readonly accountTransaction: typeof AccountTransaction,
|
||||
|
||||
@Inject(Account.name)
|
||||
private readonly account: TenantModelProxy<typeof Account>,
|
||||
private readonly account: typeof Account,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -32,9 +29,9 @@ export class GetAccountTransactionsService {
|
||||
): Promise<IGetAccountTransactionPOJO[]> => {
|
||||
// Retrieve the given account or throw not found error.
|
||||
if (filter.accountId) {
|
||||
await this.account().query().findById(filter.accountId).throwIfNotFound();
|
||||
await this.account.query().findById(filter.accountId).throwIfNotFound();
|
||||
}
|
||||
const transactions = await this.accountTransaction()
|
||||
const transactions = await this.accountTransaction
|
||||
.query()
|
||||
.onBuild((query) => {
|
||||
query.orderBy('date', 'DESC');
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import * as R from 'ramda';
|
||||
import { IAccountsFilter } from './Accounts.types';
|
||||
import { DynamicListService } from '../DynamicListing/DynamicList.service';
|
||||
import { AccountTransformer } from './Account.transformer';
|
||||
import { TransformerInjectable } from '../Transformer/TransformerInjectable.service';
|
||||
import { Account } from './models/Account.model';
|
||||
import { AccountRepository } from './repositories/Account.repository';
|
||||
import { IFilterMeta } from '@/interfaces/Model';
|
||||
|
||||
@Injectable()
|
||||
export class GetAccountsService {
|
||||
constructor(
|
||||
private readonly dynamicListService: DynamicListService,
|
||||
private readonly transformerService: TransformerInjectable,
|
||||
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: typeof Account,
|
||||
private readonly accountRepository: AccountRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieve accounts datatable list.
|
||||
* @param {IAccountsFilter} accountsFilter
|
||||
* @returns {Promise<{ accounts: IAccountResponse[]; filterMeta: IFilterMeta }>}
|
||||
*/
|
||||
public async getAccountsList(
|
||||
filterDTO: IAccountsFilter,
|
||||
): Promise<{ accounts: Account[]; filterMeta: IFilterMeta }> {
|
||||
// Parses the stringified filter roles.
|
||||
const filter = this.parseListFilterDTO(filterDTO);
|
||||
|
||||
// Dynamic list service.
|
||||
const dynamicList = await this.dynamicListService.dynamicList(
|
||||
this.accountModel,
|
||||
filter,
|
||||
);
|
||||
// Retrieve accounts model based on the given query.
|
||||
const accounts = await this.accountModel.query().onBuild((builder) => {
|
||||
dynamicList.buildQuery()(builder);
|
||||
builder.modify('inactiveMode', filter.inactiveMode);
|
||||
});
|
||||
const accountsGraph = await this.accountRepository.getDependencyGraph();
|
||||
|
||||
// Retrieves the transformed accounts collection.
|
||||
const transformedAccounts = await this.transformerService.transform(
|
||||
accounts,
|
||||
new AccountTransformer(),
|
||||
{ accountsGraph, structure: filterDTO.structure },
|
||||
);
|
||||
|
||||
return {
|
||||
accounts: transformedAccounts,
|
||||
filterMeta: dynamicList.getResponseMeta(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parsees accounts list filter DTO.
|
||||
* @param filterDTO
|
||||
* @returns
|
||||
*/
|
||||
private parseListFilterDTO(filterDTO) {
|
||||
return R.compose(this.dynamicListService.parseStringifiedFilter)(filterDTO);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
|
||||
// @Service()
|
||||
// export class MutateBaseCurrencyAccounts {
|
||||
// @Inject()
|
||||
// tenancy: HasTenancyService;
|
||||
|
||||
// /**
|
||||
// * Mutates the all accounts or the organziation.
|
||||
// * @param {number} tenantId
|
||||
// * @param {string} currencyCode
|
||||
// */
|
||||
// public mutateAllAccountsCurrency = async (
|
||||
// tenantId: number,
|
||||
// currencyCode: string
|
||||
// ) => {
|
||||
// const { Account } = this.tenancy.models(tenantId);
|
||||
|
||||
// await Account.query().update({ currencyCode });
|
||||
// };
|
||||
// }
|
||||
@@ -1,40 +1,44 @@
|
||||
/* eslint-disable global-require */
|
||||
// import { mixin, Model } from 'objection';
|
||||
import { castArray } from 'lodash';
|
||||
import { Model } from 'objection';
|
||||
import DependencyGraph from '@/libs/dependency-graph';
|
||||
import {
|
||||
ACCOUNT_TYPES,
|
||||
getAccountsSupportsMultiCurrency,
|
||||
} from '@/constants/accounts';
|
||||
import { TenantModel } from '@/modules/System/models/TenantModel';
|
||||
// import { SearchableModel } from '@/modules/Search/SearchableMdel';
|
||||
// import { CustomViewBaseModel } from '@/modules/CustomViews/CustomViewBaseModel';
|
||||
// import { ModelSettings } from '@/modules/Settings/ModelSettings';
|
||||
import { AccountTypesUtils } from '@/libs/accounts-utils/AccountTypesUtils';
|
||||
import { Model } from 'objection';
|
||||
import { PlaidItem } from '@/modules/BankingPlaid/models/PlaidItem';
|
||||
import { TenantBaseModel } from '@/modules/System/models/TenantBaseModel';
|
||||
import { flatToNestedArray } from '@/utils/flat-to-nested-array';
|
||||
import { ExportableModel } from '../../Export/decorators/ExportableModel.decorator';
|
||||
import { AccountMeta } from './Account.meta';
|
||||
import { InjectModelMeta } from '@/modules/Tenancy/TenancyModels/decorators/InjectModelMeta.decorator';
|
||||
import { ImportableModel } from '@/modules/Import/decorators/Import.decorator';
|
||||
// import AccountSettings from './Account.Settings';
|
||||
// import { DEFAULT_VIEWS } from '@/modules/Accounts/constants';
|
||||
// import { buildFilterQuery, buildSortColumnQuery } from '@/lib/ViewRolesBuilder';
|
||||
// import { flatToNestedArray } from 'utils';
|
||||
|
||||
@ExportableModel()
|
||||
@ImportableModel()
|
||||
@InjectModelMeta(AccountMeta)
|
||||
export class Account extends TenantBaseModel {
|
||||
// @ts-expect-error
|
||||
// export class Account extends mixin(TenantModel, [
|
||||
// ModelSettings,
|
||||
// CustomViewBaseModel,
|
||||
// SearchableModel,
|
||||
// ]) {
|
||||
|
||||
export class Account extends TenantModel {
|
||||
public name!: string;
|
||||
public slug!: string;
|
||||
public code!: string;
|
||||
public index!: number;
|
||||
public accountType!: string;
|
||||
public parentAccountId!: number | null;
|
||||
public predefined!: boolean;
|
||||
public currencyCode!: string;
|
||||
public active!: boolean;
|
||||
public bankBalance!: number;
|
||||
public lastFeedsUpdatedAt!: string | Date | null;
|
||||
public lastFeedsUpdatedAt!: string | null;
|
||||
public amount!: number;
|
||||
public plaidItemId!: string;
|
||||
public plaidAccountId!: string | null;
|
||||
public isFeedsActive!: boolean;
|
||||
public isSyncingOwner!: boolean;
|
||||
public plaidItemId!: number;
|
||||
|
||||
public plaidItem!: PlaidItem;
|
||||
|
||||
/**
|
||||
@@ -69,11 +73,11 @@ export class Account extends TenantBaseModel {
|
||||
/**
|
||||
* Account normal.
|
||||
*/
|
||||
get accountNormal(): string {
|
||||
get accountNormal() {
|
||||
return AccountTypesUtils.getType(this.accountType, 'normal');
|
||||
}
|
||||
|
||||
get accountNormalFormatted(): string {
|
||||
get accountNormalFormatted() {
|
||||
const paris = {
|
||||
credit: 'Credit',
|
||||
debit: 'Debit',
|
||||
@@ -84,35 +88,35 @@ export class Account extends TenantBaseModel {
|
||||
/**
|
||||
* Retrieve account type label.
|
||||
*/
|
||||
get accountTypeLabel(): string {
|
||||
get accountTypeLabel() {
|
||||
return AccountTypesUtils.getType(this.accountType, 'label');
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve account parent type.
|
||||
*/
|
||||
get accountParentType(): string {
|
||||
get accountParentType() {
|
||||
return AccountTypesUtils.getType(this.accountType, 'parentType');
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve account root type.
|
||||
*/
|
||||
get accountRootType(): string {
|
||||
get accountRootType() {
|
||||
return AccountTypesUtils.getType(this.accountType, 'rootType');
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve whether the account is balance sheet account.
|
||||
*/
|
||||
get isBalanceSheetAccount(): boolean {
|
||||
get isBalanceSheetAccount() {
|
||||
return this.isBalanceSheet();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve whether the account is profit/loss sheet account.
|
||||
*/
|
||||
get isPLSheet(): boolean {
|
||||
get isPLSheet() {
|
||||
return this.isProfitLossSheet();
|
||||
}
|
||||
/**
|
||||
@@ -227,7 +231,6 @@ export class Account extends TenantBaseModel {
|
||||
to: 'accounts_transactions.accountId',
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Account may has many items as cost account.
|
||||
*/
|
||||
@@ -405,10 +408,10 @@ export class Account extends TenantBaseModel {
|
||||
* @param {Object} options
|
||||
*/
|
||||
static toNestedArray(accounts, options = { children: 'children' }) {
|
||||
return flatToNestedArray(accounts, {
|
||||
id: 'id',
|
||||
parentId: 'parentAccountId',
|
||||
});
|
||||
// return flatToNestedArray(accounts, {
|
||||
// id: 'id',
|
||||
// parentId: 'parentAccountId',
|
||||
// });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1,39 +1,37 @@
|
||||
import { Model, raw } from 'objection';
|
||||
import * as moment from 'moment';
|
||||
import { unitOfTime } from 'moment';
|
||||
import moment, { unitOfTime } from 'moment';
|
||||
import { isEmpty, castArray } from 'lodash';
|
||||
import { BaseModel } from '@/models/Model';
|
||||
import { Account } from './Account.model';
|
||||
// import { getTransactionTypeLabel } from '@/utils/transactions-types';
|
||||
|
||||
export class AccountTransaction extends BaseModel {
|
||||
public readonly referenceType: string;
|
||||
public readonly referenceId: number;
|
||||
public readonly accountId: number;
|
||||
public readonly contactId: number;
|
||||
public readonly contactType: string;
|
||||
public readonly credit: number;
|
||||
public readonly debit: number;
|
||||
public readonly exchangeRate: number;
|
||||
public readonly taxRate: number;
|
||||
public readonly date: Date | string;
|
||||
public readonly transactionType: string;
|
||||
public readonly currencyCode: string;
|
||||
public readonly referenceTypeFormatted: string;
|
||||
public readonly transactionNumber!: string;
|
||||
public readonly referenceNumber!: string;
|
||||
public readonly note!: string;
|
||||
referenceType: string;
|
||||
referenceId: number;
|
||||
accountId: number;
|
||||
contactId: number;
|
||||
credit: number;
|
||||
debit: number;
|
||||
exchangeRate: number;
|
||||
taxRate: number;
|
||||
date: Date | string;
|
||||
transactionType: string;
|
||||
currencyCode: string;
|
||||
referenceTypeFormatted: string;
|
||||
transactionNumber!: string;
|
||||
referenceNumber!: string;
|
||||
note!: string;
|
||||
|
||||
public readonly index!: number;
|
||||
public readonly indexGroup!: number;
|
||||
index!: number;
|
||||
indexGroup!: number;
|
||||
|
||||
public readonly taxRateId!: number;
|
||||
taxRateId!: number;
|
||||
|
||||
public readonly branchId!: number;
|
||||
public readonly userId!: number;
|
||||
public readonly itemId!: number;
|
||||
public readonly projectId!: number;
|
||||
public readonly account: Account;
|
||||
branchId!: number;
|
||||
userId!: number;
|
||||
itemId!: number;
|
||||
projectId!: number;
|
||||
account: Account;
|
||||
|
||||
/**
|
||||
* Table name
|
||||
@@ -23,7 +23,7 @@ export class AccountRepository extends TenantRepository {
|
||||
private readonly tenancyContext: TenancyContext,
|
||||
|
||||
@Inject(TENANCY_DB_CONNECTION)
|
||||
private readonly tenantDBKnex: () => Knex,
|
||||
private readonly tenantDBKnex: Knex,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
@@ -32,7 +32,7 @@ export class AccountRepository extends TenantRepository {
|
||||
* Gets the repository's model.
|
||||
*/
|
||||
get model(): typeof Account {
|
||||
return Account.bindKnex(this.tenantDBKnex());
|
||||
return Account.bindKnex(this.tenantDBKnex);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -147,7 +147,7 @@ export class AccountRepository extends TenantRepository {
|
||||
}),
|
||||
accountType: 'accounts-receivable',
|
||||
currencyCode,
|
||||
active: true,
|
||||
active: 1,
|
||||
...extraAttrs,
|
||||
});
|
||||
}
|
||||
@@ -199,7 +199,7 @@ export class AccountRepository extends TenantRepository {
|
||||
}),
|
||||
accountType: 'accounts-payable',
|
||||
currencyCode,
|
||||
active: true,
|
||||
active: 1,
|
||||
...extraAttrs,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// import { Service, Inject } from 'typedi';
|
||||
// import events from '@/subscribers/events';
|
||||
// import { MutateBaseCurrencyAccounts } from '../MutateBaseCurrencyAccounts';
|
||||
|
||||
// @Service()
|
||||
// export class MutateBaseCurrencyAccountsSubscriber {
|
||||
// @Inject()
|
||||
// public mutateBaseCurrencyAccounts: MutateBaseCurrencyAccounts;
|
||||
|
||||
// /**
|
||||
// * Attaches the events with handles.
|
||||
// * @param bus
|
||||
// */
|
||||
// attach(bus) {
|
||||
// bus.subscribe(
|
||||
// events.organization.baseCurrencyUpdated,
|
||||
// this.updateAccountsCurrencyOnBaseCurrencyMutated
|
||||
// );
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Updates the all accounts currency once the base currency
|
||||
// * of the organization is mutated.
|
||||
// */
|
||||
// private updateAccountsCurrencyOnBaseCurrencyMutated = async ({
|
||||
// tenantId,
|
||||
// organizationDTO,
|
||||
// }) => {
|
||||
// await this.mutateBaseCurrencyAccounts.mutateAllAccountsCurrency(
|
||||
// tenantId,
|
||||
// organizationDTO.baseCurrency
|
||||
// );
|
||||
// };
|
||||
// }
|
||||
192
packages/server-nest/src/modules/App/App.module.ts
Normal file
192
packages/server-nest/src/modules/App/App.module.ts
Normal file
@@ -0,0 +1,192 @@
|
||||
import { MiddlewareConsumer, Module, RequestMethod } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { EventEmitterModule } from '@nestjs/event-emitter';
|
||||
import { join } from 'path';
|
||||
import {
|
||||
AcceptLanguageResolver,
|
||||
CookieResolver,
|
||||
HeaderResolver,
|
||||
I18nModule,
|
||||
QueryResolver,
|
||||
} from 'nestjs-i18n';
|
||||
import { BullModule } from '@nestjs/bullmq';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { ClsModule } from 'nestjs-cls';
|
||||
import { AppController } from './App.controller';
|
||||
import { AppService } from './App.service';
|
||||
import { ItemsModule } from '../Items/items.module';
|
||||
import { config } from '../../common/config';
|
||||
import { SystemDatabaseModule } from '../System/SystemDB/SystemDB.module';
|
||||
import { SystemModelsModule } from '../System/SystemModels/SystemModels.module';
|
||||
import { JwtStrategy } from '../Auth/Jwt.strategy';
|
||||
import { jwtConstants } from '../Auth/Auth.constants';
|
||||
import { TenancyDatabaseModule } from '../Tenancy/TenancyDB/TenancyDB.module';
|
||||
import { TenancyModelsModule } from '../Tenancy/TenancyModels/Tenancy.module';
|
||||
import { LoggerMiddleware } from '@/middleware/logger.middleware';
|
||||
import { ExcludeNullInterceptor } from '@/interceptors/ExcludeNull.interceptor';
|
||||
import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
|
||||
import { JwtAuthGuard } from '../Auth/Jwt.guard';
|
||||
import { UserIpInterceptor } from '@/interceptors/user-ip.interceptor';
|
||||
import { TenancyGlobalMiddleware } from '../Tenancy/TenancyGlobal.middleware';
|
||||
import { TransformerModule } from '../Transformer/Transformer.module';
|
||||
import { AccountsModule } from '../Accounts/Accounts.module';
|
||||
import { ExpensesModule } from '../Expenses/Expenses.module';
|
||||
import { ItemCategoryModule } from '../ItemCategories/ItemCategory.module';
|
||||
import { TaxRatesModule } from '../TaxRates/TaxRate.module';
|
||||
import { PdfTemplatesModule } from '../PdfTemplate/PdfTemplates.module';
|
||||
import { BranchesModule } from '../Branches/Branches.module';
|
||||
import { WarehousesModule } from '../Warehouses/Warehouses.module';
|
||||
import { SerializeInterceptor } from '@/common/interceptors/serialize.interceptor';
|
||||
import { ChromiumlyTenancyModule } from '../ChromiumlyTenancy/ChromiumlyTenancy.module';
|
||||
import { CustomersModule } from '../Customers/Customers.module';
|
||||
import { VendorsModule } from '../Vendors/Vendors.module';
|
||||
import { SaleEstimatesModule } from '../SaleEstimates/SaleEstimates.module';
|
||||
import { BillsModule } from '../Bills/Bills.module';
|
||||
import { SaleInvoicesModule } from '../SaleInvoices/SaleInvoices.module';
|
||||
import { SaleReceiptsModule } from '../SaleReceipts/SaleReceipts.module';
|
||||
import { ManualJournalsModule } from '../ManualJournals/ManualJournals.module';
|
||||
import { CreditNotesModule } from '../CreditNotes/CreditNotes.module';
|
||||
import { VendorCreditsModule } from '../VendorCredit/VendorCredits.module';
|
||||
import { VendorCreditApplyBillsModule } from '../VendorCreditsApplyBills/VendorCreditApplyBills.module';
|
||||
import { VendorCreditsRefundModule } from '../VendorCreditsRefund/VendorCreditsRefund.module';
|
||||
import { CreditNoteRefundsModule } from '../CreditNoteRefunds/CreditNoteRefunds.module';
|
||||
import { BillPaymentsModule } from '../BillPayments/BillPayments.module';
|
||||
import { PaymentsReceivedModule } from '../PaymentReceived/PaymentsReceived.module';
|
||||
import { LedgerModule } from '../Ledger/Ledger.module';
|
||||
import { BankRulesModule } from '../BankRules/BankRules.module';
|
||||
import { BankAccountsModule } from '../BankingAccounts/BankAccounts.module';
|
||||
import { BankingTransactionsExcludeModule } from '../BankingTransactionsExclude/BankingTransactionsExclude.module';
|
||||
import { BankingTransactionsRegonizeModule } from '../BankingTranasctionsRegonize/BankingTransactionsRegonize.module';
|
||||
import { BankingMatchingModule } from '../BankingMatching/BankingMatching.module';
|
||||
import { BankingTransactionsModule } from '../BankingTransactions/BankingTransactions.module';
|
||||
import { TransactionsLockingModule } from '../TransactionsLocking/TransactionsLocking.module';
|
||||
import { SettingsModule } from '../Settings/Settings.module';
|
||||
import { InventoryAdjustmentsModule } from '../InventoryAdjutments/InventoryAdjustments.module';
|
||||
import { PostHogModule } from '../EventsTracker/postHog.module';
|
||||
import { EventTrackerModule } from '../EventsTracker/EventTracker.module';
|
||||
import { MailModule } from '../Mail/Mail.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
envFilePath: '.env',
|
||||
load: config,
|
||||
isGlobal: true,
|
||||
}),
|
||||
SystemDatabaseModule,
|
||||
SystemModelsModule,
|
||||
EventEmitterModule.forRoot(),
|
||||
I18nModule.forRootAsync({
|
||||
useFactory: () => ({
|
||||
fallbackLanguage: 'en',
|
||||
loaderOptions: {
|
||||
path: join(__dirname, '/../../i18n/'),
|
||||
watch: true,
|
||||
},
|
||||
}),
|
||||
resolvers: [
|
||||
new QueryResolver(),
|
||||
new HeaderResolver(),
|
||||
new CookieResolver(),
|
||||
AcceptLanguageResolver,
|
||||
],
|
||||
}),
|
||||
PassportModule,
|
||||
JwtModule.register({
|
||||
secret: jwtConstants.secret,
|
||||
signOptions: { expiresIn: '60s' },
|
||||
}),
|
||||
BullModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
useFactory: async (configService: ConfigService) => ({
|
||||
connection: {
|
||||
host: configService.get('QUEUE_HOST'),
|
||||
port: configService.get('QUEUE_PORT'),
|
||||
},
|
||||
}),
|
||||
inject: [ConfigService],
|
||||
}),
|
||||
ClsModule.forRoot({
|
||||
global: true,
|
||||
middleware: {
|
||||
mount: true,
|
||||
setup: (cls, req: Request, res: Response) => {
|
||||
cls.set('organizationId', req.headers['organization-id']);
|
||||
cls.set('userId', 1);
|
||||
},
|
||||
},
|
||||
}),
|
||||
TenancyDatabaseModule,
|
||||
TenancyModelsModule,
|
||||
ChromiumlyTenancyModule,
|
||||
TransformerModule,
|
||||
MailModule,
|
||||
ItemsModule,
|
||||
ItemCategoryModule,
|
||||
AccountsModule,
|
||||
ExpensesModule,
|
||||
TaxRatesModule,
|
||||
PdfTemplatesModule,
|
||||
BranchesModule,
|
||||
WarehousesModule,
|
||||
CustomersModule,
|
||||
VendorsModule,
|
||||
SaleInvoicesModule,
|
||||
SaleEstimatesModule,
|
||||
SaleReceiptsModule,
|
||||
BillsModule,
|
||||
ManualJournalsModule,
|
||||
CreditNotesModule,
|
||||
VendorCreditsModule,
|
||||
VendorCreditApplyBillsModule,
|
||||
VendorCreditsRefundModule,
|
||||
CreditNoteRefundsModule,
|
||||
BillPaymentsModule,
|
||||
PaymentsReceivedModule,
|
||||
LedgerModule,
|
||||
BankAccountsModule,
|
||||
BankRulesModule,
|
||||
BankingTransactionsModule,
|
||||
BankingTransactionsExcludeModule,
|
||||
BankingTransactionsRegonizeModule,
|
||||
BankingMatchingModule,
|
||||
TransactionsLockingModule,
|
||||
SettingsModule,
|
||||
InventoryAdjustmentsModule,
|
||||
PostHogModule,
|
||||
EventTrackerModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [
|
||||
{
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: SerializeInterceptor,
|
||||
},
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: JwtAuthGuard,
|
||||
},
|
||||
{
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: UserIpInterceptor,
|
||||
},
|
||||
{
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: ExcludeNullInterceptor,
|
||||
},
|
||||
AppService,
|
||||
JwtStrategy,
|
||||
],
|
||||
})
|
||||
export class AppModule {
|
||||
configure(consumer: MiddlewareConsumer) {
|
||||
consumer
|
||||
.apply(LoggerMiddleware)
|
||||
.forRoutes({ path: '*', method: RequestMethod.ALL });
|
||||
|
||||
consumer
|
||||
.apply(TenancyGlobalMiddleware)
|
||||
.forRoutes({ path: '*', method: RequestMethod.ALL });
|
||||
}
|
||||
}
|
||||
24
packages/server-nest/src/modules/App/App.service.ts
Normal file
24
packages/server-nest/src/modules/App/App.service.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
// configService: ConfigService;
|
||||
|
||||
constructor(
|
||||
private configService: ConfigService,
|
||||
private jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
getHello(): string {
|
||||
console.log(this.configService.get('DATABASE_PORT'));
|
||||
const payload = {};
|
||||
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
|
||||
console.log(accessToken);
|
||||
|
||||
return accessToken;
|
||||
}
|
||||
}
|
||||
4
packages/server-nest/src/modules/Auth/Auth.constants.ts
Normal file
4
packages/server-nest/src/modules/Auth/Auth.constants.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export const jwtConstants = {
|
||||
secret:
|
||||
'DO NOT USE THIS VALUE. INSTEAD, CREATE A COMPLEX SECRET AND KEEP IT SAFE OUTSIDE OF THE SOURCE CODE.',
|
||||
};
|
||||
5
packages/server-nest/src/modules/Auth/Auth.interfaces.ts
Normal file
5
packages/server-nest/src/modules/Auth/Auth.interfaces.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export interface IAuthSignedInEventPayload {}
|
||||
|
||||
export interface IAuthSigningInEventPayload {}
|
||||
|
||||
export interface IAuthSignInPOJO {}
|
||||
@@ -0,0 +1,4 @@
|
||||
|
||||
export class AuthApplication {
|
||||
|
||||
}
|
||||
32
packages/server-nest/src/modules/Auth/Jwt.guard.ts
Normal file
32
packages/server-nest/src/modules/Auth/Jwt.guard.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
Scope,
|
||||
SetMetadata,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { ClsService } from 'nestjs-cls';
|
||||
|
||||
export const IS_PUBLIC_KEY = 'isPublic';
|
||||
export const PublicRoute = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
constructor(
|
||||
private reflector: Reflector,
|
||||
private readonly cls: ClsService,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
canActivate(context: ExecutionContext) {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (isPublic) {
|
||||
return true;
|
||||
}
|
||||
return super.canActivate(context);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user