mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-28 19:30:57 +00:00
changes
This commit is contained in:
@@ -125,6 +125,22 @@ export class ListRatesQueryDto extends PaginationQueryDto {
|
||||
@IsString()
|
||||
@MaxLength(50)
|
||||
rateType?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Filter by rate category — comma-separated appliesTo values (e.g. "CONTAINER" or "FIRST_MILE,LAST_MILE").',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
appliesTo?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Filter by surcharge trigger — comma-separated trigger values (e.g. "CUSTOMS_CLEARANCE" or "HAZARDOUS,REEFER").',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
trigger?: string;
|
||||
}
|
||||
|
||||
export class ListWeightLimitRulesQueryDto extends PaginationQueryDto {
|
||||
|
||||
@@ -117,6 +117,21 @@ export class RatesRepository implements IRatesRepository {
|
||||
if (query.rateType) {
|
||||
qb.andWhere('rate.rateType = :rateType', { rateType: query.rateType });
|
||||
}
|
||||
// Category tabs on the admin page: comma-separated appliesTo / trigger
|
||||
// lists, ANDed together (e.g. appliesTo=OTHER + trigger=CUSTOMS_CLEARANCE).
|
||||
const csv = (v?: string) =>
|
||||
(v ?? '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const appliesTo = csv(query.appliesTo);
|
||||
if (appliesTo.length > 0) {
|
||||
qb.andWhere('rate.appliesTo IN (:...appliesTo)', { appliesTo });
|
||||
}
|
||||
const triggers = csv(query.trigger);
|
||||
if (triggers.length > 0) {
|
||||
qb.andWhere('rate.trigger IN (:...triggers)', { triggers });
|
||||
}
|
||||
if (query.search) {
|
||||
qb.andWhere(
|
||||
'(rate.rateType ILIKE :search OR rate.status ILIKE :search OR rate.rateUnit ILIKE :search OR rate.currency ILIKE :search)',
|
||||
|
||||
@@ -76,3 +76,191 @@ describe('RuleEngineService — requested service without a configured surcharge
|
||||
expect(result.hardBlocked[0]).toContain('reefer');
|
||||
});
|
||||
});
|
||||
|
||||
describe('RuleEngineService — overweight surcharge by trade direction', () => {
|
||||
const baseImportRate: Rate = {
|
||||
id: 'rate-import-20',
|
||||
rateType: 'CONTAINER_IMPORT',
|
||||
trigger: 'ALWAYS',
|
||||
rateValue: 1000,
|
||||
rateUnit: 'PER_CONTAINER',
|
||||
currency: 'USD',
|
||||
status: 'LIVE',
|
||||
containerTypeId: 'ct-20',
|
||||
cargoTypeId: null,
|
||||
originYardId: 'yard-dj',
|
||||
destinationYardId: 'yard-adama',
|
||||
} as Rate;
|
||||
|
||||
const configuredOverweight: Rate = {
|
||||
id: 'rate-ow',
|
||||
rateType: 'OVERWEIGHT_PER_TON',
|
||||
trigger: 'OVERWEIGHT',
|
||||
rateValue: 10,
|
||||
rateUnit: 'PER_TON',
|
||||
currency: 'USD',
|
||||
status: 'LIVE',
|
||||
containerTypeId: null,
|
||||
cargoTypeId: null,
|
||||
} as Rate;
|
||||
|
||||
let service: RuleEngineService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new RuleEngineService(
|
||||
{ findById: jest.fn().mockResolvedValue(null) } as never,
|
||||
{ findById: jest.fn().mockResolvedValue(null) } as never,
|
||||
{
|
||||
findActiveByContainerTypeId: jest
|
||||
.fn()
|
||||
.mockResolvedValue([{ id: 'wlr-20', maxVgmTons: 20, maxCapacityTons: null }]),
|
||||
} as never,
|
||||
{ findAllActive: jest.fn().mockResolvedValue([]) } as never,
|
||||
{
|
||||
findLiveRates: jest.fn().mockResolvedValue([baseImportRate, configuredOverweight]),
|
||||
} as never,
|
||||
{ findById: jest.fn().mockResolvedValue(null) } as never,
|
||||
{} as never,
|
||||
);
|
||||
});
|
||||
|
||||
// One 20ft at 25 t against a 20 t limit → 5 t excess.
|
||||
const overweightInput = (tradeDirection: string): BookingEvaluationInput => ({
|
||||
serviceTypeId: 'svc-1',
|
||||
paymentCurrency: 'USD',
|
||||
tradeDirection,
|
||||
isHazardous: false,
|
||||
totalWagons: 1,
|
||||
originYardId: 'yard-dj',
|
||||
destinationYardId: 'yard-adama',
|
||||
containers: [
|
||||
{ containerTypeId: 'ct-20', quantity: 1, vgmPerUnitTons: 25, totalVgmTons: 25 },
|
||||
],
|
||||
});
|
||||
|
||||
it('IMPORT derives the per-ton price from base freight ÷ (2 × limit), not the configured rate', async () => {
|
||||
const result = await service.evaluate(overweightInput('IMPORT'));
|
||||
const ow = result.appliedModifiers.filter((m) => m.surchargeCode === 'OVERWEIGHT_PER_TON');
|
||||
expect(ow).toHaveLength(1);
|
||||
// 1000 / (2 × 20) = 25 USD/t on 5 excess tons.
|
||||
expect(ow[0].unitPriceUsd).toBe(25);
|
||||
expect(ow[0].calculatedAmount).toBe(125);
|
||||
expect(ow[0].triggerValue).toBe(5);
|
||||
expect(ow[0].rateId).toBe(baseImportRate.id);
|
||||
});
|
||||
|
||||
it('EXPORT keeps billing the configured OVERWEIGHT rate', async () => {
|
||||
const result = await service.evaluate(overweightInput('EXPORT'));
|
||||
const ow = result.appliedModifiers.filter((m) => m.surchargeCode === 'OVERWEIGHT_PER_TON');
|
||||
expect(ow).toHaveLength(1);
|
||||
expect(ow[0].rateId).toBe(configuredOverweight.id);
|
||||
// 5 excess tons × the configured 10 USD/t.
|
||||
expect(ow[0].calculatedAmount).toBe(50);
|
||||
expect(ow[0].unitPriceUsd).toBeUndefined();
|
||||
});
|
||||
|
||||
it('IMPORT without a route-matching base rate bills no overweight (base freight blocks anyway)', async () => {
|
||||
const result = await service.evaluate({
|
||||
...overweightInput('IMPORT'),
|
||||
destinationYardId: 'yard-elsewhere',
|
||||
});
|
||||
const ow = result.appliedModifiers.filter((m) => m.surchargeCode === 'OVERWEIGHT_PER_TON');
|
||||
expect(ow).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('RuleEngineService — empty-container return per route + container type', () => {
|
||||
const returnRate20: Rate = {
|
||||
id: 'rate-return-20',
|
||||
rateType: 'RETURN_SURCHARGE',
|
||||
trigger: 'WITH_RETURN',
|
||||
rateValue: 20,
|
||||
rateUnit: 'PER_CONTAINER',
|
||||
currency: 'USD',
|
||||
status: 'LIVE',
|
||||
containerTypeId: 'ct-20',
|
||||
cargoTypeId: null,
|
||||
tradeDirection: 'IMPORT',
|
||||
originYardId: 'yard-dj',
|
||||
destinationYardId: 'yard-adama',
|
||||
} as Rate;
|
||||
|
||||
let service: RuleEngineService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new RuleEngineService(
|
||||
{ findById: jest.fn().mockResolvedValue(null) } as never,
|
||||
{ findById: jest.fn().mockResolvedValue(null) } as never,
|
||||
{
|
||||
findActiveByContainerTypeId: jest
|
||||
.fn()
|
||||
.mockResolvedValue([{ id: 'wlr-20', maxVgmTons: 20, maxCapacityTons: null }]),
|
||||
} as never,
|
||||
{ findAllActive: jest.fn().mockResolvedValue([]) } as never,
|
||||
{ findLiveRates: jest.fn().mockResolvedValue([returnRate20]) } as never,
|
||||
{ findById: jest.fn().mockResolvedValue(null) } as never,
|
||||
{} as never,
|
||||
);
|
||||
});
|
||||
|
||||
const returnInput = (overrides: Partial<BookingEvaluationInput>): BookingEvaluationInput => ({
|
||||
serviceTypeId: 'svc-1',
|
||||
paymentCurrency: 'USD',
|
||||
tradeDirection: 'IMPORT',
|
||||
isHazardous: false,
|
||||
totalWagons: 1,
|
||||
originYardId: 'yard-dj',
|
||||
destinationYardId: 'yard-adama',
|
||||
containers: [
|
||||
{
|
||||
containerTypeId: 'ct-20',
|
||||
quantity: 4,
|
||||
vgmPerUnitTons: 10,
|
||||
totalVgmTons: 40,
|
||||
returnQuantity: 2,
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it('bills the route + type matched rate on the opted-in count', async () => {
|
||||
const result = await service.evaluate(returnInput({}));
|
||||
const ret = result.appliedModifiers.filter((m) => m.surchargeCode === 'RETURN_SURCHARGE');
|
||||
expect(result.hardBlocked).toHaveLength(0);
|
||||
expect(ret).toHaveLength(1);
|
||||
expect(ret[0].rateId).toBe(returnRate20.id);
|
||||
expect(ret[0].triggerValue).toBe(2);
|
||||
expect(ret[0].calculatedAmount).toBe(40);
|
||||
expect(ret[0].billingUnit).toBe('PER_CONTAINER');
|
||||
});
|
||||
|
||||
it('hard-blocks when the booking route has no matching return rate', async () => {
|
||||
const result = await service.evaluate(
|
||||
returnInput({ destinationYardId: 'yard-elsewhere' }),
|
||||
);
|
||||
expect(result.hardBlocked.some((m) => m.includes('return'))).toBe(true);
|
||||
expect(
|
||||
result.appliedModifiers.filter((m) => m.surchargeCode === 'RETURN_SURCHARGE'),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('hard-blocks an EXPORT booking asking for return (rates are import-only)', async () => {
|
||||
const result = await service.evaluate(returnInput({ tradeDirection: 'EXPORT' }));
|
||||
expect(result.hardBlocked.some((m) => m.includes('return'))).toBe(true);
|
||||
});
|
||||
|
||||
it('legacy booking-level flag bills every container at its type rate', async () => {
|
||||
const result = await service.evaluate(
|
||||
returnInput({
|
||||
withReturn: true,
|
||||
containers: [
|
||||
{ containerTypeId: 'ct-20', quantity: 4, vgmPerUnitTons: 10, totalVgmTons: 40 },
|
||||
],
|
||||
}),
|
||||
);
|
||||
const ret = result.appliedModifiers.filter((m) => m.surchargeCode === 'RETURN_SURCHARGE');
|
||||
expect(ret).toHaveLength(1);
|
||||
expect(ret[0].triggerValue).toBe(4);
|
||||
expect(ret[0].calculatedAmount).toBe(80);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -67,6 +67,12 @@ export interface BookingEvaluationInput {
|
||||
isGovernment?: boolean;
|
||||
allowConsolidation?: boolean;
|
||||
shippingLineId?: string | null;
|
||||
/**
|
||||
* The booking's rail leg. Import overweight derives its per-ton price from
|
||||
* this route's own container freight rate, so the engine needs the yards.
|
||||
*/
|
||||
originYardId?: string | null;
|
||||
destinationYardId?: string | null;
|
||||
/**
|
||||
* Booking's cargo type needs EDR-provided lashing/securing (cargoType
|
||||
* hasLashing = true). Fires the flat LASHING surcharge. Resolved by the
|
||||
@@ -91,6 +97,15 @@ export interface AppliedCargoModifier {
|
||||
triggerValue: number | null;
|
||||
calculatedAmount: number;
|
||||
currency: string;
|
||||
/**
|
||||
* Effective per-unit USD price when it differs from the rate row's own value
|
||||
* — set by derived charges (import overweight: base freight ÷ 2×limit) so
|
||||
* the breakdown shows the real per-ton figure, not the base container price.
|
||||
* Any modifier carrying it also bypasses frozen contract snapshots.
|
||||
*/
|
||||
unitPriceUsd?: number | null;
|
||||
/** Display unit for a unitPriceUsd modifier (e.g. PER_TON for overweight). */
|
||||
billingUnit?: string;
|
||||
}
|
||||
|
||||
export interface ContainerWeightResult {
|
||||
@@ -165,12 +180,16 @@ export class RuleEngineService {
|
||||
...(await this.capacityViolations(input.containers, input.tradeDirection)),
|
||||
);
|
||||
|
||||
// Per-container-line weight limit (maxVgmTons), index-aligned with
|
||||
// containerWeightResults — the derived import overweight divides by it.
|
||||
const lineMaxVgmTons: Array<number | null> = [];
|
||||
for (const container of input.containers) {
|
||||
const rules = await this.weightLimitRulesRepo.findActiveByContainerTypeId(
|
||||
container.containerTypeId,
|
||||
input.tradeDirection,
|
||||
);
|
||||
const rule = rules[0];
|
||||
lineMaxVgmTons.push(rule ? Number(rule.maxVgmTons) : null);
|
||||
let isOverweight = container.isOverweight ?? false;
|
||||
let excess = container.overweightExcessTons ?? null;
|
||||
|
||||
@@ -273,13 +292,6 @@ export class RuleEngineService {
|
||||
input.containers.some((c) => Number(c.reeferQuantity ?? 0) > 0),
|
||||
label: 'refrigerated (reefer) cargo',
|
||||
},
|
||||
{
|
||||
trigger: 'WITH_RETURN',
|
||||
wanted:
|
||||
truthy(input.withReturn) ||
|
||||
input.containers.some((c) => Number(c.returnQuantity ?? 0) > 0),
|
||||
label: 'empty-container return',
|
||||
},
|
||||
];
|
||||
for (const svc of requestedServices) {
|
||||
if (svc.wanted && !surchargeRates.some((r) => r.trigger === svc.trigger)) {
|
||||
@@ -292,6 +304,14 @@ export class RuleEngineService {
|
||||
}
|
||||
|
||||
for (const rate of surchargeRates) {
|
||||
// Import overweight never bills the configured rate — its per-ton price
|
||||
// derives from the route's base container freight (see below).
|
||||
if (rate.trigger === 'OVERWEIGHT' && input.tradeDirection === 'IMPORT') {
|
||||
continue;
|
||||
}
|
||||
// Empty-container return is sold per route + container type — billed by
|
||||
// the route-matched block below, never by this route-agnostic loop.
|
||||
if (rate.trigger === 'WITH_RETURN') continue;
|
||||
const triggered = this.matchesTrigger(rate.trigger, {
|
||||
isHazardous: input.isHazardous,
|
||||
hasReefer,
|
||||
@@ -384,6 +404,21 @@ export class RuleEngineService {
|
||||
});
|
||||
}
|
||||
|
||||
if (input.tradeDirection === 'IMPORT') {
|
||||
appliedModifiers.push(
|
||||
...this.derivedImportOverweight(
|
||||
input,
|
||||
containerWeightResults,
|
||||
lineMaxVgmTons,
|
||||
liveRates,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const withReturn = this.withReturnCharges(input, liveRates);
|
||||
appliedModifiers.push(...withReturn.modifiers);
|
||||
hardBlocked.push(...withReturn.blocked);
|
||||
|
||||
return {
|
||||
priorityScore,
|
||||
appliedModifiers,
|
||||
@@ -394,6 +429,132 @@ export class RuleEngineService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Import overweight — derived, never configured. Each overweight container
|
||||
* line bills its excess tons at (its own base import freight on the booking's
|
||||
* route) ÷ (2 × its weight limit): 20ft at 1000 USD with a 20 t limit →
|
||||
* 25 USD per excess ton. Export keeps the configured OVERWEIGHT rate.
|
||||
* Note: derives from the LIVE route rate even for frozen-rate contract
|
||||
* bookings — the frozen snapshot has no route-scoped container price to
|
||||
* divide.
|
||||
*/
|
||||
private derivedImportOverweight(
|
||||
input: BookingEvaluationInput,
|
||||
weightResults: ContainerWeightResult[],
|
||||
lineMaxVgmTons: Array<number | null>,
|
||||
liveRates: Rate[],
|
||||
): AppliedCargoModifier[] {
|
||||
const modifiers: AppliedCargoModifier[] = [];
|
||||
if (!input.originYardId || !input.destinationYardId) return modifiers;
|
||||
|
||||
for (let i = 0; i < weightResults.length; i++) {
|
||||
const wr = weightResults[i];
|
||||
const excess = Number(wr?.overweightExcessTons ?? 0);
|
||||
const maxVgm = Number(lineMaxVgmTons[i] ?? 0);
|
||||
if (!wr?.isOverweight || !(excess > 0) || !(maxVgm > 0)) continue;
|
||||
|
||||
// Same precedence as base freight pricing: the rate scoped to this
|
||||
// container type wins over the route's catch-all rate.
|
||||
const onLeg = liveRates.filter(
|
||||
(r) =>
|
||||
r.rateType === 'CONTAINER_IMPORT' &&
|
||||
r.currency === 'USD' &&
|
||||
r.originYardId === input.originYardId &&
|
||||
r.destinationYardId === input.destinationYardId,
|
||||
);
|
||||
const base =
|
||||
onLeg.find((r) => r.containerTypeId === wr.containerTypeId) ??
|
||||
onLeg.find((r) => !r.containerTypeId);
|
||||
// No base rate → the base-freight line hard-blocks this booking anyway.
|
||||
if (!base) continue;
|
||||
|
||||
const perTon = Number(base.rateValue) / (2 * maxVgm);
|
||||
const amount = excess * perTon;
|
||||
if (!(amount > 0)) continue;
|
||||
|
||||
modifiers.push({
|
||||
rateId: base.id,
|
||||
surchargeCode: 'OVERWEIGHT_PER_TON',
|
||||
triggerValue: excess,
|
||||
calculatedAmount: amount,
|
||||
currency: base.currency,
|
||||
unitPriceUsd: perTon,
|
||||
billingUnit: 'PER_TON',
|
||||
});
|
||||
}
|
||||
return modifiers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Empty-container return — sold per direction + route + container type, like
|
||||
* base freight. Each container line that opted in (returnQuantity, or every
|
||||
* container when only the legacy booking-level flag is set) bills the
|
||||
* route-matched WITH_RETURN rate for its own container type; a line with no
|
||||
* matching rate hard-blocks the booking instead of shipping the service for
|
||||
* free. Rates are import-only for now, so an export booking that asks for
|
||||
* return blocks too.
|
||||
* ponytail: bills the LIVE route rate, not a frozen contract snapshot — one
|
||||
* RETURN_SURCHARGE snapshot code can't hold per-size route prices.
|
||||
*/
|
||||
private withReturnCharges(
|
||||
input: BookingEvaluationInput,
|
||||
liveRates: Rate[],
|
||||
): { modifiers: AppliedCargoModifier[]; blocked: string[] } {
|
||||
const modifiers: AppliedCargoModifier[] = [];
|
||||
const blocked: string[] = [];
|
||||
const bookingLevel = truthy(input.withReturn);
|
||||
const wanted =
|
||||
bookingLevel || input.containers.some((c) => Number(c.returnQuantity ?? 0) > 0);
|
||||
if (!wanted) return { modifiers, blocked };
|
||||
|
||||
const onLeg = liveRates.filter(
|
||||
(r) =>
|
||||
r.trigger === 'WITH_RETURN' &&
|
||||
r.currency === 'USD' &&
|
||||
r.tradeDirection === input.tradeDirection &&
|
||||
r.originYardId === input.originYardId &&
|
||||
r.destinationYardId === input.destinationYardId,
|
||||
);
|
||||
|
||||
for (const container of input.containers) {
|
||||
const qty =
|
||||
Number(container.returnQuantity ?? 0) > 0
|
||||
? Number(container.returnQuantity)
|
||||
: bookingLevel
|
||||
? Number(container.quantity || 0)
|
||||
: 0;
|
||||
if (!(qty > 0)) continue;
|
||||
|
||||
const rate =
|
||||
onLeg.find((r) => r.containerTypeId === container.containerTypeId) ??
|
||||
onLeg.find((r) => !r.containerTypeId);
|
||||
if (!rate) {
|
||||
blocked.push(
|
||||
'No empty-container return rate is configured for this container ' +
|
||||
'type on this route (return is import-only) — remove the return ' +
|
||||
'option or ask EDR to configure its rate for this origin → destination.',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const rateValue = Number(rate.rateValue);
|
||||
const amount = rate.rateUnit === 'FLAT' ? rateValue : qty * rateValue;
|
||||
if (!(amount > 0)) continue;
|
||||
modifiers.push({
|
||||
rateId: rate.id,
|
||||
surchargeCode: this.surchargeCode(rate),
|
||||
triggerValue: qty,
|
||||
calculatedAmount: amount,
|
||||
currency: rate.currency,
|
||||
unitPriceUsd: rateValue,
|
||||
billingUnit: rate.rateUnit,
|
||||
});
|
||||
}
|
||||
|
||||
// Same block deduplicated — several lines missing the rate is one problem.
|
||||
return { modifiers, blocked: [...new Set(blocked)] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Messages for container lines whose total weight exceeds the hard capacity
|
||||
* ceiling (weight_limit_rules.max_capacity_tons). Non-empty ⇒ the booking
|
||||
|
||||
@@ -93,6 +93,19 @@ export class RatesService {
|
||||
return trigger === 'ALWAYS' && BASE_FREIGHT_CATEGORIES.includes(appliesTo);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rates sold per direction + route. Base freight always; customs clearance
|
||||
* and empty-container return are the surcharges that are too — their fee
|
||||
* depends on the lane (and, for returns, the container type).
|
||||
*/
|
||||
private isRouteScoped(appliesTo: Rate['appliesTo'], trigger: Rate['trigger']): boolean {
|
||||
return (
|
||||
this.isBaseFreight(appliesTo, trigger) ||
|
||||
trigger === 'CUSTOMS_CLEARANCE' ||
|
||||
trigger === 'WITH_RETURN'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Which country each end of the leg must sit in, given what the rate is for.
|
||||
* The railway only sells three shapes: import lands at the Djibouti ports and
|
||||
@@ -126,7 +139,7 @@ export class RatesService {
|
||||
destinationYardId?: string | null;
|
||||
}): Promise<YardScope> {
|
||||
const { appliesTo, trigger, tradeDirection } = input;
|
||||
if (!this.isBaseFreight(appliesTo, trigger)) {
|
||||
if (!this.isRouteScoped(appliesTo, trigger)) {
|
||||
return { originYardId: null, destinationYardId: null };
|
||||
}
|
||||
|
||||
@@ -134,7 +147,7 @@ export class RatesService {
|
||||
const destinationYardId = input.destinationYardId ?? null;
|
||||
if (!originYardId || !destinationYardId) {
|
||||
throw new BadRequestException(
|
||||
'Base freight rates are priced per leg — pick both an origin and a destination yard.',
|
||||
'This rate is priced per leg — pick both an origin and a destination yard.',
|
||||
);
|
||||
}
|
||||
if (originYardId === destinationYardId) {
|
||||
@@ -179,6 +192,25 @@ export class RatesService {
|
||||
}): void {
|
||||
const { appliesTo, trigger, tradeDirection, intercityKind } = input;
|
||||
const { containerTypeId, cargoTypeId } = input;
|
||||
if (trigger === 'CUSTOMS_CLEARANCE') {
|
||||
if (tradeDirection !== 'IMPORT' && tradeDirection !== 'EXPORT') {
|
||||
throw new BadRequestException(
|
||||
'A customs clearance rate must say whether it covers IMPORT or EXPORT.',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (trigger === 'WITH_RETURN') {
|
||||
// Returning the empty box only exists on imports (the box goes back to
|
||||
// the port) — export return rates are rejected until the business sells
|
||||
// that.
|
||||
if (tradeDirection !== 'IMPORT') {
|
||||
throw new BadRequestException(
|
||||
'An empty container return rate is import-only for now.',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!this.isBaseFreight(appliesTo, trigger)) return;
|
||||
|
||||
if (appliesTo === 'INTERCITY') {
|
||||
@@ -247,13 +279,24 @@ export class RatesService {
|
||||
const trigger = dto.trigger as Rate['trigger'];
|
||||
// Surcharges (trigger ≠ ALWAYS) carry no direction/scope — clear them so
|
||||
// the engine never accidentally narrows a surcharge by container/direction.
|
||||
// Exceptions: customs clearance keeps a direction, and empty-container
|
||||
// return keeps direction + container type — both are sold per lane.
|
||||
const isSurcharge = trigger !== 'ALWAYS';
|
||||
const containerTypeId = isSurcharge ? null : (dto.containerTypeId ?? null);
|
||||
const containerTypeId =
|
||||
trigger === 'WITH_RETURN'
|
||||
? (dto.containerTypeId ?? null)
|
||||
: isSurcharge
|
||||
? null
|
||||
: (dto.containerTypeId ?? null);
|
||||
const cargoTypeId = isSurcharge ? null : (dto.cargoTypeId ?? null);
|
||||
// Intercity never leaves Ethiopia, so it has no trade direction to store —
|
||||
// its yard pair already says where it runs.
|
||||
const tradeDirection =
|
||||
isSurcharge || appliesTo === 'INTERCITY' ? null : (dto.tradeDirection ?? null);
|
||||
trigger === 'CUSTOMS_CLEARANCE' || trigger === 'WITH_RETURN'
|
||||
? (dto.tradeDirection ?? null)
|
||||
: isSurcharge || appliesTo === 'INTERCITY'
|
||||
? null
|
||||
: (dto.tradeDirection ?? null);
|
||||
|
||||
const intercityKind = dto.intercityKind ?? null;
|
||||
this.assertScopeCoherent({
|
||||
@@ -376,7 +419,8 @@ export class RatesService {
|
||||
if (dto.appliesTo) updates.appliesTo = appliesTo;
|
||||
if (dto.trigger) updates.trigger = trigger;
|
||||
|
||||
const containerTypeId = isSurcharge
|
||||
const keepsContainerType = !isSurcharge || trigger === 'WITH_RETURN';
|
||||
const containerTypeId = !keepsContainerType
|
||||
? null
|
||||
: dto.containerTypeId !== undefined
|
||||
? dto.containerTypeId
|
||||
@@ -387,11 +431,15 @@ export class RatesService {
|
||||
? dto.cargoTypeId
|
||||
: existing.cargoTypeId;
|
||||
const tradeDirection =
|
||||
isSurcharge || appliesTo === 'INTERCITY'
|
||||
? null
|
||||
: dto.tradeDirection !== undefined
|
||||
trigger === 'CUSTOMS_CLEARANCE' || trigger === 'WITH_RETURN'
|
||||
? dto.tradeDirection !== undefined
|
||||
? dto.tradeDirection
|
||||
: existing.tradeDirection;
|
||||
: existing.tradeDirection
|
||||
: isSurcharge || appliesTo === 'INTERCITY'
|
||||
? null
|
||||
: dto.tradeDirection !== undefined
|
||||
? dto.tradeDirection
|
||||
: existing.tradeDirection;
|
||||
|
||||
updates.containerTypeId = containerTypeId ?? null;
|
||||
updates.cargoTypeId = cargoTypeId ?? null;
|
||||
|
||||
Reference in New Issue
Block a user