mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-29 07:10:57 +00:00
chore: reporting and filtering
This commit is contained in:
@@ -30,6 +30,7 @@ import {
|
||||
InvoiceDocumentService,
|
||||
pngDataUrl,
|
||||
} from "./documents/invoice-document.service";
|
||||
import { INVOICE_SORT_COLUMNS } from "./dto/filter-invoice.dto";
|
||||
import { InvoiceLine } from "./entities/invoice-line.entity";
|
||||
import { Invoice, InvoicePayment } from "./entities/invoice.entity";
|
||||
import { InvoiceLineRepository } from "./invoice-line.repository";
|
||||
@@ -97,6 +98,31 @@ export interface RecordPaymentInput {
|
||||
}
|
||||
|
||||
/** Default invoice payment-term window, in days, used to compute `dueAt`. */
|
||||
/**
|
||||
* Every dimension the backoffice invoice list narrows by. `findAllPaginated`
|
||||
* and `collectedSummary` share it so the summary card can never total a
|
||||
* different set of invoices than the table below it shows.
|
||||
*/
|
||||
export interface InvoiceListFilters {
|
||||
companyId?: string;
|
||||
status?: Freight.InvoiceStatus;
|
||||
statuses?: Freight.InvoiceStatus[];
|
||||
sources?: string[];
|
||||
eimsStatuses?: string[];
|
||||
currency?: string;
|
||||
search?: string;
|
||||
issuedFrom?: string;
|
||||
issuedTo?: string;
|
||||
dueFrom?: string;
|
||||
dueTo?: string;
|
||||
minAmount?: number;
|
||||
maxAmount?: number;
|
||||
hasBalance?: boolean;
|
||||
overdue?: boolean;
|
||||
/** Per-user trade-direction scope, applied via the source booking. */
|
||||
tradeDirections?: string[];
|
||||
}
|
||||
|
||||
const DEFAULT_DUE_DAYS = 14;
|
||||
|
||||
/** Statuses an invoice can still be settled (paid/refunded/cancelled) from. */
|
||||
@@ -243,12 +269,7 @@ export class BillingService {
|
||||
/** Same list filters `findAllPaginated` and `collectedSummary` both narrow by. */
|
||||
private applyInvoiceFilters(
|
||||
qb: SelectQueryBuilder<Invoice>,
|
||||
filter: {
|
||||
companyId?: string;
|
||||
status?: Freight.InvoiceStatus;
|
||||
search?: string;
|
||||
tradeDirections?: string[];
|
||||
},
|
||||
filter: InvoiceListFilters,
|
||||
) {
|
||||
if (filter.companyId) {
|
||||
qb.andWhere("invoice.companyId = :companyId", {
|
||||
@@ -258,6 +279,57 @@ export class BillingService {
|
||||
if (filter.status) {
|
||||
qb.andWhere("invoice.status = :status", { status: filter.status });
|
||||
}
|
||||
if (filter.statuses?.length) {
|
||||
qb.andWhere("invoice.status IN (:...statuses)", {
|
||||
statuses: filter.statuses,
|
||||
});
|
||||
}
|
||||
if (filter.sources?.length) {
|
||||
qb.andWhere("invoice.source IN (:...sources)", { sources: filter.sources });
|
||||
}
|
||||
if (filter.eimsStatuses?.length) {
|
||||
qb.andWhere("invoice.eimsStatus IN (:...eimsStatuses)", {
|
||||
eimsStatuses: filter.eimsStatuses,
|
||||
});
|
||||
}
|
||||
if (filter.currency) {
|
||||
// Stored casing has drifted ("usd" rows exist) — compare normalised.
|
||||
qb.andWhere("UPPER(invoice.currency) = :currency", {
|
||||
currency: filter.currency.toUpperCase(),
|
||||
});
|
||||
}
|
||||
if (filter.issuedFrom) {
|
||||
qb.andWhere("invoice.issuedAt >= :issuedFrom", {
|
||||
issuedFrom: filter.issuedFrom,
|
||||
});
|
||||
}
|
||||
if (filter.issuedTo) {
|
||||
qb.andWhere("invoice.issuedAt <= :issuedTo", { issuedTo: filter.issuedTo });
|
||||
}
|
||||
if (filter.dueFrom) {
|
||||
qb.andWhere("invoice.dueAt >= :dueFrom", { dueFrom: filter.dueFrom });
|
||||
}
|
||||
if (filter.dueTo) {
|
||||
qb.andWhere("invoice.dueAt <= :dueTo", { dueTo: filter.dueTo });
|
||||
}
|
||||
if (filter.minAmount !== undefined) {
|
||||
qb.andWhere("invoice.totalAmount >= :minAmount", {
|
||||
minAmount: filter.minAmount,
|
||||
});
|
||||
}
|
||||
if (filter.maxAmount !== undefined) {
|
||||
qb.andWhere("invoice.totalAmount <= :maxAmount", {
|
||||
maxAmount: filter.maxAmount,
|
||||
});
|
||||
}
|
||||
if (filter.hasBalance) {
|
||||
qb.andWhere("invoice.balanceAmount > 0");
|
||||
}
|
||||
if (filter.overdue) {
|
||||
// Computed, not `status = OVERDUE`: nothing sweeps PENDING rows into
|
||||
// that status, so reading the column alone under-reports the arrears.
|
||||
qb.andWhere("invoice.balanceAmount > 0 AND invoice.dueAt < now()");
|
||||
}
|
||||
if (filter.search) {
|
||||
// Searches what the row actually shows: its number, who it bills, and
|
||||
// the source record behind it (booking reference, GRN, shipping line).
|
||||
@@ -299,14 +371,11 @@ export class BillingService {
|
||||
}
|
||||
|
||||
async findAllPaginated(
|
||||
filter: {
|
||||
companyId?: string;
|
||||
status?: Freight.InvoiceStatus;
|
||||
search?: string;
|
||||
filter: InvoiceListFilters & {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
/** Per-user trade-direction scope, applied via the source booking. */
|
||||
tradeDirections?: string[];
|
||||
sortBy?: string;
|
||||
sortOrder?: "ASC" | "DESC";
|
||||
} = {},
|
||||
): Promise<{ items: InvoiceListRow[]; total: number }> {
|
||||
const page = filter.page && filter.page > 0 ? filter.page : 1;
|
||||
@@ -317,7 +386,14 @@ export class BillingService {
|
||||
.getRepository(Invoice)
|
||||
.createQueryBuilder("invoice")
|
||||
.leftJoinAndSelect("invoice.company", "company")
|
||||
.orderBy("invoice.issuedAt", "DESC")
|
||||
// sortBy is whitelisted through INVOICE_SORT_COLUMNS, never interpolated
|
||||
// raw. The id tiebreaker keeps paging stable when the sort column ties
|
||||
// (issuedAt is null on every DRAFT row).
|
||||
.orderBy(
|
||||
INVOICE_SORT_COLUMNS[filter.sortBy ?? ""] ?? "invoice.issuedAt",
|
||||
filter.sortOrder ?? "DESC",
|
||||
)
|
||||
.addOrderBy("invoice.id", "ASC")
|
||||
.skip((page - 1) * pageSize)
|
||||
.take(pageSize);
|
||||
|
||||
@@ -458,12 +534,7 @@ export class BillingService {
|
||||
* visible page.
|
||||
*/
|
||||
async collectedSummary(
|
||||
filter: {
|
||||
companyId?: string;
|
||||
status?: Freight.InvoiceStatus;
|
||||
search?: string;
|
||||
tradeDirections?: string[];
|
||||
} = {},
|
||||
filter: InvoiceListFilters = {},
|
||||
): Promise<Record<string, number>> {
|
||||
const qb = this.dataSource
|
||||
.getRepository(Invoice)
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { plainToInstance } from "class-transformer";
|
||||
import { validateSync } from "class-validator";
|
||||
|
||||
import { FilterInvoiceDto } from "./filter-invoice.dto";
|
||||
|
||||
/**
|
||||
* The list endpoint runs under `forbidNonWhitelisted`, so every param the
|
||||
* backoffice filter bar sends has to survive transform + validation here or
|
||||
* the whole request 400s. The CSV filters are the fragile part: they arrive as
|
||||
* one string and must come out as a validated array.
|
||||
*/
|
||||
const parse = (query: Record<string, string>) => {
|
||||
const dto = plainToInstance(FilterInvoiceDto, query);
|
||||
return { dto, errors: validateSync(dto).map((e) => e.property) };
|
||||
};
|
||||
|
||||
describe("FilterInvoiceDto", () => {
|
||||
it("accepts the full filter-bar query and splits the CSV filters", () => {
|
||||
const { dto, errors } = parse({
|
||||
page: "2",
|
||||
pageSize: "10",
|
||||
search: "INV-2026",
|
||||
statuses: "PENDING,OVERDUE",
|
||||
sources: "booking,warehouse",
|
||||
eimsStatuses: "NOT_SUBMITTED",
|
||||
currency: "etb",
|
||||
issuedFrom: "2026-08-01T00:00:00.000Z",
|
||||
issuedTo: "2026-08-20T20:59:59.999Z",
|
||||
dueFrom: "2026-08-01T00:00:00.000Z",
|
||||
dueTo: "2026-09-01T20:59:59.999Z",
|
||||
minAmount: "100",
|
||||
maxAmount: "5000",
|
||||
hasBalance: "true",
|
||||
overdue: "false",
|
||||
sortBy: "balanceAmount",
|
||||
sortOrder: "asc",
|
||||
});
|
||||
|
||||
expect(errors).toEqual([]);
|
||||
expect(dto.statuses).toEqual(["PENDING", "OVERDUE"]);
|
||||
expect(dto.sources).toEqual(["booking", "warehouse"]);
|
||||
expect(dto.currency).toBe("ETB");
|
||||
expect(dto.minAmount).toBe(100);
|
||||
expect(dto.hasBalance).toBe(true);
|
||||
expect(dto.overdue).toBe(false);
|
||||
expect(dto.sortOrder).toBe("ASC");
|
||||
});
|
||||
|
||||
it("rejects a value outside the enum and an unsortable column", () => {
|
||||
expect(parse({ statuses: "PENDING,NOT_A_STATUS" }).errors).toEqual(["statuses"]);
|
||||
expect(parse({ sortBy: "eimsIrn" }).errors).toEqual(["sortBy"]);
|
||||
});
|
||||
});
|
||||
@@ -2,14 +2,43 @@ import { Freight } from "@edr/types";
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { Transform } from "class-transformer";
|
||||
import {
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsDateString,
|
||||
IsIn,
|
||||
IsInt,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
Min,
|
||||
} from "class-validator";
|
||||
|
||||
import { EimsInvoiceStatus } from "../../eims/eims-registration.types";
|
||||
|
||||
/** Columns the invoice list may be ordered by -> their query-builder expression. */
|
||||
export const INVOICE_SORT_COLUMNS: Record<string, string> = {
|
||||
issuedAt: "invoice.issuedAt",
|
||||
dueAt: "invoice.dueAt",
|
||||
createdAt: "invoice.createdAt",
|
||||
totalAmount: "invoice.totalAmount",
|
||||
balanceAmount: "invoice.balanceAmount",
|
||||
invoiceNumber: "invoice.invoiceNumber",
|
||||
};
|
||||
|
||||
/** `?statuses=A,B` -> `["A","B"]`. A bare value stays a one-element list. */
|
||||
const csv = ({ value }: { value: unknown }) =>
|
||||
typeof value === "string"
|
||||
? value
|
||||
.split(",")
|
||||
.map((v) => v.trim())
|
||||
.filter(Boolean)
|
||||
: value;
|
||||
|
||||
const bool = ({ value }: { value: unknown }) => value === "true" || value === true;
|
||||
|
||||
const num = ({ value }: { value: unknown }) => Number(value);
|
||||
|
||||
export class FilterInvoiceDto {
|
||||
@ApiPropertyOptional({ default: 1 })
|
||||
@IsOptional()
|
||||
@@ -40,10 +69,97 @@ export class FilterInvoiceDto {
|
||||
@IsIn(Object.values(Freight.InvoiceStatus))
|
||||
status?: Freight.InvoiceStatus;
|
||||
|
||||
/** Manual-payments worklist only: restrict to one currency. */
|
||||
/**
|
||||
* Multi-select status (`?statuses=PENDING,OVERDUE`). ANDed with `status`
|
||||
* when both are sent, so the single-status worklists keep their meaning.
|
||||
*/
|
||||
@ApiPropertyOptional({ isArray: true, enum: Freight.InvoiceStatus })
|
||||
@IsOptional()
|
||||
@Transform(csv)
|
||||
@IsArray()
|
||||
@IsIn(Object.values(Freight.InvoiceStatus), { each: true })
|
||||
statuses?: Freight.InvoiceStatus[];
|
||||
|
||||
/** Originating subsystem (`booking`, `warehouse`, `shipping_line_credit`, …). */
|
||||
@ApiPropertyOptional({ isArray: true, enum: Freight.InvoiceSource })
|
||||
@IsOptional()
|
||||
@Transform(csv)
|
||||
@IsArray()
|
||||
@IsIn(Object.values(Freight.InvoiceSource), { each: true })
|
||||
sources?: Freight.InvoiceSource[];
|
||||
|
||||
/** MoR filing state — Finance's "what still needs registering" cut. */
|
||||
@ApiPropertyOptional({ isArray: true, enum: EimsInvoiceStatus })
|
||||
@IsOptional()
|
||||
@Transform(csv)
|
||||
@IsArray()
|
||||
@IsIn(Object.values(EimsInvoiceStatus), { each: true })
|
||||
eimsStatuses?: EimsInvoiceStatus[];
|
||||
|
||||
/** Manual-payments worklist and the invoice list: restrict to one currency. */
|
||||
@ApiPropertyOptional({ enum: ["USD", "ETB"] })
|
||||
@IsOptional()
|
||||
@Transform(({ value }: { value: unknown }) => String(value).toUpperCase())
|
||||
@IsIn(["USD", "ETB"])
|
||||
currency?: "USD" | "ETB";
|
||||
|
||||
@ApiPropertyOptional({ description: "Issued at or after this instant (ISO)." })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
issuedFrom?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Issued at or before this instant (ISO)." })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
issuedTo?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Due at or after this instant (ISO)." })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
dueFrom?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Due at or before this instant (ISO)." })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
dueTo?: string;
|
||||
|
||||
/** Total amount bounds, in the invoice's own currency — pair with `currency`. */
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@Transform(num)
|
||||
@IsNumber()
|
||||
minAmount?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@Transform(num)
|
||||
@IsNumber()
|
||||
maxAmount?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: "Only invoices with an outstanding balance." })
|
||||
@IsOptional()
|
||||
@Transform(bool)
|
||||
@IsBoolean()
|
||||
hasBalance?: boolean;
|
||||
|
||||
/**
|
||||
* Outstanding AND past its due date, computed rather than read off `status`:
|
||||
* nothing sweeps PENDING rows into OVERDUE, so the status alone under-reports.
|
||||
*/
|
||||
@ApiPropertyOptional({ description: "Only invoices outstanding past their due date." })
|
||||
@IsOptional()
|
||||
@Transform(bool)
|
||||
@IsBoolean()
|
||||
overdue?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ enum: Object.keys(INVOICE_SORT_COLUMNS), default: "issuedAt" })
|
||||
@IsOptional()
|
||||
@IsIn(Object.keys(INVOICE_SORT_COLUMNS))
|
||||
sortBy?: string;
|
||||
|
||||
@ApiPropertyOptional({ enum: ["ASC", "DESC"], default: "DESC" })
|
||||
@IsOptional()
|
||||
@Transform(({ value }: { value: unknown }) => String(value).toUpperCase())
|
||||
@IsIn(["ASC", "DESC"])
|
||||
sortOrder?: "ASC" | "DESC";
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user