Compare commits

..

1 Commits

Author SHA1 Message Date
Ahmed Bouhuolia
1d42a1c67a refactor(webapp): bound Formik fields across all components 2026-01-01 16:24:00 +02:00
318 changed files with 2425 additions and 5955 deletions

View File

@@ -1,93 +0,0 @@
# Dependencies
node_modules/
**/node_modules/
.pnpm-store/
# Build outputs
dist/
build/
**/dist/
**/build/
*.tsbuildinfo
# Development files
.git/
.gitignore
.vscode/
.idea/
*.swp
*.swo
*~
# Test files
test/
**/test/
**/*.spec.ts
**/*.test.ts
**/*.e2e-spec.ts
coverage/
.nyc_output/
test-results/
playwright-report/
# Documentation
*.md
!README.md
docs/
CHANGELOG.md
CONTRIBUTING.md
DISCLAIMER
LICENSE
# CI/CD
.github/
.gitpod.yml
# Environment files
.env
.env.*
!.env.example
# Logs
*.log
logs/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# OS files
.DS_Store
Thumbs.db
*.pid
*.seed
*.pid.lock
# Docker files (don't copy Dockerfiles into themselves)
docker-compose*.yml
Dockerfile*
.dockerignore
# Misc
.cache/
.temp/
tmp/
*.tmp
.qodo/
e2e/
playwright.config.ts
# Source maps (not needed in production)
*.map
# TypeScript configs (not needed at runtime)
tsconfig*.json
!tsconfig.json
# Linting/formatting
.eslintrc*
.prettierrc*
.eslintcache
# Package manager locks (we copy them explicitly)
# pnpm-lock.yaml

View File

@@ -35,10 +35,17 @@ 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=

View File

@@ -32,9 +32,11 @@ services:
- '3000'
links:
- mysql
- mongo
- redis
depends_on:
- mysql
- mongo
- redis
restart: on-failure
networks:
@@ -58,21 +60,22 @@ services:
# System database
- SYSTEM_DB_NAME=${SYSTEM_DB_NAME}
# Redis
- REDIS_HOST=redis
- REDIS_PORT=6379
- QUEUE_HOST=redis
- QUEUE_PORT=6379
# Tenants databases
- TENANT_DB_NAME_PERFIX=${TENANT_DB_NAME_PERFIX}
# 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}
@@ -119,7 +122,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}
@@ -163,6 +166,17 @@ 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
@@ -188,6 +202,10 @@ volumes:
name: bigcapital_prod_mysql
driver: local
mongo:
name: bigcapital_prod_mongo
driver: local
redis:
name: bigcapital_prod_redis
driver: local

View File

@@ -24,13 +24,25 @@ 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:
@@ -40,7 +52,7 @@ services:
gotenberg:
image: gotenberg/gotenberg:7
ports:
- '9000:3000'
- "9000:3000"
# Volumes
volumes:
@@ -48,6 +60,10 @@ volumes:
name: bigcapital_dev_mysql
driver: local
mongo:
name: bigcapital_dev_mongo
driver: local
redis:
name: bigcapital_dev_redis
driver: local
driver: local

View File

@@ -35,4 +35,4 @@ WORKDIR /app/packages/server
RUN git clone https://github.com/vishnubob/wait-for-it.git
# Once we listen the mysql port run the migration task.
CMD ./wait-for-it/wait-for-it.sh mysql:3306 -- sh -c "node dist/cli.js system:migrate:latest && node dist/cli.js tenants:migrate:latest"
CMD ./wait-for-it/wait-for-it.sh mysql:3306 -- sh -c "node ./build/commands.js system:migrate:latest && node ./build/commands.js tenants:migrate:latest"

1
docker/mongo/Dockerfile Normal file
View File

@@ -0,0 +1 @@
FROM mongo:5.0

View File

@@ -35,10 +35,17 @@ 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=

View File

@@ -1,102 +0,0 @@
# Stage 1: Build
FROM node:18.16.0-alpine AS builder
WORKDIR /app
# Install pnpm
RUN npm install -g pnpm@8.10.2
# Install build dependencies
RUN apk add --no-cache python3 build-base chromium
# Set Python environment
ENV PYTHON=/usr/bin/python3
# Copy package files for dependency installation
COPY --chown=node:node package.json pnpm-lock.yaml pnpm-workspace.yaml lerna.json ./
COPY --chown=node:node packages/server/package.json ./packages/server/
COPY --chown=node:node shared/bigcapital-utils/package.json ./shared/bigcapital-utils/
COPY --chown=node:node shared/pdf-templates/package.json ./shared/pdf-templates/
COPY --chown=node:node shared/email-components/package.json ./shared/email-components/
# Install all dependencies (including devDependencies for build)
RUN pnpm install --frozen-lockfile
# Copy source code
COPY --chown=node:node ./packages/server ./packages/server
COPY --chown=node:node ./shared/bigcapital-utils ./shared/bigcapital-utils
COPY --chown=node:node ./shared/pdf-templates ./shared/pdf-templates
COPY --chown=node:node ./shared/email-components ./shared/email-components
# Build NestJS application
RUN pnpm run build:server --skip-nx-cache
# Stage 2: Production
FROM node:18.16.0-alpine AS production
WORKDIR /app
# Install pnpm for production
RUN npm install -g pnpm@8.10.2
# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nodejs -u 1001
# Install build dependencies for native modules (bcrypt, etc.)
RUN apk add --no-cache python3 build-base
# Set Python environment
ENV PYTHON=/usr/bin/python3
# Copy package files for production dependency installation
COPY --chown=nodejs:nodejs package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY --chown=nodejs:nodejs packages/server/package.json ./packages/server/
COPY --chown=nodejs:nodejs shared/bigcapital-utils/package.json ./shared/bigcapital-utils/
COPY --chown=nodejs:nodejs shared/pdf-templates/package.json ./shared/pdf-templates/
COPY --chown=nodejs:nodejs shared/email-components/package.json ./shared/email-components/
# Copy .husky directory (needed for husky install command)
COPY --chown=nodejs:nodejs .husky ./.husky
# Install only production dependencies
# Install husky temporarily so prepare script can run, then remove it
RUN pnpm add -D -w husky && \
pnpm install --prod --frozen-lockfile && \
pnpm remove -w husky && \
# Remove build dependencies to reduce image size
apk del python3 build-base
# Copy built application from builder stage
COPY --from=builder --chown=nodejs:nodejs /app/packages/server/dist ./packages/server/dist
# Copy static assets (i18n, public, static directories)
COPY --from=builder --chown=nodejs:nodejs /app/packages/server/src/i18n ./packages/server/dist/i18n
COPY --from=builder --chown=nodejs:nodejs /app/packages/server/public ./packages/server/public
COPY --from=builder --chown=nodejs:nodejs /app/packages/server/static ./packages/server/static
# Copy database migration files (needed for running migrations)
COPY --from=builder --chown=nodejs:nodejs /app/packages/server/src/database ./packages/server/src/database
# Copy built shared packages (dist folders and package.json for module resolution)
COPY --from=builder --chown=nodejs:nodejs /app/shared/bigcapital-utils/dist ./shared/bigcapital-utils/dist
COPY --from=builder --chown=nodejs:nodejs /app/shared/pdf-templates/dist ./shared/pdf-templates/dist
COPY --from=builder --chown=nodejs:nodejs /app/shared/email-components/dist ./shared/email-components/dist
# Set runtime environment variables (these should be provided at runtime via docker-compose or k8s)
ENV NODE_ENV=production
ENV NEW_RELIC_NO_CONFIG_FILE=true
ENV PORT=3000
# Switch to non-root user
USER nodejs
# Expose port
EXPOSE 3000
# Health check - uses /api/system_db ping endpoint
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
CMD node -e "require('http').get('http://localhost:3000/api/system_db', (r) => {process.exit(r.statusCode >= 200 && r.statusCode < 300 ? 0 : 1)}).on('error', () => process.exit(1))"
# Start the application
CMD [ "node", "packages/server/dist/main.js" ]

View File

@@ -2,23 +2,10 @@
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"entryFile": "main",
"compilerOptions": {
"deleteOutDir": true,
"assets": [
{ "include": "i18n/**/*", "watchAssets": true },
{ "include": "database/**/*", "exclude": "**/*.ts", "watchAssets": true }
{ "include": "i18n/**/*", "watchAssets": true }
]
},
"projects": {
"cli": {
"type": "application",
"root": "src",
"entryFile": "cli",
"sourceRoot": "src",
"compilerOptions": {
"tsConfigPath": "tsconfig.json"
}
}
}
}

View File

@@ -40,9 +40,6 @@
"@lemonsqueezy/lemonsqueezy.js": "^2.2.0",
"@liaoliaots/nestjs-redis": "^10.0.0",
"@nest-lab/throttler-storage-redis": "^1.1.0",
"@bull-board/api": "^5.22.0",
"@bull-board/express": "^5.22.0",
"@bull-board/nestjs": "^5.22.0",
"@nestjs/bull": "^10.2.1",
"@nestjs/bullmq": "^10.2.2",
"@nestjs/cache-manager": "^2.2.2",

View File

@@ -1,8 +0,0 @@
import { registerAs } from '@nestjs/config';
import { parseBoolean } from '@/utils/parse-boolean';
export default registerAs('bullBoard', () => ({
enabled: parseBoolean<boolean>(process.env.BULL_BOARD_ENABLED, false),
username: process.env.BULL_BOARD_USERNAME,
password: process.env.BULL_BOARD_PASSWORD,
}));

View File

@@ -17,9 +17,6 @@ import loops from './loops';
import bankfeed from './bankfeed';
import throttle from './throttle';
import cloud from './cloud';
import redis from './redis';
import queue from './queue';
import bullBoard from './bull-board';
export const config = [
app,
@@ -41,7 +38,4 @@ export const config = [
loops,
bankfeed,
throttle,
redis,
queue,
bullBoard,
];

View File

@@ -1,6 +0,0 @@
import { registerAs } from '@nestjs/config';
export default registerAs('queue', () => ({
host: process.env.QUEUE_HOST || 'localhost',
port: parseInt(process.env.QUEUE_PORT, 10) || 6379,
}));

View File

@@ -5,18 +5,15 @@ import {
NestInterceptor,
} from '@nestjs/common';
import { Observable, map } from 'rxjs';
import { mapValuesDeep } from '@/utils/deepdash';
import { mapValues, 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 !== null && value !== undefined && typeof value.toJSON === 'function') {
if (value && typeof value.toJSON === 'function') {
return value.toJSON();
}
return value;

View File

@@ -22,9 +22,6 @@
"field.status.unpaid": "Unpaid",
"field.status.opened": "Opened",
"field.status.draft": "Draft",
"field.created_at": "Created At",
"allocation_method": "Allocation Method",
"allocation_method.quantity": "Quantity",
"allocation_method.value": "Valuation"
"field.created_at": "Created At"
}

View File

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

View File

@@ -4,6 +4,10 @@ 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');
@@ -21,6 +25,11 @@ 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')
@@ -30,6 +39,9 @@ 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();

View File

@@ -1,59 +0,0 @@
import { Request, Response, NextFunction } from 'express';
/**
* Creates Express middleware for the Bull Board UI:
* - When disabled: responds with 404.
* - When enabled and username/password are set: enforces HTTP Basic Auth (401 if invalid).
* - When enabled and credentials are not set: allows access (no auth).
*/
export function createBullBoardAuthMiddleware(
enabled: boolean,
username: string | undefined,
password: string | undefined,
): (req: Request, res: Response, next: NextFunction) => void {
return (req: Request, res: Response, next: NextFunction) => {
if (!enabled) {
res.status(404).send('Not Found');
return;
}
if (!username || !password) {
return next();
}
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Basic ')) {
res.setHeader('WWW-Authenticate', 'Basic realm="Bull Board"');
res.status(401).send('Authentication required');
return;
}
const base64Credentials = authHeader.slice(6);
let decoded: string;
try {
decoded = Buffer.from(base64Credentials, 'base64').toString('utf8');
} catch {
res.setHeader('WWW-Authenticate', 'Basic realm="Bull Board"');
res.status(401).send('Invalid credentials');
return;
}
const colonIndex = decoded.indexOf(':');
if (colonIndex === -1) {
res.setHeader('WWW-Authenticate', 'Basic realm="Bull Board"');
res.status(401).send('Invalid credentials');
return;
}
const reqUsername = decoded.slice(0, colonIndex);
const reqPassword = decoded.slice(colonIndex + 1);
if (reqUsername !== username || reqPassword !== password) {
res.setHeader('WWW-Authenticate', 'Basic realm="Bull Board"');
res.status(401).send('Invalid credentials');
return;
}
next();
};
}

View File

@@ -48,30 +48,14 @@ 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();
dependentRelationNames.forEach((relationName: string) => {
relationNames.forEach((relationName: string) => {
recordQuery.withGraphFetched(relationName);
});
const record = await recordQuery;
const hasRelations = dependentRelationNames.some((name) => {
const hasRelations = relationNames.some((name) => {
const val = record[name];
return Array.isArray(val) ? val.length > 0 : val != null;
});

View File

@@ -8,7 +8,6 @@ import {
Query,
ParseIntPipe,
Put,
HttpCode,
} from '@nestjs/common';
import { AccountsApplication } from './AccountsApplication.service';
import { CreateAccountDTO } from './CreateAccount.dto';
@@ -44,7 +43,6 @@ 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.',
@@ -66,7 +64,6 @@ export class AccountsController {
}
@Post('bulk-delete')
@HttpCode(200)
@ApiOperation({ summary: 'Deletes multiple accounts in bulk.' })
@ApiResponse({
status: 200,
@@ -128,7 +125,6 @@ export class AccountsController {
}
@Post(':id/activate')
@HttpCode(200)
@ApiOperation({ summary: 'Activate the given account.' })
@ApiResponse({
status: 200,
@@ -146,7 +142,6 @@ export class AccountsController {
}
@Post(':id/inactivate')
@HttpCode(200)
@ApiOperation({ summary: 'Inactivate the given account.' })
@ApiResponse({
status: 200,

View File

@@ -18,7 +18,7 @@ export class DeleteAccount {
private eventEmitter: EventEmitter2,
private uow: UnitOfWork,
private validator: CommandAccountValidators,
) { }
) {}
/**
* Authorize account delete.
@@ -57,10 +57,7 @@ export class DeleteAccount {
trx?: Knex.Transaction,
): Promise<void> => {
// Retrieve account or not found service error.
const oldAccount = await this.accountModel()
.query()
.findById(accountId)
.throwIfNotFound();
const oldAccount = await this.accountModel().query().findById(accountId);
// Authorize before delete account.
await this.authorize(accountId, oldAccount);

View File

@@ -33,7 +33,6 @@ export class AccountTransaction extends BaseModel {
public readonly userId!: number;
public readonly itemId!: number;
public readonly projectId!: number;
public readonly costable!: boolean;
public readonly account: Account;
/**

View File

@@ -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, APP_PIPE, APP_FILTER } from '@nestjs/core';
import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { join } from 'path';
import { ServeStaticModule } from '@nestjs/serve-static';
import { RedisModule } from '@liaoliaots/nestjs-redis';
@@ -12,9 +12,6 @@ import {
I18nModule,
QueryResolver,
} from 'nestjs-i18n';
import { BullBoardModule } from '@bull-board/nestjs';
import { ExpressAdapter } from '@bull-board/express';
import { createBullBoardAuthMiddleware } from '@/middleware/bull-board-auth.middleware';
import { BullModule } from '@nestjs/bullmq';
import { ScheduleModule } from '@nestjs/schedule';
import { PassportModule } from '@nestjs/passport';
@@ -39,10 +36,6 @@ 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';
@@ -140,30 +133,12 @@ import { AppThrottleModule } from './AppThrottle.module';
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
connection: {
host: configService.get('queue.host'),
port: configService.get('queue.port'),
host: configService.get('QUEUE_HOST'),
port: configService.get('QUEUE_PORT'),
},
}),
inject: [ConfigService],
}),
BullBoardModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => {
const enabled = configService.get<boolean>('bullBoard.enabled');
const username = configService.get<string>('bullBoard.username');
const password = configService.get<string>('bullBoard.password');
return {
route: '/queues',
adapter: ExpressAdapter,
middleware: createBullBoardAuthMiddleware(
enabled,
username,
password,
),
};
},
inject: [ConfigService],
}),
ClsModule.forRoot({
global: true,
middleware: {
@@ -179,8 +154,8 @@ import { AppThrottleModule } from './AppThrottle.module';
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
config: {
host: configService.get('redis.host'),
port: configService.get('redis.port'),
host: configService.get('redis.host') || 'localhost',
port: configService.get('redis.port') || 6379,
},
}),
inject: [ConfigService],
@@ -259,10 +234,6 @@ import { AppThrottleModule } from './AppThrottle.module';
],
controllers: [AppController],
providers: [
{
provide: APP_PIPE,
useClass: ValidationPipe,
},
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
@@ -271,10 +242,6 @@ import { AppThrottleModule } from './AppThrottle.module';
provide: APP_INTERCEPTOR,
useClass: SerializeInterceptor,
},
{
provide: APP_INTERCEPTOR,
useClass: ToJsonInterceptor,
},
{
provide: APP_INTERCEPTOR,
useClass: UserIpInterceptor,
@@ -283,14 +250,6 @@ import { AppThrottleModule } from './AppThrottle.module';
provide: APP_INTERCEPTOR,
useClass: ExcludeNullInterceptor,
},
{
provide: APP_FILTER,
useClass: ServiceErrorFilter,
},
{
provide: APP_FILTER,
useClass: ModelHasRelationsFilter,
},
AppService,
],
})

View File

@@ -9,27 +9,6 @@ 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');

View File

@@ -17,8 +17,6 @@ import { PassportModule } from '@nestjs/passport';
import { APP_GUARD } from '@nestjs/core';
import { JwtAuthGuard } from './guards/jwt.guard';
import { AuthMailSubscriber } from './subscribers/AuthMail.subscriber';
import { BullBoardModule } from '@bull-board/nestjs';
import { BullMQAdapter } from '@bull-board/api/bullMQAdapter';
import { BullModule } from '@nestjs/bullmq';
import {
SendResetPasswordMailQueue,
@@ -65,14 +63,6 @@ const models = [
TenancyModule,
BullModule.registerQueue({ name: SendResetPasswordMailQueue }),
BullModule.registerQueue({ name: SendSignupVerificationMailQueue }),
BullBoardModule.forFeature({
name: SendResetPasswordMailQueue,
adapter: BullMQAdapter,
}),
BullBoardModule.forFeature({
name: SendSignupVerificationMailQueue,
adapter: BullMQAdapter,
}),
],
exports: [...models],
providers: [
@@ -108,4 +98,4 @@ const models = [
AuthMailSubscriber,
],
})
export class AuthModule {}
export class AuthModule { }

View File

@@ -1,6 +1,10 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Scope } from '@nestjs/common';
import { SendResetPasswordMailQueue } from '../Auth.constants';
import {
SendResetPasswordMailJob,
SendResetPasswordMailQueue,
} from '../Auth.constants';
import { Process } from '@nestjs/bull';
import { Job } from 'bullmq';
import { AuthenticationMailMesssages } from '../AuthMailMessages.esrvice';
import { MailTransporter } from '@/modules/Mail/MailTransporter.service';
@@ -19,6 +23,7 @@ export class SendResetPasswordMailProcessor extends WorkerHost {
super();
}
@Process(SendResetPasswordMailJob)
async process(job: Job<SendResetPasswordMailJobPayload>) {
try {
await this.authMailMesssages.sendResetPasswordMail(

View File

@@ -1,7 +1,11 @@
import { Scope } from '@nestjs/common';
import { Job } from 'bullmq';
import { Process } from '@nestjs/bull';
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { SendSignupVerificationMailQueue } from '../Auth.constants';
import {
SendSignupVerificationMailJob,
SendSignupVerificationMailQueue,
} from '../Auth.constants';
import { MailTransporter } from '@/modules/Mail/MailTransporter.service';
import { AuthenticationMailMesssages } from '../AuthMailMessages.esrvice';
@@ -17,6 +21,7 @@ export class SendSignupVerificationMailProcessor extends WorkerHost {
super();
}
@Process(SendSignupVerificationMailJob)
async process(job: Job<SendSignupVerificationMailJobPayload>) {
try {
await this.authMailMesssages.sendSignupVerificationMail(

View File

@@ -1,28 +1,16 @@
import { Controller, Get, Param, Post, Query } from '@nestjs/common';
import { BankAccountsApplication } from './BankAccountsApplication.service';
import { ApiOperation, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
import { BankAccountsQueryDto } from './dtos/BankAccountsQuery.dto';
import { BankAccountResponseDto } from './dtos/BankAccountResponse.dto';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { ICashflowAccountsFilter } from './types/BankAccounts.types';
@Controller('banking/accounts')
@ApiTags('Bank Accounts')
export class BankAccountsController {
constructor(private bankAccountsApplication: BankAccountsApplication) { }
constructor(private bankAccountsApplication: BankAccountsApplication) {}
@Get()
@ApiOperation({ summary: 'Retrieve the bank accounts.' })
@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) {
getBankAccounts(@Query() filterDto: ICashflowAccountsFilter) {
return this.bankAccountsApplication.getBankAccounts(filterDto);
}

View File

@@ -6,7 +6,6 @@ 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 {
@@ -17,13 +16,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: BankAccountsQueryDto) {
getBankAccounts(filterDto: ICashflowAccountsFilter) {
return this.getBankAccountsService.getCashflowAccounts(filterDto);
}

View File

@@ -1,166 +0,0 @@
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;
}

View File

@@ -1,107 +0,0 @@
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;
}

View File

@@ -6,8 +6,6 @@ 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 {
@@ -17,14 +15,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: BankAccountsQueryDto) {
public async getCashflowAccounts(filterDTO: ICashflowAccountsFilter) {
const _filterDto = {
sortOrder: 'desc',
columnSortBy: 'created_at',
@@ -32,14 +30,12 @@ export class GetBankAccountsService {
...filterDTO,
};
// Parsees accounts list filter DTO.
const filter = this.dynamicListService.parseStringifiedFilter<BankAccountsQueryDto>(
_filterDto,
);
const filter = this.dynamicListService.parseStringifiedFilter(_filterDto);
// Dynamic list service.
const dynamicList = await this.dynamicListService.dynamicList(
this.accountModel(),
filter as IDynamicListFilter,
filter,
);
// Retrieve accounts model based on the given query.
const accounts = await this.accountModel()

View File

@@ -1,5 +1,5 @@
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Body, Controller, Get, Param, Patch, Post, Query } from '@nestjs/common';
import { Body, Controller, Get, Param, 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 {
);
}
@Patch('/unmatch/:uncategorizedTransactionId')
@Post('/unmatch/:uncategorizedTransactionId')
@ApiOperation({ summary: 'Unmatch the given uncategorized transaction.' })
async unmatchMatchedTransaction(
@Param('uncategorizedTransactionId') uncategorizedTransactionId: number,

View File

@@ -1,5 +1,3 @@
import { BullBoardModule } from '@bull-board/nestjs';
import { BullMQAdapter } from '@bull-board/api/bullMQAdapter';
import { BullModule } from '@nestjs/bullmq';
import { Module } from '@nestjs/common';
import { SocketModule } from '../Socket/Socket.module';
@@ -35,10 +33,6 @@ const models = [RegisterTenancyModel(PlaidItem)];
BankingCategorizeModule,
BankingTransactionsModule,
BullModule.registerQueue({ name: UpdateBankingPlaidTransitionsQueueJob }),
BullBoardModule.forFeature({
name: UpdateBankingPlaidTransitionsQueueJob,
adapter: BullMQAdapter,
}),
...models,
],
providers: [
@@ -57,4 +51,4 @@ const models = [RegisterTenancyModel(PlaidItem)];
exports: [...models],
controllers: [BankingPlaidController, BankingPlaidWebhooksController],
})
export class BankingPlaidModule {}
export class BankingPlaidModule { }

View File

@@ -1,9 +1,11 @@
import { Process } from '@nestjs/bull';
import { UseCls } from 'nestjs-cls';
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Scope } from '@nestjs/common';
import { Job } from 'bullmq';
import {
PlaidFetchTransitonsEventPayload,
UpdateBankingPlaidTransitionsJob,
UpdateBankingPlaidTransitionsQueueJob,
} from '../types/BankingPlaid.types';
import { PlaidUpdateTransactions } from '../command/PlaidUpdateTransactions';
@@ -26,6 +28,7 @@ export class PlaidFetchTransactionsProcessor extends WorkerHost {
/**
* Triggers the function.
*/
@Process(UpdateBankingPlaidTransitionsJob)
@UseCls()
async process(job: Job<PlaidFetchTransitonsEventPayload>) {
const { plaidItemId } = job.data;

View File

@@ -10,8 +10,6 @@ import { BankingRecognizedTransactionsController } from './BankingRecognizedTran
import { RecognizedTransactionsApplication } from './RecognizedTransactions.application';
import { GetRecognizedTransactionsService } from './GetRecongizedTransactions';
import { GetRecognizedTransactionService } from './queries/GetRecognizedTransaction.service';
import { BullBoardModule } from '@bull-board/nestjs';
import { BullMQAdapter } from '@bull-board/api/bullMQAdapter';
import { BullModule } from '@nestjs/bullmq';
import { RecognizeUncategorizedTransactionsQueue } from './_types';
import { RegonizeTransactionsPrcessor } from './jobs/RecognizeTransactionsJob';
@@ -27,10 +25,6 @@ const models = [RegisterTenancyModel(RecognizedBankTransaction)];
BullModule.registerQueue({
name: RecognizeUncategorizedTransactionsQueue,
}),
BullBoardModule.forFeature({
name: RecognizeUncategorizedTransactionsQueue,
adapter: BullMQAdapter,
}),
...models,
],
providers: [

View File

@@ -7,6 +7,7 @@ import {
RecognizeUncategorizedTransactionsJobPayload,
RecognizeUncategorizedTransactionsQueue,
} from '../_types';
import { Process } from '@nestjs/bull';
@Processor({
name: RecognizeUncategorizedTransactionsQueue,
@@ -27,6 +28,7 @@ export class RegonizeTransactionsPrcessor extends WorkerHost {
/**
* Triggers sending invoice mail.
*/
@Process(RecognizeUncategorizedTransactionsQueue)
@UseCls()
async process(job: Job<RecognizeUncategorizedTransactionsJobPayload>) {
const { ruleId, transactionsCriteria } = job.data;

View File

@@ -4,8 +4,8 @@ import {
validateTransactionShouldBeExcluded,
} from './utils';
import {
IBankTransactionUnexcludedEventPayload,
IBankTransactionUnexcludingEventPayload,
IBankTransactionExcludedEventPayload,
IBankTransactionExcludingEventPayload,
} 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,8 +50,7 @@ export class UnexcludeBankTransactionService {
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
await this.eventEmitter.emitAsync(events.bankTransactions.onUnexcluding, {
uncategorizedTransactionId,
trx,
} as IBankTransactionUnexcludingEventPayload);
} as IBankTransactionExcludingEventPayload);
await this.uncategorizedBankTransactionModel()
.query(trx)
@@ -62,8 +61,7 @@ export class UnexcludeBankTransactionService {
await this.eventEmitter.emitAsync(events.bankTransactions.onUnexcluded, {
uncategorizedTransactionId,
trx,
} as IBankTransactionUnexcludedEventPayload);
} as IBankTransactionExcludedEventPayload);
});
}
}

View File

@@ -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(trx)
.query()
.findById(uncategorizedTransactionId);
//
await this.account()

View File

@@ -2,11 +2,9 @@ import { forwardRef, Module } from '@nestjs/common';
import { TransactionLandedCostEntriesService } from './TransactionLandedCostEntries.service';
import { AllocateLandedCostService } from './commands/AllocateLandedCost.service';
import { LandedCostGLEntriesSubscriber } from './commands/LandedCostGLEntries.subscriber';
import { LandedCostGLEntriesService } from './commands/LandedCostGLEntries.service';
// import { LandedCostGLEntries } from './commands/LandedCostGLEntries.service';
import { LandedCostSyncCostTransactions } from './commands/LandedCostSyncCostTransactions.service';
import { LedgerModule } from '../Ledger/Ledger.module';
import { LandedCostSyncCostTransactionsSubscriber } from './commands/LandedCostSyncCostTransactions.subscriber';
import { LandedCostInventoryTransactionsSubscriber } from './commands/LandedCostInventoryTransactions.subscriber';
import { BillAllocatedLandedCostTransactions } from './commands/BillAllocatedLandedCostTransactions.service';
import { BillAllocateLandedCostController } from './LandedCost.controller';
import { RevertAllocatedLandedCost } from './commands/RevertAllocatedLandedCost.service';
@@ -18,12 +16,12 @@ import { ExpenseLandedCost } from './commands/ExpenseLandedCost.service';
import { BillLandedCost } from './commands/BillLandedCost.service';
@Module({
imports: [forwardRef(() => InventoryCostModule), LedgerModule],
imports: [forwardRef(() => InventoryCostModule)],
providers: [
AllocateLandedCostService,
TransactionLandedCostEntriesService,
BillAllocatedLandedCostTransactions,
LandedCostGLEntriesService,
LandedCostGLEntriesSubscriber,
TransactionLandedCost,
BillLandedCost,
ExpenseLandedCost,
@@ -31,8 +29,6 @@ import { BillLandedCost } from './commands/BillLandedCost.service';
RevertAllocatedLandedCost,
LandedCostInventoryTransactions,
LandedCostTranasctions,
LandedCostGLEntriesSubscriber,
LandedCostInventoryTransactionsSubscriber,
LandedCostSyncCostTransactionsSubscriber,
],
exports: [TransactionLandedCostEntriesService],

View File

@@ -25,7 +25,7 @@ export class BillAllocateLandedCostController {
private billAllocatedCostTransactions: BillAllocatedLandedCostTransactions,
private revertAllocatedLandedCost: RevertAllocatedLandedCost,
private landedCostTransactions: LandedCostTranasctions,
) { }
) {}
@Get('/transactions')
@ApiOperation({ summary: 'Get landed cost transactions' })

View File

@@ -23,9 +23,7 @@ export class AllocateLandedCostService extends BaseLandedCostService {
private readonly billModel: TenantModelProxy<typeof Bill>,
@Inject(BillLandedCost.name)
protected readonly billLandedCostModel: TenantModelProxy<
typeof BillLandedCost
>,
protected readonly billLandedCostModel: TenantModelProxy<typeof BillLandedCost>
) {
super();
}
@@ -56,8 +54,7 @@ export class AllocateLandedCostService extends BaseLandedCostService {
const amount = this.getAllocateItemsCostTotal(allocateCostDTO);
// Retrieve the purchase invoice or throw not found error.
const bill = await this.billModel()
.query()
const bill = await this.billModel().query()
.findById(billId)
.withGraphFetched('entries')
.throwIfNotFound();
@@ -92,9 +89,8 @@ export class AllocateLandedCostService extends BaseLandedCostService {
// unit-of-work eniverment.
return this.uow.withTransaction(async (trx: Knex.Transaction) => {
// Save the bill landed cost model.
const billLandedCost = await this.billLandedCostModel()
.query(trx)
.insertGraph(billLandedCostObj);
const billLandedCost =
await BillLandedCost.query(trx).insertGraph(billLandedCostObj);
// Triggers `onBillLandedCostCreated` event.
await this.eventPublisher.emitAsync(events.billLandedCost.onCreated, {
bill,
@@ -107,5 +103,5 @@ export class AllocateLandedCostService extends BaseLandedCostService {
return billLandedCost;
});
}
};
}

View File

@@ -21,7 +21,7 @@ export class BillAllocatedLandedCostTransactions {
private readonly billLandedCostModel: TenantModelProxy<
typeof BillLandedCost
>,
) { }
) {}
/**
* Retrieve the bill associated landed cost transactions.
@@ -77,13 +77,6 @@ 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,
@@ -91,14 +84,12 @@ export class BillAllocatedLandedCostTransactions {
...omit(transaction, [
'allocatedFromBillEntry',
'allocatedFromExpenseEntry',
'allocationMethodFormatted',
]),
name,
description,
formattedLocalAmount: formatNumber(transaction.localAmount, {
currencyCode: 'USD',
}),
allocationMethodFormatted,
};
};

View File

@@ -1,188 +1,236 @@
import { Knex } from 'knex';
import { Inject, Injectable } from '@nestjs/common';
import * as moment from 'moment';
import { BaseLandedCostService } from '../BaseLandedCost.service';
import { BillLandedCost } from '../models/BillLandedCost';
import { Bill } from '@/modules/Bills/models/Bill';
import { BillLandedCostEntry } from '../models/BillLandedCostEntry';
import { ILedgerEntry } from '@/modules/Ledger/types/Ledger.types';
import { Ledger } from '@/modules/Ledger/Ledger';
import { LedgerStorageService } from '@/modules/Ledger/LedgerStorage.service';
import { AccountNormal } from '@/modules/Accounts/Accounts.types';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
// import * as R from 'ramda';
// import { Knex } from 'knex';
// import { Inject, Injectable } from '@nestjs/common';
// import { BaseLandedCostService } from '../BaseLandedCost.service';
// import { BillLandedCost } from '../models/BillLandedCost';
// import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
// import { Bill } from '@/modules/Bills/models/Bill';
// import { BillLandedCostEntry } from '../models/BillLandedCostEntry';
// import { ILedger, ILedgerEntry } from '@/modules/Ledger/types/Ledger.types';
// import { Ledger } from '@/modules/Ledger/Ledger';
// import { AccountNormal } from '@/interfaces/Account';
// import { ILandedCostTransactionEntry } from '../types/BillLandedCosts.types';
@Injectable()
export class LandedCostGLEntriesService extends BaseLandedCostService {
constructor(
private readonly ledgerStorage: LedgerStorageService,
// @Injectable()
// export class LandedCostGLEntries extends BaseLandedCostService {
// constructor(
// private readonly journalService: JournalPosterService,
// private readonly ledgerRepository: LedgerRepository,
@Inject(BillLandedCost.name)
protected readonly billLandedCostModel: TenantModelProxy<
typeof BillLandedCost
>,
) {
super();
}
// @Inject(BillLandedCost.name)
// private readonly billLandedCostModel: TenantModelProxy<typeof BillLandedCost>,
// ) {
// super();
// }
/**
* Retrieves the landed cost GL common entry.
*/
private getLandedCostGLCommonEntry(
bill: Bill,
allocatedLandedCost: BillLandedCost,
) {
return {
date: moment(bill.billDate).format('YYYY-MM-DD'),
currencyCode: allocatedLandedCost.currencyCode,
exchangeRate: allocatedLandedCost.exchangeRate,
// /**
// * Retrieves the landed cost GL common entry.
// * @param {IBill} bill
// * @param {IBillLandedCost} allocatedLandedCost
// * @returns
// */
// private getLandedCostGLCommonEntry = (
// bill: Bill,
// allocatedLandedCost: BillLandedCost
// ) => {
// return {
// date: bill.billDate,
// currencyCode: allocatedLandedCost.currencyCode,
// exchangeRate: allocatedLandedCost.exchangeRate,
transactionType: 'LandedCost',
transactionId: allocatedLandedCost.id,
transactionNumber: bill.billNumber,
// transactionType: 'LandedCost',
// transactionId: allocatedLandedCost.id,
// transactionNumber: bill.billNumber,
referenceNumber: bill.referenceNo,
// referenceNumber: bill.referenceNo,
branchId: bill.branchId,
projectId: bill.projectId,
// credit: 0,
// debit: 0,
// };
// };
credit: 0,
debit: 0,
};
}
// /**
// * Retrieves the landed cost GL inventory entry.
// * @param {IBill} bill
// * @param {IBillLandedCost} allocatedLandedCost
// * @param {IBillLandedCostEntry} allocatedEntry
// * @returns {ILedgerEntry}
// */
// private getLandedCostGLInventoryEntry = (
// bill: Bill,
// allocatedLandedCost: BillLandedCost,
// allocatedEntry: BillLandedCostEntry
// ): ILedgerEntry => {
// const commonEntry = this.getLandedCostGLCommonEntry(
// bill,
// allocatedLandedCost
// );
// return {
// ...commonEntry,
// debit: allocatedLandedCost.localAmount,
// accountId: allocatedEntry.itemEntry.item.inventoryAccountId,
// index: 1,
// accountNormal: AccountNormal.DEBIT,
// };
// };
/**
* Retrieves the landed cost GL inventory entry for an allocated item.
*/
private getLandedCostGLInventoryEntry(
bill: Bill,
allocatedLandedCost: BillLandedCost,
allocatedEntry: BillLandedCostEntry,
index: number,
): ILedgerEntry {
const commonEntry = this.getLandedCostGLCommonEntry(
bill,
allocatedLandedCost,
);
const itemEntry = (
allocatedEntry as BillLandedCostEntry & {
itemEntry?: {
item?: { type?: string; inventoryAccountId?: number };
costAccountId?: number;
itemId?: number;
};
}
).itemEntry;
const item = itemEntry?.item;
const isInventory = item && ['inventory'].indexOf(item.type) !== -1;
const accountId = isInventory
? item?.inventoryAccountId
: itemEntry?.costAccountId;
// /**
// * Retrieves the landed cost GL cost entry.
// * @param {IBill} bill
// * @param {IBillLandedCost} allocatedLandedCost
// * @param {ILandedCostTransactionEntry} fromTransactionEntry
// * @returns {ILedgerEntry}
// */
// private getLandedCostGLCostEntry = (
// bill: Bill,
// allocatedLandedCost: BillLandedCost,
// fromTransactionEntry: ILandedCostTransactionEntry
// ): ILedgerEntry => {
// const commonEntry = this.getLandedCostGLCommonEntry(
// bill,
// allocatedLandedCost
// );
// return {
// ...commonEntry,
// credit: allocatedLandedCost.localAmount,
// accountId: fromTransactionEntry.costAccountId,
// index: 2,
// accountNormal: AccountNormal.CREDIT,
// };
// };
if (!accountId) {
throw new Error(
`Cannot determine GL account for landed cost allocate entry (entryId: ${allocatedEntry.entryId})`,
);
}
// /**
// * Retrieve allocated landed cost entry GL entries.
// * @param {IBill} bill
// * @param {IBillLandedCost} allocatedLandedCost
// * @param {ILandedCostTransactionEntry} fromTransactionEntry
// * @param {IBillLandedCostEntry} allocatedEntry
// * @returns {ILedgerEntry}
// */
// private getLandedCostGLAllocateEntry = R.curry(
// (
// bill: Bill,
// allocatedLandedCost: BillLandedCost,
// fromTransactionEntry: ILandedCostTransactionEntry,
// allocatedEntry: BillLandedCostEntry
// ): ILedgerEntry[] => {
// const inventoryEntry = this.getLandedCostGLInventoryEntry(
// bill,
// allocatedLandedCost,
// allocatedEntry
// );
// const costEntry = this.getLandedCostGLCostEntry(
// bill,
// allocatedLandedCost,
// fromTransactionEntry
// );
// return [inventoryEntry, costEntry];
// }
// );
const localAmount =
allocatedEntry.cost * (allocatedLandedCost.exchangeRate || 1);
// /**
// * Compose the landed cost GL entries.
// * @param {BillLandedCost} allocatedLandedCost
// * @param {Bill} bill
// * @param {ILandedCostTransactionEntry} fromTransactionEntry
// * @returns {ILedgerEntry[]}
// */
// public getLandedCostGLEntries = (
// allocatedLandedCost: BillLandedCost,
// bill: Bill,
// fromTransactionEntry: ILandedCostTransactionEntry
// ): ILedgerEntry[] => {
// const getEntry = this.getLandedCostGLAllocateEntry(
// bill,
// allocatedLandedCost,
// fromTransactionEntry
// );
// return allocatedLandedCost.allocateEntries.map(getEntry).flat();
// };
return {
...commonEntry,
debit: localAmount,
accountId,
index: index + 1,
indexGroup: 10,
itemId: itemEntry?.itemId,
accountNormal: AccountNormal.DEBIT,
};
}
// /**
// * Retrieves the landed cost GL ledger.
// * @param {BillLandedCost} allocatedLandedCost
// * @param {Bill} bill
// * @param {ILandedCostTransactionEntry} fromTransactionEntry
// * @returns {ILedger}
// */
// public getLandedCostLedger = (
// allocatedLandedCost: BillLandedCost,
// bill: Bill,
// fromTransactionEntry: ILandedCostTransactionEntry
// ): ILedger => {
// const entries = this.getLandedCostGLEntries(
// allocatedLandedCost,
// bill,
// fromTransactionEntry
// );
// return new Ledger(entries);
// };
/**
* Retrieves the landed cost GL cost entry (credit to cost account).
*/
private getLandedCostGLCostEntry(
bill: Bill,
allocatedLandedCost: BillLandedCost,
): ILedgerEntry {
const commonEntry = this.getLandedCostGLCommonEntry(
bill,
allocatedLandedCost,
);
// /**
// * Writes landed cost GL entries to the storage layer.
// * @param {number} tenantId -
// */
// public writeLandedCostGLEntries = async (
// allocatedLandedCost: BillLandedCost,
// bill: Bill,
// fromTransactionEntry: ILandedCostTransactionEntry,
// trx?: Knex.Transaction
// ) => {
// const ledgerEntries = this.getLandedCostGLEntries(
// allocatedLandedCost,
// bill,
// fromTransactionEntry
// );
// await this.ledgerRepository.saveLedgerEntries(ledgerEntries, trx);
// };
return {
...commonEntry,
credit: allocatedLandedCost.localAmount,
accountId: allocatedLandedCost.costAccountId,
index: 1,
indexGroup: 20,
accountNormal: AccountNormal.CREDIT,
};
}
// /**
// * Generates and writes GL entries of the given landed cost.
// * @param {number} billLandedCostId
// * @param {Knex.Transaction} trx
// */
// public createLandedCostGLEntries = async (
// billLandedCostId: number,
// trx?: Knex.Transaction
// ) => {
// // Retrieve the bill landed cost transacion with associated
// // allocated entries and items.
// const allocatedLandedCost = await this.billLandedCostModel().query(trx)
// .findById(billLandedCostId)
// .withGraphFetched('bill')
// .withGraphFetched('allocateEntries.itemEntry.item');
/**
* Composes the landed cost GL entries.
*/
public getLandedCostGLEntries(
allocatedLandedCost: BillLandedCost,
bill: Bill,
): ILedgerEntry[] {
const inventoryEntries = allocatedLandedCost.allocateEntries.map(
(allocatedEntry, index) =>
this.getLandedCostGLInventoryEntry(
bill,
allocatedLandedCost,
allocatedEntry,
index,
),
);
const costEntry = this.getLandedCostGLCostEntry(bill, allocatedLandedCost);
// // Retrieve the allocated from transactione entry.
// const transactionEntry = await this.getLandedCostEntry(
// allocatedLandedCost.fromTransactionType,
// allocatedLandedCost.fromTransactionId,
// allocatedLandedCost.fromTransactionEntryId
// );
// // Writes the given landed cost GL entries to the storage layer.
// await this.writeLandedCostGLEntries(
// allocatedLandedCost,
// allocatedLandedCost.bill,
// transactionEntry,
// trx
// );
// };
return [...inventoryEntries, costEntry];
}
/**
* Retrieves the landed cost GL ledger.
*/
public getLandedCostLedger(
allocatedLandedCost: BillLandedCost,
bill: Bill,
): Ledger {
const entries = this.getLandedCostGLEntries(allocatedLandedCost, bill);
return new Ledger(entries);
}
/**
* Generates and writes GL entries of the given landed cost.
*/
public createLandedCostGLEntries = async (
billLandedCostId: number,
trx?: Knex.Transaction,
) => {
const allocatedLandedCost = await this.billLandedCostModel()
.query(trx)
.findById(billLandedCostId)
.withGraphFetched('bill')
.withGraphFetched('allocateEntries.itemEntry.item');
if (!allocatedLandedCost?.bill) {
throw new Error('BillLandedCost or associated Bill not found');
}
const ledger = this.getLandedCostLedger(
allocatedLandedCost,
allocatedLandedCost.bill,
);
await this.ledgerStorage.commit(ledger, trx);
};
/**
* Reverts GL entries of the given allocated landed cost transaction.
*/
public revertLandedCostGLEntries = async (
landedCostId: number,
trx?: Knex.Transaction,
) => {
await this.ledgerStorage.deleteByReference(landedCostId, 'LandedCost', trx);
};
}
// /**
// * Reverts GL entries of the given allocated landed cost transaction.
// * @param {number} tenantId
// * @param {number} landedCostId
// * @param {Knex.Transaction} trx
// */
// public revertLandedCostGLEntries = async (
// landedCostId: number,
// trx: Knex.Transaction
// ) => {
// await this.journalService.revertJournalTransactions(
// landedCostId,
// 'LandedCost',
// trx
// );
// };
// }

View File

@@ -3,15 +3,14 @@ import {
IAllocatedLandedCostDeletedPayload,
} from '../types/BillLandedCosts.types';
import { OnEvent } from '@nestjs/event-emitter';
// import { LandedCostGLEntries } from './LandedCostGLEntries.service';
import { Injectable } from '@nestjs/common';
import { events } from '@/common/events/events';
import { LandedCostGLEntriesService } from './LandedCostGLEntries.service';
@Injectable()
export class LandedCostGLEntriesSubscriber {
constructor(
private readonly landedCostGLEntries: LandedCostGLEntriesService,
) {}
constructor() // private readonly billLandedCostGLEntries: LandedCostGLEntries,
{}
/**
* Writes GL entries once landed cost transaction created.
@@ -22,10 +21,10 @@ export class LandedCostGLEntriesSubscriber {
billLandedCost,
trx,
}: IAllocatedLandedCostCreatedPayload) {
await this.landedCostGLEntries.createLandedCostGLEntries(
billLandedCost.id,
trx,
);
// await this.billLandedCostGLEntries.createLandedCostGLEntries(
// billLandedCost.id,
// trx
// );
}
/**
@@ -33,13 +32,13 @@ export class LandedCostGLEntriesSubscriber {
* @param {IAllocatedLandedCostDeletedPayload} payload -
*/
@OnEvent(events.billLandedCost.onDeleted)
async revertGLEntriesOnceLandedCostDeleted({
async revertGLEnteriesOnceLandedCostDeleted({
oldBillLandedCost,
trx,
}: IAllocatedLandedCostDeletedPayload) {
await this.landedCostGLEntries.revertLandedCostGLEntries(
oldBillLandedCost.id,
trx,
);
// await this.billLandedCostGLEntries.revertLandedCostGLEntries(
// oldBillLandedCost.id,
// trx
// );
}
}

View File

@@ -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(
R.map(transformLandedCost),
this.transformLandedCostTransactions,
R.map(transformLandedCost),
)(transactions);
};
@@ -90,7 +90,7 @@ export class LandedCostTranasctions {
const entries = R.map<
ILandedCostTransactionEntry,
ILandedCostTransactionEntryDOJO
>(transformLandedCostEntry)(transaction.entries ?? []);
>(transformLandedCostEntry)(transaction.entries);
return {
...transaction,

View File

@@ -4,6 +4,7 @@ import {
IsOptional,
IsArray,
ValidateNested,
IsDecimal,
IsString,
IsNumber,
} from 'class-validator';
@@ -16,9 +17,8 @@ export class AllocateBillLandedCostItemDto {
@ToNumber()
entryId: number;
@IsNumber()
@ToNumber()
cost: number;
@IsDecimal()
cost: string; // Use string for IsDecimal, or use @IsNumber() if you want a number
}
export class AllocateBillLandedCostDto {

View File

@@ -60,8 +60,8 @@ export class BillLandedCost extends BaseModel {
const allocationMethod = lowerCase(this.allocationMethod);
const keyLabelsPairs = {
value: 'bill.allocation_method.value',
quantity: 'bill.allocation_method.quantity',
value: 'allocation_method.value.label',
quantity: 'allocation_method.quantity.label',
};
return keyLabelsPairs[allocationMethod] || '';
}

View File

@@ -14,7 +14,6 @@ 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';
@@ -40,7 +39,6 @@ import { BillPaymentsPages } from './commands/BillPaymentsPages.service';
TenancyContext,
BillPaymentGLEntries,
BillPaymentGLEntriesSubscriber,
BillPaymentBillSyncSubscriber,
BillPaymentsExportable,
BillPaymentsImportable,
GetBillPaymentsService,
@@ -54,4 +52,4 @@ import { BillPaymentsPages } from './commands/BillPaymentsPages.service';
],
controllers: [BillPaymentsController],
})
export class BillPaymentsModule { }
export class BillPaymentsModule {}

View File

@@ -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,19 +103,11 @@ export class CreateBillPaymentService {
} as IBillPaymentCreatingPayload);
// Writes the bill payment graph to the storage.
const insertedBillPayment = await this.billPaymentModel()
const billPayment = 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,

View File

@@ -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,20 +116,12 @@ export class EditBillPayment {
} as IBillPaymentEditingPayload);
// Edits the bill payment transaction graph on the storage.
await this.billPaymentModel()
const billPayment = await this.billPaymentModel()
.query(trx)
.upsertGraph({
.upsertGraphAndFetch({
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,

View File

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

View File

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

View File

@@ -11,12 +11,10 @@ import {
Post,
Body,
Put,
Patch,
Param,
Delete,
Get,
Query,
HttpCode,
} from '@nestjs/common';
import { BillsApplication } from './Bills.application';
import { IBillsFilter } from './Bills.types';
@@ -42,7 +40,6 @@ export class BillsController {
@ApiOperation({
summary: 'Validate which bills can be deleted and return the results.',
})
@HttpCode(200)
@ApiResponse({
status: 200,
description:
@@ -59,7 +56,6 @@ export class BillsController {
@Post('bulk-delete')
@ApiOperation({ summary: 'Deletes multiple bills.' })
@HttpCode(200)
@ApiResponse({
status: 200,
description: 'Bills deleted successfully',
@@ -164,7 +160,7 @@ export class BillsController {
return this.billsApplication.getBill(billId);
}
@Patch(':id/open')
@Post(':id/open')
@ApiOperation({ summary: 'Open the given bill.' })
@ApiParam({
name: 'id',

View File

@@ -1,8 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { ItemEntryDto } from '@/modules/TransactionItemEntry/dto/ItemEntry.dto';
import { AttachmentLinkDto } from '@/modules/Attachments/dtos/Attachment.dto';
import { BranchResponseDto } from '@/modules/Branches/dtos/BranchResponse.dto';
import { DiscountType } from '@/common/types/Discount';
export class BillResponseDto {
@@ -91,14 +89,6 @@ export class BillResponseDto {
})
branchId?: number;
@ApiProperty({
description: 'Branch details',
type: () => BranchResponseDto,
required: false,
})
@Type(() => BranchResponseDto)
branch?: BranchResponseDto;
@ApiProperty({
description: 'The ID of the project',
example: 301,

View File

@@ -51,7 +51,6 @@ export class Bill extends TenantBaseModel {
public updatedAt: Date | null;
public entries?: ItemEntry[];
public attachments!: Document[];
public locatedLandedCosts?: BillLandedCost[];
/**
* Timestamps columns.
@@ -634,7 +633,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));
}
/**

View File

@@ -1,7 +1,5 @@
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 {
/**
@@ -30,7 +28,6 @@ export class BillTransformer extends Transformer {
'taxes',
'entries',
'attachments',
'branch',
];
};
@@ -234,18 +231,20 @@ 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 {Bill} bill
* @param {ISaleInvoice} invoice
* @returns
*/
protected attachments = (bill: Bill) => {
return this.item(bill.attachments, new AttachmentTransformer());
};
// protected attachments = (bill: Bill) => {
// return this.item(bill.attachments, new AttachmentTransformer());
// };
}

View File

@@ -31,12 +31,6 @@ import { ValidateBranchExistance } from './integrations/ValidateBranchExistance'
import { ManualJournalBranchesValidator } from './integrations/ManualJournals/ManualJournalsBranchesValidator';
import { CashflowTransactionsActivateBranches } from './integrations/Cashflow/CashflowActivateBranches';
import { ExpensesActivateBranches } from './integrations/Expense/ExpensesActivateBranches';
import { BillActivateBranches } from './integrations/Purchases/BillBranchesActivate';
import { VendorCreditActivateBranches } from './integrations/Purchases/VendorCreditBranchesActivate';
import { BillPaymentsActivateBranches } from './integrations/Purchases/PaymentMadeBranchesActivate';
import { BillBranchesActivateSubscriber } from './subscribers/Activate/BillBranchesActivateSubscriber';
import { VendorCreditBranchesActivateSubscriber } from './subscribers/Activate/VendorCreditBranchesActivateSubscriber';
import { PaymentMadeActivateBranchesSubscriber } from './subscribers/Activate/PaymentMadeBranchesActivateSubscriber';
import { FeaturesModule } from '../Features/Features.module';
@Module({
@@ -72,13 +66,7 @@ import { FeaturesModule } from '../Features/Features.module';
ValidateBranchExistance,
ManualJournalBranchesValidator,
CashflowTransactionsActivateBranches,
ExpensesActivateBranches,
BillActivateBranches,
VendorCreditActivateBranches,
BillPaymentsActivateBranches,
BillBranchesActivateSubscriber,
VendorCreditBranchesActivateSubscriber,
PaymentMadeActivateBranchesSubscriber
ExpensesActivateBranches
],
exports: [
BranchesSettingsService,

View File

@@ -1,14 +1,11 @@
import { Knex } from 'knex';
import { Inject, Injectable } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { Bill } from '@/modules/Bills/models/Bill';
@Injectable()
export class BillActivateBranches {
constructor(
@Inject(Bill.name)
private readonly billModel: TenantModelProxy<typeof Bill>,
) {}
constructor(private readonly billModel: TenantModelProxy<typeof Bill>) {}
/**
* Updates all bills transactions with the primary branch.
@@ -20,7 +17,7 @@ export class BillActivateBranches {
primaryBranchId: number,
trx?: Knex.Transaction,
) => {
// Updates the bills with primary branch.
await this.billModel().query(trx).update({ branchId: primaryBranchId });
// Updates the sale invoice with primary branch.
await Bill.query(trx).update({ branchId: primaryBranchId });
};
}

View File

@@ -1,12 +1,11 @@
import { Knex } from 'knex';
import { Inject, Injectable } from '@nestjs/common';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { BillPayment } from '@/modules/BillPayments/models/BillPayment';
import { Injectable } from '@nestjs/common';
@Injectable()
export class BillPaymentsActivateBranches {
constructor(
@Inject(BillPayment.name)
private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>,
) {}

View File

@@ -1,12 +1,11 @@
import { Knex } from 'knex';
import { Inject, Injectable } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { VendorCredit } from '@/modules/VendorCredit/models/VendorCredit';
@Injectable()
export class VendorCreditActivateBranches {
constructor(
@Inject(VendorCredit.name)
private readonly vendorCreditModel: TenantModelProxy<typeof VendorCredit>,
) {}

View File

@@ -1,28 +0,0 @@
import { IBranchesActivatedPayload } from '../../Branches.types';
import { events } from '@/common/events/events';
import { Injectable } from '@nestjs/common';
import { BillActivateBranches } from '../../integrations/Purchases/BillBranchesActivate';
import { OnEvent } from '@nestjs/event-emitter';
@Injectable()
export class BillBranchesActivateSubscriber {
constructor(
private readonly billActivateBranches: BillActivateBranches,
) { }
/**
* Updates bills transactions with the primary branch once
* the multi-branches is activated.
* @param {IBranchesActivatedPayload}
*/
@OnEvent(events.branch.onActivated)
async updateBillsWithBranchOnActivated({
primaryBranch,
trx,
}: IBranchesActivatedPayload) {
await this.billActivateBranches.updateBillsWithBranch(
primaryBranch.id,
trx,
);
}
}

View File

@@ -1,28 +0,0 @@
import { IBranchesActivatedPayload } from '../../Branches.types';
import { events } from '@/common/events/events';
import { Injectable } from '@nestjs/common';
import { VendorCreditActivateBranches } from '../../integrations/Purchases/VendorCreditBranchesActivate';
import { OnEvent } from '@nestjs/event-emitter';
@Injectable()
export class VendorCreditBranchesActivateSubscriber {
constructor(
private readonly vendorCreditActivateBranches: VendorCreditActivateBranches,
) { }
/**
* Updates vendor credits transactions with the primary branch once
* the multi-branches is activated.
* @param {IBranchesActivatedPayload}
*/
@OnEvent(events.branch.onActivated)
async updateVendorCreditsWithBranchOnActivated({
primaryBranch,
trx,
}: IBranchesActivatedPayload) {
await this.vendorCreditActivateBranches.updateVendorCreditsWithBranch(
primaryBranch.id,
trx,
);
}
}

View File

@@ -17,7 +17,7 @@ export class BillBranchValidateSubscriber {
* Validate branch existance on bill creating.
* @param {IBillCreatingPayload} payload
*/
@OnEvent(events.bill.onCreating, { suppressErrors: false })
@OnEvent(events.bill.onCreating)
async validateBranchExistanceOnBillCreating({
billDTO,
}: IBillCreatingPayload) {
@@ -30,7 +30,7 @@ export class BillBranchValidateSubscriber {
* Validate branch existance once bill editing.
* @param {IBillEditingPayload} payload
*/
@OnEvent(events.bill.onEditing, { suppressErrors: false })
@OnEvent(events.bill.onEditing)
async validateBranchExistanceOnBillEditing({ billDTO }: IBillEditingPayload) {
await this.validateBranchExistance.validateTransactionBranchWhenActive(
billDTO.branchId,

View File

@@ -14,7 +14,7 @@ export class CashflowBranchDTOValidatorSubscriber {
* Validate branch existance once cashflow transaction creating.
* @param {ICommandCashflowCreatingPayload} payload
*/
@OnEvent(events.cashflow.onTransactionCreating, { suppressErrors: false })
@OnEvent(events.cashflow.onTransactionCreating)
async validateBranchExistanceOnCashflowTransactionCreating({
newTransactionDTO,
}: ICommandCashflowCreatingPayload) {

View File

@@ -15,13 +15,13 @@ import {
export class ContactBranchValidateSubscriber {
constructor(
private readonly validateBranchExistance: ValidateBranchExistance,
) {}
) { }
/**
* Validate branch existance on customer creating.
* @param {ICustomerEventCreatingPayload} payload
*/
@OnEvent(events.customers.onCreating, { suppressErrors: false })
@OnEvent(events.customers.onCreating)
async validateBranchExistanceOnCustomerCreating({
customerDTO,
}: ICustomerEventCreatingPayload) {
@@ -37,7 +37,7 @@ export class ContactBranchValidateSubscriber {
* Validate branch existance once customer opening balance editing.
* @param {ICustomerOpeningBalanceEditingPayload} payload
*/
@OnEvent(events.customers.onOpeningBalanceChanging, { suppressErrors: false })
@OnEvent(events.customers.onOpeningBalanceChanging)
async validateBranchExistanceOnCustomerOpeningBalanceEditing({
openingBalanceEditDTO,
}: ICustomerOpeningBalanceEditingPayload) {
@@ -52,7 +52,7 @@ export class ContactBranchValidateSubscriber {
* Validates the branch existance on vendor creating.
* @param {IVendorEventCreatingPayload} payload
*/
@OnEvent(events.vendors.onCreating, { suppressErrors: false })
@OnEvent(events.vendors.onCreating)
async validateBranchExistanceonVendorCreating({
vendorDTO,
}: IVendorEventCreatingPayload) {
@@ -68,7 +68,7 @@ export class ContactBranchValidateSubscriber {
* Validate branch existance once the vendor opening balance editing.
* @param {IVendorOpeningBalanceEditingPayload} payload
*/
@OnEvent(events.vendors.onOpeningBalanceChanging, { suppressErrors: false })
@OnEvent(events.vendors.onOpeningBalanceChanging)
async validateBranchExistanceOnVendorOpeningBalanceEditing({
openingBalanceEditDTO,
}: IVendorOpeningBalanceEditingPayload) {

View File

@@ -15,7 +15,7 @@ export class CreditNoteBranchValidateSubscriber {
* Validate branch existance on credit note creating.
* @param {ICreditNoteCreatingPayload} payload
*/
@OnEvent(events.creditNote.onCreating, { suppressErrors: false })
@OnEvent(events.creditNote.onCreating)
async validateBranchExistanceOnCreditCreating({
creditNoteDTO,
}: ICreditNoteCreatingPayload) {
@@ -28,7 +28,7 @@ export class CreditNoteBranchValidateSubscriber {
* Validate branch existance once credit note editing.
* @param {ICreditNoteEditingPayload} payload
*/
@OnEvent(events.creditNote.onEditing, { suppressErrors: false })
@OnEvent(events.creditNote.onEditing)
async validateBranchExistanceOnCreditEditing({
creditNoteEditDTO,
}: ICreditNoteEditingPayload) {

View File

@@ -14,7 +14,7 @@ export class CreditNoteRefundBranchValidateSubscriber {
* Validate branch existance on refund credit note creating.
* @param {IRefundCreditNoteCreatingPayload} payload
*/
@OnEvent(events.creditNote.onRefundCreating, { suppressErrors: false })
@OnEvent(events.creditNote.onRefundCreating)
async validateBranchExistanceOnCreditRefundCreating({
newCreditNoteDTO,
}: IRefundCreditNoteCreatingPayload) {

View File

@@ -16,7 +16,7 @@ export class ExpenseBranchValidateSubscriber {
* Validate branch existance once expense transaction creating.
* @param {IExpenseCreatingPayload} payload
*/
@OnEvent(events.expenses.onCreating, { suppressErrors: false })
@OnEvent(events.expenses.onCreating)
async validateBranchExistanceOnExpenseCreating({
expenseDTO,
}: IExpenseCreatingPayload) {
@@ -29,7 +29,7 @@ export class ExpenseBranchValidateSubscriber {
* Validate branch existance once expense transaction editing.
* @param {IExpenseEventEditingPayload} payload
*/
@OnEvent(events.expenses.onEditing, { suppressErrors: false })
@OnEvent(events.expenses.onEditing)
async validateBranchExistanceOnExpenseEditing({
expenseDTO,
}: IExpenseEventEditingPayload) {

View File

@@ -14,7 +14,7 @@ export class InventoryAdjustmentBranchValidateSubscriber {
* Validate branch existance on inventory adjustment creating.
* @param {IInventoryAdjustmentCreatingPayload} payload
*/
@OnEvent(events.inventoryAdjustment.onQuickCreating, { suppressErrors: false })
@OnEvent(events.inventoryAdjustment.onQuickCreating)
async validateBranchExistanceOnInventoryCreating({
quickAdjustmentDTO,
}: IInventoryAdjustmentCreatingPayload) {

View File

@@ -17,7 +17,7 @@ export class InvoiceBranchValidateSubscriber {
* Validate branch existance on invoice creating.
* @param {ISaleInvoiceCreatingPayload} payload
*/
@OnEvent(events.saleInvoice.onCreating, { suppressErrors: false })
@OnEvent(events.saleInvoice.onCreating)
async validateBranchExistanceOnInvoiceCreating({
saleInvoiceDTO,
}: ISaleInvoiceCreatingPaylaod) {
@@ -30,7 +30,7 @@ export class InvoiceBranchValidateSubscriber {
* Validate branch existance once invoice editing.
* @param {ISaleInvoiceEditingPayload} payload
*/
@OnEvent(events.saleInvoice.onEditing, { suppressErrors: false })
@OnEvent(events.saleInvoice.onEditing)
async validateBranchExistanceOnInvoiceEditing({
saleInvoiceDTO,
}: ISaleInvoiceEditingPayload) {

View File

@@ -17,7 +17,7 @@ export class PaymentMadeBranchValidateSubscriber {
* Validate branch existance on estimate creating.
* @param {ISaleEstimateCreatedPayload} payload
*/
@OnEvent(events.billPayment.onCreating, { suppressErrors: false })
@OnEvent(events.billPayment.onCreating)
async validateBranchExistanceOnPaymentCreating({
billPaymentDTO,
}: IBillPaymentCreatingPayload) {
@@ -30,7 +30,7 @@ export class PaymentMadeBranchValidateSubscriber {
* Validate branch existance once estimate editing.
* @param {ISaleEstimateEditingPayload} payload
*/
@OnEvent(events.billPayment.onEditing, { suppressErrors: false })
@OnEvent(events.billPayment.onEditing)
async validateBranchExistanceOnPaymentEditing({
billPaymentDTO,
}: IBillPaymentEditingPayload) {

View File

@@ -17,7 +17,7 @@ export class PaymentReceiveBranchValidateSubscriber {
* Validate branch existance on estimate creating.
* @param {IPaymentReceivedCreatingPayload} payload
*/
@OnEvent(events.paymentReceive.onCreating, { suppressErrors: false })
@OnEvent(events.paymentReceive.onCreating)
async validateBranchExistanceOnPaymentCreating({
paymentReceiveDTO,
}: IPaymentReceivedCreatingPayload) {
@@ -30,7 +30,7 @@ export class PaymentReceiveBranchValidateSubscriber {
* Validate branch existance once estimate editing.
* @param {IPaymentReceivedEditingPayload} payload
*/
@OnEvent(events.paymentReceive.onEditing, { suppressErrors: false })
@OnEvent(events.paymentReceive.onEditing)
async validateBranchExistanceOnPaymentEditing({
paymentReceiveDTO,
}: IPaymentReceivedEditingPayload) {

View File

@@ -17,7 +17,7 @@ export class SaleEstimateBranchValidateSubscriber {
* Validate branch existance on estimate creating.
* @param {ISaleEstimateCreatedPayload} payload
*/
@OnEvent(events.saleEstimate.onCreating, { suppressErrors: false })
@OnEvent(events.saleEstimate.onCreating)
async validateBranchExistanceOnEstimateCreating({
estimateDTO,
}: ISaleEstimateCreatingPayload) {
@@ -30,7 +30,7 @@ export class SaleEstimateBranchValidateSubscriber {
* Validate branch existance once estimate editing.
* @param {ISaleEstimateEditingPayload} payload
*/
@OnEvent(events.saleEstimate.onEditing, { suppressErrors: false })
@OnEvent(events.saleEstimate.onEditing)
async validateBranchExistanceOnEstimateEditing({
estimateDTO,
}: ISaleEstimateEditingPayload) {

View File

@@ -17,7 +17,7 @@ export class SaleReceiptBranchValidateSubscriber {
* Validate branch existance on estimate creating.
* @param {ISaleReceiptCreatingPayload} payload
*/
@OnEvent(events.saleReceipt.onCreating, { suppressErrors: false })
@OnEvent(events.saleReceipt.onCreating)
async validateBranchExistanceOnInvoiceCreating({
saleReceiptDTO,
}: ISaleReceiptCreatingPayload) {
@@ -30,7 +30,7 @@ export class SaleReceiptBranchValidateSubscriber {
* Validate branch existance once estimate editing.
* @param {ISaleReceiptEditingPayload} payload
*/
@OnEvent(events.saleReceipt.onEditing, { suppressErrors: false })
@OnEvent(events.saleReceipt.onEditing)
async validateBranchExistanceOnInvoiceEditing({
saleReceiptDTO,
}: ISaleReceiptEditingPayload) {

View File

@@ -17,7 +17,7 @@ export class VendorCreditBranchValidateSubscriber {
* Validate branch existance on estimate creating.
* @param {ISaleEstimateCreatedPayload} payload
*/
@OnEvent(events.vendorCredit.onCreating, { suppressErrors: false })
@OnEvent(events.vendorCredit.onCreating)
async validateBranchExistanceOnCreditCreating({
vendorCreditCreateDTO,
}: IVendorCreditCreatingPayload) {
@@ -30,7 +30,7 @@ export class VendorCreditBranchValidateSubscriber {
* Validate branch existance once estimate editing.
* @param {ISaleEstimateEditingPayload} payload
*/
@OnEvent(events.vendorCredit.onEditing, { suppressErrors: false })
@OnEvent(events.vendorCredit.onEditing)
async validateBranchExistanceOnCreditEditing({
vendorCreditDTO,
}: IVendorCreditEditingPayload) {

View File

@@ -14,7 +14,7 @@ export class VendorCreditRefundBranchValidateSubscriber {
* Validate branch existance on refund credit note creating.
* @param {IRefundVendorCreditCreatingPayload} payload
*/
@OnEvent(events.vendorCredit.onRefundCreating, { suppressErrors: false })
@OnEvent(events.vendorCredit.onRefundCreating)
async validateBranchExistanceOnCreditRefundCreating({
refundVendorCreditDTO,
}: IRefundVendorCreditCreatingPayload) {

View File

@@ -22,7 +22,6 @@ export abstract class BaseCommand extends CommandRunner {
},
migrations: {
directory: this.configService.get('systemDatabase.migrationDir'),
loadExtensions: ['.js'],
},
seeds: {
directory: this.configService.get('systemDatabase.seedsDir'),
@@ -44,7 +43,6 @@ export abstract class BaseCommand extends CommandRunner {
},
migrations: {
directory: this.configService.get('tenantDatabase.migrationsDir') || './src/database/migrations',
loadExtensions: ['.js'],
},
seeds: {
directory: this.configService.get('tenantDatabase.seedsDir') || './src/database/seeds/core',

View File

@@ -3,7 +3,7 @@ import {
Get,
Query,
Param,
Patch,
Post,
ParseIntPipe,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiParam } from '@nestjs/swagger';
@@ -27,7 +27,7 @@ export class ContactsController {
return this.getAutoCompleteService.autocompleteContacts(query);
}
@Patch(':id/activate')
@Post(':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 };
}
@Patch(':id/inactivate')
@Post(':id/inactivate')
@ApiOperation({ summary: 'Inactivate a contact' })
@ApiParam({ name: 'id', type: 'number', description: 'Contact ID' })
async inactivateContact(@Param('id', ParseIntPipe) contactId: number) {

View File

@@ -7,13 +7,9 @@ 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), LedgerModule, AccountsModule],
imports: [forwardRef(() => CreditNotesModule)],
providers: [
CreateRefundCreditNoteService,
DeleteRefundCreditNoteService,
@@ -21,10 +17,8 @@ import { AccountsModule } from '../Accounts/Accounts.module';
RefundSyncCreditNoteBalanceService,
CreditNotesRefundsApplication,
GetCreditNoteRefundsService,
RefundCreditNoteGLEntries,
RefundCreditNoteGLEntriesSubscriber,
],
exports: [RefundSyncCreditNoteBalanceService],
controllers: [CreditNoteRefundsController],
})
export class CreditNoteRefundsModule { }
export class CreditNoteRefundsModule {}

View File

@@ -1,6 +1,5 @@
import { ApiProperty } from '@nestjs/swagger';
import { ToNumber, IsOptional } from '@/common/decorators/Validators';
import { IsDateString, IsNotEmpty, IsPositive, IsString } from 'class-validator';
import { IsNotEmpty, IsOptional, IsPositive, IsString } from 'class-validator';
import { IsDate } from 'class-validator';
import { IsNumber } from 'class-validator';
@@ -11,13 +10,8 @@ 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()
@@ -27,7 +21,6 @@ export class CreditNoteRefundDto {
})
amount: number;
@ToNumber()
@IsNumber()
@IsOptional()
@IsPositive()
@@ -37,23 +30,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;
@IsDateString()
@IsDate()
@IsNotEmpty()
@ApiProperty({
description: 'The date of the credit note refund',
@@ -61,7 +54,6 @@ export class CreditNoteRefundDto {
})
date: Date;
@ToNumber()
@IsNumber()
@IsOptional()
@ApiProperty({

View File

@@ -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,6 +15,7 @@ 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.
@@ -23,6 +24,7 @@ export class GetCreditNotePdf {
*/
constructor(
private readonly chromiumlyTenancy: ChromiumlyTenancy,
private readonly templateInjectable: TemplateInjectable,
private readonly getCreditNoteService: GetCreditNoteService,
private readonly creditNoteBrandingTemplate: CreditNoteBrandingTemplate,
private readonly eventPublisher: EventEmitter2,
@@ -34,40 +36,23 @@ export class GetCreditNotePdf {
private readonly pdfTemplateModel: TenantModelProxy<
typeof PdfTemplateModel
>,
) { }
) {}
/**
* 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.
* Retrieves sale invoice 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);

View File

@@ -1,103 +1,117 @@
import { Injectable } from '@nestjs/common';
import { AccountNormal } from '@/interfaces/Account';
import { ILedgerEntry } from '@/modules/Ledger/types/Ledger.types';
import { Ledger } from '@/modules/Ledger/Ledger';
import { Customer } from './models/Customer';
// import { Service, Inject } from 'typedi';
// import { AccountNormal, ICustomer, ILedgerEntry } from '@/interfaces';
// import Ledger from '@/services/Accounting/Ledger';
@Injectable()
export class CustomerGLEntries {
/**
* Retrieves the customer opening balance common entry attributes.
*/
private getCustomerOpeningGLCommonEntry = (customer: Customer) => {
return {
exchangeRate: customer.openingBalanceExchangeRate,
currencyCode: customer.currencyCode,
// @Service()
// export class CustomerGLEntries {
// /**
// * Retrieves the customer opening balance common entry attributes.
// * @param {ICustomer} customer
// */
// private getCustomerOpeningGLCommonEntry = (customer: ICustomer) => {
// return {
// exchangeRate: customer.openingBalanceExchangeRate,
// currencyCode: customer.currencyCode,
transactionType: 'CustomerOpeningBalance',
transactionId: customer.id,
// transactionType: 'CustomerOpeningBalance',
// transactionId: customer.id,
date: customer.openingBalanceAt,
contactId: customer.id,
// date: customer.openingBalanceAt,
// userId: customer.userId,
// contactId: customer.id,
credit: 0,
debit: 0,
// credit: 0,
// debit: 0,
branchId: customer.openingBalanceBranchId,
};
};
// branchId: customer.openingBalanceBranchId,
// };
// };
/**
* Retrieves the customer opening GL credit entry.
*/
private getCustomerOpeningGLCreditEntry = (
ARAccountId: number,
customer: Customer
): ILedgerEntry => {
const commonEntry = this.getCustomerOpeningGLCommonEntry(customer);
// /**
// * Retrieves the customer opening GL credit entry.
// * @param {number} ARAccountId
// * @param {ICustomer} customer
// * @returns {ILedgerEntry}
// */
// private getCustomerOpeningGLCreditEntry = (
// ARAccountId: number,
// customer: ICustomer
// ): ILedgerEntry => {
// const commonEntry = this.getCustomerOpeningGLCommonEntry(customer);
return {
...commonEntry,
credit: 0,
debit: customer.localOpeningBalance,
accountId: ARAccountId,
accountNormal: AccountNormal.DEBIT,
index: 1,
};
};
// return {
// ...commonEntry,
// credit: 0,
// debit: customer.localOpeningBalance,
// accountId: ARAccountId,
// accountNormal: AccountNormal.DEBIT,
// index: 1,
// };
// };
/**
* Retrieves the customer opening GL debit entry.
*/
private getCustomerOpeningGLDebitEntry = (
incomeAccountId: number,
customer: Customer
): ILedgerEntry => {
const commonEntry = this.getCustomerOpeningGLCommonEntry(customer);
// /**
// * Retrieves the customer opening GL debit entry.
// * @param {number} incomeAccountId
// * @param {ICustomer} customer
// * @returns {ILedgerEntry}
// */
// private getCustomerOpeningGLDebitEntry = (
// incomeAccountId: number,
// customer: ICustomer
// ): ILedgerEntry => {
// const commonEntry = this.getCustomerOpeningGLCommonEntry(customer);
return {
...commonEntry,
credit: customer.localOpeningBalance,
debit: 0,
accountId: incomeAccountId,
accountNormal: AccountNormal.CREDIT,
// return {
// ...commonEntry,
// credit: customer.localOpeningBalance,
// debit: 0,
// accountId: incomeAccountId,
// accountNormal: AccountNormal.CREDIT,
index: 2,
};
};
// index: 2,
// };
// };
/**
* Retrieves the customer opening GL entries.
*/
public getCustomerOpeningGLEntries = (
ARAccountId: number,
incomeAccountId: number,
customer: Customer
) => {
const debitEntry = this.getCustomerOpeningGLDebitEntry(
incomeAccountId,
customer
);
const creditEntry = this.getCustomerOpeningGLCreditEntry(
ARAccountId,
customer
);
return [debitEntry, creditEntry];
};
// /**
// * Retrieves the customer opening GL entries.
// * @param {number} ARAccountId
// * @param {number} incomeAccountId
// * @param {ICustomer} customer
// * @returns {ILedgerEntry[]}
// */
// public getCustomerOpeningGLEntries = (
// ARAccountId: number,
// incomeAccountId: number,
// customer: ICustomer
// ) => {
// const debitEntry = this.getCustomerOpeningGLDebitEntry(
// incomeAccountId,
// customer
// );
// const creditEntry = this.getCustomerOpeningGLCreditEntry(
// ARAccountId,
// customer
// );
// return [debitEntry, creditEntry];
// };
/**
* Retrieves the customer opening balance ledger.
*/
public getCustomerOpeningLedger = (
ARAccountId: number,
incomeAccountId: number,
customer: Customer
) => {
const entries = this.getCustomerOpeningGLEntries(
ARAccountId,
incomeAccountId,
customer
);
return new Ledger(entries);
};
}
// /**
// * Retrieves the customer opening balance ledger.
// * @param {number} ARAccountId
// * @param {number} incomeAccountId
// * @param {ICustomer} customer
// * @returns {ILedger}
// */
// public getCustomerOpeningLedger = (
// ARAccountId: number,
// incomeAccountId: number,
// customer: ICustomer
// ) => {
// const entries = this.getCustomerOpeningGLEntries(
// ARAccountId,
// incomeAccountId,
// customer
// );
// return new Ledger(entries);
// };
// }

View File

@@ -1,84 +1,90 @@
import { Knex } from 'knex';
import { Inject, Injectable } from '@nestjs/common';
import { LedgerStorageService } from '@/modules/Ledger/LedgerStorage.service';
import { AccountRepository } from '@/modules/Accounts/repositories/Account.repository';
import { CustomerGLEntries } from './CustomerGLEntries';
import { Customer } from './models/Customer';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { Account } from '../Accounts/models/Account.model';
// import { Knex } from 'knex';
// import LedgerStorageService from '@/services/Accounting/LedgerStorageService';
// import HasTenancyService from '@/services/Tenancy/TenancyService';
// import { Service, Inject } from 'typedi';
// import { CustomerGLEntries } from './CustomerGLEntries';
@Injectable()
export class CustomerGLEntriesStorage {
constructor(
private readonly ledgerStorage: LedgerStorageService,
private readonly accountRepository: AccountRepository,
private readonly customerGLEntries: CustomerGLEntries,
// @Service()
// export class CustomerGLEntriesStorage {
// @Inject()
// private tenancy: HasTenancyService;
@Inject(Account.name)
private readonly accountModel: TenantModelProxy<typeof Account>,
// @Inject()
// private ledegrRepository: LedgerStorageService;
@Inject(Customer.name)
private readonly customerModel: TenantModelProxy<typeof Customer>,
) { }
// @Inject()
// private customerGLEntries: CustomerGLEntries;
/**
* Customer opening balance journals.
*/
public writeCustomerOpeningBalance = async (
customerId: number,
trx?: Knex.Transaction,
) => {
const customer = await this.customerModel()
.query(trx)
.findById(customerId);
// /**
// * Customer opening balance journals.
// * @param {number} tenantId
// * @param {number} customerId
// * @param {Knex.Transaction} trx
// */
// public writeCustomerOpeningBalance = async (
// tenantId: number,
// customerId: number,
// trx?: Knex.Transaction
// ) => {
// const { Customer } = this.tenancy.models(tenantId);
// const { accountRepository } = this.tenancy.repositories(tenantId);
// Finds the income account.
const incomeAccount = await this.accountModel()
.query(trx)
.findOne({ slug: 'other-income' });
// const customer = await Customer.query(trx).findById(customerId);
// Find or create the A/R account.
const ARAccount =
await this.accountRepository.findOrCreateAccountReceivable(
customer.currencyCode,
{},
trx,
);
// Retrieves the customer opening balance ledger.
const ledger = this.customerGLEntries.getCustomerOpeningLedger(
ARAccount.id,
incomeAccount.id,
customer,
);
// Commits the ledger entries to the storage.
await this.ledgerStorage.commit(ledger, trx);
};
// // Finds the income account.
// const incomeAccount = await accountRepository.findOne({
// slug: 'other-income',
// });
// // Find or create the A/R account.
// const ARAccount = await accountRepository.findOrCreateAccountReceivable(
// customer.currencyCode,
// {},
// trx
// );
// // Retrieves the customer opening balance ledger.
// const ledger = this.customerGLEntries.getCustomerOpeningLedger(
// ARAccount.id,
// incomeAccount.id,
// customer
// );
// // Commits the ledger entries to the storage.
// await this.ledegrRepository.commit(tenantId, ledger, trx);
// };
/**
* Reverts the customer opening balance GL entries.
*/
public revertCustomerOpeningBalance = async (
customerId: number,
trx?: Knex.Transaction,
) => {
await this.ledgerStorage.deleteByReference(
customerId,
'CustomerOpeningBalance',
trx,
);
};
// /**
// * Reverts the customer opening balance GL entries.
// * @param {number} tenantId
// * @param {number} customerId
// * @param {Knex.Transaction} trx
// */
// public revertCustomerOpeningBalance = async (
// tenantId: number,
// customerId: number,
// trx?: Knex.Transaction
// ) => {
// await this.ledegrRepository.deleteByReference(
// tenantId,
// customerId,
// 'CustomerOpeningBalance',
// trx
// );
// };
/**
* Writes the customer opening balance GL entries.
*/
public rewriteCustomerOpeningBalance = async (
customerId: number,
trx?: Knex.Transaction,
) => {
// Reverts the customer opening balance entries.
await this.revertCustomerOpeningBalance(customerId, trx);
// /**
// * Writes the customer opening balance GL entries.
// * @param {number} tenantId
// * @param {number} customerId
// * @param {Knex.Transaction} trx
// */
// public rewriteCustomerOpeningBalance = async (
// tenantId: number,
// customerId: number,
// trx?: Knex.Transaction
// ) => {
// // Reverts the customer opening balance entries.
// await this.revertCustomerOpeningBalance(tenantId, customerId, trx);
// Write the customer opening balance entries.
await this.writeCustomerOpeningBalance(customerId, trx);
};
}
// // Write the customer opening balance entries.
// await this.writeCustomerOpeningBalance(tenantId, customerId, trx);
// };
// }

View File

@@ -9,7 +9,10 @@ import {
Query,
} from '@nestjs/common';
import { CustomersApplication } from './CustomersApplication.service';
import { CustomerOpeningBalanceEditDto } from './dtos/CustomerOpeningBalanceEdit.dto';
import {
ICustomerOpeningBalanceEditDTO,
ICustomersFilter,
} from './types/Customers.types';
import {
ApiOperation,
ApiResponse,
@@ -103,7 +106,7 @@ export class CustomersController {
})
editOpeningBalance(
@Param('id') customerId: number,
@Body() openingBalanceDTO: CustomerOpeningBalanceEditDto,
@Body() openingBalanceDTO: ICustomerOpeningBalanceEditDTO,
) {
return this.customersApplication.editOpeningBalance(
customerId,

View File

@@ -18,19 +18,9 @@ import { GetCustomers } from './queries/GetCustomers.service';
import { DynamicListModule } from '../DynamicListing/DynamicList.module';
import { BulkDeleteCustomersService } from './BulkDeleteCustomers.service';
import { ValidateBulkDeleteCustomersService } from './ValidateBulkDeleteCustomers.service';
import { LedgerModule } from '../Ledger/Ledger.module';
import { AccountsModule } from '../Accounts/Accounts.module';
import { CustomerGLEntries } from './CustomerGLEntries';
import { CustomerGLEntriesStorage } from './CustomerGLEntriesStorage';
import { CustomerWriteGLOpeningBalanceSubscriber } from './subscribers/CustomerGLEntriesSubscriber';
@Module({
imports: [
TenancyDatabaseModule,
DynamicListModule,
LedgerModule,
AccountsModule,
],
imports: [TenancyDatabaseModule, DynamicListModule],
controllers: [CustomersController],
providers: [
ActivateCustomer,
@@ -51,9 +41,6 @@ import { CustomerWriteGLOpeningBalanceSubscriber } from './subscribers/CustomerG
GetCustomers,
BulkDeleteCustomersService,
ValidateBulkDeleteCustomersService,
CustomerGLEntries,
CustomerGLEntriesStorage,
CustomerWriteGLOpeningBalanceSubscriber,
],
})
export class CustomersModule {}

View File

@@ -4,7 +4,10 @@ import { CreateCustomer } from './commands/CreateCustomer.service';
import { EditCustomer } from './commands/EditCustomer.service';
import { DeleteCustomer } from './commands/DeleteCustomer.service';
import { EditOpeningBalanceCustomer } from './commands/EditOpeningBalanceCustomer.service';
import { CustomerOpeningBalanceEditDto } from './dtos/CustomerOpeningBalanceEdit.dto';
import {
ICustomerOpeningBalanceEditDTO,
ICustomersFilter,
} from './types/Customers.types';
import { CreateCustomerDto } from './dtos/CreateCustomer.dto';
import { EditCustomerDto } from './dtos/EditCustomer.dto';
import { GetCustomers } from './queries/GetCustomers.service';
@@ -15,12 +18,12 @@ import { ValidateBulkDeleteCustomersService } from './ValidateBulkDeleteCustomer
@Injectable()
export class CustomersApplication {
constructor(
private readonly getCustomerService: GetCustomerService,
private readonly createCustomerService: CreateCustomer,
private readonly editCustomerService: EditCustomer,
private readonly deleteCustomerService: DeleteCustomer,
private readonly editOpeningBalanceService: EditOpeningBalanceCustomer,
private readonly getCustomersService: GetCustomers,
private getCustomerService: GetCustomerService,
private createCustomerService: CreateCustomer,
private editCustomerService: EditCustomer,
private deleteCustomerService: DeleteCustomer,
private editOpeningBalanceService: EditOpeningBalanceCustomer,
private getCustomersService: GetCustomers,
private readonly bulkDeleteCustomersService: BulkDeleteCustomersService,
private readonly validateBulkDeleteCustomersService: ValidateBulkDeleteCustomersService,
) {}
@@ -69,7 +72,7 @@ export class CustomersApplication {
*/
public editOpeningBalance = (
customerId: number,
openingBalanceEditDTO: CustomerOpeningBalanceEditDto,
openingBalanceEditDTO: ICustomerOpeningBalanceEditDTO,
) => {
return this.editOpeningBalanceService.changeOpeningBalance(
customerId,
@@ -79,7 +82,7 @@ export class CustomersApplication {
/**
* Retrieve customers paginated list.
* @param {GetCustomersQueryDto} filter - Cusotmers filter.
* @param {ICustomersFilter} filter - Cusotmers filter.
*/
public getCustomers = (filterDTO: GetCustomersQueryDto) => {
return this.getCustomersService.getCustomersList(filterDTO);

View File

@@ -31,7 +31,7 @@ export class CreateCustomer {
/**
* Creates a new customer.
* @param {CreateCustomerDto} customerDTO
* @param {ICustomerNewDTO} customerDTO
* @return {Promise<ICustomer>}
*/
public async createCustomer(

View File

@@ -1,10 +1,10 @@
import { Inject, Injectable } from '@nestjs/common';
import { Knex } from 'knex';
import {
ICustomerOpeningBalanceEditDTO,
ICustomerOpeningBalanceEditedPayload,
ICustomerOpeningBalanceEditingPayload,
} from '../types/Customers.types';
import { CustomerOpeningBalanceEditDto } from '../dtos/CustomerOpeningBalanceEdit.dto';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
import { Customer } from '../models/Customer';
@@ -29,11 +29,11 @@ export class EditOpeningBalanceCustomer {
/**
* Changes the opening balance of the given customer.
* @param {number} customerId - Customer ID.
* @param {CustomerOpeningBalanceEditDto} openingBalanceEditDTO
* @param {ICustomerOpeningBalanceEditDTO} openingBalanceEditDTO
*/
public async changeOpeningBalance(
customerId: number,
openingBalanceEditDTO: CustomerOpeningBalanceEditDto,
openingBalanceEditDTO: ICustomerOpeningBalanceEditDTO,
): Promise<Customer> {
// Retrieves the old customer or throw not found error.
const oldCustomer = await this.customerModel()

View File

@@ -4,7 +4,6 @@ import {
IsNotEmpty,
IsNumber,
IsString,
ValidateIf,
} from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
import { IsOptional, ToNumber } from '@/common/decorators/Validators';
@@ -41,11 +40,10 @@ export class CreateCustomerDto extends ContactAddressDto {
@ApiProperty({
required: false,
description: 'Opening balance date (required when openingBalance is provided)',
description: 'Opening balance date',
example: '2024-01-01',
})
@ValidateIf((o) => o.openingBalance != null)
@IsNotEmpty({ message: 'openingBalanceAt is required when openingBalance is provided' })
@IsOptional()
@IsString()
openingBalanceAt?: string;

View File

@@ -1,44 +0,0 @@
import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
import { IsOptional, ToNumber } from '@/common/decorators/Validators';
export class CustomerOpeningBalanceEditDto {
@ApiProperty({
required: true,
description: 'Opening balance',
example: 5000.0,
})
@IsNumber()
@IsNotEmpty()
@ToNumber()
openingBalance: number;
@ApiProperty({
required: false,
description: 'Opening balance date',
example: '2024-01-01',
})
@IsOptional()
@IsString()
openingBalanceAt?: string;
@ApiProperty({
required: false,
description: 'Opening balance exchange rate',
example: 1.0,
})
@IsOptional()
@IsNumber()
@ToNumber()
openingBalanceExchangeRate?: number;
@ApiProperty({
required: false,
description: 'Opening balance branch ID',
example: 101,
})
@IsOptional()
@IsNumber()
@ToNumber()
openingBalanceBranchId?: number;
}

View File

@@ -1,63 +1,91 @@
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import {
ICustomerEventCreatedPayload,
ICustomerEventDeletedPayload,
ICustomerOpeningBalanceEditedPayload,
} from '../types/Customers.types';
import { events } from '@/common/events/events';
import { CustomerGLEntriesStorage } from '../CustomerGLEntriesStorage';
// import { Service, Inject } from 'typedi';
// import {
// ICustomerEventCreatedPayload,
// ICustomerEventDeletedPayload,
// ICustomerOpeningBalanceEditedPayload,
// } from '@/interfaces';
// import events from '@/subscribers/events';
// import { CustomerGLEntriesStorage } from '../CustomerGLEntriesStorage';
@Injectable()
export class CustomerWriteGLOpeningBalanceSubscriber {
constructor(private readonly customerGLEntries: CustomerGLEntriesStorage) { }
// @Service()
// export class CustomerWriteGLOpeningBalanceSubscriber {
// @Inject()
// private customerGLEntries: CustomerGLEntriesStorage;
/**
* Handles the writing opening balance journal entries once the customer created.
*/
@OnEvent(events.customers.onCreated)
public async handleWriteOpenBalanceEntries({
customer,
trx,
}: ICustomerEventCreatedPayload) {
// Writes the customer opening balance journal entries.
if (customer.openingBalance) {
await this.customerGLEntries.writeCustomerOpeningBalance(
customer.id,
trx,
);
}
}
// /**
// * Attaches events with handlers.
// */
// public attach(bus) {
// bus.subscribe(
// events.customers.onCreated,
// this.handleWriteOpenBalanceEntries
// );
// bus.subscribe(
// events.customers.onDeleted,
// this.handleRevertOpeningBalanceEntries
// );
// bus.subscribe(
// events.customers.onOpeningBalanceChanged,
// this.handleRewriteOpeningEntriesOnChanged
// );
// }
/**
* Handles the deleting opening balance journal entries once the customer deleted.
*/
@OnEvent(events.customers.onDeleted)
public async handleRevertOpeningBalanceEntries({
customerId,
trx,
}: ICustomerEventDeletedPayload) {
await this.customerGLEntries.revertCustomerOpeningBalance(customerId, trx);
}
// /**
// * Handles the writing opening balance journal entries once the customer created.
// * @param {ICustomerEventCreatedPayload} payload -
// */
// private handleWriteOpenBalanceEntries = async ({
// tenantId,
// customer,
// trx,
// }: ICustomerEventCreatedPayload) => {
// // Writes the customer opening balance journal entries.
// if (customer.openingBalance) {
// await this.customerGLEntries.writeCustomerOpeningBalance(
// tenantId,
// customer.id,
// trx
// );
// }
// };
/**
* Handles the rewrite opening balance entries once opening balance changed.
*/
@OnEvent(events.customers.onOpeningBalanceChanged)
public async handleRewriteOpeningEntriesOnChanged({
customer,
trx,
}: ICustomerOpeningBalanceEditedPayload) {
if (customer.openingBalance) {
await this.customerGLEntries.rewriteCustomerOpeningBalance(
customer.id,
trx,
);
} else {
await this.customerGLEntries.revertCustomerOpeningBalance(
customer.id,
trx,
);
}
}
}
// /**
// * Handles the deleting opeing balance journal entrise once the customer deleted.
// * @param {ICustomerEventDeletedPayload} payload -
// */
// private handleRevertOpeningBalanceEntries = async ({
// tenantId,
// customerId,
// trx,
// }: ICustomerEventDeletedPayload) => {
// await this.customerGLEntries.revertCustomerOpeningBalance(
// tenantId,
// customerId,
// trx
// );
// };
// /**
// * Handles the rewrite opening balance entries once opening balnace changed.
// * @param {ICustomerOpeningBalanceEditedPayload} payload -
// */
// private handleRewriteOpeningEntriesOnChanged = async ({
// tenantId,
// customer,
// trx,
// }: ICustomerOpeningBalanceEditedPayload) => {
// if (customer.openingBalance) {
// await this.customerGLEntries.rewriteCustomerOpeningBalance(
// tenantId,
// customer.id,
// trx
// );
// } else {
// await this.customerGLEntries.revertCustomerOpeningBalance(
// tenantId,
// customer.id,
// trx
// );
// }
// };
// }

View File

@@ -4,7 +4,6 @@ import { IContactAddressDTO } from '@/modules/Contacts/types/Contacts.types';
import { IDynamicListFilter } from '@/modules/DynamicListing/DynamicFilter/DynamicFilter.types';
import { IFilterMeta, IPaginationMeta } from '@/interfaces/Model';
import { CreateCustomerDto } from '../dtos/CreateCustomer.dto';
import { CustomerOpeningBalanceEditDto } from '../dtos/CustomerOpeningBalanceEdit.dto';
import { EditCustomerDto } from '../dtos/EditCustomer.dto';
// Customer Interfaces.
@@ -114,16 +113,23 @@ export enum VendorAction {
View = 'View',
}
export interface ICustomerOpeningBalanceEditDTO {
openingBalance: number;
openingBalanceAt: Date | string;
openingBalanceExchangeRate: number;
openingBalanceBranchId?: number;
}
export interface ICustomerOpeningBalanceEditingPayload {
oldCustomer: Customer;
openingBalanceEditDTO: CustomerOpeningBalanceEditDto;
openingBalanceEditDTO: ICustomerOpeningBalanceEditDTO;
trx?: Knex.Transaction;
}
export interface ICustomerOpeningBalanceEditedPayload {
customer: Customer;
oldCustomer: Customer;
openingBalanceEditDTO: CustomerOpeningBalanceEditDto;
openingBalanceEditDTO: ICustomerOpeningBalanceEditDTO;
trx: Knex.Transaction;
}

View File

@@ -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 { stringifiedFilterRoles?: string }>(
public parseStringifiedFilter<T extends IDynamicListFilter>(
filterRoles: T,
): T {
return {

View File

@@ -4,15 +4,14 @@ import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service';
import { TableSheetPdf } from './TableSheetPdf';
import { TemplateInjectableModule } from '@/modules/TemplateInjectable/TemplateInjectable.module';
import { ChromiumlyTenancyModule } from '@/modules/ChromiumlyTenancy/ChromiumlyTenancy.module';
import { InventoryCostModule } from '@/modules/InventoryCost/InventoryCost.module';
@Module({
imports: [
TemplateInjectableModule,
ChromiumlyTenancyModule,
InventoryCostModule,
imports: [TemplateInjectableModule, ChromiumlyTenancyModule],
providers: [
FinancialSheetMeta,
TenancyContext,
TableSheetPdf,
],
providers: [FinancialSheetMeta, TenancyContext, TableSheetPdf],
exports: [FinancialSheetMeta, TableSheetPdf],
})
export class FinancialSheetCommonModule {}

View File

@@ -1,14 +1,10 @@
import { Injectable } from '@nestjs/common';
import { IFinancialSheetCommonMeta } from '../types/Report.types';
import { TenancyContext } from '@/modules/Tenancy/TenancyContext.service';
import { InventoryComputeCostService } from '@/modules/InventoryCost/commands/InventoryComputeCost.service';
@Injectable()
export class FinancialSheetMeta {
constructor(
private readonly tenancyContext: TenancyContext,
private readonly inventoryComputeCostService: InventoryComputeCostService,
) {}
constructor(private readonly tenancyContext: TenancyContext) {}
/**
* Retrieves the common meta data of the financial sheet.
@@ -21,8 +17,10 @@ export class FinancialSheetMeta {
const baseCurrency = tenantMetadata.baseCurrency;
const dateFormat = tenantMetadata.dateFormat;
const isCostComputeRunning =
await this.inventoryComputeCostService.isItemsCostComputeRunning();
// const isCostComputeRunning =
// this.inventoryService.isItemsCostComputeRunning();
const isCostComputeRunning = false;
return {
organizationName,

View File

@@ -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,13 +37,12 @@ export class APAgingSummaryController {
@Res({ passthrough: true }) res: Response,
@Headers('accept') acceptHeader: string,
) {
const accept = acceptHeader || '';
// Retrieves the json table format.
if (accept.includes(AcceptType.ApplicationJsonTable)) {
if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
return this.APAgingSummaryApp.table(filter);
// Retrieves the csv format.
} else if (accept.includes(AcceptType.ApplicationCsv)) {
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
const csv = await this.APAgingSummaryApp.csv(filter);
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
@@ -51,7 +50,7 @@ export class APAgingSummaryController {
res.send(csv);
// Retrieves the xlsx format.
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
const buffer = await this.APAgingSummaryApp.xlsx(filter);
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
@@ -61,7 +60,7 @@ export class APAgingSummaryController {
);
res.send(buffer);
// Retrieves the pdf format.
} else if (accept.includes(AcceptType.ApplicationPdf)) {
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
const pdfContent = await this.APAgingSummaryApp.pdf(filter);
res.set({

View File

@@ -38,9 +38,8 @@ export class ARAgingSummaryController {
@Res({ passthrough: true }) res: Response,
@Headers('accept') acceptHeader: string,
) {
const accept = acceptHeader || '';
// Retrieves the xlsx format.
if (accept.includes(AcceptType.ApplicationXlsx)) {
if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
const buffer = await this.ARAgingSummaryApp.xlsx(filter);
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
@@ -50,11 +49,11 @@ export class ARAgingSummaryController {
);
res.send(buffer);
// Retrieves the table format.
} else if (accept.includes(AcceptType.ApplicationJsonTable)) {
} else if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
return this.ARAgingSummaryApp.table(filter);
// Retrieves the csv format.
} else if (accept.includes(AcceptType.ApplicationCsv)) {
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
const buffer = await this.ARAgingSummaryApp.csv(filter);
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
@@ -62,7 +61,7 @@ export class ARAgingSummaryController {
res.send(buffer);
// Retrieves the pdf format.
} else if (accept.includes(AcceptType.ApplicationPdf)) {
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
const pdfContent = await this.ARAgingSummaryApp.pdf(filter);
res.set({

View File

@@ -43,14 +43,13 @@ export class BalanceSheetStatementController {
@Res({ passthrough: true }) res: Response,
@Headers('accept') acceptHeader: string,
) {
const accept = acceptHeader || '';
// Retrieves the json table format.
if (accept.includes(AcceptType.ApplicationJsonTable)) {
if (acceptHeader.includes(AcceptType.ApplicationJsonTable)) {
const table = await this.balanceSheetApp.table(query);
return table;
// Retrieves the csv format.
} else if (accept.includes(AcceptType.ApplicationCsv)) {
} else if (acceptHeader.includes(AcceptType.ApplicationCsv)) {
const buffer = await this.balanceSheetApp.csv(query);
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
@@ -58,7 +57,7 @@ export class BalanceSheetStatementController {
res.send(buffer);
// Retrieves the xlsx format.
} else if (accept.includes(AcceptType.ApplicationXlsx)) {
} else if (acceptHeader.includes(AcceptType.ApplicationXlsx)) {
const buffer = await this.balanceSheetApp.xlsx(query);
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
@@ -68,7 +67,7 @@ export class BalanceSheetStatementController {
);
res.send(buffer);
// Retrieves the pdf format.
} else if (accept.includes(AcceptType.ApplicationPdf)) {
} else if (acceptHeader.includes(AcceptType.ApplicationPdf)) {
const pdfContent = await this.balanceSheetApp.pdf(query);
res.set({

View File

@@ -24,14 +24,14 @@ export class BalanceSheetQueryDto extends FinancialSheetBranchesQueryDto {
displayColumnsType: 'total' | 'date_periods' = 'total';
@ApiProperty({
enum: ['day', 'month', 'year', 'quarter'],
enum: ['day', 'month', 'year'],
default: 'year',
description: 'Time period for column display',
})
@IsString()
@IsOptional()
@IsEnum(['day', 'month', 'year', 'quarter'])
displayColumnsBy: 'day' | 'month' | 'year' | 'quarter' = 'year';
@IsEnum(['day', 'month', 'year'])
displayColumnsBy: 'day' | 'month' | 'year' = 'year';
@ApiProperty({
description: 'Start date for the balance sheet period',

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