fix issue, add transit flow, fix cancellation

This commit is contained in:
Marshal
2026-08-28 22:13:49 +00:00
parent 3015de7508
commit 7e163088d9
50 changed files with 2787 additions and 337 deletions

View File

@@ -1,25 +1,34 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsBoolean, IsDateString, IsOptional, IsString, MaxLength } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { Transform } from "class-transformer";
import {
IsBoolean,
IsDateString,
IsEmail,
IsOptional,
IsString,
MaxLength,
} from "class-validator";
import { IsValidPhone } from "../../../common/validators/is-phone-number.validator";
const toBoolean = ({ value }: { value: unknown }) => {
if (typeof value === 'boolean') return value;
if (value === 'true') return true;
if (value === 'false') return false;
if (typeof value === "boolean") return value;
if (value === "true") return true;
if (value === "false") return false;
return value;
};
export class CreateTransitAgentDto {
@ApiProperty({ maxLength: 150, example: 'Ahmed Bourhan' })
@ApiProperty({ maxLength: 150, example: "Ahmed Bourhan" })
@IsString()
@MaxLength(150)
name!: string;
@ApiProperty({ example: '2026-01-01' })
@ApiProperty({ example: "2026-01-01" })
@IsDateString()
validFrom!: string;
@ApiProperty({ example: '2026-12-31' })
@ApiProperty({ example: "2026-12-31" })
@IsDateString()
validTo!: string;
@@ -28,4 +37,33 @@ export class CreateTransitAgentDto {
@Transform(toBoolean)
@IsBoolean()
isActive?: boolean;
/**
* Becomes the IAM account's email and is where the activation link is sent.
* Optional: an agent may be created as a GL-assignable roster entry only, and
* invited later. Supplying it creates the portal account right away.
*/
@ApiPropertyOptional({ example: "a.bourhan@transit.dj" })
@IsOptional()
@IsEmail()
@MaxLength(150)
email?: string;
@ApiPropertyOptional({
example: "+25377834567",
description:
"E.164. Djiboutian (+253 77…) and Ethiopian (+251 9…) mobiles also receive the activation link by SMS.",
})
@IsOptional()
@IsString()
@MaxLength(30)
@IsValidPhone()
phoneNumber?: string;
/** Login name. Defaults to the email, which is what the agent tries first. */
@ApiPropertyOptional({ example: "a-bourhan" })
@IsOptional()
@IsString()
@MaxLength(100)
username?: string;
}

View File

@@ -0,0 +1,36 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsEmail, IsOptional, IsString, MaxLength } from "class-validator";
import { IsValidPhone } from "../../../common/validators/is-phone-number.validator";
/**
* Give an EXISTING roster-only transit agent a portal login.
*
* Email is required here even though it is optional on the agent itself: this
* endpoint's whole job is to send the activation link, and email is the only
* channel guaranteed to reach a Djibouti-registered officer. Omitting a field
* keeps whatever the agent already has.
*/
export class InviteTransitAgentDto {
@ApiProperty({ example: "a.bourhan@transit.dj" })
@IsEmail()
@MaxLength(150)
email!: string;
@ApiPropertyOptional({
example: "+25377834567",
description:
"E.164. Djiboutian (+253 77…) and Ethiopian (+251 9…) mobiles also receive the activation link by SMS.",
})
@IsOptional()
@IsString()
@MaxLength(30)
@IsValidPhone()
phoneNumber?: string;
@ApiPropertyOptional({ example: "a-bourhan" })
@IsOptional()
@IsString()
@MaxLength(100)
username?: string;
}

View File

@@ -1,5 +1,5 @@
import { PartialType } from '@nestjs/mapped-types';
import { PartialType } from "@nestjs/mapped-types";
import { CreateTransitAgentDto } from './create-transit-agent.dto';
import { CreateTransitAgentDto } from "./create-transit-agent.dto";
export class UpdateTransitAgentDto extends PartialType(CreateTransitAgentDto) {}

View File

@@ -1,5 +1,5 @@
import { BaseEntity } from '@edr/api-common';
import { Column, Entity, Index } from 'typeorm';
import { BaseEntity } from "@edr/api-common";
import { Column, Entity, Index } from "typeorm";
/**
* Djibouti transit officer GL Djibouti may assign against a shipment's
@@ -7,18 +7,43 @@ import { Column, Entity, Index } from 'typeorm';
* validity window arrive without a code change; `isActive` is the manual
* suspend/reactivate switch, independent of the validity window.
*/
@Entity({ schema: 'freight', name: 'transit_agents' })
@Index(['isActive'])
@Entity({ schema: "freight", name: "transit_agents" })
@Index(["isActive"])
export class TransitAgent extends BaseEntity {
@Column({ name: 'name', type: 'varchar', length: 150 })
@Column({ name: "name", type: "varchar", length: 150 })
name!: string;
@Column({ name: 'valid_from', type: 'date' })
@Column({ name: "valid_from", type: "date" })
validFrom!: string;
@Column({ name: 'valid_to', type: 'date' })
@Column({ name: "valid_to", type: "date" })
validTo!: string;
@Column({ name: 'is_active', type: 'boolean', default: true })
@Column({ name: "is_active", type: "boolean", default: true })
isActive!: boolean;
/**
* The IAM account (`iam.users`, userType `individual`) that signs in to the
* portal as this agent. No FK: `iam` is a separate schema owned by the IAM
* service, and the rest of the codebase reaches it by query rather than by
* relation.
*
* NULL for every agent that exists only as a GL-assignable roster entry —
* which is all of them before this feature, and stays legal afterwards. An
* agent gains an account when staff invite it, so `userId !== null` IS the
* "has a portal login" predicate; nothing else needs to track it.
*/
@Column({ name: "user_id", type: "uuid", nullable: true })
userId?: string | null;
/**
* Mirrors the IAM account's email; the activation link is sent here. Nullable
* because a roster-only agent has never needed one — but an invite cannot be
* sent without it, so {@link TransitAgentsService.invite} requires it.
*/
@Column({ name: "email", type: "varchar", length: 150, nullable: true })
email?: string | null;
@Column({ name: "phone_number", type: "varchar", length: 30, nullable: true })
phoneNumber?: string | null;
}

View File

@@ -10,36 +10,38 @@ import {
Patch,
Post,
Query,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
} from "@nestjs/common";
import { ApiBearerAuth, ApiOperation, ApiTags } from "@nestjs/swagger";
import {
RuleEngineCreate,
RuleEngineDelete,
RuleEngineUpdate,
RuleEngineView,
} from '../../common/rule-engine-guards';
} from "../../common/rule-engine-guards";
import { CreateTransitAgentDto } from './dto/create-transit-agent.dto';
import { UpdateTransitAgentDto } from './dto/update-transit-agent.dto';
import { TransitAgentsService } from './transit-agents.service';
import { BackofficeResetPasswordDto } from "../auth/dto/forgot-password.dto";
import { CreateTransitAgentDto } from "./dto/create-transit-agent.dto";
import { InviteTransitAgentDto } from "./dto/invite-transit-agent.dto";
import { UpdateTransitAgentDto } from "./dto/update-transit-agent.dto";
import { TransitAgentsService } from "./transit-agents.service";
@ApiTags('transit-agents')
@Controller('transit-agents')
@ApiTags("transit-agents")
@Controller("transit-agents")
@ApiBearerAuth()
export class TransitAgentsController {
constructor(private readonly transitAgentsService: TransitAgentsService) {}
@Get()
@RuleEngineView('transit-agents')
@ApiOperation({ summary: 'List transit agents' })
@RuleEngineView("transit-agents")
@ApiOperation({ summary: "List transit agents" })
findAll(@Query() query: Record<string, string | undefined>) {
return this.transitAgentsService.findAll({
isActive:
query.isActive === 'all'
query.isActive === "all"
? undefined
: query.isActive !== undefined
? query.isActive === 'true'
? query.isActive === "true"
: undefined,
page: query.page ? parseInt(query.page, 10) : undefined,
pageSize: query.pageSize ? parseInt(query.pageSize, 10) : undefined,
@@ -49,39 +51,77 @@ export class TransitAgentsController {
}
/** Active + currently valid officers — the transit-assignee assignment dropdown. */
@Get('assignable')
@RuleEngineView('transit-agents')
@ApiOperation({ summary: 'List transit agents assignable right now (active and in-window)' })
@Get("assignable")
@RuleEngineView("transit-agents")
@ApiOperation({
summary: "List transit agents assignable right now (active and in-window)",
})
findAssignable() {
return this.transitAgentsService.findAssignable();
}
@Get(':id')
@RuleEngineView('transit-agents')
@ApiOperation({ summary: 'Get a transit agent by ID' })
findOne(@Param('id', ParseUUIDPipe) id: string) {
@Get(":id")
@RuleEngineView("transit-agents")
@ApiOperation({ summary: "Get a transit agent by ID" })
findOne(@Param("id", ParseUUIDPipe) id: string) {
return this.transitAgentsService.findById(id);
}
@Post()
@RuleEngineCreate('transit-agents')
@ApiOperation({ summary: 'Create a transit agent' })
@RuleEngineCreate("transit-agents")
@ApiOperation({
summary:
"Create a transit agent; with an email, also creates its portal account and sends the activation link",
})
create(@Body() dto: CreateTransitAgentDto) {
return this.transitAgentsService.create(dto);
return this.transitAgentsService.createWithInvite(dto);
}
@Patch(':id')
@RuleEngineUpdate('transit-agents')
@ApiOperation({ summary: 'Update a transit agent' })
update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateTransitAgentDto) {
/**
* The path for the roster entries already in production: they were created
* before transit agents had logins, so they get their account here rather
* than at create time.
*/
@Post(":id/invite")
@RuleEngineUpdate("transit-agents")
@ApiOperation({
summary:
"Create a portal account for an existing transit agent and send the activation link",
})
invite(
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: InviteTransitAgentDto,
) {
return this.transitAgentsService.invite(id, dto);
}
@Post(":id/resend-activation")
@RuleEngineUpdate("transit-agents")
@ApiOperation({
summary: "Resend a transit agent's activation / password-reset link",
})
resendActivation(
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: BackofficeResetPasswordDto,
) {
return this.transitAgentsService.resendActivation(id, dto.channel);
}
@Patch(":id")
@RuleEngineUpdate("transit-agents")
@ApiOperation({ summary: "Update a transit agent" })
update(
@Param("id", ParseUUIDPipe) id: string,
@Body() dto: UpdateTransitAgentDto,
) {
return this.transitAgentsService.update(id, dto);
}
@Delete(':id')
@RuleEngineDelete('transit-agents')
@Delete(":id")
@RuleEngineDelete("transit-agents")
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Soft-delete a transit agent' })
remove(@Param('id', ParseUUIDPipe) id: string) {
@ApiOperation({ summary: "Soft-delete a transit agent" })
remove(@Param("id", ParseUUIDPipe) id: string) {
return this.transitAgentsService.remove(id);
}
}

View File

@@ -1,13 +1,24 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { TransitAgent } from './entities/transit-agent.entity';
import { TransitAgentsController } from './transit-agents.controller';
import { TransitAgentsRepository } from './transit-agents.repository';
import { TransitAgentsService } from './transit-agents.service';
import { User } from "@tria-plc/iamapi-common/entities/iam/user/user.entity";
import { FreightAuthModule } from "../auth/freight-auth.module";
import { OtpModule } from "../otp/otp.module";
import { TransitAgent } from "./entities/transit-agent.entity";
import { TransitAgentsController } from "./transit-agents.controller";
import { TransitAgentsRepository } from "./transit-agents.repository";
import { TransitAgentsService } from "./transit-agents.service";
@Module({
imports: [TypeOrmModule.forFeature([TransitAgent])],
imports: [
// `User` is registered here so this module can create the IAM account that
// backs an invited transit agent, in the same transaction as the agent row.
TypeOrmModule.forFeature([TransitAgent, User]),
// CustomerResetService — activation links reuse the staff-triggered reset path.
FreightAuthModule,
OtpModule,
],
controllers: [TransitAgentsController],
providers: [TransitAgentsRepository, TransitAgentsService],
exports: [TransitAgentsRepository, TransitAgentsService],

View File

@@ -1,9 +1,14 @@
import { BaseRepository } from '@edr/api-common';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { LessThanOrEqual, MoreThanOrEqual, Repository } from 'typeorm';
import { BaseRepository } from "@edr/api-common";
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import {
EntityManager,
LessThanOrEqual,
MoreThanOrEqual,
Repository,
} from "typeorm";
import { TransitAgent } from './entities/transit-agent.entity';
import { TransitAgent } from "./entities/transit-agent.entity";
@Injectable()
export class TransitAgentsRepository extends BaseRepository<TransitAgent> {
@@ -22,7 +27,48 @@ export class TransitAgentsRepository extends BaseRepository<TransitAgent> {
validFrom: LessThanOrEqual(today),
validTo: MoreThanOrEqual(today),
},
order: { name: 'ASC' },
order: { name: "ASC" },
});
}
/** The transit agent signed in as `userId`, or null for any other account. */
findByUserId(userId: string): Promise<TransitAgent | null> {
return this.repository.findOne({ where: { userId } });
}
/**
* Case-insensitive, matching the `lower(email)` unique index. `exceptId` lets
* an update re-save its own address without colliding with itself.
*/
async existsByEmail(email: string, exceptId?: string): Promise<boolean> {
const qb = this.repository
.createQueryBuilder("ta")
.where("lower(ta.email) = lower(:email)", { email });
if (exceptId) qb.andWhere("ta.id != :exceptId", { exceptId });
return (await qb.getCount()) > 0;
}
/**
* Insert inside a caller-supplied transaction, so the agent row and the IAM
* user it points at commit together — a row referencing a user that was
* rolled back (or vice versa) is an account nobody can sign in to.
*/
createInTransaction(
manager: EntityManager,
data: Partial<TransitAgent>,
): Promise<TransitAgent> {
const repo = manager.getRepository(TransitAgent);
return repo.save(repo.create(data));
}
/** Attach an IAM account to an existing agent, inside the caller's transaction. */
async linkAccountInTransaction(
manager: EntityManager,
id: string,
data: Pick<TransitAgent, "userId" | "email" | "phoneNumber">,
): Promise<TransitAgent> {
const repo = manager.getRepository(TransitAgent);
await repo.update(id, data);
return repo.findOneOrFail({ where: { id } });
}
}

View File

@@ -0,0 +1,346 @@
import { BadRequestException, ConflictException } from "@nestjs/common";
import {
EUserStatus,
EUserType,
} from "@tria-plc/api-common/utils/enums/user.enum";
import { ResetChannel } from "../auth/dto/forgot-password.dto";
import { TransitAgentsService } from "./transit-agents.service";
/**
* The account half of a transit agent. The roster half (validity window,
* assignability) predates this and is untouched — what these lock is that
* adding a login did not make an account MANDATORY, since production is full of
* roster-only agents that must keep working.
*/
describe("TransitAgentsService accounts", () => {
const savedUser = { id: "user-1" };
let repo: {
existsByEmail: jest.Mock;
createInTransaction: jest.Mock;
linkAccountInTransaction: jest.Mock;
findById: jest.Mock;
findByUserId: jest.Mock;
create: jest.Mock;
update: jest.Mock;
};
let userRepository: { findOne: jest.Mock; update: jest.Mock };
let customerResetService: {
sendResetLinkToUser: jest.Mock;
sendResetLinkToUserOnChannels: jest.Mock;
};
let dataSource: { transaction: jest.Mock };
let userRepoInTx: { create: jest.Mock; save: jest.Mock };
let service: TransitAgentsService;
const base = {
name: "Ahmed Bourhan",
validFrom: "2026-01-01",
validTo: "2026-12-31",
};
beforeEach(() => {
userRepoInTx = {
create: jest.fn((v) => v),
save: jest.fn().mockResolvedValue(savedUser),
};
repo = {
existsByEmail: jest.fn().mockResolvedValue(false),
createInTransaction: jest.fn(async (_m, data) => ({
id: "ta-1",
...data,
})),
linkAccountInTransaction: jest.fn(async (_m, id, data) => ({
id,
...base,
isActive: true,
...data,
})),
findById: jest.fn(),
findByUserId: jest.fn(),
create: jest.fn(async (data) => ({ id: "ta-1", ...data })),
// `BaseRepository.update` re-reads the row via `findById`, so the result
// carries columns the caller never passed — `userId` above all, which is
// what decides whether IAM gets synced.
update: jest.fn(async (id, data) => ({
...(await repo.findById(id)),
id,
...data,
})),
};
userRepository = {
findOne: jest.fn().mockResolvedValue(null),
update: jest.fn(),
};
customerResetService = {
sendResetLinkToUser: jest
.fn()
.mockResolvedValue({
maskedTarget: "a**@transit.dj",
channel: ResetChannel.Email,
}),
sendResetLinkToUserOnChannels: jest
.fn()
.mockResolvedValue([
{ maskedTarget: "a**@transit.dj", channel: ResetChannel.Email },
]),
};
dataSource = {
transaction: jest.fn(async (cb) =>
cb({ getRepository: () => userRepoInTx } as never),
),
};
service = new TransitAgentsService(
repo as never,
userRepository as never,
customerResetService as never,
dataSource as never,
);
});
describe("create", () => {
it("creates a roster-only agent with no account when no email is given", async () => {
const { agent, activationSentTo } = await service.createWithInvite(base);
expect(dataSource.transaction).not.toHaveBeenCalled();
expect(
customerResetService.sendResetLinkToUserOnChannels,
).not.toHaveBeenCalled();
expect(agent.hasAccount).toBe(false);
expect(activationSentTo).toBeNull();
});
it("creates the IAM account with no password set when an email is given", async () => {
await service.createWithInvite({
...base,
email: "A.Bourhan@Transit.DJ",
});
expect(userRepoInTx.save).toHaveBeenCalledWith(
expect.objectContaining({
email: "a.bourhan@transit.dj",
username: "a.bourhan@transit.dj",
userType: EUserType.INDIVIDUAL,
hasSetPassword: false,
status: EUserStatus.ACCEPTED,
}),
);
});
it("sends the activation link only after the transaction commits", async () => {
const order: string[] = [];
dataSource.transaction.mockImplementation(
async (cb: (m: unknown) => unknown) => {
const result = await cb({ getRepository: () => userRepoInTx });
order.push("commit");
return result;
},
);
customerResetService.sendResetLinkToUserOnChannels.mockImplementation(
async () => {
order.push("send");
return [
{ maskedTarget: "a**@transit.dj", channel: ResetChannel.Email },
];
},
);
await service.createWithInvite({ ...base, email: "a@transit.dj" });
expect(order).toEqual(["commit", "send"]);
});
});
describe("invite", () => {
it("attaches an account to an existing roster-only agent and sends the link", async () => {
repo.findById.mockResolvedValue({
id: "ta-1",
...base,
isActive: true,
userId: null,
});
const { agent, activationSentTo } = await service.invite("ta-1", {
email: "a@transit.dj",
});
expect(repo.linkAccountInTransaction).toHaveBeenCalledWith(
expect.anything(),
"ta-1",
expect.objectContaining({ userId: "user-1", email: "a@transit.dj" }),
);
expect(agent.hasAccount).toBe(true);
expect(activationSentTo).toBe("a**@transit.dj");
});
it("refuses to mint a second account for an agent that already has one", async () => {
repo.findById.mockResolvedValue({
id: "ta-1",
...base,
isActive: true,
userId: "user-9",
});
await expect(
service.invite("ta-1", { email: "a@transit.dj" }),
).rejects.toThrow(ConflictException);
expect(dataSource.transaction).not.toHaveBeenCalled();
});
it("refuses credentials that already belong to another account", async () => {
repo.findById.mockResolvedValue({
id: "ta-1",
...base,
isActive: true,
userId: null,
});
userRepository.findOne.mockResolvedValue({ id: "someone-else" });
await expect(
service.invite("ta-1", { email: "a@transit.dj" }),
).rejects.toThrow(ConflictException);
});
it("texts the link as well when the number is domestic", async () => {
repo.findById.mockResolvedValue({
id: "ta-1",
...base,
isActive: true,
userId: null,
});
await service.invite("ta-1", {
email: "a@transit.dj",
phoneNumber: "+251911223344",
});
expect(
customerResetService.sendResetLinkToUserOnChannels,
).toHaveBeenCalledWith(
"user-1",
[ResetChannel.Email, ResetChannel.Phone],
expect.objectContaining({ allowWithoutCredential: true }),
);
});
it("emails only when the number is foreign — the SMS gateway is domestic-only", async () => {
repo.findById.mockResolvedValue({
id: "ta-1",
...base,
isActive: true,
userId: null,
});
await service.invite("ta-1", {
email: "a@transit.dj",
phoneNumber: "+33612345678",
});
expect(
customerResetService.sendResetLinkToUserOnChannels,
).toHaveBeenCalledWith("user-1", [ResetChannel.Email], expect.anything());
});
});
describe("update", () => {
it("mirrors an edited email onto the linked IAM account", async () => {
repo.findById.mockResolvedValue({
id: "ta-1",
...base,
isActive: true,
userId: "user-1",
});
await service.update("ta-1", { email: "New@Transit.DJ" });
expect(repo.update).toHaveBeenCalledWith(
"ta-1",
expect.objectContaining({ email: "new@transit.dj" }),
);
expect(userRepository.update).toHaveBeenCalledWith(
"user-1",
expect.objectContaining({ email: "new@transit.dj" }),
);
});
it("never writes username — it names an IAM account, not a column on this table", async () => {
repo.findById.mockResolvedValue({
id: "ta-1",
...base,
isActive: true,
userId: null,
});
await service.update("ta-1", { username: "nope" } as never);
expect(repo.update).toHaveBeenCalledWith(
"ta-1",
expect.not.objectContaining({ username: expect.anything() }),
);
});
it("leaves IAM alone for a roster-only agent", async () => {
repo.findById.mockResolvedValue({
id: "ta-1",
...base,
isActive: true,
userId: null,
});
await service.update("ta-1", { email: "a@transit.dj" });
expect(userRepository.update).not.toHaveBeenCalled();
});
});
describe("resendActivation", () => {
it("refuses for an agent that has no account yet", async () => {
repo.findById.mockResolvedValue({
id: "ta-1",
...base,
isActive: true,
userId: null,
});
await expect(
service.resendActivation("ta-1", ResetChannel.Email),
).rejects.toThrow(BadRequestException);
});
it("refuses an SMS resend to a foreign number", async () => {
repo.findById.mockResolvedValue({
id: "ta-1",
...base,
isActive: true,
userId: "user-1",
phoneNumber: "+33612345678",
});
await expect(
service.resendActivation("ta-1", ResetChannel.Phone),
).rejects.toThrow(BadRequestException);
});
it("reuses the existing account rather than minting a new one", async () => {
repo.findById.mockResolvedValue({
id: "ta-1",
...base,
isActive: true,
userId: "user-1",
email: "a@transit.dj",
});
await service.resendActivation("ta-1", ResetChannel.Email);
expect(customerResetService.sendResetLinkToUser).toHaveBeenCalledWith(
"user-1",
ResetChannel.Email,
expect.objectContaining({ allowWithoutCredential: true }),
);
expect(dataSource.transaction).not.toHaveBeenCalled();
});
});
});

View File

@@ -1,17 +1,49 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { FindOptionsOrder } from 'typeorm';
import {
BadRequestException,
ConflictException,
Injectable,
Logger,
NotFoundException,
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import {
EUserStatus,
EUserType,
} from "@tria-plc/api-common/utils/enums/user.enum";
// Subpath import (not the package root) so ts-jest can resolve it when this
// file lands in a spec's compile graph — same reason as backoffice.service.ts.
import { User } from "@tria-plc/iamapi-common/entities/iam/user/user.entity";
import {
DataSource,
EntityManager,
FindOptionsOrder,
Repository,
} from "typeorm";
import { CreateTransitAgentDto } from './dto/create-transit-agent.dto';
import { UpdateTransitAgentDto } from './dto/update-transit-agent.dto';
import { TransitAgent } from './entities/transit-agent.entity';
import { TransitAgentsRepository } from './transit-agents.repository';
import { CustomerResetService } from "../auth/customer-reset.service";
import { ResetChannel } from "../auth/dto/forgot-password.dto";
import { isDomesticPhone } from "../otp/otp.service";
import { CreateTransitAgentDto } from "./dto/create-transit-agent.dto";
import { InviteTransitAgentDto } from "./dto/invite-transit-agent.dto";
import { UpdateTransitAgentDto } from "./dto/update-transit-agent.dto";
import { TransitAgent } from "./entities/transit-agent.entity";
import { TransitAgentsRepository } from "./transit-agents.repository";
export type TransitAgentValidityStatus = 'VALID' | 'NOT_STARTED' | 'EXPIRED';
export type TransitAgentValidityStatus = "VALID" | "NOT_STARTED" | "EXPIRED";
export type TransitAgentView = TransitAgent & {
validityStatus: TransitAgentValidityStatus;
/** True once an IAM account backs this agent — i.e. it can sign in. */
hasAccount: boolean;
};
export interface InvitedTransitAgent {
agent: TransitAgentView;
/** Masked destination of the activation link, or null if none was sent. */
activationSentTo: string | null;
activationChannel: ResetChannel | null;
}
type TransitAgentListFilter = {
isActive?: boolean;
page?: number;
@@ -25,20 +57,34 @@ function todayISODate(): string {
return new Date().toISOString().slice(0, 10);
}
function validityStatus(agent: Pick<TransitAgent, 'validFrom' | 'validTo'>): TransitAgentValidityStatus {
function validityStatus(
agent: Pick<TransitAgent, "validFrom" | "validTo">,
): TransitAgentValidityStatus {
const today = todayISODate();
if (today < agent.validFrom) return 'NOT_STARTED';
if (today > agent.validTo) return 'EXPIRED';
return 'VALID';
if (today < agent.validFrom) return "NOT_STARTED";
if (today > agent.validTo) return "EXPIRED";
return "VALID";
}
function withValidityStatus(agent: TransitAgent): TransitAgentView {
return { ...agent, validityStatus: validityStatus(agent) };
return {
...agent,
validityStatus: validityStatus(agent),
hasAccount: Boolean(agent.userId),
};
}
@Injectable()
export class TransitAgentsService {
constructor(private readonly transitAgentsRepository: TransitAgentsRepository) {}
private readonly logger = new Logger(TransitAgentsService.name);
constructor(
private readonly transitAgentsRepository: TransitAgentsRepository,
@InjectRepository(User)
private readonly userRepository: Repository<User>,
private readonly customerResetService: CustomerResetService,
private readonly dataSource: DataSource,
) {}
async findAll(filter: TransitAgentListFilter = {}): Promise<{
data: TransitAgentView[];
@@ -46,10 +92,13 @@ export class TransitAgentsService {
}> {
const page = filter.page ?? 1;
const pageSize = filter.pageSize ?? 500;
const sortBy = ['name', 'validFrom', 'validTo', 'isActive'].includes(filter.sortBy ?? '')
const sortBy = ["name", "validFrom", "validTo", "isActive"].includes(
filter.sortBy ?? "",
)
? (filter.sortBy as keyof TransitAgent)
: 'name';
const sortOrder = filter.sortOrder?.toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
: "name";
const sortOrder =
filter.sortOrder?.toUpperCase() === "DESC" ? "DESC" : "ASC";
const [data, total] = await this.transitAgentsRepository.findAndCount({
where: filter.isActive === undefined ? {} : { isActive: filter.isActive },
@@ -86,12 +135,14 @@ export class TransitAgentsService {
async getAssignable(id: string): Promise<TransitAgent> {
const agent = await this.transitAgentsRepository.findById(id);
if (!agent) {
throw new BadRequestException('Selected transit officer was not found.');
throw new BadRequestException("Selected transit officer was not found.");
}
if (!agent.isActive) {
throw new BadRequestException(`${agent.name} is suspended — pick another transit officer.`);
throw new BadRequestException(
`${agent.name} is suspended — pick another transit officer.`,
);
}
if (validityStatus(agent) !== 'VALID') {
if (validityStatus(agent) !== "VALID") {
throw new BadRequestException(
`${agent.name}'s validity window has expired — pick another transit officer or extend their dates.`,
);
@@ -99,38 +150,364 @@ export class TransitAgentsService {
return agent;
}
async create(dto: CreateTransitAgentDto): Promise<TransitAgentView> {
if (dto.validTo < dto.validFrom) {
throw new BadRequestException('Valid-to date must be on or after valid-from date.');
/**
* Create an IAM account for a transit agent, inside the caller's transaction.
*
* Follows `ShippingLineCompaniesService.register` — same entities, same shape
* — including its one deliberate difference from employee creation: no
* `UserCredential` row is written and `hasSetPassword` stays false, so the
* agent must come through the activation link. Staff never handle a password.
*/
private async createIamAccount(
manager: EntityManager,
args: {
name: string;
email: string;
username: string;
phoneNumber?: string;
},
): Promise<string> {
const userRepo = manager.getRepository(User);
const user = await userRepo.save(
userRepo.create({
email: args.email,
username: args.username,
phoneNumber: args.phoneNumber,
name: { en: args.name },
userType: EUserType.INDIVIDUAL,
isActive: true,
// No credential row: the account has no password until the activation
// link is used. `hasSetPassword` must stay false or the portal treats
// the account as ready to sign in with a password that does not exist.
hasSetPassword: false,
status: EUserStatus.ACCEPTED,
}),
);
return user.id as string;
}
/**
* Normalize and validate the account fields shared by create and invite, and
* refuse credentials that already belong to somebody.
*/
private async prepareAccountFields(
dto: { email: string; phoneNumber?: string; username?: string },
exceptAgentId?: string,
) {
const email = dto.email.trim().toLowerCase();
const username = (dto.username?.trim() || email).toLowerCase();
const phoneNumber = dto.phoneNumber?.trim() || undefined;
if (
await this.transitAgentsRepository.existsByEmail(email, exceptAgentId)
) {
throw new ConflictException(
`A transit agent with email ${email} already exists`,
);
}
const agent = await this.transitAgentsRepository.create({
// An existing IAM account means these credentials already belong to a
// customer, a shipping line or an employee. Reusing it would let one login
// resolve to two different account kinds, so this is refused rather than
// merged.
const existingUser = await this.userRepository.findOne({
where: [{ email }, { username }],
select: { id: true },
});
if (existingUser) {
throw new ConflictException("email_or_username_already_in_use");
}
return { email, username, phoneNumber };
}
/**
* Create a transit agent.
*
* With no `email` this is the pre-existing behaviour: a GL-assignable roster
* entry with no login, which is what production is full of. With an `email`
* the IAM account and the agent row are created in one transaction and the
* activation link goes out.
*/
async create(dto: CreateTransitAgentDto): Promise<TransitAgentView> {
return (await this.createWithInvite(dto)).agent;
}
/** {@link create}, also reporting where the activation link went. */
async createWithInvite(
dto: CreateTransitAgentDto,
): Promise<InvitedTransitAgent> {
if (dto.validTo < dto.validFrom) {
throw new BadRequestException(
"Valid-to date must be on or after valid-from date.",
);
}
const base = {
name: dto.name.trim(),
validFrom: dto.validFrom,
validTo: dto.validTo,
isActive: dto.isActive ?? true,
};
if (!dto.email) {
// Roster-only agent — no account, nothing to send.
const agent = await this.transitAgentsRepository.create(base);
return {
agent: withValidityStatus(agent),
activationSentTo: null,
activationChannel: null,
};
}
const { email, username, phoneNumber } = await this.prepareAccountFields({
email: dto.email,
phoneNumber: dto.phoneNumber,
username: dto.username,
});
return withValidityStatus(agent);
const agent = await this.dataSource.transaction(async (manager) => {
const userId = await this.createIamAccount(manager, {
name: base.name,
email,
username,
phoneNumber,
});
return this.transitAgentsRepository.createInTransaction(manager, {
...base,
userId,
email,
phoneNumber: phoneNumber ?? null,
});
});
// Outside the transaction on purpose: a delivery failure must not roll back
// a registered agent. The link is resendable, and the account is already
// valid without it.
const activation = await this.sendActivationLink(agent);
return {
agent: withValidityStatus(agent),
activationSentTo: activation?.maskedTarget ?? null,
activationChannel: activation?.channel ?? null,
};
}
async update(id: string, dto: UpdateTransitAgentDto): Promise<TransitAgentView> {
/**
* Give an EXISTING agent a portal login — the path for the roster entries
* already in production. Creates the IAM account, attaches it, and sends the
* activation link.
*/
async invite(
id: string,
dto: InviteTransitAgentDto,
): Promise<InvitedTransitAgent> {
const current = await this.transitAgentsRepository.findById(id);
if (!current) {
throw new NotFoundException(`Transit agent ${id} not found`);
}
if (current.userId) {
// Already has an account — resending is `resendActivation`, which reuses
// the existing user instead of minting a second one for the same person.
throw new ConflictException(
"This transit agent already has a portal account — resend the activation link instead.",
);
}
const { email, username, phoneNumber } = await this.prepareAccountFields(
dto,
id,
);
const agent = await this.dataSource.transaction(async (manager) => {
const userId = await this.createIamAccount(manager, {
name: current.name,
email,
username,
phoneNumber,
});
return this.transitAgentsRepository.linkAccountInTransaction(
manager,
id,
{
userId,
email,
phoneNumber: phoneNumber ?? null,
},
);
});
const activation = await this.sendActivationLink(agent);
return {
agent: withValidityStatus(agent),
activationSentTo: activation?.maskedTarget ?? null,
activationChannel: activation?.channel ?? null,
};
}
/**
* Send the activation link.
*
* Email always goes out — it is the only channel guaranteed to reach a
* foreign-registered officer. SMS is sent in addition when the number is
* domestic, since the gateway silently drops anything else. Both carry the
* SAME single-use ticket: minting retires earlier tickets, so two mints would
* kill the email link the moment the SMS went out.
*
* Reports the email send, as that is the one that is always attempted.
*/
async sendActivationLink(agent: TransitAgent) {
if (!agent.userId) return null;
const scope = `transit agent ${agent.id}`;
const channels = [ResetChannel.Email];
if (agent.phoneNumber && isDomesticPhone(agent.phoneNumber)) {
channels.push(ResetChannel.Phone);
}
const sent = await this.customerResetService.sendResetLinkToUserOnChannels(
agent.userId,
channels,
{ scope, allowWithoutCredential: true },
);
const emailed = sent.find((s) => s.channel === ResetChannel.Email) ?? null;
if (!emailed) {
this.logger.error(
`Activation email not sent for transit agent ${agent.id} — no reachable address`,
);
}
if (
channels.includes(ResetChannel.Phone) &&
!sent.some((s) => s.channel === ResetChannel.Phone)
) {
this.logger.warn(`Activation SMS not sent for transit agent ${agent.id}`);
}
return emailed;
}
async resendActivation(id: string, channel: ResetChannel) {
const agent = await this.transitAgentsRepository.findById(id);
if (!agent) {
throw new NotFoundException("Transit agent not found");
}
if (!agent.userId) {
throw new BadRequestException(
"This transit agent has no portal account yet — invite them first.",
);
}
if (
channel === ResetChannel.Phone &&
(!agent.phoneNumber || !isDomesticPhone(agent.phoneNumber))
) {
throw new BadRequestException(
"This transit agent has no domestic phone number — the SMS gateway cannot reach it",
);
}
const sent = await this.customerResetService.sendResetLinkToUser(
agent.userId,
channel,
{
scope: `transit agent ${agent.id}`,
allowWithoutCredential: true,
},
);
if (!sent) {
throw new NotFoundException(
`No active account with ${
channel === ResetChannel.Email ? "an email address" : "a phone number"
} for this transit agent`,
);
}
return sent;
}
/** The transit agent signed in as `userId`, or null for any other account. */
findByUserId(userId: string): Promise<TransitAgent | null> {
return this.transitAgentsRepository.findByUserId(userId);
}
async update(
id: string,
dto: UpdateTransitAgentDto,
): Promise<TransitAgentView> {
const current = await this.findById(id);
const nextValidFrom = dto.validFrom ?? current.validFrom;
const nextValidTo = dto.validTo ?? current.validTo;
if (nextValidTo < nextValidFrom) {
throw new BadRequestException('Valid-to date must be on or after valid-from date.');
throw new BadRequestException(
"Valid-to date must be on or after valid-from date.",
);
}
// `username` only ever names an IAM account, and it is chosen once at
// account creation. Accepting it here (PartialType inherits it from the
// create DTO) would write a column that does not exist on this table.
const { username: _ignoredUsername, email, phoneNumber, ...rest } = dto;
const contact: Partial<TransitAgent> = {};
if (email !== undefined) {
const normalized = email.trim().toLowerCase();
if (await this.transitAgentsRepository.existsByEmail(normalized, id)) {
throw new ConflictException(
`A transit agent with email ${normalized} already exists`,
);
}
contact.email = normalized;
}
if (phoneNumber !== undefined) {
contact.phoneNumber = phoneNumber.trim() || null;
}
const updated = await this.transitAgentsRepository.update(id, {
...dto,
...rest,
...contact,
...(dto.name ? { name: dto.name.trim() } : {}),
});
if (!updated) {
throw new NotFoundException(`Transit agent ${id} not found`);
}
// Keep the IAM account in step. Without this, an agent whose address was
// corrected here would still receive its activation link at the old one —
// the reset service reads the address off `iam.users`, not off this row.
if (
updated.userId &&
(contact.email !== undefined || contact.phoneNumber !== undefined)
) {
await this.syncIamContact(updated);
}
return withValidityStatus(updated);
}
/**
* Mirror an edited email/phone onto the linked IAM account.
*
* Best-effort: a failure here must not fail the agent edit that already
* committed, but it does mean the two are out of step, so it is logged loudly
* rather than swallowed. Re-running the edit retries it.
*/
private async syncIamContact(agent: TransitAgent): Promise<void> {
if (!agent.userId) return;
try {
await this.userRepository.update(agent.userId, {
...(agent.email ? { email: agent.email } : {}),
phoneNumber: agent.phoneNumber ?? undefined,
});
} catch (error) {
this.logger.error(
`Transit agent ${agent.id} contact updated but IAM user ${agent.userId} was not — ` +
`activation links will still go to the old address: ${String(error)}`,
);
}
}
async remove(id: string): Promise<void> {
await this.findById(id);
await this.transitAgentsRepository.softDelete(id);