Compare commits
52 Commits
auth-pages
...
v0.23.0-rc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
32d74b0413 | ||
|
|
71b1206f8a | ||
|
|
cb1bcaae77 | ||
|
|
eb51646035 | ||
|
|
8f54754aba | ||
|
|
0f446f90ca | ||
|
|
7cb67b257b | ||
|
|
0a1fffb3a4 | ||
|
|
b756f090ed | ||
|
|
f9e49727fc | ||
|
|
66969753b1 | ||
|
|
3648fb3ffc | ||
|
|
e196d485cf | ||
|
|
74e46364ac | ||
|
|
8817be4813 | ||
|
|
cd4816aa3b | ||
|
|
82a2c74182 | ||
|
|
e231efb9de | ||
|
|
65ffc31ec0 | ||
|
|
dc6cf13a3e | ||
|
|
adfa8852db | ||
|
|
ff04c4b762 | ||
|
|
fe4bd88f9f | ||
|
|
caf232d928 | ||
|
|
234b1804b3 | ||
|
|
98b3b551c1 | ||
|
|
ceed9e453f | ||
|
|
43faa45dcf | ||
|
|
56e00d254b | ||
|
|
d90b6ffbe7 | ||
|
|
5eafd23bf8 | ||
|
|
2b384b2f6f | ||
|
|
17bcc14231 | ||
|
|
2c64e1b8ab | ||
|
|
6f50138260 | ||
|
|
0a7d687f91 | ||
|
|
2383091b6e | ||
|
|
e2f5d4c66e | ||
|
|
ce70234ebd | ||
|
|
80abd1f66f | ||
|
|
a0bc9db9a6 | ||
|
|
8161439365 | ||
|
|
46871c8113 | ||
|
|
a4aee58f93 | ||
|
|
f64875404a | ||
|
|
cca116f6bb | ||
|
|
fdec94a3f7 | ||
|
|
c66299aacd | ||
|
|
77dc0778a3 | ||
|
|
a76445a6eb | ||
|
|
41143d8bbd | ||
|
|
844a050c9a |
@@ -168,6 +168,16 @@
|
||||
"contributions": [
|
||||
"bug"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "Daniel15",
|
||||
"name": "Daniel Lo Nigro",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/91933?v=4",
|
||||
"profile": "https://d.sb/",
|
||||
"contributions": [
|
||||
"bug",
|
||||
"code"
|
||||
]
|
||||
}
|
||||
],
|
||||
"contributorsPerLine": 7,
|
||||
|
||||
12
.env.example
12
.env.example
@@ -98,8 +98,18 @@ POSTHOG_API_KEY=
|
||||
POSTHOG_HOST=
|
||||
|
||||
# Stripe Payment
|
||||
# Get the keys from the Stripe dashboard
|
||||
# Starts with "sk_"
|
||||
STRIPE_PAYMENT_SECRET_KEY=
|
||||
# Starts with "pk_"
|
||||
STRIPE_PAYMENT_PUBLISHABLE_KEY=
|
||||
# Get the client ID from https://dashboard.stripe.com/settings/connect/onboarding-options/oauth
|
||||
# Starts with "ca_"
|
||||
STRIPE_PAYMENT_CLIENT_ID=
|
||||
# Configure the webhook here: https://dashboard.stripe.com/workbench/webhooks/
|
||||
# Endpoint URL is https://example.com/api/webhooks/stripe (replace "example.com" with the correct domain)
|
||||
# Select the "checkout.session.completed" and "account.updated" events
|
||||
# Starts with "whsec_"
|
||||
STRIPE_PAYMENT_WEBHOOKS_SECRET=
|
||||
STRIPE_PAYMENT_REDIRECT_URL=
|
||||
# Replace example.com with the correct domain
|
||||
STRIPE_PAYMENT_REDIRECT_URL=https://example.com/preferences/payment-methods/stripe/callback
|
||||
|
||||
@@ -54,7 +54,7 @@ pnpm install
|
||||
- Run all required docker containers in the development, we already configured all containers under `docker-compose.yml`.
|
||||
|
||||
```
|
||||
docker-compose up -d
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Wait some seconds, and hit `docker-compose ps` and you should see the same result below.
|
||||
@@ -75,7 +75,7 @@ pnpm run build:server
|
||||
- Run the database migration for system database.
|
||||
|
||||
```
|
||||
node packages/server/build/commands.js system:migrate:latest
|
||||
pnpm run system:migrate:latest
|
||||
```
|
||||
|
||||
And you should get something like that.
|
||||
@@ -84,10 +84,10 @@ And you should get something like that.
|
||||
Batch 1 run: 6 migrations
|
||||
```
|
||||
|
||||
- Next, start the webapp application.
|
||||
- Next, start the server.
|
||||
|
||||
```
|
||||
pnpm run dev:server
|
||||
pnpm run server:start
|
||||
```
|
||||
|
||||
**[`^top^`](#)**
|
||||
@@ -96,12 +96,6 @@ pnpm run dev:server
|
||||
|
||||
## Contribute to Frontend
|
||||
|
||||
- Clone the `bigcapital` repository and cd into `bigcapital` directory.
|
||||
|
||||
```
|
||||
git clone https://github.com/bigcapital/bigcapital.git && cd bigcaptial
|
||||
```
|
||||
|
||||
- Install all npm dependencies of the monorepo, you don't have to change directory to the `frontend` package. just hit that command and will install all packages across all application.
|
||||
|
||||
```
|
||||
@@ -138,4 +132,4 @@ There are many other ways to get involved with the community and to participate
|
||||
|
||||
Again, Feel free to ping us on [`#contributing`](https://discord.com/invite/c8nPBJafeb) on our Discord community if you need any help on this :)
|
||||
|
||||
Thank You!
|
||||
Thank You!
|
||||
|
||||
@@ -135,6 +135,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://myself.vercel.app/"><img src="https://avatars.githubusercontent.com/u/42431274?v=4?s=100" width="100px;" alt="Sachin Mittal"/><br /><sub><b>Sachin Mittal</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3Amittalsam98" title="Bug reports">🐛</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://www.camilooviedo.com/"><img src="https://avatars.githubusercontent.com/u/64604272?v=4?s=100" width="100px;" alt="Camilo Oviedo"/><br /><sub><b>Camilo Oviedo</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/commits?author=Champetaman" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://nklmantey.com/"><img src="https://avatars.githubusercontent.com/u/90279429?v=4?s=100" width="100px;" alt="Mantey"/><br /><sub><b>Mantey</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3Anklmantey" title="Bug reports">🐛</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://d.sb/"><img src="https://avatars.githubusercontent.com/u/91933?v=4?s=100" width="100px;" alt="Daniel Lo Nigro"/><br /><sub><b>Daniel Lo Nigro</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3ADaniel15" title="Bug reports">🐛</a> <a href="https://github.com/bigcapitalhq/bigcapital/commits?author=Daniel15" title="Code">💻</a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -93,7 +93,7 @@ services:
|
||||
- OPEN_EXCHANGE_RATE_APP_ID-${OPEN_EXCHANGE_RATE_APP_ID}
|
||||
|
||||
# Bank Sync
|
||||
- BANKING_CONNECT=${BANKING_CONNECT}
|
||||
- BANK_FEED_ENABLED=${BANK_FEED_ENABLED}
|
||||
|
||||
# Plaid
|
||||
- PLAID_ENV=${PLAID_ENV}
|
||||
@@ -122,6 +122,13 @@ services:
|
||||
- S3_SECRET_ACCESS_KEY=${S3_SECRET_ACCESS_KEY}
|
||||
- S3_ENDPOINT=${S3_ENDPOINT}
|
||||
- S3_BUCKET=${S3_BUCKET}
|
||||
|
||||
# Stripe
|
||||
- STRIPE_PAYMENT_SECRET_KEY=${STRIPE_PAYMENT_SECRET_KEY}
|
||||
- STRIPE_PAYMENT_PUBLISHABLE_KEY=${STRIPE_PAYMENT_PUBLISHABLE_KEY}
|
||||
- STRIPE_PAYMENT_CLIENT_ID=${STRIPE_PAYMENT_CLIENT_ID}
|
||||
- STRIPE_PAYMENT_WEBHOOKS_SECRET=${STRIPE_PAYMENT_WEBHOOKS_SECRET}
|
||||
- STRIPE_PAYMENT_REDIRECT_URL=${STRIPE_PAYMENT_REDIRECT_URL}
|
||||
|
||||
database_migration:
|
||||
container_name: bigcapital-database-migration
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM redis:6.2.0
|
||||
FROM redis:6.2.21
|
||||
|
||||
COPY redis.conf /usr/local/etc/redis/redis.conf
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
"@casl/ability": "^5.4.3",
|
||||
"@lemonsqueezy/lemonsqueezy.js": "^2.2.0",
|
||||
"@liaoliaots/nestjs-redis": "^10.0.0",
|
||||
"@nest-lab/throttler-storage-redis": "^1.1.0",
|
||||
"@nestjs/bull": "^10.2.1",
|
||||
"@nestjs/bullmq": "^10.2.2",
|
||||
"@nestjs/cache-manager": "^2.2.2",
|
||||
|
||||
5
packages/server/src/common/config/cloud.ts
Normal file
5
packages/server/src/common/config/cloud.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { registerAs } from '@nestjs/config';
|
||||
|
||||
export default registerAs('cloud', () => ({
|
||||
hostedOnCloud: process.env.HOSTED_ON_BIGCAPITAL_CLOUD === 'true',
|
||||
}));
|
||||
@@ -14,9 +14,12 @@ import jwt from './jwt';
|
||||
import mail from './mail';
|
||||
import loops from './loops';
|
||||
import bankfeed from './bankfeed';
|
||||
import throttle from './throttle';
|
||||
import cloud from './cloud';
|
||||
|
||||
export const config = [
|
||||
systemDatabase,
|
||||
cloud,
|
||||
tenantDatabase,
|
||||
signup,
|
||||
gotenberg,
|
||||
@@ -32,4 +35,5 @@ export const config = [
|
||||
mail,
|
||||
loops,
|
||||
bankfeed,
|
||||
throttle,
|
||||
];
|
||||
|
||||
14
packages/server/src/common/config/throttle.ts
Normal file
14
packages/server/src/common/config/throttle.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { registerAs } from '@nestjs/config';
|
||||
|
||||
export default registerAs('throttle', () => ({
|
||||
global: {
|
||||
ttl: parseInt(process.env.THROTTLE_GLOBAL_TTL ?? '60000', 10),
|
||||
limit: parseInt(process.env.THROTTLE_GLOBAL_LIMIT ?? '100', 10),
|
||||
},
|
||||
auth: {
|
||||
ttl: parseInt(process.env.THROTTLE_AUTH_TTL ?? '60000', 10),
|
||||
limit: parseInt(process.env.THROTTLE_AUTH_LIMIT ?? '10', 10),
|
||||
},
|
||||
}));
|
||||
|
||||
|
||||
55
packages/server/src/common/dtos/BulkDelete.dto.ts
Normal file
55
packages/server/src/common/dtos/BulkDelete.dto.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { IsArray, IsInt, ArrayNotEmpty, IsBoolean, IsOptional } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Transform } from 'class-transformer';
|
||||
import { parseBoolean } from '@/utils/parse-boolean';
|
||||
|
||||
export class BulkDeleteDto {
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@IsInt({ each: true })
|
||||
@ApiProperty({
|
||||
description: 'Array of IDs to delete',
|
||||
type: [Number],
|
||||
example: [1, 2, 3],
|
||||
})
|
||||
ids: number[];
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Transform(({ value, obj }) => parseBoolean(value ?? obj?.skip_undeletable, false))
|
||||
@ApiPropertyOptional({
|
||||
description: 'When true, undeletable items will be skipped and only deletable ones will be removed.',
|
||||
type: Boolean,
|
||||
default: false,
|
||||
})
|
||||
skipUndeletable?: boolean;
|
||||
}
|
||||
|
||||
export class ValidateBulkDeleteResponseDto {
|
||||
@ApiProperty({
|
||||
description: 'Number of items that can be deleted',
|
||||
example: 2,
|
||||
})
|
||||
deletableCount: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Number of items that cannot be deleted',
|
||||
example: 1,
|
||||
})
|
||||
nonDeletableCount: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'IDs of items that can be deleted',
|
||||
type: [Number],
|
||||
example: [1, 2],
|
||||
})
|
||||
deletableIds: number[];
|
||||
|
||||
@ApiProperty({
|
||||
description: 'IDs of items that cannot be deleted',
|
||||
type: [Number],
|
||||
example: [3],
|
||||
})
|
||||
nonDeletableIds: number[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* @param { import("knex").Knex } knex
|
||||
* @returns { Promise<void> }
|
||||
*/
|
||||
exports.up = function (knex) {
|
||||
return knex.schema.createTable('api_keys', (table) => {
|
||||
table.increments();
|
||||
table.string('key').notNullable().unique().index();
|
||||
table.string('name');
|
||||
table
|
||||
.integer('user_id')
|
||||
.unsigned()
|
||||
.notNullable()
|
||||
.index()
|
||||
.references('id')
|
||||
.inTable('users');
|
||||
table
|
||||
.bigInteger('tenant_id')
|
||||
.unsigned()
|
||||
.notNullable()
|
||||
.index()
|
||||
.references('id')
|
||||
.inTable('tenants');
|
||||
table.dateTime('expires_at').nullable().index();
|
||||
table.dateTime('revoked_at').nullable().index();
|
||||
table.timestamps();
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @param { import("knex").Knex } knex
|
||||
* @returns { Promise<void> }
|
||||
*/
|
||||
exports.down = function (knex) {
|
||||
return knex.schema.dropTableIfExists('api_keys');
|
||||
};
|
||||
@@ -11,6 +11,7 @@ class FsMigrations {
|
||||
private sortDirsSeparately: boolean;
|
||||
private migrationsPaths: string[];
|
||||
private loadExtensions: string[];
|
||||
private seedsDirectory: string;
|
||||
|
||||
/**
|
||||
* Constructor method.
|
||||
@@ -30,6 +31,8 @@ class FsMigrations {
|
||||
}
|
||||
this.migrationsPaths = migrationDirectories;
|
||||
this.loadExtensions = loadExtensions || DEFAULT_LOAD_EXTENSIONS;
|
||||
// Store the seeds directory (first path is the seeds directory)
|
||||
this.seedsDirectory = migrationDirectories[0] || '';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,7 +96,10 @@ class FsMigrations {
|
||||
* @returns {string}
|
||||
*/
|
||||
public getMigration(migration: MigrateItem): string {
|
||||
return importWebpackSeedModule(migration.file.replace('.ts', ''));
|
||||
return importWebpackSeedModule(
|
||||
migration.file.replace('.ts', ''),
|
||||
this.seedsDirectory,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// @ts-nocheck
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
/**
|
||||
* Detarmines the module type of the given file path.
|
||||
@@ -35,8 +36,32 @@ export async function importFile(filepath: string): any {
|
||||
/**
|
||||
*
|
||||
* @param {string} moduleName
|
||||
* @param {string} seedsDirectory - The seeds directory path from config
|
||||
* @returns
|
||||
*/
|
||||
export async function importWebpackSeedModule(moduleName: string): any {
|
||||
return import(`../../database/seeds/core/${moduleName}`);
|
||||
export async function importWebpackSeedModule(
|
||||
moduleName: string,
|
||||
seedsDirectory: string,
|
||||
): any {
|
||||
// Convert the seeds directory to a relative path from this file's location
|
||||
const utilsDir = __dirname;
|
||||
const seedsDirAbsolute = path.isAbsolute(seedsDirectory)
|
||||
? seedsDirectory
|
||||
: path.resolve(process.cwd(), seedsDirectory);
|
||||
|
||||
// Get relative path from Utils.js location to seeds directory
|
||||
const relativePath = path.relative(utilsDir, seedsDirAbsolute);
|
||||
|
||||
// Convert to forward slashes for import (works on all platforms)
|
||||
const importPath = relativePath.split(path.sep).join('/');
|
||||
|
||||
// Construct the import path (add ./ prefix if not already present, or handle empty/current dir)
|
||||
let finalPath = importPath;
|
||||
if (!finalPath || finalPath === '.') {
|
||||
finalPath = './';
|
||||
} else if (!finalPath.startsWith('.')) {
|
||||
finalPath = `./${finalPath}`;
|
||||
}
|
||||
|
||||
return import(`${finalPath}/${moduleName}`);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ global.__views_dirname = path.join(global.__static_dirname, '/views');
|
||||
global.__images_dirname = path.join(global.__static_dirname, '/images');
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
const app = await NestFactory.create(AppModule, { rawBody: true });
|
||||
app.setGlobalPrefix('/api');
|
||||
|
||||
// create and mount the middleware manually here
|
||||
|
||||
@@ -7,15 +7,16 @@ import {
|
||||
Get,
|
||||
Query,
|
||||
ParseIntPipe,
|
||||
Put,
|
||||
} from '@nestjs/common';
|
||||
import { AccountsApplication } from './AccountsApplication.service';
|
||||
import { CreateAccountDTO } from './CreateAccount.dto';
|
||||
import { EditAccountDTO } from './EditAccount.dto';
|
||||
import { IAccountsFilter } from './Accounts.types';
|
||||
import {
|
||||
ApiExtraModels,
|
||||
ApiOperation,
|
||||
ApiParam,
|
||||
ApiQuery,
|
||||
ApiResponse,
|
||||
ApiTags,
|
||||
getSchemaPath,
|
||||
@@ -24,16 +25,57 @@ import { AccountResponseDto } from './dtos/AccountResponse.dto';
|
||||
import { AccountTypeResponseDto } from './dtos/AccountTypeResponse.dto';
|
||||
import { GetAccountTransactionResponseDto } from './dtos/GetAccountTransactionResponse.dto';
|
||||
import { GetAccountTransactionsQueryDto } from './dtos/GetAccountTransactionsQuery.dto';
|
||||
import { GetAccountsQueryDto } from './dtos/GetAccountsQuery.dto';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
import {
|
||||
BulkDeleteDto,
|
||||
ValidateBulkDeleteResponseDto,
|
||||
} from '@/common/dtos/BulkDelete.dto';
|
||||
|
||||
@Controller('accounts')
|
||||
@ApiTags('Accounts')
|
||||
@ApiExtraModels(AccountResponseDto)
|
||||
@ApiExtraModels(AccountTypeResponseDto)
|
||||
@ApiExtraModels(GetAccountTransactionResponseDto)
|
||||
@ApiExtraModels(ValidateBulkDeleteResponseDto)
|
||||
@ApiCommonHeaders()
|
||||
export class AccountsController {
|
||||
constructor(private readonly accountsApplication: AccountsApplication) {}
|
||||
constructor(private readonly accountsApplication: AccountsApplication) { }
|
||||
|
||||
@Post('validate-bulk-delete')
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Validates which accounts can be deleted and returns counts of deletable and non-deletable accounts.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
'Validation completed. Returns counts and IDs of deletable and non-deletable accounts.',
|
||||
schema: {
|
||||
$ref: getSchemaPath(ValidateBulkDeleteResponseDto),
|
||||
},
|
||||
})
|
||||
async validateBulkDeleteAccounts(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
): Promise<ValidateBulkDeleteResponseDto> {
|
||||
return this.accountsApplication.validateBulkDeleteAccounts(
|
||||
bulkDeleteDto.ids,
|
||||
);
|
||||
}
|
||||
|
||||
@Post('bulk-delete')
|
||||
@ApiOperation({ summary: 'Deletes multiple accounts in bulk.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'The accounts have been successfully deleted.',
|
||||
})
|
||||
async bulkDeleteAccounts(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
): Promise<void> {
|
||||
return this.accountsApplication.bulkDeleteAccounts(bulkDeleteDto.ids, {
|
||||
skipUndeletable: bulkDeleteDto.skipUndeletable ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create an account' })
|
||||
@@ -45,7 +87,7 @@ export class AccountsController {
|
||||
return this.accountsApplication.createAccount(accountDTO);
|
||||
}
|
||||
|
||||
@Post(':id')
|
||||
@Put(':id')
|
||||
@ApiOperation({ summary: 'Edit the given account.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
@@ -178,7 +220,19 @@ export class AccountsController {
|
||||
items: { $ref: getSchemaPath(AccountResponseDto) },
|
||||
},
|
||||
})
|
||||
async getAccounts(@Query() filter: Partial<IAccountsFilter>) {
|
||||
@ApiQuery({
|
||||
name: 'onlyInactive',
|
||||
required: false,
|
||||
type: Boolean,
|
||||
description: 'Filter to show only inactive accounts',
|
||||
})
|
||||
@ApiQuery({
|
||||
name: 'structure',
|
||||
required: false,
|
||||
type: String,
|
||||
description: 'Structure type for the accounts list',
|
||||
})
|
||||
async getAccounts(@Query() filter: GetAccountsQueryDto) {
|
||||
return this.accountsApplication.getAccounts(filter);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,8 @@ import { GetAccountsService } from './GetAccounts.service';
|
||||
import { DynamicListModule } from '../DynamicListing/DynamicList.module';
|
||||
import { AccountsExportable } from './AccountsExportable.service';
|
||||
import { AccountsImportable } from './AccountsImportable.service';
|
||||
import { BulkDeleteAccountsService } from './BulkDeleteAccounts.service';
|
||||
import { ValidateBulkDeleteAccountsService } from './ValidateBulkDeleteAccounts.service';
|
||||
|
||||
const models = [RegisterTenancyModel(BankAccount)];
|
||||
|
||||
@@ -40,7 +42,9 @@ const models = [RegisterTenancyModel(BankAccount)];
|
||||
GetAccountTransactionsService,
|
||||
GetAccountsService,
|
||||
AccountsExportable,
|
||||
AccountsImportable
|
||||
AccountsImportable,
|
||||
BulkDeleteAccountsService,
|
||||
ValidateBulkDeleteAccountsService,
|
||||
],
|
||||
exports: [
|
||||
AccountRepository,
|
||||
|
||||
@@ -10,10 +10,14 @@ import { GetAccount } from './GetAccount.service';
|
||||
import { ActivateAccount } from './ActivateAccount.service';
|
||||
import { GetAccountTypesService } from './GetAccountTypes.service';
|
||||
import { GetAccountTransactionsService } from './GetAccountTransactions.service';
|
||||
import { IAccountsFilter, IAccountsTransactionsFilter } from './Accounts.types';
|
||||
import { IAccountsTransactionsFilter } from './Accounts.types';
|
||||
import { GetAccountsService } from './GetAccounts.service';
|
||||
import { IFilterMeta } from '@/interfaces/Model';
|
||||
import { GetAccountTransactionResponseDto } from './dtos/GetAccountTransactionResponse.dto';
|
||||
import { GetAccountsQueryDto } from './dtos/GetAccountsQuery.dto';
|
||||
import { BulkDeleteAccountsService } from './BulkDeleteAccounts.service';
|
||||
import { ValidateBulkDeleteAccountsService } from './ValidateBulkDeleteAccounts.service';
|
||||
import { ValidateBulkDeleteResponseDto } from '@/common/dtos/BulkDelete.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AccountsApplication {
|
||||
@@ -36,7 +40,9 @@ export class AccountsApplication {
|
||||
private readonly getAccountService: GetAccount,
|
||||
private readonly getAccountTransactionsService: GetAccountTransactionsService,
|
||||
private readonly getAccountsService: GetAccountsService,
|
||||
) {}
|
||||
private readonly bulkDeleteAccountsService: BulkDeleteAccountsService,
|
||||
private readonly validateBulkDeleteAccountsService: ValidateBulkDeleteAccountsService,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Creates a new account.
|
||||
@@ -108,11 +114,11 @@ export class AccountsApplication {
|
||||
|
||||
/**
|
||||
* Retrieves the accounts list.
|
||||
* @param {IAccountsFilter} filterDTO - Filter DTO.
|
||||
* @param {GetAccountsQueryDto} filterDTO - Filter DTO.
|
||||
* @returns {Promise<{ accounts: IAccountResponse[]; filterMeta: IFilterMeta }>}
|
||||
*/
|
||||
public getAccounts = (
|
||||
filterDTO: Partial<IAccountsFilter>,
|
||||
filterDTO: GetAccountsQueryDto,
|
||||
): Promise<{ accounts: Account[]; filterMeta: IFilterMeta }> => {
|
||||
return this.getAccountsService.getAccountsList(filterDTO);
|
||||
};
|
||||
@@ -127,4 +133,28 @@ export class AccountsApplication {
|
||||
): Promise<Array<GetAccountTransactionResponseDto>> => {
|
||||
return this.getAccountTransactionsService.getAccountsTransactions(filter);
|
||||
};
|
||||
|
||||
/**
|
||||
* Validates which accounts can be deleted in bulk.
|
||||
*/
|
||||
public validateBulkDeleteAccounts = (
|
||||
accountIds: number[],
|
||||
): Promise<ValidateBulkDeleteResponseDto> => {
|
||||
return this.validateBulkDeleteAccountsService.validateBulkDeleteAccounts(
|
||||
accountIds,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes multiple accounts in bulk.
|
||||
*/
|
||||
public bulkDeleteAccounts = (
|
||||
accountIds: number[],
|
||||
options?: { skipUndeletable?: boolean },
|
||||
): Promise<void> => {
|
||||
return this.bulkDeleteAccountsService.bulkDeleteAccounts(
|
||||
accountIds,
|
||||
options,
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { PromisePool } from '@supercharge/promise-pool';
|
||||
import { castArray, uniq } from 'lodash';
|
||||
import { DeleteAccount } from './DeleteAccount.service';
|
||||
|
||||
@Injectable()
|
||||
export class BulkDeleteAccountsService {
|
||||
constructor(private readonly deleteAccountService: DeleteAccount) { }
|
||||
|
||||
/**
|
||||
* Deletes multiple accounts.
|
||||
* @param {number | Array<number>} accountIds - The account id or ids.
|
||||
* @param {Knex.Transaction} trx - The transaction.
|
||||
*/
|
||||
async bulkDeleteAccounts(
|
||||
accountIds: number | Array<number>,
|
||||
options?: { skipUndeletable?: boolean },
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
const { skipUndeletable = false } = options ?? {};
|
||||
const accountsIds = uniq(castArray(accountIds));
|
||||
|
||||
const results = await PromisePool.withConcurrency(1)
|
||||
.for(accountsIds)
|
||||
.process(async (accountId: number) => {
|
||||
try {
|
||||
await this.deleteAccountService.deleteAccount(accountId);
|
||||
} catch (error) {
|
||||
if (!skipUndeletable) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!skipUndeletable && results.errors && results.errors.length > 0) {
|
||||
throw results.errors[0].raw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ export class CommandAccountValidators {
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: TenantModelProxy<typeof Account>,
|
||||
private readonly accountRepository: AccountRepository,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Throws error if the account was prefined.
|
||||
@@ -115,7 +115,7 @@ export class CommandAccountValidators {
|
||||
accountName: string,
|
||||
notAccountId?: number,
|
||||
) {
|
||||
const foundAccount = await this.accountModel
|
||||
const foundAccount = await this.accountModel()
|
||||
.query()
|
||||
.findOne('name', accountName)
|
||||
.onBuild((query) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { IsOptional, ToNumber } from '@/common/decorators/Validators';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
IsString,
|
||||
IsOptional,
|
||||
IsInt,
|
||||
MinLength,
|
||||
MaxLength,
|
||||
@@ -65,7 +65,7 @@ export class CreateAccountDTO {
|
||||
description?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@ToNumber()
|
||||
@ApiProperty({
|
||||
description: 'ID of the parent account',
|
||||
example: 1,
|
||||
|
||||
@@ -50,8 +50,12 @@ export class DeleteAccount {
|
||||
/**
|
||||
* Deletes the account from the storage.
|
||||
* @param {number} accountId
|
||||
* @param {Knex.Transaction} trx - Database transaction instance.
|
||||
*/
|
||||
public deleteAccount = async (accountId: number): Promise<void> => {
|
||||
public deleteAccount = async (
|
||||
accountId: number,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> => {
|
||||
// Retrieve account or not found service error.
|
||||
const oldAccount = await this.accountModel().query().findById(accountId);
|
||||
|
||||
@@ -82,6 +86,6 @@ export class DeleteAccount {
|
||||
oldAccount,
|
||||
trx,
|
||||
} as IAccountEventDeletedPayload);
|
||||
});
|
||||
}, trx);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
import { IsString, MinLength, MaxLength } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
IsString,
|
||||
IsOptional,
|
||||
IsInt,
|
||||
MinLength,
|
||||
MaxLength,
|
||||
} from 'class-validator';
|
||||
import { IsOptional, ToNumber } from '@/common/decorators/Validators';
|
||||
|
||||
export class EditAccountDTO {
|
||||
@IsString()
|
||||
@@ -45,7 +40,7 @@ export class EditAccountDTO {
|
||||
description?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@ToNumber()
|
||||
@ApiProperty({
|
||||
description: 'The parent account ID of the account',
|
||||
example: 1,
|
||||
|
||||
@@ -17,7 +17,7 @@ export class EditAccount {
|
||||
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: TenantModelProxy<typeof Account>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Authorize the account editing.
|
||||
@@ -85,8 +85,7 @@ export class EditAccount {
|
||||
// Update the account on the storage.
|
||||
const account = await this.accountModel()
|
||||
.query(trx)
|
||||
.findById(accountId)
|
||||
.updateAndFetch({ ...accountDTO });
|
||||
.updateAndFetchById(accountId, { ...accountDTO });
|
||||
|
||||
// Triggers `onAccountEdited` event.
|
||||
// await this.eventEmitter.emitAsync(events.accounts.onEdited, {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Account } from './models/Account.model';
|
||||
import { AccountRepository } from './repositories/Account.repository';
|
||||
import { IFilterMeta } from '@/interfaces/Model';
|
||||
import { TenantModelProxy } from '../System/models/TenantBaseModel';
|
||||
import { GetAccountsQueryDto } from './dtos/GetAccountsQuery.dto';
|
||||
|
||||
@Injectable()
|
||||
export class GetAccountsService {
|
||||
@@ -18,7 +19,7 @@ export class GetAccountsService {
|
||||
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: TenantModelProxy<typeof Account>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieve accounts datatable list.
|
||||
@@ -26,12 +27,12 @@ export class GetAccountsService {
|
||||
* @returns {Promise<{ accounts: IAccountResponse[]; filterMeta: IFilterMeta }>}
|
||||
*/
|
||||
public async getAccountsList(
|
||||
filterDto: Partial<IAccountsFilter>,
|
||||
filterDto: Partial<GetAccountsQueryDto>,
|
||||
): Promise<{ accounts: Account[]; filterMeta: IFilterMeta }> {
|
||||
const parsedFilterDto = {
|
||||
sortOrder: 'desc',
|
||||
columnSortBy: 'created_at',
|
||||
inactiveMode: false,
|
||||
onlyInactive: false,
|
||||
structure: IAccountsStructureType.Tree,
|
||||
...filterDto,
|
||||
};
|
||||
@@ -48,7 +49,7 @@ export class GetAccountsService {
|
||||
.query()
|
||||
.onBuild((builder) => {
|
||||
dynamicList.buildQuery()(builder);
|
||||
builder.modify('inactiveMode', filter.inactiveMode);
|
||||
builder.modify('inactiveMode', filterDto.onlyInactive);
|
||||
});
|
||||
const accountsGraph = await this.accountRepository.getDependencyGraph();
|
||||
|
||||
@@ -58,7 +59,6 @@ export class GetAccountsService {
|
||||
new AccountTransformer(),
|
||||
{ accountsGraph, structure: parsedFilterDto.structure },
|
||||
);
|
||||
|
||||
return {
|
||||
accounts: transformedAccounts,
|
||||
filterMeta: dynamicList.getResponseMeta(),
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
|
||||
import { DeleteAccount } from './DeleteAccount.service';
|
||||
import { ModelHasRelationsError } from '@/common/exceptions/ModelHasRelations.exception';
|
||||
|
||||
@Injectable()
|
||||
export class ValidateBulkDeleteAccountsService {
|
||||
constructor(
|
||||
private readonly deleteAccountService: DeleteAccount,
|
||||
@Inject(TENANCY_DB_CONNECTION)
|
||||
private readonly tenantKnex: () => Knex,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Validates which accounts from the provided IDs can be deleted.
|
||||
* Uses the actual deleteAccount service to validate, ensuring the same validation logic.
|
||||
* Uses a transaction that is always rolled back to ensure no database changes.
|
||||
* @param {number[]} accountIds - Array of account IDs to validate
|
||||
* @returns {Promise<{deletableCount: number, nonDeletableCount: number, deletableIds: number[], nonDeletableIds: number[]}>}
|
||||
*/
|
||||
public async validateBulkDeleteAccounts(accountIds: number[]): Promise<{
|
||||
deletableCount: number;
|
||||
nonDeletableCount: number;
|
||||
deletableIds: number[];
|
||||
nonDeletableIds: number[];
|
||||
}> {
|
||||
const trx = await this.tenantKnex().transaction({
|
||||
isolationLevel: 'read uncommitted',
|
||||
});
|
||||
|
||||
try {
|
||||
const deletableIds: number[] = [];
|
||||
const nonDeletableIds: number[] = [];
|
||||
|
||||
for (const accountId of accountIds) {
|
||||
try {
|
||||
await this.deleteAccountService.deleteAccount(accountId, trx);
|
||||
deletableIds.push(accountId);
|
||||
} catch (error) {
|
||||
if (error instanceof ModelHasRelationsError) {
|
||||
nonDeletableIds.push(accountId);
|
||||
} else {
|
||||
nonDeletableIds.push(accountId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await trx.rollback();
|
||||
|
||||
return {
|
||||
deletableCount: deletableIds.length,
|
||||
nonDeletableCount: nonDeletableIds.length,
|
||||
deletableIds,
|
||||
nonDeletableIds,
|
||||
};
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { IsBoolean, IsEnum, IsOptional } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Transform } from 'class-transformer';
|
||||
import { parseBoolean } from '@/utils/parse-boolean';
|
||||
import { IAccountsStructureType } from '../Accounts.types';
|
||||
|
||||
export class GetAccountsQueryDto {
|
||||
@ApiPropertyOptional({
|
||||
type: Boolean,
|
||||
description: 'Filter to show only inactive accounts',
|
||||
default: false,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Transform(({ value }) => parseBoolean(value, false))
|
||||
onlyInactive?: boolean;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
enum: IAccountsStructureType,
|
||||
description: 'Structure type for the accounts list',
|
||||
default: IAccountsStructureType.Tree,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsEnum(IAccountsStructureType)
|
||||
structure?: IAccountsStructureType;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { MiddlewareConsumer, Module, RequestMethod } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { EventEmitterModule } from '@nestjs/event-emitter';
|
||||
import { APP_INTERCEPTOR } from '@nestjs/core';
|
||||
import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
|
||||
import { join } from 'path';
|
||||
import { ServeStaticModule } from '@nestjs/serve-static';
|
||||
import { RedisModule } from '@liaoliaots/nestjs-redis';
|
||||
@@ -95,6 +95,8 @@ import { BankingCategorizeModule } from '../BankingCategorize/BankingCategorize.
|
||||
import { TenantModelsInitializeModule } from '../Tenancy/TenantModelsInitialize.module';
|
||||
import { BillLandedCostsModule } from '../BillLandedCosts/BillLandedCosts.module';
|
||||
import { SocketModule } from '../Socket/Socket.module';
|
||||
import { ThrottlerGuard } from '@nestjs/throttler';
|
||||
import { AppThrottleModule } from './AppThrottle.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -126,6 +128,7 @@ import { SocketModule } from '../Socket/Socket.module';
|
||||
],
|
||||
}),
|
||||
PassportModule,
|
||||
AppThrottleModule,
|
||||
BullModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
useFactory: async (configService: ConfigService) => ({
|
||||
@@ -231,6 +234,10 @@ import { SocketModule } from '../Socket/Socket.module';
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: ThrottlerGuard,
|
||||
},
|
||||
{
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: SerializeInterceptor,
|
||||
|
||||
48
packages/server/src/modules/App/AppThrottle.module.ts
Normal file
48
packages/server/src/modules/App/AppThrottle.module.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { ThrottlerModule } from '@nestjs/throttler';
|
||||
import { ThrottlerStorageRedisService } from '@nest-lab/throttler-storage-redis';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ThrottlerModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: (configService: ConfigService) => {
|
||||
const host = configService.get<string>('redis.host') || 'localhost';
|
||||
const port = Number(configService.get<number>('redis.port') || 6379);
|
||||
const password = configService.get<string>('redis.password');
|
||||
const db = configService.get<number>('redis.db');
|
||||
|
||||
const globalTtl = configService.get<number>('throttle.global.ttl');
|
||||
const globalLimit = configService.get<number>('throttle.global.limit');
|
||||
const authTtl = configService.get<number>('throttle.auth.ttl');
|
||||
const authLimit = configService.get<number>('throttle.auth.limit');
|
||||
|
||||
return {
|
||||
throttlers: [
|
||||
{
|
||||
name: 'default',
|
||||
ttl: globalTtl,
|
||||
limit: globalLimit,
|
||||
},
|
||||
{
|
||||
name: 'auth',
|
||||
ttl: authTtl,
|
||||
limit: authLimit,
|
||||
},
|
||||
],
|
||||
storage: new ThrottlerStorageRedisService({
|
||||
host,
|
||||
port,
|
||||
password,
|
||||
db,
|
||||
}),
|
||||
};
|
||||
},
|
||||
}),
|
||||
],
|
||||
})
|
||||
export class AppThrottleModule { }
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
Request,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
@@ -28,6 +29,7 @@ import { SystemUser } from '../System/models/SystemUser';
|
||||
@ApiTags('Auth')
|
||||
@ApiExcludeController()
|
||||
@PublicRoute()
|
||||
@Throttle({ auth: {} })
|
||||
export class AuthController {
|
||||
constructor(
|
||||
private readonly authApp: AuthenticationApplication,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Controller, Post, Param, Get, Put } from '@nestjs/common';
|
||||
import { Controller, Post, Param, Get, Put, Body } from '@nestjs/common';
|
||||
import { GenerateApiKey } from './commands/GenerateApiKey.service';
|
||||
import { GetApiKeysService } from './queries/GetApiKeys.service';
|
||||
import {
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
ApiParam,
|
||||
ApiExtraModels,
|
||||
getSchemaPath,
|
||||
ApiBody,
|
||||
ApiProperty,
|
||||
} from '@nestjs/swagger';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
import {
|
||||
@@ -16,6 +18,20 @@ import {
|
||||
ApiKeyListResponseDto,
|
||||
ApiKeyListItemDto,
|
||||
} from './dtos/ApiKey.dto';
|
||||
import { IsString, MaxLength } from 'class-validator';
|
||||
import { IsOptional } from '@/common/decorators/Validators';
|
||||
|
||||
class GenerateApiKeyDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
@ApiProperty({
|
||||
description: 'Optional name for the API key',
|
||||
required: false,
|
||||
example: 'My API Key',
|
||||
})
|
||||
name?: string;
|
||||
}
|
||||
|
||||
@Controller('api-keys')
|
||||
@ApiTags('Api keys')
|
||||
@@ -29,17 +45,18 @@ export class AuthApiKeysController {
|
||||
constructor(
|
||||
private readonly getApiKeysService: GetApiKeysService,
|
||||
private readonly generateApiKeyService: GenerateApiKey,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
@Post('generate')
|
||||
@ApiOperation({ summary: 'Generate a new API key' })
|
||||
@ApiBody({ type: GenerateApiKeyDto })
|
||||
@ApiResponse({
|
||||
status: 201,
|
||||
description: 'The generated API key',
|
||||
type: ApiKeyResponseDto,
|
||||
})
|
||||
async generate() {
|
||||
return this.generateApiKeyService.generate();
|
||||
async generate(@Body() body: GenerateApiKeyDto) {
|
||||
return this.generateApiKeyService.generate(body.name);
|
||||
}
|
||||
|
||||
@Put(':id/revoke')
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from '@nestjs/swagger';
|
||||
import { GetAuthenticatedAccount } from './queries/GetAuthedAccount.service';
|
||||
import { Controller, Get, Post } from '@nestjs/common';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { IgnoreTenantSeededRoute } from '../Tenancy/EnsureTenantIsSeeded.guards';
|
||||
import { IgnoreTenantInitializedRoute } from '../Tenancy/EnsureTenantIsInitialized.guard';
|
||||
import { AuthenticationApplication } from './AuthApplication.sevice';
|
||||
@@ -18,11 +19,12 @@ import { IgnoreUserVerifiedRoute } from './guards/EnsureUserVerified.guard';
|
||||
@IgnoreTenantSeededRoute()
|
||||
@IgnoreTenantInitializedRoute()
|
||||
@IgnoreUserVerifiedRoute()
|
||||
@Throttle({ auth: {} })
|
||||
export class AuthedController {
|
||||
constructor(
|
||||
private readonly getAuthedAccountService: GetAuthenticatedAccount,
|
||||
private readonly authApp: AuthenticationApplication,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
@Post('/signup/verify/resend')
|
||||
@ApiOperation({ summary: 'Resend the signup confirmation message' })
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import { defaultTo } from 'ramda';
|
||||
import { ERRORS } from '../Auth.constants';
|
||||
import { hashPassword } from '../Auth.utils';
|
||||
import { ClsService } from 'nestjs-cls';
|
||||
|
||||
@Injectable()
|
||||
export class AuthSignupService {
|
||||
@@ -29,6 +30,7 @@ export class AuthSignupService {
|
||||
private readonly configService: ConfigService,
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
private readonly tenantsManager: TenantsManagerService,
|
||||
private readonly clsService: ClsService,
|
||||
|
||||
@Inject(SystemUser.name)
|
||||
private readonly systemUserModel: typeof SystemUser,
|
||||
@@ -70,6 +72,11 @@ export class AuthSignupService {
|
||||
tenantId: tenant.id,
|
||||
inviteAcceptedAt,
|
||||
});
|
||||
// Set the user in the cls service.
|
||||
this.clsService.set('tenantId', user.tenantId);
|
||||
this.clsService.set('userId', user.id);
|
||||
this.clsService.set('organizationId', tenant.organizationId);
|
||||
|
||||
// Triggers signed up event.
|
||||
await this.eventEmitter.emitAsync(events.auth.signUp, {
|
||||
signupDTO,
|
||||
|
||||
@@ -10,14 +10,15 @@ export class GenerateApiKey {
|
||||
private readonly tenancyContext: TenancyContext,
|
||||
@Inject(ApiKeyModel.name)
|
||||
private readonly apiKeyModel: typeof ApiKeyModel,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Generates a new secure API key for the current tenant and system user.
|
||||
* The key is saved in the database and returned (only the key and id for security).
|
||||
* @param {string} name - Optional name for the API key.
|
||||
* @returns {Promise<{ key: string; id: number }>} The generated API key and its database id.
|
||||
*/
|
||||
async generate() {
|
||||
async generate(name?: string) {
|
||||
const tenant = await this.tenancyContext.getTenant();
|
||||
const user = await this.tenancyContext.getSystemUser();
|
||||
|
||||
@@ -26,6 +27,7 @@ export class GenerateApiKey {
|
||||
// Save the API key to the database
|
||||
const apiKeyRecord = await this.apiKeyModel.query().insert({
|
||||
key,
|
||||
name,
|
||||
tenantId: tenant.id,
|
||||
userId: user.id,
|
||||
createdAt: new Date(),
|
||||
|
||||
@@ -29,6 +29,12 @@ export class ApiKeyListItemDto {
|
||||
@ApiProperty({ example: 'My API Key', description: 'API key name' })
|
||||
name?: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: 'bc_1234...',
|
||||
description: 'First 8 characters of the API key token',
|
||||
})
|
||||
token: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: '2024-01-01T00:00:00.000Z',
|
||||
description: 'Creation date',
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { Transformer } from '@/modules/Transformer/Transformer';
|
||||
|
||||
export class GetApiKeysTransformer extends Transformer {
|
||||
|
||||
public includeAttributes = (): string[] => {
|
||||
return ['token'];
|
||||
};
|
||||
|
||||
public excludeAttributes = (): string[] => {
|
||||
return ['tenantId'];
|
||||
};
|
||||
|
||||
public token(apiKey) {
|
||||
return apiKey.key ? `${apiKey.key.substring(0, 8)}...` : '';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import { Injectable } from '@nestjs/common';
|
||||
import { GetBillsService } from './queries/GetBills.service';
|
||||
import { CreateBillDto, EditBillDto } from './dtos/Bill.dto';
|
||||
import { GetBillPaymentTransactionsService } from './queries/GetBillPayments';
|
||||
import { BulkDeleteBillsService } from './BulkDeleteBills.service';
|
||||
import { ValidateBulkDeleteBillsService } from './ValidateBulkDeleteBills.service';
|
||||
// import { GetBillPayments } from './queries/GetBillPayments';
|
||||
// import { GetBills } from './queries/GetBills';
|
||||
|
||||
@@ -23,7 +25,9 @@ export class BillsApplication {
|
||||
private openBillService: OpenBillService,
|
||||
private getBillsService: GetBillsService,
|
||||
private getBillPaymentTransactionsService: GetBillPaymentTransactionsService,
|
||||
) {}
|
||||
private bulkDeleteBillsService: BulkDeleteBillsService,
|
||||
private validateBulkDeleteBillsService: ValidateBulkDeleteBillsService,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Creates a new bill with associated GL entries.
|
||||
@@ -53,6 +57,25 @@ export class BillsApplication {
|
||||
return this.deleteBillService.deleteBill(billId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes multiple bills.
|
||||
* @param {number[]} billIds
|
||||
*/
|
||||
public bulkDeleteBills(
|
||||
billIds: number[],
|
||||
options?: { skipUndeletable?: boolean },
|
||||
) {
|
||||
return this.bulkDeleteBillsService.bulkDeleteBills(billIds, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates which bills can be deleted.
|
||||
* @param {number[]} billIds
|
||||
*/
|
||||
public validateBulkDeleteBills(billIds: number[]) {
|
||||
return this.validateBulkDeleteBillsService.validateBulkDeleteBills(billIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve bills data table list.
|
||||
* @param {IBillsFilter} billsFilter -
|
||||
|
||||
@@ -22,14 +22,51 @@ import { CreateBillDto, EditBillDto } from './dtos/Bill.dto';
|
||||
import { BillResponseDto } from './dtos/BillResponse.dto';
|
||||
import { PaginatedResponseDto } from '@/common/dtos/PaginatedResults.dto';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
import {
|
||||
BulkDeleteDto,
|
||||
ValidateBulkDeleteResponseDto,
|
||||
} from '@/common/dtos/BulkDelete.dto';
|
||||
|
||||
@Controller('bills')
|
||||
@ApiTags('Bills')
|
||||
@ApiExtraModels(BillResponseDto)
|
||||
@ApiExtraModels(PaginatedResponseDto)
|
||||
@ApiCommonHeaders()
|
||||
@ApiExtraModels(ValidateBulkDeleteResponseDto)
|
||||
export class BillsController {
|
||||
constructor(private billsApplication: BillsApplication) {}
|
||||
constructor(private billsApplication: BillsApplication) { }
|
||||
|
||||
@Post('validate-bulk-delete')
|
||||
@ApiOperation({
|
||||
summary: 'Validate which bills can be deleted and return the results.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
'Validation completed with counts and IDs of deletable and non-deletable bills.',
|
||||
schema: {
|
||||
$ref: getSchemaPath(ValidateBulkDeleteResponseDto),
|
||||
},
|
||||
})
|
||||
validateBulkDeleteBills(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
): Promise<ValidateBulkDeleteResponseDto> {
|
||||
return this.billsApplication.validateBulkDeleteBills(bulkDeleteDto.ids);
|
||||
}
|
||||
|
||||
@Post('bulk-delete')
|
||||
@ApiOperation({ summary: 'Deletes multiple bills.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'Bills deleted successfully',
|
||||
})
|
||||
bulkDeleteBills(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
): Promise<void> {
|
||||
return this.billsApplication.bulkDeleteBills(bulkDeleteDto.ids, {
|
||||
skipUndeletable: bulkDeleteDto.skipUndeletable ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create a new bill.' })
|
||||
|
||||
@@ -29,6 +29,8 @@ import { InventoryCostModule } from '../InventoryCost/InventoryCost.module';
|
||||
import { BillsExportable } from './commands/BillsExportable';
|
||||
import { BillsImportable } from './commands/BillsImportable';
|
||||
import { GetBillPaymentTransactionsService } from './queries/GetBillPayments';
|
||||
import { BulkDeleteBillsService } from './BulkDeleteBills.service';
|
||||
import { ValidateBulkDeleteBillsService } from './ValidateBulkDeleteBills.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -63,8 +65,10 @@ import { GetBillPaymentTransactionsService } from './queries/GetBillPayments';
|
||||
BillsExportable,
|
||||
BillsImportable,
|
||||
GetBillPaymentTransactionsService,
|
||||
BulkDeleteBillsService,
|
||||
ValidateBulkDeleteBillsService,
|
||||
],
|
||||
controllers: [BillsController],
|
||||
exports: [BillsExportable, BillsImportable],
|
||||
})
|
||||
export class BillsModule {}
|
||||
export class BillsModule { }
|
||||
|
||||
36
packages/server/src/modules/Bills/BulkDeleteBills.service.ts
Normal file
36
packages/server/src/modules/Bills/BulkDeleteBills.service.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { PromisePool } from '@supercharge/promise-pool';
|
||||
import { castArray, uniq } from 'lodash';
|
||||
import { DeleteBill } from './commands/DeleteBill.service';
|
||||
|
||||
@Injectable()
|
||||
export class BulkDeleteBillsService {
|
||||
constructor(private readonly deleteBillService: DeleteBill) { }
|
||||
|
||||
async bulkDeleteBills(
|
||||
billIds: number | Array<number>,
|
||||
options?: { skipUndeletable?: boolean },
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
const { skipUndeletable = false } = options ?? {};
|
||||
const billsIds = uniq(castArray(billIds));
|
||||
|
||||
const results = await PromisePool.withConcurrency(1)
|
||||
.for(billsIds)
|
||||
.process(async (billId: number) => {
|
||||
try {
|
||||
await this.deleteBillService.deleteBill(billId);
|
||||
} catch (error) {
|
||||
if (!skipUndeletable) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!skipUndeletable && results.errors && results.errors.length > 0) {
|
||||
throw results.errors[0].raw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
|
||||
import { DeleteBill } from './commands/DeleteBill.service';
|
||||
|
||||
@Injectable()
|
||||
export class ValidateBulkDeleteBillsService {
|
||||
constructor(
|
||||
private readonly deleteBillService: DeleteBill,
|
||||
@Inject(TENANCY_DB_CONNECTION)
|
||||
private readonly tenantKnex: () => Knex,
|
||||
) { }
|
||||
|
||||
public async validateBulkDeleteBills(billIds: number[]): Promise<{
|
||||
deletableCount: number;
|
||||
nonDeletableCount: number;
|
||||
deletableIds: number[];
|
||||
nonDeletableIds: number[];
|
||||
}> {
|
||||
const trx = await this.tenantKnex().transaction({
|
||||
isolationLevel: 'read uncommitted',
|
||||
});
|
||||
|
||||
try {
|
||||
const deletableIds: number[] = [];
|
||||
const nonDeletableIds: number[] = [];
|
||||
|
||||
for (const billId of billIds) {
|
||||
try {
|
||||
await this.deleteBillService.deleteBill(billId, trx);
|
||||
deletableIds.push(billId);
|
||||
} catch (error) {
|
||||
nonDeletableIds.push(billId);
|
||||
}
|
||||
}
|
||||
|
||||
await trx.rollback();
|
||||
|
||||
return {
|
||||
deletableCount: deletableIds.length,
|
||||
nonDeletableCount: nonDeletableIds.length,
|
||||
deletableIds,
|
||||
nonDeletableIds,
|
||||
};
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,9 +29,10 @@ export class DeleteBill {
|
||||
/**
|
||||
* Deletes the bill with associated entries.
|
||||
* @param {number} billId
|
||||
* @param {Knex.Transaction} trx - Database transaction instance.
|
||||
* @return {void}
|
||||
*/
|
||||
public async deleteBill(billId: number) {
|
||||
public async deleteBill(billId: number, trx?: Knex.Transaction) {
|
||||
// Retrieve the given bill or throw not found error.
|
||||
const oldBill = await this.billModel()
|
||||
.query()
|
||||
@@ -75,6 +76,6 @@ export class DeleteBill {
|
||||
oldBill,
|
||||
trx,
|
||||
} as IBIllEventDeletedPayload);
|
||||
});
|
||||
}, trx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { PromisePool } from '@supercharge/promise-pool';
|
||||
import { castArray, uniq } from 'lodash';
|
||||
import { DeleteCreditNoteService } from './commands/DeleteCreditNote.service';
|
||||
|
||||
@Injectable()
|
||||
export class BulkDeleteCreditNotesService {
|
||||
constructor(
|
||||
private readonly deleteCreditNoteService: DeleteCreditNoteService,
|
||||
) { }
|
||||
|
||||
async bulkDeleteCreditNotes(
|
||||
creditNoteIds: number | Array<number>,
|
||||
options?: { skipUndeletable?: boolean },
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
const { skipUndeletable = false } = options ?? {};
|
||||
const notesIds = uniq(castArray(creditNoteIds));
|
||||
|
||||
const results = await PromisePool.withConcurrency(1)
|
||||
.for(notesIds)
|
||||
.process(async (creditNoteId: number) => {
|
||||
try {
|
||||
await this.deleteCreditNoteService.deleteCreditNote(creditNoteId);
|
||||
} catch (error) {
|
||||
if (!skipUndeletable) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!skipUndeletable && results.errors && results.errors.length > 0) {
|
||||
throw results.errors[0].raw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import { GetCreditNotesService } from './queries/GetCreditNotes.service';
|
||||
import { CreateCreditNoteDto, EditCreditNoteDto } from './dtos/CreditNote.dto';
|
||||
import { GetCreditNoteState } from './queries/GetCreditNoteState.service';
|
||||
import { GetCreditNoteService } from './queries/GetCreditNote.service';
|
||||
import { BulkDeleteCreditNotesService } from './BulkDeleteCreditNotes.service';
|
||||
import { ValidateBulkDeleteCreditNotesService } from './ValidateBulkDeleteCreditNotes.service';
|
||||
|
||||
@Injectable()
|
||||
export class CreditNoteApplication {
|
||||
@@ -20,8 +22,10 @@ export class CreditNoteApplication {
|
||||
private readonly getCreditNotePdfService: GetCreditNotePdf,
|
||||
private readonly getCreditNotesService: GetCreditNotesService,
|
||||
private readonly getCreditNoteStateService: GetCreditNoteState,
|
||||
private readonly getCreditNoteService: GetCreditNoteService
|
||||
) {}
|
||||
private readonly getCreditNoteService: GetCreditNoteService,
|
||||
private readonly bulkDeleteCreditNotesService: BulkDeleteCreditNotesService,
|
||||
private readonly validateBulkDeleteCreditNotesService: ValidateBulkDeleteCreditNotesService,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Creates a new credit note.
|
||||
@@ -97,4 +101,30 @@ export class CreditNoteApplication {
|
||||
getCreditNote(creditNoteId: number) {
|
||||
return this.getCreditNoteService.getCreditNote(creditNoteId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes multiple credit notes.
|
||||
* @param {number[]} creditNoteIds
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
bulkDeleteCreditNotes(
|
||||
creditNoteIds: number[],
|
||||
options?: { skipUndeletable?: boolean },
|
||||
) {
|
||||
return this.bulkDeleteCreditNotesService.bulkDeleteCreditNotes(
|
||||
creditNoteIds,
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates which credit notes can be deleted.
|
||||
* @param {number[]} creditNoteIds
|
||||
* @returns {Promise<{deletableCount: number, nonDeletableCount: number, deletableIds: number[], nonDeletableIds: number[]}>}
|
||||
*/
|
||||
validateBulkDeleteCreditNotes(creditNoteIds: number[]) {
|
||||
return this.validateBulkDeleteCreditNotesService.validateBulkDeleteCreditNotes(
|
||||
creditNoteIds,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Response } from 'express';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
@@ -11,10 +12,12 @@ import {
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Headers,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import { CreditNoteApplication } from './CreditNoteApplication.service';
|
||||
import { ICreditNotesQueryDTO } from './types/CreditNotes.types';
|
||||
@@ -22,17 +25,23 @@ import { CreateCreditNoteDto, EditCreditNoteDto } from './dtos/CreditNote.dto';
|
||||
import { CreditNoteResponseDto } from './dtos/CreditNoteResponse.dto';
|
||||
import { PaginatedResponseDto } from '@/common/dtos/PaginatedResults.dto';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
import {
|
||||
BulkDeleteDto,
|
||||
ValidateBulkDeleteResponseDto,
|
||||
} from '@/common/dtos/BulkDelete.dto';
|
||||
import { AcceptType } from '@/constants/accept-type';
|
||||
|
||||
@Controller('credit-notes')
|
||||
@ApiTags('Credit Notes')
|
||||
@ApiExtraModels(CreditNoteResponseDto)
|
||||
@ApiExtraModels(PaginatedResponseDto)
|
||||
@ApiExtraModels(ValidateBulkDeleteResponseDto)
|
||||
@ApiCommonHeaders()
|
||||
export class CreditNotesController {
|
||||
/**
|
||||
* @param {CreditNoteApplication} creditNoteApplication - The credit note application service.
|
||||
*/
|
||||
constructor(private creditNoteApplication: CreditNoteApplication) {}
|
||||
constructor(private creditNoteApplication: CreditNoteApplication) { }
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create a new credit note' })
|
||||
@@ -60,8 +69,26 @@ export class CreditNotesController {
|
||||
},
|
||||
})
|
||||
@ApiResponse({ status: 404, description: 'Credit note not found' })
|
||||
getCreditNote(@Param('id') creditNoteId: number) {
|
||||
return this.creditNoteApplication.getCreditNote(creditNoteId);
|
||||
async getCreditNote(
|
||||
@Param('id') creditNoteId: number,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
const [pdfContent, filename] =
|
||||
await this.creditNoteApplication.getCreditNotePdf(creditNoteId);
|
||||
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Length': pdfContent.length,
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
});
|
||||
res.status(200).send(pdfContent);
|
||||
} else {
|
||||
const creditNote =
|
||||
await this.creditNoteApplication.getCreditNote(creditNoteId);
|
||||
return creditNote;
|
||||
}
|
||||
}
|
||||
|
||||
@Get()
|
||||
@@ -112,6 +139,39 @@ export class CreditNotesController {
|
||||
return this.creditNoteApplication.openCreditNote(creditNoteId);
|
||||
}
|
||||
|
||||
@Post('validate-bulk-delete')
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Validates which credit notes can be deleted and returns the results.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
'Validation completed with counts and IDs of deletable and non-deletable credit notes.',
|
||||
schema: {
|
||||
$ref: getSchemaPath(ValidateBulkDeleteResponseDto),
|
||||
},
|
||||
})
|
||||
validateBulkDeleteCreditNotes(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
): Promise<ValidateBulkDeleteResponseDto> {
|
||||
return this.creditNoteApplication.validateBulkDeleteCreditNotes(
|
||||
bulkDeleteDto.ids,
|
||||
);
|
||||
}
|
||||
|
||||
@Post('bulk-delete')
|
||||
@ApiOperation({ summary: 'Deletes multiple credit notes.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'Credit notes deleted successfully',
|
||||
})
|
||||
bulkDeleteCreditNotes(@Body() bulkDeleteDto: BulkDeleteDto): Promise<void> {
|
||||
return this.creditNoteApplication.bulkDeleteCreditNotes(bulkDeleteDto.ids, {
|
||||
skipUndeletable: bulkDeleteDto.skipUndeletable ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@ApiOperation({ summary: 'Delete a credit note' })
|
||||
@ApiParam({ name: 'id', description: 'Credit note ID', type: 'number' })
|
||||
|
||||
@@ -29,10 +29,13 @@ import { CreditNotesImportable } from './commands/CreditNotesImportable';
|
||||
import { CreditNoteInventoryTransactionsSubscriber } from './subscribers/CreditNoteInventoryTransactionsSubscriber';
|
||||
import { RefundSyncCreditNoteBalanceSubscriber } from './subscribers/RefundSyncCreditNoteBalanceSubscriber';
|
||||
import { DeleteCustomerLinkedCreditSubscriber } from './subscribers/DeleteCustomerLinkedCreditSubscriber';
|
||||
import { CreditNoteAutoSerialSubscriber } from './subscribers/CreditNoteAutoSerialSubscriber';
|
||||
import { CreditNoteInventoryTransactions } from './commands/CreditNotesInventoryTransactions';
|
||||
import { InventoryCostModule } from '../InventoryCost/InventoryCost.module';
|
||||
import { CreditNoteRefundsModule } from '../CreditNoteRefunds/CreditNoteRefunds.module';
|
||||
import { CreditNotesApplyInvoiceModule } from '../CreditNotesApplyInvoice/CreditNotesApplyInvoice.module';
|
||||
import { BulkDeleteCreditNotesService } from './BulkDeleteCreditNotes.service';
|
||||
import { ValidateBulkDeleteCreditNotesService } from './ValidateBulkDeleteCreditNotes.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -71,6 +74,9 @@ import { CreditNotesApplyInvoiceModule } from '../CreditNotesApplyInvoice/Credit
|
||||
CreditNoteInventoryTransactionsSubscriber,
|
||||
RefundSyncCreditNoteBalanceSubscriber,
|
||||
DeleteCustomerLinkedCreditSubscriber,
|
||||
CreditNoteAutoSerialSubscriber,
|
||||
BulkDeleteCreditNotesService,
|
||||
ValidateBulkDeleteCreditNotesService,
|
||||
],
|
||||
exports: [
|
||||
CreateCreditNoteService,
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
|
||||
import { DeleteCreditNoteService } from './commands/DeleteCreditNote.service';
|
||||
|
||||
@Injectable()
|
||||
export class ValidateBulkDeleteCreditNotesService {
|
||||
constructor(
|
||||
private readonly deleteCreditNoteService: DeleteCreditNoteService,
|
||||
@Inject(TENANCY_DB_CONNECTION)
|
||||
private readonly tenantKnex: () => Knex,
|
||||
) { }
|
||||
|
||||
public async validateBulkDeleteCreditNotes(creditNoteIds: number[]): Promise<{
|
||||
deletableCount: number;
|
||||
nonDeletableCount: number;
|
||||
deletableIds: number[];
|
||||
nonDeletableIds: number[];
|
||||
}> {
|
||||
const trx = await this.tenantKnex().transaction({
|
||||
isolationLevel: 'read uncommitted',
|
||||
});
|
||||
|
||||
try {
|
||||
const deletableIds: number[] = [];
|
||||
const nonDeletableIds: number[] = [];
|
||||
|
||||
for (const creditNoteId of creditNoteIds) {
|
||||
try {
|
||||
await this.deleteCreditNoteService.deleteCreditNote(
|
||||
creditNoteId,
|
||||
trx,
|
||||
);
|
||||
deletableIds.push(creditNoteId);
|
||||
} catch (error) {
|
||||
nonDeletableIds.push(creditNoteId);
|
||||
}
|
||||
}
|
||||
|
||||
await trx.rollback();
|
||||
|
||||
return {
|
||||
deletableCount: deletableIds.length,
|
||||
nonDeletableCount: nonDeletableIds.length,
|
||||
deletableIds,
|
||||
nonDeletableIds,
|
||||
};
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,9 +49,13 @@ export class DeleteCreditNoteService {
|
||||
/**
|
||||
* Deletes the given credit note transactions.
|
||||
* @param {number} creditNoteId
|
||||
* @param {Knex.Transaction} trx - Database transaction instance.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public async deleteCreditNote(creditNoteId: number): Promise<void> {
|
||||
public async deleteCreditNote(
|
||||
creditNoteId: number,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
// Retrieve the credit note or throw not found service error.
|
||||
const oldCreditNote = await this.creditNoteModel()
|
||||
.query()
|
||||
@@ -88,7 +92,7 @@ export class DeleteCreditNoteService {
|
||||
creditNoteId,
|
||||
trx,
|
||||
} as ICreditNoteDeletedPayload);
|
||||
});
|
||||
}, trx);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,17 +5,17 @@ import { ICreditNoteCreatedPayload } from '../types/CreditNotes.types';
|
||||
import { events } from '@/common/events/events';
|
||||
|
||||
@Injectable()
|
||||
export default class CreditNoteAutoSerialSubscriber {
|
||||
export class CreditNoteAutoSerialSubscriber {
|
||||
constructor(
|
||||
private readonly creditNoteIncrementService: CreditNoteAutoIncrementService,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Auto serial increment once credit note created.
|
||||
* @param {ICreditNoteCreatedPayload} payload -
|
||||
*/
|
||||
@OnEvent(events.creditNote.onCreated)
|
||||
async autoSerialIncrementOnceCreated({}: ICreditNoteCreatedPayload) {
|
||||
async autoSerialIncrementOnceCreated({ }: ICreditNoteCreatedPayload) {
|
||||
await this.creditNoteIncrementService.incrementSerialNumber();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@ export const InitialCurrencies = [
|
||||
];
|
||||
|
||||
export const ERRORS = {
|
||||
CURRENCY_NOT_FOUND: 'currency_not_found',
|
||||
CURRENCY_CODE_EXISTS: 'currency_code_exists',
|
||||
CURRENCY_NOT_FOUND: 'CURRENCY_NOT_FOUND',
|
||||
CURRENCY_CODE_EXISTS: 'CURRENCY_CODE_EXISTS',
|
||||
BASE_CURRENCY_INVALID: 'BASE_CURRENCY_INVALID',
|
||||
CANNOT_DELETE_BASE_CURRENCY: 'CANNOT_DELETE_BASE_CURRENCY',
|
||||
};
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { castArray, uniq } from 'lodash';
|
||||
import { PromisePool } from '@supercharge/promise-pool';
|
||||
import { DeleteCustomer } from './commands/DeleteCustomer.service';
|
||||
|
||||
@Injectable()
|
||||
export class BulkDeleteCustomersService {
|
||||
constructor(private readonly deleteCustomerService: DeleteCustomer) {}
|
||||
|
||||
public async bulkDeleteCustomers(
|
||||
customerIds: number[],
|
||||
options?: { skipUndeletable?: boolean },
|
||||
): Promise<void> {
|
||||
const { skipUndeletable = false } = options ?? {};
|
||||
const ids = uniq(castArray(customerIds));
|
||||
|
||||
const results = await PromisePool.withConcurrency(1)
|
||||
.for(ids)
|
||||
.process(async (customerId: number) => {
|
||||
try {
|
||||
await this.deleteCustomerService.deleteCustomer(customerId);
|
||||
} catch (error) {
|
||||
if (!skipUndeletable) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!skipUndeletable && results.errors && results.errors.length > 0) {
|
||||
throw results.errors[0].raw ?? results.errors[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,10 @@ import { CreateCustomerDto } from './dtos/CreateCustomer.dto';
|
||||
import { EditCustomerDto } from './dtos/EditCustomer.dto';
|
||||
import { CustomerResponseDto } from './dtos/CustomerResponse.dto';
|
||||
import { GetCustomersQueryDto } from './dtos/GetCustomersQuery.dto';
|
||||
import {
|
||||
BulkDeleteCustomersDto,
|
||||
ValidateBulkDeleteCustomersResponseDto,
|
||||
} from './dtos/BulkDeleteCustomers.dto';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
|
||||
@Controller('customers')
|
||||
@@ -31,7 +35,7 @@ import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
@ApiExtraModels(CustomerResponseDto)
|
||||
@ApiCommonHeaders()
|
||||
export class CustomersController {
|
||||
constructor(private customersApplication: CustomersApplication) {}
|
||||
constructor(private customersApplication: CustomersApplication) { }
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'Retrieves the customer details.' })
|
||||
@@ -109,4 +113,37 @@ export class CustomersController {
|
||||
openingBalanceDTO,
|
||||
);
|
||||
}
|
||||
|
||||
@Post('validate-bulk-delete')
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Validates which customers can be deleted and returns counts of deletable and non-deletable customers.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
'Validation completed. Returns counts and IDs of deletable and non-deletable customers.',
|
||||
schema: { $ref: getSchemaPath(ValidateBulkDeleteCustomersResponseDto) },
|
||||
})
|
||||
validateBulkDeleteCustomers(
|
||||
@Body() bulkDeleteDto: BulkDeleteCustomersDto,
|
||||
): Promise<ValidateBulkDeleteCustomersResponseDto> {
|
||||
return this.customersApplication.validateBulkDeleteCustomers(
|
||||
bulkDeleteDto.ids,
|
||||
);
|
||||
}
|
||||
|
||||
@Post('bulk-delete')
|
||||
@ApiOperation({ summary: 'Deletes multiple customers in bulk.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'The customers have been successfully deleted.',
|
||||
})
|
||||
async bulkDeleteCustomers(
|
||||
@Body() bulkDeleteDto: BulkDeleteCustomersDto,
|
||||
): Promise<void> {
|
||||
return this.customersApplication.bulkDeleteCustomers(bulkDeleteDto.ids, {
|
||||
skipUndeletable: bulkDeleteDto.skipUndeletable ?? false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ import { CustomersExportable } from './CustomersExportable';
|
||||
import { CustomersImportable } from './CustomersImportable';
|
||||
import { GetCustomers } from './queries/GetCustomers.service';
|
||||
import { DynamicListModule } from '../DynamicListing/DynamicList.module';
|
||||
import { BulkDeleteCustomersService } from './BulkDeleteCustomers.service';
|
||||
import { ValidateBulkDeleteCustomersService } from './ValidateBulkDeleteCustomers.service';
|
||||
|
||||
@Module({
|
||||
imports: [TenancyDatabaseModule, DynamicListModule],
|
||||
@@ -37,6 +39,8 @@ import { DynamicListModule } from '../DynamicListing/DynamicList.module';
|
||||
CustomersExportable,
|
||||
CustomersImportable,
|
||||
GetCustomers,
|
||||
BulkDeleteCustomersService,
|
||||
ValidateBulkDeleteCustomersService,
|
||||
],
|
||||
})
|
||||
export class CustomersModule {}
|
||||
|
||||
@@ -12,6 +12,8 @@ import { CreateCustomerDto } from './dtos/CreateCustomer.dto';
|
||||
import { EditCustomerDto } from './dtos/EditCustomer.dto';
|
||||
import { GetCustomers } from './queries/GetCustomers.service';
|
||||
import { GetCustomersQueryDto } from './dtos/GetCustomersQuery.dto';
|
||||
import { BulkDeleteCustomersService } from './BulkDeleteCustomers.service';
|
||||
import { ValidateBulkDeleteCustomersService } from './ValidateBulkDeleteCustomers.service';
|
||||
|
||||
@Injectable()
|
||||
export class CustomersApplication {
|
||||
@@ -22,6 +24,8 @@ export class CustomersApplication {
|
||||
private deleteCustomerService: DeleteCustomer,
|
||||
private editOpeningBalanceService: EditOpeningBalanceCustomer,
|
||||
private getCustomersService: GetCustomers,
|
||||
private readonly bulkDeleteCustomersService: BulkDeleteCustomersService,
|
||||
private readonly validateBulkDeleteCustomersService: ValidateBulkDeleteCustomersService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -83,4 +87,20 @@ export class CustomersApplication {
|
||||
public getCustomers = (filterDTO: GetCustomersQueryDto) => {
|
||||
return this.getCustomersService.getCustomersList(filterDTO);
|
||||
};
|
||||
|
||||
public bulkDeleteCustomers = (
|
||||
customerIds: number[],
|
||||
options?: { skipUndeletable?: boolean },
|
||||
) => {
|
||||
return this.bulkDeleteCustomersService.bulkDeleteCustomers(
|
||||
customerIds,
|
||||
options,
|
||||
);
|
||||
};
|
||||
|
||||
public validateBulkDeleteCustomers = (customerIds: number[]) => {
|
||||
return this.validateBulkDeleteCustomersService.validateBulkDeleteCustomers(
|
||||
customerIds,
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
|
||||
import { DeleteCustomer } from './commands/DeleteCustomer.service';
|
||||
import { ModelHasRelationsError } from '@/common/exceptions/ModelHasRelations.exception';
|
||||
import { ServiceError } from '@/modules/Items/ServiceError';
|
||||
|
||||
@Injectable()
|
||||
export class ValidateBulkDeleteCustomersService {
|
||||
constructor(
|
||||
private readonly deleteCustomerService: DeleteCustomer,
|
||||
@Inject(TENANCY_DB_CONNECTION)
|
||||
private readonly tenantKnex: () => Knex,
|
||||
) {}
|
||||
|
||||
public async validateBulkDeleteCustomers(customerIds: number[]): Promise<{
|
||||
deletableCount: number;
|
||||
nonDeletableCount: number;
|
||||
deletableIds: number[];
|
||||
nonDeletableIds: number[];
|
||||
}> {
|
||||
const trx = await this.tenantKnex().transaction({
|
||||
isolationLevel: 'read uncommitted',
|
||||
});
|
||||
|
||||
try {
|
||||
const deletableIds: number[] = [];
|
||||
const nonDeletableIds: number[] = [];
|
||||
|
||||
for (const customerId of customerIds) {
|
||||
try {
|
||||
await this.deleteCustomerService.deleteCustomer(customerId, trx);
|
||||
deletableIds.push(customerId);
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof ModelHasRelationsError ||
|
||||
(error instanceof ServiceError &&
|
||||
error.errorType === 'CUSTOMER_HAS_TRANSACTIONS')
|
||||
) {
|
||||
nonDeletableIds.push(customerId);
|
||||
} else {
|
||||
nonDeletableIds.push(customerId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await trx.rollback();
|
||||
|
||||
return {
|
||||
deletableCount: deletableIds.length,
|
||||
nonDeletableCount: nonDeletableIds.length,
|
||||
deletableIds,
|
||||
nonDeletableIds,
|
||||
};
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,12 +31,13 @@ export class DeleteCustomer {
|
||||
* @param {number} customerId - Customer ID.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async deleteCustomer(customerId: number): Promise<void> {
|
||||
public async deleteCustomer(
|
||||
customerId: number,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
// Retrieve the customer or throw not found service error.
|
||||
const oldCustomer = await this.customerModel()
|
||||
.query()
|
||||
.findById(customerId)
|
||||
.throwIfNotFound();
|
||||
const query = this.customerModel().query(trx);
|
||||
const oldCustomer = await query.findById(customerId).throwIfNotFound();
|
||||
|
||||
// Triggers `onCustomerDeleting` event.
|
||||
await this.eventPublisher.emitAsync(events.customers.onDeleting, {
|
||||
@@ -45,10 +46,10 @@ export class DeleteCustomer {
|
||||
} as ICustomerDeletingPayload);
|
||||
|
||||
// Deletes the customer and associated entities under UOW transaction.
|
||||
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
|
||||
return this.uow.withTransaction(async (transaction: Knex.Transaction) => {
|
||||
// Delete the customer from the storage.
|
||||
await this.customerModel()
|
||||
.query(trx)
|
||||
.query(transaction)
|
||||
.findById(customerId)
|
||||
.deleteIfNoRelations({
|
||||
type: ERRORS.CUSTOMER_HAS_TRANSACTIONS,
|
||||
@@ -58,8 +59,8 @@ export class DeleteCustomer {
|
||||
await this.eventPublisher.emitAsync(events.customers.onDeleted, {
|
||||
customerId,
|
||||
oldCustomer,
|
||||
trx,
|
||||
trx: transaction,
|
||||
} as ICustomerEventDeletedPayload);
|
||||
});
|
||||
}, trx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
ArrayNotEmpty,
|
||||
IsArray,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsBoolean,
|
||||
} from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Transform } from 'class-transformer';
|
||||
import { parseBoolean } from '@/utils/parse-boolean';
|
||||
|
||||
export class BulkDeleteCustomersDto {
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@IsInt({ each: true })
|
||||
@ApiProperty({
|
||||
description: 'Array of customer IDs to delete',
|
||||
type: [Number],
|
||||
example: [1, 2, 3],
|
||||
})
|
||||
ids: number[];
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Transform(({ value, obj }) => parseBoolean(value ?? obj?.skip_undeletable, false))
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
'When true, undeletable customers will be skipped and only deletable ones removed.',
|
||||
type: Boolean,
|
||||
default: false,
|
||||
})
|
||||
skipUndeletable?: boolean;
|
||||
}
|
||||
|
||||
export class ValidateBulkDeleteCustomersResponseDto {
|
||||
@ApiProperty({
|
||||
description: 'Number of customers that can be deleted',
|
||||
example: 2,
|
||||
})
|
||||
deletableCount: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Number of customers that cannot be deleted',
|
||||
example: 1,
|
||||
})
|
||||
nonDeletableCount: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'IDs of customers that can be deleted',
|
||||
type: [Number],
|
||||
example: [1, 2],
|
||||
})
|
||||
deletableIds: number[];
|
||||
|
||||
@ApiProperty({
|
||||
description: 'IDs of customers that cannot be deleted',
|
||||
type: [Number],
|
||||
example: [3],
|
||||
})
|
||||
nonDeletableIds: number[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { PromisePool } from '@supercharge/promise-pool';
|
||||
import { castArray, uniq } from 'lodash';
|
||||
import { DeleteExpense } from './commands/DeleteExpense.service';
|
||||
|
||||
@Injectable()
|
||||
export class BulkDeleteExpensesService {
|
||||
constructor(private readonly deleteExpenseService: DeleteExpense) { }
|
||||
|
||||
async bulkDeleteExpenses(
|
||||
expenseIds: number | Array<number>,
|
||||
options?: { skipUndeletable?: boolean },
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
const { skipUndeletable = false } = options ?? {};
|
||||
const expensesIds = uniq(castArray(expenseIds));
|
||||
|
||||
const results = await PromisePool.withConcurrency(1)
|
||||
.for(expensesIds)
|
||||
.process(async (expenseId: number) => {
|
||||
try {
|
||||
await this.deleteExpenseService.deleteExpense(expenseId);
|
||||
} catch (error) {
|
||||
if (!skipUndeletable) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!skipUndeletable && results.errors && results.errors.length > 0) {
|
||||
throw results.errors[0].raw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,13 +21,55 @@ import { CreateExpenseDto, EditExpenseDto } from './dtos/Expense.dto';
|
||||
import { PaginatedResponseDto } from '@/common/dtos/PaginatedResults.dto';
|
||||
import { ExpenseResponseDto } from './dtos/ExpenseResponse.dto';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
import {
|
||||
BulkDeleteDto,
|
||||
ValidateBulkDeleteResponseDto,
|
||||
} from '@/common/dtos/BulkDelete.dto';
|
||||
|
||||
@Controller('expenses')
|
||||
@ApiTags('Expenses')
|
||||
@ApiExtraModels(PaginatedResponseDto, ExpenseResponseDto)
|
||||
@ApiExtraModels(
|
||||
PaginatedResponseDto,
|
||||
ExpenseResponseDto,
|
||||
ValidateBulkDeleteResponseDto,
|
||||
)
|
||||
@ApiCommonHeaders()
|
||||
export class ExpensesController {
|
||||
constructor(private readonly expensesApplication: ExpensesApplication) {}
|
||||
constructor(private readonly expensesApplication: ExpensesApplication) { }
|
||||
|
||||
@Post('validate-bulk-delete')
|
||||
@ApiOperation({
|
||||
summary: 'Validate which expenses can be deleted and return the results.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
'Validation completed with counts and IDs of deletable and non-deletable expenses.',
|
||||
schema: {
|
||||
$ref: getSchemaPath(ValidateBulkDeleteResponseDto),
|
||||
},
|
||||
})
|
||||
public validateBulkDeleteExpenses(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
): Promise<ValidateBulkDeleteResponseDto> {
|
||||
return this.expensesApplication.validateBulkDeleteExpenses(
|
||||
bulkDeleteDto.ids,
|
||||
);
|
||||
}
|
||||
|
||||
@Post('bulk-delete')
|
||||
@ApiOperation({ summary: 'Deletes multiple expenses.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'Expenses deleted successfully',
|
||||
})
|
||||
public bulkDeleteExpenses(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
) {
|
||||
return this.expensesApplication.bulkDeleteExpenses(bulkDeleteDto.ids, {
|
||||
skipUndeletable: bulkDeleteDto.skipUndeletable ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new expense transaction.
|
||||
|
||||
@@ -19,6 +19,8 @@ import { GetExpensesService } from './queries/GetExpenses.service';
|
||||
import { DynamicListModule } from '../DynamicListing/DynamicList.module';
|
||||
import { ExpensesExportable } from './ExpensesExportable';
|
||||
import { ExpensesImportable } from './ExpensesImportable';
|
||||
import { BulkDeleteExpensesService } from './BulkDeleteExpenses.service';
|
||||
import { ValidateBulkDeleteExpensesService } from './ValidateBulkDeleteExpenses.service';
|
||||
|
||||
@Module({
|
||||
imports: [LedgerModule, BranchesModule, DynamicListModule],
|
||||
@@ -41,6 +43,8 @@ import { ExpensesImportable } from './ExpensesImportable';
|
||||
GetExpensesService,
|
||||
ExpensesExportable,
|
||||
ExpensesImportable,
|
||||
BulkDeleteExpensesService,
|
||||
ValidateBulkDeleteExpensesService,
|
||||
],
|
||||
})
|
||||
export class ExpensesModule {}
|
||||
|
||||
@@ -7,6 +7,8 @@ import { GetExpenseService } from './queries/GetExpense.service';
|
||||
import { IExpensesFilter } from './interfaces/Expenses.interface';
|
||||
import { GetExpensesService } from './queries/GetExpenses.service';
|
||||
import { CreateExpenseDto, EditExpenseDto } from './dtos/Expense.dto';
|
||||
import { BulkDeleteExpensesService } from './BulkDeleteExpenses.service';
|
||||
import { ValidateBulkDeleteExpensesService } from './ValidateBulkDeleteExpenses.service';
|
||||
|
||||
@Injectable()
|
||||
export class ExpensesApplication {
|
||||
@@ -17,7 +19,9 @@ export class ExpensesApplication {
|
||||
private readonly publishExpenseService: PublishExpense,
|
||||
private readonly getExpenseService: GetExpenseService,
|
||||
private readonly getExpensesService: GetExpensesService,
|
||||
) {}
|
||||
private readonly bulkDeleteExpensesService: BulkDeleteExpensesService,
|
||||
private readonly validateBulkDeleteExpensesService: ValidateBulkDeleteExpensesService,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Create a new expense transaction.
|
||||
@@ -47,6 +51,30 @@ export class ExpensesApplication {
|
||||
return this.deleteExpenseService.deleteExpense(expenseId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes expenses in bulk.
|
||||
* @param {number[]} expenseIds - Expense ids.
|
||||
*/
|
||||
public bulkDeleteExpenses(
|
||||
expenseIds: number[],
|
||||
options?: { skipUndeletable?: boolean },
|
||||
) {
|
||||
return this.bulkDeleteExpensesService.bulkDeleteExpenses(
|
||||
expenseIds,
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates which expenses can be deleted.
|
||||
* @param {number[]} expenseIds - Expense ids.
|
||||
*/
|
||||
public validateBulkDeleteExpenses(expenseIds: number[]) {
|
||||
return this.validateBulkDeleteExpensesService.validateBulkDeleteExpenses(
|
||||
expenseIds,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes the given expense.
|
||||
* @param {number} expenseId - Expense id.
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
|
||||
import { DeleteExpense } from './commands/DeleteExpense.service';
|
||||
|
||||
@Injectable()
|
||||
export class ValidateBulkDeleteExpensesService {
|
||||
constructor(
|
||||
private readonly deleteExpenseService: DeleteExpense,
|
||||
@Inject(TENANCY_DB_CONNECTION)
|
||||
private readonly tenantKnex: () => Knex,
|
||||
) { }
|
||||
|
||||
public async validateBulkDeleteExpenses(expenseIds: number[]): Promise<{
|
||||
deletableCount: number;
|
||||
nonDeletableCount: number;
|
||||
deletableIds: number[];
|
||||
nonDeletableIds: number[];
|
||||
}> {
|
||||
const trx = await this.tenantKnex().transaction({
|
||||
isolationLevel: 'read uncommitted',
|
||||
});
|
||||
|
||||
try {
|
||||
const deletableIds: number[] = [];
|
||||
const nonDeletableIds: number[] = [];
|
||||
|
||||
for (const expenseId of expenseIds) {
|
||||
try {
|
||||
await this.deleteExpenseService.deleteExpense(expenseId, trx);
|
||||
deletableIds.push(expenseId);
|
||||
} catch (error) {
|
||||
nonDeletableIds.push(expenseId);
|
||||
}
|
||||
}
|
||||
|
||||
await trx.rollback();
|
||||
|
||||
return {
|
||||
deletableCount: deletableIds.length,
|
||||
nonDeletableCount: nonDeletableIds.length,
|
||||
deletableIds,
|
||||
nonDeletableIds,
|
||||
};
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,9 +36,12 @@ export class DeleteExpense {
|
||||
/**
|
||||
* Deletes the given expense.
|
||||
* @param {number} expenseId
|
||||
* @param {ISystemUser} authorizedUser
|
||||
* @param {Knex.Transaction} trx - Database transaction instance.
|
||||
*/
|
||||
public async deleteExpense(expenseId: number): Promise<void> {
|
||||
public async deleteExpense(
|
||||
expenseId: number,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
// Retrieves the expense transaction with associated entries or
|
||||
// throw not found error.
|
||||
const oldExpense = await this.expenseModel()
|
||||
@@ -74,6 +77,6 @@ export class DeleteExpense {
|
||||
oldExpense,
|
||||
trx,
|
||||
} as IExpenseEventDeletePayload);
|
||||
});
|
||||
}, trx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { PromisePool } from '@supercharge/promise-pool';
|
||||
import { castArray, uniq } from 'lodash';
|
||||
import { DeleteItemCategoryService } from './commands/DeleteItemCategory.service';
|
||||
|
||||
@Injectable()
|
||||
export class BulkDeleteItemCategoriesService {
|
||||
constructor(
|
||||
private readonly deleteItemCategoryService: DeleteItemCategoryService,
|
||||
) { }
|
||||
|
||||
async bulkDeleteItemCategories(
|
||||
itemCategoryIds: number | Array<number>,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
const categoriesIds = uniq(castArray(itemCategoryIds));
|
||||
|
||||
const results = await PromisePool.withConcurrency(1)
|
||||
.for(categoriesIds)
|
||||
.process(async (itemCategoryId: number) => {
|
||||
await this.deleteItemCategoryService.deleteItemCategory(itemCategoryId);
|
||||
});
|
||||
|
||||
if (results.errors && results.errors.length > 0) {
|
||||
throw results.errors[0].raw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
|
||||
import { DeleteItemCategoryService } from './commands/DeleteItemCategory.service';
|
||||
|
||||
@Injectable()
|
||||
export class ValidateBulkDeleteItemCategoriesService {
|
||||
constructor(
|
||||
private readonly deleteItemCategoryService: DeleteItemCategoryService,
|
||||
@Inject(TENANCY_DB_CONNECTION)
|
||||
private readonly tenantKnex: () => Knex,
|
||||
) {}
|
||||
|
||||
public async validateBulkDeleteItemCategories(itemCategoryIds: number[]): Promise<{
|
||||
deletableCount: number;
|
||||
nonDeletableCount: number;
|
||||
deletableIds: number[];
|
||||
nonDeletableIds: number[];
|
||||
}> {
|
||||
const trx = await this.tenantKnex().transaction({
|
||||
isolationLevel: 'read uncommitted',
|
||||
});
|
||||
|
||||
try {
|
||||
const deletableIds: number[] = [];
|
||||
const nonDeletableIds: number[] = [];
|
||||
|
||||
for (const itemCategoryId of itemCategoryIds) {
|
||||
try {
|
||||
await this.deleteItemCategoryService.deleteItemCategory(
|
||||
itemCategoryId,
|
||||
trx,
|
||||
);
|
||||
deletableIds.push(itemCategoryId);
|
||||
} catch (error) {
|
||||
nonDeletableIds.push(itemCategoryId);
|
||||
}
|
||||
}
|
||||
|
||||
await trx.rollback();
|
||||
|
||||
return {
|
||||
deletableCount: deletableIds.length,
|
||||
nonDeletableCount: nonDeletableIds.length,
|
||||
deletableIds,
|
||||
nonDeletableIds,
|
||||
};
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,9 +32,13 @@ export class DeleteItemCategoryService {
|
||||
/**
|
||||
* Deletes the given item category.
|
||||
* @param {number} itemCategoryId - Item category id.
|
||||
* @param {Knex.Transaction} trx - Database transaction instance.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async deleteItemCategory(itemCategoryId: number) {
|
||||
public async deleteItemCategory(
|
||||
itemCategoryId: number,
|
||||
trx?: Knex.Transaction,
|
||||
) {
|
||||
// Retrieve item category or throw not found error.
|
||||
const oldItemCategory = await this.itemCategoryModel()
|
||||
.query()
|
||||
@@ -56,7 +60,7 @@ export class DeleteItemCategoryService {
|
||||
itemCategoryId,
|
||||
oldItemCategory,
|
||||
} as IItemCategoryDeletedPayload);
|
||||
});
|
||||
}, trx);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
41
packages/server/src/modules/Items/BulkDeleteItems.service.ts
Normal file
41
packages/server/src/modules/Items/BulkDeleteItems.service.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { PromisePool } from '@supercharge/promise-pool';
|
||||
import { castArray, uniq } from 'lodash';
|
||||
import { DeleteItemService } from './DeleteItem.service';
|
||||
|
||||
@Injectable()
|
||||
export class BulkDeleteItemsService {
|
||||
constructor(private readonly deleteItemService: DeleteItemService) {}
|
||||
|
||||
/**
|
||||
* Deletes multiple items.
|
||||
* @param {number | Array<number>} itemIds - The item id or ids.
|
||||
* @param {Knex.Transaction} trx - The transaction.
|
||||
*/
|
||||
async bulkDeleteItems(
|
||||
itemIds: number | Array<number>,
|
||||
options?: { skipUndeletable?: boolean },
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
const { skipUndeletable = false } = options ?? {};
|
||||
const itemsIds = uniq(castArray(itemIds));
|
||||
|
||||
const results = await PromisePool.withConcurrency(1)
|
||||
.for(itemsIds)
|
||||
.process(async (itemId: number) => {
|
||||
try {
|
||||
await this.deleteItemService.deleteItem(itemId, trx);
|
||||
} catch (error) {
|
||||
if (!skipUndeletable) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!skipUndeletable && results.errors && results.errors.length > 0) {
|
||||
throw results.errors[0].raw ?? results.errors[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,10 @@ import { ItemEstimatesResponseDto } from './dtos/ItemEstimatesResponse.dto';
|
||||
import { ItemBillsResponseDto } from './dtos/ItemBillsResponse.dto';
|
||||
import { ItemReceiptsResponseDto } from './dtos/ItemReceiptsResponse.dto';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
import {
|
||||
BulkDeleteItemsDto,
|
||||
ValidateBulkDeleteItemsResponseDto,
|
||||
} from './dtos/BulkDeleteItems.dto';
|
||||
|
||||
@Controller('/items')
|
||||
@ApiTags('Items')
|
||||
@@ -39,6 +43,7 @@ import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
@ApiExtraModels(ItemBillsResponseDto)
|
||||
@ApiExtraModels(ItemEstimatesResponseDto)
|
||||
@ApiExtraModels(ItemReceiptsResponseDto)
|
||||
@ApiExtraModels(ValidateBulkDeleteItemsResponseDto)
|
||||
@ApiCommonHeaders()
|
||||
export class ItemsController extends TenantController {
|
||||
constructor(private readonly itemsApplication: ItemsApplicationService) {
|
||||
@@ -340,4 +345,37 @@ export class ItemsController extends TenantController {
|
||||
const itemId = parseInt(id, 10);
|
||||
return this.itemsApplication.getItemReceiptsTransactions(itemId);
|
||||
}
|
||||
|
||||
@Post('validate-bulk-delete')
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Validates which items can be deleted and returns counts of deletable and non-deletable items.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
'Validation completed. Returns counts and IDs of deletable and non-deletable items.',
|
||||
schema: {
|
||||
$ref: getSchemaPath(ValidateBulkDeleteItemsResponseDto),
|
||||
},
|
||||
})
|
||||
async validateBulkDeleteItems(
|
||||
@Body() bulkDeleteDto: BulkDeleteItemsDto,
|
||||
): Promise<ValidateBulkDeleteItemsResponseDto> {
|
||||
return this.itemsApplication.validateBulkDeleteItems(bulkDeleteDto.ids);
|
||||
}
|
||||
|
||||
@Post('bulk-delete')
|
||||
@ApiOperation({ summary: 'Deletes multiple items in bulk.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'The items have been successfully deleted.',
|
||||
})
|
||||
async bulkDeleteItems(
|
||||
@Body() bulkDeleteDto: BulkDeleteItemsDto,
|
||||
): Promise<void> {
|
||||
return this.itemsApplication.bulkDeleteItems(bulkDeleteDto.ids, {
|
||||
skipUndeletable: bulkDeleteDto.skipUndeletable ?? false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ import { DynamicListModule } from '../DynamicListing/DynamicList.module';
|
||||
import { InventoryAdjustmentsModule } from '../InventoryAdjutments/InventoryAdjustments.module';
|
||||
import { ItemsExportable } from './ItemsExportable.service';
|
||||
import { ItemsImportable } from './ItemsImportable.service';
|
||||
import { BulkDeleteItemsService } from './BulkDeleteItems.service';
|
||||
import { ValidateBulkDeleteItemsService } from './ValidateBulkDeleteItems.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -41,8 +43,10 @@ import { ItemsImportable } from './ItemsImportable.service';
|
||||
TransformerInjectable,
|
||||
ItemsEntriesService,
|
||||
ItemsExportable,
|
||||
ItemsImportable
|
||||
ItemsImportable,
|
||||
BulkDeleteItemsService,
|
||||
ValidateBulkDeleteItemsService,
|
||||
],
|
||||
exports: [ItemsEntriesService, ItemsExportable, ItemsImportable],
|
||||
})
|
||||
export class ItemsModule {}
|
||||
export class ItemsModule { }
|
||||
|
||||
@@ -13,6 +13,8 @@ import { GetItemsService } from './GetItems.service';
|
||||
import { IItemsFilter } from './types/Items.types';
|
||||
import { EditItemDto, CreateItemDto } from './dtos/Item.dto';
|
||||
import { GetItemsQueryDto } from './dtos/GetItemsQuery.dto';
|
||||
import { BulkDeleteItemsService } from './BulkDeleteItems.service';
|
||||
import { ValidateBulkDeleteItemsService } from './ValidateBulkDeleteItems.service';
|
||||
|
||||
@Injectable()
|
||||
export class ItemsApplicationService {
|
||||
@@ -25,7 +27,9 @@ export class ItemsApplicationService {
|
||||
private readonly getItemService: GetItemService,
|
||||
private readonly getItemsService: GetItemsService,
|
||||
private readonly itemTransactionsService: ItemTransactionsService,
|
||||
) {}
|
||||
private readonly bulkDeleteItemsService: BulkDeleteItemsService,
|
||||
private readonly validateBulkDeleteItemsService: ValidateBulkDeleteItemsService,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Creates a new item.
|
||||
@@ -134,4 +138,30 @@ export class ItemsApplicationService {
|
||||
async getItemReceiptsTransactions(itemId: number): Promise<any> {
|
||||
return this.itemTransactionsService.getItemReceiptTransactions(itemId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates which items can be deleted in bulk.
|
||||
* @param {number[]} itemIds - Array of item IDs to validate
|
||||
* @returns {Promise<{deletableCount: number, nonDeletableCount: number, deletableIds: number[], nonDeletableIds: number[]}>}
|
||||
*/
|
||||
async validateBulkDeleteItems(itemIds: number[]): Promise<{
|
||||
deletableCount: number;
|
||||
nonDeletableCount: number;
|
||||
deletableIds: number[];
|
||||
nonDeletableIds: number[];
|
||||
}> {
|
||||
return this.validateBulkDeleteItemsService.validateBulkDeleteItems(itemIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes multiple items in bulk.
|
||||
* @param {number[]} itemIds - Array of item IDs to delete
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async bulkDeleteItems(
|
||||
itemIds: number[],
|
||||
options?: { skipUndeletable?: boolean },
|
||||
): Promise<void> {
|
||||
return this.bulkDeleteItemsService.bulkDeleteItems(itemIds, options);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
|
||||
import { DeleteItemService } from './DeleteItem.service';
|
||||
import { ModelHasRelationsError } from '@/common/exceptions/ModelHasRelations.exception';
|
||||
|
||||
@Injectable()
|
||||
export class ValidateBulkDeleteItemsService {
|
||||
constructor(
|
||||
private readonly deleteItemService: DeleteItemService,
|
||||
@Inject(TENANCY_DB_CONNECTION)
|
||||
private readonly tenantKnex: () => Knex,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Validates which items from the provided IDs can be deleted.
|
||||
* Uses the actual deleteItem service to validate, ensuring the same validation logic.
|
||||
* Uses a transaction that is always rolled back to ensure no database changes.
|
||||
* @param {number[]} itemIds - Array of item IDs to validate
|
||||
* @returns {Promise<{deletableCount: number, nonDeletableCount: number, deletableIds: number[], nonDeletableIds: number[]}>}
|
||||
*/
|
||||
public async validateBulkDeleteItems(itemIds: number[]): Promise<{
|
||||
deletableCount: number;
|
||||
nonDeletableCount: number;
|
||||
deletableIds: number[];
|
||||
nonDeletableIds: number[];
|
||||
}> {
|
||||
// Create a transaction that will be rolled back
|
||||
const trx = await this.tenantKnex().transaction({
|
||||
isolationLevel: 'read uncommitted',
|
||||
});
|
||||
|
||||
try {
|
||||
const deletableIds: number[] = [];
|
||||
const nonDeletableIds: number[] = [];
|
||||
|
||||
// Check each item to see if it can be deleted by attempting deletion in transaction
|
||||
for (const itemId of itemIds) {
|
||||
try {
|
||||
// Attempt to delete the item using the deleteItem service with the transaction
|
||||
// This will use the exact same validation logic as the actual delete
|
||||
await this.deleteItemService.deleteItem(itemId, trx);
|
||||
|
||||
// If deletion succeeds, item is deletable
|
||||
deletableIds.push(itemId);
|
||||
} catch (error) {
|
||||
// If error occurs, check the type of error
|
||||
if (error instanceof ModelHasRelationsError) {
|
||||
// Item has associated transactions/relations, cannot be deleted
|
||||
nonDeletableIds.push(itemId);
|
||||
} else {
|
||||
// Other errors (e.g., item not found), also mark as non-deletable
|
||||
nonDeletableIds.push(itemId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Always rollback the transaction to ensure no changes are persisted
|
||||
await trx.rollback();
|
||||
|
||||
return {
|
||||
deletableCount: deletableIds.length,
|
||||
nonDeletableCount: nonDeletableIds.length,
|
||||
deletableIds,
|
||||
nonDeletableIds,
|
||||
};
|
||||
} catch (error) {
|
||||
// Rollback in case of any error
|
||||
await trx.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
IsArray,
|
||||
IsInt,
|
||||
ArrayNotEmpty,
|
||||
IsOptional,
|
||||
IsBoolean,
|
||||
} from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Transform } from 'class-transformer';
|
||||
import { parseBoolean } from '@/utils/parse-boolean';
|
||||
|
||||
export class BulkDeleteItemsDto {
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@IsInt({ each: true })
|
||||
@ApiProperty({
|
||||
description: 'Array of item IDs to delete',
|
||||
type: [Number],
|
||||
example: [1, 2, 3],
|
||||
})
|
||||
ids: number[];
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Transform(({ value, obj }) => parseBoolean(value ?? obj?.skip_undeletable, false))
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
'When true, undeletable items will be skipped and only deletable ones removed.',
|
||||
type: Boolean,
|
||||
default: false,
|
||||
})
|
||||
skipUndeletable?: boolean;
|
||||
}
|
||||
|
||||
export class ValidateBulkDeleteItemsResponseDto {
|
||||
@ApiProperty({
|
||||
description: 'Number of items that can be deleted',
|
||||
example: 2,
|
||||
})
|
||||
deletableCount: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Number of items that cannot be deleted',
|
||||
example: 1,
|
||||
})
|
||||
nonDeletableCount: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'IDs of items that can be deleted',
|
||||
type: [Number],
|
||||
example: [1, 2],
|
||||
})
|
||||
deletableIds: number[];
|
||||
|
||||
@ApiProperty({
|
||||
description: 'IDs of items that cannot be deleted',
|
||||
type: [Number],
|
||||
example: [3],
|
||||
})
|
||||
nonDeletableIds: number[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { PromisePool } from '@supercharge/promise-pool';
|
||||
import { castArray, uniq } from 'lodash';
|
||||
import { DeleteManualJournalService } from './commands/DeleteManualJournal.service';
|
||||
|
||||
@Injectable()
|
||||
export class BulkDeleteManualJournalsService {
|
||||
constructor(
|
||||
private readonly deleteManualJournalService: DeleteManualJournalService,
|
||||
) { }
|
||||
|
||||
async bulkDeleteManualJournals(
|
||||
manualJournalIds: number | Array<number>,
|
||||
options?: { skipUndeletable?: boolean },
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
const { skipUndeletable = false } = options ?? {};
|
||||
const journalsIds = uniq(castArray(manualJournalIds));
|
||||
|
||||
const results = await PromisePool.withConcurrency(1)
|
||||
.for(journalsIds)
|
||||
.process(async (manualJournalId: number) => {
|
||||
try {
|
||||
await this.deleteManualJournalService.deleteManualJournal(
|
||||
manualJournalId,
|
||||
);
|
||||
} catch (error) {
|
||||
if (!skipUndeletable) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!skipUndeletable && results.errors && results.errors.length > 0) {
|
||||
throw results.errors[0].raw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,13 +25,54 @@ import {
|
||||
import { IManualJournalsFilter } from './types/ManualJournals.types';
|
||||
import { ManualJournalResponseDto } from './dtos/ManualJournalResponse.dto';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
import {
|
||||
BulkDeleteDto,
|
||||
ValidateBulkDeleteResponseDto,
|
||||
} from '@/common/dtos/BulkDelete.dto';
|
||||
|
||||
@Controller('manual-journals')
|
||||
@ApiTags('Manual Journals')
|
||||
@ApiExtraModels(ManualJournalResponseDto)
|
||||
@ApiExtraModels(ValidateBulkDeleteResponseDto)
|
||||
@ApiCommonHeaders()
|
||||
export class ManualJournalsController {
|
||||
constructor(private manualJournalsApplication: ManualJournalsApplication) {}
|
||||
constructor(private manualJournalsApplication: ManualJournalsApplication) { }
|
||||
|
||||
@Post('validate-bulk-delete')
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Validate which manual journals can be deleted and return the results.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
'Validation completed with counts and IDs of deletable and non-deletable manual journals.',
|
||||
schema: {
|
||||
$ref: getSchemaPath(ValidateBulkDeleteResponseDto),
|
||||
},
|
||||
})
|
||||
public validateBulkDeleteManualJournals(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
): Promise<ValidateBulkDeleteResponseDto> {
|
||||
return this.manualJournalsApplication.validateBulkDeleteManualJournals(
|
||||
bulkDeleteDto.ids,
|
||||
);
|
||||
}
|
||||
|
||||
@Post('bulk-delete')
|
||||
@ApiOperation({ summary: 'Deletes multiple manual journals.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'Manual journals deleted successfully',
|
||||
})
|
||||
public bulkDeleteManualJournals(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
): Promise<void> {
|
||||
return this.manualJournalsApplication.bulkDeleteManualJournals(
|
||||
bulkDeleteDto.ids,
|
||||
{ skipUndeletable: bulkDeleteDto.skipUndeletable ?? false },
|
||||
);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create a new manual journal.' })
|
||||
|
||||
@@ -19,6 +19,8 @@ import { ManualJournalsExportable } from './commands/ManualJournalExportable';
|
||||
import { ManualJournalImportable } from './commands/ManualJournalsImport';
|
||||
import { GetManualJournals } from './queries/GetManualJournals.service';
|
||||
import { DynamicListModule } from '../DynamicListing/DynamicList.module';
|
||||
import { BulkDeleteManualJournalsService } from './BulkDeleteManualJournals.service';
|
||||
import { ValidateBulkDeleteManualJournalsService } from './ValidateBulkDeleteManualJournals.service';
|
||||
|
||||
@Module({
|
||||
imports: [BranchesModule, LedgerModule, DynamicListModule],
|
||||
@@ -41,6 +43,8 @@ import { DynamicListModule } from '../DynamicListing/DynamicList.module';
|
||||
ManualJournalWriteGLSubscriber,
|
||||
ManualJournalsExportable,
|
||||
ManualJournalImportable,
|
||||
BulkDeleteManualJournalsService,
|
||||
ValidateBulkDeleteManualJournalsService,
|
||||
],
|
||||
exports: [ManualJournalsExportable, ManualJournalImportable],
|
||||
})
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
EditManualJournalDto,
|
||||
} from './dtos/ManualJournal.dto';
|
||||
import { GetManualJournals } from './queries/GetManualJournals.service';
|
||||
import { BulkDeleteManualJournalsService } from './BulkDeleteManualJournals.service';
|
||||
import { ValidateBulkDeleteManualJournalsService } from './ValidateBulkDeleteManualJournals.service';
|
||||
// import { GetManualJournals } from './queries/GetManualJournals';
|
||||
|
||||
@Injectable()
|
||||
@@ -21,7 +23,9 @@ export class ManualJournalsApplication {
|
||||
private publishManualJournalService: PublishManualJournal,
|
||||
private getManualJournalService: GetManualJournal,
|
||||
private getManualJournalsService: GetManualJournals,
|
||||
) {}
|
||||
private bulkDeleteManualJournalsService: BulkDeleteManualJournalsService,
|
||||
private validateBulkDeleteManualJournalsService: ValidateBulkDeleteManualJournalsService,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Make journal entries.
|
||||
@@ -57,6 +61,30 @@ export class ManualJournalsApplication {
|
||||
return this.deleteManualJournalService.deleteManualJournal(manualJournalId);
|
||||
};
|
||||
|
||||
/**
|
||||
* Bulk deletes manual journals.
|
||||
* @param {number[]} manualJournalIds
|
||||
*/
|
||||
public bulkDeleteManualJournals = (
|
||||
manualJournalIds: number[],
|
||||
options?: { skipUndeletable?: boolean },
|
||||
) => {
|
||||
return this.bulkDeleteManualJournalsService.bulkDeleteManualJournals(
|
||||
manualJournalIds,
|
||||
options,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Validates which manual journals can be deleted.
|
||||
* @param {number[]} manualJournalIds
|
||||
*/
|
||||
public validateBulkDeleteManualJournals = (manualJournalIds: number[]) => {
|
||||
return this.validateBulkDeleteManualJournalsService.validateBulkDeleteManualJournals(
|
||||
manualJournalIds,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Publish the given manual journal.
|
||||
* @param {number} manualJournalId - Manual journal id.
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
|
||||
import { DeleteManualJournalService } from './commands/DeleteManualJournal.service';
|
||||
|
||||
@Injectable()
|
||||
export class ValidateBulkDeleteManualJournalsService {
|
||||
constructor(
|
||||
private readonly deleteManualJournalService: DeleteManualJournalService,
|
||||
@Inject(TENANCY_DB_CONNECTION)
|
||||
private readonly tenantKnex: () => Knex,
|
||||
) {}
|
||||
|
||||
public async validateBulkDeleteManualJournals(
|
||||
manualJournalIds: number[],
|
||||
): Promise<{
|
||||
deletableCount: number;
|
||||
nonDeletableCount: number;
|
||||
deletableIds: number[];
|
||||
nonDeletableIds: number[];
|
||||
}> {
|
||||
const trx = await this.tenantKnex().transaction({
|
||||
isolationLevel: 'read uncommitted',
|
||||
});
|
||||
|
||||
try {
|
||||
const deletableIds: number[] = [];
|
||||
const nonDeletableIds: number[] = [];
|
||||
|
||||
for (const manualJournalId of manualJournalIds) {
|
||||
try {
|
||||
await this.deleteManualJournalService.deleteManualJournal(
|
||||
manualJournalId,
|
||||
trx,
|
||||
);
|
||||
deletableIds.push(manualJournalId);
|
||||
} catch (error) {
|
||||
nonDeletableIds.push(manualJournalId);
|
||||
}
|
||||
}
|
||||
|
||||
await trx.rollback();
|
||||
|
||||
return {
|
||||
deletableCount: deletableIds.length,
|
||||
nonDeletableCount: nonDeletableIds.length,
|
||||
deletableIds,
|
||||
nonDeletableIds,
|
||||
};
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,10 +29,12 @@ export class DeleteManualJournalService {
|
||||
/**
|
||||
* Deletes the given manual journal
|
||||
* @param {number} manualJournalId
|
||||
* @param {Knex.Transaction} trx - Database transaction instance.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public deleteManualJournal = async (
|
||||
manualJournalId: number,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<{
|
||||
oldManualJournal: ManualJournal;
|
||||
}> => {
|
||||
@@ -70,6 +72,6 @@ export class DeleteManualJournalService {
|
||||
} as IManualJournalEventDeletedPayload);
|
||||
|
||||
return { oldManualJournal };
|
||||
});
|
||||
}, trx);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Response } from 'express';
|
||||
import { Controller, Get, Param, Res } from '@nestjs/common';
|
||||
import { Controller, Get, Param, Post, Res } from '@nestjs/common';
|
||||
import { PaymentLinksApplication } from './PaymentLinksApplication';
|
||||
import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
@@ -40,7 +40,7 @@ export class PaymentLinksController {
|
||||
return { data };
|
||||
}
|
||||
|
||||
@Get('/:paymentLinkId/stripe_checkout_session')
|
||||
@Post('/:paymentLinkId/stripe_checkout_session')
|
||||
@ApiOperation({
|
||||
summary: 'Create Stripe checkout session',
|
||||
description:
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { PromisePool } from '@supercharge/promise-pool';
|
||||
import { castArray, uniq } from 'lodash';
|
||||
import { DeletePaymentReceivedService } from './commands/DeletePaymentReceived.service';
|
||||
|
||||
@Injectable()
|
||||
export class BulkDeletePaymentReceivedService {
|
||||
constructor(
|
||||
private readonly deletePaymentReceivedService: DeletePaymentReceivedService,
|
||||
) { }
|
||||
|
||||
async bulkDeletePaymentReceived(
|
||||
paymentReceiveIds: number | Array<number>,
|
||||
options?: { skipUndeletable?: boolean },
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
const { skipUndeletable = false } = options ?? {};
|
||||
const paymentsIds = uniq(castArray(paymentReceiveIds));
|
||||
|
||||
const results = await PromisePool.withConcurrency(1)
|
||||
.for(paymentsIds)
|
||||
.process(async (paymentReceiveId: number) => {
|
||||
try {
|
||||
await this.deletePaymentReceivedService.deletePaymentReceive(
|
||||
paymentReceiveId,
|
||||
);
|
||||
} catch (error) {
|
||||
if (!skipUndeletable) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!skipUndeletable && results.errors && results.errors.length > 0) {
|
||||
throw results.errors[0].raw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
} from './dtos/PaymentReceived.dto';
|
||||
import { PaymentsReceivedPagesService } from './queries/PaymentsReceivedPages.service';
|
||||
import { GetPaymentReceivedMailState } from './queries/GetPaymentReceivedMailState.service';
|
||||
import { BulkDeletePaymentReceivedService } from './BulkDeletePaymentReceived.service';
|
||||
import { ValidateBulkDeletePaymentReceivedService } from './ValidateBulkDeletePaymentReceived.service';
|
||||
|
||||
@Injectable()
|
||||
export class PaymentReceivesApplication {
|
||||
@@ -33,7 +35,9 @@ export class PaymentReceivesApplication {
|
||||
private getPaymentReceivePdfService: GetPaymentReceivedPdfService,
|
||||
private getPaymentReceivedStateService: GetPaymentReceivedStateService,
|
||||
private paymentsReceivedPagesService: PaymentsReceivedPagesService,
|
||||
) {}
|
||||
private bulkDeletePaymentReceivedService: BulkDeletePaymentReceivedService,
|
||||
private validateBulkDeletePaymentReceivedService: ValidateBulkDeletePaymentReceivedService,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Creates a new payment receive.
|
||||
@@ -73,6 +77,29 @@ export class PaymentReceivesApplication {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes multiple payment receives.
|
||||
* @param {number[]} paymentReceiveIds
|
||||
*/
|
||||
public bulkDeletePaymentReceives(
|
||||
paymentReceiveIds: number[],
|
||||
options?: { skipUndeletable?: boolean },
|
||||
) {
|
||||
return this.bulkDeletePaymentReceivedService.bulkDeletePaymentReceived(
|
||||
paymentReceiveIds,
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates which payment receives can be deleted.
|
||||
* @param {number[]} paymentReceiveIds
|
||||
*/
|
||||
public validateBulkDeletePaymentReceives(paymentReceiveIds: number[]) {
|
||||
return this.validateBulkDeletePaymentReceivedService
|
||||
.validateBulkDeletePaymentReceived(paymentReceiveIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve payment receives paginated and filterable.
|
||||
* @param {number} tenantId
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Response } from 'express';
|
||||
import {
|
||||
ApiExtraModels,
|
||||
ApiOperation,
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import { PaymentReceivesApplication } from './PaymentReceived.application';
|
||||
import {
|
||||
@@ -32,15 +34,20 @@ import { PaymentReceivedResponseDto } from './dtos/PaymentReceivedResponse.dto';
|
||||
import { PaginatedResponseDto } from '@/common/dtos/PaginatedResults.dto';
|
||||
import { PaymentReceivedStateResponseDto } from './dtos/PaymentReceivedStateResponse.dto';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
import {
|
||||
BulkDeleteDto,
|
||||
ValidateBulkDeleteResponseDto,
|
||||
} from '@/common/dtos/BulkDelete.dto';
|
||||
|
||||
@Controller('payments-received')
|
||||
@ApiTags('Payments Received')
|
||||
@ApiExtraModels(PaymentReceivedResponseDto)
|
||||
@ApiExtraModels(PaginatedResponseDto)
|
||||
@ApiExtraModels(PaymentReceivedStateResponseDto)
|
||||
@ApiExtraModels(ValidateBulkDeleteResponseDto)
|
||||
@ApiCommonHeaders()
|
||||
export class PaymentReceivesController {
|
||||
constructor(private paymentReceivesApplication: PaymentReceivesApplication) {}
|
||||
constructor(private paymentReceivesApplication: PaymentReceivesApplication) { }
|
||||
|
||||
@Post(':id/mail')
|
||||
@HttpCode(200)
|
||||
@@ -143,6 +150,42 @@ export class PaymentReceivesController {
|
||||
return this.paymentReceivesApplication.getPaymentsReceived(filterDTO);
|
||||
}
|
||||
|
||||
@Post('validate-bulk-delete')
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Validates which payments received can be deleted and returns the results.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
'Validation completed with counts and IDs of deletable and non-deletable payments received.',
|
||||
schema: {
|
||||
$ref: getSchemaPath(ValidateBulkDeleteResponseDto),
|
||||
},
|
||||
})
|
||||
public validateBulkDeletePaymentsReceived(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
): Promise<ValidateBulkDeleteResponseDto> {
|
||||
return this.paymentReceivesApplication.validateBulkDeletePaymentReceives(
|
||||
bulkDeleteDto.ids,
|
||||
);
|
||||
}
|
||||
|
||||
@Post('bulk-delete')
|
||||
@ApiOperation({ summary: 'Deletes multiple payments received.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'Payments received deleted successfully.',
|
||||
})
|
||||
public bulkDeletePaymentsReceived(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
) {
|
||||
return this.paymentReceivesApplication.bulkDeletePaymentReceives(
|
||||
bulkDeleteDto.ids,
|
||||
{ skipUndeletable: bulkDeleteDto.skipUndeletable ?? false },
|
||||
);
|
||||
}
|
||||
|
||||
@Get('state')
|
||||
@ApiOperation({ summary: 'Retrieves the payment received state.' })
|
||||
@ApiResponse({
|
||||
@@ -184,11 +227,18 @@ export class PaymentReceivesController {
|
||||
public async getPaymentReceive(
|
||||
@Param('id', ParseIntPipe) paymentReceiveId: number,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
return this.paymentReceivesApplication.getPaymentReceivePdf(
|
||||
const [pdfContent, filename] = await this.paymentReceivesApplication.getPaymentReceivePdf(
|
||||
paymentReceiveId,
|
||||
);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Length': pdfContent.length,
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
});
|
||||
res.send(pdfContent);
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationTextHtml)) {
|
||||
const htmlContent =
|
||||
await this.paymentReceivesApplication.getPaymentReceivedHtml(
|
||||
|
||||
@@ -39,6 +39,8 @@ import { PaymentsReceivedImportable } from './commands/PaymentsReceivedImportabl
|
||||
import { PaymentsReceivedPagesService } from './queries/PaymentsReceivedPages.service';
|
||||
import { GetPaymentReceivedMailTemplate } from './queries/GetPaymentReceivedMailTemplate.service';
|
||||
import { GetPaymentReceivedMailState } from './queries/GetPaymentReceivedMailState.service';
|
||||
import { BulkDeletePaymentReceivedService } from './BulkDeletePaymentReceived.service';
|
||||
import { ValidateBulkDeletePaymentReceivedService } from './ValidateBulkDeletePaymentReceived.service';
|
||||
|
||||
@Module({
|
||||
controllers: [PaymentReceivesController],
|
||||
@@ -68,7 +70,9 @@ import { GetPaymentReceivedMailState } from './queries/GetPaymentReceivedMailSta
|
||||
PaymentsReceivedImportable,
|
||||
PaymentsReceivedPagesService,
|
||||
GetPaymentReceivedMailTemplate,
|
||||
GetPaymentReceivedMailState
|
||||
GetPaymentReceivedMailState,
|
||||
BulkDeletePaymentReceivedService,
|
||||
ValidateBulkDeletePaymentReceivedService,
|
||||
],
|
||||
exports: [
|
||||
PaymentReceivesApplication,
|
||||
@@ -76,7 +80,7 @@ import { GetPaymentReceivedMailState } from './queries/GetPaymentReceivedMailSta
|
||||
PaymentReceivedGLEntries,
|
||||
PaymentsReceivedExportable,
|
||||
PaymentsReceivedImportable,
|
||||
PaymentReceivedValidators
|
||||
PaymentReceivedValidators,
|
||||
],
|
||||
imports: [
|
||||
ChromiumlyTenancyModule,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
|
||||
import { DeletePaymentReceivedService } from './commands/DeletePaymentReceived.service';
|
||||
|
||||
@Injectable()
|
||||
export class ValidateBulkDeletePaymentReceivedService {
|
||||
constructor(
|
||||
private readonly deletePaymentReceivedService: DeletePaymentReceivedService,
|
||||
@Inject(TENANCY_DB_CONNECTION)
|
||||
private readonly tenantKnex: () => Knex,
|
||||
) { }
|
||||
|
||||
public async validateBulkDeletePaymentReceived(
|
||||
paymentReceiveIds: number[],
|
||||
): Promise<{
|
||||
deletableCount: number;
|
||||
nonDeletableCount: number;
|
||||
deletableIds: number[];
|
||||
nonDeletableIds: number[];
|
||||
}> {
|
||||
const trx = await this.tenantKnex().transaction({
|
||||
isolationLevel: 'read uncommitted',
|
||||
});
|
||||
|
||||
try {
|
||||
const deletableIds: number[] = [];
|
||||
const nonDeletableIds: number[] = [];
|
||||
|
||||
for (const paymentReceiveId of paymentReceiveIds) {
|
||||
try {
|
||||
await this.deletePaymentReceivedService.deletePaymentReceive(
|
||||
paymentReceiveId,
|
||||
trx,
|
||||
);
|
||||
deletableIds.push(paymentReceiveId);
|
||||
} catch (error) {
|
||||
nonDeletableIds.push(paymentReceiveId);
|
||||
}
|
||||
}
|
||||
|
||||
await trx.rollback();
|
||||
|
||||
return {
|
||||
deletableCount: deletableIds.length,
|
||||
nonDeletableCount: nonDeletableIds.length,
|
||||
deletableIds,
|
||||
nonDeletableIds,
|
||||
};
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ export class DeletePaymentReceivedService {
|
||||
private paymentReceiveEntryModel: TenantModelProxy<
|
||||
typeof PaymentReceivedEntry
|
||||
>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Deletes the given payment receive with associated entries
|
||||
@@ -43,9 +43,12 @@ export class DeletePaymentReceivedService {
|
||||
* - Revert the payment amount of the associated invoices.
|
||||
* @async
|
||||
* @param {Integer} paymentReceiveId - Payment receive id.
|
||||
* @param {IPaymentReceived} paymentReceive - Payment receive object.
|
||||
* @param {Knex.Transaction} trx - Database transaction instance.
|
||||
*/
|
||||
public async deletePaymentReceive(paymentReceiveId: number) {
|
||||
public async deletePaymentReceive(
|
||||
paymentReceiveId: number,
|
||||
trx?: Knex.Transaction,
|
||||
) {
|
||||
// Retreive payment receive or throw not found service error.
|
||||
const oldPaymentReceive = await this.paymentReceiveModel()
|
||||
.query()
|
||||
@@ -79,6 +82,6 @@ export class DeletePaymentReceivedService {
|
||||
oldPaymentReceive,
|
||||
trx,
|
||||
} as IPaymentReceivedDeletedPayload);
|
||||
});
|
||||
}, trx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ export class GetPaymentMethodsStateService {
|
||||
private readonly paymentIntegrationModel: TenantModelProxy<
|
||||
typeof PaymentIntegration
|
||||
>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieves the payment state provising state.
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { PdfTemplateApplication } from './PdfTemplate.application';
|
||||
import { ICreateInvoicePdfTemplateDTO, IEditPdfTemplateDTO } from './types';
|
||||
@@ -77,7 +78,7 @@ export class PdfTemplatesController {
|
||||
status: 200,
|
||||
description: 'The PDF templates have been successfully retrieved.',
|
||||
})
|
||||
async getPdfTemplates(@Body('resource') resource: string) {
|
||||
async getPdfTemplates(@Query('resource') resource?: string) {
|
||||
return this.pdfTemplateApplication.getPdfTemplates({ resource });
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { PromisePool } from '@supercharge/promise-pool';
|
||||
import { castArray, uniq } from 'lodash';
|
||||
import { DeleteSaleEstimate } from './commands/DeleteSaleEstimate.service';
|
||||
|
||||
@Injectable()
|
||||
export class BulkDeleteSaleEstimatesService {
|
||||
constructor(private readonly deleteSaleEstimateService: DeleteSaleEstimate) { }
|
||||
|
||||
async bulkDeleteSaleEstimates(
|
||||
saleEstimateIds: number | Array<number>,
|
||||
options?: { skipUndeletable?: boolean },
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
const { skipUndeletable = false } = options ?? {};
|
||||
const estimatesIds = uniq(castArray(saleEstimateIds));
|
||||
|
||||
const results = await PromisePool.withConcurrency(1)
|
||||
.for(estimatesIds)
|
||||
.process(async (saleEstimateId: number) => {
|
||||
try {
|
||||
await this.deleteSaleEstimateService.deleteEstimate(saleEstimateId);
|
||||
} catch (error) {
|
||||
if (!skipUndeletable) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!skipUndeletable && results.errors && results.errors.length > 0) {
|
||||
throw results.errors[0].raw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
EditSaleEstimateDto,
|
||||
} from './dtos/SaleEstimate.dto';
|
||||
import { GetSaleEstimateMailStateService } from './queries/GetSaleEstimateMailState.service';
|
||||
import { BulkDeleteSaleEstimatesService } from './BulkDeleteSaleEstimates.service';
|
||||
import { ValidateBulkDeleteSaleEstimatesService } from './ValidateBulkDeleteSaleEstimates.service';
|
||||
|
||||
@Injectable()
|
||||
export class SaleEstimatesApplication {
|
||||
@@ -35,7 +37,9 @@ export class SaleEstimatesApplication {
|
||||
private readonly getSaleEstimateStateService: GetSaleEstimateState,
|
||||
private readonly saleEstimatesPdfService: GetSaleEstimatePdf,
|
||||
private readonly getSaleEstimateMailStateService: GetSaleEstimateMailStateService,
|
||||
) {}
|
||||
private readonly bulkDeleteSaleEstimatesService: BulkDeleteSaleEstimatesService,
|
||||
private readonly validateBulkDeleteSaleEstimatesService: ValidateBulkDeleteSaleEstimatesService,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Create a sale estimate.
|
||||
@@ -68,6 +72,31 @@ export class SaleEstimatesApplication {
|
||||
return this.deleteSaleEstimateService.deleteEstimate(estimateId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes multiple sale estimates.
|
||||
* @param {number[]} saleEstimateIds
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public bulkDeleteSaleEstimates(
|
||||
saleEstimateIds: number[],
|
||||
options?: { skipUndeletable?: boolean },
|
||||
) {
|
||||
return this.bulkDeleteSaleEstimatesService.bulkDeleteSaleEstimates(
|
||||
saleEstimateIds,
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates which sale estimates can be deleted.
|
||||
* @param {number[]} saleEstimateIds
|
||||
*/
|
||||
public validateBulkDeleteSaleEstimates(saleEstimateIds: number[]) {
|
||||
return this.validateBulkDeleteSaleEstimatesService.validateBulkDeleteSaleEstimates(
|
||||
saleEstimateIds,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the given sale estimate.
|
||||
* @param {number} estimateId - Sale estimate ID.
|
||||
|
||||
@@ -36,6 +36,10 @@ import { SaleEstimateResponseDto } from './dtos/SaleEstimateResponse.dto';
|
||||
import { PaginatedResponseDto } from '@/common/dtos/PaginatedResults.dto';
|
||||
import { SaleEstiamteStateResponseDto } from './dtos/SaleEstimateStateResponse.dto';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
import {
|
||||
BulkDeleteDto,
|
||||
ValidateBulkDeleteResponseDto,
|
||||
} from '@/common/dtos/BulkDelete.dto';
|
||||
|
||||
@Controller('sale-estimates')
|
||||
@ApiTags('Sale Estimates')
|
||||
@@ -43,13 +47,50 @@ import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
@ApiExtraModels(PaginatedResponseDto)
|
||||
@ApiExtraModels(SaleEstiamteStateResponseDto)
|
||||
@ApiCommonHeaders()
|
||||
@ApiExtraModels(ValidateBulkDeleteResponseDto)
|
||||
export class SaleEstimatesController {
|
||||
@Post('validate-bulk-delete')
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Validates which sale estimates can be deleted and returns the results.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
'Validation completed with counts and IDs of deletable and non-deletable sale estimates.',
|
||||
schema: {
|
||||
$ref: getSchemaPath(ValidateBulkDeleteResponseDto),
|
||||
},
|
||||
})
|
||||
public validateBulkDeleteSaleEstimates(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
): Promise<ValidateBulkDeleteResponseDto> {
|
||||
return this.saleEstimatesApplication.validateBulkDeleteSaleEstimates(
|
||||
bulkDeleteDto.ids,
|
||||
);
|
||||
}
|
||||
|
||||
@Post('bulk-delete')
|
||||
@ApiOperation({ summary: 'Deletes multiple sale estimates.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'Sale estimates deleted successfully',
|
||||
})
|
||||
public bulkDeleteSaleEstimates(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
): Promise<void> {
|
||||
return this.saleEstimatesApplication.bulkDeleteSaleEstimates(
|
||||
bulkDeleteDto.ids,
|
||||
{ skipUndeletable: bulkDeleteDto.skipUndeletable ?? false },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {SaleEstimatesApplication} saleEstimatesApplication - Sale estimates application.
|
||||
*/
|
||||
constructor(
|
||||
private readonly saleEstimatesApplication: SaleEstimatesApplication,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create a new sale estimate.' })
|
||||
@@ -277,7 +318,7 @@ export class SaleEstimatesController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent =
|
||||
const [pdfContent] =
|
||||
await this.saleEstimatesApplication.getSaleEstimatePdf(estimateId);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -39,6 +39,9 @@ import { SaleEstimatesExportable } from './SaleEstimatesExportable';
|
||||
import { SaleEstimatesImportable } from './SaleEstimatesImportable';
|
||||
import { GetSaleEstimateMailStateService } from './queries/GetSaleEstimateMailState.service';
|
||||
import { GetSaleEstimateMailTemplateService } from './queries/GetSaleEstimateMailTemplate.service';
|
||||
import { SaleEstimateAutoIncrementSubscriber } from './subscribers/SaleEstimateAutoIncrementSubscriber';
|
||||
import { BulkDeleteSaleEstimatesService } from './BulkDeleteSaleEstimates.service';
|
||||
import { ValidateBulkDeleteSaleEstimatesService } from './ValidateBulkDeleteSaleEstimates.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -82,13 +85,16 @@ import { GetSaleEstimateMailTemplateService } from './queries/GetSaleEstimateMai
|
||||
SaleEstimatesExportable,
|
||||
SaleEstimatesImportable,
|
||||
GetSaleEstimateMailStateService,
|
||||
GetSaleEstimateMailTemplateService
|
||||
GetSaleEstimateMailTemplateService,
|
||||
SaleEstimateAutoIncrementSubscriber,
|
||||
BulkDeleteSaleEstimatesService,
|
||||
ValidateBulkDeleteSaleEstimatesService,
|
||||
],
|
||||
exports: [
|
||||
SaleEstimatesExportable,
|
||||
SaleEstimatesImportable,
|
||||
GetSaleEstimateMailStateService,
|
||||
GetSaleEstimateMailTemplateService
|
||||
]
|
||||
GetSaleEstimateMailTemplateService,
|
||||
],
|
||||
})
|
||||
export class SaleEstimatesModule {}
|
||||
export class SaleEstimatesModule { }
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
|
||||
import { DeleteSaleEstimate } from './commands/DeleteSaleEstimate.service';
|
||||
|
||||
@Injectable()
|
||||
export class ValidateBulkDeleteSaleEstimatesService {
|
||||
constructor(
|
||||
private readonly deleteSaleEstimateService: DeleteSaleEstimate,
|
||||
@Inject(TENANCY_DB_CONNECTION)
|
||||
private readonly tenantKnex: () => Knex,
|
||||
) { }
|
||||
|
||||
public async validateBulkDeleteSaleEstimates(
|
||||
saleEstimateIds: number[],
|
||||
): Promise<{
|
||||
deletableCount: number;
|
||||
nonDeletableCount: number;
|
||||
deletableIds: number[];
|
||||
nonDeletableIds: number[];
|
||||
}> {
|
||||
const trx = await this.tenantKnex().transaction({
|
||||
isolationLevel: 'read uncommitted',
|
||||
});
|
||||
|
||||
try {
|
||||
const deletableIds: number[] = [];
|
||||
const nonDeletableIds: number[] = [];
|
||||
|
||||
for (const saleEstimateId of saleEstimateIds) {
|
||||
try {
|
||||
await this.deleteSaleEstimateService.deleteEstimate(
|
||||
saleEstimateId,
|
||||
trx,
|
||||
);
|
||||
deletableIds.push(saleEstimateId);
|
||||
} catch (error) {
|
||||
nonDeletableIds.push(saleEstimateId);
|
||||
}
|
||||
}
|
||||
|
||||
await trx.rollback();
|
||||
|
||||
return {
|
||||
deletableCount: deletableIds.length,
|
||||
nonDeletableCount: nonDeletableIds.length,
|
||||
deletableIds,
|
||||
nonDeletableIds,
|
||||
};
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,18 +24,22 @@ export class DeleteSaleEstimate {
|
||||
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Deletes the given estimate id with associated entries.
|
||||
* @async
|
||||
* @param {number} estimateId
|
||||
* @param {number} estimateId - Sale estimate id.
|
||||
* @param {Knex.Transaction} trx - Database transaction instance.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public async deleteEstimate(estimateId: number): Promise<void> {
|
||||
public async deleteEstimate(
|
||||
estimateId: number,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
// Retrieve sale estimate or throw not found service error.
|
||||
const oldSaleEstimate = await this.saleEstimateModel()
|
||||
.query()
|
||||
.query(trx)
|
||||
.findById(estimateId)
|
||||
.throwIfNotFound();
|
||||
|
||||
@@ -70,6 +74,6 @@ export class DeleteSaleEstimate {
|
||||
oldSaleEstimate,
|
||||
trx,
|
||||
} as ISaleEstimateDeletedPayload);
|
||||
});
|
||||
}, trx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ export class GetSaleEstimatePdf {
|
||||
|
||||
@Inject(SaleEstimate.name)
|
||||
private readonly saleEstimateModel: TenantModelProxy<typeof SaleEstimate>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieve sale estimate html content.
|
||||
@@ -50,9 +50,9 @@ export class GetSaleEstimatePdf {
|
||||
|
||||
// Retrieves the sale estimate html.
|
||||
const htmlContent = await this.saleEstimateHtml(saleEstimateId);
|
||||
|
||||
const content =
|
||||
const buffer =
|
||||
await this.chromiumlyTenancy.convertHtmlContent(htmlContent);
|
||||
|
||||
const eventPayload = { saleEstimateId };
|
||||
|
||||
// Triggers the `onSaleEstimatePdfViewed` event.
|
||||
@@ -60,7 +60,7 @@ export class GetSaleEstimatePdf {
|
||||
events.saleEstimate.onPdfViewed,
|
||||
eventPayload,
|
||||
);
|
||||
return [content, filename];
|
||||
return [buffer, filename];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { OnEvent } from '@nestjs/event-emitter';
|
||||
import { events } from '@/common/events/events';
|
||||
import { SaleEstimateIncrement } from '../commands/SaleEstimateIncrement.service';
|
||||
import { ISaleEstimateCreatedPayload } from '../types/SaleEstimates.types';
|
||||
|
||||
@Injectable()
|
||||
export class SaleEstimateAutoIncrementSubscriber {
|
||||
constructor(private readonly estimateIncrement: SaleEstimateIncrement) { }
|
||||
|
||||
/**
|
||||
* Handles increment next number of estimate once be created.
|
||||
* @param {ISaleEstimateCreatedPayload} payload -
|
||||
*/
|
||||
@OnEvent(events.saleEstimate.onCreated)
|
||||
private async handleEstimateNextNumberIncrement({ }: ISaleEstimateCreatedPayload) {
|
||||
await this.estimateIncrement.incrementNextEstimateNumber();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { PromisePool } from '@supercharge/promise-pool';
|
||||
import { castArray, uniq } from 'lodash';
|
||||
import { DeleteSaleInvoice } from './commands/DeleteSaleInvoice.service';
|
||||
|
||||
@Injectable()
|
||||
export class BulkDeleteSaleInvoicesService {
|
||||
constructor(private readonly deleteSaleInvoiceService: DeleteSaleInvoice) { }
|
||||
|
||||
async bulkDeleteSaleInvoices(
|
||||
saleInvoiceIds: number | Array<number>,
|
||||
options?: { skipUndeletable?: boolean },
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> {
|
||||
const { skipUndeletable = false } = options ?? {};
|
||||
const invoicesIds = uniq(castArray(saleInvoiceIds));
|
||||
|
||||
const results = await PromisePool.withConcurrency(1)
|
||||
.for(invoicesIds)
|
||||
.process(async (saleInvoiceId: number) => {
|
||||
try {
|
||||
await this.deleteSaleInvoiceService.deleteSaleInvoice(saleInvoiceId);
|
||||
} catch (error) {
|
||||
if (!skipUndeletable) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!skipUndeletable && results.errors && results.errors.length > 0) {
|
||||
throw results.errors[0].raw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,8 @@ import {
|
||||
EditSaleInvoiceDto,
|
||||
} from './dtos/SaleInvoice.dto';
|
||||
import { GenerateShareLink } from './commands/GenerateInvoicePaymentLink.service';
|
||||
import { BulkDeleteSaleInvoicesService } from './BulkDeleteSaleInvoices.service';
|
||||
import { ValidateBulkDeleteSaleInvoicesService } from './ValidateBulkDeleteSaleInvoices.service';
|
||||
|
||||
@Injectable()
|
||||
export class SaleInvoiceApplication {
|
||||
@@ -41,7 +43,9 @@ export class SaleInvoiceApplication {
|
||||
private sendSaleInvoiceMailService: SendSaleInvoiceMail,
|
||||
private getSaleInvoiceMailStateService: GetSaleInvoiceMailState,
|
||||
private generateShareLinkService: GenerateShareLink,
|
||||
) {}
|
||||
private bulkDeleteSaleInvoicesService: BulkDeleteSaleInvoicesService,
|
||||
private validateBulkDeleteSaleInvoicesService: ValidateBulkDeleteSaleInvoicesService,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Creates a new sale invoice with associated GL entries.
|
||||
@@ -78,6 +82,31 @@ export class SaleInvoiceApplication {
|
||||
return this.deleteSaleInvoiceService.deleteSaleInvoice(saleInvoiceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes multiple sale invoices.
|
||||
* @param {number[]} saleInvoiceIds
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
public bulkDeleteSaleInvoices(
|
||||
saleInvoiceIds: number[],
|
||||
options?: { skipUndeletable?: boolean },
|
||||
) {
|
||||
return this.bulkDeleteSaleInvoicesService.bulkDeleteSaleInvoices(
|
||||
saleInvoiceIds,
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates which sale invoices can be deleted.
|
||||
* @param {number[]} saleInvoiceIds
|
||||
*/
|
||||
public validateBulkDeleteSaleInvoices(saleInvoiceIds: number[]) {
|
||||
return this.validateBulkDeleteSaleInvoicesService.validateBulkDeleteSaleInvoices(
|
||||
saleInvoiceIds,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the given sale invoice details.
|
||||
* @param {ISalesInvoicesFilter} filterDTO
|
||||
|
||||
@@ -39,6 +39,10 @@ import { PaginatedResponseDto } from '@/common/dtos/PaginatedResults.dto';
|
||||
import { SaleInvoiceStateResponseDto } from './dtos/SaleInvoiceState.dto';
|
||||
import { GenerateSaleInvoiceSharableLinkResponseDto } from './dtos/GenerateSaleInvoiceSharableLinkResponse.dto';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
import {
|
||||
BulkDeleteDto,
|
||||
ValidateBulkDeleteResponseDto,
|
||||
} from '@/common/dtos/BulkDelete.dto';
|
||||
|
||||
@Controller('sale-invoices')
|
||||
@ApiTags('Sale Invoices')
|
||||
@@ -47,9 +51,44 @@ import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
@ApiExtraModels(SaleInvoiceStateResponseDto)
|
||||
@ApiExtraModels(GenerateSaleInvoiceSharableLinkResponseDto)
|
||||
@ApiCommonHeaders()
|
||||
@ApiExtraModels(ValidateBulkDeleteResponseDto)
|
||||
export class SaleInvoicesController {
|
||||
constructor(private saleInvoiceApplication: SaleInvoiceApplication) { }
|
||||
|
||||
@Post('validate-bulk-delete')
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Validates which sale invoices can be deleted and returns the results.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
'Validation completed with counts and IDs of deletable and non-deletable sale invoices.',
|
||||
schema: {
|
||||
$ref: getSchemaPath(ValidateBulkDeleteResponseDto),
|
||||
},
|
||||
})
|
||||
validateBulkDeleteSaleInvoices(
|
||||
@Body() bulkDeleteDto: BulkDeleteDto,
|
||||
): Promise<ValidateBulkDeleteResponseDto> {
|
||||
return this.saleInvoiceApplication.validateBulkDeleteSaleInvoices(
|
||||
bulkDeleteDto.ids,
|
||||
);
|
||||
}
|
||||
|
||||
@Post('bulk-delete')
|
||||
@ApiOperation({ summary: 'Deletes multiple sale invoices.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'Sale invoices deleted successfully',
|
||||
})
|
||||
bulkDeleteSaleInvoices(@Body() bulkDeleteDto: BulkDeleteDto): Promise<void> {
|
||||
return this.saleInvoiceApplication.bulkDeleteSaleInvoices(
|
||||
bulkDeleteDto.ids,
|
||||
{ skipUndeletable: bulkDeleteDto.skipUndeletable ?? false },
|
||||
);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create a new sale invoice.' })
|
||||
@ApiResponse({
|
||||
@@ -171,7 +210,8 @@ export class SaleInvoicesController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.saleInvoiceApplication.saleInvoicePdf(id);
|
||||
const [pdfContent, filename] =
|
||||
await this.saleInvoiceApplication.saleInvoicePdf(id);
|
||||
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
|
||||
@@ -52,6 +52,7 @@ import { InvoiceChangeStatusOnMailSentSubscriber } from './subscribers/InvoiceCh
|
||||
import { InvoiceCostGLEntriesSubscriber } from './subscribers/InvoiceCostGLEntriesSubscriber';
|
||||
import { InvoicePaymentGLRewriteSubscriber } from './subscribers/InvoicePaymentGLRewriteSubscriber';
|
||||
import { SaleInvoiceWriteInventoryTransactionsSubscriber } from './subscribers/InvoiceWriteInventoryTransactions';
|
||||
import { SaleInvoiceAutoIncrementSubscriber } from './subscribers/SaleInvoiceAutoIncrementSubscriber';
|
||||
import { SaleInvoiceCostGLEntries } from './SaleInvoiceCostGLEntries';
|
||||
import { InvoicePaymentsGLEntriesRewrite } from './InvoicePaymentsGLRewrite';
|
||||
import { PaymentsReceivedModule } from '../PaymentReceived/PaymentsReceived.module';
|
||||
@@ -59,6 +60,8 @@ import { SaleInvoicesCost } from './SalesInvoicesCost';
|
||||
import { SaleInvoicesExportable } from './commands/SaleInvoicesExportable';
|
||||
import { SaleInvoicesImportable } from './commands/SaleInvoicesImportable';
|
||||
import { PaymentLinksModule } from '../PaymentLinks/PaymentLinks.module';
|
||||
import { BulkDeleteSaleInvoicesService } from './BulkDeleteSaleInvoices.service';
|
||||
import { ValidateBulkDeleteSaleInvoicesService } from './ValidateBulkDeleteSaleInvoices.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -120,10 +123,13 @@ import { PaymentLinksModule } from '../PaymentLinks/PaymentLinks.module';
|
||||
InvoiceCostGLEntriesSubscriber,
|
||||
InvoicePaymentGLRewriteSubscriber,
|
||||
SaleInvoiceWriteInventoryTransactionsSubscriber,
|
||||
SaleInvoiceAutoIncrementSubscriber,
|
||||
InvoicePaymentsGLEntriesRewrite,
|
||||
SaleInvoicesCost,
|
||||
SaleInvoicesExportable,
|
||||
SaleInvoicesImportable,
|
||||
BulkDeleteSaleInvoicesService,
|
||||
ValidateBulkDeleteSaleInvoicesService,
|
||||
],
|
||||
exports: [
|
||||
GetSaleInvoice,
|
||||
@@ -133,4 +139,4 @@ import { PaymentLinksModule } from '../PaymentLinks/PaymentLinks.module';
|
||||
SaleInvoicesImportable,
|
||||
],
|
||||
})
|
||||
export class SaleInvoicesModule {}
|
||||
export class SaleInvoicesModule { }
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { TENANCY_DB_CONNECTION } from '../Tenancy/TenancyDB/TenancyDB.constants';
|
||||
import { DeleteSaleInvoice } from './commands/DeleteSaleInvoice.service';
|
||||
|
||||
@Injectable()
|
||||
export class ValidateBulkDeleteSaleInvoicesService {
|
||||
constructor(
|
||||
private readonly deleteSaleInvoiceService: DeleteSaleInvoice,
|
||||
@Inject(TENANCY_DB_CONNECTION)
|
||||
private readonly tenantKnex: () => Knex,
|
||||
) { }
|
||||
|
||||
public async validateBulkDeleteSaleInvoices(saleInvoiceIds: number[]): Promise<{
|
||||
deletableCount: number;
|
||||
nonDeletableCount: number;
|
||||
deletableIds: number[];
|
||||
nonDeletableIds: number[];
|
||||
}> {
|
||||
const trx = await this.tenantKnex().transaction({
|
||||
isolationLevel: 'read uncommitted',
|
||||
});
|
||||
|
||||
try {
|
||||
const deletableIds: number[] = [];
|
||||
const nonDeletableIds: number[] = [];
|
||||
|
||||
for (const saleInvoiceId of saleInvoiceIds) {
|
||||
try {
|
||||
await this.deleteSaleInvoiceService.deleteSaleInvoice(
|
||||
saleInvoiceId,
|
||||
trx,
|
||||
);
|
||||
deletableIds.push(saleInvoiceId);
|
||||
} catch (error) {
|
||||
nonDeletableIds.push(saleInvoiceId);
|
||||
}
|
||||
}
|
||||
|
||||
await trx.rollback();
|
||||
|
||||
return {
|
||||
deletableCount: deletableIds.length,
|
||||
nonDeletableCount: nonDeletableIds.length,
|
||||
deletableIds,
|
||||
nonDeletableIds,
|
||||
};
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user