All files / src/domains/finance/services posting-engine.service.ts

0% Statements 0/87
0% Branches 0/68
0% Functions 0/5
0% Lines 0/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207                                                                                                                                                                                                                                                                                                                                                                                                                             
import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { JournalEntry, JournalLine } from '../schemas/journal-entry.schema';
import { GeneralLedgerEntry } from '../schemas/general-ledger-entry.schema';
import { LedgerAccount } from '../schemas/ledger-account.schema';
import { FinancePeriod } from '../schemas/fiscal-period.schema';
import { FinanceConfiguration } from '../schemas/finance-configuration.schema';
import { EventBusService } from '../../../platform/events/event-bus.service';
 
@Injectable()
export class PostingEngineService {
  constructor(
    @InjectModel(JournalEntry.name)
    private readonly journalModel: Model<JournalEntry>,
    @InjectModel(JournalLine.name)
    private readonly lineModel: Model<JournalLine>,
    @InjectModel(GeneralLedgerEntry.name)
    private readonly glModel: Model<GeneralLedgerEntry>,
    @InjectModel(LedgerAccount.name)
    private readonly accountModel: Model<LedgerAccount>,
    @InjectModel(FinancePeriod.name)
    private readonly periodModel: Model<FinancePeriod>,
    @InjectModel(FinanceConfiguration.name)
    private readonly configModel: Model<FinanceConfiguration>,
    private readonly eventBus: EventBusService,
  ) {}
 
  async postJournalEntry(tenantId: string, journalId: string, userId: string): Promise<JournalEntry> {
    const journal = await this.journalModel.findOne({ _id: journalId, tenantId }).exec();
    if (!journal) throw new NotFoundException('Journal Entry not found');
    if (journal.status === 'posted') {
      throw new BadRequestException('Journal Entry is already posted and immutable');
    }
 
    const lines = await this.lineModel.find({ journalEntryId: journal._id }).exec();
    if (lines.length === 0) {
      throw new BadRequestException('Journal Entry must contain at least one line');
    }
 
    // 1. Verify Debit equals Credit in integers
    let totalDebit = 0;
    let totalCredit = 0;
    for (const line of lines) {
      totalDebit += line.debitAmountMinor;
      totalCredit += line.creditAmountMinor;
    }
 
    if (totalDebit !== totalCredit) {
      throw new BadRequestException(`Unbalanced journal: Sum of Debits (${totalDebit}) must equal Sum of Credits (${totalCredit})`);
    }
 
    // 2. Validate Posting Period is OPEN
    const pDate = journal.postingDate;
    const period = await this.periodModel.findOne({
      tenantId,
      startDate: { $lte: pDate },
      endDate: { $gte: pDate }
    }).exec();
 
    if (!period) {
      throw new BadRequestException(`No active fiscal period defined for posting date: ${pDate.toISOString()}`);
    }
    if (period.status !== 'open' && period.status !== 'reopened') {
      throw new BadRequestException(`Posting blocked: Period ${period.periodName} is in ${period.status} status`);
    }
 
    // 3. Post to Accounts and create General Ledger Entries
    const glEntries: any[] = [];
    
    for (const line of lines) {
      const account = await this.accountModel.findOne({ _id: line.ledgerAccountId, tenantId }).exec();
      if (!account) {
        throw new NotFoundException(`Account ${line.ledgerAccountId} not found`);
      }
 
      // If manual entry and configuration locks it, check control account rule
      if (journal.journalSource === 'Manual' && account.isControlAccount) {
        throw new BadRequestException(`Manual posts are prohibited to control account: ${account.accountCode}`);
      }
 
      // Update Ledger balances:
      // Asset, Expense, Contra Liability, Contra Asset adjustments
      let change = 0;
      if (account.accountType === 'Asset' || account.accountType === 'Expense') {
        change = line.debitAmountMinor - line.creditAmountMinor;
      } else {
        change = line.creditAmountMinor - line.debitAmountMinor;
      }
 
      await this.accountModel.updateOne(
        { _id: account._id, tenantId },
        { $inc: { currentBalanceMinor: change } }
      ).exec();
 
      // Create GL record
      const glEntry = new this.glModel({
        tenantId: new Types.ObjectId(tenantId),
        legalEntityId: journal.legalEntityId,
        accountingBookId: journal.accountingBookId,
        journalEntryId: journal._id,
        journalLineId: line._id,
        ledgerAccountId: account._id,
        postingDate: journal.postingDate,
        debitAmountMinor: line.debitAmountMinor,
        creditAmountMinor: line.creditAmountMinor,
        baseDebitAmountMinor: line.baseDebitAmountMinor || Math.round(line.debitAmountMinor * journal.exchangeRate),
        baseCreditAmountMinor: line.baseCreditAmountMinor || Math.round(line.creditAmountMinor * journal.exchangeRate),
        currency: journal.currency,
        exchangeRate: journal.exchangeRate,
        description: line.description || journal.reversalReason,
        dimensions: line.dimensions
      });
      await glEntry.save();
      glEntries.push(glEntry);
    }
 
    journal.status = 'posted';
    journal.postedBy = new Types.ObjectId(userId) as any;
    journal.postedAt = new Date();
    journal.baseDebitTotalMinor = totalDebit;
    journal.baseCreditTotalMinor = totalCredit;
    await journal.save();
 
    // Publish event outbox pattern
    await this.eventBus.publish('finance.journal.posted.v1', {
      journalId: journal._id.toString(),
      tenantId,
      journalNumber: journal.journalNumber,
      totalAmountMinor: totalDebit,
      currency: journal.currency,
      postedAt: journal.postedAt
    }, tenantId);
 
    return journal;
  }
 
  async createReversalJournal(tenantId: string, originalJournalId: string, reason: string, userId: string): Promise<JournalEntry> {
    const original = await this.journalModel.findOne({ _id: originalJournalId, tenantId }).exec();
    if (!original) throw new NotFoundException('Original Journal not found');
    if (original.status !== 'posted') {
      throw new BadRequestException('Only posted journals can be reversed');
    }
    if (original.reversalJournalId) {
      throw new BadRequestException('This journal has already been reversed');
    }
 
    const lines = await this.lineModel.find({ journalEntryId: original._id }).exec();
    
    // Create new draft reversal journal
    const revNo = `REV-${original.journalNumber}`;
    const reversal = new this.journalModel({
      tenantId: new Types.ObjectId(tenantId),
      legalEntityId: original.legalEntityId,
      accountingBookId: original.accountingBookId,
      journalNumber: revNo,
      postingDate: new Date(),
      status: 'draft',
      journalSource: 'Adjustment',
      currency: original.currency,
      exchangeRate: original.exchangeRate,
      isReversal: true,
      reversalReason: reason
    });
    await reversal.save();
 
    // Copy lines with inverted Debits/Credits
    for (const line of lines) {
      await this.lineModel.create({
        journalEntryId: reversal._id,
        ledgerAccountId: line.ledgerAccountId,
        debitAmountMinor: line.creditAmountMinor,
        creditAmountMinor: line.debitAmountMinor,
        baseDebitAmountMinor: line.baseCreditAmountMinor,
        baseCreditAmountMinor: line.baseDebitAmountMinor,
        description: `Reversal of line: ${line.description || ''}`,
        dimensions: line.dimensions
      });
    }
 
    // Post it
    await this.postJournalEntry(tenantId, reversal._id.toString(), userId);
 
    original.reversalJournalId = reversal._id as any;
    await original.save();
 
    await this.eventBus.publish('finance.journal.reversed.v1', {
      originalJournalId,
      reversalJournalId: reversal._id.toString(),
      tenantId
    }, tenantId);
 
    return reversal;
  }
 
  async getPendingApprovals(tenantId: string): Promise<JournalEntry[]> {
    return this.journalModel.find({ tenantId, status: 'approval_pending' }).exec();
  }
 
  async approveJournal(tenantId: string, journalId: string): Promise<JournalEntry> {
    const journal = await this.journalModel.findOne({ _id: journalId, tenantId }).exec();
    if (!journal) throw new NotFoundException('Journal not found');
    journal.status = 'approved';
    return journal.save();
  }
}