import { IEntityQuery } from "@entity-access/entity-access/dist/model/IFilterWithParameter.js"; import AuthenticatedEvents from "./AuthenticatedEvents.js"; import EntityAccessError from "@entity-access/entity-access/dist/common/EntityAccessError.js"; import { StoreJournalEntry } from "../entities/StoreJournalEntry.js"; import ChangeEntry from "@entity-access/entity-access/dist/model/changes/ChangeEntry.js"; import Inject, { ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import SocialMailContext from "../SocialMailContext.js"; import Sql from "@entity-access/entity-access/dist/sql/Sql.js"; import SalesInvoiceService from "../../services/accounts/sales/SalesInvoiceService.js"; import JournalService from "../../services/accounts/JournalService.js"; import { StoreJournal } from "../entities/StoreJournal.js"; import { Symbols } from "../../../common/Symbols.js"; import { Decimal } from "decimal.js"; export default class StoreJournalEvents extends AuthenticatedEvents { @Inject db: SocialMailContext; filter(query: IEntityQuery) { if (!this.verify) { return query; } const { sessionUser } = this; if (sessionUser.isAdmin) { return query; } return query.where(sessionUser, (x, p) => Sql.text.likeAny(x.store.folder.path, p.writeFileAccess) || x.buyer.userID === p.userID ); } modify(query: IEntityQuery) { return this.filter(query); } delete(query: IEntityQuery): IEntityQuery { if (!this.verify) { return query; } // only draft mode journals can be deleted return query.where((x) => x.posted === false); } includeFilter(query: IEntityQuery, type?: any, key?: string) { return query; } async beforeDelete(entity: StoreJournal, entry: ChangeEntry) { if (entity.posted) { throw new EntityAccessError(`Posted journals cannot be deleted`); } await this.db.storeJournalEntries.asQuery().delete(entity, (x, p) => x.journalID === p.journalID); await this.db.storeJournalLineItems.asQuery().delete(entity, (x, p) => x.journalID === p.journalID); } async beforeInsert(entity: StoreJournal, entry: ChangeEntry) { if (this.verify) { if (entity[Symbols.enableSaveWithoutLogin] !== true) { this.sessionUser.ensureLoggedIn(); } } await this.syncAmount(entry); if (entity.posted) { await this.verifyEntries(entry); } } async syncAmount(entry: ChangeEntry) { const { entity } = entry; switch(entity.journalType) { case "order": case "purchase-bill": case "purchase-order": case "sales-invoice": const si = ServiceProvider.resolve(this, SalesInvoiceService); await si.syncAmount(entry, entity); break; } } async beforeUpdate(entity: StoreJournal, entry: ChangeEntry) { if (entity[Symbols.enableSaveWithoutLogin] !== true) { this.sessionUser.ensureLoggedIn(); } await entry.loadNavigationAsync((x) => x.orderCoupons); if (entry.isModified("posted")) { if(entry.getChange("posted").oldValue) { throw new EntityAccessError("Posted journal cannot be saved as draft."); } await this.verifyEntries(entry); } else { if (entity.posted) { throw new EntityAccessError("Posted journal cannot be modified"); } } await this.syncAmount(entry); } async verifyEntries(entry: ChangeEntry) { const { entity } = entry; // create sales entries... await entry.loadNavigationAsync((x) => x.store); entity.entries ??= []; const journalService = ServiceProvider.resolve(this, JournalService); await journalService.syncEntries(entry, entity); if (!entity.entries?.length) { throw new EntityAccessError("Cannot save empty voucher"); } let credits = Decimal(0); let debits = Decimal(0); for (const iterator of entity.entries) { iterator.credit ??= 0; iterator.debit ??= 0; if (!( (iterator.credit > 0 && iterator.debit === 0) || (iterator.debit > 0 && iterator.credit === 0) )) { throw new EntityAccessError(`Journal entry can only have positive credit or debit, not both.`); } credits = credits.add(Decimal(iterator.credit)); debits = debits.add(Decimal(iterator.debit)); } if (!credits.equals(debits)) { // eslint-disable-next-line no-console console.log(entity.entries); throw new EntityAccessError(`Journal is not balanced, sum of all credits ${credits} and debits ${debits} must be equal.`); } } afterInsert(entity: StoreJournal, entry: ChangeEntry) { if (entity.subscription) { entity.subscription.currentOrderID = entity.journalID; } return this.updateBalances(entity, entry); } afterUpdate(entity: StoreJournal, entry: ChangeEntry) { return this.updateBalances(entity, entry); } async updateBalances(entity: StoreJournal, entry: ChangeEntry) { if (!entry.isUpdated("posted")) { return; } if (entity.journalType === "sales-invoice") { let { invoiceID, store: { nextInvoiceID } } = entity; const { journalID, store: { folderID } } = entity; // set invoiceID if(!invoiceID) { await entry.loadNavigationAsync((x) => x.store); const { invoicePrefix } = entity.store; invoiceID = `${invoicePrefix ?? ""}${nextInvoiceID.toString().padStart(5, "0")}`; await this.db.storeJournals.statements.update({ invoiceID }, { journalID }); nextInvoiceID++; await this.db.websiteFolders.statements.update({ nextInvoiceID }, { folderID }); } else { if (invoiceID) { const m = /(?\d+)$/.exec(invoiceID); const id = m?.groups["id"]; if (id) { const { storeID } = entity; nextInvoiceID = (BigInt(id) + 1n).toString() as any; await this.db.websiteFolders.where({ storeID, nextInvoiceID }, (x, p) => x.folderID === p.storeID && x.nextInvoiceID < p.nextInvoiceID) .update({ nextInvoiceID }, (x, p) => ({ nextInvoiceID })); } } } } this.db.queuePostSaveTask(async () => { await entry.loadNavigationAsync((x) => x.entries); if (!entity.entries?.length) { return; } for (const iterator of entity.entries) { await this.updateBalance(iterator); } }); } async updateBalance(entry: StoreJournalEntry) { const last = await this.db.storeJournalEntries.where(entry, (x, p) => x.accountID === p.accountID) .orderByDescending((x) => x.entryID) .first(); const lastBalance = last?.balance ?? 0; entry.balance = lastBalance + entry.debit - entry.credit; await this.db.storeJournalEntries.where(entry, (x, p) => x.entryID === p.entryID) .update(entry, (x, p) => ({ balance: Sql.cast.asDecimal(p.balance) })); await this.db.storeAccounts.where(entry, (x, p) => x.accountID === p.accountID) .update(entry, (x, p) => ({ balance: Sql.cast.asDecimal(p.balance)})); if (entry.storeAccount?.parentID) { await this.db.storeAccounts.where(entry.storeAccount, (x, p) => x.accountID === p.parentID) .update((x) => ({ balance: Sql.coll.sum(x.children.map((c) => c.balance)) })); } } }