mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-27 00:52:50 +00:00
Credit and Debt plus reason attribute inide register
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||
|
||||
/**
|
||||
* Debit/credit note filing — confirmed directly by MoR support: same `/v1/register` endpoint,
|
||||
* distinguished by `DocumentDetails.Type` ("DEB"/"CRE") + a `Reason`, linked to the original
|
||||
* invoice via `ReferenceDetails.RelatedDocument`. See `Invoice.eimsDocumentType`.
|
||||
*/
|
||||
export class EimsDebitCreditNotes3550000000000 implements MigrationInterface {
|
||||
name = "EimsDebitCreditNotes3550000000000";
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE freight.invoices
|
||||
ADD COLUMN IF NOT EXISTS eims_document_type varchar(8) NOT NULL DEFAULT 'INV',
|
||||
ADD COLUMN IF NOT EXISTS eims_reason text,
|
||||
ADD COLUMN IF NOT EXISTS related_invoice_id uuid REFERENCES freight.invoices(id)
|
||||
`);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE freight.invoices
|
||||
DROP COLUMN IF EXISTS eims_document_type,
|
||||
DROP COLUMN IF EXISTS eims_reason,
|
||||
DROP COLUMN IF EXISTS related_invoice_id
|
||||
`);
|
||||
}
|
||||
}
|
||||
@@ -212,6 +212,59 @@ describe("toEimsInvoice", () => {
|
||||
expect(() => toEimsInvoice(invoice({ issuedAt: null }), seller, context())).toThrow(/not issued/);
|
||||
});
|
||||
|
||||
describe("debit/credit notes — confirmed by MoR support, same /v1/register endpoint", () => {
|
||||
it("defaults DocumentDetails.Type to INV with no Reason field", () => {
|
||||
const doc = toEimsInvoice(invoice(), seller, context());
|
||||
expect(doc.DocumentDetails.Type).toBe("INV");
|
||||
expect(doc.DocumentDetails).not.toHaveProperty("Reason");
|
||||
});
|
||||
|
||||
it("files a credit note with Type, Reason and RelatedDocument", () => {
|
||||
const doc = toEimsInvoice(
|
||||
invoice(),
|
||||
seller,
|
||||
context({
|
||||
documentType: "CRE",
|
||||
reason: "Overbilled freight charge",
|
||||
relatedDocument: "9fe9bbbece6ab76c112b617534e6aac7aa8b819d5be79f4d3d088ed2e887b2e0",
|
||||
}),
|
||||
);
|
||||
expect(doc.DocumentDetails).toMatchObject({ Type: "CRE", Reason: "Overbilled freight charge" });
|
||||
expect(doc.ReferenceDetails.RelatedDocument).toBe(
|
||||
"9fe9bbbece6ab76c112b617534e6aac7aa8b819d5be79f4d3d088ed2e887b2e0",
|
||||
);
|
||||
});
|
||||
|
||||
it("files a debit note the same way", () => {
|
||||
const doc = toEimsInvoice(
|
||||
invoice(),
|
||||
seller,
|
||||
context({ documentType: "DEB", reason: "Additional handling fee", relatedDocument: "IRN-1" }),
|
||||
);
|
||||
expect(doc.DocumentDetails).toMatchObject({ Type: "DEB", Reason: "Additional handling fee" });
|
||||
});
|
||||
|
||||
it("throws when a credit/debit note has no reason", () => {
|
||||
expect(() =>
|
||||
toEimsInvoice(
|
||||
invoice(),
|
||||
seller,
|
||||
context({ documentType: "CRE", reason: null, relatedDocument: "IRN-1" }),
|
||||
),
|
||||
).toThrow(/needs a reason/);
|
||||
});
|
||||
|
||||
it("throws when a credit/debit note has no relatedDocument", () => {
|
||||
expect(() =>
|
||||
toEimsInvoice(
|
||||
invoice(),
|
||||
seller,
|
||||
context({ documentType: "CRE", reason: "Overbilled", relatedDocument: null }),
|
||||
),
|
||||
).toThrow(/needs.*relatedDocument/);
|
||||
});
|
||||
});
|
||||
|
||||
it("throws when the lines do not sum to the invoice total", () => {
|
||||
expect(() => toEimsInvoice(invoice({ totalAmount: "9000.00" }), seller, context())).toThrow(
|
||||
/lines sum to 11000 but the invoice total is 9000/,
|
||||
|
||||
@@ -20,8 +20,15 @@ import { round2 } from "./invoice-settlement.util";
|
||||
/** Only proven-required constant: the 400 SCHEMA ERROR sample rejects a payload without it. */
|
||||
const EIMS_VERSION = "1";
|
||||
|
||||
/** The only `DocumentDetails.Type` observed in the supplied material. */
|
||||
const EIMS_DOCUMENT_TYPE = "INV";
|
||||
/**
|
||||
* `DocumentDetails.Type`. `"INV"` is the only value observed in the collection; `"DEB"`/`"CRE"`
|
||||
* (debit/credit note) were confirmed directly by MoR support — same `/v1/register` endpoint, no
|
||||
* separate API. MoR's answer, verbatim: "the same endpoint used for registration should be used
|
||||
* ... within the Document Detail object, you should specify DEB for a debit note, CRE for a
|
||||
* credit note... add a Reason attribute under document detail object".
|
||||
*/
|
||||
export const EIMS_DOCUMENT_TYPES = ["INV", "DEB", "CRE"] as const;
|
||||
export type EimsDocumentType = (typeof EIMS_DOCUMENT_TYPES)[number];
|
||||
|
||||
export interface EimsBuyerDetails {
|
||||
City: string | null;
|
||||
@@ -60,7 +67,9 @@ export interface EimsDocumentDetails {
|
||||
DocumentNumber: string;
|
||||
/** Observed format `dd-MM-yyyyTHH:mm:ss`. Rule seen in the collection: within 3 days of now. */
|
||||
Date: string;
|
||||
Type: string;
|
||||
Type: EimsDocumentType;
|
||||
/** Only for DEB/CRE, per MoR support — why the debit/credit note was issued. Absent for INV. */
|
||||
Reason?: string;
|
||||
}
|
||||
|
||||
export interface EimsInvoiceItem {
|
||||
@@ -212,7 +221,18 @@ export interface EimsMapperContext {
|
||||
unitDefault: string;
|
||||
incomeWithholdValue: number;
|
||||
transactionWithholdValue: number;
|
||||
/** Null for an ordinary invoice; set only for a real related-document case. */
|
||||
/**
|
||||
* `DocumentDetails.Type`. Defaults to `"INV"`. For `"DEB"`/`"CRE"` both `reason` and
|
||||
* `relatedDocument` become required — confirmed directly by MoR support, not the collection.
|
||||
*/
|
||||
documentType?: EimsDocumentType;
|
||||
/** Required when `documentType` is `"DEB"`/`"CRE"` — why the note was issued. Unused for INV. */
|
||||
reason?: string | null;
|
||||
/**
|
||||
* `ReferenceDetails.RelatedDocument`. Null for an ordinary invoice; required for a DEB/CRE —
|
||||
* the original registered invoice's IRN, per MoR's own IRC-P06/P07 checklist ("credit memo
|
||||
* from a registered invoice").
|
||||
*/
|
||||
relatedDocument?: string | null;
|
||||
/** MoR numeric country code for the buyer; our DB stores the country name. */
|
||||
buyerCountryCode?: string | null;
|
||||
@@ -326,6 +346,26 @@ export function toEimsInvoice(
|
||||
);
|
||||
}
|
||||
|
||||
const documentType = context.documentType ?? "INV";
|
||||
if (!EIMS_DOCUMENT_TYPES.includes(documentType)) {
|
||||
throw new Error(
|
||||
`EIMS mapping: invoice ${invoice.invoiceNumber} has documentType "${documentType}", must be one of ${EIMS_DOCUMENT_TYPES.join(", ")}`,
|
||||
);
|
||||
}
|
||||
if (documentType !== "INV") {
|
||||
if (!context.reason?.trim()) {
|
||||
throw new Error(
|
||||
`EIMS mapping: invoice ${invoice.invoiceNumber} is a ${documentType} (debit/credit note) and needs a reason`,
|
||||
);
|
||||
}
|
||||
if (!context.relatedDocument?.trim()) {
|
||||
throw new Error(
|
||||
`EIMS mapping: invoice ${invoice.invoiceNumber} is a ${documentType} (debit/credit note) and needs ` +
|
||||
"relatedDocument — the original registered invoice's IRN",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const issuedAt = invoice.issuedAt instanceof Date ? invoice.issuedAt : new Date(invoice.issuedAt);
|
||||
if (Number.isNaN(issuedAt.getTime())) {
|
||||
throw new Error(`EIMS mapping: invoice ${invoice.invoiceNumber} has an unparseable issuedAt`);
|
||||
@@ -430,7 +470,8 @@ export function toEimsInvoice(
|
||||
DocumentDetails: {
|
||||
DocumentNumber: context.documentNumber,
|
||||
Date: (context.formatDate ?? formatEimsDate)(issuedAt),
|
||||
Type: EIMS_DOCUMENT_TYPE,
|
||||
Type: documentType,
|
||||
...(documentType !== "INV" ? { Reason: context.reason! } : {}),
|
||||
},
|
||||
ItemList,
|
||||
PaymentDetails: { Mode: context.payment.mode, PaymentTerm: context.payment.term },
|
||||
|
||||
@@ -180,4 +180,27 @@ export class Invoice extends BaseEntity {
|
||||
|
||||
@Column({ name: "eims_cancellation_remark", type: "text", nullable: true })
|
||||
eimsCancellationRemark?: string | null;
|
||||
|
||||
/**
|
||||
* `DocumentDetails.Type` to file this invoice as — "INV" (default), "DEB" or "CRE". Confirmed
|
||||
* by MoR support directly (not the collection): debit/credit notes go through this same
|
||||
* `/v1/register` endpoint, distinguished only by `Type` + `Reason`, linked via
|
||||
* `ReferenceDetails.RelatedDocument` to the original invoice's IRN. This module does not create
|
||||
* debit/credit note invoices — that is a freight-workflow decision — it only files one
|
||||
* correctly once these columns are set on an existing row.
|
||||
*/
|
||||
@Column({ name: "eims_document_type", type: "varchar", length: 8, default: "INV" })
|
||||
eimsDocumentType!: string;
|
||||
|
||||
/** Required by MoR when `eimsDocumentType` is DEB/CRE — why the note was issued. */
|
||||
@Column({ name: "eims_reason", type: "text", nullable: true })
|
||||
eimsReason?: string | null;
|
||||
|
||||
/** The original registered invoice this debit/credit note adjusts. Required for DEB/CRE. */
|
||||
@Column({ name: "related_invoice_id", type: "uuid", nullable: true })
|
||||
relatedInvoiceId?: string | null;
|
||||
|
||||
@ManyToOne(() => Invoice)
|
||||
@JoinColumn({ name: "related_invoice_id" })
|
||||
relatedInvoice?: Invoice | null;
|
||||
}
|
||||
|
||||
@@ -157,6 +157,12 @@ export interface EimsContextInput {
|
||||
session: EimsSessionContext;
|
||||
/** Required when the invoice currency is not ETB. */
|
||||
exchangeRate?: number | null;
|
||||
/** `DocumentDetails.Type` — defaults to "INV" in the mapper when omitted. */
|
||||
documentType?: EimsMapperContext["documentType"];
|
||||
/** Required (by the mapper) when documentType is DEB/CRE. */
|
||||
reason?: string | null;
|
||||
/** `ReferenceDetails.RelatedDocument` — the original invoice's IRN, required for DEB/CRE. */
|
||||
relatedDocument?: string | null;
|
||||
}
|
||||
|
||||
export function buildEimsContext(config: EimsConfig, input: EimsContextInput): EimsMapperContext {
|
||||
@@ -206,5 +212,8 @@ export function buildEimsContext(config: EimsConfig, input: EimsContextInput): E
|
||||
buyerIdType: invoice.buyerIdType,
|
||||
buyerIdNumber: invoice.buyerIdNumber,
|
||||
exchangeRate: input.exchangeRate ?? null,
|
||||
documentType: input.documentType,
|
||||
reason: input.reason ?? null,
|
||||
relatedDocument: input.relatedDocument ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -295,6 +295,58 @@ describe("EimsInvoiceRegistrationService.registerInvoiceWithEims", () => {
|
||||
expect(request.SourceSystem.SystemNumber).toBe(SYSTEM_NUMBER);
|
||||
});
|
||||
|
||||
it("files a credit note with Type/Reason/RelatedDocument from the invoice row", async () => {
|
||||
const original = invoiceRow({
|
||||
id: "original-invoice",
|
||||
invoiceNumber: "INV-20260807-00001",
|
||||
eimsIrn: IRN,
|
||||
});
|
||||
const db = new FakeDb([
|
||||
invoiceRow({
|
||||
eimsDocumentType: "CRE",
|
||||
eimsReason: "Overbilled freight charge",
|
||||
relatedInvoice: original,
|
||||
} as Partial<Invoice>),
|
||||
]);
|
||||
const postSigned = jest.fn().mockResolvedValue(okResponse());
|
||||
|
||||
await build(db, postSigned).registerInvoiceWithEims(INVOICE_ID);
|
||||
|
||||
const request = postSigned.mock.calls[0][1] as EimsInvoiceRequest;
|
||||
expect(request.DocumentDetails).toMatchObject({ Type: "CRE", Reason: "Overbilled freight charge" });
|
||||
expect(request.ReferenceDetails.RelatedDocument).toBe(IRN);
|
||||
});
|
||||
|
||||
it("refuses a credit/debit note whose related invoice was never registered, before touching a counter", async () => {
|
||||
const original = invoiceRow({ id: "original-invoice", eimsIrn: null });
|
||||
const db = new FakeDb([
|
||||
invoiceRow({
|
||||
eimsDocumentType: "DEB",
|
||||
eimsReason: "Additional handling",
|
||||
relatedInvoice: original,
|
||||
} as Partial<Invoice>),
|
||||
]);
|
||||
const postSigned = jest.fn();
|
||||
|
||||
await expect(build(db, postSigned).registerInvoiceWithEims(INVOICE_ID)).rejects.toBeInstanceOf(
|
||||
BadRequestException,
|
||||
);
|
||||
expect(postSigned).not.toHaveBeenCalled();
|
||||
expect(db.state).toMatchObject({ nextInvoiceCounter: 7 }); // unchanged — never reserved
|
||||
});
|
||||
|
||||
it("refuses a credit/debit note with no related invoice set at all", async () => {
|
||||
const db = new FakeDb([
|
||||
invoiceRow({ eimsDocumentType: "CRE", eimsReason: "x", relatedInvoice: null } as Partial<Invoice>),
|
||||
]);
|
||||
const postSigned = jest.fn();
|
||||
|
||||
await expect(build(db, postSigned).registerInvoiceWithEims(INVOICE_ID)).rejects.toBeInstanceOf(
|
||||
BadRequestException,
|
||||
);
|
||||
expect(postSigned).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("takes SourceSystem from the token session, not from configuration", async () => {
|
||||
const db = new FakeDb([invoiceRow()]);
|
||||
const postSigned = jest.fn().mockResolvedValue(okResponse());
|
||||
|
||||
@@ -13,6 +13,7 @@ import type { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialE
|
||||
import { EimsConfig } from "../../config/eims.config";
|
||||
import { Invoice } from "../billing/entities/invoice.entity";
|
||||
import {
|
||||
EimsDocumentType,
|
||||
EimsInvoiceRequest,
|
||||
EimsMapperLine,
|
||||
toEimsInvoice,
|
||||
@@ -96,6 +97,27 @@ export class EimsInvoiceRegistrationService {
|
||||
const invoice = await this.loadInvoiceForMapping(invoiceId);
|
||||
if (invoice.eimsIrn) return this.toView(invoice);
|
||||
|
||||
// Debit/credit notes (confirmed by MoR support: same endpoint, Type DEB/CRE + Reason,
|
||||
// ReferenceDetails.RelatedDocument = the original's IRN) must fail here — before a counter is
|
||||
// touched — if the original was never actually registered.
|
||||
const documentType = (invoice.eimsDocumentType as EimsDocumentType | undefined) ?? "INV";
|
||||
let relatedDocument: string | null = null;
|
||||
if (documentType !== "INV") {
|
||||
if (!invoice.relatedInvoice) {
|
||||
throw new BadRequestException({
|
||||
code: "EIMS_RELATED_INVOICE_REQUIRED",
|
||||
message: `Invoice ${invoice.invoiceNumber} is a ${documentType} but has no related invoice set.`,
|
||||
});
|
||||
}
|
||||
if (!invoice.relatedInvoice.eimsIrn) {
|
||||
throw new BadRequestException({
|
||||
code: "EIMS_RELATED_INVOICE_NOT_REGISTERED",
|
||||
message: `Invoice ${invoice.invoiceNumber} is a ${documentType} against invoice ${invoice.relatedInvoice.invoiceNumber}, which was never registered with EIMS — nothing to reference.`,
|
||||
});
|
||||
}
|
||||
relatedDocument = invoice.relatedInvoice.eimsIrn;
|
||||
}
|
||||
|
||||
// Authenticate before reserving: the source system comes from the token, and the state row is
|
||||
// keyed by it. A login failure here costs nothing — no counter has been consumed yet.
|
||||
const session = await this.auth.getSessionContext();
|
||||
@@ -114,6 +136,9 @@ export class EimsInvoiceRegistrationService {
|
||||
invoiceCounter: reservation.invoiceCounter,
|
||||
previousIrn: reservation.previousIrn,
|
||||
session,
|
||||
documentType,
|
||||
reason: invoice.eimsReason,
|
||||
relatedDocument,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -639,7 +664,7 @@ export class EimsInvoiceRegistrationService {
|
||||
): Promise<Invoice & { lines: EimsMapperLine[] }> {
|
||||
const invoice = await this.dataSource.getRepository(Invoice).findOne({
|
||||
where: { id: invoiceId },
|
||||
relations: { company: true, companyProfile: true },
|
||||
relations: { company: true, companyProfile: true, relatedInvoice: true },
|
||||
});
|
||||
if (!invoice) throw new NotFoundException(`Invoice ${invoiceId} not found`);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user