mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-17 05:10:31 +00:00
Compare commits
2 Commits
darkmode-u
...
feature/20
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04d065b969 | ||
|
|
ca910ee489 |
@@ -167,9 +167,6 @@
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node",
|
||||
"moduleNameMapper": {
|
||||
"^@/(.*)$": "<rootDir>/$1"
|
||||
}
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,4 @@
|
||||
import { chain, mapKeys } from 'lodash';
|
||||
|
||||
const getTransactionsLockingSettingsSchema = (modules: string[]) => {
|
||||
const moduleSchema = {
|
||||
active: { type: 'boolean' },
|
||||
lock_to_date: { type: 'date' },
|
||||
unlock_from_date: { type: 'date' },
|
||||
unlock_to_date: { type: 'date' },
|
||||
lock_reason: { type: 'string' },
|
||||
unlock_reason: { type: 'string' },
|
||||
};
|
||||
return chain(modules)
|
||||
.map((module: string) => {
|
||||
return mapKeys(moduleSchema, (value, key: string) => `${module}.${key}`);
|
||||
})
|
||||
.flattenDeep()
|
||||
.reduce((result, value) => {
|
||||
return {
|
||||
...result,
|
||||
...value,
|
||||
};
|
||||
}, {})
|
||||
.value();
|
||||
};
|
||||
// import { getTransactionsLockingSettingsSchema } from '@/api/controllers/TransactionsLocking/utils';
|
||||
|
||||
export const SettingsOptions = {
|
||||
organization: {
|
||||
@@ -246,12 +223,12 @@ export const SettingsOptions = {
|
||||
'locking-type': {
|
||||
type: 'string',
|
||||
},
|
||||
...getTransactionsLockingSettingsSchema([
|
||||
'all',
|
||||
'sales',
|
||||
'purchases',
|
||||
'financial',
|
||||
]),
|
||||
// ...getTransactionsLockingSettingsSchema([
|
||||
// 'all',
|
||||
// 'sales',
|
||||
// 'purchases',
|
||||
// 'financial',
|
||||
// ]),
|
||||
},
|
||||
features: {
|
||||
'multi-warehouses': {
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
"field.description": "Description",
|
||||
"field.slug": "Account slug",
|
||||
"field.code": "Account code",
|
||||
"field.code_hint": "Unique number to identify the account.",
|
||||
"field.root_type": "Root type",
|
||||
"field.normal": "Account normal",
|
||||
"field.normal.credit": "Credit",
|
||||
@@ -14,6 +13,5 @@
|
||||
"field.balance": "Balance",
|
||||
"field.bank_balance": "Bank Balance",
|
||||
"field.parent_account": "Parent Account",
|
||||
"field.created_at": "Created at",
|
||||
"field.account_hint": "Matches the account name or code."
|
||||
"field.created_at": "Created at"
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
{
|
||||
"field.vendor": "Vendor",
|
||||
"field.bill_number": "Bill No.",
|
||||
"field.bill_date": "Date",
|
||||
"field.due_date": "Due Date",
|
||||
"field.reference_no": "Reference No.",
|
||||
"field.exchange_rate": "Exchange Rate",
|
||||
"field.note": "Note",
|
||||
"field.open": "Open",
|
||||
"field.entries": "Entries",
|
||||
"field.item": "Item",
|
||||
"field.item_hint": "Matches the item name or code.",
|
||||
"field.rate": "Rate",
|
||||
"field.quantity": "Quantity",
|
||||
"field.description": "Line Description",
|
||||
"field.amount": "Amount",
|
||||
"field.payment_amount": "Payment Amount",
|
||||
"field.status": "Status",
|
||||
"field.status.paid": "Paid",
|
||||
"field.status.partially-paid": "Partially Paid",
|
||||
"field.status.overdue": "Overdue",
|
||||
"field.status.unpaid": "Unpaid",
|
||||
"field.status.opened": "Opened",
|
||||
"field.status.draft": "Draft",
|
||||
"field.created_at": "Created At"
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"field.vendor": "Vendor",
|
||||
"field.payment_date": "Payment Date",
|
||||
"field.payment_number": "Payment No.",
|
||||
"field.payment_account": "Payment Account",
|
||||
"field.exchange_rate": "Exchange Rate",
|
||||
"field.note": "Note",
|
||||
"field.reference": "Reference",
|
||||
"field.entries": "Entries",
|
||||
"field.entries.bill": "Bill",
|
||||
"field.entries.payment_amount": "Payment Amount",
|
||||
"field.payment_number_hint": "The payment number should be unique.",
|
||||
"field.bill_hint": "Matches the bill number."
|
||||
}
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"field.customer": "Customer",
|
||||
"field.exchange_rate": "Exchange Rate",
|
||||
"field.credit_note_date": "Credit Note Date",
|
||||
"field.reference_no": "Reference No.",
|
||||
"field.note": "Note",
|
||||
"field.terms_conditions": "Terms & Conditions",
|
||||
"field.credit_note_number": "Credit Note Number",
|
||||
"field.open": "Open",
|
||||
"field.entries": "Entries",
|
||||
"field.item": "Item",
|
||||
"field.rate": "Rate",
|
||||
"field.quantity": "Quantity",
|
||||
"field.description": "Description"
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"field.customer": "Customer",
|
||||
"field.estimate_date": "Estimate Date",
|
||||
"field.expiration_date": "Expiration Date",
|
||||
"field.estimate_number": "Estimate No.",
|
||||
"field.reference_no": "Reference No.",
|
||||
"field.exchange_rate": "Exchange Rate",
|
||||
"field.currency": "Currency",
|
||||
"field.note": "Note",
|
||||
"field.terms_conditions": "Terms & Conditions",
|
||||
"field.delivered": "Delivered",
|
||||
"field.entries": "Entries",
|
||||
"field.amount": "Amount",
|
||||
"field.status": "Status",
|
||||
"field.status.draft": "Draft",
|
||||
"field.status.delivered": "Delivered",
|
||||
"field.status.rejected": "Rejected",
|
||||
"field.status.approved": "Approved",
|
||||
"field.created_at": "Created At"
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@
|
||||
"field.due_amount": "Due amount",
|
||||
"field.delivered": "Delivered",
|
||||
"field.item_name": "Item Name",
|
||||
"field.item_hint": "Matches the item name or code.",
|
||||
"field.rate": "Rate",
|
||||
"field.quantity": "Quantity",
|
||||
"field.description": "Description",
|
||||
@@ -39,7 +38,5 @@
|
||||
"field.status.draft": "Draft",
|
||||
"field.created_at": "Created at",
|
||||
"field.currency": "Currency",
|
||||
"field.entries": "Entries",
|
||||
"field.branch": "Branch",
|
||||
"field.warehouse": "Warehouse"
|
||||
"field.entries": "Entries"
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
"field.quantity_on_hand": "Quantity on Hand",
|
||||
"field.note": "Note",
|
||||
"field.category": "Category",
|
||||
"field.category_hint": "Matches the category name.",
|
||||
"field.active": "Active",
|
||||
"field.created_at": "Created At"
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"field.customer": "Customer",
|
||||
"field.payment_date": "Payment Date",
|
||||
"field.amount": "Amount",
|
||||
"field.reference_no": "Reference No.",
|
||||
"field.deposit_account": "Deposit Account",
|
||||
"field.payment_receive_no": "Payment No.",
|
||||
"field.statement": "Statement",
|
||||
"field.entries": "Entries",
|
||||
"field.exchange_rate": "Exchange Rate",
|
||||
"field.invoice": "Invoice",
|
||||
"field.entries.payment_amount": "Payment Amount",
|
||||
"field.created_at": "Created At",
|
||||
"field.payment_no_hint": "The payment number should be unique.",
|
||||
"field.invoice_hint": "Matches the invoice number."
|
||||
}
|
||||
|
||||
@@ -10,21 +10,5 @@
|
||||
"paper.receipt_amount": "Receipt amount",
|
||||
"paper.total": "Total",
|
||||
"paper.balance_due": "Balance Due",
|
||||
"paper.payment_amount": "Payment Amount",
|
||||
|
||||
"field.receipt_date": "Receipt Date",
|
||||
"field.customer": "Customer",
|
||||
"field.deposit_account": "Deposit Account",
|
||||
"field.exchange_rate": "Exchange Rate",
|
||||
"field.receipt_number": "Receipt Number",
|
||||
"field.reference_no": "Reference No.",
|
||||
"field.closed": "Closed",
|
||||
"field.entries": "Entries",
|
||||
"field.statement": "Statement",
|
||||
"field.receipt_message": "Receipt Message",
|
||||
"field.amount": "Amount",
|
||||
"field.status": "Status",
|
||||
"field.status.draft": "Draft",
|
||||
"field.status.closed": "Closed",
|
||||
"field.created_at": "Created At"
|
||||
"paper.payment_amount": "Payment Amount"
|
||||
}
|
||||
@@ -2,18 +2,5 @@
|
||||
"view.draft": "Draft",
|
||||
"view.published": "Published",
|
||||
"view.open": "Open",
|
||||
"view.closed": "Closed",
|
||||
|
||||
"field.vendor": "Vendor",
|
||||
"field.vendor_credit_number": "Vendor Credit No.",
|
||||
"field.vendor_credit_date": "Vendor Credit Date",
|
||||
"field.reference_no": "Reference No.",
|
||||
"field.exchange_rate": "Exchange Rate",
|
||||
"field.note": "Note",
|
||||
"field.open": "Open",
|
||||
"field.entries": "Entries",
|
||||
"field.item": "Item",
|
||||
"field.rate": "Rate",
|
||||
"field.quantity": "Quantity",
|
||||
"field.description": "Description"
|
||||
"view.closed": "Closed"
|
||||
}
|
||||
|
||||
@@ -156,7 +156,7 @@ export const AccountMeta = {
|
||||
minLength: 3,
|
||||
maxLength: 6,
|
||||
unique: true,
|
||||
importHint: 'account.field.code_hint',
|
||||
importHint: 'Unique number to identify the account.',
|
||||
},
|
||||
accountType: {
|
||||
name: 'account.field.type',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import * as yup from 'yup';
|
||||
import * as uniqid from 'uniqid';
|
||||
import uniqid from 'uniqid';
|
||||
import { Importable } from '../../Import/Importable';
|
||||
import { CreateUncategorizedTransactionService } from './CreateUncategorizedTransaction.service';
|
||||
import { ImportableContext } from '../../Import/interfaces';
|
||||
@@ -9,10 +9,8 @@ import { BankTransactionsSampleData } from '../../BankingTransactions/constants'
|
||||
import { Account } from '@/modules/Accounts/models/Account.model';
|
||||
import { CreateUncategorizedTransactionDTO } from '../types/BankingCategorize.types';
|
||||
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
|
||||
import { ImportableService } from '../../Import/decorators/Import.decorator';
|
||||
import { UncategorizedBankTransaction } from '../../BankingTransactions/models/UncategorizedBankTransaction';
|
||||
|
||||
@Injectable()
|
||||
@ImportableService({ name: UncategorizedBankTransaction.name })
|
||||
export class UncategorizedTransactionsImportable extends Importable {
|
||||
constructor(
|
||||
private readonly createUncategorizedTransaction: CreateUncategorizedTransactionService,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as moment from 'moment';
|
||||
import * as R from 'ramda';
|
||||
import { isEmpty, round, sumBy } from 'lodash';
|
||||
import { isEmpty, sumBy } from 'lodash';
|
||||
import { ERRORS, MatchedTransactionPOJO } from './types';
|
||||
import { ServiceError } from '../Items/ServiceError';
|
||||
|
||||
@@ -22,24 +22,18 @@ export const sortClosestMatchTransactions = (
|
||||
};
|
||||
|
||||
export const sumMatchTranasctions = (transactions: Array<any>) => {
|
||||
const total = transactions.reduce(
|
||||
(sum, item) => {
|
||||
const amount = parseFloat(item.amount) || 0;
|
||||
const multiplier = item.transactionNormal === 'debit' ? 1 : -1;
|
||||
return sum + multiplier * amount;
|
||||
},
|
||||
return transactions.reduce(
|
||||
(total, item) =>
|
||||
total +
|
||||
(item.transactionNormal === 'debit' ? 1 : -1) * parseFloat(item.amount),
|
||||
0
|
||||
);
|
||||
// Round to 2 decimal places to avoid floating-point precision issues
|
||||
return round(total, 2);
|
||||
};
|
||||
|
||||
export const sumUncategorizedTransactions = (
|
||||
uncategorizedTransactions: Array<any>
|
||||
) => {
|
||||
const total = sumBy(uncategorizedTransactions, 'amount');
|
||||
// Round to 2 decimal places to avoid floating-point precision issues
|
||||
return round(total, 2);
|
||||
return sumBy(uncategorizedTransactions, 'amount');
|
||||
};
|
||||
|
||||
export const validateUncategorizedTransactionsNotMatched = (
|
||||
|
||||
@@ -34,7 +34,7 @@ export class MatchBankTransactions {
|
||||
private readonly uncategorizedBankTransactionModel: TenantModelProxy<
|
||||
typeof UncategorizedBankTransaction
|
||||
>,
|
||||
) { }
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Validates the match bank transactions DTO.
|
||||
@@ -100,10 +100,7 @@ export class MatchBankTransactions {
|
||||
);
|
||||
// Validates the total given matching transcations whether is not equal
|
||||
// uncategorized transaction amount.
|
||||
// Use tolerance-based comparison to handle floating-point precision issues
|
||||
const tolerance = 0.01; // Allow 0.01 difference for floating-point precision
|
||||
const difference = Math.abs(totalUncategorizedTransactions - totalMatchedTranasctions);
|
||||
if (difference > tolerance) {
|
||||
if (totalUncategorizedTransactions !== totalMatchedTranasctions) {
|
||||
throw new ServiceError(ERRORS.TOTAL_MATCHING_TRANSACTIONS_INVALID);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,30 +12,24 @@ export class MatchTransactionsTypes {
|
||||
private static registry: MatchTransactionsTypesRegistry;
|
||||
|
||||
/**
|
||||
* Constructor method.
|
||||
* Consttuctor method.
|
||||
*/
|
||||
constructor(
|
||||
private readonly getMatchedInvoicesService: GetMatchedTransactionsByInvoices,
|
||||
private readonly getMatchedBillsService: GetMatchedTransactionsByBills,
|
||||
private readonly getMatchedExpensesService: GetMatchedTransactionsByExpenses,
|
||||
private readonly getMatchedManualJournalsService: GetMatchedTransactionsByManualJournals,
|
||||
private readonly getMatchedCashflowService: GetMatchedTransactionsByCashflow,
|
||||
) {
|
||||
constructor() {
|
||||
this.boot();
|
||||
}
|
||||
|
||||
get registered() {
|
||||
return [
|
||||
{ type: 'SaleInvoice', service: this.getMatchedInvoicesService },
|
||||
{ type: 'Bill', service: this.getMatchedBillsService },
|
||||
{ type: 'Expense', service: this.getMatchedExpensesService },
|
||||
{ type: 'SaleInvoice', service: GetMatchedTransactionsByInvoices },
|
||||
{ type: 'Bill', service: GetMatchedTransactionsByBills },
|
||||
{ type: 'Expense', service: GetMatchedTransactionsByExpenses },
|
||||
{
|
||||
type: 'ManualJournal',
|
||||
service: this.getMatchedManualJournalsService,
|
||||
service: GetMatchedTransactionsByManualJournals,
|
||||
},
|
||||
{
|
||||
type: 'CashflowTransaction',
|
||||
service: this.getMatchedCashflowService,
|
||||
service: GetMatchedTransactionsByCashflow,
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -56,13 +50,14 @@ export class MatchTransactionsTypes {
|
||||
* Boots all the registered importables.
|
||||
*/
|
||||
public boot() {
|
||||
const instance = MatchTransactionsTypesRegistry.getInstance();
|
||||
if (!MatchTransactionsTypes.registry) {
|
||||
const instance = MatchTransactionsTypesRegistry.getInstance();
|
||||
|
||||
// Always register services to ensure they're available
|
||||
this.registered.forEach((registered) => {
|
||||
instance.register(registered.type, registered.service);
|
||||
});
|
||||
|
||||
MatchTransactionsTypes.registry = instance;
|
||||
this.registered.forEach((registered) => {
|
||||
// const serviceInstanace = Container.get(registered.service);
|
||||
// instance.register(registered.type, serviceInstanace);
|
||||
});
|
||||
MatchTransactionsTypes.registry = instance;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,4 +83,4 @@ const models = [
|
||||
CreateBankTransactionService
|
||||
],
|
||||
})
|
||||
export class BankingTransactionsModule { }
|
||||
export class BankingTransactionsModule {}
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
export const UncategorizedBankTransactionMeta = {
|
||||
defaultFilterField: 'createdAt',
|
||||
defaultSort: {
|
||||
sortOrder: 'DESC',
|
||||
sortField: 'created_at',
|
||||
},
|
||||
importable: true,
|
||||
fields: {
|
||||
date: {
|
||||
name: 'Date',
|
||||
column: 'date',
|
||||
fieldType: 'date',
|
||||
},
|
||||
payee: {
|
||||
name: 'Payee',
|
||||
column: 'payee',
|
||||
fieldType: 'text',
|
||||
},
|
||||
description: {
|
||||
name: 'Description',
|
||||
column: 'description',
|
||||
fieldType: 'text',
|
||||
},
|
||||
referenceNo: {
|
||||
name: 'Reference No.',
|
||||
column: 'reference_no',
|
||||
fieldType: 'text',
|
||||
},
|
||||
amount: {
|
||||
name: 'Amount',
|
||||
column: 'Amount',
|
||||
fieldType: 'numeric',
|
||||
required: true,
|
||||
},
|
||||
account: {
|
||||
name: 'Account',
|
||||
column: 'account_id',
|
||||
fieldType: 'relation',
|
||||
to: { model: 'Account', to: 'id' },
|
||||
},
|
||||
createdAt: {
|
||||
name: 'Created At',
|
||||
column: 'createdAt',
|
||||
fieldType: 'date',
|
||||
importable: false,
|
||||
},
|
||||
},
|
||||
fields2: {
|
||||
date: {
|
||||
name: 'Date',
|
||||
fieldType: 'date',
|
||||
required: true,
|
||||
},
|
||||
payee: {
|
||||
name: 'Payee',
|
||||
fieldType: 'text',
|
||||
},
|
||||
description: {
|
||||
name: 'Description',
|
||||
fieldType: 'text',
|
||||
},
|
||||
referenceNo: {
|
||||
name: 'Reference No.',
|
||||
fieldType: 'text',
|
||||
},
|
||||
amount: {
|
||||
name: 'Amount',
|
||||
fieldType: 'number',
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -2,10 +2,7 @@
|
||||
import * as moment from 'moment';
|
||||
import { Model } from 'objection';
|
||||
import { TenantBaseModel } from '@/modules/System/models/TenantBaseModel';
|
||||
import { UncategorizedBankTransactionMeta } from './UncategorizedBankTransaction.meta';
|
||||
import { InjectModelMeta } from '@/modules/Tenancy/TenancyModels/decorators/InjectModelMeta.decorator';
|
||||
|
||||
@InjectModelMeta(UncategorizedBankTransactionMeta)
|
||||
export class UncategorizedBankTransaction extends TenantBaseModel {
|
||||
readonly amount!: number;
|
||||
readonly date!: Date | string;
|
||||
|
||||
@@ -104,12 +104,6 @@ export class BillPaymentResponseDto {
|
||||
@ApiProperty({ description: 'The formatted amount', example: '100.00 USD' })
|
||||
formattedAmount: string;
|
||||
|
||||
@ApiProperty({ description: 'The formatted total', example: '100.00 USD' })
|
||||
formattedTotal: string;
|
||||
|
||||
@ApiProperty({ description: 'The formatted subtotal', example: '100.00 USD' })
|
||||
formattedSubtotal: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The date when the payment was created',
|
||||
example: '2024-01-01T12:00:00Z',
|
||||
|
||||
@@ -167,7 +167,7 @@ export const BillPaymentMeta = {
|
||||
name: 'bill_payment.field.payment_number',
|
||||
fieldType: 'text',
|
||||
unique: true,
|
||||
importHint: 'bill_payment.field.payment_number_hint',
|
||||
importHint: 'The payment number should be unique.',
|
||||
},
|
||||
paymentAccountId: {
|
||||
name: 'bill_payment.field.payment_account',
|
||||
@@ -175,7 +175,7 @@ export const BillPaymentMeta = {
|
||||
relationModel: 'Account',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
required: true,
|
||||
importHint: 'account.field.account_hint',
|
||||
importHint: 'Matches the account name or code.',
|
||||
},
|
||||
exchangeRate: {
|
||||
name: 'bill_payment.field.exchange_rate',
|
||||
@@ -203,7 +203,7 @@ export const BillPaymentMeta = {
|
||||
relationModel: 'Bill',
|
||||
relationImportMatch: 'billNumber',
|
||||
required: true,
|
||||
importHint: 'bill_payment.field.bill_hint',
|
||||
importHint: 'Matches the bill number.',
|
||||
},
|
||||
paymentAmount: {
|
||||
name: 'bill_payment.field.entries.payment_amount',
|
||||
@@ -213,7 +213,7 @@ export const BillPaymentMeta = {
|
||||
},
|
||||
},
|
||||
branchId: {
|
||||
name: 'invoice.field.branch',
|
||||
name: 'Branch',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Branch',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
|
||||
@@ -13,8 +13,6 @@ export class BillPaymentTransformer extends Transformer {
|
||||
'formattedPaymentDate',
|
||||
'formattedCreatedAt',
|
||||
'formattedAmount',
|
||||
'formattedTotal',
|
||||
'formattedSubtotal',
|
||||
'entries',
|
||||
'attachments',
|
||||
];
|
||||
@@ -49,29 +47,6 @@ export class BillPaymentTransformer extends Transformer {
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the formatted total.
|
||||
* @param {IBillPayment} billPayment
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedTotal = (billPayment: BillPayment): string => {
|
||||
return this.formatNumber(billPayment.amount, {
|
||||
currencyCode: billPayment.currencyCode,
|
||||
money: true,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the formatted subtotal.
|
||||
* @param {IBillPayment} billPayment
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedSubtotal = (billPayment: BillPayment): string => {
|
||||
return this.formatNumber(billPayment.amount, {
|
||||
currencyCode: billPayment.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retreives the bill payment entries.
|
||||
*/
|
||||
|
||||
@@ -184,76 +184,76 @@ export const BillMeta = {
|
||||
},
|
||||
fields2: {
|
||||
billNumber: {
|
||||
name: 'bill.field.bill_number',
|
||||
name: 'Bill No.',
|
||||
fieldType: 'text',
|
||||
required: true,
|
||||
},
|
||||
referenceNo: {
|
||||
name: 'bill.field.reference_no',
|
||||
name: 'Reference No.',
|
||||
fieldType: 'text',
|
||||
},
|
||||
billDate: {
|
||||
name: 'bill.field.bill_date',
|
||||
name: 'Date',
|
||||
fieldType: 'date',
|
||||
required: true,
|
||||
},
|
||||
dueDate: {
|
||||
name: 'bill.field.due_date',
|
||||
name: 'Due Date',
|
||||
fieldType: 'date',
|
||||
required: true,
|
||||
},
|
||||
vendorId: {
|
||||
name: 'bill.field.vendor',
|
||||
name: 'Vendor',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Contact',
|
||||
relationImportMatch: 'displayName',
|
||||
required: true,
|
||||
},
|
||||
exchangeRate: {
|
||||
name: 'bill.field.exchange_rate',
|
||||
name: 'Exchange Rate',
|
||||
fieldType: 'number',
|
||||
},
|
||||
note: {
|
||||
name: 'bill.field.note',
|
||||
name: 'Note',
|
||||
fieldType: 'text',
|
||||
},
|
||||
open: {
|
||||
name: 'bill.field.open',
|
||||
name: 'Open',
|
||||
fieldType: 'boolean',
|
||||
},
|
||||
entries: {
|
||||
name: 'bill.field.entries',
|
||||
name: 'Entries',
|
||||
fieldType: 'collection',
|
||||
collectionOf: 'object',
|
||||
collectionMinLength: 1,
|
||||
required: true,
|
||||
fields: {
|
||||
itemId: {
|
||||
name: 'bill.field.item',
|
||||
name: 'Item',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Item',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
required: true,
|
||||
importHint: 'bill.field.item_hint',
|
||||
importHint: 'Matches the item name or code.',
|
||||
},
|
||||
rate: {
|
||||
name: 'bill.field.rate',
|
||||
name: 'Rate',
|
||||
fieldType: 'number',
|
||||
required: true,
|
||||
},
|
||||
quantity: {
|
||||
name: 'bill.field.quantity',
|
||||
name: 'Quantity',
|
||||
fieldType: 'number',
|
||||
required: true,
|
||||
},
|
||||
description: {
|
||||
name: 'bill.field.description',
|
||||
name: 'Line Description',
|
||||
fieldType: 'text',
|
||||
},
|
||||
},
|
||||
},
|
||||
branchId: {
|
||||
name: 'invoice.field.branch',
|
||||
name: 'Branch',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Branch',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
@@ -261,7 +261,7 @@ export const BillMeta = {
|
||||
required: true,
|
||||
},
|
||||
warehouseId: {
|
||||
name: 'invoice.field.warehouse',
|
||||
name: 'Warehouse',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Warehouse',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
|
||||
@@ -94,7 +94,6 @@ export class BillTransformer extends Transformer {
|
||||
protected formattedDueAmount = (bill: Bill): string => {
|
||||
return this.formatNumber(bill.dueAmount, {
|
||||
currencyCode: bill.currencyCode,
|
||||
money: true,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -170,7 +169,6 @@ export class BillTransformer extends Transformer {
|
||||
protected totalFormatted = (bill: Bill): string => {
|
||||
return this.formatNumber(bill.total, {
|
||||
currencyCode: bill.currencyCode,
|
||||
money: true,
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ export class BillBranchValidateSubscriber {
|
||||
* Validate branch existance on bill creating.
|
||||
* @param {IBillCreatingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.bill.onCreating)
|
||||
@OnEvent(events.bill.onCreating, { suppressErrors: false })
|
||||
async validateBranchExistanceOnBillCreating({
|
||||
billDTO,
|
||||
}: IBillCreatingPayload) {
|
||||
@@ -30,7 +30,7 @@ export class BillBranchValidateSubscriber {
|
||||
* Validate branch existance once bill editing.
|
||||
* @param {IBillEditingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.bill.onEditing)
|
||||
@OnEvent(events.bill.onEditing, { suppressErrors: false })
|
||||
async validateBranchExistanceOnBillEditing({ billDTO }: IBillEditingPayload) {
|
||||
await this.validateBranchExistance.validateTransactionBranchWhenActive(
|
||||
billDTO.branchId,
|
||||
|
||||
@@ -14,7 +14,7 @@ export class CashflowBranchDTOValidatorSubscriber {
|
||||
* Validate branch existance once cashflow transaction creating.
|
||||
* @param {ICommandCashflowCreatingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.cashflow.onTransactionCreating)
|
||||
@OnEvent(events.cashflow.onTransactionCreating, { suppressErrors: false })
|
||||
async validateBranchExistanceOnCashflowTransactionCreating({
|
||||
newTransactionDTO,
|
||||
}: ICommandCashflowCreatingPayload) {
|
||||
|
||||
@@ -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)
|
||||
@OnEvent(events.customers.onCreating, { suppressErrors: false })
|
||||
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)
|
||||
@OnEvent(events.customers.onOpeningBalanceChanging, { suppressErrors: false })
|
||||
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)
|
||||
@OnEvent(events.vendors.onCreating, { suppressErrors: false })
|
||||
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)
|
||||
@OnEvent(events.vendors.onOpeningBalanceChanging, { suppressErrors: false })
|
||||
async validateBranchExistanceOnVendorOpeningBalanceEditing({
|
||||
openingBalanceEditDTO,
|
||||
}: IVendorOpeningBalanceEditingPayload) {
|
||||
|
||||
@@ -15,7 +15,7 @@ export class CreditNoteBranchValidateSubscriber {
|
||||
* Validate branch existance on credit note creating.
|
||||
* @param {ICreditNoteCreatingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.creditNote.onCreating)
|
||||
@OnEvent(events.creditNote.onCreating, { suppressErrors: false })
|
||||
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)
|
||||
@OnEvent(events.creditNote.onEditing, { suppressErrors: false })
|
||||
async validateBranchExistanceOnCreditEditing({
|
||||
creditNoteEditDTO,
|
||||
}: ICreditNoteEditingPayload) {
|
||||
|
||||
@@ -14,7 +14,7 @@ export class CreditNoteRefundBranchValidateSubscriber {
|
||||
* Validate branch existance on refund credit note creating.
|
||||
* @param {IRefundCreditNoteCreatingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.creditNote.onRefundCreating)
|
||||
@OnEvent(events.creditNote.onRefundCreating, { suppressErrors: false })
|
||||
async validateBranchExistanceOnCreditRefundCreating({
|
||||
newCreditNoteDTO,
|
||||
}: IRefundCreditNoteCreatingPayload) {
|
||||
|
||||
@@ -16,7 +16,7 @@ export class ExpenseBranchValidateSubscriber {
|
||||
* Validate branch existance once expense transaction creating.
|
||||
* @param {IExpenseCreatingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.expenses.onCreating)
|
||||
@OnEvent(events.expenses.onCreating, { suppressErrors: false })
|
||||
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)
|
||||
@OnEvent(events.expenses.onEditing, { suppressErrors: false })
|
||||
async validateBranchExistanceOnExpenseEditing({
|
||||
expenseDTO,
|
||||
}: IExpenseEventEditingPayload) {
|
||||
|
||||
@@ -14,7 +14,7 @@ export class InventoryAdjustmentBranchValidateSubscriber {
|
||||
* Validate branch existance on inventory adjustment creating.
|
||||
* @param {IInventoryAdjustmentCreatingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.inventoryAdjustment.onQuickCreating)
|
||||
@OnEvent(events.inventoryAdjustment.onQuickCreating, { suppressErrors: false })
|
||||
async validateBranchExistanceOnInventoryCreating({
|
||||
quickAdjustmentDTO,
|
||||
}: IInventoryAdjustmentCreatingPayload) {
|
||||
|
||||
@@ -17,7 +17,7 @@ export class InvoiceBranchValidateSubscriber {
|
||||
* Validate branch existance on invoice creating.
|
||||
* @param {ISaleInvoiceCreatingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.saleInvoice.onCreating)
|
||||
@OnEvent(events.saleInvoice.onCreating, { suppressErrors: false })
|
||||
async validateBranchExistanceOnInvoiceCreating({
|
||||
saleInvoiceDTO,
|
||||
}: ISaleInvoiceCreatingPaylaod) {
|
||||
@@ -30,7 +30,7 @@ export class InvoiceBranchValidateSubscriber {
|
||||
* Validate branch existance once invoice editing.
|
||||
* @param {ISaleInvoiceEditingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.saleInvoice.onEditing)
|
||||
@OnEvent(events.saleInvoice.onEditing, { suppressErrors: false })
|
||||
async validateBranchExistanceOnInvoiceEditing({
|
||||
saleInvoiceDTO,
|
||||
}: ISaleInvoiceEditingPayload) {
|
||||
|
||||
@@ -17,7 +17,7 @@ export class PaymentMadeBranchValidateSubscriber {
|
||||
* Validate branch existance on estimate creating.
|
||||
* @param {ISaleEstimateCreatedPayload} payload
|
||||
*/
|
||||
@OnEvent(events.billPayment.onCreating)
|
||||
@OnEvent(events.billPayment.onCreating, { suppressErrors: false })
|
||||
async validateBranchExistanceOnPaymentCreating({
|
||||
billPaymentDTO,
|
||||
}: IBillPaymentCreatingPayload) {
|
||||
@@ -30,7 +30,7 @@ export class PaymentMadeBranchValidateSubscriber {
|
||||
* Validate branch existance once estimate editing.
|
||||
* @param {ISaleEstimateEditingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.billPayment.onEditing)
|
||||
@OnEvent(events.billPayment.onEditing, { suppressErrors: false })
|
||||
async validateBranchExistanceOnPaymentEditing({
|
||||
billPaymentDTO,
|
||||
}: IBillPaymentEditingPayload) {
|
||||
|
||||
@@ -17,7 +17,7 @@ export class PaymentReceiveBranchValidateSubscriber {
|
||||
* Validate branch existance on estimate creating.
|
||||
* @param {IPaymentReceivedCreatingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.paymentReceive.onCreating)
|
||||
@OnEvent(events.paymentReceive.onCreating, { suppressErrors: false })
|
||||
async validateBranchExistanceOnPaymentCreating({
|
||||
paymentReceiveDTO,
|
||||
}: IPaymentReceivedCreatingPayload) {
|
||||
@@ -30,7 +30,7 @@ export class PaymentReceiveBranchValidateSubscriber {
|
||||
* Validate branch existance once estimate editing.
|
||||
* @param {IPaymentReceivedEditingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.paymentReceive.onEditing)
|
||||
@OnEvent(events.paymentReceive.onEditing, { suppressErrors: false })
|
||||
async validateBranchExistanceOnPaymentEditing({
|
||||
paymentReceiveDTO,
|
||||
}: IPaymentReceivedEditingPayload) {
|
||||
|
||||
@@ -17,7 +17,7 @@ export class SaleEstimateBranchValidateSubscriber {
|
||||
* Validate branch existance on estimate creating.
|
||||
* @param {ISaleEstimateCreatedPayload} payload
|
||||
*/
|
||||
@OnEvent(events.saleEstimate.onCreating)
|
||||
@OnEvent(events.saleEstimate.onCreating, { suppressErrors: false })
|
||||
async validateBranchExistanceOnEstimateCreating({
|
||||
estimateDTO,
|
||||
}: ISaleEstimateCreatingPayload) {
|
||||
@@ -30,7 +30,7 @@ export class SaleEstimateBranchValidateSubscriber {
|
||||
* Validate branch existance once estimate editing.
|
||||
* @param {ISaleEstimateEditingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.saleEstimate.onEditing)
|
||||
@OnEvent(events.saleEstimate.onEditing, { suppressErrors: false })
|
||||
async validateBranchExistanceOnEstimateEditing({
|
||||
estimateDTO,
|
||||
}: ISaleEstimateEditingPayload) {
|
||||
|
||||
@@ -17,7 +17,7 @@ export class SaleReceiptBranchValidateSubscriber {
|
||||
* Validate branch existance on estimate creating.
|
||||
* @param {ISaleReceiptCreatingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.saleReceipt.onCreating)
|
||||
@OnEvent(events.saleReceipt.onCreating, { suppressErrors: false })
|
||||
async validateBranchExistanceOnInvoiceCreating({
|
||||
saleReceiptDTO,
|
||||
}: ISaleReceiptCreatingPayload) {
|
||||
@@ -30,7 +30,7 @@ export class SaleReceiptBranchValidateSubscriber {
|
||||
* Validate branch existance once estimate editing.
|
||||
* @param {ISaleReceiptEditingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.saleReceipt.onEditing)
|
||||
@OnEvent(events.saleReceipt.onEditing, { suppressErrors: false })
|
||||
async validateBranchExistanceOnInvoiceEditing({
|
||||
saleReceiptDTO,
|
||||
}: ISaleReceiptEditingPayload) {
|
||||
|
||||
@@ -17,7 +17,7 @@ export class VendorCreditBranchValidateSubscriber {
|
||||
* Validate branch existance on estimate creating.
|
||||
* @param {ISaleEstimateCreatedPayload} payload
|
||||
*/
|
||||
@OnEvent(events.vendorCredit.onCreating)
|
||||
@OnEvent(events.vendorCredit.onCreating, { suppressErrors: false })
|
||||
async validateBranchExistanceOnCreditCreating({
|
||||
vendorCreditCreateDTO,
|
||||
}: IVendorCreditCreatingPayload) {
|
||||
@@ -30,7 +30,7 @@ export class VendorCreditBranchValidateSubscriber {
|
||||
* Validate branch existance once estimate editing.
|
||||
* @param {ISaleEstimateEditingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.vendorCredit.onEditing)
|
||||
@OnEvent(events.vendorCredit.onEditing, { suppressErrors: false })
|
||||
async validateBranchExistanceOnCreditEditing({
|
||||
vendorCreditDTO,
|
||||
}: IVendorCreditEditingPayload) {
|
||||
|
||||
@@ -14,7 +14,7 @@ export class VendorCreditRefundBranchValidateSubscriber {
|
||||
* Validate branch existance on refund credit note creating.
|
||||
* @param {IRefundVendorCreditCreatingPayload} payload
|
||||
*/
|
||||
@OnEvent(events.vendorCredit.onRefundCreating)
|
||||
@OnEvent(events.vendorCredit.onRefundCreating, { suppressErrors: false })
|
||||
async validateBranchExistanceOnCreditRefundCreating({
|
||||
refundVendorCreditDTO,
|
||||
}: IRefundVendorCreditCreatingPayload) {
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -164,73 +164,73 @@ export const CreditNoteMeta = {
|
||||
},
|
||||
fields2: {
|
||||
customerId: {
|
||||
name: 'credit_note.field.customer',
|
||||
name: 'Customer',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Contact',
|
||||
relationImportMatch: 'displayName',
|
||||
required: true,
|
||||
},
|
||||
exchangeRate: {
|
||||
name: 'credit_note.field.exchange_rate',
|
||||
name: 'Exchange Rate',
|
||||
fieldType: 'number',
|
||||
},
|
||||
creditNoteDate: {
|
||||
name: 'credit_note.field.credit_note_date',
|
||||
name: 'Credit Note Date',
|
||||
fieldType: 'date',
|
||||
required: true,
|
||||
},
|
||||
referenceNo: {
|
||||
name: 'credit_note.field.reference_no',
|
||||
name: 'Reference No.',
|
||||
fieldType: 'text',
|
||||
},
|
||||
note: {
|
||||
name: 'credit_note.field.note',
|
||||
name: 'Note',
|
||||
fieldType: 'text',
|
||||
},
|
||||
termsConditions: {
|
||||
name: 'credit_note.field.terms_conditions',
|
||||
name: 'Terms & Conditions',
|
||||
fieldType: 'text',
|
||||
},
|
||||
creditNoteNumber: {
|
||||
name: 'credit_note.field.credit_note_number',
|
||||
name: 'Credit Note Number',
|
||||
fieldType: 'text',
|
||||
},
|
||||
open: {
|
||||
name: 'credit_note.field.open',
|
||||
name: 'Open',
|
||||
fieldType: 'boolean',
|
||||
},
|
||||
entries: {
|
||||
name: 'credit_note.field.entries',
|
||||
name: 'Entries',
|
||||
fieldType: 'collection',
|
||||
collectionOf: 'object',
|
||||
collectionMinLength: 1,
|
||||
fields: {
|
||||
itemId: {
|
||||
name: 'credit_note.field.item',
|
||||
name: 'Item',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Item',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
required: true,
|
||||
importHint: 'invoice.field.item_hint',
|
||||
importHint: 'Matches the item name or code.',
|
||||
},
|
||||
rate: {
|
||||
name: 'credit_note.field.rate',
|
||||
name: 'Rate',
|
||||
fieldType: 'number',
|
||||
required: true,
|
||||
},
|
||||
quantity: {
|
||||
name: 'credit_note.field.quantity',
|
||||
name: 'Quantity',
|
||||
fieldType: 'number',
|
||||
required: true,
|
||||
},
|
||||
description: {
|
||||
name: 'credit_note.field.description',
|
||||
name: 'Description',
|
||||
fieldType: 'text',
|
||||
},
|
||||
},
|
||||
},
|
||||
branchId: {
|
||||
name: 'invoice.field.branch',
|
||||
name: 'Branch',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Branch',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
@@ -238,7 +238,7 @@ export const CreditNoteMeta = {
|
||||
required: true,
|
||||
},
|
||||
warehouseId: {
|
||||
name: 'invoice.field.warehouse',
|
||||
name: 'Warehouse',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Warehouse',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
|
||||
@@ -90,7 +90,7 @@ export class CreditNoteTransformer extends Transformer {
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedSubtotal = (credit): string => {
|
||||
return this.formatNumber(credit.amount);
|
||||
return this.formatNumber(credit.amount, { money: false });
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -130,7 +130,7 @@ export class CreditNoteTransformer extends Transformer {
|
||||
* @returns {string}
|
||||
*/
|
||||
protected adjustmentFormatted = (credit): string => {
|
||||
return this.formatNumber(credit.adjustment, {
|
||||
return this.formatMoney(credit.adjustment, {
|
||||
currencyCode: credit.currencyCode,
|
||||
excerptZero: true,
|
||||
});
|
||||
@@ -156,7 +156,6 @@ export class CreditNoteTransformer extends Transformer {
|
||||
protected totalFormatted = (credit): string => {
|
||||
return this.formatNumber(credit.total, {
|
||||
currencyCode: credit.currencyCode,
|
||||
money: true,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -168,7 +167,6 @@ export class CreditNoteTransformer extends Transformer {
|
||||
protected totalLocalFormatted = (credit): string => {
|
||||
return this.formatNumber(credit.totalLocal, {
|
||||
currencyCode: credit.currencyCode,
|
||||
money: true,
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,117 +1,103 @@
|
||||
// import { Service, Inject } from 'typedi';
|
||||
// import { AccountNormal, ICustomer, ILedgerEntry } from '@/interfaces';
|
||||
// import Ledger from '@/services/Accounting/Ledger';
|
||||
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';
|
||||
|
||||
// @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,
|
||||
@Injectable()
|
||||
export class CustomerGLEntries {
|
||||
/**
|
||||
* Retrieves the customer opening balance common entry attributes.
|
||||
*/
|
||||
private getCustomerOpeningGLCommonEntry = (customer: Customer) => {
|
||||
return {
|
||||
exchangeRate: customer.openingBalanceExchangeRate,
|
||||
currencyCode: customer.currencyCode,
|
||||
|
||||
// transactionType: 'CustomerOpeningBalance',
|
||||
// transactionId: customer.id,
|
||||
transactionType: 'CustomerOpeningBalance',
|
||||
transactionId: customer.id,
|
||||
|
||||
// date: customer.openingBalanceAt,
|
||||
// userId: customer.userId,
|
||||
// contactId: customer.id,
|
||||
date: customer.openingBalanceAt,
|
||||
contactId: customer.id,
|
||||
|
||||
// credit: 0,
|
||||
// debit: 0,
|
||||
credit: 0,
|
||||
debit: 0,
|
||||
|
||||
// branchId: customer.openingBalanceBranchId,
|
||||
// };
|
||||
// };
|
||||
branchId: customer.openingBalanceBranchId,
|
||||
};
|
||||
};
|
||||
|
||||
// /**
|
||||
// * 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);
|
||||
/**
|
||||
* Retrieves the customer opening GL credit entry.
|
||||
*/
|
||||
private getCustomerOpeningGLCreditEntry = (
|
||||
ARAccountId: number,
|
||||
customer: Customer
|
||||
): 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.
|
||||
// * @param {number} incomeAccountId
|
||||
// * @param {ICustomer} customer
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getCustomerOpeningGLDebitEntry = (
|
||||
// incomeAccountId: number,
|
||||
// customer: ICustomer
|
||||
// ): ILedgerEntry => {
|
||||
// const commonEntry = this.getCustomerOpeningGLCommonEntry(customer);
|
||||
/**
|
||||
* Retrieves the customer opening GL debit entry.
|
||||
*/
|
||||
private getCustomerOpeningGLDebitEntry = (
|
||||
incomeAccountId: number,
|
||||
customer: Customer
|
||||
): 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.
|
||||
// * @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 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 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);
|
||||
// };
|
||||
// }
|
||||
/**
|
||||
* 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);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,90 +1,84 @@
|
||||
// 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';
|
||||
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';
|
||||
|
||||
// @Service()
|
||||
// export class CustomerGLEntriesStorage {
|
||||
// @Inject()
|
||||
// private tenancy: HasTenancyService;
|
||||
@Injectable()
|
||||
export class CustomerGLEntriesStorage {
|
||||
constructor(
|
||||
private readonly ledgerStorage: LedgerStorageService,
|
||||
private readonly accountRepository: AccountRepository,
|
||||
private readonly customerGLEntries: CustomerGLEntries,
|
||||
|
||||
// @Inject()
|
||||
// private ledegrRepository: LedgerStorageService;
|
||||
@Inject(Account.name)
|
||||
private readonly accountModel: TenantModelProxy<typeof Account>,
|
||||
|
||||
// @Inject()
|
||||
// private customerGLEntries: CustomerGLEntries;
|
||||
@Inject(Customer.name)
|
||||
private readonly customerModel: TenantModelProxy<typeof Customer>,
|
||||
) { }
|
||||
|
||||
// /**
|
||||
// * 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);
|
||||
/**
|
||||
* Customer opening balance journals.
|
||||
*/
|
||||
public writeCustomerOpeningBalance = async (
|
||||
customerId: number,
|
||||
trx?: Knex.Transaction,
|
||||
) => {
|
||||
const customer = await this.customerModel()
|
||||
.query(trx)
|
||||
.findById(customerId);
|
||||
|
||||
// const customer = await Customer.query(trx).findById(customerId);
|
||||
// Finds the income account.
|
||||
const incomeAccount = await this.accountModel()
|
||||
.query(trx)
|
||||
.findOne({ slug: 'other-income' });
|
||||
|
||||
// // 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);
|
||||
// };
|
||||
// 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);
|
||||
};
|
||||
|
||||
// /**
|
||||
// * 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
|
||||
// );
|
||||
// };
|
||||
/**
|
||||
* Reverts the customer opening balance GL entries.
|
||||
*/
|
||||
public revertCustomerOpeningBalance = async (
|
||||
customerId: number,
|
||||
trx?: Knex.Transaction,
|
||||
) => {
|
||||
await this.ledgerStorage.deleteByReference(
|
||||
customerId,
|
||||
'CustomerOpeningBalance',
|
||||
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);
|
||||
/**
|
||||
* 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);
|
||||
|
||||
// // Write the customer opening balance entries.
|
||||
// await this.writeCustomerOpeningBalance(tenantId, customerId, trx);
|
||||
// };
|
||||
// }
|
||||
// Write the customer opening balance entries.
|
||||
await this.writeCustomerOpeningBalance(customerId, trx);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -9,10 +9,7 @@ import {
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { CustomersApplication } from './CustomersApplication.service';
|
||||
import {
|
||||
ICustomerOpeningBalanceEditDTO,
|
||||
ICustomersFilter,
|
||||
} from './types/Customers.types';
|
||||
import { CustomerOpeningBalanceEditDto } from './dtos/CustomerOpeningBalanceEdit.dto';
|
||||
import {
|
||||
ApiOperation,
|
||||
ApiResponse,
|
||||
@@ -106,7 +103,7 @@ export class CustomersController {
|
||||
})
|
||||
editOpeningBalance(
|
||||
@Param('id') customerId: number,
|
||||
@Body() openingBalanceDTO: ICustomerOpeningBalanceEditDTO,
|
||||
@Body() openingBalanceDTO: CustomerOpeningBalanceEditDto,
|
||||
) {
|
||||
return this.customersApplication.editOpeningBalance(
|
||||
customerId,
|
||||
|
||||
@@ -18,9 +18,19 @@ 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],
|
||||
imports: [
|
||||
TenancyDatabaseModule,
|
||||
DynamicListModule,
|
||||
LedgerModule,
|
||||
AccountsModule,
|
||||
],
|
||||
controllers: [CustomersController],
|
||||
providers: [
|
||||
ActivateCustomer,
|
||||
@@ -41,6 +51,9 @@ import { ValidateBulkDeleteCustomersService } from './ValidateBulkDeleteCustomer
|
||||
GetCustomers,
|
||||
BulkDeleteCustomersService,
|
||||
ValidateBulkDeleteCustomersService,
|
||||
CustomerGLEntries,
|
||||
CustomerGLEntriesStorage,
|
||||
CustomerWriteGLOpeningBalanceSubscriber,
|
||||
],
|
||||
})
|
||||
export class CustomersModule {}
|
||||
|
||||
@@ -4,10 +4,7 @@ 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 {
|
||||
ICustomerOpeningBalanceEditDTO,
|
||||
ICustomersFilter,
|
||||
} from './types/Customers.types';
|
||||
import { CustomerOpeningBalanceEditDto } from './dtos/CustomerOpeningBalanceEdit.dto';
|
||||
import { CreateCustomerDto } from './dtos/CreateCustomer.dto';
|
||||
import { EditCustomerDto } from './dtos/EditCustomer.dto';
|
||||
import { GetCustomers } from './queries/GetCustomers.service';
|
||||
@@ -18,12 +15,12 @@ import { ValidateBulkDeleteCustomersService } from './ValidateBulkDeleteCustomer
|
||||
@Injectable()
|
||||
export class CustomersApplication {
|
||||
constructor(
|
||||
private getCustomerService: GetCustomerService,
|
||||
private createCustomerService: CreateCustomer,
|
||||
private editCustomerService: EditCustomer,
|
||||
private deleteCustomerService: DeleteCustomer,
|
||||
private editOpeningBalanceService: EditOpeningBalanceCustomer,
|
||||
private getCustomersService: GetCustomers,
|
||||
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 readonly bulkDeleteCustomersService: BulkDeleteCustomersService,
|
||||
private readonly validateBulkDeleteCustomersService: ValidateBulkDeleteCustomersService,
|
||||
) {}
|
||||
@@ -72,7 +69,7 @@ export class CustomersApplication {
|
||||
*/
|
||||
public editOpeningBalance = (
|
||||
customerId: number,
|
||||
openingBalanceEditDTO: ICustomerOpeningBalanceEditDTO,
|
||||
openingBalanceEditDTO: CustomerOpeningBalanceEditDto,
|
||||
) => {
|
||||
return this.editOpeningBalanceService.changeOpeningBalance(
|
||||
customerId,
|
||||
@@ -82,7 +79,7 @@ export class CustomersApplication {
|
||||
|
||||
/**
|
||||
* Retrieve customers paginated list.
|
||||
* @param {ICustomersFilter} filter - Cusotmers filter.
|
||||
* @param {GetCustomersQueryDto} filter - Cusotmers filter.
|
||||
*/
|
||||
public getCustomers = (filterDTO: GetCustomersQueryDto) => {
|
||||
return this.getCustomersService.getCustomersList(filterDTO);
|
||||
|
||||
@@ -31,7 +31,7 @@ export class CreateCustomer {
|
||||
|
||||
/**
|
||||
* Creates a new customer.
|
||||
* @param {ICustomerNewDTO} customerDTO
|
||||
* @param {CreateCustomerDto} customerDTO
|
||||
* @return {Promise<ICustomer>}
|
||||
*/
|
||||
public async createCustomer(
|
||||
|
||||
@@ -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 {ICustomerOpeningBalanceEditDTO} openingBalanceEditDTO
|
||||
* @param {CustomerOpeningBalanceEditDto} openingBalanceEditDTO
|
||||
*/
|
||||
public async changeOpeningBalance(
|
||||
customerId: number,
|
||||
openingBalanceEditDTO: ICustomerOpeningBalanceEditDTO,
|
||||
openingBalanceEditDTO: CustomerOpeningBalanceEditDto,
|
||||
): Promise<Customer> {
|
||||
// Retrieves the old customer or throw not found error.
|
||||
const oldCustomer = await this.customerModel()
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
IsString,
|
||||
ValidateIf,
|
||||
} from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsOptional, ToNumber } from '@/common/decorators/Validators';
|
||||
@@ -40,10 +41,11 @@ export class CreateCustomerDto extends ContactAddressDto {
|
||||
|
||||
@ApiProperty({
|
||||
required: false,
|
||||
description: 'Opening balance date',
|
||||
description: 'Opening balance date (required when openingBalance is provided)',
|
||||
example: '2024-01-01',
|
||||
})
|
||||
@IsOptional()
|
||||
@ValidateIf((o) => o.openingBalance != null)
|
||||
@IsNotEmpty({ message: 'openingBalanceAt is required when openingBalance is provided' })
|
||||
@IsString()
|
||||
openingBalanceAt?: string;
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,91 +1,63 @@
|
||||
// import { Service, Inject } from 'typedi';
|
||||
// import {
|
||||
// ICustomerEventCreatedPayload,
|
||||
// ICustomerEventDeletedPayload,
|
||||
// ICustomerOpeningBalanceEditedPayload,
|
||||
// } from '@/interfaces';
|
||||
// import events from '@/subscribers/events';
|
||||
// import { CustomerGLEntriesStorage } from '../CustomerGLEntriesStorage';
|
||||
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';
|
||||
|
||||
// @Service()
|
||||
// export class CustomerWriteGLOpeningBalanceSubscriber {
|
||||
// @Inject()
|
||||
// private customerGLEntries: CustomerGLEntriesStorage;
|
||||
@Injectable()
|
||||
export class CustomerWriteGLOpeningBalanceSubscriber {
|
||||
constructor(private readonly customerGLEntries: CustomerGLEntriesStorage) { }
|
||||
|
||||
// /**
|
||||
// * 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 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// /**
|
||||
// * 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 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 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
|
||||
// );
|
||||
// }
|
||||
// };
|
||||
// }
|
||||
/**
|
||||
* 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ 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.
|
||||
@@ -113,23 +114,16 @@ export enum VendorAction {
|
||||
View = 'View',
|
||||
}
|
||||
|
||||
export interface ICustomerOpeningBalanceEditDTO {
|
||||
openingBalance: number;
|
||||
openingBalanceAt: Date | string;
|
||||
openingBalanceExchangeRate: number;
|
||||
openingBalanceBranchId?: number;
|
||||
}
|
||||
|
||||
export interface ICustomerOpeningBalanceEditingPayload {
|
||||
oldCustomer: Customer;
|
||||
openingBalanceEditDTO: ICustomerOpeningBalanceEditDTO;
|
||||
openingBalanceEditDTO: CustomerOpeningBalanceEditDto;
|
||||
trx?: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface ICustomerOpeningBalanceEditedPayload {
|
||||
customer: Customer;
|
||||
oldCustomer: Customer;
|
||||
openingBalanceEditDTO: ICustomerOpeningBalanceEditDTO;
|
||||
openingBalanceEditDTO: CustomerOpeningBalanceEditDto;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,10 +5,10 @@ import { ExpensesSampleData } from './constants';
|
||||
import { CreateExpense } from './commands/CreateExpense.service';
|
||||
import { CreateExpenseDto } from './dtos/Expense.dto';
|
||||
import { ImportableService } from '../Import/decorators/Import.decorator';
|
||||
import { Expense } from './models/Expense.model';
|
||||
import { ManualJournal } from '../ManualJournals/models/ManualJournal';
|
||||
|
||||
@Injectable()
|
||||
@ImportableService({ name: Expense.name })
|
||||
@ImportableService({ name: ManualJournal.name })
|
||||
export class ExpensesImportable extends Importable {
|
||||
constructor(private readonly createExpenseService: CreateExpense) {
|
||||
super();
|
||||
|
||||
@@ -135,7 +135,7 @@ export const ExpenseMeta = {
|
||||
relationModel: 'Account',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
required: true,
|
||||
importHint: 'account.field.account_hint',
|
||||
importHint: 'Matches the account name or code.',
|
||||
},
|
||||
referenceNo: {
|
||||
name: 'expense.field.reference_no',
|
||||
@@ -169,7 +169,7 @@ export const ExpenseMeta = {
|
||||
relationModel: 'Account',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
required: true,
|
||||
importHint: 'account.field.account_hint',
|
||||
importHint: 'Matches the account name or code.',
|
||||
},
|
||||
amount: {
|
||||
name: 'expense.field.amount',
|
||||
@@ -187,7 +187,7 @@ export const ExpenseMeta = {
|
||||
fieldType: 'boolean',
|
||||
},
|
||||
branchId: {
|
||||
name: 'invoice.field.branch',
|
||||
name: 'Branch',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Branch',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ChromiumlyTenancy } from '../ChromiumlyTenancy/ChromiumlyTenancy.service';
|
||||
import { renderExportResourceTableTemplateHtml } from '@bigcapital/pdf-templates';
|
||||
import { TemplateInjectable } from '../TemplateInjectable/TemplateInjectable.service';
|
||||
import { mapPdfRows } from './utils';
|
||||
|
||||
@Injectable()
|
||||
export class ExportPdf {
|
||||
constructor(
|
||||
private readonly templateInjectable: TemplateInjectable,
|
||||
private readonly chromiumlyTenancy: ChromiumlyTenancy,
|
||||
) { }
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Generates the pdf table sheet for the given data and columns.
|
||||
@@ -18,18 +19,21 @@ export class ExportPdf {
|
||||
* @returns
|
||||
*/
|
||||
public async pdf(
|
||||
columns: { accessor: string; name?: string; style?: string; group?: string }[],
|
||||
columns: { accessor: string },
|
||||
data: Record<string, any>,
|
||||
sheetTitle: string = '',
|
||||
sheetDescription: string = ''
|
||||
) {
|
||||
const rows = mapPdfRows(columns, data);
|
||||
|
||||
const htmlContent = renderExportResourceTableTemplateHtml({
|
||||
table: { rows, columns },
|
||||
sheetTitle,
|
||||
sheetDescription,
|
||||
});
|
||||
const htmlContent = await this.templateInjectable.render(
|
||||
'modules/export-resource-table',
|
||||
{
|
||||
table: { rows, columns },
|
||||
sheetTitle,
|
||||
sheetDescription,
|
||||
}
|
||||
);
|
||||
// Convert the HTML content to PDF
|
||||
return this.chromiumlyTenancy.convertHtmlContent(htmlContent, {
|
||||
margins: { top: 0.2, bottom: 0.2, left: 0.2, right: 0.2 },
|
||||
|
||||
@@ -211,7 +211,7 @@ export class InventoryValuationSheet extends FinancialSheet {
|
||||
* Detarmines whether the items post filter is active.
|
||||
*/
|
||||
private isItemsPostFilter = (): boolean => {
|
||||
return !isEmpty(this.query.itemsIds);
|
||||
return isEmpty(this.query.itemsIds);
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -18,7 +18,7 @@ export class InventoryValuationSheetService {
|
||||
private readonly inventoryValuationMeta: InventoryValuationMetaInjectable,
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
private readonly inventoryValuationSheetRepository: InventoryValuationSheetRepository,
|
||||
) { }
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Inventory valuation sheet.
|
||||
|
||||
@@ -172,10 +172,7 @@ export class TrialBalanceSheet extends FinancialSheet {
|
||||
private filterNoneTransactions = (
|
||||
accountNode: ITrialBalanceAccount
|
||||
): boolean => {
|
||||
const accountLedger = this.repository.totalAccountsLedger.whereAccountId(
|
||||
accountNode.id,
|
||||
);
|
||||
return !accountLedger.isEmpty();
|
||||
return false === this.repository.totalAccountsLedger.isEmpty();
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -22,7 +22,7 @@ export class ImportFileCommon {
|
||||
private readonly importFileValidator: ImportFileDataValidator,
|
||||
private readonly resource: ResourceService,
|
||||
private readonly importableRegistry: ImportableRegistry,
|
||||
) { }
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Imports the given parsed data to the resource storage through registered importable service.
|
||||
|
||||
@@ -18,7 +18,7 @@ import { CurrencyParsingDTOs } from './_constants';
|
||||
export class ImportFileDataTransformer {
|
||||
constructor(
|
||||
private readonly resource: ResourceService,
|
||||
) { }
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Parses the given sheet data before passing to the service layer.
|
||||
@@ -55,8 +55,9 @@ export class ImportFileDataTransformer {
|
||||
|
||||
/**
|
||||
* Aggregates parsed data based on resource metadata configuration.
|
||||
* @param {string} resourceName - The resource name.
|
||||
* @param {Record<string, any>} parsedData - The parsed data to aggregate.
|
||||
* @param {number} tenantId
|
||||
* @param {string} resourceName
|
||||
* @param {Record<string, any>} parsedData
|
||||
* @returns {Record<string, any>[]}
|
||||
*/
|
||||
public aggregateParsedValues(
|
||||
@@ -109,11 +110,8 @@ export class ImportFileDataTransformer {
|
||||
valueDTOs: Record<string, any>[],
|
||||
trx?: Knex.Transaction
|
||||
): Promise<Record<string, any>[]> {
|
||||
// Create a model resolver function that uses ResourceService
|
||||
const modelResolver = (modelName: string) => {
|
||||
return this.resource.getResourceModel(modelName)();
|
||||
};
|
||||
const _valueParser = valueParser(fields, modelResolver, trx);
|
||||
// const tenantModels = this.tenancy.models(tenantId);
|
||||
const _valueParser = valueParser(fields, {}, trx);
|
||||
const _keyParser = parseKey(fields);
|
||||
|
||||
const parseAsync = async (valueDTO) => {
|
||||
|
||||
@@ -19,8 +19,7 @@ export class ImportFileDataValidator {
|
||||
|
||||
/**
|
||||
* Validates the given mapped DTOs and returns errors with their index.
|
||||
* @param {ResourceMetaFieldsMap} importableFields - Already localized fields from ResourceService
|
||||
* @param {Record<string, any>} data
|
||||
* @param {Record<string, any>} mappedDTOs
|
||||
* @returns {Promise<void | ImportInsertError[]>}
|
||||
*/
|
||||
public async validateData(
|
||||
|
||||
@@ -24,7 +24,7 @@ export class ImportFileUploadService {
|
||||
|
||||
@Inject(ImportModel.name)
|
||||
private readonly importModel: typeof ImportModel,
|
||||
) { }
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Imports the specified file for the given resource.
|
||||
@@ -84,7 +84,7 @@ export class ImportFileUploadService {
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
const _params = await this.importFileCommon.transformParams(resource, params);
|
||||
const _params = this.importFileCommon.transformParams(resource, params);
|
||||
const paramsStringified = JSON.stringify(_params);
|
||||
|
||||
const tenant = await this.tenancyContext.getTenant();
|
||||
|
||||
@@ -6,7 +6,7 @@ import { ContextIdFactory, ModuleRef } from '@nestjs/core';
|
||||
|
||||
@Injectable()
|
||||
export class ImportableRegistry {
|
||||
constructor(private readonly moduleRef: ModuleRef) { }
|
||||
constructor(private readonly moduleRef: ModuleRef) {}
|
||||
/**
|
||||
* Retrieves the importable service instance of the given resource name.
|
||||
* @param {string} name
|
||||
@@ -15,12 +15,6 @@ export class ImportableRegistry {
|
||||
public async getImportable(name: string) {
|
||||
const _name = this.sanitizeResourceName(name);
|
||||
const importable = getImportableService(_name);
|
||||
|
||||
if (!importable) {
|
||||
throw new Error(
|
||||
`No importable service found for resource "${_name}". Make sure the resource has an @ImportableService decorator registered.`,
|
||||
);
|
||||
}
|
||||
const contextId = ContextIdFactory.create();
|
||||
|
||||
const importableInstance = await this.moduleRef.resolve(importable, contextId, {
|
||||
|
||||
@@ -1,287 +0,0 @@
|
||||
import { aggregate } from './_utils';
|
||||
|
||||
describe('aggregate', () => {
|
||||
describe('basic aggregation', () => {
|
||||
it('should aggregate entries with matching comparator attribute', () => {
|
||||
const input = [
|
||||
{ id: 1, name: 'John', entries: ['entry1'] },
|
||||
{ id: 2, name: 'Jane', entries: ['entry2'] },
|
||||
{ id: 1, name: 'John', entries: ['entry3'] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0]).toEqual({
|
||||
id: 1,
|
||||
name: 'John',
|
||||
entries: ['entry1', 'entry3'],
|
||||
});
|
||||
expect(result[1]).toEqual({
|
||||
id: 2,
|
||||
name: 'Jane',
|
||||
entries: ['entry2'],
|
||||
});
|
||||
});
|
||||
|
||||
it('should preserve order of first occurrence', () => {
|
||||
const input = [
|
||||
{ id: 2, entries: ['a'] },
|
||||
{ id: 1, entries: ['b'] },
|
||||
{ id: 2, entries: ['c'] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
expect(result[0].id).toBe(2);
|
||||
expect(result[1].id).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('no matching entries', () => {
|
||||
it('should return all entries unchanged when no comparator matches', () => {
|
||||
const input = [
|
||||
{ id: 1, name: 'John', entries: ['entry1'] },
|
||||
{ id: 2, name: 'Jane', entries: ['entry2'] },
|
||||
{ id: 3, name: 'Bob', entries: ['entry3'] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
expect(result).toHaveLength(3);
|
||||
expect(result).toEqual(input);
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('should return empty array when input is empty', () => {
|
||||
const result = aggregate([], 'id', 'entries');
|
||||
|
||||
expect(result).toEqual([]);
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should return single entry unchanged when input has one item', () => {
|
||||
const input = [{ id: 1, name: 'John', entries: ['entry1'] }];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual({
|
||||
id: 1,
|
||||
name: 'John',
|
||||
entries: ['entry1'],
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle multiple entries with same comparator value', () => {
|
||||
const input = [
|
||||
{ id: 1, entries: ['a'] },
|
||||
{ id: 1, entries: ['b'] },
|
||||
{ id: 1, entries: ['c'] },
|
||||
{ id: 1, entries: ['d'] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].entries).toEqual(['a', 'b', 'c', 'd']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('different comparator attributes', () => {
|
||||
it('should work with string comparator attribute', () => {
|
||||
const input = [
|
||||
{ name: 'Product A', category: 'Electronics', entries: ['item1'] },
|
||||
{ name: 'Product B', category: 'Books', entries: ['item2'] },
|
||||
{ name: 'Product C', category: 'Electronics', entries: ['item3'] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'category', 'entries');
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0]).toEqual({
|
||||
name: 'Product A',
|
||||
category: 'Electronics',
|
||||
entries: ['item1', 'item3'],
|
||||
});
|
||||
expect(result[1]).toEqual({
|
||||
name: 'Product B',
|
||||
category: 'Books',
|
||||
entries: ['item2'],
|
||||
});
|
||||
});
|
||||
|
||||
it('should not aggregate items with undefined comparator values', () => {
|
||||
const input = [
|
||||
{ id: undefined, entries: ['a'] },
|
||||
{ id: 1, entries: ['b'] },
|
||||
{ id: undefined, entries: ['c'] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
expect(result).toHaveLength(3);
|
||||
// Items with undefined id are NOT aggregated - each remains separate
|
||||
expect(result[0].entries).toEqual(['a']);
|
||||
expect(result[1].entries).toEqual(['b']);
|
||||
expect(result[2].entries).toEqual(['c']);
|
||||
});
|
||||
|
||||
it('should handle null comparator values separately', () => {
|
||||
const input = [
|
||||
{ id: null, entries: ['a'] },
|
||||
{ id: 1, entries: ['b'] },
|
||||
{ id: null, entries: ['c'] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
expect(result).toHaveLength(3);
|
||||
expect(result[0].entries).toEqual(['a']);
|
||||
expect(result[1].entries).toEqual(['b']);
|
||||
expect(result[2].entries).toEqual(['c']);
|
||||
});
|
||||
|
||||
it('should not aggregate items missing the comparatorAttr property', () => {
|
||||
const input = [
|
||||
{ id: 1, entries: ['a'] },
|
||||
{ name: 'No ID', entries: ['b'] }, // missing 'id' property
|
||||
{ id: 1, entries: ['c'] },
|
||||
{ entries: ['d'] }, // also missing 'id' property
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
// 3 entries: aggregated id:1, and two separate items without 'id' property
|
||||
expect(result).toHaveLength(3);
|
||||
// Items with id: 1 are aggregated
|
||||
expect(result[0]).toEqual({ id: 1, entries: ['a', 'c'] });
|
||||
// Items missing 'id' are NOT aggregated - each remains separate
|
||||
expect(result[1]).toEqual({ name: 'No ID', entries: ['b'] });
|
||||
expect(result[2]).toEqual({ entries: ['d'] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('different group attributes', () => {
|
||||
it('should work with different groupOn attribute name', () => {
|
||||
const input = [
|
||||
{ id: 1, items: ['item1'] },
|
||||
{ id: 1, items: ['item2'] },
|
||||
{ id: 2, items: ['item3'] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'items');
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0].items).toEqual(['item1', 'item2']);
|
||||
expect(result[1].items).toEqual(['item3']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('complex entries', () => {
|
||||
it('should aggregate entries containing objects', () => {
|
||||
const input = [
|
||||
{ invoiceId: 'INV-001', entries: [{ itemId: 1, quantity: 2 }] },
|
||||
{ invoiceId: 'INV-002', entries: [{ itemId: 2, quantity: 1 }] },
|
||||
{ invoiceId: 'INV-001', entries: [{ itemId: 3, quantity: 5 }] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'invoiceId', 'entries');
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0].entries).toEqual([
|
||||
{ itemId: 1, quantity: 2 },
|
||||
{ itemId: 3, quantity: 5 },
|
||||
]);
|
||||
expect(result[1].entries).toEqual([{ itemId: 2, quantity: 1 }]);
|
||||
});
|
||||
|
||||
it('should aggregate entries with multiple items in each entry', () => {
|
||||
const input = [
|
||||
{ id: 1, entries: ['a', 'b'] },
|
||||
{ id: 1, entries: ['c', 'd'] },
|
||||
{ id: 2, entries: ['e'] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0].entries).toEqual(['a', 'b', 'c', 'd']);
|
||||
expect(result[1].entries).toEqual(['e']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('numeric comparator values', () => {
|
||||
it('should correctly compare numeric values', () => {
|
||||
const input = [
|
||||
{ id: 1, entries: ['a'] },
|
||||
{ id: 2, entries: ['b'] },
|
||||
{ id: 1, entries: ['c'] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result.find((r) => r.id === 1).entries).toEqual(['a', 'c']);
|
||||
expect(result.find((r) => r.id === 2).entries).toEqual(['b']);
|
||||
});
|
||||
|
||||
it('should treat 0 as a valid comparator value', () => {
|
||||
const input = [
|
||||
{ id: 0, entries: ['a'] },
|
||||
{ id: 1, entries: ['b'] },
|
||||
{ id: 0, entries: ['c'] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0].entries).toEqual(['a', 'c']);
|
||||
expect(result[1].entries).toEqual(['b']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('preserving other properties', () => {
|
||||
it('should preserve all properties from the first matching entry', () => {
|
||||
const input = [
|
||||
{ id: 1, name: 'First', extra: 'data1', entries: ['a'] },
|
||||
{ id: 1, name: 'Second', extra: 'data2', entries: ['b'] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe('First');
|
||||
expect(result[0].extra).toBe('data1');
|
||||
expect(result[0].entries).toEqual(['a', 'b']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('empty entries arrays', () => {
|
||||
it('should handle empty entries arrays', () => {
|
||||
const input = [
|
||||
{ id: 1, entries: [] },
|
||||
{ id: 1, entries: ['a'] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].entries).toEqual(['a']);
|
||||
});
|
||||
|
||||
it('should handle all empty entries arrays', () => {
|
||||
const input = [
|
||||
{ id: 1, entries: [] },
|
||||
{ id: 1, entries: [] },
|
||||
];
|
||||
|
||||
const result = aggregate(input, 'id', 'entries');
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].entries).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -253,28 +253,28 @@ export const getResourceColumns = (resourceColumns: {
|
||||
}) => {
|
||||
const mapColumn =
|
||||
(group: string) =>
|
||||
([fieldKey, { name, importHint, required, order, ...field }]: [
|
||||
string,
|
||||
IModelMetaField2,
|
||||
]) => {
|
||||
const extra: Record<string, any> = {};
|
||||
const key = fieldKey;
|
||||
([fieldKey, { name, importHint, required, order, ...field }]: [
|
||||
string,
|
||||
IModelMetaField2,
|
||||
]) => {
|
||||
const extra: Record<string, any> = {};
|
||||
const key = fieldKey;
|
||||
|
||||
if (group) {
|
||||
extra.group = group;
|
||||
}
|
||||
if (field.fieldType === 'collection') {
|
||||
extra.fields = mapColumns(field.fields, key);
|
||||
}
|
||||
return {
|
||||
key,
|
||||
name,
|
||||
required,
|
||||
hint: importHint,
|
||||
order,
|
||||
...extra,
|
||||
};
|
||||
if (group) {
|
||||
extra.group = group;
|
||||
}
|
||||
if (field.fieldType === 'collection') {
|
||||
extra.fields = mapColumns(field.fields, key);
|
||||
}
|
||||
return {
|
||||
key,
|
||||
name,
|
||||
required,
|
||||
hint: importHint,
|
||||
order,
|
||||
...extra,
|
||||
};
|
||||
};
|
||||
const sortColumn = (a, b) =>
|
||||
a.order && b.order ? a.order - b.order : a.order ? -1 : b.order ? 1 : 0;
|
||||
|
||||
@@ -284,54 +284,52 @@ export const getResourceColumns = (resourceColumns: {
|
||||
return R.compose(transformInputToGroupedFields, mapColumns)(resourceColumns);
|
||||
};
|
||||
|
||||
export type ModelResolver = (modelName: string) => any;
|
||||
|
||||
// Prases the given object value based on the field key type.
|
||||
export const valueParser =
|
||||
(fields: ResourceMetaFieldsMap, modelResolver: ModelResolver, trx?: Knex.Transaction) =>
|
||||
async (value: any, key: string, group = '') => {
|
||||
let _value = value;
|
||||
(fields: ResourceMetaFieldsMap, tenantModels: any, trx?: Knex.Transaction) =>
|
||||
async (value: any, key: string, group = '') => {
|
||||
let _value = value;
|
||||
|
||||
const fieldKey = key.includes('.') ? key.split('.')[0] : key;
|
||||
const field = group ? fields[group]?.fields[fieldKey] : fields[fieldKey];
|
||||
const fieldKey = key.includes('.') ? key.split('.')[0] : key;
|
||||
const field = group ? fields[group]?.fields[fieldKey] : fields[fieldKey];
|
||||
|
||||
// Parses the boolean value.
|
||||
if (field.fieldType === 'boolean') {
|
||||
_value = parseBoolean(value);
|
||||
// Parses the boolean value.
|
||||
if (field.fieldType === 'boolean') {
|
||||
_value = parseBoolean(value);
|
||||
|
||||
// Parses the enumeration value.
|
||||
} else if (field.fieldType === 'enumeration') {
|
||||
const option = get(field, 'options', []).find(
|
||||
(option) => option.label?.toLowerCase() === value?.toLowerCase(),
|
||||
);
|
||||
_value = get(option, 'key');
|
||||
// Parses the numeric value.
|
||||
} else if (field.fieldType === 'number') {
|
||||
_value = multiNumberParse(value);
|
||||
// Parses the relation value.
|
||||
} else if (field.fieldType === 'relation') {
|
||||
const RelationModel = modelResolver(field.relationModel);
|
||||
// Parses the enumeration value.
|
||||
} else if (field.fieldType === 'enumeration') {
|
||||
const option = get(field, 'options', []).find(
|
||||
(option) => option.label?.toLowerCase() === value?.toLowerCase(),
|
||||
);
|
||||
_value = get(option, 'key');
|
||||
// Parses the numeric value.
|
||||
} else if (field.fieldType === 'number') {
|
||||
_value = multiNumberParse(value);
|
||||
// Parses the relation value.
|
||||
} else if (field.fieldType === 'relation') {
|
||||
const RelationModel = tenantModels[field.relationModel];
|
||||
|
||||
if (!RelationModel) {
|
||||
throw new Error(`The relation model of ${key} field is not exist.`);
|
||||
}
|
||||
const relationQuery = RelationModel.query(trx);
|
||||
const relationKeys = castArray(field?.relationImportMatch);
|
||||
|
||||
relationQuery.where(function () {
|
||||
relationKeys.forEach((relationKey: string) => {
|
||||
this.orWhereRaw('LOWER(??) = LOWER(?)', [relationKey, value]);
|
||||
});
|
||||
});
|
||||
const result = await relationQuery.first();
|
||||
_value = get(result, 'id');
|
||||
} else if (field.fieldType === 'collection') {
|
||||
const ObjectFieldKey = key.includes('.') ? key.split('.')[1] : key;
|
||||
const _valueParser = valueParser(fields, modelResolver);
|
||||
_value = await _valueParser(value, ObjectFieldKey, fieldKey);
|
||||
if (!RelationModel) {
|
||||
throw new Error(`The relation model of ${key} field is not exist.`);
|
||||
}
|
||||
return _value;
|
||||
};
|
||||
const relationQuery = RelationModel.query(trx);
|
||||
const relationKeys = castArray(field?.relationImportMatch);
|
||||
|
||||
relationQuery.where(function () {
|
||||
relationKeys.forEach((relationKey: string) => {
|
||||
this.orWhereRaw('LOWER(??) = LOWER(?)', [relationKey, value]);
|
||||
});
|
||||
});
|
||||
const result = await relationQuery.first();
|
||||
_value = get(result, 'id');
|
||||
} else if (field.fieldType === 'collection') {
|
||||
const ObjectFieldKey = key.includes('.') ? key.split('.')[1] : key;
|
||||
const _valueParser = valueParser(fields, tenantModels);
|
||||
_value = await _valueParser(value, ObjectFieldKey, fieldKey);
|
||||
}
|
||||
return _value;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses the field key and detarmines the key path.
|
||||
@@ -404,17 +402,12 @@ export function aggregate(
|
||||
groupOn: string,
|
||||
): Array<Record<string, any>> {
|
||||
return input.reduce((acc, curr) => {
|
||||
// Skip aggregation if the current item doesn't have the comparator attribute
|
||||
if (curr[comparatorAttr] === undefined || curr[comparatorAttr] === null) {
|
||||
acc.push({ ...curr });
|
||||
return acc;
|
||||
}
|
||||
const existingEntry = acc.find(
|
||||
(entry) => entry[comparatorAttr] === curr[comparatorAttr],
|
||||
);
|
||||
|
||||
if (existingEntry) {
|
||||
existingEntry[groupOn].push(...curr[groupOn]);
|
||||
existingEntry[groupOn].push(...curr.entries);
|
||||
} else {
|
||||
acc.push({ ...curr });
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ export class InventoryComputeCostService {
|
||||
*/
|
||||
async scheduleComputeItemCost(itemId: number, startingDate: Date | string) {
|
||||
const debounceKey = `inventory-cost-compute-debounce:${itemId}`;
|
||||
const debounceTime = 1000 * 10; // 10 seconds
|
||||
const debounceTime = 1000 * 60; // 1 minute
|
||||
|
||||
// Generate a unique job ID or use a custom identifier
|
||||
const jobId = `task-${Date.now()}-${Math.random().toString(36).substring(2)}`;
|
||||
|
||||
@@ -2,8 +2,7 @@ import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { Processor, WorkerHost } from '@nestjs/bullmq';
|
||||
import { Scope } from '@nestjs/common';
|
||||
import { Job } from 'bullmq';
|
||||
import { ClsService, UseCls } from 'nestjs-cls';
|
||||
import * as moment from 'moment';
|
||||
import { ClsService } from 'nestjs-cls';
|
||||
import { TenantJobPayload } from '@/interfaces/Tenant';
|
||||
import { InventoryComputeCostService } from '../commands/InventoryComputeCost.service';
|
||||
import { events } from '@/common/events/events';
|
||||
@@ -15,7 +14,7 @@ import { Process } from '@nestjs/bull';
|
||||
|
||||
interface ComputeItemCostJobPayload extends TenantJobPayload {
|
||||
itemId: number;
|
||||
startingDate: Date | string;
|
||||
startingDate: Date;
|
||||
}
|
||||
@Processor({
|
||||
name: ComputeItemCostQueue,
|
||||
@@ -40,34 +39,28 @@ export class ComputeItemCostProcessor extends WorkerHost {
|
||||
* @param {Job<ComputeItemCostJobPayload>} job - The job to process
|
||||
*/
|
||||
@Process(ComputeItemCostQueueJob)
|
||||
@UseCls()
|
||||
async process(job: Job<ComputeItemCostJobPayload>) {
|
||||
const { itemId, startingDate, organizationId, userId } = job.data;
|
||||
|
||||
// Parse startingDate using moment to handle both Date and string formats
|
||||
const startingDateObj = moment(startingDate).toDate();
|
||||
console.log(`Compute item cost for item ${itemId} started`);
|
||||
|
||||
console.log(`[info] Compute item cost for item ${itemId} started`, {
|
||||
payload: job.data,
|
||||
jobId: job.id
|
||||
});
|
||||
this.clsService.set('organizationId', organizationId);
|
||||
this.clsService.set('userId', userId);
|
||||
|
||||
try {
|
||||
await this.inventoryComputeCostService.computeItemCost(
|
||||
startingDateObj,
|
||||
startingDate,
|
||||
itemId,
|
||||
);
|
||||
// Emit job completed event
|
||||
await this.eventEmitter.emitAsync(
|
||||
events.inventory.onComputeItemCostJobCompleted,
|
||||
{ startingDate: startingDateObj, itemId, organizationId, userId },
|
||||
{ startingDate, itemId, organizationId, userId },
|
||||
);
|
||||
console.log(`[info] Compute item cost for item ${itemId} completed successfully`);
|
||||
|
||||
console.log(`Compute item cost for item ${itemId} completed`);
|
||||
} catch (error) {
|
||||
console.error(`[error] Error computing item cost for item ${itemId}:`, error);
|
||||
console.error('Error stack:', error instanceof Error ? error.stack : 'No stack trace');
|
||||
console.error('Error computing item cost:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,28 +267,28 @@ export const ItemMeta = {
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Account',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
importHint: 'account.field.account_hint',
|
||||
importHint: 'Matches the account name or code.',
|
||||
},
|
||||
sellAccountId: {
|
||||
name: 'item.field.sell_account',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Account',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
importHint: 'account.field.account_hint',
|
||||
importHint: 'Matches the account name or code.',
|
||||
},
|
||||
inventoryAccountId: {
|
||||
name: 'item.field.inventory_account',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Account',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
importHint: 'account.field.account_hint',
|
||||
importHint: 'Matches the account name or code.',
|
||||
},
|
||||
sellDescription: {
|
||||
name: 'item.field.sell_description',
|
||||
name: 'Sell Description',
|
||||
fieldType: 'text',
|
||||
},
|
||||
purchaseDescription: {
|
||||
name: 'item.field.purchase_description',
|
||||
name: 'Purchase Description',
|
||||
fieldType: 'text',
|
||||
},
|
||||
note: {
|
||||
@@ -300,7 +300,7 @@ export const ItemMeta = {
|
||||
fieldType: 'relation',
|
||||
relationModel: 'ItemCategory',
|
||||
relationImportMatch: ['name'],
|
||||
importHint: 'item.field.category_hint',
|
||||
importHint: 'Matches the category name.',
|
||||
},
|
||||
active: {
|
||||
name: 'item.field.active',
|
||||
|
||||
@@ -74,9 +74,6 @@ export class PaymentReceivedResponseDto {
|
||||
@ApiProperty({ description: 'The formatted amount', example: '100.00' })
|
||||
formattedAmount: string;
|
||||
|
||||
@ApiProperty({ description: 'The formatted total', example: '100.00 USD' })
|
||||
formattedTotal: string;
|
||||
|
||||
@ApiProperty({ description: 'The currency code', example: 'USD' })
|
||||
currencyCode: string;
|
||||
|
||||
|
||||
@@ -165,12 +165,12 @@ export const PaymentReceivedMeta = {
|
||||
relationModel: 'Account',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
required: true,
|
||||
importHint: 'account.field.account_hint',
|
||||
importHint: 'Matches the account name or code.',
|
||||
},
|
||||
paymentReceiveNo: {
|
||||
name: 'payment_receive.field.payment_receive_no',
|
||||
fieldType: 'text',
|
||||
importHint: 'payment_receive.field.payment_no_hint',
|
||||
importHint: 'The payment number should be unique.',
|
||||
},
|
||||
statement: {
|
||||
name: 'payment_receive.field.statement',
|
||||
@@ -189,7 +189,7 @@ export const PaymentReceivedMeta = {
|
||||
relationModel: 'SaleInvoice',
|
||||
relationImportMatch: 'invoiceNo',
|
||||
required: true,
|
||||
importHint: 'payment_receive.field.invoice_hint',
|
||||
importHint: 'Matches the invoice number.',
|
||||
},
|
||||
paymentAmount: {
|
||||
name: 'payment_receive.field.entries.payment_amount',
|
||||
@@ -199,7 +199,7 @@ export const PaymentReceivedMeta = {
|
||||
},
|
||||
},
|
||||
branchId: {
|
||||
name: 'invoice.field.branch',
|
||||
name: 'Branch',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Branch',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
|
||||
@@ -11,7 +11,6 @@ export class PaymentReceiveTransfromer extends Transformer {
|
||||
public includeAttributes = (): string[] => {
|
||||
return [
|
||||
'subtotalFormatted',
|
||||
'formatttedTotal',
|
||||
'formattedPaymentDate',
|
||||
'formattedCreatedAt',
|
||||
'formattedAmount',
|
||||
@@ -46,18 +45,7 @@ export class PaymentReceiveTransfromer extends Transformer {
|
||||
protected subtotalFormatted = (payment: PaymentReceived): string => {
|
||||
return this.formatNumber(payment.amount, {
|
||||
currencyCode: payment.currencyCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the formatted total.
|
||||
* @param {PaymentReceived} payment
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formatttedTotal = (payment: PaymentReceived): string => {
|
||||
return this.formatNumber(payment.amount, {
|
||||
currencyCode: payment.currencyCode,
|
||||
money: true,
|
||||
money: false,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -78,7 +66,7 @@ export class PaymentReceiveTransfromer extends Transformer {
|
||||
* @returns {string}
|
||||
*/
|
||||
protected formattedExchangeRate = (payment: PaymentReceived): string => {
|
||||
return this.formatNumber(payment.exchangeRate);
|
||||
return this.formatNumber(payment.exchangeRate, { money: false });
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { ModuleRef } from '@nestjs/core';
|
||||
import { pickBy, mapValues } from 'lodash';
|
||||
import { I18nService } from 'nestjs-i18n';
|
||||
import { pickBy } from 'lodash';
|
||||
import { WarehousesSettings } from '../Warehouses/WarehousesSettings';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { BranchesSettingsService } from '../Branches/BranchesSettings';
|
||||
@@ -21,8 +20,7 @@ export class ResourceService {
|
||||
private readonly branchesSettings: BranchesSettingsService,
|
||||
private readonly warehousesSettings: WarehousesSettings,
|
||||
private readonly moduleRef: ModuleRef,
|
||||
private readonly i18nService: I18nService,
|
||||
) { }
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieve resource model object.
|
||||
@@ -98,45 +96,7 @@ export class ResourceService {
|
||||
};
|
||||
|
||||
/**
|
||||
* Localizes a single field by translating its name and importHint.
|
||||
* @param {IModelMetaField2} field - The field to localize.
|
||||
* @returns {IModelMetaField2} - The localized field.
|
||||
*/
|
||||
private localizeField(field: IModelMetaField2): IModelMetaField2 {
|
||||
const localizedField = {
|
||||
...field,
|
||||
name: this.i18nService.t(field.name, { defaultValue: field.name }),
|
||||
} as IModelMetaField2;
|
||||
|
||||
if (field.importHint) {
|
||||
localizedField.importHint = this.i18nService.t(field.importHint, {
|
||||
defaultValue: field.importHint,
|
||||
});
|
||||
}
|
||||
|
||||
// Recursively localize nested fields (for collection types)
|
||||
if (field.fields) {
|
||||
localizedField.fields = this.localizeFields(
|
||||
field.fields as unknown as Record<string, IModelMetaField2>,
|
||||
) as unknown as typeof field.fields;
|
||||
}
|
||||
|
||||
return localizedField;
|
||||
}
|
||||
|
||||
/**
|
||||
* Localizes all fields in a fields map.
|
||||
* @param {Record<string, IModelMetaField2>} fields - The fields to localize.
|
||||
* @returns {Record<string, IModelMetaField2>} - The localized fields.
|
||||
*/
|
||||
private localizeFields(
|
||||
fields: Record<string, IModelMetaField2>,
|
||||
): Record<string, IModelMetaField2> {
|
||||
return mapValues(fields, (field) => this.localizeField(field));
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the resource fields with localized names and hints.
|
||||
* Retrieve the resource fields.
|
||||
* @param {string} modelName
|
||||
* @returns {IModelMetaField2}
|
||||
*/
|
||||
@@ -144,11 +104,8 @@ export class ResourceService {
|
||||
[key: string]: IModelMetaField2;
|
||||
} {
|
||||
const meta = this.getResourceMeta(modelName);
|
||||
const filteredFields = this.filterSupportFeatures(meta.fields2);
|
||||
|
||||
return this.localizeFields(
|
||||
filteredFields as Record<string, IModelMetaField2>,
|
||||
);
|
||||
return this.filterSupportFeatures(meta.fields2);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -191,52 +191,52 @@ export const SaleEstimateMeta = {
|
||||
},
|
||||
fields2: {
|
||||
customerId: {
|
||||
name: 'estimate.field.customer',
|
||||
name: 'Customer',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Contact',
|
||||
relationImportMatch: ['displayName'],
|
||||
required: true,
|
||||
},
|
||||
estimateDate: {
|
||||
name: 'estimate.field.estimate_date',
|
||||
name: 'Estimate Date',
|
||||
fieldType: 'date',
|
||||
required: true,
|
||||
},
|
||||
expirationDate: {
|
||||
name: 'estimate.field.expiration_date',
|
||||
name: 'Expiration Date',
|
||||
fieldType: 'date',
|
||||
required: true,
|
||||
},
|
||||
estimateNumber: {
|
||||
name: 'estimate.field.estimate_number',
|
||||
name: 'Estimate No.',
|
||||
fieldType: 'text',
|
||||
},
|
||||
reference: {
|
||||
name: 'estimate.field.reference_no',
|
||||
name: 'Reference No.',
|
||||
fieldType: 'text',
|
||||
},
|
||||
exchangeRate: {
|
||||
name: 'estimate.field.exchange_rate',
|
||||
name: 'Exchange Rate',
|
||||
fieldType: 'number',
|
||||
},
|
||||
currencyCode: {
|
||||
name: 'estimate.field.currency',
|
||||
name: 'Currency',
|
||||
fieldType: 'text',
|
||||
},
|
||||
note: {
|
||||
name: 'estimate.field.note',
|
||||
name: 'Note',
|
||||
fieldType: 'text',
|
||||
},
|
||||
termsConditions: {
|
||||
name: 'estimate.field.terms_conditions',
|
||||
name: 'Terms & Conditions',
|
||||
fieldType: 'text',
|
||||
},
|
||||
delivered: {
|
||||
name: 'estimate.field.delivered',
|
||||
name: 'Delivered',
|
||||
type: 'boolean',
|
||||
},
|
||||
entries: {
|
||||
name: 'estimate.field.entries',
|
||||
name: 'Entries',
|
||||
fieldType: 'collection',
|
||||
collectionOf: 'object',
|
||||
collectionMinLength: 1,
|
||||
@@ -248,7 +248,7 @@ export const SaleEstimateMeta = {
|
||||
relationModel: 'Item',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
required: true,
|
||||
importHint: 'invoice.field.item_hint',
|
||||
importHint: 'Matches the item name or code.',
|
||||
},
|
||||
rate: {
|
||||
name: 'invoice.field.rate',
|
||||
@@ -261,13 +261,13 @@ export const SaleEstimateMeta = {
|
||||
required: true,
|
||||
},
|
||||
description: {
|
||||
name: 'invoice.field.description',
|
||||
name: 'Line Description',
|
||||
fieldType: 'text',
|
||||
},
|
||||
},
|
||||
},
|
||||
branchId: {
|
||||
name: 'invoice.field.branch',
|
||||
name: 'Branch',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Branch',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
@@ -275,7 +275,7 @@ export const SaleEstimateMeta = {
|
||||
required: true,
|
||||
},
|
||||
warehouseId: {
|
||||
name: 'invoice.field.warehouse',
|
||||
name: 'Warehouse',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Warehouse',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
|
||||
@@ -17,7 +17,7 @@ export class SaleEstimateTransfromer extends Transformer {
|
||||
'formattedDeliveredAtDate',
|
||||
'formattedApprovedAtDate',
|
||||
'formattedRejectedAtDate',
|
||||
|
||||
|
||||
'discountAmountFormatted',
|
||||
'discountPercentageFormatted',
|
||||
'adjustmentFormatted',
|
||||
@@ -135,7 +135,7 @@ export class SaleEstimateTransfromer extends Transformer {
|
||||
* @returns {string}
|
||||
*/
|
||||
protected adjustmentFormatted = (estimate: SaleEstimate): string => {
|
||||
return this.formatNumber(estimate.adjustment, {
|
||||
return this.formatMoney(estimate.adjustment, {
|
||||
currencyCode: estimate.currencyCode,
|
||||
excerptZero: true,
|
||||
});
|
||||
|
||||
@@ -19,7 +19,7 @@ export class SaleInvoiceCostGLEntries {
|
||||
private readonly inventoryCostLotTracker: TenantModelProxy<
|
||||
typeof InventoryCostLotTracker
|
||||
>,
|
||||
) { }
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Writes journal entries from sales invoices.
|
||||
|
||||
@@ -5,10 +5,10 @@ import { Importable } from '@/modules/Import/Importable';
|
||||
import { CreateSaleInvoiceDto } from '../dtos/SaleInvoice.dto';
|
||||
import { SaleInvoicesSampleData } from '../constants';
|
||||
import { ImportableService } from '@/modules/Import/decorators/Import.decorator';
|
||||
import { SaleInvoice } from '../models/SaleInvoice';
|
||||
import { ManualJournal } from '@/modules/ManualJournals/models/ManualJournal';
|
||||
|
||||
@Injectable()
|
||||
@ImportableService({ name: SaleInvoice.name })
|
||||
@ImportableService({ name: ManualJournal.name })
|
||||
export class SaleInvoicesImportable extends Importable {
|
||||
constructor(private readonly createInvoiceService: CreateSaleInvoice) {
|
||||
super();
|
||||
|
||||
@@ -259,7 +259,7 @@ export const SaleInvoiceMeta = {
|
||||
relationModel: 'Item',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
required: true,
|
||||
importHint: 'invoice.field.item_hint',
|
||||
importHint: 'Matches the item name or code.',
|
||||
},
|
||||
rate: {
|
||||
name: 'invoice.field.rate',
|
||||
@@ -283,7 +283,7 @@ export const SaleInvoiceMeta = {
|
||||
printable: false,
|
||||
},
|
||||
branchId: {
|
||||
name: 'invoice.field.branch',
|
||||
name: 'Branch',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Branch',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
@@ -291,7 +291,7 @@ export const SaleInvoiceMeta = {
|
||||
required: true,
|
||||
},
|
||||
warehouseId: {
|
||||
name: 'invoice.field.warehouse',
|
||||
name: 'Warehouse',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Warehouse',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
|
||||
@@ -70,7 +70,6 @@ export class SaleInvoiceTransformer extends Transformer {
|
||||
protected dueAmountFormatted = (invoice: SaleInvoice): string => {
|
||||
return this.formatNumber(invoice.dueAmount, {
|
||||
currencyCode: invoice.currencyCode,
|
||||
money: true
|
||||
});
|
||||
};
|
||||
|
||||
@@ -114,6 +113,7 @@ export class SaleInvoiceTransformer extends Transformer {
|
||||
protected subtotalFormatted = (invoice: SaleInvoice): string => {
|
||||
return this.formatNumber(invoice.subtotal, {
|
||||
currencyCode: this.context.organization.baseCurrency,
|
||||
money: false,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -170,7 +170,6 @@ export class SaleInvoiceTransformer extends Transformer {
|
||||
protected totalFormatted = (invoice: SaleInvoice): string => {
|
||||
return this.formatNumber(invoice.total, {
|
||||
currencyCode: invoice.currencyCode,
|
||||
money: true
|
||||
});
|
||||
};
|
||||
|
||||
@@ -213,7 +212,7 @@ export class SaleInvoiceTransformer extends Transformer {
|
||||
* @returns {string}
|
||||
*/
|
||||
protected adjustmentFormatted = (invoice: SaleInvoice): string => {
|
||||
return this.formatNumber(invoice.adjustment, {
|
||||
return this.formatMoney(invoice.adjustment, {
|
||||
currencyCode: invoice.currencyCode,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import { events } from '@/common/events/events';
|
||||
|
||||
@Injectable()
|
||||
export class InvoiceGLEntriesSubscriber {
|
||||
constructor(public readonly saleInvoiceGLEntries: SaleInvoiceGLEntries) { }
|
||||
constructor(public readonly saleInvoiceGLEntries: SaleInvoiceGLEntries) {}
|
||||
|
||||
/**
|
||||
* Records journal entries of the non-inventory invoice.
|
||||
|
||||
@@ -186,42 +186,42 @@ export const SaleReceiptMeta = {
|
||||
},
|
||||
fields2: {
|
||||
receiptDate: {
|
||||
name: 'receipt.field.receipt_date',
|
||||
name: 'Receipt Date',
|
||||
fieldType: 'date',
|
||||
required: true,
|
||||
},
|
||||
customerId: {
|
||||
name: 'receipt.field.customer',
|
||||
name: 'Customer',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Contact',
|
||||
relationImportMatch: 'displayName',
|
||||
required: true,
|
||||
},
|
||||
depositAccountId: {
|
||||
name: 'receipt.field.deposit_account',
|
||||
name: 'Deposit Account',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Account',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
required: true,
|
||||
},
|
||||
exchangeRate: {
|
||||
name: 'receipt.field.exchange_rate',
|
||||
name: 'Exchange Rate',
|
||||
fieldType: 'number',
|
||||
},
|
||||
receiptNumber: {
|
||||
name: 'receipt.field.receipt_number',
|
||||
name: 'Receipt Number',
|
||||
fieldType: 'text',
|
||||
},
|
||||
referenceNo: {
|
||||
name: 'receipt.field.reference_no',
|
||||
name: 'Reference No.',
|
||||
fieldType: 'text',
|
||||
},
|
||||
closed: {
|
||||
name: 'receipt.field.closed',
|
||||
name: 'Closed',
|
||||
fieldType: 'boolean',
|
||||
},
|
||||
entries: {
|
||||
name: 'receipt.field.entries',
|
||||
name: 'Entries',
|
||||
fieldType: 'collection',
|
||||
collectionOf: 'object',
|
||||
collectionMinLength: 1,
|
||||
@@ -233,7 +233,7 @@ export const SaleReceiptMeta = {
|
||||
relationModel: 'Item',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
required: true,
|
||||
importHint: 'invoice.field.item_hint',
|
||||
importHint: 'Matches the item name or code.',
|
||||
},
|
||||
rate: {
|
||||
name: 'invoice.field.rate',
|
||||
@@ -252,15 +252,15 @@ export const SaleReceiptMeta = {
|
||||
},
|
||||
},
|
||||
statement: {
|
||||
name: 'receipt.field.statement',
|
||||
name: 'Statement',
|
||||
fieldType: 'text',
|
||||
},
|
||||
receiptMessage: {
|
||||
name: 'receipt.field.receipt_message',
|
||||
name: 'Receipt Message',
|
||||
fieldType: 'text',
|
||||
},
|
||||
branchId: {
|
||||
name: 'invoice.field.branch',
|
||||
name: 'Branch',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Branch',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
@@ -268,7 +268,7 @@ export const SaleReceiptMeta = {
|
||||
required: true,
|
||||
},
|
||||
warehouseId: {
|
||||
name: 'invoice.field.warehouse',
|
||||
name: 'Warehouse',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Warehouse',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
|
||||
@@ -107,4 +107,4 @@ const modelProviders = models.map((model) => RegisterTenancyModel(model));
|
||||
imports: [...modelProviders],
|
||||
exports: [...modelProviders],
|
||||
})
|
||||
export class TenancyModelsModule { }
|
||||
export class TenancyModelsModule {}
|
||||
|
||||
@@ -26,7 +26,7 @@ export class TransactionsLockingService {
|
||||
constructor(
|
||||
private readonly transactionsLockingRepo: TransactionsLockingRepository,
|
||||
private readonly eventPublisher: EventEmitter2,
|
||||
) { }
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Enable/disable all transacations locking.
|
||||
|
||||
@@ -203,7 +203,6 @@ export class Transformer<T = {}, ExtraContext = {}> {
|
||||
protected formatMoney(money, options?) {
|
||||
return formatNumber(money, {
|
||||
currencyCode: this.context.organization.baseCurrency,
|
||||
money: true,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -177,70 +177,70 @@ export const VendorCreditMeta = {
|
||||
},
|
||||
fields2: {
|
||||
vendorId: {
|
||||
name: 'vendor_credit.field.vendor',
|
||||
name: 'Vendor',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Contact',
|
||||
relationImportMatch: 'displayName',
|
||||
required: true,
|
||||
},
|
||||
exchangeRate: {
|
||||
name: 'vendor_credit.field.exchange_rate',
|
||||
name: 'Echange Rate',
|
||||
fieldType: 'text',
|
||||
},
|
||||
vendorCreditNumber: {
|
||||
name: 'vendor_credit.field.vendor_credit_number',
|
||||
name: 'Vendor Credit No.',
|
||||
fieldType: 'text',
|
||||
},
|
||||
referenceNo: {
|
||||
name: 'vendor_credit.field.reference_no',
|
||||
name: 'Refernece No.',
|
||||
fieldType: 'text',
|
||||
},
|
||||
vendorCreditDate: {
|
||||
name: 'vendor_credit.field.vendor_credit_date',
|
||||
name: 'Vendor Credit Date',
|
||||
fieldType: 'date',
|
||||
required: true,
|
||||
},
|
||||
note: {
|
||||
name: 'vendor_credit.field.note',
|
||||
name: 'Note',
|
||||
fieldType: 'text',
|
||||
},
|
||||
open: {
|
||||
name: 'vendor_credit.field.open',
|
||||
name: 'Open',
|
||||
fieldType: 'boolean',
|
||||
},
|
||||
entries: {
|
||||
name: 'vendor_credit.field.entries',
|
||||
name: 'Entries',
|
||||
fieldType: 'collection',
|
||||
collectionOf: 'object',
|
||||
collectionMinLength: 1,
|
||||
required: true,
|
||||
fields: {
|
||||
itemId: {
|
||||
name: 'vendor_credit.field.item',
|
||||
name: 'Item Name',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Item',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
required: true,
|
||||
importHint: 'invoice.field.item_hint',
|
||||
importHint: 'Matches the item name or code.',
|
||||
},
|
||||
rate: {
|
||||
name: 'vendor_credit.field.rate',
|
||||
name: 'Rate',
|
||||
fieldType: 'number',
|
||||
required: true,
|
||||
},
|
||||
quantity: {
|
||||
name: 'vendor_credit.field.quantity',
|
||||
name: 'Quantity',
|
||||
fieldType: 'number',
|
||||
required: true,
|
||||
},
|
||||
description: {
|
||||
name: 'vendor_credit.field.description',
|
||||
name: 'Description',
|
||||
fieldType: 'text',
|
||||
},
|
||||
},
|
||||
},
|
||||
branchId: {
|
||||
name: 'invoice.field.branch',
|
||||
name: 'Branch',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Branch',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
@@ -248,7 +248,7 @@ export const VendorCreditMeta = {
|
||||
required: true
|
||||
},
|
||||
warehouseId: {
|
||||
name: 'invoice.field.warehouse',
|
||||
name: 'Warehouse',
|
||||
fieldType: 'relation',
|
||||
relationModel: 'Warehouse',
|
||||
relationImportMatch: ['name', 'code'],
|
||||
|
||||
@@ -2,35 +2,19 @@ import { Injectable } from '@nestjs/common';
|
||||
import { DeleteRefundVendorCreditService } from './commands/DeleteRefundVendorCredit.service';
|
||||
import { RefundVendorCredit } from './models/RefundVendorCredit';
|
||||
import { CreateRefundVendorCredit } from './commands/CreateRefundVendorCredit.service';
|
||||
import { IRefundVendorCreditDTO } from './types/VendorCreditRefund.types';
|
||||
import { RefundVendorCreditDto } from './dtos/RefundVendorCredit.dto';
|
||||
import { GetRefundVendorCreditsService } from './queries/GetRefundVendorCredits.service';
|
||||
import { IRefundVendorCreditPOJO } from './types/VendorCreditRefund.types';
|
||||
|
||||
@Injectable()
|
||||
export class VendorCreditsRefundApplication {
|
||||
/**
|
||||
* @param {CreateRefundVendorCredit} createRefundVendorCreditService
|
||||
* @param {DeleteRefundVendorCreditService} deleteRefundVendorCreditService
|
||||
* @param {GetRefundVendorCreditsService} getRefundVendorCreditsService
|
||||
*/
|
||||
constructor(
|
||||
private readonly createRefundVendorCreditService: CreateRefundVendorCredit,
|
||||
private readonly deleteRefundVendorCreditService: DeleteRefundVendorCreditService,
|
||||
private readonly getRefundVendorCreditsService: GetRefundVendorCreditsService,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieve the vendor credit refunds graph.
|
||||
* @param {number} vendorCreditId - Vendor credit id.
|
||||
* @returns {Promise<IRefundVendorCreditPOJO[]>}
|
||||
*/
|
||||
public getVendorCreditRefunds(
|
||||
vendorCreditId: number,
|
||||
): Promise<IRefundVendorCreditPOJO[]> {
|
||||
return this.getRefundVendorCreditsService.getVendorCreditRefunds(
|
||||
vendorCreditId,
|
||||
);
|
||||
}
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Creates a refund vendor credit.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
|
||||
import { Body, Controller, Delete, Param, Post } from '@nestjs/common';
|
||||
import { VendorCreditsRefundApplication } from './VendorCreditsRefund.application';
|
||||
import { RefundVendorCredit } from './models/RefundVendorCredit';
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
@@ -9,22 +9,7 @@ import { RefundVendorCreditDto } from './dtos/RefundVendorCredit.dto';
|
||||
export class VendorCreditsRefundController {
|
||||
constructor(
|
||||
private readonly vendorCreditsRefundApplication: VendorCreditsRefundApplication,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Retrieve the vendor credit refunds graph.
|
||||
* @param {number} vendorCreditId - Vendor credit id.
|
||||
* @returns {Promise<IRefundVendorCreditPOJO[]>}
|
||||
*/
|
||||
@Get(':vendorCreditId/refund')
|
||||
@ApiOperation({ summary: 'Retrieve the vendor credit refunds graph.' })
|
||||
public getVendorCreditRefunds(
|
||||
@Param('vendorCreditId') vendorCreditId: string,
|
||||
) {
|
||||
return this.vendorCreditsRefundApplication.getVendorCreditRefunds(
|
||||
Number(vendorCreditId),
|
||||
);
|
||||
}
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Creates a refund vendor credit.
|
||||
@@ -32,7 +17,7 @@ export class VendorCreditsRefundController {
|
||||
* @param {IRefundVendorCreditDTO} refundVendorCreditDTO
|
||||
* @returns {Promise<RefundVendorCredit>}
|
||||
*/
|
||||
@Post(':vendorCreditId/refund')
|
||||
@Post(':vendorCreditId/refunds')
|
||||
@ApiOperation({ summary: 'Create a refund for the given vendor credit.' })
|
||||
public async createRefundVendorCredit(
|
||||
@Param('vendorCreditId') vendorCreditId: string,
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import { IsOptional, ToNumber } from '@/common/decorators/Validators';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsDateString, Min } from 'class-validator';
|
||||
import { Min } from 'class-validator';
|
||||
import { IsString } from 'class-validator';
|
||||
import { IsDate } from 'class-validator';
|
||||
import { IsNotEmpty, IsNumber, IsPositive } from 'class-validator';
|
||||
import { IsNotEmpty, IsNumber, IsOptional, IsPositive } from 'class-validator';
|
||||
|
||||
export class RefundVendorCreditDto {
|
||||
@ToNumber()
|
||||
@IsNumber()
|
||||
@IsNotEmpty()
|
||||
@Min(0)
|
||||
@@ -34,7 +32,6 @@ export class RefundVendorCreditDto {
|
||||
})
|
||||
depositAccountId: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({
|
||||
@@ -43,7 +40,7 @@ export class RefundVendorCreditDto {
|
||||
})
|
||||
description: string;
|
||||
|
||||
@IsDateString()
|
||||
@IsDate()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty({
|
||||
description: 'The date of the refund',
|
||||
|
||||
@@ -1,115 +1,116 @@
|
||||
// import { Service } from 'typedi';
|
||||
// import { IVendor, AccountNormal, ILedgerEntry } from '@/interfaces';
|
||||
// import Ledger from '@/services/Accounting/Ledger';
|
||||
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 { Vendor } from './models/Vendor';
|
||||
|
||||
// @Service()
|
||||
// export class VendorGLEntries {
|
||||
// /**
|
||||
// * Retrieves the opening balance GL common entry.
|
||||
// * @param {IVendor} vendor -
|
||||
// */
|
||||
// private getOpeningBalanceGLCommonEntry = (vendor: IVendor) => {
|
||||
// return {
|
||||
// exchangeRate: vendor.openingBalanceExchangeRate,
|
||||
// currencyCode: vendor.currencyCode,
|
||||
@Injectable()
|
||||
export class VendorGLEntries {
|
||||
/**
|
||||
* Retrieves the opening balance GL common entry.
|
||||
* @param {Vendor} vendor -
|
||||
*/
|
||||
private getOpeningBalanceGLCommonEntry = (vendor: Vendor) => {
|
||||
return {
|
||||
exchangeRate: vendor.openingBalanceExchangeRate,
|
||||
currencyCode: vendor.currencyCode,
|
||||
|
||||
// transactionType: 'VendorOpeningBalance',
|
||||
// transactionId: vendor.id,
|
||||
transactionType: 'VendorOpeningBalance',
|
||||
transactionId: vendor.id,
|
||||
|
||||
// date: vendor.openingBalanceAt,
|
||||
// userId: vendor.userId,
|
||||
// contactId: vendor.id,
|
||||
date: vendor.openingBalanceAt,
|
||||
contactId: vendor.id,
|
||||
|
||||
// credit: 0,
|
||||
// debit: 0,
|
||||
credit: 0,
|
||||
debit: 0,
|
||||
|
||||
// branchId: vendor.openingBalanceBranchId,
|
||||
// };
|
||||
// };
|
||||
branchId: vendor.openingBalanceBranchId,
|
||||
};
|
||||
};
|
||||
|
||||
// /**
|
||||
// * Retrieves the opening balance GL debit entry.
|
||||
// * @param {number} costAccountId -
|
||||
// * @param {IVendor} vendor
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getOpeningBalanceGLDebitEntry = (
|
||||
// costAccountId: number,
|
||||
// vendor: IVendor
|
||||
// ): ILedgerEntry => {
|
||||
// const commonEntry = this.getOpeningBalanceGLCommonEntry(vendor);
|
||||
/**
|
||||
* Retrieves the opening balance GL debit entry.
|
||||
* @param {number} costAccountId -
|
||||
* @param {Vendor} vendor
|
||||
* @returns {ILedgerEntry}
|
||||
*/
|
||||
private getOpeningBalanceGLDebitEntry = (
|
||||
costAccountId: number,
|
||||
vendor: Vendor
|
||||
): ILedgerEntry => {
|
||||
const commonEntry = this.getOpeningBalanceGLCommonEntry(vendor);
|
||||
|
||||
// return {
|
||||
// ...commonEntry,
|
||||
// accountId: costAccountId,
|
||||
// accountNormal: AccountNormal.DEBIT,
|
||||
// debit: vendor.localOpeningBalance,
|
||||
// credit: 0,
|
||||
// index: 2,
|
||||
// };
|
||||
// };
|
||||
return {
|
||||
...commonEntry,
|
||||
accountId: costAccountId,
|
||||
accountNormal: AccountNormal.DEBIT,
|
||||
debit: vendor.localOpeningBalance,
|
||||
credit: 0,
|
||||
index: 2,
|
||||
};
|
||||
};
|
||||
|
||||
// /**
|
||||
// * Retrieves the opening balance GL credit entry.
|
||||
// * @param {number} APAccountId
|
||||
// * @param {IVendor} vendor
|
||||
// * @returns {ILedgerEntry}
|
||||
// */
|
||||
// private getOpeningBalanceGLCreditEntry = (
|
||||
// APAccountId: number,
|
||||
// vendor: IVendor
|
||||
// ): ILedgerEntry => {
|
||||
// const commonEntry = this.getOpeningBalanceGLCommonEntry(vendor);
|
||||
/**
|
||||
* Retrieves the opening balance GL credit entry.
|
||||
* @param {number} APAccountId
|
||||
* @param {Vendor} vendor
|
||||
* @returns {ILedgerEntry}
|
||||
*/
|
||||
private getOpeningBalanceGLCreditEntry = (
|
||||
APAccountId: number,
|
||||
vendor: Vendor
|
||||
): ILedgerEntry => {
|
||||
const commonEntry = this.getOpeningBalanceGLCommonEntry(vendor);
|
||||
|
||||
// return {
|
||||
// ...commonEntry,
|
||||
// accountId: APAccountId,
|
||||
// accountNormal: AccountNormal.CREDIT,
|
||||
// credit: vendor.localOpeningBalance,
|
||||
// index: 1,
|
||||
// };
|
||||
// };
|
||||
return {
|
||||
...commonEntry,
|
||||
accountId: APAccountId,
|
||||
accountNormal: AccountNormal.CREDIT,
|
||||
credit: vendor.localOpeningBalance,
|
||||
index: 1,
|
||||
};
|
||||
};
|
||||
|
||||
// /**
|
||||
// * Retrieves the opening balance GL entries.
|
||||
// * @param {number} APAccountId
|
||||
// * @param {number} costAccountId -
|
||||
// * @param {IVendor} vendor
|
||||
// * @returns {ILedgerEntry[]}
|
||||
// */
|
||||
// public getOpeningBalanceGLEntries = (
|
||||
// APAccountId: number,
|
||||
// costAccountId: number,
|
||||
// vendor: IVendor
|
||||
// ): ILedgerEntry[] => {
|
||||
// const debitEntry = this.getOpeningBalanceGLDebitEntry(
|
||||
// costAccountId,
|
||||
// vendor
|
||||
// );
|
||||
// const creditEntry = this.getOpeningBalanceGLCreditEntry(
|
||||
// APAccountId,
|
||||
// vendor
|
||||
// );
|
||||
// return [debitEntry, creditEntry];
|
||||
// };
|
||||
/**
|
||||
* Retrieves the opening balance GL entries.
|
||||
* @param {number} APAccountId
|
||||
* @param {number} costAccountId -
|
||||
* @param {Vendor} vendor
|
||||
* @returns {ILedgerEntry[]}
|
||||
*/
|
||||
public getOpeningBalanceGLEntries = (
|
||||
APAccountId: number,
|
||||
costAccountId: number,
|
||||
vendor: Vendor
|
||||
): ILedgerEntry[] => {
|
||||
const debitEntry = this.getOpeningBalanceGLDebitEntry(
|
||||
costAccountId,
|
||||
vendor
|
||||
);
|
||||
const creditEntry = this.getOpeningBalanceGLCreditEntry(
|
||||
APAccountId,
|
||||
vendor
|
||||
);
|
||||
return [debitEntry, creditEntry];
|
||||
};
|
||||
|
||||
// /**
|
||||
// * Retrieves the opening balance ledger.
|
||||
// * @param {number} APAccountId
|
||||
// * @param {number} costAccountId -
|
||||
// * @param {IVendor} vendor
|
||||
// * @returns {Ledger}
|
||||
// */
|
||||
// public getOpeningBalanceLedger = (
|
||||
// APAccountId: number,
|
||||
// costAccountId: number,
|
||||
// vendor: IVendor
|
||||
// ) => {
|
||||
// const entries = this.getOpeningBalanceGLEntries(
|
||||
// APAccountId,
|
||||
// costAccountId,
|
||||
// vendor
|
||||
// );
|
||||
// return new Ledger(entries);
|
||||
// };
|
||||
// }
|
||||
/**
|
||||
* Retrieves the opening balance ledger.
|
||||
* @param {number} APAccountId
|
||||
* @param {number} costAccountId -
|
||||
* @param {Vendor} vendor
|
||||
* @returns {Ledger}
|
||||
*/
|
||||
public getOpeningBalanceLedger = (
|
||||
APAccountId: number,
|
||||
costAccountId: number,
|
||||
vendor: Vendor
|
||||
) => {
|
||||
const entries = this.getOpeningBalanceGLEntries(
|
||||
APAccountId,
|
||||
costAccountId,
|
||||
vendor
|
||||
);
|
||||
return new Ledger(entries);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,88 +1,86 @@
|
||||
// import { Knex } from 'knex';
|
||||
// import { Service, Inject } from 'typedi';
|
||||
// import LedgerStorageService from '@/services/Accounting/LedgerStorageService';
|
||||
// import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
// import { VendorGLEntries } from './VendorGLEntries';
|
||||
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 { VendorGLEntries } from './VendorGLEntries';
|
||||
import { Vendor } from './models/Vendor';
|
||||
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
|
||||
|
||||
// @Service()
|
||||
// export class VendorGLEntriesStorage {
|
||||
// @Inject()
|
||||
// private tenancy: HasTenancyService;
|
||||
@Injectable()
|
||||
export class VendorGLEntriesStorage {
|
||||
constructor(
|
||||
private readonly ledgerStorage: LedgerStorageService,
|
||||
private readonly accountRepository: AccountRepository,
|
||||
private readonly vendorGLEntries: VendorGLEntries,
|
||||
|
||||
// @Inject()
|
||||
// private ledegrRepository: LedgerStorageService;
|
||||
@Inject(Vendor.name)
|
||||
private readonly vendorModel: TenantModelProxy<typeof Vendor>,
|
||||
) { }
|
||||
|
||||
// @Inject()
|
||||
// private vendorGLEntries: VendorGLEntries;
|
||||
/**
|
||||
* Vendor opening balance journals.
|
||||
* @param {number} vendorId
|
||||
* @param {Knex.Transaction} trx
|
||||
*/
|
||||
public writeVendorOpeningBalance = async (
|
||||
vendorId: number,
|
||||
trx?: Knex.Transaction,
|
||||
) => {
|
||||
const vendor = await this.vendorModel()
|
||||
.query(trx)
|
||||
.findById(vendorId);
|
||||
|
||||
// /**
|
||||
// * Vendor opening balance journals.
|
||||
// * @param {number} tenantId
|
||||
// * @param {number} vendorId
|
||||
// * @param {Knex.Transaction} trx
|
||||
// */
|
||||
// public writeVendorOpeningBalance = async (
|
||||
// tenantId: number,
|
||||
// vendorId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ) => {
|
||||
// const { Vendor } = this.tenancy.models(tenantId);
|
||||
// const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||
// Finds the expense account.
|
||||
const expenseAccount = await this.accountRepository.findOrCreateOtherExpensesAccount(
|
||||
{},
|
||||
trx,
|
||||
);
|
||||
// Find or create the A/P account.
|
||||
const APAccount =
|
||||
await this.accountRepository.findOrCreateAccountsPayable(
|
||||
vendor.currencyCode,
|
||||
{},
|
||||
trx,
|
||||
);
|
||||
// Retrieves the vendor opening balance ledger.
|
||||
const ledger = this.vendorGLEntries.getOpeningBalanceLedger(
|
||||
APAccount.id,
|
||||
expenseAccount.id,
|
||||
vendor,
|
||||
);
|
||||
// Commits the ledger entries to the storage.
|
||||
await this.ledgerStorage.commit(ledger, trx);
|
||||
};
|
||||
|
||||
// const vendor = await Vendor.query(trx).findById(vendorId);
|
||||
/**
|
||||
* Reverts the vendor opening balance GL entries.
|
||||
* @param {number} vendorId
|
||||
* @param {Knex.Transaction} trx
|
||||
*/
|
||||
public revertVendorOpeningBalance = async (
|
||||
vendorId: number,
|
||||
trx?: Knex.Transaction,
|
||||
) => {
|
||||
await this.ledgerStorage.deleteByReference(
|
||||
vendorId,
|
||||
'VendorOpeningBalance',
|
||||
trx,
|
||||
);
|
||||
};
|
||||
|
||||
// // Finds the expense account.
|
||||
// const expenseAccount = await accountRepository.findOne({
|
||||
// slug: 'other-expenses',
|
||||
// });
|
||||
// // Find or create the A/P account.
|
||||
// const APAccount = await accountRepository.findOrCreateAccountsPayable(
|
||||
// vendor.currencyCode,
|
||||
// {},
|
||||
// trx
|
||||
// );
|
||||
// // Retrieves the vendor opening balance ledger.
|
||||
// const ledger = this.vendorGLEntries.getOpeningBalanceLedger(
|
||||
// APAccount.id,
|
||||
// expenseAccount.id,
|
||||
// vendor
|
||||
// );
|
||||
// // Commits the ledger entries to the storage.
|
||||
// await this.ledegrRepository.commit(tenantId, ledger, trx);
|
||||
// };
|
||||
/**
|
||||
* Writes the vendor opening balance GL entries.
|
||||
* @param {number} vendorId
|
||||
* @param {Knex.Transaction} trx
|
||||
*/
|
||||
public rewriteVendorOpeningBalance = async (
|
||||
vendorId: number,
|
||||
trx?: Knex.Transaction,
|
||||
) => {
|
||||
// Reverts the vendor opening balance entries first.
|
||||
await this.revertVendorOpeningBalance(vendorId, trx);
|
||||
|
||||
// /**
|
||||
// * Reverts the vendor opening balance GL entries.
|
||||
// * @param {number} tenantId
|
||||
// * @param {number} vendorId
|
||||
// * @param {Knex.Transaction} trx
|
||||
// */
|
||||
// public revertVendorOpeningBalance = async (
|
||||
// tenantId: number,
|
||||
// vendorId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ) => {
|
||||
// await this.ledegrRepository.deleteByReference(
|
||||
// tenantId,
|
||||
// vendorId,
|
||||
// 'VendorOpeningBalance',
|
||||
// trx
|
||||
// );
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Writes the vendor opening balance GL entries.
|
||||
// * @param {number} tenantId
|
||||
// * @param {number} vendorId
|
||||
// * @param {Knex.Transaction} trx
|
||||
// */
|
||||
// public rewriteVendorOpeningBalance = async (
|
||||
// tenantId: number,
|
||||
// vendorId: number,
|
||||
// trx?: Knex.Transaction
|
||||
// ) => {
|
||||
// await this.writeVendorOpeningBalance(tenantId, vendorId, trx);
|
||||
|
||||
// await this.revertVendorOpeningBalance(tenantId, vendorId, trx);
|
||||
// };
|
||||
// }
|
||||
// Write the vendor opening balance entries.
|
||||
await this.writeVendorOpeningBalance(vendorId, trx);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -9,10 +9,7 @@ import {
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { VendorsApplication } from './VendorsApplication.service';
|
||||
import {
|
||||
IVendorOpeningBalanceEditDTO,
|
||||
IVendorsFilter,
|
||||
} from './types/Vendors.types';
|
||||
import { VendorOpeningBalanceEditDto } from './dtos/VendorOpeningBalanceEdit.dto';
|
||||
import {
|
||||
ApiOperation,
|
||||
ApiResponse,
|
||||
@@ -68,7 +65,7 @@ export class VendorsController {
|
||||
@ApiOperation({ summary: 'Edit the given vendor opening balance.' })
|
||||
editOpeningBalance(
|
||||
@Param('id') vendorId: number,
|
||||
@Body() openingBalanceDTO: IVendorOpeningBalanceEditDTO,
|
||||
@Body() openingBalanceDTO: VendorOpeningBalanceEditDto,
|
||||
) {
|
||||
return this.vendorsApplication.editOpeningBalance(
|
||||
vendorId,
|
||||
|
||||
@@ -18,9 +18,14 @@ import { VendorsExportable } from './VendorsExportable';
|
||||
import { VendorsImportable } from './VendorsImportable';
|
||||
import { BulkDeleteVendorsService } from './BulkDeleteVendors.service';
|
||||
import { ValidateBulkDeleteVendorsService } from './ValidateBulkDeleteVendors.service';
|
||||
import { LedgerModule } from '../Ledger/Ledger.module';
|
||||
import { AccountsModule } from '../Accounts/Accounts.module';
|
||||
import { VendorGLEntries } from './VendorGLEntries';
|
||||
import { VendorGLEntriesStorage } from './VendorGLEntriesStorage';
|
||||
import { VendorsWriteGLOpeningSubscriber } from './subscribers/VendorGLEntriesSubscriber';
|
||||
|
||||
@Module({
|
||||
imports: [TenancyDatabaseModule, DynamicListModule],
|
||||
imports: [TenancyDatabaseModule, DynamicListModule, LedgerModule, AccountsModule],
|
||||
controllers: [VendorsController],
|
||||
providers: [
|
||||
ActivateVendorService,
|
||||
@@ -38,7 +43,10 @@ import { ValidateBulkDeleteVendorsService } from './ValidateBulkDeleteVendors.se
|
||||
TransformerInjectable,
|
||||
TenancyContext,
|
||||
VendorsExportable,
|
||||
VendorsImportable
|
||||
VendorsImportable,
|
||||
VendorGLEntries,
|
||||
VendorGLEntriesStorage,
|
||||
VendorsWriteGLOpeningSubscriber,
|
||||
],
|
||||
})
|
||||
export class VendorsModule {}
|
||||
export class VendorsModule { }
|
||||
|
||||
@@ -5,10 +5,7 @@ import { EditVendorService } from './commands/EditVendor.service';
|
||||
import { DeleteVendorService } from './commands/DeleteVendor.service';
|
||||
import { EditOpeningBalanceVendorService } from './commands/EditOpeningBalanceVendor.service';
|
||||
import { GetVendorService } from './queries/GetVendor';
|
||||
import {
|
||||
IVendorOpeningBalanceEditDTO,
|
||||
IVendorsFilter,
|
||||
} from './types/Vendors.types';
|
||||
import { VendorOpeningBalanceEditDto } from './dtos/VendorOpeningBalanceEdit.dto';
|
||||
import { GetVendorsService } from './queries/GetVendors.service';
|
||||
import { CreateVendorDto } from './dtos/CreateVendor.dto';
|
||||
import { EditVendorDto } from './dtos/EditVendor.dto';
|
||||
@@ -58,14 +55,14 @@ export class VendorsApplication {
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the opening balance of the given customer.
|
||||
* @param {number} vendorId
|
||||
* @param {IVendorOpeningBalanceEditDTO} openingBalanceEditDTO
|
||||
* Changes the opening balance of the given vendor.
|
||||
* @param {number} vendorId
|
||||
* @param {VendorOpeningBalanceEditDto} openingBalanceEditDTO
|
||||
* @returns {Promise<IVendor>}
|
||||
*/
|
||||
public editOpeningBalance(
|
||||
vendorId: number,
|
||||
openingBalanceEditDTO: IVendorOpeningBalanceEditDTO,
|
||||
openingBalanceEditDTO: VendorOpeningBalanceEditDto,
|
||||
) {
|
||||
return this.editOpeningBalanceService.editOpeningBalance(
|
||||
vendorId,
|
||||
@@ -95,10 +92,7 @@ export class VendorsApplication {
|
||||
vendorIds: number[],
|
||||
options?: { skipUndeletable?: boolean },
|
||||
) {
|
||||
return this.bulkDeleteVendorsService.bulkDeleteVendors(
|
||||
vendorIds,
|
||||
options,
|
||||
);
|
||||
return this.bulkDeleteVendorsService.bulkDeleteVendors(vendorIds, options);
|
||||
}
|
||||
|
||||
public validateBulkDeleteVendors(vendorIds: number[]) {
|
||||
|
||||
@@ -2,10 +2,10 @@ import { Knex } from 'knex';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import {
|
||||
IVendorOpeningBalanceEditDTO,
|
||||
IVendorOpeningBalanceEditedPayload,
|
||||
IVendorOpeningBalanceEditingPayload,
|
||||
} from '../types/Vendors.types';
|
||||
import { VendorOpeningBalanceEditDto } from '../dtos/VendorOpeningBalanceEdit.dto';
|
||||
import { UnitOfWork } from '@/modules/Tenancy/TenancyDB/UnitOfWork.service';
|
||||
import { Vendor } from '../models/Vendor';
|
||||
import { events } from '@/common/events/events';
|
||||
@@ -29,12 +29,12 @@ export class EditOpeningBalanceVendorService {
|
||||
/**
|
||||
* Changes the opening balance of the given customer.
|
||||
* @param {number} vendorId
|
||||
* @param {IVendorOpeningBalanceEditDTO} openingBalanceEditDTO
|
||||
* @param {VendorOpeningBalanceEditDto} openingBalanceEditDTO
|
||||
* @returns {Promise<IVendor>}
|
||||
*/
|
||||
public async editOpeningBalance(
|
||||
vendorId: number,
|
||||
openingBalanceEditDTO: IVendorOpeningBalanceEditDTO,
|
||||
openingBalanceEditDTO: VendorOpeningBalanceEditDto,
|
||||
) {
|
||||
// Retrieves the old vendor or throw not found error.
|
||||
const oldVendor = await this.vendorModel()
|
||||
|
||||
@@ -2,11 +2,13 @@ import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
IsISO8601,
|
||||
IsInt,
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
Min,
|
||||
IsBoolean,
|
||||
IsEmail,
|
||||
IsString,
|
||||
ValidateIf,
|
||||
} from 'class-validator';
|
||||
import { ContactAddressDto } from '@/modules/Customers/dtos/ContactAddress.dto';
|
||||
import { IsOptional, ToNumber } from '@/common/decorators/Validators';
|
||||
@@ -30,8 +32,12 @@ export class CreateVendorDto extends ContactAddressDto {
|
||||
@ToNumber()
|
||||
openingBalanceExchangeRate?: number;
|
||||
|
||||
@ApiProperty({ required: false, description: 'Date of the opening balance' })
|
||||
@IsOptional()
|
||||
@ApiProperty({
|
||||
required: false,
|
||||
description: 'Date of the opening balance (required when openingBalance is provided)',
|
||||
})
|
||||
@ValidateIf((o) => o.openingBalance != null)
|
||||
@IsNotEmpty({ message: 'openingBalanceAt is required when openingBalance is provided' })
|
||||
@IsISO8601()
|
||||
openingBalanceAt?: Date;
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsOptional, ToNumber } from '@/common/decorators/Validators';
|
||||
|
||||
export class VendorOpeningBalanceEditDto {
|
||||
@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;
|
||||
}
|
||||
@@ -36,6 +36,7 @@ export class Vendor extends TenantBaseModel {
|
||||
openingBalance: number;
|
||||
openingBalanceExchangeRate: number;
|
||||
openingBalanceAt: Date | string;
|
||||
openingBalanceBranchId?: number;
|
||||
|
||||
salutation: string;
|
||||
firstName: string;
|
||||
|
||||
@@ -1,91 +1,71 @@
|
||||
// import { Inject, Service } from 'typedi';
|
||||
// import events from '@/subscribers/events';
|
||||
// import { VendorGLEntriesStorage } from '../VendorGLEntriesStorage';
|
||||
// import {
|
||||
// IVendorEventCreatedPayload,
|
||||
// IVendorEventDeletedPayload,
|
||||
// IVendorOpeningBalanceEditedPayload,
|
||||
// } from '@/interfaces';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { OnEvent } from '@nestjs/event-emitter';
|
||||
import { events } from '@/common/events/events';
|
||||
import { VendorGLEntriesStorage } from '../VendorGLEntriesStorage';
|
||||
import {
|
||||
IVendorEventCreatedPayload,
|
||||
IVendorEventDeletedPayload,
|
||||
IVendorOpeningBalanceEditedPayload,
|
||||
} from '../types/Vendors.types';
|
||||
|
||||
// @Service()
|
||||
// export class VendorsWriteGLOpeningSubscriber {
|
||||
// @Inject()
|
||||
// private vendorGLEntriesStorage: VendorGLEntriesStorage;
|
||||
@Injectable()
|
||||
export class VendorsWriteGLOpeningSubscriber {
|
||||
constructor(
|
||||
private readonly vendorGLEntriesStorage: VendorGLEntriesStorage,
|
||||
) {}
|
||||
|
||||
// /**
|
||||
// * Constructor method.
|
||||
// */
|
||||
// public attach(bus) {
|
||||
// bus.subscribe(
|
||||
// events.vendors.onCreated,
|
||||
// this.handleWriteOpeningBalanceEntries
|
||||
// );
|
||||
// bus.subscribe(
|
||||
// events.vendors.onDeleted,
|
||||
// this.handleRevertOpeningBalanceEntries
|
||||
// );
|
||||
// bus.subscribe(
|
||||
// events.vendors.onOpeningBalanceChanged,
|
||||
// this.handleRewriteOpeningEntriesOnChanged
|
||||
// );
|
||||
// }
|
||||
/**
|
||||
* Writes the open balance journal entries once the vendor created.
|
||||
* @param {IVendorEventCreatedPayload} payload -
|
||||
*/
|
||||
@OnEvent(events.vendors.onCreated)
|
||||
public async handleWriteOpeningBalanceEntries({
|
||||
vendor,
|
||||
trx,
|
||||
}: IVendorEventCreatedPayload) {
|
||||
// Writes the vendor opening balance journal entries.
|
||||
if (vendor.openingBalance) {
|
||||
await this.vendorGLEntriesStorage.writeVendorOpeningBalance(
|
||||
vendor.id,
|
||||
trx,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// /**
|
||||
// * Writes the open balance journal entries once the vendor created.
|
||||
// * @param {IVendorEventCreatedPayload} payload -
|
||||
// */
|
||||
// private handleWriteOpeningBalanceEntries = async ({
|
||||
// tenantId,
|
||||
// vendor,
|
||||
// trx,
|
||||
// }: IVendorEventCreatedPayload) => {
|
||||
// // Writes the vendor opening balance journal entries.
|
||||
// if (vendor.openingBalance) {
|
||||
// await this.vendorGLEntriesStorage.writeVendorOpeningBalance(
|
||||
// tenantId,
|
||||
// vendor.id,
|
||||
// trx
|
||||
// );
|
||||
// }
|
||||
// };
|
||||
/**
|
||||
* Revert the opening balance journal entries once the vendor deleted.
|
||||
* @param {IVendorEventDeletedPayload} payload -
|
||||
*/
|
||||
@OnEvent(events.vendors.onDeleted)
|
||||
public async handleRevertOpeningBalanceEntries({
|
||||
vendorId,
|
||||
trx,
|
||||
}: IVendorEventDeletedPayload) {
|
||||
await this.vendorGLEntriesStorage.revertVendorOpeningBalance(
|
||||
vendorId,
|
||||
trx,
|
||||
);
|
||||
}
|
||||
|
||||
// /**
|
||||
// * Revert the opening balance journal entries once the vendor deleted.
|
||||
// * @param {IVendorEventDeletedPayload} payload -
|
||||
// */
|
||||
// private handleRevertOpeningBalanceEntries = async ({
|
||||
// tenantId,
|
||||
// vendorId,
|
||||
// trx,
|
||||
// }: IVendorEventDeletedPayload) => {
|
||||
// await this.vendorGLEntriesStorage.revertVendorOpeningBalance(
|
||||
// tenantId,
|
||||
// vendorId,
|
||||
// trx
|
||||
// );
|
||||
// };
|
||||
|
||||
// /**
|
||||
// * Handles the rewrite opening balance entries once opening balnace changed.
|
||||
// * @param {ICustomerOpeningBalanceEditedPayload} payload -
|
||||
// */
|
||||
// private handleRewriteOpeningEntriesOnChanged = async ({
|
||||
// tenantId,
|
||||
// vendor,
|
||||
// trx,
|
||||
// }: IVendorOpeningBalanceEditedPayload) => {
|
||||
// if (vendor.openingBalance) {
|
||||
// await this.vendorGLEntriesStorage.rewriteVendorOpeningBalance(
|
||||
// tenantId,
|
||||
// vendor.id,
|
||||
// trx
|
||||
// );
|
||||
// } else {
|
||||
// await this.vendorGLEntriesStorage.revertVendorOpeningBalance(
|
||||
// tenantId,
|
||||
// vendor.id,
|
||||
// trx
|
||||
// );
|
||||
// }
|
||||
// };
|
||||
// }
|
||||
/**
|
||||
* Handles the rewrite opening balance entries once opening balance changed.
|
||||
* @param {IVendorOpeningBalanceEditedPayload} payload -
|
||||
*/
|
||||
@OnEvent(events.vendors.onOpeningBalanceChanged)
|
||||
public async handleRewriteOpeningEntriesOnChanged({
|
||||
vendor,
|
||||
trx,
|
||||
}: IVendorOpeningBalanceEditedPayload) {
|
||||
if (vendor.openingBalance) {
|
||||
await this.vendorGLEntriesStorage.rewriteVendorOpeningBalance(
|
||||
vendor.id,
|
||||
trx,
|
||||
);
|
||||
} else {
|
||||
await this.vendorGLEntriesStorage.revertVendorOpeningBalance(
|
||||
vendor.id,
|
||||
trx,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { IDynamicListFilter } from '@/modules/DynamicListing/DynamicFilter/Dynam
|
||||
import { IFilterMeta, IPaginationMeta } from '@/interfaces/Model';
|
||||
import { CreateVendorDto } from '../dtos/CreateVendor.dto';
|
||||
import { EditVendorDto } from '../dtos/EditVendor.dto';
|
||||
import { VendorOpeningBalanceEditDto } from '../dtos/VendorOpeningBalanceEdit.dto';
|
||||
|
||||
// ----------------------------------
|
||||
export interface IVendorNewDTO extends IContactAddressDTO {
|
||||
@@ -92,23 +93,16 @@ export interface IVendorEventEditedPayload {
|
||||
trx?: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface IVendorOpeningBalanceEditDTO {
|
||||
openingBalance: number;
|
||||
openingBalanceAt: Date | string;
|
||||
openingBalanceExchangeRate: number;
|
||||
openingBalanceBranchId?: number;
|
||||
}
|
||||
|
||||
export interface IVendorOpeningBalanceEditingPayload {
|
||||
oldVendor: Vendor;
|
||||
openingBalanceEditDTO: IVendorOpeningBalanceEditDTO;
|
||||
openingBalanceEditDTO: VendorOpeningBalanceEditDto;
|
||||
trx?: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface IVendorOpeningBalanceEditedPayload {
|
||||
vendor: Vendor;
|
||||
oldVendor: Vendor;
|
||||
openingBalanceEditDTO: IVendorOpeningBalanceEditDTO;
|
||||
openingBalanceEditDTO: VendorOpeningBalanceEditDto;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user