Compare commits
47 Commits
bugs-bashi
...
v0.23.0-rc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e3cf6bf099 | ||
|
|
6da7e8185c | ||
|
|
785c49f2e6 | ||
|
|
d7331554ad | ||
|
|
78b1e9136a | ||
|
|
fea9bb5caa | ||
|
|
db5caa138a | ||
|
|
bf821885c0 | ||
|
|
5ce5d8b899 | ||
|
|
458093fca2 | ||
|
|
97e17848f8 | ||
|
|
3dfe884413 | ||
|
|
f26a59f0fb | ||
|
|
7ee161733f | ||
|
|
4efc0b3eb4 | ||
|
|
532aa07e7f | ||
|
|
abacb543c7 | ||
|
|
769eaebc76 | ||
|
|
e0fb345a48 | ||
|
|
c21301061f | ||
|
|
2bbc154f18 | ||
|
|
3c1273becb | ||
|
|
16f1d57279 | ||
|
|
8726b4b3b0 | ||
|
|
5ace03ea99 | ||
|
|
5b6c473780 | ||
|
|
2186828516 | ||
|
|
3f2ab6e8f0 | ||
|
|
f0fae7d148 | ||
|
|
e063597a80 | ||
|
|
9b3f6b22d1 | ||
|
|
0475ce136a | ||
|
|
987ad992a4 | ||
|
|
ee92c2815b | ||
|
|
5767f1f603 | ||
|
|
885d8014c2 | ||
|
|
3ffab896ed | ||
|
|
92a5086f1f | ||
|
|
1bf9038ddc | ||
|
|
2736b76ced | ||
|
|
9e921b074f | ||
|
|
0f377e19f3 | ||
|
|
5d872798ff | ||
|
|
0ef78a19fe | ||
|
|
70b0a4833c | ||
|
|
ead4fc9b97 | ||
|
|
a91a7c612f |
@@ -35,17 +35,10 @@ TENANT_DB_NAME_PERFIX=bigcapital_tenant_
|
||||
BASE_URL=http://example.com
|
||||
JWT_SECRET=b0JDZW56RnV6aEthb0RGPXVEcUI
|
||||
|
||||
# Jobs MongoDB
|
||||
MONGODB_DATABASE_URL=mongodb://localhost/bigcapital
|
||||
|
||||
# App proxy
|
||||
PUBLIC_PROXY_PORT=80
|
||||
PUBLIC_PROXY_SSL_PORT=443
|
||||
|
||||
# Agendash
|
||||
AGENDASH_AUTH_USER=agendash
|
||||
AGENDASH_AUTH_PASSWORD=123123
|
||||
|
||||
# Sign-up restrictions
|
||||
SIGNUP_DISABLED=false
|
||||
SIGNUP_ALLOWED_DOMAINS=
|
||||
|
||||
@@ -32,11 +32,9 @@ services:
|
||||
- '3000'
|
||||
links:
|
||||
- mysql
|
||||
- mongo
|
||||
- redis
|
||||
depends_on:
|
||||
- mysql
|
||||
- mongo
|
||||
- redis
|
||||
restart: on-failure
|
||||
networks:
|
||||
@@ -66,16 +64,9 @@ services:
|
||||
# Authentication
|
||||
- JWT_SECRET=${JWT_SECRET}
|
||||
|
||||
# MongoDB
|
||||
- MONGODB_DATABASE_URL=mongodb://mongo/bigcapital
|
||||
|
||||
# Application
|
||||
- BASE_URL=${BASE_URL}
|
||||
|
||||
# Agendash
|
||||
- AGENDASH_AUTH_USER=${AGENDASH_AUTH_USER}
|
||||
- AGENDASH_AUTH_PASSWORD=${AGENDASH_AUTH_PASSWORD}
|
||||
|
||||
# Sign-up restrictions
|
||||
- SIGNUP_DISABLED=${SIGNUP_DISABLED}
|
||||
- SIGNUP_ALLOWED_DOMAINS=${SIGNUP_ALLOWED_DOMAINS}
|
||||
@@ -122,7 +113,7 @@ 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}
|
||||
@@ -166,17 +157,6 @@ services:
|
||||
networks:
|
||||
- bigcapital_network
|
||||
|
||||
mongo:
|
||||
container_name: bigcapital-mongo
|
||||
restart: on-failure
|
||||
build: ./docker/mongo
|
||||
expose:
|
||||
- '27017'
|
||||
volumes:
|
||||
- mongo:/var/lib/mongodb
|
||||
networks:
|
||||
- bigcapital_network
|
||||
|
||||
redis:
|
||||
container_name: bigcapital-redis
|
||||
restart: on-failure
|
||||
@@ -202,10 +182,6 @@ volumes:
|
||||
name: bigcapital_prod_mysql
|
||||
driver: local
|
||||
|
||||
mongo:
|
||||
name: bigcapital_prod_mongo
|
||||
driver: local
|
||||
|
||||
redis:
|
||||
name: bigcapital_prod_redis
|
||||
driver: local
|
||||
|
||||
@@ -24,25 +24,13 @@ services:
|
||||
restart_policy:
|
||||
condition: unless-stopped
|
||||
|
||||
mongo:
|
||||
build: ./docker/mongo
|
||||
expose:
|
||||
- '27017'
|
||||
volumes:
|
||||
- mongo:/var/lib/mongodb
|
||||
ports:
|
||||
- '27017:27017'
|
||||
deploy:
|
||||
restart_policy:
|
||||
condition: unless-stopped
|
||||
|
||||
redis:
|
||||
build:
|
||||
context: ./docker/redis
|
||||
expose:
|
||||
- "6379"
|
||||
- '6379'
|
||||
ports:
|
||||
- "6379:6379"
|
||||
- '6379:6379'
|
||||
volumes:
|
||||
- redis:/data
|
||||
deploy:
|
||||
@@ -52,7 +40,7 @@ services:
|
||||
gotenberg:
|
||||
image: gotenberg/gotenberg:7
|
||||
ports:
|
||||
- "9000:3000"
|
||||
- '9000:3000'
|
||||
|
||||
# Volumes
|
||||
volumes:
|
||||
@@ -60,10 +48,6 @@ volumes:
|
||||
name: bigcapital_dev_mysql
|
||||
driver: local
|
||||
|
||||
mongo:
|
||||
name: bigcapital_dev_mongo
|
||||
driver: local
|
||||
|
||||
redis:
|
||||
name: bigcapital_dev_redis
|
||||
driver: local
|
||||
driver: local
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
FROM mongo:5.0
|
||||
@@ -35,17 +35,10 @@ TENANT_DB_NAME_PERFIX=bigcapital_tenant_
|
||||
BASE_URL=http://example.com
|
||||
JWT_SECRET=b0JDZW56RnV6aEthb0RGPXVEcUI
|
||||
|
||||
# Jobs MongoDB
|
||||
MONGODB_DATABASE_URL=mongodb://localhost/bigcapital
|
||||
|
||||
# App proxy
|
||||
PUBLIC_PROXY_PORT=80
|
||||
PUBLIC_PROXY_SSL_PORT=443
|
||||
|
||||
# Agendash
|
||||
AGENDASH_AUTH_USER=agendash
|
||||
AGENDASH_AUTH_PASSWORD=123123
|
||||
|
||||
# Sign-up restrictions
|
||||
SIGNUP_DISABLED=false
|
||||
SIGNUP_ALLOWED_DOMAINS=
|
||||
|
||||
100
packages/server/Dockerfile
Normal file
100
packages/server/Dockerfile
Normal file
@@ -0,0 +1,100 @@
|
||||
FROM node:18.16.0-alpine as build
|
||||
|
||||
USER root
|
||||
|
||||
ARG MAIL_HOST= \
|
||||
MAIL_USERNAME= \
|
||||
MAIL_PASSWORD= \
|
||||
MAIL_PORT= \
|
||||
MAIL_SECURE= \
|
||||
MAIL_FROM_NAME= \
|
||||
MAIL_FROM_ADDRESS= \
|
||||
# Database
|
||||
DB_HOST= \
|
||||
DB_USER= \
|
||||
DB_PASSWORD= \
|
||||
DB_CHARSET= \
|
||||
# System database.
|
||||
SYSTEM_DB_NAME= \
|
||||
SYSTEM_DB_PASSWORD= \
|
||||
SYSTEM_DB_USER= \
|
||||
SYSTEM_DB_HOST= \
|
||||
SYSTEM_DB_CHARSET= \
|
||||
# Tenant databases.
|
||||
TENANT_DB_USER= \
|
||||
TENANT_DB_PASSWORD= \
|
||||
TENANT_DB_HOST= \
|
||||
TENANT_DB_NAME_PERFIX= \
|
||||
TENANT_DB_CHARSET= \
|
||||
# Authentication
|
||||
JWT_SECRET= \
|
||||
# Application
|
||||
BASE_URL= \
|
||||
# Sign-up restriction
|
||||
SIGNUP_DISABLED= \
|
||||
SIGNUP_ALLOWED_DOMAINS= \
|
||||
SIGNUP_ALLOWED_EMAILS=
|
||||
|
||||
ENV MAIL_HOST=$MAIL_HOST \
|
||||
MAIL_USERNAME=$MAIL_USERNAME \
|
||||
MAIL_PASSWORD=$MAIL_PASSWORD \
|
||||
MAIL_PORT=$MAIL_PORT \
|
||||
MAIL_SECURE=$MAIL_SECURE \
|
||||
MAIL_FROM_NAME=$MAIL_FROM_NAME \
|
||||
MAIL_FROM_ADDRESS=$MAIL_FROM_ADDRESS \
|
||||
# Database
|
||||
DB_HOST=$DB_HOST \
|
||||
DB_USER=$DB_USER \
|
||||
DB_PASSWORD=$DB_PASSWORD \
|
||||
DB_CHARSET=$DB_CHARSET \
|
||||
# System database.
|
||||
SYSTEM_DB_HOST=$SYSTEM_DB_HOST \
|
||||
SYSTEM_DB_USER=$SYSTEM_DB_USER \
|
||||
SYSTEM_DB_PASSWORD=$SYSTEM_DB_PASSWORD \
|
||||
SYSTEM_DB_NAME=$SYSTEM_DB_NAME \
|
||||
SYSTEM_DB_CHARSET=$SYSTEM_DB_CHARSET \
|
||||
# Tenant databases.
|
||||
TENANT_DB_NAME_PERFIX=$TENANT_DB_NAME_PERFIX \
|
||||
TENANT_DB_HOST=$TENANT_DB_HOST \
|
||||
TENANT_DB_PASSWORD=$TENANT_DB_PASSWORD \
|
||||
TENANT_DB_USER=$TENANT_DB_USER \
|
||||
TENANT_DB_CHARSET=$TENANT_DB_CHARSET \
|
||||
# Authentication
|
||||
JWT_SECRET=$JWT_SECRET \
|
||||
# Application
|
||||
BASE_URL=$BASE_URL \
|
||||
# Sign-up restriction
|
||||
SIGNUP_DISABLED=$SIGNUP_DISABLED \
|
||||
SIGNUP_ALLOWED_DOMAINS=$SIGNUP_ALLOWED_DOMAINS \
|
||||
SIGNUP_ALLOWED_EMAILS=$SIGNUP_ALLOWED_EMAILS
|
||||
|
||||
# New Relic config file.
|
||||
ENV NEW_RELIC_NO_CONFIG_FILE=true
|
||||
|
||||
# Create app directory.
|
||||
WORKDIR /app
|
||||
|
||||
RUN chown node:node /
|
||||
|
||||
# Install pnpm
|
||||
RUN npm install -g pnpm
|
||||
|
||||
# Copy application dependency manifests to the container image.
|
||||
COPY --chown=node:node ./ ./
|
||||
|
||||
# Install application dependencies
|
||||
RUN apk update
|
||||
RUN apk add python3 build-base chromium
|
||||
|
||||
# Set PYHTON env
|
||||
ENV PYTHON=/usr/bin/python3
|
||||
|
||||
# Install packages dependencies for production.
|
||||
RUN pnpm install
|
||||
|
||||
COPY --chown=node:node ./packages/server ./packages/server
|
||||
|
||||
# # Creates a "dist" folder with the production build
|
||||
RUN pnpm run build:server --skip-nx-cache
|
||||
|
||||
CMD [ "node", "./packages/server/build/index.js" ]
|
||||
@@ -5,15 +5,18 @@ import {
|
||||
NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
import { Observable, map } from 'rxjs';
|
||||
import { mapValues, mapValuesDeep } from '@/utils/deepdash';
|
||||
import { mapValuesDeep } from '@/utils/deepdash';
|
||||
|
||||
@Injectable()
|
||||
export class ToJsonInterceptor implements NestInterceptor {
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
|
||||
return next.handle().pipe(
|
||||
map((data) => {
|
||||
if (data === null || data === undefined) {
|
||||
return data;
|
||||
}
|
||||
return mapValuesDeep(data, (value) => {
|
||||
if (value && typeof value.toJSON === 'function') {
|
||||
if (value !== null && value !== undefined && typeof value.toJSON === 'function') {
|
||||
return value.toJSON();
|
||||
}
|
||||
return value;
|
||||
|
||||
@@ -22,6 +22,9 @@
|
||||
"field.status.unpaid": "Unpaid",
|
||||
"field.status.opened": "Opened",
|
||||
"field.status.draft": "Draft",
|
||||
"field.created_at": "Created At"
|
||||
"field.created_at": "Created At",
|
||||
"allocation_method": "Allocation Method",
|
||||
"allocation_method.quantity": "Quantity",
|
||||
"allocation_method.value": "Valuation"
|
||||
}
|
||||
|
||||
|
||||
5
packages/server/src/i18n/en/customer.json
Normal file
5
packages/server/src/i18n/en/customer.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"type.business": "Business",
|
||||
"type.individual": "Individual"
|
||||
}
|
||||
|
||||
@@ -4,10 +4,6 @@ import { ClsMiddleware } from 'nestjs-cls';
|
||||
import * as path from 'path';
|
||||
import './utils/moment-mysql';
|
||||
import { AppModule } from './modules/App/App.module';
|
||||
import { ServiceErrorFilter } from './common/filters/service-error.filter';
|
||||
import { ModelHasRelationsFilter } from './common/filters/model-has-relations.filter';
|
||||
import { ValidationPipe } from './common/pipes/ClassValidation.pipe';
|
||||
import { ToJsonInterceptor } from './common/interceptors/to-json.interceptor';
|
||||
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||
|
||||
global.__public_dirname = path.join(__dirname, '..', 'public');
|
||||
@@ -25,11 +21,6 @@ async function bootstrap() {
|
||||
// create and mount the middleware manually here
|
||||
app.use(new ClsMiddleware({}).use);
|
||||
|
||||
app.useGlobalInterceptors(new ToJsonInterceptor());
|
||||
|
||||
// use the validation pipe globally
|
||||
app.useGlobalPipes(new ValidationPipe());
|
||||
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('Bigcapital')
|
||||
.setDescription('Financial accounting software')
|
||||
@@ -39,9 +30,6 @@ async function bootstrap() {
|
||||
const documentFactory = () => SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('swagger', app, documentFactory);
|
||||
|
||||
app.useGlobalFilters(new ServiceErrorFilter());
|
||||
app.useGlobalFilters(new ModelHasRelationsFilter());
|
||||
|
||||
await app.listen(process.env.PORT ?? 3000);
|
||||
}
|
||||
bootstrap();
|
||||
|
||||
@@ -48,14 +48,30 @@ export class PaginationQueryBuilder<
|
||||
// No relations defined
|
||||
return this.delete();
|
||||
}
|
||||
|
||||
// Only check HasManyRelation and ManyToManyRelation relations, as BelongsToOneRelation are just
|
||||
// foreign key references and shouldn't prevent deletion. Only dependent records should block deletion.
|
||||
const dependentRelationNames = relationNames.filter((name) => {
|
||||
const relation = relationMappings[name];
|
||||
return relation && (
|
||||
relation.relation === Model.HasManyRelation ||
|
||||
relation.relation === Model.ManyToManyRelation
|
||||
);
|
||||
});
|
||||
|
||||
if (dependentRelationNames.length === 0) {
|
||||
// No dependent relations defined, safe to delete
|
||||
return this.delete();
|
||||
}
|
||||
|
||||
const recordQuery = this.clone();
|
||||
|
||||
relationNames.forEach((relationName: string) => {
|
||||
dependentRelationNames.forEach((relationName: string) => {
|
||||
recordQuery.withGraphFetched(relationName);
|
||||
});
|
||||
const record = await recordQuery;
|
||||
|
||||
const hasRelations = relationNames.some((name) => {
|
||||
const hasRelations = dependentRelationNames.some((name) => {
|
||||
const val = record[name];
|
||||
return Array.isArray(val) ? val.length > 0 : val != null;
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
Query,
|
||||
ParseIntPipe,
|
||||
Put,
|
||||
HttpCode,
|
||||
} from '@nestjs/common';
|
||||
import { AccountsApplication } from './AccountsApplication.service';
|
||||
import { CreateAccountDTO } from './CreateAccount.dto';
|
||||
@@ -43,6 +44,7 @@ export class AccountsController {
|
||||
constructor(private readonly accountsApplication: AccountsApplication) { }
|
||||
|
||||
@Post('validate-bulk-delete')
|
||||
@HttpCode(200)
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'Validates which accounts can be deleted and returns counts of deletable and non-deletable accounts.',
|
||||
@@ -64,6 +66,7 @@ export class AccountsController {
|
||||
}
|
||||
|
||||
@Post('bulk-delete')
|
||||
@HttpCode(200)
|
||||
@ApiOperation({ summary: 'Deletes multiple accounts in bulk.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
@@ -125,6 +128,7 @@ export class AccountsController {
|
||||
}
|
||||
|
||||
@Post(':id/activate')
|
||||
@HttpCode(200)
|
||||
@ApiOperation({ summary: 'Activate the given account.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
@@ -142,6 +146,7 @@ export class AccountsController {
|
||||
}
|
||||
|
||||
@Post(':id/inactivate')
|
||||
@HttpCode(200)
|
||||
@ApiOperation({ summary: 'Inactivate the given account.' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
|
||||
@@ -18,7 +18,7 @@ export class DeleteAccount {
|
||||
private eventEmitter: EventEmitter2,
|
||||
private uow: UnitOfWork,
|
||||
private validator: CommandAccountValidators,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Authorize account delete.
|
||||
@@ -57,7 +57,10 @@ export class DeleteAccount {
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> => {
|
||||
// Retrieve account or not found service error.
|
||||
const oldAccount = await this.accountModel().query().findById(accountId);
|
||||
const oldAccount = await this.accountModel()
|
||||
.query()
|
||||
.findById(accountId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Authorize before delete account.
|
||||
await this.authorize(accountId, oldAccount);
|
||||
|
||||
@@ -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_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
|
||||
import { APP_GUARD, APP_INTERCEPTOR, APP_PIPE, APP_FILTER } from '@nestjs/core';
|
||||
import { join } from 'path';
|
||||
import { ServeStaticModule } from '@nestjs/serve-static';
|
||||
import { RedisModule } from '@liaoliaots/nestjs-redis';
|
||||
@@ -36,6 +36,10 @@ import { PdfTemplatesModule } from '../PdfTemplate/PdfTemplates.module';
|
||||
import { BranchesModule } from '../Branches/Branches.module';
|
||||
import { WarehousesModule } from '../Warehouses/Warehouses.module';
|
||||
import { SerializeInterceptor } from '@/common/interceptors/serialize.interceptor';
|
||||
import { ToJsonInterceptor } from '@/common/interceptors/to-json.interceptor';
|
||||
import { ValidationPipe } from '@/common/pipes/ClassValidation.pipe';
|
||||
import { ServiceErrorFilter } from '@/common/filters/service-error.filter';
|
||||
import { ModelHasRelationsFilter } from '@/common/filters/model-has-relations.filter';
|
||||
import { ChromiumlyTenancyModule } from '../ChromiumlyTenancy/ChromiumlyTenancy.module';
|
||||
import { CustomersModule } from '../Customers/Customers.module';
|
||||
import { VendorsModule } from '../Vendors/Vendors.module';
|
||||
@@ -234,6 +238,10 @@ import { AppThrottleModule } from './AppThrottle.module';
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [
|
||||
{
|
||||
provide: APP_PIPE,
|
||||
useClass: ValidationPipe,
|
||||
},
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: ThrottlerGuard,
|
||||
@@ -242,6 +250,10 @@ import { AppThrottleModule } from './AppThrottle.module';
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: SerializeInterceptor,
|
||||
},
|
||||
{
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: ToJsonInterceptor,
|
||||
},
|
||||
{
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: UserIpInterceptor,
|
||||
@@ -250,6 +262,14 @@ import { AppThrottleModule } from './AppThrottle.module';
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: ExcludeNullInterceptor,
|
||||
},
|
||||
{
|
||||
provide: APP_FILTER,
|
||||
useClass: ServiceErrorFilter,
|
||||
},
|
||||
{
|
||||
provide: APP_FILTER,
|
||||
useClass: ModelHasRelationsFilter,
|
||||
},
|
||||
AppService,
|
||||
],
|
||||
})
|
||||
|
||||
@@ -9,6 +9,27 @@ import { ThrottlerStorageRedisService } from '@nest-lab/throttler-storage-redis'
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: (configService: ConfigService) => {
|
||||
// Use in-memory storage with very high limits for test environment
|
||||
const isTest = process.env.NODE_ENV === 'test' || process.env.JEST_WORKER_ID !== undefined;
|
||||
|
||||
if (isTest) {
|
||||
return {
|
||||
throttlers: [
|
||||
{
|
||||
name: 'default',
|
||||
ttl: 60000,
|
||||
limit: 1000000, // Effectively disable throttling in tests
|
||||
},
|
||||
{
|
||||
name: 'auth',
|
||||
ttl: 60000,
|
||||
limit: 1000000, // Effectively disable throttling in tests
|
||||
},
|
||||
],
|
||||
// No storage specified = uses in-memory storage
|
||||
};
|
||||
}
|
||||
|
||||
const host = configService.get<string>('redis.host') || 'localhost';
|
||||
const port = Number(configService.get<number>('redis.port') || 6379);
|
||||
const password = configService.get<string>('redis.password');
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
import { Controller, Get, Param, Post, Query } from '@nestjs/common';
|
||||
import { BankAccountsApplication } from './BankAccountsApplication.service';
|
||||
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { ICashflowAccountsFilter } from './types/BankAccounts.types';
|
||||
import { ApiOperation, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { BankAccountsQueryDto } from './dtos/BankAccountsQuery.dto';
|
||||
import { BankAccountResponseDto } from './dtos/BankAccountResponse.dto';
|
||||
|
||||
@Controller('banking/accounts')
|
||||
@ApiTags('Bank Accounts')
|
||||
export class BankAccountsController {
|
||||
constructor(private bankAccountsApplication: BankAccountsApplication) {}
|
||||
constructor(private bankAccountsApplication: BankAccountsApplication) { }
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Retrieve the bank accounts.' })
|
||||
getBankAccounts(@Query() filterDto: ICashflowAccountsFilter) {
|
||||
@ApiQuery({
|
||||
name: 'query',
|
||||
description: 'Query parameters for the bank accounts list.',
|
||||
type: BankAccountsQueryDto,
|
||||
required: false,
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'List of bank accounts retrieved successfully.',
|
||||
type: [BankAccountResponseDto],
|
||||
})
|
||||
getBankAccounts(@Query() filterDto: BankAccountsQueryDto) {
|
||||
return this.bankAccountsApplication.getBankAccounts(filterDto);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { PauseBankAccountFeeds } from './commands/PauseBankAccountFeeds.service'
|
||||
import { GetBankAccountsService } from './queries/GetBankAccounts';
|
||||
import { ICashflowAccountsFilter } from './types/BankAccounts.types';
|
||||
import { GetBankAccountSummary } from './queries/GetBankAccountSummary';
|
||||
import { BankAccountsQueryDto } from './dtos/BankAccountsQuery.dto';
|
||||
|
||||
@Injectable()
|
||||
export class BankAccountsApplication {
|
||||
@@ -16,13 +17,13 @@ export class BankAccountsApplication {
|
||||
private readonly refreshBankAccountService: RefreshBankAccountService,
|
||||
private readonly resumeBankAccountFeedsService: ResumeBankAccountFeedsService,
|
||||
private readonly pauseBankAccountFeedsService: PauseBankAccountFeeds,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieves the bank accounts.
|
||||
* @param {ICashflowAccountsFilter} filterDto -
|
||||
*/
|
||||
getBankAccounts(filterDto: ICashflowAccountsFilter) {
|
||||
getBankAccounts(filterDto: BankAccountsQueryDto) {
|
||||
return this.getBankAccountsService.getCashflowAccounts(filterDto);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
/**
|
||||
* Bank Account Response DTO
|
||||
* Based on AccountResponseDto but excludes fields that are filtered out by CashflowAccountTransformer:
|
||||
* - predefined
|
||||
* - index
|
||||
* - accountTypeLabel
|
||||
*/
|
||||
export class BankAccountResponseDto {
|
||||
@ApiProperty({
|
||||
description: 'The unique identifier of the account',
|
||||
example: 1,
|
||||
})
|
||||
id: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The name of the account',
|
||||
example: 'Cash Account',
|
||||
})
|
||||
name: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The slug of the account',
|
||||
example: 'cash-account',
|
||||
})
|
||||
slug: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The code of the account',
|
||||
example: '1001',
|
||||
})
|
||||
code: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The type of the account',
|
||||
example: 'bank',
|
||||
})
|
||||
accountType: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The parent account ID',
|
||||
example: null,
|
||||
})
|
||||
parentAccountId: number | null;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The currency code of the account',
|
||||
example: 'USD',
|
||||
})
|
||||
currencyCode: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Whether the account is active',
|
||||
example: true,
|
||||
})
|
||||
active: boolean;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The bank balance of the account',
|
||||
example: 5000.0,
|
||||
})
|
||||
bankBalance: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The formatted bank balance',
|
||||
example: '$5,000.00',
|
||||
})
|
||||
bankBalanceFormatted: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The last feeds update timestamp',
|
||||
example: '2024-03-20T10:30:00Z',
|
||||
})
|
||||
lastFeedsUpdatedAt: string | Date | null;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The formatted last feeds update timestamp',
|
||||
example: 'Mar 20, 2024 10:30 AM',
|
||||
})
|
||||
lastFeedsUpdatedAtFormatted: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The last feeds updated from now (relative time)',
|
||||
example: '2 hours ago',
|
||||
})
|
||||
lastFeedsUpdatedFromNow: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The amount of the account',
|
||||
example: 5000.0,
|
||||
})
|
||||
amount: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The formatted amount',
|
||||
example: '$5,000.00',
|
||||
})
|
||||
formattedAmount: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The Plaid item ID',
|
||||
example: 'plaid-item-123',
|
||||
})
|
||||
plaidItemId: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The Plaid account ID',
|
||||
example: 'plaid-account-456',
|
||||
})
|
||||
plaidAccountId: string | null;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Whether the feeds are active',
|
||||
example: true,
|
||||
})
|
||||
isFeedsActive: boolean;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Whether the account is syncing owner',
|
||||
example: true,
|
||||
})
|
||||
isSyncingOwner: boolean;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Whether the feeds are paused',
|
||||
example: false,
|
||||
})
|
||||
isFeedsPaused: boolean;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The account normal',
|
||||
example: 'debit',
|
||||
})
|
||||
accountNormal: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The formatted account normal',
|
||||
example: 'Debit',
|
||||
})
|
||||
accountNormalFormatted: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The flatten name with all dependant accounts names',
|
||||
example: 'Assets: Cash Account',
|
||||
})
|
||||
flattenName: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The account level in the hierarchy',
|
||||
example: 2,
|
||||
})
|
||||
accountLevel?: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The creation timestamp',
|
||||
example: '2024-03-20T10:00:00Z',
|
||||
})
|
||||
createdAt: Date;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The update timestamp',
|
||||
example: '2024-03-20T10:30:00Z',
|
||||
})
|
||||
updatedAt: Date;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Transform } from 'class-transformer';
|
||||
import { IsArray, IsBoolean, IsEnum, IsInt, IsOptional, IsString, Min } from 'class-validator';
|
||||
import { ToNumber } from '@/common/decorators/Validators';
|
||||
import { IFilterRole, ISortOrder } from '@/modules/DynamicListing/DynamicFilter/DynamicFilter.types';
|
||||
import { parseBoolean } from '@/utils/parse-boolean';
|
||||
|
||||
export class BankAccountsQueryDto {
|
||||
@ApiPropertyOptional({
|
||||
description: 'Custom view ID',
|
||||
type: Number,
|
||||
example: 1,
|
||||
})
|
||||
@IsOptional()
|
||||
@ToNumber()
|
||||
@IsInt()
|
||||
customViewId?: number;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Filter roles array',
|
||||
type: Array,
|
||||
isArray: true,
|
||||
})
|
||||
@IsArray()
|
||||
@IsOptional()
|
||||
filterRoles?: IFilterRole[];
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Column to sort by',
|
||||
type: String,
|
||||
example: 'created_at',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
columnSortBy?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Sort order',
|
||||
enum: ISortOrder,
|
||||
example: ISortOrder.DESC,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsEnum(ISortOrder)
|
||||
sortOrder?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Stringified filter roles',
|
||||
type: String,
|
||||
example: '{"fieldKey":"status","value":"active"}',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
stringifiedFilterRoles?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Search keyword',
|
||||
type: String,
|
||||
example: 'bank account',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
searchKeyword?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'View slug',
|
||||
type: String,
|
||||
example: 'active-accounts',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
viewSlug?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Page number',
|
||||
type: Number,
|
||||
example: 1,
|
||||
minimum: 1,
|
||||
})
|
||||
@IsOptional()
|
||||
@ToNumber()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
page?: number;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Page size',
|
||||
type: Number,
|
||||
example: 25,
|
||||
minimum: 1,
|
||||
})
|
||||
@IsOptional()
|
||||
@ToNumber()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
pageSize?: number;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Include inactive accounts',
|
||||
type: Boolean,
|
||||
example: false,
|
||||
default: false,
|
||||
})
|
||||
@IsOptional()
|
||||
@Transform(({ value }) => parseBoolean(value, false))
|
||||
@IsBoolean()
|
||||
inactiveMode?: boolean;
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
|
||||
import { ICashflowAccountsFilter } from '../types/BankAccounts.types';
|
||||
import { TransformerInjectable } from '@/modules/Transformer/TransformerInjectable.service';
|
||||
import { DynamicListService } from '@/modules/DynamicListing/DynamicList.service';
|
||||
import { BankAccountsQueryDto } from '../dtos/BankAccountsQuery.dto';
|
||||
import { IDynamicListFilter } from '@/modules/DynamicListing/DynamicFilter/DynamicFilter.types';
|
||||
|
||||
@Injectable()
|
||||
export class GetBankAccountsService {
|
||||
@@ -15,14 +17,14 @@ export class GetBankAccountsService {
|
||||
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: TenantModelProxy<typeof Account>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieve the cash flow accounts.
|
||||
* @param {ICashflowAccountsFilter} filterDTO - Filter DTO.
|
||||
* @returns {ICashflowAccount[]}
|
||||
*/
|
||||
public async getCashflowAccounts(filterDTO: ICashflowAccountsFilter) {
|
||||
public async getCashflowAccounts(filterDTO: BankAccountsQueryDto) {
|
||||
const _filterDto = {
|
||||
sortOrder: 'desc',
|
||||
columnSortBy: 'created_at',
|
||||
@@ -30,12 +32,14 @@ export class GetBankAccountsService {
|
||||
...filterDTO,
|
||||
};
|
||||
// Parsees accounts list filter DTO.
|
||||
const filter = this.dynamicListService.parseStringifiedFilter(_filterDto);
|
||||
const filter = this.dynamicListService.parseStringifiedFilter<BankAccountsQueryDto>(
|
||||
_filterDto,
|
||||
);
|
||||
|
||||
// Dynamic list service.
|
||||
const dynamicList = await this.dynamicListService.dynamicList(
|
||||
this.accountModel(),
|
||||
filter,
|
||||
filter as IDynamicListFilter,
|
||||
);
|
||||
// Retrieve accounts model based on the given query.
|
||||
const accounts = await this.accountModel()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Patch, Post, Query } from '@nestjs/common';
|
||||
import { BankingMatchingApplication } from './BankingMatchingApplication';
|
||||
import { GetMatchedTransactionsFilter } from './types';
|
||||
import { MatchBankTransactionDto } from './dtos/MatchBankTransaction.dto';
|
||||
@@ -34,7 +34,7 @@ export class BankingMatchingController {
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/unmatch/:uncategorizedTransactionId')
|
||||
@Patch('/unmatch/:uncategorizedTransactionId')
|
||||
@ApiOperation({ summary: 'Unmatch the given uncategorized transaction.' })
|
||||
async unmatchMatchedTransaction(
|
||||
@Param('uncategorizedTransactionId') uncategorizedTransactionId: number,
|
||||
|
||||
@@ -4,8 +4,8 @@ import {
|
||||
validateTransactionShouldBeExcluded,
|
||||
} from './utils';
|
||||
import {
|
||||
IBankTransactionExcludedEventPayload,
|
||||
IBankTransactionExcludingEventPayload,
|
||||
IBankTransactionUnexcludedEventPayload,
|
||||
IBankTransactionUnexcludingEventPayload,
|
||||
} from '../types/BankTransactionsExclude.types';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
@@ -24,7 +24,7 @@ export class UnexcludeBankTransactionService {
|
||||
private readonly uncategorizedBankTransactionModel: TenantModelProxy<
|
||||
typeof UncategorizedBankTransaction
|
||||
>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Marks the given bank transaction as excluded.
|
||||
@@ -50,7 +50,8 @@ export class UnexcludeBankTransactionService {
|
||||
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
|
||||
await this.eventEmitter.emitAsync(events.bankTransactions.onUnexcluding, {
|
||||
uncategorizedTransactionId,
|
||||
} as IBankTransactionExcludingEventPayload);
|
||||
trx,
|
||||
} as IBankTransactionUnexcludingEventPayload);
|
||||
|
||||
await this.uncategorizedBankTransactionModel()
|
||||
.query(trx)
|
||||
@@ -61,7 +62,8 @@ export class UnexcludeBankTransactionService {
|
||||
|
||||
await this.eventEmitter.emitAsync(events.bankTransactions.onUnexcluded, {
|
||||
uncategorizedTransactionId,
|
||||
} as IBankTransactionExcludedEventPayload);
|
||||
trx,
|
||||
} as IBankTransactionUnexcludedEventPayload);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ export class DecrementUncategorizedTransactionOnExclude {
|
||||
private readonly uncategorizedBankTransaction: TenantModelProxy<
|
||||
typeof UncategorizedBankTransaction
|
||||
>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Validates the cashflow transaction whether matched with bank transaction on deleting.
|
||||
@@ -50,7 +50,7 @@ export class DecrementUncategorizedTransactionOnExclude {
|
||||
trx,
|
||||
}: IBankTransactionUnexcludedEventPayload) {
|
||||
const transaction = await this.uncategorizedBankTransaction()
|
||||
.query()
|
||||
.query(trx)
|
||||
.findById(uncategorizedTransactionId);
|
||||
//
|
||||
await this.account()
|
||||
|
||||
@@ -25,7 +25,7 @@ export class BillAllocateLandedCostController {
|
||||
private billAllocatedCostTransactions: BillAllocatedLandedCostTransactions,
|
||||
private revertAllocatedLandedCost: RevertAllocatedLandedCost,
|
||||
private landedCostTransactions: LandedCostTranasctions,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
@Get('/transactions')
|
||||
@ApiOperation({ summary: 'Get landed cost transactions' })
|
||||
|
||||
@@ -21,7 +21,7 @@ export class BillAllocatedLandedCostTransactions {
|
||||
private readonly billLandedCostModel: TenantModelProxy<
|
||||
typeof BillLandedCost
|
||||
>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieve the bill associated landed cost transactions.
|
||||
@@ -77,6 +77,13 @@ export class BillAllocatedLandedCostTransactions {
|
||||
transaction.fromTransactionType,
|
||||
transaction,
|
||||
);
|
||||
const allocationMethodFormattedKey = transaction.allocationMethodFormatted;
|
||||
const allocationMethodFormatted = allocationMethodFormattedKey
|
||||
? this.i18nService.t(allocationMethodFormattedKey, {
|
||||
defaultValue: allocationMethodFormattedKey,
|
||||
})
|
||||
: '';
|
||||
|
||||
return {
|
||||
formattedAmount: formatNumber(transaction.amount, {
|
||||
currencyCode: transaction.currencyCode,
|
||||
@@ -84,12 +91,14 @@ export class BillAllocatedLandedCostTransactions {
|
||||
...omit(transaction, [
|
||||
'allocatedFromBillEntry',
|
||||
'allocatedFromExpenseEntry',
|
||||
'allocationMethodFormatted',
|
||||
]),
|
||||
name,
|
||||
description,
|
||||
formattedLocalAmount: formatNumber(transaction.localAmount, {
|
||||
currencyCode: 'USD',
|
||||
}),
|
||||
allocationMethodFormatted,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import { LandedCostTransactionsQueryDto } from '../dtos/LandedCostTransactionsQu
|
||||
|
||||
@Injectable()
|
||||
export class LandedCostTranasctions {
|
||||
constructor(private readonly transactionLandedCost: TransactionLandedCost) {}
|
||||
constructor(private readonly transactionLandedCost: TransactionLandedCost) { }
|
||||
|
||||
/**
|
||||
* Retrieve the landed costs based on the given query.
|
||||
@@ -45,8 +45,8 @@ export class LandedCostTranasctions {
|
||||
)(transactionType);
|
||||
|
||||
return pipe(
|
||||
this.transformLandedCostTransactions,
|
||||
R.map(transformLandedCost),
|
||||
this.transformLandedCostTransactions,
|
||||
)(transactions);
|
||||
};
|
||||
|
||||
@@ -90,7 +90,7 @@ export class LandedCostTranasctions {
|
||||
const entries = R.map<
|
||||
ILandedCostTransactionEntry,
|
||||
ILandedCostTransactionEntryDOJO
|
||||
>(transformLandedCostEntry)(transaction.entries);
|
||||
>(transformLandedCostEntry)(transaction.entries ?? []);
|
||||
|
||||
return {
|
||||
...transaction,
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
IsOptional,
|
||||
IsArray,
|
||||
ValidateNested,
|
||||
IsDecimal,
|
||||
IsString,
|
||||
IsNumber,
|
||||
} from 'class-validator';
|
||||
@@ -17,8 +16,9 @@ export class AllocateBillLandedCostItemDto {
|
||||
@ToNumber()
|
||||
entryId: number;
|
||||
|
||||
@IsDecimal()
|
||||
cost: string; // Use string for IsDecimal, or use @IsNumber() if you want a number
|
||||
@IsNumber()
|
||||
@ToNumber()
|
||||
cost: number;
|
||||
}
|
||||
|
||||
export class AllocateBillLandedCostDto {
|
||||
|
||||
@@ -60,8 +60,8 @@ export class BillLandedCost extends BaseModel {
|
||||
const allocationMethod = lowerCase(this.allocationMethod);
|
||||
|
||||
const keyLabelsPairs = {
|
||||
value: 'allocation_method.value.label',
|
||||
quantity: 'allocation_method.quantity.label',
|
||||
value: 'bill.allocation_method.value',
|
||||
quantity: 'bill.allocation_method.quantity',
|
||||
};
|
||||
return keyLabelsPairs[allocationMethod] || '';
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import { BranchesSettingsService } from '../Branches/BranchesSettings';
|
||||
import { BillPaymentsController } from './BillPayments.controller';
|
||||
import { BillPaymentGLEntries } from './commands/BillPaymentGLEntries';
|
||||
import { BillPaymentGLEntriesSubscriber } from './subscribers/BillPaymentGLEntriesSubscriber';
|
||||
import { BillPaymentBillSyncSubscriber } from './subscribers/BillPaymentBillSyncSubscriber';
|
||||
import { LedgerModule } from '../Ledger/Ledger.module';
|
||||
import { AccountsModule } from '../Accounts/Accounts.module';
|
||||
import { BillPaymentsExportable } from './queries/BillPaymentsExportable';
|
||||
@@ -39,6 +40,7 @@ import { BillPaymentsPages } from './commands/BillPaymentsPages.service';
|
||||
TenancyContext,
|
||||
BillPaymentGLEntries,
|
||||
BillPaymentGLEntriesSubscriber,
|
||||
BillPaymentBillSyncSubscriber,
|
||||
BillPaymentsExportable,
|
||||
BillPaymentsImportable,
|
||||
GetBillPaymentsService,
|
||||
@@ -52,4 +54,4 @@ import { BillPaymentsPages } from './commands/BillPaymentsPages.service';
|
||||
],
|
||||
controllers: [BillPaymentsController],
|
||||
})
|
||||
export class BillPaymentsModule {}
|
||||
export class BillPaymentsModule { }
|
||||
|
||||
@@ -38,7 +38,7 @@ export class CreateBillPaymentService {
|
||||
|
||||
@Inject(BillPayment.name)
|
||||
private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Creates a new bill payment transcations and store it to the storage
|
||||
@@ -103,11 +103,19 @@ export class CreateBillPaymentService {
|
||||
} as IBillPaymentCreatingPayload);
|
||||
|
||||
// Writes the bill payment graph to the storage.
|
||||
const billPayment = await this.billPaymentModel()
|
||||
const insertedBillPayment = await this.billPaymentModel()
|
||||
.query(trx)
|
||||
.insertGraphAndFetch({
|
||||
...billPaymentObj,
|
||||
});
|
||||
|
||||
// Fetch the bill payment with entries to ensure they're loaded for the subscriber.
|
||||
const billPayment = await this.billPaymentModel()
|
||||
.query(trx)
|
||||
.withGraphFetched('entries')
|
||||
.findById(insertedBillPayment.id)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Triggers `onBillPaymentCreated` event.
|
||||
await this.eventPublisher.emitAsync(events.billPayment.onCreated, {
|
||||
billPayment,
|
||||
|
||||
@@ -29,7 +29,7 @@ export class EditBillPayment {
|
||||
|
||||
@Inject(Vendor.name)
|
||||
private readonly vendorModel: TenantModelProxy<typeof Vendor>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Edits the details of the given bill payment.
|
||||
@@ -116,12 +116,20 @@ export class EditBillPayment {
|
||||
} as IBillPaymentEditingPayload);
|
||||
|
||||
// Edits the bill payment transaction graph on the storage.
|
||||
const billPayment = await this.billPaymentModel()
|
||||
await this.billPaymentModel()
|
||||
.query(trx)
|
||||
.upsertGraphAndFetch({
|
||||
.upsertGraph({
|
||||
id: billPaymentId,
|
||||
...billPaymentObj,
|
||||
});
|
||||
|
||||
// Fetch the bill payment with entries to ensure they're loaded for the subscriber.
|
||||
const billPayment = await this.billPaymentModel()
|
||||
.query(trx)
|
||||
.withGraphFetched('entries')
|
||||
.findById(billPaymentId)
|
||||
.throwIfNotFound();
|
||||
|
||||
// Triggers `onBillPaymentEdited` event.
|
||||
await this.eventPublisher.emitAsync(events.billPayment.onEdited, {
|
||||
billPaymentId,
|
||||
|
||||
@@ -16,8 +16,6 @@ export class BillPaymentsExportable extends Exportable {
|
||||
|
||||
/**
|
||||
* Retrieves the accounts data to exportable sheet.
|
||||
* @param {number} tenantId
|
||||
* @returns
|
||||
*/
|
||||
public async exportable(query: any) {
|
||||
const filterQuery = (builder) => {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
IBillPaymentEventCreatedPayload,
|
||||
IBillPaymentEventDeletedPayload,
|
||||
IBillPaymentEventEditedPayload,
|
||||
} from '../types/BillPayments.types';
|
||||
import { BillPaymentBillSync } from '../commands/BillPaymentBillSync.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { OnEvent } from '@nestjs/event-emitter';
|
||||
import { events } from '@/common/events/events';
|
||||
|
||||
@Injectable()
|
||||
export class BillPaymentBillSyncSubscriber {
|
||||
/**
|
||||
* @param {BillPaymentBillSync} billPaymentBillSync - Bill payment bill sync service.
|
||||
*/
|
||||
constructor(private readonly billPaymentBillSync: BillPaymentBillSync) { }
|
||||
|
||||
/**
|
||||
* Handle bill increment/decrement payment amount
|
||||
* once created, edited or deleted.
|
||||
*/
|
||||
@OnEvent(events.billPayment.onCreated)
|
||||
async handleBillIncrementPaymentOnceCreated({
|
||||
billPayment,
|
||||
trx,
|
||||
}: IBillPaymentEventCreatedPayload) {
|
||||
// Ensure entries are available - they should be included in insertGraphAndFetch
|
||||
const entries = billPayment.entries || [];
|
||||
await this.billPaymentBillSync.saveChangeBillsPaymentAmount(
|
||||
entries.map((entry) => ({
|
||||
billId: entry.billId,
|
||||
paymentAmount: entry.paymentAmount,
|
||||
})),
|
||||
null,
|
||||
trx,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle bill increment/decrement payment amount once edited.
|
||||
*/
|
||||
@OnEvent(events.billPayment.onEdited)
|
||||
async handleBillIncrementPaymentOnceEdited({
|
||||
billPayment,
|
||||
oldBillPayment,
|
||||
trx,
|
||||
}: IBillPaymentEventEditedPayload) {
|
||||
const entries = billPayment.entries || [];
|
||||
const oldEntries = oldBillPayment?.entries || null;
|
||||
|
||||
await this.billPaymentBillSync.saveChangeBillsPaymentAmount(
|
||||
entries.map((entry) => ({
|
||||
billId: entry.billId,
|
||||
paymentAmount: entry.paymentAmount,
|
||||
})),
|
||||
oldEntries,
|
||||
trx,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle revert bills payment amount once bill payment deleted.
|
||||
*/
|
||||
@OnEvent(events.billPayment.onDeleted)
|
||||
async handleBillDecrementPaymentAmount({
|
||||
oldBillPayment,
|
||||
trx,
|
||||
}: IBillPaymentEventDeletedPayload) {
|
||||
const oldEntries = oldBillPayment.entries || [];
|
||||
|
||||
await this.billPaymentBillSync.saveChangeBillsPaymentAmount(
|
||||
oldEntries.map((entry) => ({
|
||||
billId: entry.billId,
|
||||
paymentAmount: 0,
|
||||
})),
|
||||
oldEntries,
|
||||
trx,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,12 @@ import {
|
||||
Post,
|
||||
Body,
|
||||
Put,
|
||||
Patch,
|
||||
Param,
|
||||
Delete,
|
||||
Get,
|
||||
Query,
|
||||
HttpCode,
|
||||
} from '@nestjs/common';
|
||||
import { BillsApplication } from './Bills.application';
|
||||
import { IBillsFilter } from './Bills.types';
|
||||
@@ -40,6 +42,7 @@ export class BillsController {
|
||||
@ApiOperation({
|
||||
summary: 'Validate which bills can be deleted and return the results.',
|
||||
})
|
||||
@HttpCode(200)
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
@@ -56,6 +59,7 @@ export class BillsController {
|
||||
|
||||
@Post('bulk-delete')
|
||||
@ApiOperation({ summary: 'Deletes multiple bills.' })
|
||||
@HttpCode(200)
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: 'Bills deleted successfully',
|
||||
@@ -160,7 +164,7 @@ export class BillsController {
|
||||
return this.billsApplication.getBill(billId);
|
||||
}
|
||||
|
||||
@Post(':id/open')
|
||||
@Patch(':id/open')
|
||||
@ApiOperation({ summary: 'Open the given bill.' })
|
||||
@ApiParam({
|
||||
name: 'id',
|
||||
|
||||
@@ -51,6 +51,7 @@ export class Bill extends TenantBaseModel {
|
||||
public updatedAt: Date | null;
|
||||
|
||||
public entries?: ItemEntry[];
|
||||
public attachments!: Document[];
|
||||
public locatedLandedCosts?: BillLandedCost[];
|
||||
/**
|
||||
* Timestamps columns.
|
||||
@@ -633,7 +634,7 @@ export class Bill extends TenantBaseModel {
|
||||
|
||||
return this.query(trx)
|
||||
.where('id', billId)
|
||||
[changeMethod]('payment_amount', Math.abs(amount));
|
||||
[changeMethod]('payment_amount', Math.abs(amount));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Transformer } from '@/modules/Transformer/Transformer';
|
||||
import { Bill } from '../models/Bill';
|
||||
import { ItemEntryTransformer } from '@/modules/TransactionItemEntry/ItemEntry.transformer';
|
||||
import { AttachmentTransformer } from '@/modules/Attachments/Attachment.transformer';
|
||||
|
||||
export class BillTransformer extends Transformer {
|
||||
/**
|
||||
@@ -231,20 +233,18 @@ export class BillTransformer extends Transformer {
|
||||
/**
|
||||
* Retrieves the entries of the bill.
|
||||
* @param {Bill} credit
|
||||
* @returns {}
|
||||
*/
|
||||
// protected entries = (bill: Bill) => {
|
||||
// return this.item(bill.entries, new ItemEntryTransformer(), {
|
||||
// currencyCode: bill.currencyCode,
|
||||
// });
|
||||
// };
|
||||
protected entries = (bill: Bill) => {
|
||||
return this.item(bill.entries, new ItemEntryTransformer(), {
|
||||
currencyCode: bill.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the bill attachments.
|
||||
* @param {ISaleInvoice} invoice
|
||||
* @returns
|
||||
* @param {Bill} bill
|
||||
*/
|
||||
// protected attachments = (bill: Bill) => {
|
||||
// return this.item(bill.attachments, new AttachmentTransformer());
|
||||
// };
|
||||
protected attachments = (bill: Bill) => {
|
||||
return this.item(bill.attachments, new AttachmentTransformer());
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
Get,
|
||||
Query,
|
||||
Param,
|
||||
Post,
|
||||
Patch,
|
||||
ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiParam } from '@nestjs/swagger';
|
||||
@@ -27,7 +27,7 @@ export class ContactsController {
|
||||
return this.getAutoCompleteService.autocompleteContacts(query);
|
||||
}
|
||||
|
||||
@Post(':id/activate')
|
||||
@Patch(':id/activate')
|
||||
@ApiOperation({ summary: 'Activate a contact' })
|
||||
@ApiParam({ name: 'id', type: 'number', description: 'Contact ID' })
|
||||
async activateContact(@Param('id', ParseIntPipe) contactId: number) {
|
||||
@@ -35,7 +35,7 @@ export class ContactsController {
|
||||
return { id: contactId, activated: true };
|
||||
}
|
||||
|
||||
@Post(':id/inactivate')
|
||||
@Patch(':id/inactivate')
|
||||
@ApiOperation({ summary: 'Inactivate a contact' })
|
||||
@ApiParam({ name: 'id', type: 'number', description: 'Contact ID' })
|
||||
async inactivateContact(@Param('id', ParseIntPipe) contactId: number) {
|
||||
|
||||
@@ -7,9 +7,13 @@ import { CreditNotesRefundsApplication } from './CreditNotesRefundsApplication.s
|
||||
import { CreditNoteRefundsController } from './CreditNoteRefunds.controller';
|
||||
import { CreditNotesModule } from '../CreditNotes/CreditNotes.module';
|
||||
import { GetCreditNoteRefundsService } from './queries/GetCreditNoteRefunds.service';
|
||||
import { RefundCreditNoteGLEntries } from './commands/RefundCreditNoteGLEntries';
|
||||
import { RefundCreditNoteGLEntriesSubscriber } from '../CreditNotes/subscribers/RefundCreditNoteGLEntriesSubscriber';
|
||||
import { LedgerModule } from '../Ledger/Ledger.module';
|
||||
import { AccountsModule } from '../Accounts/Accounts.module';
|
||||
|
||||
@Module({
|
||||
imports: [forwardRef(() => CreditNotesModule)],
|
||||
imports: [forwardRef(() => CreditNotesModule), LedgerModule, AccountsModule],
|
||||
providers: [
|
||||
CreateRefundCreditNoteService,
|
||||
DeleteRefundCreditNoteService,
|
||||
@@ -17,8 +21,10 @@ import { GetCreditNoteRefundsService } from './queries/GetCreditNoteRefunds.serv
|
||||
RefundSyncCreditNoteBalanceService,
|
||||
CreditNotesRefundsApplication,
|
||||
GetCreditNoteRefundsService,
|
||||
RefundCreditNoteGLEntries,
|
||||
RefundCreditNoteGLEntriesSubscriber,
|
||||
],
|
||||
exports: [RefundSyncCreditNoteBalanceService],
|
||||
controllers: [CreditNoteRefundsController],
|
||||
})
|
||||
export class CreditNoteRefundsModule {}
|
||||
export class CreditNoteRefundsModule { }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsOptional, IsPositive, IsString } from 'class-validator';
|
||||
import { ToNumber, IsOptional } from '@/common/decorators/Validators';
|
||||
import { IsDateString, IsNotEmpty, IsPositive, IsString } from 'class-validator';
|
||||
import { IsDate } from 'class-validator';
|
||||
import { IsNumber } from 'class-validator';
|
||||
|
||||
@@ -10,8 +11,13 @@ export class CreditNoteRefundDto {
|
||||
description: 'The id of the from account',
|
||||
example: 1,
|
||||
})
|
||||
@ApiProperty({
|
||||
description: 'The id of the from account',
|
||||
example: 1,
|
||||
})
|
||||
fromAccountId: number;
|
||||
|
||||
@ToNumber()
|
||||
@IsNumber()
|
||||
@IsPositive()
|
||||
@IsNotEmpty()
|
||||
@@ -21,6 +27,7 @@ export class CreditNoteRefundDto {
|
||||
})
|
||||
amount: number;
|
||||
|
||||
@ToNumber()
|
||||
@IsNumber()
|
||||
@IsOptional()
|
||||
@IsPositive()
|
||||
@@ -30,23 +37,23 @@ export class CreditNoteRefundDto {
|
||||
})
|
||||
exchangeRate?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({
|
||||
description: 'The reference number of the credit note refund',
|
||||
example: '123456',
|
||||
})
|
||||
referenceNo: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({
|
||||
description: 'The description of the credit note refund',
|
||||
example: 'Credit note refund',
|
||||
})
|
||||
description: string;
|
||||
|
||||
@IsDate()
|
||||
@IsDateString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({
|
||||
description: 'The date of the credit note refund',
|
||||
@@ -54,6 +61,7 @@ export class CreditNoteRefundDto {
|
||||
})
|
||||
date: Date;
|
||||
|
||||
@ToNumber()
|
||||
@IsNumber()
|
||||
@IsOptional()
|
||||
@ApiProperty({
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { renderCreditNotePaperTemplateHtml } from '@bigcapital/pdf-templates';
|
||||
import { GetCreditNoteService } from './GetCreditNote.service';
|
||||
import { CreditNoteBrandingTemplate } from './CreditNoteBrandingTemplate.service';
|
||||
import { transformCreditNoteToPdfTemplate } from '../utils';
|
||||
import { CreditNote } from '../models/CreditNote';
|
||||
import { ChromiumlyTenancy } from '@/modules/ChromiumlyTenancy/ChromiumlyTenancy.service';
|
||||
import { TemplateInjectable } from '@/modules/TemplateInjectable/TemplateInjectable.service';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate';
|
||||
import { CreditNotePdfTemplateAttributes } from '../types/CreditNotes.types';
|
||||
@@ -15,7 +15,6 @@ import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
|
||||
export class GetCreditNotePdf {
|
||||
/**
|
||||
* @param {ChromiumlyTenancy} chromiumlyTenancy - Chromiumly tenancy service.
|
||||
* @param {TemplateInjectable} templateInjectable - Template injectable service.
|
||||
* @param {GetCreditNote} getCreditNoteService - Get credit note service.
|
||||
* @param {CreditNoteBrandingTemplate} creditNoteBrandingTemplate - Credit note branding template service.
|
||||
* @param {EventEmitter2} eventPublisher - Event publisher service.
|
||||
@@ -24,7 +23,6 @@ export class GetCreditNotePdf {
|
||||
*/
|
||||
constructor(
|
||||
private readonly chromiumlyTenancy: ChromiumlyTenancy,
|
||||
private readonly templateInjectable: TemplateInjectable,
|
||||
private readonly getCreditNoteService: GetCreditNoteService,
|
||||
private readonly creditNoteBrandingTemplate: CreditNoteBrandingTemplate,
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
@@ -36,23 +34,40 @@ export class GetCreditNotePdf {
|
||||
private readonly pdfTemplateModel: TenantModelProxy<
|
||||
typeof PdfTemplateModel
|
||||
>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieves sale invoice pdf content.
|
||||
* Retrieves credit note html content.
|
||||
* @param {number} creditNoteId - Credit note id.
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
public async getCreditNoteHtml(creditNoteId: number): Promise<string> {
|
||||
const brandingAttributes =
|
||||
await this.getCreditNoteBrandingAttributes(creditNoteId);
|
||||
|
||||
// Map attributes to match the React component props
|
||||
// The branding template returns companyLogoUri, but type may have companyLogo
|
||||
const props = {
|
||||
...brandingAttributes,
|
||||
companyLogoUri:
|
||||
(brandingAttributes as any).companyLogoUri ||
|
||||
(brandingAttributes as any).companyLogo ||
|
||||
'',
|
||||
};
|
||||
|
||||
return renderCreditNotePaperTemplateHtml(props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves credit note pdf content.
|
||||
* @param {number} creditNoteId - Credit note id.
|
||||
* @returns {Promise<[Buffer, string]>}
|
||||
*/
|
||||
public async getCreditNotePdf(
|
||||
creditNoteId: number,
|
||||
): Promise<[Buffer, string]> {
|
||||
const brandingAttributes =
|
||||
await this.getCreditNoteBrandingAttributes(creditNoteId);
|
||||
const htmlContent = await this.templateInjectable.render(
|
||||
'modules/credit-note-standard',
|
||||
brandingAttributes,
|
||||
);
|
||||
const filename = await this.getCreditNoteFilename(creditNoteId);
|
||||
const htmlContent = await this.getCreditNoteHtml(creditNoteId);
|
||||
|
||||
const document =
|
||||
await this.chromiumlyTenancy.convertHtmlContent(htmlContent);
|
||||
|
||||
@@ -16,7 +16,7 @@ export class DynamicListService {
|
||||
private dynamicListSearch: DynamicListSearch,
|
||||
private dynamicListSortBy: DynamicListSortBy,
|
||||
private dynamicListView: DynamicListCustomView,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Parses filter DTO.
|
||||
@@ -31,9 +31,9 @@ export class DynamicListService {
|
||||
// Merges the default properties with filter object.
|
||||
...(model.defaultSort
|
||||
? {
|
||||
sortOrder: model.defaultSort.sortOrder,
|
||||
columnSortBy: model.defaultSort.sortOrder,
|
||||
}
|
||||
sortOrder: model.defaultSort.sortOrder,
|
||||
columnSortBy: model.defaultSort.sortOrder,
|
||||
}
|
||||
: {}),
|
||||
...filterDTO,
|
||||
};
|
||||
@@ -93,7 +93,7 @@ export class DynamicListService {
|
||||
* Parses stringified filter roles.
|
||||
* @param {string} stringifiedFilterRoles - Stringified filter roles.
|
||||
*/
|
||||
public parseStringifiedFilter<T extends IDynamicListFilter>(
|
||||
public parseStringifiedFilter<T extends { stringifiedFilterRoles?: string }>(
|
||||
filterRoles: T,
|
||||
): T {
|
||||
return {
|
||||
|
||||
@@ -16,7 +16,7 @@ import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
@ApiTags('Reports')
|
||||
@ApiCommonHeaders()
|
||||
export class APAgingSummaryController {
|
||||
constructor(private readonly APAgingSummaryApp: APAgingSummaryApplication) {}
|
||||
constructor(private readonly APAgingSummaryApp: APAgingSummaryApplication) { }
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Get payable aging summary' })
|
||||
@@ -37,12 +37,13 @@ export class APAgingSummaryController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the json table format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.APAgingSummaryApp.table(filter);
|
||||
|
||||
// Retrieves the csv format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const csv = await this.APAgingSummaryApp.csv(filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
@@ -50,7 +51,7 @@ export class APAgingSummaryController {
|
||||
|
||||
res.send(csv);
|
||||
// Retrieves the xlsx format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.APAgingSummaryApp.xlsx(filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -60,7 +61,7 @@ export class APAgingSummaryController {
|
||||
);
|
||||
res.send(buffer);
|
||||
// Retrieves the pdf format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.APAgingSummaryApp.pdf(filter);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -38,8 +38,9 @@ export class ARAgingSummaryController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the xlsx format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.ARAgingSummaryApp.xlsx(filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -49,11 +50,11 @@ export class ARAgingSummaryController {
|
||||
);
|
||||
res.send(buffer);
|
||||
// Retrieves the table format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.ARAgingSummaryApp.table(filter);
|
||||
|
||||
// Retrieves the csv format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.ARAgingSummaryApp.csv(filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
@@ -61,7 +62,7 @@ export class ARAgingSummaryController {
|
||||
|
||||
res.send(buffer);
|
||||
// Retrieves the pdf format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.ARAgingSummaryApp.pdf(filter);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -43,13 +43,14 @@ export class BalanceSheetStatementController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the json table format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
const table = await this.balanceSheetApp.table(query);
|
||||
|
||||
return table;
|
||||
// Retrieves the csv format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.balanceSheetApp.csv(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
@@ -57,7 +58,7 @@ export class BalanceSheetStatementController {
|
||||
|
||||
res.send(buffer);
|
||||
// Retrieves the xlsx format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.balanceSheetApp.xlsx(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -67,7 +68,7 @@ export class BalanceSheetStatementController {
|
||||
);
|
||||
res.send(buffer);
|
||||
// Retrieves the pdf format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.balanceSheetApp.pdf(query);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -16,7 +16,7 @@ import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
@ApiTags('Reports')
|
||||
@ApiCommonHeaders()
|
||||
export class CashflowController {
|
||||
constructor(private readonly cashflowSheetApp: CashflowSheetApplication) {}
|
||||
constructor(private readonly cashflowSheetApp: CashflowSheetApplication) { }
|
||||
|
||||
@Get()
|
||||
@ApiResponse({
|
||||
@@ -37,11 +37,12 @@ export class CashflowController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the json table format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.cashflowSheetApp.table(query);
|
||||
// Retrieves the csv format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.cashflowSheetApp.csv(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
@@ -49,7 +50,7 @@ export class CashflowController {
|
||||
|
||||
res.status(200).send(buffer);
|
||||
// Retrieves the pdf format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.cashflowSheetApp.xlsx(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -59,7 +60,7 @@ export class CashflowController {
|
||||
);
|
||||
res.send(buffer);
|
||||
// Retrieves the pdf format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.cashflowSheetApp.pdf(query);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -34,8 +34,9 @@ export class CustomerBalanceSummaryController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the xlsx format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.customerBalanceSummaryApp.xlsx(filter);
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
res.setHeader(
|
||||
@@ -44,18 +45,18 @@ export class CustomerBalanceSummaryController {
|
||||
);
|
||||
res.send(buffer);
|
||||
// Retrieves the csv format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.customerBalanceSummaryApp.csv(filter);
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
res.setHeader('Content-Type', 'text/csv');
|
||||
|
||||
res.send(buffer);
|
||||
// Retrieves the json table format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.customerBalanceSummaryApp.table(filter);
|
||||
|
||||
// Retrieves the pdf format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const buffer = await this.customerBalanceSummaryApp.pdf(filter);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -39,11 +39,12 @@ export class GeneralLedgerController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the table format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.generalLedgerApplication.table(query);
|
||||
// Retrieves the csv format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.generalLedgerApplication.csv(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
@@ -51,7 +52,7 @@ export class GeneralLedgerController {
|
||||
|
||||
res.send(buffer);
|
||||
// Retrieves the xlsx format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.generalLedgerApplication.xlsx(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -61,7 +62,7 @@ export class GeneralLedgerController {
|
||||
);
|
||||
res.send(buffer);
|
||||
// Retrieves the pdf format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.generalLedgerApplication.pdf(query);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
|
||||
@@ -21,7 +21,8 @@ export class InventoryItemDetailsController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
const accept = acceptHeader || '';
|
||||
if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.inventoryItemDetailsApp.csv(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
@@ -29,7 +30,7 @@ export class InventoryItemDetailsController {
|
||||
|
||||
res.send(buffer);
|
||||
// Retrieves the xlsx format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.inventoryItemDetailsApp.xlsx(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -39,10 +40,10 @@ export class InventoryItemDetailsController {
|
||||
);
|
||||
res.send(buffer);
|
||||
// Retrieves the json table format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.inventoryItemDetailsApp.table(query);
|
||||
// Retrieves the pdf format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const buffer = await this.inventoryItemDetailsApp.pdf(query);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -37,11 +37,12 @@ export class InventoryValuationController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the json table format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.inventoryValuationApp.table(query);
|
||||
// Retrieves the csv format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.inventoryValuationApp.csv(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
@@ -49,7 +50,7 @@ export class InventoryValuationController {
|
||||
|
||||
res.send(buffer);
|
||||
// Retrieves the xslx buffer format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.inventoryValuationApp.xlsx(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -59,7 +60,7 @@ export class InventoryValuationController {
|
||||
);
|
||||
res.send(buffer);
|
||||
// Retrieves the pdf format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.inventoryValuationApp.pdf(query);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -37,12 +37,13 @@ export class JournalSheetController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the json table format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.journalSheetApp.table(query);
|
||||
|
||||
// Retrieves the csv format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.journalSheetApp.csv(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
@@ -50,7 +51,7 @@ export class JournalSheetController {
|
||||
|
||||
res.send(buffer);
|
||||
// Retrieves the xlsx format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.journalSheetApp.xlsx(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -60,7 +61,7 @@ export class JournalSheetController {
|
||||
);
|
||||
res.send(buffer);
|
||||
// Retrieves the json format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.journalSheetApp.pdf(query);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { FinancialSheet } from '../../common/FinancialSheet';
|
||||
import { JournalSheetRepository } from './JournalSheetRepository';
|
||||
import { ILedgerEntry } from '@/modules/Ledger/types/Ledger.types';
|
||||
import { getTransactionTypeLabel } from '@/modules/BankingTransactions/utils';
|
||||
|
||||
export class JournalSheet extends FinancialSheet {
|
||||
readonly query: IJournalReportQuery;
|
||||
@@ -97,10 +98,13 @@ export class JournalSheet extends FinancialSheet {
|
||||
|
||||
transactionType: groupEntry.transactionType,
|
||||
referenceId: groupEntry.transactionId,
|
||||
referenceTypeFormatted: this.i18n.t(groupEntry.transactionType),
|
||||
|
||||
referenceTypeFormatted: this.i18n.t(
|
||||
getTransactionTypeLabel(
|
||||
groupEntry.transactionType,
|
||||
groupEntry.transactionSubType,
|
||||
),
|
||||
),
|
||||
entries: this.entriesMapper(entriesGroup),
|
||||
|
||||
currencyCode: this.baseCurrency,
|
||||
|
||||
credit: totalCredit,
|
||||
|
||||
@@ -45,8 +45,9 @@ export class ProfitLossSheetController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the csv format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const sheet = await this.profitLossSheetApp.csv(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
@@ -54,11 +55,11 @@ export class ProfitLossSheetController {
|
||||
|
||||
res.send(sheet);
|
||||
// Retrieves the json table format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.profitLossSheetApp.table(query);
|
||||
|
||||
// Retrieves the xlsx format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const sheet = await this.profitLossSheetApp.xlsx(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -68,7 +69,7 @@ export class ProfitLossSheetController {
|
||||
);
|
||||
res.send(sheet);
|
||||
// Retrieves the json format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.profitLossSheetApp.pdf(query);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -22,11 +22,12 @@ export class PurchasesByItemReportController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// JSON table response format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.purchasesByItemsApp.table(filter);
|
||||
// CSV response format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.purchasesByItemsApp.csv(filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
@@ -34,7 +35,7 @@ export class PurchasesByItemReportController {
|
||||
|
||||
res.send(buffer);
|
||||
// Xlsx response format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.purchasesByItemsApp.xlsx(filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -44,7 +45,7 @@ export class PurchasesByItemReportController {
|
||||
);
|
||||
res.send(buffer);
|
||||
// PDF response format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.purchasesByItemsApp.pdf(filter);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -31,8 +31,9 @@ export class SalesByItemsController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the csv format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.salesByItemsApp.csv(filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
@@ -40,10 +41,10 @@ export class SalesByItemsController {
|
||||
|
||||
res.send(buffer);
|
||||
// Retrieves the json table format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.salesByItemsApp.table(filter);
|
||||
// Retrieves the xlsx format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = this.salesByItemsApp.xlsx(filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -53,7 +54,7 @@ export class SalesByItemsController {
|
||||
);
|
||||
res.send(buffer);
|
||||
// Retrieves the json format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.salesByItemsApp.pdf(filter);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -37,11 +37,12 @@ export class SalesTaxLiabilitySummaryController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the json table format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.salesTaxLiabilitySummaryApp.table(query);
|
||||
// Retrieves the xlsx format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.salesTaxLiabilitySummaryApp.xlsx(query);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -51,14 +52,14 @@ export class SalesTaxLiabilitySummaryController {
|
||||
);
|
||||
res.send(buffer);
|
||||
// Retrieves the csv format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.salesTaxLiabilitySummaryApp.csv(query);
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
res.setHeader('Content-Type', 'text/csv');
|
||||
|
||||
res.send(buffer);
|
||||
// Retrieves the json format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.salesTaxLiabilitySummaryApp.pdf(query);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
|
||||
@@ -9,17 +9,18 @@ import { TaxRateModel } from '@/modules/TaxRates/models/TaxRate.model';
|
||||
import { AccountTransaction } from '@/modules/Accounts/models/AccountTransaction.model';
|
||||
import { Account } from '@/modules/Accounts/models/Account.model';
|
||||
import { ModelObject } from 'objection';
|
||||
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
|
||||
|
||||
@Injectable({ scope: Scope.TRANSIENT })
|
||||
export class SalesTaxLiabilitySummaryRepository {
|
||||
@Inject(TaxRateModel.name)
|
||||
private readonly taxRateModel: typeof TaxRateModel;
|
||||
private readonly taxRateModel: TenantModelProxy<typeof TaxRateModel>;
|
||||
|
||||
@Inject(AccountTransaction.name)
|
||||
private readonly accountTransactionModel: typeof AccountTransaction;
|
||||
private readonly accountTransactionModel: TenantModelProxy<typeof AccountTransaction>;
|
||||
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: typeof Account;
|
||||
private readonly accountModel: TenantModelProxy<typeof Account>;
|
||||
|
||||
/**
|
||||
* @param {SalesTaxLiabilitySummarySalesById}
|
||||
@@ -77,7 +78,7 @@ export class SalesTaxLiabilitySummaryRepository {
|
||||
* @returns {Promise<TaxRate[]>}
|
||||
*/
|
||||
public getTaxRates = () => {
|
||||
return this.taxRateModel.query().orderBy('name', 'desc');
|
||||
return this.taxRateModel().query().orderBy('name', 'desc');
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -86,13 +87,13 @@ export class SalesTaxLiabilitySummaryRepository {
|
||||
*/
|
||||
public async getTaxesPayableSumGroupedByRateId(): Promise<SalesTaxLiabilitySummaryPayableById> {
|
||||
// Retrieves tax payable accounts.
|
||||
const taxPayableAccounts = await this.accountModel
|
||||
const taxPayableAccounts = await this.accountModel()
|
||||
.query()
|
||||
.whereIn('accountType', [ACCOUNT_TYPE.TAX_PAYABLE]);
|
||||
|
||||
const payableAccountsIds = taxPayableAccounts.map((account) => account.id);
|
||||
|
||||
const groupedTaxesById = await this.accountTransactionModel
|
||||
const groupedTaxesById = await this.accountTransactionModel()
|
||||
.query()
|
||||
.whereIn('account_id', payableAccountsIds)
|
||||
.whereNot('tax_rate_id', null)
|
||||
@@ -110,7 +111,7 @@ export class SalesTaxLiabilitySummaryRepository {
|
||||
*/
|
||||
public taxesSalesSumGroupedByRateId =
|
||||
async (): Promise<SalesTaxLiabilitySummarySalesById> => {
|
||||
const incomeAccounts = await this.accountModel
|
||||
const incomeAccounts = await this.accountModel()
|
||||
.query()
|
||||
.whereIn('accountType', [
|
||||
ACCOUNT_TYPE.INCOME,
|
||||
@@ -118,7 +119,7 @@ export class SalesTaxLiabilitySummaryRepository {
|
||||
]);
|
||||
const incomeAccountsIds = incomeAccounts.map((account) => account.id);
|
||||
|
||||
const groupedTaxesById = await this.accountTransactionModel
|
||||
const groupedTaxesById = await this.accountTransactionModel()
|
||||
.query()
|
||||
.whereIn('account_id', incomeAccountsIds)
|
||||
.whereNot('tax_rate_id', null)
|
||||
|
||||
@@ -23,12 +23,13 @@ export class TransactionsByCustomerController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the json table format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.transactionsByCustomersApp.table(filter);
|
||||
|
||||
// Retrieve the csv format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const csv = await this.transactionsByCustomersApp.csv(filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
@@ -37,7 +38,7 @@ export class TransactionsByCustomerController {
|
||||
res.send(csv);
|
||||
|
||||
// Retrieve the xlsx format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.transactionsByCustomersApp.xlsx(filter);
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
res.setHeader(
|
||||
@@ -47,7 +48,7 @@ export class TransactionsByCustomerController {
|
||||
res.send(buffer);
|
||||
|
||||
// Retrieve the json format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.transactionsByCustomersApp.pdf(filter);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
|
||||
@@ -4,8 +4,11 @@ import { TransactionsByReferenceRepository } from './TransactionsByReferenceRepo
|
||||
import { TransactionsByReferenceService } from './TransactionsByReference.service';
|
||||
import { TransactionsByReferenceController } from './TransactionsByReference.controller';
|
||||
import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service';
|
||||
import { FinancialSheetCommonModule } from '../../common/FinancialSheetCommon.module';
|
||||
import { AccountsModule } from '@/modules/Accounts/Accounts.module';
|
||||
|
||||
@Module({
|
||||
imports: [FinancialSheetCommonModule, AccountsModule],
|
||||
providers: [
|
||||
TransactionsByReferenceRepository,
|
||||
TransactionsByReferenceApplication,
|
||||
@@ -14,4 +17,4 @@ import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service';
|
||||
],
|
||||
controllers: [TransactionsByReferenceController],
|
||||
})
|
||||
export class TransactionsByReferenceModule {}
|
||||
export class TransactionsByReferenceModule { }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Controller, Get, Query } from '@nestjs/common';
|
||||
import { TransactionsByReferenceApplication } from './TransactionsByReferenceApplication';
|
||||
import { ITransactionsByReferenceQuery } from './TransactionsByReference.types';
|
||||
import { TransactionsByReferenceQueryDto } from './TransactionsByReferenceQuery.dto';
|
||||
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
|
||||
@Controller('reports/transactions-by-reference')
|
||||
@@ -8,13 +8,13 @@ import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
export class TransactionsByReferenceController {
|
||||
constructor(
|
||||
private readonly transactionsByReferenceApp: TransactionsByReferenceApplication,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
@Get()
|
||||
@ApiResponse({ status: 200, description: 'Transactions by reference' })
|
||||
@ApiOperation({ summary: 'Get transactions by reference' })
|
||||
async getTransactionsByReference(
|
||||
@Query() query: ITransactionsByReferenceQuery,
|
||||
@Query() query: TransactionsByReferenceQueryDto,
|
||||
) {
|
||||
const data = await this.transactionsByReferenceApp.getTransactions(query);
|
||||
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
ITransactionsByReferencePojo,
|
||||
ITransactionsByReferenceQuery,
|
||||
} from './TransactionsByReference.types';
|
||||
import { TransactionsByReferenceRepository } from './TransactionsByReferenceRepository';
|
||||
import { TransactionsByReference } from './TransactionsByReferenceReport';
|
||||
import { getTransactionsByReferenceQuery } from './_utils';
|
||||
import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service';
|
||||
import { TransactionsByReferenceQueryDto } from './TransactionsByReferenceQuery.dto';
|
||||
|
||||
@Injectable()
|
||||
export class TransactionsByReferenceService {
|
||||
constructor(
|
||||
private readonly repository: TransactionsByReferenceRepository,
|
||||
private readonly tenancyContext: TenancyContext
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieve accounts transactions by given reference id and type.
|
||||
* @param {ITransactionsByReferenceQuery} filter - Transactions by reference query.
|
||||
* @param {TransactionsByReferenceQueryDto} filter - Transactions by reference query.
|
||||
* @returns {Promise<ITransactionsByReferencePojo>}
|
||||
*/
|
||||
public async getTransactionsByReference(
|
||||
query: ITransactionsByReferenceQuery
|
||||
query: TransactionsByReferenceQueryDto
|
||||
): Promise<ITransactionsByReferencePojo> {
|
||||
const filter = {
|
||||
...getTransactionsByReferenceQuery(),
|
||||
@@ -31,7 +31,7 @@ export class TransactionsByReferenceService {
|
||||
|
||||
// Retrieve the accounts transactions of the given reference.
|
||||
const transactions = await this.repository.getTransactions(
|
||||
Number(filter.referenceId),
|
||||
query.referenceId,
|
||||
filter.referenceType
|
||||
);
|
||||
// Transactions by reference report.
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { TransactionsByReferenceService } from './TransactionsByReference.service';
|
||||
import { ITransactionsByReferenceQuery } from './TransactionsByReference.types';
|
||||
import { TransactionsByReferenceQueryDto } from './TransactionsByReferenceQuery.dto';
|
||||
|
||||
@Injectable()
|
||||
export class TransactionsByReferenceApplication {
|
||||
constructor(
|
||||
private readonly transactionsByReferenceService: TransactionsByReferenceService,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieve accounts transactions by given reference id and type.
|
||||
* @param {ITransactionsByReferenceQuery} query - Transactions by reference query.
|
||||
* @param {TransactionsByReferenceQueryDto} query - Transactions by reference query.
|
||||
* @returns {Promise<ITransactionsByReferencePojo>}
|
||||
*/
|
||||
public async getTransactions(query: ITransactionsByReferenceQuery) {
|
||||
public async getTransactions(query: TransactionsByReferenceQueryDto) {
|
||||
return this.transactionsByReferenceService.getTransactionsByReference(
|
||||
query,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class TransactionsByReferenceQueryDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({
|
||||
description: 'The type of the reference (e.g., SaleInvoice, Bill, etc.)',
|
||||
example: 'SaleInvoice',
|
||||
required: true,
|
||||
})
|
||||
referenceType: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({
|
||||
description: 'The ID of the reference',
|
||||
example: '1',
|
||||
required: true,
|
||||
})
|
||||
referenceId: number;
|
||||
}
|
||||
@@ -1,27 +1,27 @@
|
||||
import {
|
||||
ITransactionsByReferenceQuery,
|
||||
ITransactionsByReferenceTransaction,
|
||||
} from './TransactionsByReference.types';
|
||||
import { FinancialSheet } from '../../common/FinancialSheet';
|
||||
import { ModelObject } from 'objection';
|
||||
import { AccountTransaction } from '@/modules/Accounts/models/AccountTransaction.model';
|
||||
import { INumberFormatQuery } from '../../types/Report.types';
|
||||
import { TransactionsByReferenceQueryDto } from './TransactionsByReferenceQuery.dto';
|
||||
|
||||
export class TransactionsByReference extends FinancialSheet {
|
||||
readonly transactions: ModelObject<AccountTransaction>[];
|
||||
readonly query: ITransactionsByReferenceQuery;
|
||||
readonly query: TransactionsByReferenceQueryDto;
|
||||
readonly baseCurrency: string;
|
||||
readonly numberFormat: INumberFormatQuery;
|
||||
|
||||
/**
|
||||
* Constructor method.
|
||||
* @param {ModelObject<AccountTransaction>[]} transactions
|
||||
* @param {ITransactionsByReferenceQuery} query
|
||||
* @param {TransactionsByVendorQueryDto} query
|
||||
* @param {string} baseCurrency
|
||||
*/
|
||||
constructor(
|
||||
transactions: ModelObject<AccountTransaction>[],
|
||||
query: ITransactionsByReferenceQuery,
|
||||
query: TransactionsByReferenceQueryDto,
|
||||
baseCurrency: string
|
||||
) {
|
||||
super();
|
||||
@@ -46,19 +46,16 @@ export class TransactionsByReference extends FinancialSheet {
|
||||
credit: this.getAmountMeta(transaction.credit, { money: false }),
|
||||
debit: this.getAmountMeta(transaction.debit, { money: false }),
|
||||
|
||||
// @ts-ignore
|
||||
// referenceTypeFormatted: transaction.referenceTypeFormatted,
|
||||
referenceTypeFormatted: '',
|
||||
|
||||
referenceType: transaction.referenceType,
|
||||
referenceId: transaction.referenceId,
|
||||
formattedReferenceType: transaction.referenceTypeFormatted,
|
||||
|
||||
contactId: transaction.contactId,
|
||||
contactType: transaction.contactType,
|
||||
contactTypeFormatted: transaction.contactType,
|
||||
formattedContactType: transaction.contactType || '',
|
||||
|
||||
accountName: transaction.account.name,
|
||||
accountCode: transaction.account.code,
|
||||
accountName: transaction.account?.name || '',
|
||||
accountCode: transaction.account?.code || '',
|
||||
accountId: transaction.accountId,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -24,6 +24,7 @@ export class TransactionsByReferenceRepository {
|
||||
): Promise<Array<ModelObject<AccountTransaction>>> {
|
||||
return this.accountTransactionModel()
|
||||
.query()
|
||||
.skipUndefined()
|
||||
.where('reference_id', referenceId)
|
||||
.where('reference_type', referenceType)
|
||||
.withGraphFetched('account');
|
||||
|
||||
@@ -23,8 +23,9 @@ export class TransactionsByVendorController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the xlsx format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.transactionsByVendorsApp.xlsx(filter);
|
||||
|
||||
res.setHeader('Content-Type', 'application/vnd.openxmlformats');
|
||||
@@ -32,7 +33,7 @@ export class TransactionsByVendorController {
|
||||
|
||||
res.send(buffer);
|
||||
// Retrieves the csv format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.transactionsByVendorsApp.csv(filter);
|
||||
|
||||
res.setHeader('Content-Type', 'text/csv');
|
||||
@@ -40,10 +41,10 @@ export class TransactionsByVendorController {
|
||||
|
||||
res.send(buffer);
|
||||
// Retrieves the json table format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.transactionsByVendorsApp.table(filter);
|
||||
// Retrieves the pdf format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.transactionsByVendorsApp.pdf(filter);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
|
||||
@@ -2,7 +2,6 @@ import { Injectable } from '@nestjs/common';
|
||||
import { I18nService } from 'nestjs-i18n';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import {
|
||||
ITransactionsByVendorsFilter,
|
||||
ITransactionsByVendorsStatement,
|
||||
} from './TransactionsByVendor.types';
|
||||
import { TransactionsByVendor } from './TransactionsByVendor';
|
||||
@@ -10,6 +9,7 @@ import { TransactionsByVendorRepository } from './TransactionsByVendorRepository
|
||||
import { TransactionsByVendorMeta } from './TransactionsByVendorMeta';
|
||||
import { getTransactionsByVendorDefaultQuery } from './utils';
|
||||
import { events } from '@/common/events/events';
|
||||
import { TransactionsByVendorQueryDto } from './TransactionsByVendorQuery.dto';
|
||||
|
||||
@Injectable()
|
||||
export class TransactionsByVendorsInjectable {
|
||||
@@ -18,15 +18,15 @@ export class TransactionsByVendorsInjectable {
|
||||
private readonly transactionsByVendorMeta: TransactionsByVendorMeta,
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
private readonly i18n: I18nService,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieve transactions by by the customers.
|
||||
* @param {ITransactionsByVendorsFilter} query - Transactions by vendors filter.
|
||||
* @param {TransactionsByVendorQueryDto} query - Transactions by vendors filter.
|
||||
* @return {Promise<ITransactionsByVendorsStatement>}
|
||||
*/
|
||||
public async transactionsByVendors(
|
||||
query: ITransactionsByVendorsFilter,
|
||||
query: TransactionsByVendorQueryDto,
|
||||
): Promise<ITransactionsByVendorsStatement> {
|
||||
const filter = { ...getTransactionsByVendorDefaultQuery(), ...query };
|
||||
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
import { TransactionsByVendorsTable } from './TransactionsByVendorTable';
|
||||
import {
|
||||
ITransactionsByVendorTable,
|
||||
ITransactionsByVendorsFilter,
|
||||
} from './TransactionsByVendor.types';
|
||||
import { TransactionsByVendorsInjectable } from './TransactionsByVendorInjectable';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { I18nService } from 'nestjs-i18n';
|
||||
import { TransactionsByVendorQueryDto } from './TransactionsByVendorQuery.dto';
|
||||
|
||||
@Injectable()
|
||||
export class TransactionsByVendorTableInjectable {
|
||||
constructor(
|
||||
private readonly transactionsByVendor: TransactionsByVendorsInjectable,
|
||||
private readonly i18n: I18nService
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieves the transactions by vendor in table format.
|
||||
* @param {ITransactionsByReferenceQuery} query - The filter query.
|
||||
* @param {TransactionsByVendorQueryDto} query - The filter query.
|
||||
* @returns {Promise<ITransactionsByVendorTable>}
|
||||
*/
|
||||
public async table(
|
||||
query: ITransactionsByVendorsFilter
|
||||
query: TransactionsByVendorQueryDto
|
||||
): Promise<ITransactionsByVendorTable> {
|
||||
const sheet = await this.transactionsByVendor.transactionsByVendors(
|
||||
query
|
||||
|
||||
@@ -40,15 +40,16 @@ export class TrialBalanceSheetController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
const filter = {
|
||||
...query,
|
||||
accountIds: castArray(query.accountIds),
|
||||
};
|
||||
// Retrieves in json table format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.trialBalanceSheetApp.table(filter);
|
||||
// Retrieves in xlsx format
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.trialBalanceSheetApp.xlsx(filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -58,7 +59,7 @@ export class TrialBalanceSheetController {
|
||||
);
|
||||
res.send(buffer);
|
||||
// Retrieves in csv format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.trialBalanceSheetApp.csv(filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
@@ -66,7 +67,7 @@ export class TrialBalanceSheetController {
|
||||
|
||||
res.send(buffer);
|
||||
// Retrieves in pdf format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.trialBalanceSheetApp.pdf(filter);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -35,15 +35,16 @@ export class VendorBalanceSummaryController {
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Headers('accept') acceptHeader: string,
|
||||
) {
|
||||
const accept = acceptHeader || '';
|
||||
// Retrieves the csv format.
|
||||
if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
|
||||
if (accept.includes(AcceptType.ApplicationCsv)) {
|
||||
const buffer = await this.vendorBalanceSummaryApp.csv(filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
res.setHeader('Content-Type', 'text/csv');
|
||||
|
||||
res.send(buffer);
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
|
||||
const buffer = await this.vendorBalanceSummaryApp.xlsx(filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
@@ -52,10 +53,10 @@ export class VendorBalanceSummaryController {
|
||||
res.send(buffer);
|
||||
|
||||
// Retrieves the json table format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationJsonTable)) {
|
||||
return this.vendorBalanceSummaryApp.table(filter);
|
||||
// Retrieves the pdf format.
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
} else if (accept.includes(AcceptType.ApplicationPdf)) {
|
||||
const pdfContent = await this.vendorBalanceSummaryApp.pdf(filter);
|
||||
|
||||
res.set({
|
||||
|
||||
@@ -6,6 +6,7 @@ import { SaleInvoice } from '@/modules/SaleInvoices/models/SaleInvoice';
|
||||
import { SaleReceipt } from '@/modules/SaleReceipts/models/SaleReceipt';
|
||||
import { Item } from '@/modules/Items/models/Item';
|
||||
import { BaseModel } from '@/models/Model';
|
||||
import { ItemEntry } from '@/modules/TransactionItemEntry/models/ItemEntry';
|
||||
|
||||
export class InventoryCostLotTracker extends BaseModel {
|
||||
date: Date;
|
||||
@@ -27,6 +28,7 @@ export class InventoryCostLotTracker extends BaseModel {
|
||||
warehouseId: number;
|
||||
|
||||
item?: Item;
|
||||
itemEntry?: ItemEntry;
|
||||
invoice?: SaleInvoice;
|
||||
receipt?: SaleReceipt;
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ export class InventoryCostSubscriber {
|
||||
private readonly itemsQuantitySync: InventoryItemsQuantitySyncService,
|
||||
private readonly inventoryService: InventoryComputeCostService,
|
||||
private readonly importAls: ImportAls,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Sync inventory items quantity once inventory transactions created.
|
||||
@@ -60,7 +60,7 @@ export class InventoryCostSubscriber {
|
||||
* Marks items cost compute running state.
|
||||
*/
|
||||
@OnEvent(events.inventory.onInventoryTransactionsCreated)
|
||||
async markGlobalSettingsComputeItems({}) {
|
||||
async markGlobalSettingsComputeItems({ }) {
|
||||
await this.inventoryService.markItemsCostComputeRunning(true);
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ export class InventoryCostSubscriber {
|
||||
* Marks items cost compute as completed.
|
||||
*/
|
||||
@OnEvent(events.inventory.onInventoryCostEntriesWritten)
|
||||
async markGlobalSettingsComputeItemsCompeted({}) {
|
||||
async markGlobalSettingsComputeItemsCompeted({ }) {
|
||||
await this.inventoryService.markItemsCostComputeRunning(false);
|
||||
}
|
||||
|
||||
@@ -80,15 +80,13 @@ export class InventoryCostSubscriber {
|
||||
itemId,
|
||||
startingDate,
|
||||
}: IComputeItemCostJobCompletedPayload) {
|
||||
// const dependsComputeJobs = await this.agenda.jobs({
|
||||
// name: 'compute-item-cost',
|
||||
// nextRunAt: { $ne: null },
|
||||
// 'data.tenantId': tenantId,
|
||||
// });
|
||||
// // There is no scheduled compute jobs waiting.
|
||||
// if (dependsComputeJobs.length === 0) {
|
||||
// await this.saleInvoicesCost.scheduleWriteJournalEntries(startingDate);
|
||||
// }
|
||||
// Convert startingDate to Date if it's a string
|
||||
const startingDateObj = startingDate instanceof Date
|
||||
? startingDate
|
||||
: new Date(startingDate);
|
||||
|
||||
// Write GL entries for inventory cost lots after cost computation completes
|
||||
await this.saleInvoicesCost.writeCostLotsGLEntries(startingDateObj);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,7 +6,7 @@ import { DeleteItemService } from './DeleteItem.service';
|
||||
|
||||
@Injectable()
|
||||
export class BulkDeleteItemsService {
|
||||
constructor(private readonly deleteItemService: DeleteItemService) {}
|
||||
constructor(private readonly deleteItemService: DeleteItemService) { }
|
||||
|
||||
/**
|
||||
* Deletes multiple items.
|
||||
|
||||
@@ -25,7 +25,7 @@ export class DeleteItemService {
|
||||
|
||||
@Inject(Item.name)
|
||||
private readonly itemModel: TenantModelProxy<typeof Item>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Delete the given item from the storage.
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
Get,
|
||||
Put,
|
||||
Query,
|
||||
HttpCode,
|
||||
} from '@nestjs/common';
|
||||
import { TenantController } from '../Tenancy/Tenant.controller';
|
||||
import { ItemsApplicationService } from './ItemsApplication.service';
|
||||
@@ -156,9 +157,45 @@ export class ItemsController extends TenantController {
|
||||
async editItem(
|
||||
@Param('id') id: string,
|
||||
@Body() editItemDto: EditItemDto,
|
||||
): Promise<number> {
|
||||
): Promise<{ id: number; message: string }> {
|
||||
const itemId = parseInt(id, 10);
|
||||
return this.itemsApplication.editItem(itemId, editItemDto);
|
||||
await this.itemsApplication.editItem(itemId, editItemDto);
|
||||
return { id: itemId, message: 'The item has been successfully updated.' };
|
||||
}
|
||||
|
||||
@Post('validate-bulk-delete')
|
||||
@HttpCode(200)
|
||||
@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')
|
||||
@HttpCode(200)
|
||||
@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,
|
||||
});
|
||||
}
|
||||
|
||||
@Post()
|
||||
@@ -168,8 +205,12 @@ export class ItemsController extends TenantController {
|
||||
description: 'The item has been successfully created.',
|
||||
})
|
||||
// @UsePipes(new ZodValidationPipe(createItemSchema))
|
||||
async createItem(@Body() createItemDto: CreateItemDto): Promise<number> {
|
||||
return this.itemsApplication.createItem(createItemDto);
|
||||
async createItem(
|
||||
@Body() createItemDto: CreateItemDto,
|
||||
): Promise<{ id: number; message: string }> {
|
||||
const itemId = await this.itemsApplication.createItem(createItemDto);
|
||||
|
||||
return { id: itemId, message: 'The item has been successfully created.' };
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@@ -346,36 +387,4 @@ export class ItemsController extends TenantController {
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ export class ItemsEntriesService {
|
||||
|
||||
@Inject(ItemEntry.name)
|
||||
private readonly itemEntryModel: TenantModelProxy<typeof ItemEntry>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieve the inventory items entries of the reference id and type.
|
||||
@@ -226,6 +226,10 @@ export class ItemsEntriesService {
|
||||
return entries.map((entry) => {
|
||||
const item = items.find((i) => i.id === entry.itemId);
|
||||
|
||||
if (!item) {
|
||||
throw new Error(`Item with id ${entry.itemId} not found`);
|
||||
}
|
||||
|
||||
return {
|
||||
...entry,
|
||||
sellAccountId: entry.sellAccountId || item.sellAccountId,
|
||||
|
||||
@@ -13,9 +13,8 @@ export class UpdateOrganizationService {
|
||||
private readonly tenancyContext: TenancyContext,
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
private readonly commandOrganizationValidators: CommandOrganizationValidators,
|
||||
|
||||
private readonly tenantRepository: TenantRepository,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Updates organization information.
|
||||
|
||||
@@ -229,7 +229,7 @@ export class PaymentReceivesController {
|
||||
@Headers('accept') acceptHeader: string,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
if (acceptHeader?.includes(AcceptType.ApplicationPdf)) {
|
||||
const [pdfContent, filename] = await this.paymentReceivesApplication.getPaymentReceivePdf(
|
||||
paymentReceiveId,
|
||||
);
|
||||
@@ -239,7 +239,7 @@ export class PaymentReceivesController {
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
});
|
||||
res.send(pdfContent);
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationTextHtml)) {
|
||||
} else if (acceptHeader?.includes(AcceptType.ApplicationTextHtml)) {
|
||||
const htmlContent =
|
||||
await this.paymentReceivesApplication.getPaymentReceivedHtml(
|
||||
paymentReceiveId,
|
||||
|
||||
@@ -32,7 +32,7 @@ export class PaymentReceivedValidators {
|
||||
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: TenantModelProxy<typeof Account>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Validates the payment existance.
|
||||
@@ -76,9 +76,14 @@ export class PaymentReceivedValidators {
|
||||
customerId: number,
|
||||
paymentReceiveEntries: { invoiceId: number }[],
|
||||
): Promise<SaleInvoice[]> {
|
||||
const invoicesIds = paymentReceiveEntries.map(
|
||||
(e: { invoiceId: number }) => e.invoiceId,
|
||||
);
|
||||
const invoicesIds = paymentReceiveEntries
|
||||
.map((e: { invoiceId: number }) => e.invoiceId)
|
||||
.filter((id): id is number => id !== undefined && id !== null);
|
||||
|
||||
if (invoicesIds.length === 0) {
|
||||
throw new ServiceError(ERRORS.INVOICES_IDS_NOT_FOUND);
|
||||
}
|
||||
|
||||
const storedInvoices = await this.saleInvoiceModel()
|
||||
.query()
|
||||
.whereIn('id', invoicesIds)
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import {
|
||||
Controller,
|
||||
Post,
|
||||
Put,
|
||||
Get,
|
||||
Delete,
|
||||
Param,
|
||||
Body,
|
||||
Next,
|
||||
HttpStatus,
|
||||
ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { NextFunction } from 'express';
|
||||
import { CreateRoleDto, EditRoleDto } from './dtos/Role.dto';
|
||||
import { RolesApplication } from './Roles.application';
|
||||
import {
|
||||
@@ -29,7 +28,7 @@ import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
@ApiExtraModels(RoleResponseDto)
|
||||
@ApiCommonHeaders()
|
||||
export class RolesController {
|
||||
constructor(private readonly rolesApp: RolesApplication) {}
|
||||
constructor(private readonly rolesApp: RolesApplication) { }
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Create a new role' })
|
||||
@@ -38,19 +37,16 @@ export class RolesController {
|
||||
status: HttpStatus.OK,
|
||||
description: 'Role created successfully',
|
||||
})
|
||||
async createRole(
|
||||
@Next() next: NextFunction,
|
||||
@Body() createRoleDto: CreateRoleDto,
|
||||
) {
|
||||
async createRole(@Body() createRoleDto: CreateRoleDto) {
|
||||
const role = await this.rolesApp.createRole(createRoleDto);
|
||||
|
||||
return {
|
||||
data: { roleId: role.id },
|
||||
data: { id: role.id },
|
||||
message: 'The role has been created successfully.',
|
||||
};
|
||||
}
|
||||
|
||||
@Post(':id')
|
||||
@Put(':id')
|
||||
@ApiOperation({ summary: 'Edit an existing role' })
|
||||
@ApiParam({ name: 'id', description: 'Role ID' })
|
||||
@ApiBody({ type: EditRoleDto })
|
||||
@@ -65,7 +61,7 @@ export class RolesController {
|
||||
const role = await this.rolesApp.editRole(roleId, editRoleDto);
|
||||
|
||||
return {
|
||||
data: { roleId },
|
||||
data: { id: role.id },
|
||||
message: 'The given role has been updated successfully.',
|
||||
};
|
||||
}
|
||||
@@ -81,7 +77,7 @@ export class RolesController {
|
||||
await this.rolesApp.deleteRole(roleId);
|
||||
|
||||
return {
|
||||
data: { roleId },
|
||||
data: { id: roleId },
|
||||
message: 'The given role has been deleted successfully.',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ export class EditRoleService {
|
||||
|
||||
@Inject(Role.name)
|
||||
private readonly roleModel: TenantModelProxy<typeof Role>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Edits details of the given role on the storage.
|
||||
@@ -30,7 +30,13 @@ export class EditRoleService {
|
||||
|
||||
// Retrieve the given role or throw not found serice error.
|
||||
const oldRole = await this.roleModel().query().findById(roleId);
|
||||
const permissions = editRoleDTO.permissions;
|
||||
// Transform permissions: map permissionId to id for Objection.js upsertGraph
|
||||
const permissions = editRoleDTO.permissions.map((perm) => ({
|
||||
id: perm.permissionId,
|
||||
subject: perm.subject,
|
||||
ability: perm.ability,
|
||||
value: perm.value,
|
||||
}));
|
||||
|
||||
// Updates the role on the storage.
|
||||
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
|
||||
|
||||
@@ -38,7 +38,7 @@ export class CommandRolePermissionDto {
|
||||
value: boolean;
|
||||
}
|
||||
|
||||
export class CreateRolePermissionDto extends CommandRolePermissionDto {}
|
||||
export class CreateRolePermissionDto extends CommandRolePermissionDto { }
|
||||
export class EditRolePermissionDto extends CommandRolePermissionDto {
|
||||
@IsNumber()
|
||||
@IsNotEmpty()
|
||||
@@ -83,9 +83,9 @@ export class EditRoleDto extends CommandRoleDto {
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => CommandRolePermissionDto)
|
||||
@Type(() => EditRolePermissionDto)
|
||||
@ApiProperty({
|
||||
type: [CommandRolePermissionDto],
|
||||
type: [EditRolePermissionDto],
|
||||
description: 'The permissions of the role',
|
||||
})
|
||||
permissions: Array<EditRolePermissionDto>;
|
||||
|
||||
@@ -38,7 +38,8 @@ export class SaleInvoiceCostGLEntries {
|
||||
.modify('filterDateRange', startingDate)
|
||||
.orderBy('date', 'ASC')
|
||||
.withGraphFetched('invoice')
|
||||
.withGraphFetched('item');
|
||||
.withGraphFetched('item')
|
||||
.withGraphFetched('itemEntry');
|
||||
|
||||
const ledger = this.getInventoryCostLotsLedger(inventoryCostLotTrans);
|
||||
|
||||
@@ -79,6 +80,9 @@ export class SaleInvoiceCostGLEntries {
|
||||
transactionType: inventoryCostLot.transactionType,
|
||||
transactionId: inventoryCostLot.transactionId,
|
||||
|
||||
transactionNumber: inventoryCostLot.invoice.invoiceNo,
|
||||
referenceNumber: inventoryCostLot.invoice.referenceNo,
|
||||
|
||||
date: inventoryCostLot.date,
|
||||
indexGroup: 20,
|
||||
costable: true,
|
||||
@@ -105,6 +109,9 @@ export class SaleInvoiceCostGLEntries {
|
||||
const costAccountId =
|
||||
inventoryCostLot.costAccountId || inventoryCostLot.item.costAccountId;
|
||||
|
||||
// Get description from item entry if available
|
||||
const description = inventoryCostLot.itemEntry?.description || null;
|
||||
|
||||
// XXX Debit - Cost account.
|
||||
const costEntry = {
|
||||
...commonEntry,
|
||||
@@ -112,6 +119,7 @@ export class SaleInvoiceCostGLEntries {
|
||||
accountId: costAccountId,
|
||||
accountNormal: AccountNormal.DEBIT,
|
||||
itemId: inventoryCostLot.itemId,
|
||||
note: description,
|
||||
index: getIndexIncrement(),
|
||||
};
|
||||
// XXX Credit - Inventory account.
|
||||
@@ -121,6 +129,7 @@ export class SaleInvoiceCostGLEntries {
|
||||
accountId: inventoryCostLot.item.inventoryAccountId,
|
||||
accountNormal: AccountNormal.DEBIT,
|
||||
itemId: inventoryCostLot.itemId,
|
||||
note: description,
|
||||
index: getIndexIncrement(),
|
||||
};
|
||||
return [costEntry, inventoryEntry];
|
||||
|
||||
@@ -210,7 +210,7 @@ export class SaleInvoicesController {
|
||||
@Headers('accept') acceptHeader: string,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
if (acceptHeader?.includes(AcceptType.ApplicationPdf)) {
|
||||
const [pdfContent, filename] =
|
||||
await this.saleInvoiceApplication.saleInvoicePdf(id);
|
||||
|
||||
@@ -219,7 +219,7 @@ export class SaleInvoicesController {
|
||||
'Content-Length': pdfContent.length,
|
||||
});
|
||||
res.send(pdfContent);
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationTextHtml)) {
|
||||
} else if (acceptHeader?.includes(AcceptType.ApplicationTextHtml)) {
|
||||
const htmlContent = await this.saleInvoiceApplication.saleInvoiceHtml(id);
|
||||
return { htmlContent };
|
||||
} else {
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { OnEvent } from '@nestjs/event-emitter';
|
||||
import { events } from '@/common/events/events';
|
||||
import { IInventoryCostLotsGLEntriesWriteEvent } from '@/modules/InventoryCost/types/InventoryCost.types';
|
||||
import { SaleInvoiceCostGLEntries } from '../SaleInvoiceCostGLEntries';
|
||||
|
||||
@Injectable()
|
||||
export class InvoiceCostGLEntriesSubscriber {
|
||||
constructor(private readonly invoiceCostEntries: SaleInvoiceCostGLEntries) {}
|
||||
constructor(private readonly invoiceCostEntries: SaleInvoiceCostGLEntries) { }
|
||||
|
||||
/**
|
||||
* Writes the invoices cost GL entries once the inventory cost lots be written.
|
||||
* @param {IInventoryCostLotsGLEntriesWriteEvent}
|
||||
*/
|
||||
@OnEvent(events.inventory.onCostLotsGLEntriesWrite)
|
||||
async writeInvoicesCostEntriesOnCostLotsWritten({
|
||||
trx,
|
||||
startingDate,
|
||||
|
||||
@@ -168,7 +168,7 @@ export class SaleReceiptsController {
|
||||
@Headers('accept') acceptHeader: string,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
|
||||
if (acceptHeader?.includes(AcceptType.ApplicationPdf)) {
|
||||
const [pdfContent] =
|
||||
await this.saleReceiptApplication.getSaleReceiptPdf(id);
|
||||
|
||||
@@ -177,7 +177,7 @@ export class SaleReceiptsController {
|
||||
'Content-Length': pdfContent.length,
|
||||
});
|
||||
res.send(pdfContent);
|
||||
} else if (acceptHeader.includes(AcceptType.ApplicationTextHtml)) {
|
||||
} else if (acceptHeader?.includes(AcceptType.ApplicationTextHtml)) {
|
||||
const htmlContent =
|
||||
await this.saleReceiptApplication.getSaleReceiptHtml(id);
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ export class CreateSaleReceipt {
|
||||
|
||||
@Inject(Customer.name)
|
||||
private readonly customerModel: TenantModelProxy<typeof Customer>,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Creates a new sale receipt with associated entries.
|
||||
@@ -89,7 +89,7 @@ export class CreateSaleReceipt {
|
||||
|
||||
// Inserts the sale receipt graph to the storage.
|
||||
const saleReceipt = await this.saleReceiptModel()
|
||||
.query()
|
||||
.query(trx)
|
||||
.upsertGraph({
|
||||
...saleReceiptObj,
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common';
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { UsersApplication } from './Users.application';
|
||||
import { InviteUserDto, SendInviteUserDto } from './dtos/InviteUser.dto';
|
||||
@@ -38,7 +38,7 @@ export class UsersInviteController {
|
||||
/**
|
||||
* Send an invitation to a new user.
|
||||
*/
|
||||
@Post()
|
||||
@Patch()
|
||||
@ApiOperation({ summary: 'Send an invitation to a new user.' })
|
||||
async sendInvite(@Body() sendInviteDTO: SendInviteUserDto) {
|
||||
const result = await this.usersApplication.sendInvite(sendInviteDTO);
|
||||
|
||||
@@ -18,7 +18,7 @@ export class EditUserService {
|
||||
private readonly tenantUserModel: TenantModelProxy<typeof TenantUser>,
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
private readonly tenancyContext: TenancyContext,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Creates a new user.
|
||||
@@ -52,7 +52,10 @@ export class EditUserService {
|
||||
const tenantUser = await this.tenantUserModel()
|
||||
.query()
|
||||
.updateAndFetchById(userId, {
|
||||
...editUserDTO,
|
||||
firstName: editUserDTO.firstName,
|
||||
lastName: editUserDTO.lastName,
|
||||
email: editUserDTO.email,
|
||||
roleId: editUserDTO.roleId,
|
||||
});
|
||||
// Triggers `onTenantUserEdited` event.
|
||||
await this.eventEmitter.emitAsync(events.tenantUser.onEdited, {
|
||||
|
||||
@@ -2,19 +2,35 @@ import { Injectable } from '@nestjs/common';
|
||||
import { DeleteRefundVendorCreditService } from './commands/DeleteRefundVendorCredit.service';
|
||||
import { RefundVendorCredit } from './models/RefundVendorCredit';
|
||||
import { CreateRefundVendorCredit } from './commands/CreateRefundVendorCredit.service';
|
||||
import { IRefundVendorCreditDTO } from './types/VendorCreditRefund.types';
|
||||
import { RefundVendorCreditDto } from './dtos/RefundVendorCredit.dto';
|
||||
import { GetRefundVendorCreditsService } from './queries/GetRefundVendorCredits.service';
|
||||
import { IRefundVendorCreditPOJO } from './types/VendorCreditRefund.types';
|
||||
|
||||
@Injectable()
|
||||
export class VendorCreditsRefundApplication {
|
||||
/**
|
||||
* @param {CreateRefundVendorCredit} createRefundVendorCreditService
|
||||
* @param {DeleteRefundVendorCreditService} deleteRefundVendorCreditService
|
||||
* @param {GetRefundVendorCreditsService} getRefundVendorCreditsService
|
||||
*/
|
||||
constructor(
|
||||
private readonly createRefundVendorCreditService: CreateRefundVendorCredit,
|
||||
private readonly deleteRefundVendorCreditService: DeleteRefundVendorCreditService,
|
||||
) {}
|
||||
private readonly getRefundVendorCreditsService: GetRefundVendorCreditsService,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieve the vendor credit refunds graph.
|
||||
* @param {number} vendorCreditId - Vendor credit id.
|
||||
* @returns {Promise<IRefundVendorCreditPOJO[]>}
|
||||
*/
|
||||
public getVendorCreditRefunds(
|
||||
vendorCreditId: number,
|
||||
): Promise<IRefundVendorCreditPOJO[]> {
|
||||
return this.getRefundVendorCreditsService.getVendorCreditRefunds(
|
||||
vendorCreditId,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a refund vendor credit.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Delete, Param, Post } from '@nestjs/common';
|
||||
import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
|
||||
import { VendorCreditsRefundApplication } from './VendorCreditsRefund.application';
|
||||
import { RefundVendorCredit } from './models/RefundVendorCredit';
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
@@ -9,7 +9,22 @@ import { RefundVendorCreditDto } from './dtos/RefundVendorCredit.dto';
|
||||
export class VendorCreditsRefundController {
|
||||
constructor(
|
||||
private readonly vendorCreditsRefundApplication: VendorCreditsRefundApplication,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieve the vendor credit refunds graph.
|
||||
* @param {number} vendorCreditId - Vendor credit id.
|
||||
* @returns {Promise<IRefundVendorCreditPOJO[]>}
|
||||
*/
|
||||
@Get(':vendorCreditId/refund')
|
||||
@ApiOperation({ summary: 'Retrieve the vendor credit refunds graph.' })
|
||||
public getVendorCreditRefunds(
|
||||
@Param('vendorCreditId') vendorCreditId: string,
|
||||
) {
|
||||
return this.vendorCreditsRefundApplication.getVendorCreditRefunds(
|
||||
Number(vendorCreditId),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a refund vendor credit.
|
||||
@@ -17,7 +32,7 @@ export class VendorCreditsRefundController {
|
||||
* @param {IRefundVendorCreditDTO} refundVendorCreditDTO
|
||||
* @returns {Promise<RefundVendorCredit>}
|
||||
*/
|
||||
@Post(':vendorCreditId/refunds')
|
||||
@Post(':vendorCreditId/refund')
|
||||
@ApiOperation({ summary: 'Create a refund for the given vendor credit.' })
|
||||
public async createRefundVendorCredit(
|
||||
@Param('vendorCreditId') vendorCreditId: string,
|
||||
|
||||
@@ -6,15 +6,21 @@ import { VendorCreditsRefundApplication } from './VendorCreditsRefund.applicatio
|
||||
import { CreateRefundVendorCredit } from './commands/CreateRefundVendorCredit.service';
|
||||
import { WarehousesModule } from '../Warehouses/Warehouses.module';
|
||||
import { BranchesModule } from '../Branches/Branches.module';
|
||||
import { RefundVendorCreditGLEntries } from './commands/RefundVendorCreditGLEntries';
|
||||
import { RefundVendorCreditGLEntriesSubscriber } from './subscribers/RefundVendorCreditGLEntriesSubscriber';
|
||||
import { LedgerModule } from '../Ledger/Ledger.module';
|
||||
import { AccountsModule } from '../Accounts/Accounts.module';
|
||||
|
||||
@Module({
|
||||
imports: [WarehousesModule, BranchesModule],
|
||||
imports: [WarehousesModule, BranchesModule, LedgerModule, AccountsModule],
|
||||
providers: [
|
||||
GetRefundVendorCreditsService,
|
||||
DeleteRefundVendorCreditService,
|
||||
CreateRefundVendorCredit,
|
||||
VendorCreditsRefundApplication
|
||||
VendorCreditsRefundApplication,
|
||||
RefundVendorCreditGLEntries,
|
||||
RefundVendorCreditGLEntriesSubscriber,
|
||||
],
|
||||
controllers: [VendorCreditsRefundController],
|
||||
})
|
||||
export class VendorCreditsRefundModule {}
|
||||
export class VendorCreditsRefundModule { }
|
||||
|
||||
@@ -1,159 +1,172 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import { Knex } from 'knex';
|
||||
// import { AccountNormal, ILedgerEntry } from '@/interfaces';
|
||||
// import { IRefundVendorCredit } from '@/interfaces';
|
||||
// import JournalPosterService from '@/services/Sales/JournalPosterService';
|
||||
// import LedgerRepository from '@/services/Ledger/LedgerRepository';
|
||||
// import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { LedgerStorageService } from '@/modules/Ledger/LedgerStorage.service';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { RefundVendorCredit } from '../models/RefundVendorCredit';
|
||||
import { Ledger } from '@/modules/Ledger/Ledger';
|
||||
import { Knex } from 'knex';
|
||||
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
|
||||
import { Account } from '@/modules/Accounts/models/Account.model';
|
||||
import { ILedgerEntry } from '@/modules/Ledger/types/Ledger.types';
|
||||
import { AccountNormal } from '@/interfaces/Account';
|
||||
import { AccountRepository } from '@/modules/Accounts/repositories/Account.repository';
|
||||
|
||||
// @Service()
|
||||
// export default class RefundVendorCreditGLEntries {
|
||||
// @Inject()
|
||||
// private journalService: JournalPosterService;
|
||||
@Injectable()
|
||||
export class RefundVendorCreditGLEntries {
|
||||
constructor(
|
||||
private readonly ledgerStorage: LedgerStorageService,
|
||||
private readonly accountRepository: AccountRepository,
|
||||
|
||||
// @Inject()
|
||||
// private ledgerRepository: LedgerRepository;
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: TenantModelProxy<typeof Account>,
|
||||
|
||||
// @Inject()
|
||||
// private tenancy: HasTenancyService;
|
||||
@Inject(RefundVendorCredit.name)
|
||||
private readonly refundVendorCreditModel: TenantModelProxy<
|
||||
typeof RefundVendorCredit
|
||||
>,
|
||||
) { }
|
||||
|
||||
// /**
|
||||
// * Retrieves the refund credit common GL entry.
|
||||
// * @param {IRefundVendorCredit} refundCredit
|
||||
// */
|
||||
// private getRefundCreditGLCommonEntry = (
|
||||
// refundCredit: IRefundVendorCredit
|
||||
// ) => {
|
||||
// return {
|
||||
// exchangeRate: refundCredit.exchangeRate,
|
||||
// currencyCode: refundCredit.currencyCode,
|
||||
/**
|
||||
* Retrieves the refund vendor credit common GL entry.
|
||||
* @param {RefundVendorCredit} refundVendorCredit
|
||||
* @returns
|
||||
*/
|
||||
private getRefundVendorCreditCommonGLEntry = (
|
||||
refundVendorCredit: RefundVendorCredit,
|
||||
) => {
|
||||
const model = refundVendorCredit as any;
|
||||
return {
|
||||
currencyCode: refundVendorCredit.currencyCode,
|
||||
exchangeRate: refundVendorCredit.exchangeRate,
|
||||
|
||||
// transactionType: 'RefundVendorCredit',
|
||||
// transactionId: refundCredit.id,
|
||||
transactionType: 'RefundVendorCredit',
|
||||
transactionId: refundVendorCredit.id,
|
||||
date: refundVendorCredit.date,
|
||||
userId: refundVendorCredit.vendorCredit?.userId,
|
||||
|
||||
// date: refundCredit.date,
|
||||
// userId: refundCredit.userId,
|
||||
// referenceNumber: refundCredit.referenceNo,
|
||||
// createdAt: refundCredit.createdAt,
|
||||
// indexGroup: 10,
|
||||
referenceNumber: refundVendorCredit.referenceNo,
|
||||
|
||||
// credit: 0,
|
||||
// debit: 0,
|
||||
createdAt: model.createdAt,
|
||||
indexGroup: 10,
|
||||
|
||||
// note: refundCredit.description,
|
||||
// branchId: refundCredit.branchId,
|
||||
// };
|
||||
// };
|
||||
credit: 0,
|
||||
debit: 0,
|
||||
|
||||
// /**
|
||||
// * Retrieves the refund credit payable GL entry.
|
||||
// * @param {IRefundVendorCredit} refundCredit
|
||||
// * @param {number} APAccountId
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getRefundCreditGLPayableEntry = (
|
||||
// refundCredit: IRefundVendorCredit,
|
||||
// APAccountId: number
|
||||
// ): ILedgerEntry => {
|
||||
// const commonEntry = this.getRefundCreditGLCommonEntry(refundCredit);
|
||||
note: refundVendorCredit.description,
|
||||
branchId: refundVendorCredit.branchId,
|
||||
};
|
||||
};
|
||||
|
||||
// return {
|
||||
// ...commonEntry,
|
||||
// credit: refundCredit.amount,
|
||||
// accountId: APAccountId,
|
||||
// contactId: refundCredit.vendorCredit.vendorId,
|
||||
// index: 1,
|
||||
// accountNormal: AccountNormal.CREDIT,
|
||||
// };
|
||||
// };
|
||||
/**
|
||||
* Retrieves the refund vendor credit payable GL entry.
|
||||
* @param {RefundVendorCredit} refundVendorCredit
|
||||
* @param {number} APAccountId
|
||||
* @returns {ILedgerEntry}
|
||||
*/
|
||||
private getRefundVendorCreditGLPayableEntry = (
|
||||
refundVendorCredit: RefundVendorCredit,
|
||||
APAccountId: number,
|
||||
): ILedgerEntry => {
|
||||
const commonEntry = this.getRefundVendorCreditCommonGLEntry(
|
||||
refundVendorCredit,
|
||||
);
|
||||
|
||||
// /**
|
||||
// * Retrieves the refund credit deposit GL entry.
|
||||
// * @param {IRefundVendorCredit} refundCredit
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getRefundCreditGLDepositEntry = (
|
||||
// refundCredit: IRefundVendorCredit
|
||||
// ): ILedgerEntry => {
|
||||
// const commonEntry = this.getRefundCreditGLCommonEntry(refundCredit);
|
||||
return {
|
||||
...commonEntry,
|
||||
credit: refundVendorCredit.amount,
|
||||
accountId: APAccountId,
|
||||
contactId: refundVendorCredit.vendorCredit.vendorId,
|
||||
index: 1,
|
||||
accountNormal: AccountNormal.CREDIT,
|
||||
};
|
||||
};
|
||||
|
||||
// return {
|
||||
// ...commonEntry,
|
||||
// debit: refundCredit.amount,
|
||||
// accountId: refundCredit.depositAccountId,
|
||||
// index: 2,
|
||||
// accountNormal: AccountNormal.DEBIT,
|
||||
// };
|
||||
// };
|
||||
/**
|
||||
* Retrieves the refund vendor credit deposit GL entry.
|
||||
* @param {RefundVendorCredit} refundVendorCredit
|
||||
* @returns {ILedgerEntry}
|
||||
*/
|
||||
private getRefundVendorCreditGLDepositEntry = (
|
||||
refundVendorCredit: RefundVendorCredit,
|
||||
): ILedgerEntry => {
|
||||
const commonEntry = this.getRefundVendorCreditCommonGLEntry(
|
||||
refundVendorCredit,
|
||||
);
|
||||
|
||||
// /**
|
||||
// * Retrieve refund vendor credit GL entries.
|
||||
// * @param {IRefundVendorCredit} refundCredit
|
||||
// * @param {number} APAccountId
|
||||
// * @returns {ILedgerEntry[]}
|
||||
// */
|
||||
// public getRefundCreditGLEntries = (
|
||||
// refundCredit: IRefundVendorCredit,
|
||||
// APAccountId: number
|
||||
// ): ILedgerEntry[] => {
|
||||
// const payableEntry = this.getRefundCreditGLPayableEntry(
|
||||
// refundCredit,
|
||||
// APAccountId
|
||||
// );
|
||||
// const depositEntry = this.getRefundCreditGLDepositEntry(refundCredit);
|
||||
return {
|
||||
...commonEntry,
|
||||
debit: refundVendorCredit.amount,
|
||||
accountId: refundVendorCredit.depositAccountId,
|
||||
index: 2,
|
||||
accountNormal: AccountNormal.DEBIT,
|
||||
};
|
||||
};
|
||||
|
||||
// return [payableEntry, depositEntry];
|
||||
// };
|
||||
/**
|
||||
* Retrieve refund vendor credit GL entries.
|
||||
* @param {RefundVendorCredit} refundVendorCredit
|
||||
* @param {number} APAccountId
|
||||
* @returns {ILedgerEntry[]}
|
||||
*/
|
||||
public getRefundVendorCreditGLEntries(
|
||||
refundVendorCredit: RefundVendorCredit,
|
||||
APAccountId: number,
|
||||
): ILedgerEntry[] {
|
||||
const payableEntry = this.getRefundVendorCreditGLPayableEntry(
|
||||
refundVendorCredit,
|
||||
APAccountId,
|
||||
);
|
||||
const depositEntry = this.getRefundVendorCreditGLDepositEntry(
|
||||
refundVendorCredit,
|
||||
);
|
||||
|
||||
// /**
|
||||
// * Saves refund credit note GL entries.
|
||||
// * @param {number} tenantId
|
||||
// * @param {IRefundVendorCredit} refundCredit -
|
||||
// * @param {Knex.Transaction} trx -
|
||||
// * @return {Promise<void>}
|
||||
// */
|
||||
// public saveRefundCreditGLEntries = async (
|
||||
// tenantId: number,
|
||||
// refundCreditId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ): Promise<void> => {
|
||||
// const { Account, RefundVendorCredit } = this.tenancy.models(tenantId);
|
||||
return [payableEntry, depositEntry];
|
||||
}
|
||||
|
||||
// // Retireve refund with associated vendor credit entity.
|
||||
// const refundCredit = await RefundVendorCredit.query()
|
||||
// .findById(refundCreditId)
|
||||
// .withGraphFetched('vendorCredit');
|
||||
/**
|
||||
* Creates refund vendor credit GL entries.
|
||||
* @param {number} refundVendorCreditId
|
||||
* @param {Knex.Transaction} trx
|
||||
*/
|
||||
public createRefundVendorCreditGLEntries = async (
|
||||
refundVendorCreditId: number,
|
||||
trx?: Knex.Transaction,
|
||||
) => {
|
||||
// Retrieve the refund with associated vendor credit.
|
||||
const refundVendorCredit = await this.refundVendorCreditModel()
|
||||
.query(trx)
|
||||
.findById(refundVendorCreditId)
|
||||
.withGraphFetched('vendorCredit');
|
||||
|
||||
// const payableAccount = await Account.query().findOne(
|
||||
// 'slug',
|
||||
// 'accounts-payable'
|
||||
// );
|
||||
// // Generates the GL entries of the given refund credit.
|
||||
// const entries = this.getRefundCreditGLEntries(
|
||||
// refundCredit,
|
||||
// payableAccount.id
|
||||
// );
|
||||
// // Saves the ledegr to the storage.
|
||||
// await this.ledgerRepository.saveLedgerEntries(tenantId, entries, trx);
|
||||
// };
|
||||
// Retrieve the payable account (A/P) account based on the given currency.
|
||||
const APAccount = await this.accountRepository.findOrCreateAccountsPayable(
|
||||
refundVendorCredit.currencyCode,
|
||||
{},
|
||||
trx,
|
||||
);
|
||||
|
||||
// /**
|
||||
// * Reverts refund credit note GL entries.
|
||||
// * @param {number} tenantId
|
||||
// * @param {number} refundCreditId
|
||||
// * @param {Knex.Transaction} trx
|
||||
// * @return {Promise<void>}
|
||||
// */
|
||||
// public revertRefundCreditGLEntries = async (
|
||||
// tenantId: number,
|
||||
// refundCreditId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ) => {
|
||||
// await this.journalService.revertJournalTransactions(
|
||||
// tenantId,
|
||||
// refundCreditId,
|
||||
// 'RefundVendorCredit',
|
||||
// trx
|
||||
// );
|
||||
// };
|
||||
// }
|
||||
// Retrieve refund vendor credit GL entries.
|
||||
const refundGLEntries = this.getRefundVendorCreditGLEntries(
|
||||
refundVendorCredit,
|
||||
APAccount.id,
|
||||
);
|
||||
const ledger = new Ledger(refundGLEntries);
|
||||
|
||||
// Saves refund ledger entries.
|
||||
await this.ledgerStorage.commit(ledger, trx);
|
||||
};
|
||||
|
||||
/**
|
||||
* Reverts refund vendor credit GL entries.
|
||||
* @param {number} refundVendorCreditId
|
||||
* @param {Knex.Transaction} trx
|
||||
*/
|
||||
public revertRefundVendorCreditGLEntries = async (
|
||||
refundVendorCreditId: number,
|
||||
trx?: Knex.Transaction,
|
||||
) => {
|
||||
await this.ledgerStorage.deleteByReference(
|
||||
refundVendorCreditId,
|
||||
'RefundVendorCredit',
|
||||
trx,
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { IsOptional, ToNumber } from '@/common/decorators/Validators';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { Min } from 'class-validator';
|
||||
import { IsDateString, Min } from 'class-validator';
|
||||
import { IsString } from 'class-validator';
|
||||
import { IsDate } from 'class-validator';
|
||||
import { IsNotEmpty, IsNumber, IsOptional, IsPositive } from 'class-validator';
|
||||
import { IsNotEmpty, IsNumber, IsPositive } from 'class-validator';
|
||||
|
||||
export class RefundVendorCreditDto {
|
||||
@ToNumber()
|
||||
@IsNumber()
|
||||
@IsNotEmpty()
|
||||
@Min(0)
|
||||
@@ -32,6 +34,7 @@ export class RefundVendorCreditDto {
|
||||
})
|
||||
depositAccountId: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({
|
||||
@@ -40,7 +43,7 @@ export class RefundVendorCreditDto {
|
||||
})
|
||||
description: string;
|
||||
|
||||
@IsDate()
|
||||
@IsDateString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({
|
||||
description: 'The date of the refund',
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { events } from '@/common/events/events';
|
||||
import { RefundVendorCreditGLEntries } from '../commands/RefundVendorCreditGLEntries';
|
||||
import {
|
||||
IRefundVendorCreditCreatedPayload,
|
||||
IRefundVendorCreditDeletedPayload,
|
||||
} from '../types/VendorCreditRefund.types';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { OnEvent } from '@nestjs/event-emitter';
|
||||
|
||||
@Injectable()
|
||||
export class RefundVendorCreditGLEntriesSubscriber {
|
||||
constructor(
|
||||
private readonly refundVendorCreditGLEntries: RefundVendorCreditGLEntries,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Writes refund vendor credit GL entries once the transaction created.
|
||||
* @param {IRefundVendorCreditCreatedPayload} payload -
|
||||
*/
|
||||
@OnEvent(events.vendorCredit.onRefundCreated)
|
||||
async writeRefundVendorCreditGLEntriesOnceCreated({
|
||||
trx,
|
||||
refundVendorCredit,
|
||||
vendorCredit,
|
||||
}: IRefundVendorCreditCreatedPayload) {
|
||||
await this.refundVendorCreditGLEntries.createRefundVendorCreditGLEntries(
|
||||
refundVendorCredit.id,
|
||||
trx,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverts refund vendor credit GL entries once the transaction deleted.
|
||||
* @param {IRefundVendorCreditDeletedPayload} payload -
|
||||
*/
|
||||
@OnEvent(events.vendorCredit.onRefundDeleted)
|
||||
async revertRefundVendorCreditGLEntriesOnceDeleted({
|
||||
trx,
|
||||
refundCreditId,
|
||||
oldRefundCredit,
|
||||
}: IRefundVendorCreditDeletedPayload) {
|
||||
await this.refundVendorCreditGLEntries.revertRefundVendorCreditGLEntries(
|
||||
refundCreditId,
|
||||
trx,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Controller, Get, Param } from '@nestjs/common';
|
||||
import { WarehousesApplication } from './WarehousesApplication.service';
|
||||
import {
|
||||
ApiOperation,
|
||||
ApiParam,
|
||||
ApiResponse,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
|
||||
@Controller('items')
|
||||
@ApiTags('Warehouses')
|
||||
@ApiCommonHeaders()
|
||||
export class WarehouseItemsController {
|
||||
constructor(private warehousesApplication: WarehousesApplication) { }
|
||||
|
||||
@Get(':id/warehouses')
|
||||
@ApiOperation({
|
||||
summary: 'Retrieves the item associated warehouses.',
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
'The item associated warehouses have been successfully retrieved.',
|
||||
})
|
||||
@ApiResponse({ status: 404, description: 'The item not found.' })
|
||||
@ApiParam({
|
||||
name: 'id',
|
||||
required: true,
|
||||
type: Number,
|
||||
description: 'The item id',
|
||||
})
|
||||
getItemWarehouses(@Param('id') itemId: string) {
|
||||
return this.warehousesApplication.getItemWarehouses(Number(itemId));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,10 +85,4 @@ export class WarehousesController {
|
||||
markWarehousePrimary(@Param('id') warehouseId: string) {
|
||||
return this.warehousesApplication.markWarehousePrimary(Number(warehouseId));
|
||||
}
|
||||
|
||||
@Get('items/:itemId')
|
||||
@ApiOperation({ summary: 'Get item warehouses' })
|
||||
getItemWarehouses(@Param('itemId') itemId: string) {
|
||||
return this.warehousesApplication.getItemWarehouses(Number(itemId));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { CreateWarehouse } from './commands/CreateWarehouse.service';
|
||||
import { EditWarehouse } from './commands/EditWarehouse.service';
|
||||
import { DeleteWarehouseService } from './commands/DeleteWarehouse.service';
|
||||
import { WarehousesController } from './Warehouses.controller';
|
||||
import { WarehouseItemsController } from './WarehouseItems.controller';
|
||||
import { GetWarehouse } from './queries/GetWarehouse';
|
||||
import { WarehouseMarkPrimary } from './commands/WarehouseMarkPrimary.service';
|
||||
import { GetWarehouses } from './queries/GetWarehouses';
|
||||
@@ -47,7 +48,7 @@ const models = [RegisterTenancyModel(Warehouse)];
|
||||
|
||||
@Module({
|
||||
imports: [TenancyDatabaseModule, ...models],
|
||||
controllers: [WarehousesController],
|
||||
controllers: [WarehousesController, WarehouseItemsController],
|
||||
providers: [
|
||||
CreateWarehouse,
|
||||
EditWarehouse,
|
||||
@@ -90,6 +91,6 @@ const models = [RegisterTenancyModel(Warehouse)];
|
||||
InventoryTransactionsWarehouses,
|
||||
ValidateWarehouseExistance
|
||||
],
|
||||
exports: [WarehousesSettings, WarehouseTransactionDTOTransform, ...models],
|
||||
exports: [WarehousesSettings, WarehouseTransactionDTOTransform, WarehousesApplication, ...models],
|
||||
})
|
||||
export class WarehousesModule {}
|
||||
|
||||
182
packages/server/test/accounts.e2e-spec.ts
Normal file
182
packages/server/test/accounts.e2e-spec.ts
Normal file
@@ -0,0 +1,182 @@
|
||||
import * as request from 'supertest';
|
||||
import { faker } from '@faker-js/faker';
|
||||
import {
|
||||
app,
|
||||
AuthorizationHeader,
|
||||
orgainzationId,
|
||||
} from './init-app-test';
|
||||
|
||||
const makeAccountRequest = () => ({
|
||||
name: `${faker.finance.accountName()} ${Date.now()}-${faker.string.alphanumeric({ length: 4 })}`,
|
||||
accountType: 'cash',
|
||||
code: faker.string.alphanumeric({ length: 6 }).toUpperCase(),
|
||||
});
|
||||
|
||||
describe.only('Accounts (e2e)', () => {
|
||||
it('/accounts (POST)', () => {
|
||||
return request(app.getHttpServer())
|
||||
.post('/accounts')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send(makeAccountRequest())
|
||||
.expect(201);
|
||||
});
|
||||
|
||||
it('/accounts (GET)', () => {
|
||||
return request(app.getHttpServer())
|
||||
.get('/accounts')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('/accounts/:id (GET)', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.post('/accounts')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send(makeAccountRequest())
|
||||
.expect(201);
|
||||
|
||||
const accountId = response.body.id;
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.get(`/accounts/${accountId}`)
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('/accounts/:id (PUT)', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.post('/accounts')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send(makeAccountRequest())
|
||||
.expect(201);
|
||||
const accountId = response.body.id;
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.put(`/accounts/${accountId}`)
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send(makeAccountRequest())
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('/accounts/:id (DELETE)', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.post('/accounts')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send(makeAccountRequest())
|
||||
.expect(201);
|
||||
const accountId = response.body.id;
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.delete(`/accounts/${accountId}`)
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('/accounts/:id/activate (POST)', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.post('/accounts')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send({
|
||||
...makeAccountRequest(),
|
||||
active: false,
|
||||
})
|
||||
.expect(201);
|
||||
const accountId = response.body.id;
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post(`/accounts/${accountId}/activate`)
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('/accounts/:id/inactivate (POST)', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.post('/accounts')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send({
|
||||
...makeAccountRequest(),
|
||||
active: true,
|
||||
})
|
||||
.expect(201);
|
||||
const accountId = response.body.id;
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post(`/accounts/${accountId}/inactivate`)
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('/accounts/types (GET)', () => {
|
||||
return request(app.getHttpServer())
|
||||
.get('/accounts/types')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('/accounts/validate-bulk-delete (POST)', async () => {
|
||||
const response1 = await request(app.getHttpServer())
|
||||
.post('/accounts')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send(makeAccountRequest())
|
||||
.expect(201);
|
||||
const accountId1 = response1.body.id;
|
||||
|
||||
const response2 = await request(app.getHttpServer())
|
||||
.post('/accounts')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send(makeAccountRequest())
|
||||
.expect(201);
|
||||
const accountId2 = response2.body.id;
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post('/accounts/validate-bulk-delete')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send({
|
||||
ids: [accountId1, accountId2],
|
||||
})
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('/accounts/bulk-delete (POST)', async () => {
|
||||
const response1 = await request(app.getHttpServer())
|
||||
.post('/accounts')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send(makeAccountRequest())
|
||||
.expect(201);
|
||||
const accountId1 = response1.body.id;
|
||||
|
||||
const response2 = await request(app.getHttpServer())
|
||||
.post('/accounts')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send(makeAccountRequest())
|
||||
.expect(201);
|
||||
const accountId2 = response2.body.id;
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post('/accounts/bulk-delete')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send({
|
||||
ids: [accountId1, accountId2],
|
||||
})
|
||||
.expect(200);
|
||||
});
|
||||
});
|
||||
24
packages/server/test/api-keys.e2e-spec.ts
Normal file
24
packages/server/test/api-keys.e2e-spec.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import * as request from 'supertest';
|
||||
import { faker } from '@faker-js/faker';
|
||||
import { app, AuthorizationHeader, orgainzationId } from './init-app-test';
|
||||
|
||||
describe('API Keys (e2e)', () => {
|
||||
it('/api-keys (GET)', () => {
|
||||
return request(app.getHttpServer())
|
||||
.get('/api-keys')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('/api-keys/generate (POST)', () => {
|
||||
return request(app.getHttpServer())
|
||||
.post('/api-keys/generate')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.send({
|
||||
name: faker.string.alphanumeric(10),
|
||||
})
|
||||
.expect(201);
|
||||
});
|
||||
});
|
||||
12
packages/server/test/attachments.e2e-spec.ts
Normal file
12
packages/server/test/attachments.e2e-spec.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import * as request from 'supertest';
|
||||
import { app, AuthorizationHeader, orgainzationId } from './init-app-test';
|
||||
|
||||
describe('Attachments (e2e)', () => {
|
||||
it('/attachments/:id/presigned-url (GET)', () => {
|
||||
return request(app.getHttpServer())
|
||||
.get('/attachments/test-id/presigned-url')
|
||||
.set('organization-id', orgainzationId)
|
||||
.set('Authorization', AuthorizationHeader)
|
||||
.expect(200);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user