fix: sync contacts balance with journal entries.

fix: edit invoice amount that has payment transactions.
This commit is contained in:
a.bouhuolia
2021-03-02 11:22:44 +02:00
parent b98d18f189
commit d51d9a5038
29 changed files with 477 additions and 401 deletions

View File

@@ -17,7 +17,6 @@ import {
export default class JournalCommands {
journal: JournalPoster;
models: any;
repositories: any;
@@ -77,7 +76,6 @@ export default class JournalCommands {
credit: bill.amount,
account: payableAccount.id,
contactId: bill.vendorId,
contactType: 'Vendor',
index: 1,
});
this.journal.credit(payableEntry);
@@ -113,8 +111,8 @@ export default class JournalCommands {
) {
const { accountRepository } = this.repositories;
const openingBalanceAccount = await accountRepository.findOne({
slug: 'opening-balance',
const incomeAccount = await accountRepository.findOne({
slug: 'other-income',
});
const receivableAccount = await accountRepository.findOne({
slug: 'accounts-receivable',
@@ -123,8 +121,6 @@ export default class JournalCommands {
const commonEntry = {
referenceType: 'CustomerOpeningBalance',
referenceId: customerId,
contactType: 'Customer',
contactId: customerId,
date: openingBalanceAt,
userId,
};
@@ -133,13 +129,14 @@ export default class JournalCommands {
credit: 0,
debit: openingBalance,
account: receivableAccount.id,
contactId: customerId,
index: 1,
});
const creditEntry = new JournalEntry({
...commonEntry,
credit: openingBalance,
debit: 0,
account: openingBalanceAccount.id,
account: incomeAccount.id,
index: 2,
});
this.journal.debit(debitEntry);
@@ -171,8 +168,6 @@ export default class JournalCommands {
const commonEntry = {
referenceType: 'VendorOpeningBalance',
referenceId: vendorId,
contactType: 'Vendor',
contactId: vendorId,
date: openingBalanceAt,
userId: authorizedUserId,
};
@@ -182,6 +177,7 @@ export default class JournalCommands {
credit: openingBalance,
debit: 0,
index: 1,
contactId: vendorId,
});
const debitEntry = new JournalEntry({
...commonEntry,
@@ -297,7 +293,6 @@ export default class JournalCommands {
account: entry.accountId,
referenceType: 'Journal',
referenceId: manualJournalObj.id,
contactType: entry.contactType,
contactId: entry.contactId,
note: entry.note,
date: manualJournalObj.date,
@@ -379,6 +374,7 @@ export default class JournalCommands {
...commonEntry,
debit: saleInvoice.balance,
account: receivableAccountId,
contactId: saleInvoice.customerId,
index: 1,
});
this.journal.debit(receivableEntry);

View File

@@ -0,0 +1,74 @@
import async from 'async';
export default class JournalContacts {
saveContactBalanceQueue: any;
contactsBalanceTable: {
[key: number]: { credit: number; debit: number };
} = {};
constructor(journal) {
this.journal = journal;
this.saveContactBalanceQueue = async.queue(
this.saveContactBalanceChangeTask.bind(this),
10
);
}
/**
* Sets the contact balance change.
*/
private getContactsBalanceChanges(entry) {
if (!entry.contactId) {
return;
}
const change = {
debit: entry.debit,
credit: entry.credit,
};
if (!this.contactsBalanceTable[entry.contactId]) {
this.contactsBalanceTable[entry.contactId] = { credit: 0, debit: 0 };
}
if (change.credit) {
this.contactsBalanceTable[entry.contactId].credit += change.credit;
}
if (change.debit) {
this.contactsBalanceTable[entry.contactId].debit += change.debit;
}
}
/**
* Save contacts balance change.
*/
saveContactsBalance() {
const balanceChanges = Object.entries(
this.contactsBalanceTable
).map(([contactId, { credit, debit }]) => ({ contactId, credit, debit }));
return this.saveContactBalanceQueue.pushAsync(balanceChanges);
}
/**
* Saves contact balance change task.
* @param {number} contactId - Contact id.
* @param {number} credit - Credit amount.
* @param {number} debit - Debit amount.
*/
async saveContactBalanceChangeTask({ contactId, credit, debit }, callback) {
const { contactRepository } = this.repositories;
const contact = await contactRepository.findOneById(contactId);
let balanceChange = 0;
if (contact.contactNormal === 'credit') {
balanceChange += credit - debit;
} else {
balanceChange += debit - credit;
}
// Contact change balance.
await contactRepository.changeNumber(
{ id: contactId },
'balance',
balanceChange
);
callback();
}
}

View File

@@ -14,6 +14,4 @@ export default class JournalFinancial {
this.journal = journal;
this.accountsDepGraph = this.journal.accountsDepGraph;
}
}

View File

@@ -1,6 +1,7 @@
import { omit, get } from 'lodash';
import { omit, get, chain } from 'lodash';
import moment from 'moment';
import { Container } from 'typedi';
import async from 'async';
import JournalEntry from 'services/Accounting/JournalEntry';
import TenancyService from 'services/Tenancy/TenancyService';
import {
@@ -11,6 +12,19 @@ import {
TEntryType,
} from 'interfaces';
const CONTACTS_CONFIG = [
{
accountBySlug: 'accounts-receivable',
contactService: 'customer',
assignRequired: true,
},
{
accountBySlug: 'accounts-payable',
contactService: 'vendor',
assignRequired: true,
},
];
export default class JournalPoster implements IJournalPoster {
tenantId: number;
tenancy: TenancyService;
@@ -24,6 +38,10 @@ export default class JournalPoster implements IJournalPoster {
accountsDepGraph: IAccountsChange;
accountsBalanceTable: { [key: number]: number } = {};
contactsBalanceTable: {
[key: number]: { credit: number; debit: number }[];
} = {};
saveContactBalanceQueue: any;
/**
* Journal poster constructor.
@@ -39,6 +57,10 @@ export default class JournalPoster implements IJournalPoster {
if (accountsGraph) {
this.accountsDepGraph = accountsGraph;
}
this.saveContactBalanceQueue = async.queue(
this.saveContactBalanceChangeTask.bind(this),
10
);
}
/**
@@ -69,7 +91,7 @@ export default class JournalPoster implements IJournalPoster {
}
/**
*
* Detarmines the ledger is empty.
*/
public isEmpty() {
return this.entries.length === 0;
@@ -85,6 +107,7 @@ export default class JournalPoster implements IJournalPoster {
}
this.entries.push(entryModel.entry);
this.setAccountBalanceChange(entryModel.entry);
this.setContactBalanceChange(entryModel.entry);
}
/**
@@ -97,6 +120,83 @@ export default class JournalPoster implements IJournalPoster {
}
this.entries.push(entryModel.entry);
this.setAccountBalanceChange(entryModel.entry);
this.setContactBalanceChange(entryModel.entry);
}
/**
* Sets the contact balance change.
*/
private setContactBalanceChange(entry) {
if (!entry.contactId) {
return;
}
const change = {
debit: entry.debit || 0,
credit: entry.credit || 0,
account: entry.account,
};
if (!this.contactsBalanceTable[entry.contactId]) {
this.contactsBalanceTable[entry.contactId] = [];
}
this.contactsBalanceTable[entry.contactId].push(change);
}
/**
* Save contacts balance change.
*/
async saveContactsBalance() {
await this.initAccountsDepGraph();
const balanceChanges = Object.entries(this.contactsBalanceTable).map(
([contactId, entries]) => ({
contactId,
entries: entries.filter((entry) => {
const account = this.accountsDepGraph.getNodeData(entry.account);
return (
account &&
CONTACTS_CONFIG.some((config) => {
return config.accountBySlug === account.slug;
})
);
}),
})
);
const balanceEntries = chain(balanceChanges)
.map((change) => change.entries.map(entry => ({
...entry,
contactId: change.contactId
})))
.flatten()
.value();
return this.saveContactBalanceQueue.pushAsync(balanceEntries);
}
/**
* Saves contact balance change task.
* @param {number} contactId - Contact id.
* @param {number} credit - Credit amount.
* @param {number} debit - Debit amount.
*/
async saveContactBalanceChangeTask({ contactId, credit, debit }) {
const { contactRepository } = this.repositories;
const contact = await contactRepository.findOneById(contactId);
let balanceChange = 0;
if (contact.contactNormal === 'credit') {
balanceChange += credit - debit;
} else {
balanceChange += debit - credit;
}
// Contact change balance.
await contactRepository.changeNumber(
{ id: contactId },
'balance',
balanceChange
);
}
/**
@@ -321,7 +421,8 @@ export default class JournalPoster implements IJournalPoster {
entry.credit = -1 * entry.credit;
entry.debit = -1 * entry.debit;
this.setAccountBalanceChange(entry, entry.accountNormal);
this.setAccountBalanceChange(entry);
this.setContactBalanceChange(entry);
});
this.deletedEntriesIds.push(...removeEntries.map((entry) => entry.id));
}

View File

@@ -240,7 +240,10 @@ export default class ContactsService {
journal.fromTransactions(contactsTransactions);
journal.removeEntries();
await Promise.all([journal.saveBalance(), journal.deleteEntries()]);
await Promise.all([
journal.saveBalance(),
journal.deleteEntries(),
]);
}
/**

View File

@@ -268,7 +268,11 @@ export default class CustomersService {
openingBalanceAt,
authorizedUserId
);
await Promise.all([journal.saveBalance(), journal.saveEntries()]);
await Promise.all([
journal.saveBalance(),
journal.saveEntries(),
journal.saveContactsBalance(),
]);
}
/**

View File

@@ -192,7 +192,11 @@ export default class VendorsService {
openingBalanceAt,
user
);
await Promise.all([journal.saveBalance(), journal.saveEntries()]);
await Promise.all([
journal.saveBalance(),
journal.saveEntries(),
journal.saveContactsBalance(),
]);
}
/**

View File

@@ -10,29 +10,12 @@ import DynamicListingService from 'services/DynamicListing/DynamicListService';
import TenancyService from 'services/Tenancy/TenancyService';
import { ServiceError } from 'exceptions';
import InventoryService from 'services/Inventory/Inventory';
import { ACCOUNT_PARENT_TYPE, ACCOUNT_ROOT_TYPE, ACCOUNT_TYPE } from 'data/AccountTypes'
const ERRORS = {
NOT_FOUND: 'NOT_FOUND',
ITEMS_NOT_FOUND: 'ITEMS_NOT_FOUND',
ITEM_NAME_EXISTS: 'ITEM_NAME_EXISTS',
ITEM_CATEOGRY_NOT_FOUND: 'ITEM_CATEOGRY_NOT_FOUND',
COST_ACCOUNT_NOT_COGS: 'COST_ACCOUNT_NOT_COGS',
COST_ACCOUNT_NOT_FOUMD: 'COST_ACCOUNT_NOT_FOUMD',
SELL_ACCOUNT_NOT_FOUND: 'SELL_ACCOUNT_NOT_FOUND',
SELL_ACCOUNT_NOT_INCOME: 'SELL_ACCOUNT_NOT_INCOME',
INVENTORY_ACCOUNT_NOT_FOUND: 'INVENTORY_ACCOUNT_NOT_FOUND',
INVENTORY_ACCOUNT_NOT_INVENTORY: 'INVENTORY_ACCOUNT_NOT_INVENTORY',
ITEMS_HAVE_ASSOCIATED_TRANSACTIONS: 'ITEMS_HAVE_ASSOCIATED_TRANSACTIONS',
ITEM_HAS_ASSOCIATED_TRANSACTINS: 'ITEM_HAS_ASSOCIATED_TRANSACTINS',
ITEM_HAS_ASSOCIATED_INVENTORY_ADJUSTMENT:
'ITEM_HAS_ASSOCIATED_INVENTORY_ADJUSTMENT',
};
import {
ACCOUNT_PARENT_TYPE,
ACCOUNT_ROOT_TYPE,
ACCOUNT_TYPE,
} from 'data/AccountTypes';
import { ERRORS } from './constants';
@Service()
export default class ItemsService implements IItemsService {
@Inject()
@@ -130,7 +113,7 @@ export default class ItemsService implements IItemsService {
});
throw new ServiceError(ERRORS.COST_ACCOUNT_NOT_FOUMD);
// Detarmines the cost of goods sold account.
// Detarmines the cost of goods sold account.
} else if (!foundAccount.isParentType(ACCOUNT_PARENT_TYPE.EXPENSE)) {
this.logger.info('[items] validate cost account not COGS type.', {
tenantId,
@@ -149,9 +132,7 @@ export default class ItemsService implements IItemsService {
tenantId: number,
sellAccountId: number
) {
const {
accountRepository,
} = this.tenancy.repositories(tenantId);
const { accountRepository } = this.tenancy.repositories(tenantId);
this.logger.info('[items] validate sell account existance.', {
tenantId,
@@ -166,7 +147,6 @@ export default class ItemsService implements IItemsService {
sellAccountId,
});
throw new ServiceError(ERRORS.SELL_ACCOUNT_NOT_FOUND);
} else if (!foundAccount.isParentType(ACCOUNT_ROOT_TYPE.INCOME)) {
this.logger.info('[items] sell account not income type.', {
tenantId,
@@ -185,9 +165,7 @@ export default class ItemsService implements IItemsService {
tenantId: number,
inventoryAccountId: number
) {
const {
accountRepository,
} = this.tenancy.repositories(tenantId);
const { accountRepository } = this.tenancy.repositories(tenantId);
this.logger.info('[items] validate inventory account existance.', {
tenantId,
@@ -203,7 +181,6 @@ export default class ItemsService implements IItemsService {
inventoryAccountId,
});
throw new ServiceError(ERRORS.INVENTORY_ACCOUNT_NOT_FOUND);
} else if (!foundAccount.isAccountType(ACCOUNT_TYPE.INVENTORY)) {
this.logger.info('[items] inventory account not inventory type.', {
tenantId,

View File

@@ -0,0 +1,21 @@
export const ERRORS = {
NOT_FOUND: 'NOT_FOUND',
ITEMS_NOT_FOUND: 'ITEMS_NOT_FOUND',
ITEM_NAME_EXISTS: 'ITEM_NAME_EXISTS',
ITEM_CATEOGRY_NOT_FOUND: 'ITEM_CATEOGRY_NOT_FOUND',
COST_ACCOUNT_NOT_COGS: 'COST_ACCOUNT_NOT_COGS',
COST_ACCOUNT_NOT_FOUMD: 'COST_ACCOUNT_NOT_FOUMD',
SELL_ACCOUNT_NOT_FOUND: 'SELL_ACCOUNT_NOT_FOUND',
SELL_ACCOUNT_NOT_INCOME: 'SELL_ACCOUNT_NOT_INCOME',
INVENTORY_ACCOUNT_NOT_FOUND: 'INVENTORY_ACCOUNT_NOT_FOUND',
INVENTORY_ACCOUNT_NOT_INVENTORY: 'INVENTORY_ACCOUNT_NOT_INVENTORY',
ITEMS_HAVE_ASSOCIATED_TRANSACTIONS: 'ITEMS_HAVE_ASSOCIATED_TRANSACTIONS',
ITEM_HAS_ASSOCIATED_TRANSACTINS: 'ITEM_HAS_ASSOCIATED_TRANSACTINS',
ITEM_HAS_ASSOCIATED_INVENTORY_ADJUSTMENT:
'ITEM_HAS_ASSOCIATED_INVENTORY_ADJUSTMENT',
};

View File

@@ -9,6 +9,7 @@ import {
ISystemUser,
IManualJournal,
IPaginationMeta,
IManualJournalEntry,
} from 'interfaces';
import TenancyService from 'services/Tenancy/TenancyService';
import DynamicListingService from 'services/DynamicListing/DynamicListService';
@@ -20,30 +21,7 @@ import {
import JournalPoster from 'services/Accounting/JournalPoster';
import JournalCommands from 'services/Accounting/JournalCommands';
import JournalPosterService from 'services/Sales/JournalPosterService';
const ERRORS = {
NOT_FOUND: 'manual_journal_not_found',
CREDIT_DEBIT_NOT_EQUAL_ZERO: 'credit_debit_not_equal_zero',
CREDIT_DEBIT_NOT_EQUAL: 'credit_debit_not_equal',
ACCCOUNTS_IDS_NOT_FOUND: 'acccounts_ids_not_found',
JOURNAL_NUMBER_EXISTS: 'journal_number_exists',
ENTRIES_SHOULD_ASSIGN_WITH_CONTACT: 'ENTRIES_SHOULD_ASSIGN_WITH_CONTACT',
CONTACTS_NOT_FOUND: 'contacts_not_found',
MANUAL_JOURNAL_ALREADY_PUBLISHED: 'MANUAL_JOURNAL_ALREADY_PUBLISHED',
};
const CONTACTS_CONFIG = [
{
accountBySlug: 'accounts-receivable',
contactService: 'customer',
assignRequired: false,
},
{
accountBySlug: 'accounts-payable',
contactService: 'vendor',
assignRequired: true,
},
];
import { ERRORS } from './constants';
@Service()
export default class ManualJournalsService implements IManualJournalsService {
@@ -159,8 +137,7 @@ export default class ManualJournalsService implements IManualJournalsService {
const { Account } = this.tenancy.models(tenantId);
const manualAccountsIds = manualJournalDTO.entries.map((e) => e.accountId);
const accounts = await Account.query()
.whereIn('id', manualAccountsIds);
const accounts = await Account.query().whereIn('id', manualAccountsIds);
const storedAccountsIds = accounts.map((account) => account.id);
@@ -203,29 +180,37 @@ export default class ManualJournalsService implements IManualJournalsService {
* @param {string} accountBySlug
* @param {string} contactType
*/
private async validateAccountsWithContactType(
private async validateAccountWithContactType(
tenantId: number,
manualJournalDTO: IManualJournalDTO,
accountBySlug: string,
contactType: string,
contactRequired: boolean = true
): Promise<void> {
const { accountRepository } = this.tenancy.repositories(tenantId);
const payableAccount = await accountRepository.findOne({
slug: accountBySlug,
});
entriesDTO: IManualJournalEntry[],
const entriesHasNoVendorContact = manualJournalDTO.entries.filter(
(e) =>
e.accountId === payableAccount.id &&
((!e.contactId && contactRequired) || e.contactType !== contactType)
accountBySlug: string,
contactType: string
): Promise<void> {
const { Account, Contact } = this.tenancy.models(tenantId);
// Retrieve account meta by the given account slug.
const account = await Account.query().findOne('slug', accountBySlug);
// Filter all entries of the given account.
const accountEntries = entriesDTO.filter(
(entry) => entry.accountId === account.id
);
if (entriesHasNoVendorContact.length > 0) {
const indexes = entriesHasNoVendorContact.map((e) => e.index);
// Can't continue if there is no entry that associate to the given account.
if (accountEntries.length === 0) {
return;
}
// Filter entries that have no contact type or not equal the valid type.
const entriesNoContact = accountEntries.filter(
(entry) => !entry.contactType || entry.contactType !== contactType
);
// Throw error in case one of entries that has invalid contact type.
if (entriesNoContact.length > 0) {
const indexes = entriesNoContact.map(e => e.index);
throw new ServiceError(ERRORS.ENTRIES_SHOULD_ASSIGN_WITH_CONTACT, '', {
accountSlug: accountBySlug,
contactType,
accountBySlug,
indexes,
});
}
@@ -238,19 +223,22 @@ export default class ManualJournalsService implements IManualJournalsService {
*/
private async dynamicValidateAccountsWithContactType(
tenantId: number,
manualJournalDTO: IManualJournalDTO
entriesDTO: IManualJournalEntry[]
): Promise<any> {
return Promise.all(
CONTACTS_CONFIG.map(({ accountBySlug, contactService, assignRequired }) =>
this.validateAccountsWithContactType(
tenantId,
manualJournalDTO,
accountBySlug,
contactService,
assignRequired
)
)
);
return Promise.all([
this.validateAccountWithContactType(
tenantId,
entriesDTO,
'accounts-receivable',
'customer'
),
this.validateAccountWithContactType(
tenantId,
entriesDTO,
'accounts-payable',
'vendor'
),
]);
}
/**
@@ -273,9 +261,9 @@ export default class ManualJournalsService implements IManualJournalsService {
const entriesContactsIds = entriesContactPairs.map(
(entry) => entry.contactId
);
// Retrieve all stored contacts on the storage from contacts entries.
const storedContacts = await contactRepository.findByIds(
const storedContacts = await contactRepository.findWhereIn(
'id',
entriesContactsIds
);
// Converts the stored contacts to map with id as key and entry as value.
@@ -287,8 +275,7 @@ export default class ManualJournalsService implements IManualJournalsService {
entriesContactPairs.forEach((contactEntry) => {
const storedContact = storedContactsMap.get(contactEntry.contactId);
// in case the contact id not found or contact type no equals pushed to
// not found contacts.
// in case the contact id not found.
if (
!storedContact ||
storedContact.contactService !== contactEntry.contactType
@@ -378,7 +365,7 @@ export default class ManualJournalsService implements IManualJournalsService {
// Validate accounts with contact type from the given config.
await this.dynamicValidateAccountsWithContactType(
tenantId,
manualJournalDTO
manualJournalDTO.entries
);
this.logger.info(
'[manual_journal] trying to save manual journal to the storage.',
@@ -446,7 +433,7 @@ export default class ManualJournalsService implements IManualJournalsService {
// Validate accounts with contact type from the given config.
await this.dynamicValidateAccountsWithContactType(
tenantId,
manualJournalDTO
manualJournalDTO.entries
);
// Transform manual journal DTO to model.
const manualJournalObj = this.transformEditDTOToModel(
@@ -525,7 +512,7 @@ export default class ManualJournalsService implements IManualJournalsService {
tenantId: number,
manualJournalsIds: number[]
): Promise<{
oldManualJournals: IManualJournal[]
oldManualJournals: IManualJournal[];
}> {
const { ManualJournal, ManualJournalEntry } = this.tenancy.models(tenantId);
@@ -817,6 +804,7 @@ export default class ManualJournalsService implements IManualJournalsService {
journal.saveBalance(),
journal.deleteEntries(),
journal.saveEntries(),
journal.saveContactsBalance(),
]);
this.logger.info(
'[manual_journal] the journal entries saved successfully.',

View File

@@ -0,0 +1,24 @@
export const ERRORS = {
NOT_FOUND: 'manual_journal_not_found',
CREDIT_DEBIT_NOT_EQUAL_ZERO: 'credit_debit_not_equal_zero',
CREDIT_DEBIT_NOT_EQUAL: 'credit_debit_not_equal',
ACCCOUNTS_IDS_NOT_FOUND: 'acccounts_ids_not_found',
JOURNAL_NUMBER_EXISTS: 'journal_number_exists',
ENTRIES_SHOULD_ASSIGN_WITH_CONTACT: 'ENTRIES_SHOULD_ASSIGN_WITH_CONTACT',
CONTACTS_NOT_FOUND: 'contacts_not_found',
ENTRIES_CONTACTS_NOT_FOUND: 'ENTRIES_CONTACTS_NOT_FOUND',
MANUAL_JOURNAL_ALREADY_PUBLISHED: 'MANUAL_JOURNAL_ALREADY_PUBLISHED',
};
export const CONTACTS_CONFIG = [
{
accountBySlug: 'accounts-receivable',
contactService: 'customer',
assignRequired: true,
},
{
accountBySlug: 'accounts-payable',
contactService: 'vendor',
assignRequired: true,
},
];

View File

@@ -27,7 +27,6 @@ import DynamicListingService from 'services/DynamicListing/DynamicListService';
import { entriesAmountDiff, formatDateFields } from 'utils';
import { ServiceError } from 'exceptions';
import { ACCOUNT_PARENT_TYPE } from 'data/AccountTypes';
import PayableAgingSummaryService from 'services/FinancialStatements/AgingSummary/APAgingSummaryService';
const ERRORS = {
BILL_VENDOR_NOT_FOUND: 'VENDOR_NOT_FOUND',
@@ -452,6 +451,7 @@ export default class BillPaymentsService {
.delete();
await BillPayment.query().where('id', billPaymentId).delete();
// Triggers `onBillPaymentDeleted` event.
await this.eventDispatcher.dispatch(events.billPayment.onDeleted, {
tenantId,
billPaymentId,
@@ -490,7 +490,8 @@ export default class BillPaymentsService {
*/
public async recordJournalEntries(
tenantId: number,
billPayment: IBillPayment
billPayment: IBillPayment,
override: boolean = false,
) {
const { AccountTransaction } = this.tenancy.models(tenantId);
const { accountRepository } = this.tenancy.repositories(tenantId);
@@ -498,7 +499,7 @@ export default class BillPaymentsService {
const paymentAmount = sumBy(billPayment.entries, 'paymentAmount');
const formattedDate = moment(billPayment.paymentDate).format('YYYY-MM-DD');
// Retrieve AP account from the storage.
// Retrieve A/P account from the storage.
const payableAccount = await accountRepository.findOne({
slug: 'accounts-payable',
});
@@ -511,26 +512,27 @@ export default class BillPaymentsService {
referenceType: 'BillPayment',
date: formattedDate,
};
if (billPayment.id) {
if (override) {
const transactions = await AccountTransaction.query()
.whereIn('reference_type', ['BillPayment'])
.where('reference_id', billPayment.id)
.withGraphFetched('account');
journal.loadEntries(transactions);
journal.fromTransactions(transactions);
journal.removeEntries();
}
const debitReceivable = new JournalEntry({
...commonJournal,
debit: paymentAmount,
contactType: 'Vendor',
contactId: billPayment.vendorId,
account: payableAccount.id,
index: 1,
});
const creditPaymentAccount = new JournalEntry({
...commonJournal,
credit: paymentAmount,
account: billPayment.paymentAccountId,
index: 2,
});
journal.debit(debitReceivable);
journal.credit(creditPaymentAccount);
@@ -539,6 +541,7 @@ export default class BillPaymentsService {
journal.deleteEntries(),
journal.saveEntries(),
journal.saveBalance(),
journal.saveContactsBalance(),
]);
}
@@ -554,7 +557,11 @@ export default class BillPaymentsService {
await journalCommands.revertJournalEntries(billPaymentId, 'BillPayment');
return Promise.all([journal.saveBalance(), journal.deleteEntries()]);
return Promise.all([
journal.saveBalance(),
journal.deleteEntries(),
journal.saveContactsBalance(),
]);
}
/**

View File

@@ -527,6 +527,7 @@ export default class BillsService extends SalesInvoicesCost {
journal.deleteEntries(),
journal.saveEntries(),
journal.saveBalance(),
journal.saveContactsBalance(),
]);
}

View File

@@ -27,7 +27,8 @@ export default class JournalPosterService {
await Promise.all([
journal.deleteEntries(),
journal.saveBalance()
journal.saveBalance(),
journal.saveContactsBalance(),
]);
}
}

View File

@@ -16,7 +16,6 @@ import {
IPaymentReceiveEntryDTO,
IPaymentReceivesFilter,
ISaleInvoice,
ISystemService,
ISystemUser,
IPaymentReceivePageEntry,
} from 'interfaces';
@@ -496,7 +495,7 @@ export default class PaymentReceiveService {
paymentReceiveId: number,
authorizedUser: ISystemUser
): Promise<{
paymentReceive: Omit<IPaymentReceive, "entries">;
paymentReceive: Omit<IPaymentReceive, 'entries'>;
entries: IPaymentReceivePageEntry[];
}> {
const { PaymentReceive, SaleInvoice } = this.tenancy.models(tenantId);
@@ -665,7 +664,6 @@ export default class PaymentReceiveService {
const creditReceivable = new JournalEntry({
...commonJournal,
credit: paymentAmount,
contactType: 'Customer',
contactId: paymentReceive.customerId,
account: receivableAccount.id,
index: 1,
@@ -683,6 +681,7 @@ export default class PaymentReceiveService {
journal.deleteEntries(),
journal.saveEntries(),
journal.saveBalance(),
journal.saveContactsBalance(),
]);
}
@@ -705,7 +704,11 @@ export default class PaymentReceiveService {
await commands.revertJournalEntries(paymentReceiveId, 'PaymentReceive');
await Promise.all([journal.saveBalance(), journal.deleteEntries()]);
await Promise.all([
journal.saveBalance(),
journal.deleteEntries(),
journal.saveContactsBalance(),
]);
}
/**

View File

@@ -29,6 +29,7 @@ import ItemsEntriesService from 'services/Items/ItemsEntriesService';
import CustomersService from 'services/Contacts/CustomersService';
import SaleEstimateService from 'services/Sales/SalesEstimate';
import JournalPosterService from './JournalPosterService';
import SaleInvoiceRepository from 'repositories/SaleInvoiceRepository';
const ERRORS = {
INVOICE_NUMBER_NOT_UNIQUE: 'INVOICE_NUMBER_NOT_UNIQUE',
@@ -37,6 +38,8 @@ const ERRORS = {
ENTRIES_ITEMS_IDS_NOT_EXISTS: 'ENTRIES_ITEMS_IDS_NOT_EXISTS',
NOT_SELLABLE_ITEMS: 'NOT_SELLABLE_ITEMS',
SALE_INVOICE_NO_NOT_UNIQUE: 'SALE_INVOICE_NO_NOT_UNIQUE',
INVOICE_AMOUNT_SMALLER_THAN_PAYMENT_AMOUNT:
'INVOICE_AMOUNT_SMALLER_THAN_PAYMENT_AMOUNT',
INVOICE_HAS_ASSOCIATED_PAYMENT_ENTRIES:
'INVOICE_HAS_ASSOCIATED_PAYMENT_ENTRIES',
};
@@ -130,6 +133,20 @@ export default class SaleInvoicesService {
return entries;
}
/**
* Validate the invoice amount is bigger than payment amount before edit the invoice.
* @param {number} saleInvoiceAmount
* @param {number} paymentAmount
*/
validateInvoiceAmountBiggerPaymentAmount(
saleInvoiceAmount: number,
paymentAmount: number
) {
if (saleInvoiceAmount < paymentAmount) {
throw new ServiceError(ERRORS.INVOICE_AMOUNT_SMALLER_THAN_PAYMENT_AMOUNT);
}
}
/**
* Validate whether sale invoice exists on the storage.
* @param {Request} req
@@ -267,7 +284,7 @@ export default class SaleInvoicesService {
saleInvoiceDTO: any,
authorizedUser: ISystemUser
): Promise<ISaleInvoice> {
const { SaleInvoice } = this.tenancy.models(tenantId);
const { saleInvoiceRepository } = this.tenancy.repositories(tenantId);
const oldSaleInvoice = await this.getInvoiceOrThrowError(
tenantId,
@@ -309,12 +326,16 @@ export default class SaleInvoicesService {
'SaleInvoice',
saleInvoiceDTO.entries
);
// Validate the invoice amount is not smaller than the invoice payment amount.
this.validateInvoiceAmountBiggerPaymentAmount(
saleInvoiceObj.balance,
oldSaleInvoice.paymentAmount
);
this.logger.info('[sale_invoice] trying to update sale invoice.');
const saleInvoice: ISaleInvoice = await SaleInvoice.query().upsertGraphAndFetch(
{
id: saleInvoiceId,
...saleInvoiceObj,
}
const saleInvoice: ISaleInvoice = await saleInvoiceRepository.update(
{ ...omit(saleInvoiceObj, ['paymentAmount']) },
{ id: saleInvoiceId }
);
// Triggers `onSaleInvoiceEdited` event.
await this.eventDispatcher.dispatch(events.saleInvoice.onEdited, {
@@ -470,6 +491,7 @@ export default class SaleInvoicesService {
await Promise.all([
journal.deleteEntries(),
journal.saveBalance(),
journal.saveContactsBalance(),
journal.saveEntries(),
]);
}