All files / src/domains/procurement/returns/services return.service.ts

0% Statements 0/24
0% Branches 0/14
0% Functions 0/5
0% Lines 0/21

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                                                                                                                                   
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { VendorReturn } from '../schemas/return.schema';
import { EventBusService } from '../../../../platform/events/event-bus.service';
import { AuditLogService } from '../../../../platform/audit/audit-log.service';
 
@Injectable()
export class ReturnService {
  constructor(
    @InjectModel(VendorReturn.name)
    private readonly returnModel: Model<VendorReturn>,
    private readonly eventBus: EventBusService,
    private readonly auditLog: AuditLogService,
  ) {}
 
  async createReturn(tenantId: string, data: any, userId: string): Promise<VendorReturn> {
    const count = await this.returnModel.countDocuments({ tenantId }).exec();
    const returnNumber = `RET-${new Date().getFullYear()}-${(count + 1).toString().padStart(5, '0')}`;
 
    const subtotal = data.lines.reduce((sum: number, line: any) => sum + line.total, 0);
    const tax = subtotal * 0.1; // Resolved returns default
    const totalAmount = subtotal + tax;
 
    const record = await this.returnModel.create({
      ...data,
      tenantId,
      returnNumber,
      subtotal,
      tax,
      totalAmount,
      status: 'approved',
    });
 
    await this.eventBus.publish('procurement.purchase-return.approved.v1', {
      eventId: `evt-ret-${(record as any)._id.toString()}`,
      occurredAt: new Date(),
      idempotencyKey: `idemp-ret-${(record as any)._id.toString()}`,
      tenantId,
      purchaseOrderId: data.purchaseOrderId,
      returnId: (record as any)._id.toString(),
      vendorId: data.vendorId,
      lines: data.lines.map((line: any, idx: number) => ({
        poLineIndex: line.poLineIndex,
        quantityReturned: line.quantity,
        unitCostSnapshot: line.unitPrice || 0,
      })),
    }, tenantId);
 
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'APPROVE_RETURN',
      resource: 'VendorReturn',
      resourceId: (record as any)._id.toString(),
      newValues: { returnNumber },
    });
 
    return record;
  }
 
  async getReturns(tenantId: string): Promise<VendorReturn[]> {
    return this.returnModel.find({ tenantId }).exec();
  }
}