mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-29 00:10:57 +00:00
@@ -46,7 +46,8 @@ export class BackofficeService {
|
||||
|
||||
/**
|
||||
* IAM user ids of every current employee across all organizations — used by
|
||||
* the notification recipients resolver's `allBackoffice` selector.
|
||||
* support chat for staff room membership. Notifications deliberately do NOT
|
||||
* use this: they target a desk via `getEmployeeUserIdsByPermission`.
|
||||
*/
|
||||
async getAllCurrentEmployeeUserIds(): Promise<string[]> {
|
||||
const employees = await this.employeeRepository.find({
|
||||
@@ -63,24 +64,67 @@ export class BackofficeService {
|
||||
* IAM user ids of current employees (any org) holding ANY of the given
|
||||
* permission keys — used by the notification recipients resolver's
|
||||
* `permissionKeys` selector for department/role-scoped targeting.
|
||||
*
|
||||
* This MUST agree with the request-time guard (`hasFreightPermission`,
|
||||
* common/freight-permission.util.ts), which counts four grant carriers plus
|
||||
* the super_admin bypass. Counting fewer silently drops legitimate
|
||||
* recipients: an earlier version joined only direct position permissions, on
|
||||
* which `bookings:view` resolved to 2 users — against 21 through position
|
||||
* TYPES, which is where admin-created positions actually keep their grants.
|
||||
*
|
||||
* Raw SQL rather than QueryBuilder because `Position.positionTypePermissions`
|
||||
* declares its inverse side against PositionType, so a relation join emits
|
||||
* `ptp.position_type_id = position.id` and silently matches nothing. Same
|
||||
* approach as FreightMeService's position-type lookups.
|
||||
*/
|
||||
async getEmployeeUserIdsByPermission(
|
||||
permissionKeys: string[],
|
||||
): Promise<string[]> {
|
||||
if (!permissionKeys.length) return [];
|
||||
const rows: { userId: string | null }[] = await this.employeeRepository
|
||||
.createQueryBuilder("employee")
|
||||
.innerJoin("employee.employeePositions", "employeePosition")
|
||||
.innerJoin("employeePosition.position", "position")
|
||||
.innerJoin("position.positionPermission", "positionPermission")
|
||||
.innerJoin("positionPermission.permission", "permission")
|
||||
.where("employee.isCurrent = :isCurrent", { isCurrent: true })
|
||||
.andWhere("permission.key IN (:...permissionKeys)", { permissionKeys })
|
||||
.select("DISTINCT employee.user_id", "userId")
|
||||
.getRawMany();
|
||||
return rows
|
||||
.map((r) => r.userId)
|
||||
.filter((id): id is string => Boolean(id));
|
||||
const rows: { userId: string }[] = await this.dataSource.query(
|
||||
`WITH target AS (SELECT id FROM iam.permissions WHERE key = ANY($1))
|
||||
-- 1. IAM role grants (user_roles -> role_permissions).
|
||||
SELECT e.user_id AS "userId"
|
||||
FROM iam.employees e
|
||||
JOIN iam.user_roles ur ON ur.user_id = e.user_id
|
||||
JOIN iam.role_permissions rp ON rp.role_id = ur.role_id
|
||||
WHERE e.is_current AND e.user_id IS NOT NULL
|
||||
AND rp.permission_id IN (SELECT id FROM target)
|
||||
UNION
|
||||
-- 2. Direct position grants. A delegate keeps their own position AND
|
||||
-- gains the one they stand in for, so both columns count.
|
||||
SELECT e.user_id
|
||||
FROM iam.employees e
|
||||
JOIN iam.employee_positions ep
|
||||
ON ep.employee_id = e.id AND ep.is_current
|
||||
JOIN iam.position_permissions pp
|
||||
ON pp.position_id IN (ep.position_id, ep.delegatee_position_id)
|
||||
WHERE e.is_current AND e.user_id IS NOT NULL
|
||||
AND pp.permission_id IN (SELECT id FROM target)
|
||||
UNION
|
||||
-- 3. Position TYPE grants — where admin-created positions keep theirs.
|
||||
SELECT e.user_id
|
||||
FROM iam.employees e
|
||||
JOIN iam.employee_positions ep
|
||||
ON ep.employee_id = e.id AND ep.is_current
|
||||
JOIN iam.positions p
|
||||
ON p.id IN (ep.position_id, ep.delegatee_position_id)
|
||||
JOIN iam.position_type_permissions ptp
|
||||
ON ptp.position_type_id = p.position_type_id
|
||||
WHERE e.is_current AND e.user_id IS NOT NULL
|
||||
AND ptp.permission_id IN (SELECT id FROM target)
|
||||
UNION
|
||||
-- 4. super_admin passes every freight permission check, so mirror that
|
||||
-- here or admins go blind on desks nobody else has been granted yet.
|
||||
SELECT e.user_id
|
||||
FROM iam.employees e
|
||||
JOIN iam.user_roles ur ON ur.user_id = e.user_id
|
||||
JOIN iam.roles r ON r.id = ur.role_id
|
||||
WHERE e.is_current AND e.user_id IS NOT NULL
|
||||
AND r.key = 'super_admin'`,
|
||||
[permissionKeys],
|
||||
);
|
||||
return rows.map((r) => r.userId);
|
||||
}
|
||||
|
||||
async createOrganizationUser(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BookingLifecycleNotifierService } from './booking-lifecycle-notifier.service';
|
||||
import type { Booking } from './entities/booking.entity';
|
||||
import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry';
|
||||
|
||||
/**
|
||||
* Who hears "Operations wants changes" depends on who owns the booking. A
|
||||
@@ -74,3 +75,39 @@ describe('BookingLifecycleNotifierService — operation changes requested', () =
|
||||
expect(inbox.notify.mock.calls[0][0].recipients).toEqual({ companyId: 'co-1' });
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Staff notifications used to go to every employee in every organization. They
|
||||
* now target a desk — and the two desks are disjoint: the GL presets hold no
|
||||
* bookings:view and no intake keys, so intake pings would be noise they cannot
|
||||
* act on. Both branches run through the same `inAppStaff` helper, which is the
|
||||
* easy place to lose the distinction again.
|
||||
*/
|
||||
describe('BookingLifecycleNotifierService — staff desk targeting', () => {
|
||||
const booking = () =>
|
||||
({ id: 'b-1', reference: 'BKG-0001', companyId: 'co-1' }) as Booking;
|
||||
|
||||
let inbox: { notify: jest.Mock };
|
||||
let service: BookingLifecycleNotifierService;
|
||||
|
||||
beforeEach(() => {
|
||||
inbox = { notify: jest.fn().mockResolvedValue(undefined) };
|
||||
service = new BookingLifecycleNotifierService(
|
||||
{ directSend: jest.fn().mockResolvedValue(undefined) } as never,
|
||||
inbox as never,
|
||||
{ query: jest.fn().mockResolvedValue([]) } as never,
|
||||
);
|
||||
});
|
||||
|
||||
it('routes intake items to the booking desk and clearance items to the clearance desk', () => {
|
||||
service.submittedToStaff(booking());
|
||||
service.clearanceDocsUploadedToStaff(booking());
|
||||
|
||||
expect(inbox.notify.mock.calls[0][0].recipients).toEqual({
|
||||
permissionKeys: [FREIGHT_PERMS.bookings.getNotification],
|
||||
});
|
||||
expect(inbox.notify.mock.calls[1][0].recipients).toEqual({
|
||||
permissionKeys: [FREIGHT_PERMS.bookings.clearanceGetNotification],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,6 +11,16 @@ import { Booking } from './entities/booking.entity';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { NotificationInboxService } from '../notification-inbox/notification-inbox.service';
|
||||
import { resolveCompanyNotifyPhone } from '../notifications/resolve-company-phone.util';
|
||||
import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry';
|
||||
|
||||
/**
|
||||
* Clearance items are worked by the GL desks, which hold no bookings:view and
|
||||
* no intake keys — so they take their own selector rather than the booking
|
||||
* desk's. Every override using this deep-links to a clearance page.
|
||||
*/
|
||||
const CLEARANCE_DESK = {
|
||||
permissionKeys: [FREIGHT_PERMS.bookings.clearanceGetNotification],
|
||||
};
|
||||
|
||||
/**
|
||||
* Customer + staff notifications for the booking lifecycle: review, clearance
|
||||
@@ -89,7 +99,11 @@ export class BookingLifecycleNotifierService {
|
||||
});
|
||||
}
|
||||
|
||||
/** Persist + push an in-app item to every backoffice staff user. */
|
||||
/**
|
||||
* Persist + push an in-app item to the booking desk — staff holding
|
||||
* `bookings:get_notification`. Callers whose item belongs to a different desk
|
||||
* override `recipients` (see {@link CLEARANCE_DESK}).
|
||||
*/
|
||||
private inAppStaff(
|
||||
b: Booking,
|
||||
title: string,
|
||||
@@ -97,7 +111,7 @@ export class BookingLifecycleNotifierService {
|
||||
overrides: Partial<NotifyInput> = {},
|
||||
): void {
|
||||
void this.inbox.notify({
|
||||
recipients: { allBackoffice: true },
|
||||
recipients: { permissionKeys: [FREIGHT_PERMS.bookings.getNotification] },
|
||||
audience: NotificationAudience.BACKOFFICE,
|
||||
type: NotificationType.REQUEST_SUBMITTED,
|
||||
title,
|
||||
@@ -274,6 +288,7 @@ export class BookingLifecycleNotifierService {
|
||||
`the customs declaration can be filed.${note ? ` Note: "${note}"` : ''}`;
|
||||
this.logger.log(`TRANSIT ASSIGNEE REQUESTED — ${this.ref(b)}`);
|
||||
this.inAppStaff(b, `Transit assignee needed — ${b.reference}`, msg, {
|
||||
recipients: CLEARANCE_DESK,
|
||||
type: NotificationType.CLEARANCE_REVIEW,
|
||||
link: `/dashboard/gl-djibouti/clearance/${b.id}`,
|
||||
});
|
||||
@@ -288,6 +303,7 @@ export class BookingLifecycleNotifierService {
|
||||
`The customs declaration can now be filed.`;
|
||||
this.logger.log(`TRANSIT ASSIGNEE ASSIGNED — ${this.ref(b)}`);
|
||||
this.inAppStaff(b, `Transit assignee set — ${b.reference}`, msg, {
|
||||
recipients: CLEARANCE_DESK,
|
||||
type: NotificationType.CLEARANCE_REVIEW,
|
||||
link: `/dashboard/bookings/${b.id}/clearance`,
|
||||
});
|
||||
@@ -395,6 +411,7 @@ export class BookingLifecycleNotifierService {
|
||||
'Clearance documents uploaded',
|
||||
`Customer uploaded clearance documents for booking ${this.ref(b)} — review them in the clearance queue.`,
|
||||
{
|
||||
recipients: CLEARANCE_DESK,
|
||||
type: NotificationType.CLEARANCE_REVIEW,
|
||||
link: `/dashboard/bookings/${b.id}/clearance`,
|
||||
},
|
||||
@@ -422,6 +439,7 @@ export class BookingLifecycleNotifierService {
|
||||
`The customer requested a change to the draft declaration on booking ${this.ref(b)}: ` +
|
||||
`"${note}". Send a corrected draft from the clearance page.`;
|
||||
this.inAppStaff(b, `Draft declaration change requested — ${this.ref(b)}`, msg, {
|
||||
recipients: CLEARANCE_DESK,
|
||||
type: NotificationType.CLEARANCE_REVIEW,
|
||||
link: `/dashboard/bookings/${b.id}/clearance`,
|
||||
});
|
||||
@@ -440,6 +458,7 @@ export class BookingLifecycleNotifierService {
|
||||
'Payment slip uploaded',
|
||||
`Customer uploaded the ${label} payment slip for booking ${this.ref(b)}.`,
|
||||
{
|
||||
recipients: CLEARANCE_DESK,
|
||||
type: NotificationType.PAYMENT_RECEIVED,
|
||||
link: `/dashboard/bookings/${b.id}/clearance`,
|
||||
},
|
||||
|
||||
@@ -1112,12 +1112,14 @@ export class BookingWagonCancellationService {
|
||||
|
||||
private notifyStaff(booking: Booking, title: string, body: string): void {
|
||||
void this.inbox.notify({
|
||||
recipients: { allBackoffice: true },
|
||||
recipients: { permissionKeys: [FREIGHT_PERMS.bookings.getNotification] },
|
||||
audience: NotificationAudience.BACKOFFICE,
|
||||
type: NotificationType.BOOKING_STATUS,
|
||||
title,
|
||||
body,
|
||||
link: `/bookings/${booking.id}`,
|
||||
// The portal path `/bookings/:id` used to be sent here, which 404s in the
|
||||
// dashboard. The staff view of these lives on the queue page.
|
||||
link: '/dashboard/wagon-cancellations',
|
||||
data: { bookingId: booking.id, reference: booking.reference },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Company, CompanyStatus } from "./entities/company.entity";
|
||||
import { NotificationsService } from "../notifications/notifications.service";
|
||||
import { NotificationInboxService } from "../notification-inbox/notification-inbox.service";
|
||||
import { resolveCompanyNotifyPhone } from "../notifications/resolve-company-phone.util";
|
||||
import { FREIGHT_PERMS } from "../../seed/freight-permissions.registry";
|
||||
|
||||
/** Account statuses that lock the customer out and therefore must be told to them. */
|
||||
const PUNITIVE_STATUSES: readonly CompanyStatus[] = [
|
||||
@@ -175,12 +176,9 @@ export class CompanyNotifierService {
|
||||
// ── Backoffice-facing: work has arrived back in the review queue ────────────
|
||||
|
||||
/**
|
||||
* Persist + push an in-app item to every backoffice staff user, deep-linked to
|
||||
* the customer's detail page.
|
||||
*
|
||||
* The recipient resolver has no role/permission targeting (see
|
||||
* `notification-recipients.service.ts`) — `allBackoffice` is the narrowest
|
||||
* selector available, so marketing is reached by notifying all staff.
|
||||
* Persist + push an in-app item to the customer desk — staff holding
|
||||
* `customers:get_notification` — deep-linked to the customer's detail page,
|
||||
* which is itself gated on `customers:view`.
|
||||
*/
|
||||
private notifyStaff(
|
||||
company: Company,
|
||||
@@ -189,7 +187,7 @@ export class CompanyNotifierService {
|
||||
data: Record<string, unknown> = {},
|
||||
): void {
|
||||
void this.inbox.notify({
|
||||
recipients: { allBackoffice: true },
|
||||
recipients: { permissionKeys: [FREIGHT_PERMS.customers.getNotification] },
|
||||
audience: NotificationAudience.BACKOFFICE,
|
||||
type: NotificationType.REQUEST_SUBMITTED,
|
||||
title,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ContractExpiryService } from './contract-expiry.service';
|
||||
import type { Contract } from './entities/contract.entity';
|
||||
import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry';
|
||||
|
||||
/**
|
||||
* The reminder must warn each customer once, ten days out, and must never let a
|
||||
@@ -60,4 +61,18 @@ describe('ContractExpiryService — expiry reminder', () => {
|
||||
inbox.notify.mockRejectedValue(new Error('inbox down'));
|
||||
await expect(service.remindExpiringContracts()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
// The sweep-failure alert is staff-facing. It used to go to every employee;
|
||||
// it belongs to the people who would notice expired contracts still listed
|
||||
// as active, i.e. the contract desk.
|
||||
it('alerts the contract desk when the sweep itself fails', async () => {
|
||||
repo.expireLapsedContracts.mockRejectedValue(new Error('deadlock'));
|
||||
|
||||
await service.expireLapsedContracts();
|
||||
|
||||
expect(inbox.notify).toHaveBeenCalledTimes(1);
|
||||
expect(inbox.notify.mock.calls[0][0].recipients).toEqual({
|
||||
permissionKeys: [FREIGHT_PERMS.contracts.getNotification],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import { NotificationAudience, NotificationType } from '@edr/types';
|
||||
|
||||
import { NotificationInboxService } from '../notification-inbox/notification-inbox.service';
|
||||
import { ContractsRepository } from './contracts.repository';
|
||||
import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry';
|
||||
|
||||
/**
|
||||
* How many days before a contract lapses the customer is reminded. Mirrored by
|
||||
@@ -79,7 +80,11 @@ export class ContractExpiryService {
|
||||
);
|
||||
try {
|
||||
await this.inbox.notify({
|
||||
recipients: { allBackoffice: true },
|
||||
// The people who would notice expired contracts still listed as
|
||||
// active are the ones working the contract desk.
|
||||
recipients: {
|
||||
permissionKeys: [FREIGHT_PERMS.contracts.getNotification],
|
||||
},
|
||||
audience: NotificationAudience.BACKOFFICE,
|
||||
type: NotificationType.GENERIC,
|
||||
title: 'Contract expiry sweep failed',
|
||||
|
||||
@@ -11,6 +11,16 @@ import { Contract } from './entities/contract.entity';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { NotificationInboxService } from '../notification-inbox/notification-inbox.service';
|
||||
import { resolveCompanyNotifyPhone } from '../notifications/resolve-company-phone.util';
|
||||
import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry';
|
||||
|
||||
/**
|
||||
* Clearance items are worked by the GL desks, which hold no intake keys — so
|
||||
* they take their own selector rather than the contract desk's. Every override
|
||||
* using this deep-links to a clearance or shipment-request page.
|
||||
*/
|
||||
const CLEARANCE_DESK = {
|
||||
permissionKeys: [FREIGHT_PERMS.contracts.clearanceGetNotification],
|
||||
};
|
||||
|
||||
/**
|
||||
* Customer + staff notifications for the contract lifecycle. Every customer
|
||||
@@ -86,7 +96,11 @@ export class ContractNotifierService {
|
||||
});
|
||||
}
|
||||
|
||||
/** Persist + push an in-app item to every backoffice staff user. */
|
||||
/**
|
||||
* Persist + push an in-app item to the contract desk — staff holding
|
||||
* `contracts:get_notification`. Callers whose item belongs to a different
|
||||
* desk override `recipients` (see {@link CLEARANCE_DESK}).
|
||||
*/
|
||||
private inAppStaff(
|
||||
c: Contract,
|
||||
title: string,
|
||||
@@ -94,7 +108,7 @@ export class ContractNotifierService {
|
||||
overrides: Partial<NotifyInput> = {},
|
||||
): void {
|
||||
void this.inbox.notify({
|
||||
recipients: { allBackoffice: true },
|
||||
recipients: { permissionKeys: [FREIGHT_PERMS.contracts.getNotification] },
|
||||
audience: NotificationAudience.BACKOFFICE,
|
||||
type: NotificationType.REQUEST_SUBMITTED,
|
||||
title,
|
||||
@@ -230,6 +244,7 @@ export class ContractNotifierService {
|
||||
`the customs declaration can be filed.${note ? ` Note: "${note}"` : ''}`;
|
||||
this.logger.log(`TRANSIT ASSIGNEE REQUESTED — ${c.reference}`);
|
||||
this.inAppStaff(c, `Transit assignee needed — ${c.reference}`, msg, {
|
||||
recipients: CLEARANCE_DESK,
|
||||
type: NotificationType.CLEARANCE_REVIEW,
|
||||
link: `/dashboard/gl-djibouti/clearance/${c.id}`,
|
||||
});
|
||||
@@ -248,6 +263,7 @@ export class ContractNotifierService {
|
||||
`The customs declaration can now be filed.`;
|
||||
this.logger.log(`TRANSIT ASSIGNEE ASSIGNED — ${c.reference}`);
|
||||
this.inAppStaff(c, `Transit assignee set — ${c.reference}`, msg, {
|
||||
recipients: CLEARANCE_DESK,
|
||||
type: NotificationType.CLEARANCE_REVIEW,
|
||||
link: `/dashboard/contracts/clearance/${c.id}`,
|
||||
});
|
||||
@@ -264,6 +280,7 @@ export class ContractNotifierService {
|
||||
`"${note}". Review and re-advise the amount on the clearance page.`;
|
||||
this.logger.log(`DUTY DISPUTED — ${c.reference}`);
|
||||
this.inAppStaff(c, `Duty disputed on ${c.reference}`, msg, {
|
||||
recipients: CLEARANCE_DESK,
|
||||
type: NotificationType.CLEARANCE_REVIEW,
|
||||
link: `/dashboard/contracts/clearance/${c.id}`,
|
||||
});
|
||||
@@ -321,6 +338,7 @@ export class ContractNotifierService {
|
||||
'Clearance documents uploaded',
|
||||
`Customer uploaded clearance documents for contract ${this.ref(c)} — review them in the clearance queue.`,
|
||||
{
|
||||
recipients: CLEARANCE_DESK,
|
||||
type: NotificationType.CLEARANCE_REVIEW,
|
||||
link: `/dashboard/contracts/clearance/${c.id}`,
|
||||
},
|
||||
@@ -334,6 +352,7 @@ export class ContractNotifierService {
|
||||
'Duty slip uploaded',
|
||||
`Customer uploaded the duty & tax payment slip for contract ${this.ref(c)}.`,
|
||||
{
|
||||
recipients: CLEARANCE_DESK,
|
||||
type: NotificationType.PAYMENT_RECEIVED,
|
||||
link: `/dashboard/contracts/clearance/${c.id}`,
|
||||
},
|
||||
@@ -347,6 +366,9 @@ export class ContractNotifierService {
|
||||
'New shipment request',
|
||||
`Shipment request ${requestRef} was filed under contract ${this.ref(c)} and awaits GL review.`,
|
||||
{
|
||||
// GL reviews these, and the shipment-requests page is gated on
|
||||
// contracts:create_booking — a key only the GL Ethiopia preset holds.
|
||||
recipients: CLEARANCE_DESK,
|
||||
link: `/dashboard/shipment-requests/${requestId}`,
|
||||
data: { contractId: c.id, requestId, reference: requestRef },
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NotificationAudience } from '@edr/types';
|
||||
|
||||
import { MaintenanceService } from './maintenance.service';
|
||||
import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry';
|
||||
|
||||
/**
|
||||
* The daily due-alert: a SCHEDULED item that crossed its km or date threshold
|
||||
@@ -37,6 +38,10 @@ describe('MaintenanceService.sendDueAlerts', () => {
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
audience: NotificationAudience.BACKOFFICE,
|
||||
// The fleet desk, not every employee in the company.
|
||||
recipients: {
|
||||
permissionKeys: [FREIGHT_PERMS.maintenance.getNotification],
|
||||
},
|
||||
title: 'Maintenance due — ET-9875',
|
||||
body: expect.stringContaining('driven 50200 km (due at 50000 km)'),
|
||||
}),
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
UpsertMaintenanceIntervalDto,
|
||||
} from './dto/create-maintenance.dto';
|
||||
import { NotificationInboxService } from '../notification-inbox/notification-inbox.service';
|
||||
import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry';
|
||||
|
||||
@Injectable()
|
||||
export class MaintenanceService {
|
||||
@@ -53,7 +54,9 @@ export class MaintenanceService {
|
||||
? `driven ${item.currentKm} km (due at ${item.nextDueKm} km)`
|
||||
: `due ${new Date(item.nextDueDate as Date).toLocaleDateString()}`;
|
||||
await this.inbox.notify({
|
||||
recipients: { allBackoffice: true },
|
||||
recipients: {
|
||||
permissionKeys: [FREIGHT_PERMS.maintenance.getNotification],
|
||||
},
|
||||
audience: NotificationAudience.BACKOFFICE,
|
||||
type: NotificationType.GENERIC,
|
||||
title: `Maintenance due — ${item.plateNumber}`,
|
||||
|
||||
@@ -14,7 +14,9 @@ import { ExternalProfileRepository } from "../companies/external-profile.reposit
|
||||
* - `companyProfileId` → resolved to its company, then to that company's users.
|
||||
* - `organizationId` → all current employees of the org (backoffice staff).
|
||||
* - `permissionKeys` → current employees (any org) holding any of these
|
||||
* permission keys (e.g. department/role-scoped targeting).
|
||||
* permission keys — how every staff-facing notification is targeted. There is
|
||||
* deliberately no "all backoffice" selector: staff notifications belong to a
|
||||
* desk, and the `<module>:get_notification` keys name which one.
|
||||
*/
|
||||
@Injectable()
|
||||
export class NotificationRecipientsService {
|
||||
@@ -69,18 +71,6 @@ export class NotificationRecipientsService {
|
||||
}
|
||||
}
|
||||
|
||||
if (recipients.allBackoffice) {
|
||||
try {
|
||||
for (const uid of await this.backoffice.getAllCurrentEmployeeUserIds()) {
|
||||
ids.add(uid);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Failed to resolve allBackoffice recipients: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (recipients.permissionKeys?.length) {
|
||||
try {
|
||||
for (const uid of await this.backoffice.getEmployeeUserIdsByPermission(
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
PriorityRuleChangeStatus,
|
||||
} from '../entities/priority-rule-change-request.entity';
|
||||
import { PriorityConfigsService } from './priority-configs.service';
|
||||
import { FREIGHT_PERMS } from '../../../seed/freight-permissions.registry';
|
||||
|
||||
/** Backoffice rule-engine page — where both queue and rules live. */
|
||||
const RULES_LINK = '/dashboard/rules/priority-configs';
|
||||
@@ -221,7 +222,9 @@ export class PriorityRuleChangeRequestsService {
|
||||
): void {
|
||||
void this.inbox
|
||||
.notify({
|
||||
recipients: { allBackoffice: true },
|
||||
recipients: {
|
||||
permissionKeys: [FREIGHT_PERMS.ruleEngine.getNotification],
|
||||
},
|
||||
audience: NotificationAudience.BACKOFFICE,
|
||||
type: NotificationType.REQUEST_SUBMITTED,
|
||||
title,
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
} from '../entities/rate-change-request.entity';
|
||||
import { Rate } from '../entities/rate.entity';
|
||||
import { RatesService } from './rates.service';
|
||||
import { FREIGHT_PERMS } from '../../../seed/freight-permissions.registry';
|
||||
|
||||
/** Backoffice page where both the queue and the rates live. */
|
||||
const RATES_LINK = '/dashboard/rules/rates';
|
||||
@@ -234,7 +235,9 @@ export class RateChangeRequestsService {
|
||||
private notifyTeam(title: string, body: string, request: RateChangeRequest): void {
|
||||
void this.inbox
|
||||
.notify({
|
||||
recipients: { allBackoffice: true },
|
||||
recipients: {
|
||||
permissionKeys: [FREIGHT_PERMS.ruleEngine.getNotification],
|
||||
},
|
||||
audience: NotificationAudience.BACKOFFICE,
|
||||
type: NotificationType.REQUEST_SUBMITTED,
|
||||
title,
|
||||
|
||||
@@ -313,6 +313,8 @@ export class BookingWindowService implements OnModuleInit {
|
||||
// Fire-and-forget: a slow SMS/email gateway must not stall the tick loop
|
||||
// (the `ticking` guard would otherwise delay every schedule's transition).
|
||||
void this.notifyWindowOpened(schedule);
|
||||
// Intercity rides along whatever train passes, export included.
|
||||
void this.notifyIntercityCorridorScheduled(schedule);
|
||||
this.logger.log(`Export booking window opened for schedule ${schedule.id}`);
|
||||
return true;
|
||||
}
|
||||
@@ -365,7 +367,10 @@ export class BookingWindowService implements OnModuleInit {
|
||||
}
|
||||
// Only announce the first opening of the day; reopen cycles don't re-notify.
|
||||
// Fire-and-forget so a slow SMS/email gateway never stalls the tick loop.
|
||||
if (schedule.bookingCycleNo === 1) void this.notifyWindowOpened(schedule);
|
||||
if (schedule.bookingCycleNo === 1) {
|
||||
void this.notifyWindowOpened(schedule);
|
||||
void this.notifyIntercityCorridorScheduled(schedule);
|
||||
}
|
||||
this.logger.log(
|
||||
`[WINDOW] ${schedule.id} PRE_WINDOW→OPEN — booking window opened ` +
|
||||
`(cycle ${schedule.bookingCycleNo})`,
|
||||
@@ -710,6 +715,149 @@ export class BookingWindowService implements OnModuleInit {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SMS + email + inbox the owner of every waiting intercity booking whose
|
||||
* corridor lies on this schedule's route.
|
||||
*
|
||||
* Intercity (DOMESTIC) bookings carry no date — the customer books a corridor
|
||||
* and the cargo waits in a pool until staff ride it along a passing
|
||||
* import/export train (see IntercityService). Until now that wait was silent:
|
||||
* `notifyWindowOpened` only reaches companies holding an ACTIVE contract whose
|
||||
* `contract_routes` match the train's exact origin→destination, and an
|
||||
* intercity booking is neither contracted nor necessarily end-to-end.
|
||||
*
|
||||
* Corridor match mirrors `IntercityService.corridorOnRoute` exactly — both
|
||||
* yards on the route with origin strictly before destination, falling back to
|
||||
* the train's own origin/destination when the route has fewer than two
|
||||
* milestones — so nobody is told about a train they can never be placed on.
|
||||
*/
|
||||
private async notifyIntercityCorridorScheduled(
|
||||
schedule: TrainSchedule,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const rows: Array<{
|
||||
bookingId: string;
|
||||
companyId: string;
|
||||
phone: string | null;
|
||||
email: string | null;
|
||||
corridor: string;
|
||||
}> = await this.dataSource.query(
|
||||
// `stops` is the schedule's stop list, with the two-stop
|
||||
// origin→destination pseudo-route as the legacy fallback — the same
|
||||
// shape IntercityService.milestoneSequenceOf builds in TypeScript.
|
||||
`WITH ms AS (
|
||||
SELECT yard_id, sequence_no
|
||||
FROM freight.route_milestones
|
||||
WHERE route_id = $1 AND deleted_at IS NULL
|
||||
),
|
||||
stops AS (
|
||||
SELECT yard_id, sequence_no FROM ms WHERE (SELECT count(*) FROM ms) >= 2
|
||||
UNION ALL
|
||||
SELECT v.yard_id, v.seq
|
||||
FROM (VALUES ($2::uuid, 1), ($3::uuid, 2)) AS v(yard_id, seq)
|
||||
WHERE (SELECT count(*) FROM ms) < 2
|
||||
)
|
||||
SELECT DISTINCT
|
||||
b.id AS "bookingId",
|
||||
b.company_id AS "companyId",
|
||||
${companyNotifyPhoneExpr('co')} AS phone,
|
||||
COALESCE(co.email, co.general_manager_email) AS email,
|
||||
COALESCE(oy.label, oy.code) || ' to ' ||
|
||||
COALESCE(dy.label, dy.code) AS corridor
|
||||
FROM freight.bookings b
|
||||
JOIN stops o ON o.yard_id = b.origin_yard_id
|
||||
JOIN stops d ON d.yard_id = b.destination_yard_id
|
||||
AND d.sequence_no > o.sequence_no
|
||||
JOIN freight.companies co ON co.id = b.company_id AND co.deleted_at IS NULL
|
||||
JOIN freight.yards oy ON oy.id = b.origin_yard_id
|
||||
JOIN freight.yards dy ON dy.id = b.destination_yard_id
|
||||
${primaryContactUserJoin('co')}
|
||||
WHERE b.deleted_at IS NULL
|
||||
AND b.trade_direction = 'DOMESTIC'
|
||||
AND b.train_schedule_id IS NULL
|
||||
-- Same waiting pool IntercityService.findWaitingIntercityBookings
|
||||
-- draws candidates from: commercial paid/executed, government approved.
|
||||
AND ((b.is_government = false AND b.status IN ('FULLY_EXECUTED', 'PAID'))
|
||||
OR (b.is_government = true AND b.status = 'APPROVED'))
|
||||
-- Once per booking, not once per train. A booking can sit in the
|
||||
-- pool for weeks while several trains open a window on its corridor,
|
||||
-- and "trains run your corridor, you are queued" is the same message
|
||||
-- every time. The inbox row written below is the marker.
|
||||
-- ponytail: unindexed jsonb probe over freight.notifications; add a
|
||||
-- partial index on (data->>'intercityCorridorBookingId') if the
|
||||
-- table grows enough for this to show up in the tick loop.
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM freight.notifications n
|
||||
WHERE n.data->>'intercityCorridorBookingId' = b.id::text)`,
|
||||
[schedule.routeId, schedule.originStationId, schedule.destinationStationId],
|
||||
);
|
||||
if (!rows.length) return;
|
||||
|
||||
const depart = schedule.scheduledDepartureDate.toLocaleDateString('en-GB', {
|
||||
timeZone: BATCH_TIMEZONE,
|
||||
});
|
||||
const msgFor = (corridors: string[]) =>
|
||||
`A train is scheduled on your intercity corridor ${corridors.join(', ')}, ` +
|
||||
`departing ${depart}. EDR will confirm once your cargo is placed on a train.`;
|
||||
|
||||
// One inbox item per booking (its `data` is the once-per-booking marker
|
||||
// the query above reads), but one SMS/email per company — a customer with
|
||||
// three waiting bookings gets one message naming all three corridors.
|
||||
const byCompany = new Map<
|
||||
string,
|
||||
{ phone: string | null; email: string | null; corridors: string[] }
|
||||
>();
|
||||
for (const row of rows) {
|
||||
const entry = byCompany.get(row.companyId) ?? {
|
||||
phone: row.phone,
|
||||
email: row.email,
|
||||
corridors: [],
|
||||
};
|
||||
if (!entry.corridors.includes(row.corridor)) entry.corridors.push(row.corridor);
|
||||
byCompany.set(row.companyId, entry);
|
||||
|
||||
await this.inbox.notify({
|
||||
recipients: { companyId: row.companyId },
|
||||
audience: NotificationAudience.PORTAL,
|
||||
type: NotificationType.SCHEDULE_UPDATE,
|
||||
title: 'Train scheduled on your corridor',
|
||||
body: msgFor([row.corridor]),
|
||||
link: `/bookings/${row.bookingId}`,
|
||||
data: {
|
||||
intercityCorridorBookingId: row.bookingId,
|
||||
trainScheduleId: schedule.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
for (const [companyId, entry] of byCompany) {
|
||||
const msg = msgFor(entry.corridors);
|
||||
if (entry.phone) {
|
||||
await this.notifications
|
||||
.directSend('sms', entry.phone, msg)
|
||||
.catch((e) =>
|
||||
this.logger.warn(`Intercity corridor SMS failed: ${(e as Error).message}`),
|
||||
);
|
||||
}
|
||||
if (entry.email) {
|
||||
await this.notifications
|
||||
.directSend('email', entry.email, msg)
|
||||
.catch((e) =>
|
||||
this.logger.warn(`Intercity corridor email failed: ${(e as Error).message}`),
|
||||
);
|
||||
}
|
||||
this.logger.log(
|
||||
`Notified company ${companyId} of ${entry.corridors.length} intercity ` +
|
||||
`corridor(s) served by schedule ${schedule.id}`,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`notifyIntercityCorridorScheduled failed for ${schedule.id}: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async setPhase(
|
||||
schedule: TrainSchedule,
|
||||
patch: Partial<
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { BookingWindowService } from './booking-window.service';
|
||||
import type { TrainSchedule } from '../train-schedules/entities/train-schedule.entity';
|
||||
|
||||
/**
|
||||
* Intercity corridor announcement: when a train's booking window opens, every
|
||||
* customer with a waiting intercity booking on that corridor is told over SMS,
|
||||
* email and the portal inbox.
|
||||
*
|
||||
* The corridor SQL itself is EXPLAIN-validated against the dev database; what
|
||||
* this covers is the fan-out shape around it — one inbox row per booking
|
||||
* (that row's `data` is the once-per-booking marker the query dedupes on) but
|
||||
* one SMS/email per company, naming every corridor at once.
|
||||
*/
|
||||
describe('BookingWindowService — intercity corridor announcement', () => {
|
||||
const schedule = {
|
||||
id: 'sched-1',
|
||||
routeId: 'route-1',
|
||||
originStationId: 'yard-o',
|
||||
destinationStationId: 'yard-d',
|
||||
scheduledDepartureDate: new Date('2026-08-01T06:00:00.000Z'),
|
||||
} as unknown as TrainSchedule;
|
||||
|
||||
const build = (rows: unknown[]) => {
|
||||
const query = jest.fn().mockResolvedValue(rows);
|
||||
const directSend = jest.fn().mockResolvedValue(undefined);
|
||||
const notify = jest.fn().mockResolvedValue(undefined);
|
||||
const service = new BookingWindowService(
|
||||
{ query, getRepository: () => ({ update: jest.fn() }) } as never,
|
||||
{ findById: jest.fn(), findAll: jest.fn() } as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{ directSend } as never,
|
||||
{ notify } as never,
|
||||
{ emitPhase: jest.fn() } as never,
|
||||
);
|
||||
const run = (): Promise<void> =>
|
||||
(
|
||||
service as unknown as {
|
||||
notifyIntercityCorridorScheduled: (s: TrainSchedule) => Promise<void>;
|
||||
}
|
||||
).notifyIntercityCorridorScheduled(schedule);
|
||||
return { run, query, directSend, notify };
|
||||
};
|
||||
|
||||
it('sends one inbox item per booking and one SMS/email per company', async () => {
|
||||
const { run, directSend, notify } = build([
|
||||
{
|
||||
bookingId: 'bk-1',
|
||||
companyId: 'co-1',
|
||||
phone: '+251900000001',
|
||||
email: 'ops@co1.example',
|
||||
corridor: 'Dire Dawa to Adama',
|
||||
},
|
||||
{
|
||||
bookingId: 'bk-2',
|
||||
companyId: 'co-1',
|
||||
phone: '+251900000001',
|
||||
email: 'ops@co1.example',
|
||||
corridor: 'Adama to Mojo',
|
||||
},
|
||||
]);
|
||||
|
||||
await run();
|
||||
|
||||
// Per booking: the marker keeps the next train on this corridor from
|
||||
// re-announcing the same thing to the same booking.
|
||||
expect(notify).toHaveBeenCalledTimes(2);
|
||||
expect(notify.mock.calls.map((c) => c[0].data.intercityCorridorBookingId)).toEqual([
|
||||
'bk-1',
|
||||
'bk-2',
|
||||
]);
|
||||
expect(notify.mock.calls[0][0].recipients).toEqual({ companyId: 'co-1' });
|
||||
expect(notify.mock.calls[0][0].link).toBe('/bookings/bk-1');
|
||||
|
||||
// Per company: two bookings, one SMS and one email, both corridors named.
|
||||
expect(directSend).toHaveBeenCalledTimes(2);
|
||||
const [smsChannel, smsTo, smsBody] = directSend.mock.calls[0];
|
||||
expect([smsChannel, smsTo]).toEqual(['sms', '+251900000001']);
|
||||
expect(smsBody).toContain('Dire Dawa to Adama, Adama to Mojo');
|
||||
expect(smsBody).toContain('01/08/2026');
|
||||
expect(directSend.mock.calls[1][0]).toBe('email');
|
||||
});
|
||||
|
||||
it('sends nothing when no waiting booking rides this corridor', async () => {
|
||||
const { run, directSend, notify } = build([]);
|
||||
|
||||
await run();
|
||||
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
expect(directSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips the channels a company has no contact for', async () => {
|
||||
const { run, directSend, notify } = build([
|
||||
{
|
||||
bookingId: 'bk-3',
|
||||
companyId: 'co-2',
|
||||
phone: null,
|
||||
email: 'ops@co2.example',
|
||||
corridor: 'Dire Dawa to Adama',
|
||||
},
|
||||
]);
|
||||
|
||||
await run();
|
||||
|
||||
expect(notify).toHaveBeenCalledTimes(1);
|
||||
expect(directSend).toHaveBeenCalledTimes(1);
|
||||
expect(directSend.mock.calls[0][0]).toBe('email');
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import { NotificationInboxService } from '../notification-inbox/notification-inb
|
||||
import { CreateFeeRuleDto, UpdateFeeRuleDto } from './dto/fee-rule.dto';
|
||||
import { FeeRuleBasis, FeeRuleType, WarehouseFeeRule, WarehouseFeeTier } from './entities/warehouse-fee-rule.entity';
|
||||
import { WarehouseFeeRuleRepository } from './warehouse-fee-rule.repository';
|
||||
import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry';
|
||||
|
||||
interface ItemAttributes {
|
||||
arrivedAt: Date | null;
|
||||
@@ -178,7 +179,11 @@ export class WarehouseFeeService {
|
||||
const total = alerts.reduce((sum, r) => sum + r.accruedAmount, 0);
|
||||
try {
|
||||
await this.inbox.notify({
|
||||
recipients: { allBackoffice: true },
|
||||
recipients: {
|
||||
permissionKeys: [
|
||||
FREIGHT_PERMS.warehouseFeeInvoices.getNotification,
|
||||
],
|
||||
},
|
||||
audience: NotificationAudience.BACKOFFICE,
|
||||
type: NotificationType.BOOKING_STATUS,
|
||||
title: 'Warehouse fee accruals need attention',
|
||||
|
||||
Reference in New Issue
Block a user