refactor contract handling to support single route per contract and improve reference generation logic

This commit is contained in:
Marshal
2026-07-06 08:42:44 +00:00
parent 1b92c57e23
commit 8336a5aff8
7 changed files with 113 additions and 31 deletions

View File

@@ -5,6 +5,7 @@ import {
Logger,
} from '@nestjs/common';
import { Readable } from 'stream';
import { insertWithGeneratedReference } from '@edr/api-common';
import type { TCurrentUser } from '@tria-plc/api-common/modules/auth/types/current-user.type';
import { ContractDocumentViewModelBuilder } from '../../contracts/contract-document-view-model.builder';
@@ -611,8 +612,11 @@ export class ContractTransitionService {
async renew(contractId: string, userId?: string): Promise<Contract> {
const source = await this.contractsService.findById(contractId);
const reference = await this.generateRenewalReference();
const renewal = await this.contractsRepository.create({
// Retry past a concurrent insert that grabbed the same CTR sequence number.
const renewal = await insertWithGeneratedReference(
() => this.generateRenewalReference(),
(reference) =>
this.contractsRepository.create({
reference,
companyId: source.companyId,
companyProfileId: source.companyProfileId,
@@ -640,7 +644,8 @@ export class ContractTransitionService {
status: 'RENEWAL_DRAFT',
clearanceStatus: 'NOT_APPLICABLE',
clearanceCycleNumber: 0,
} as never);
} as never),
);
void userId;
return this.contractsService.findById(renewal.id);
@@ -648,7 +653,7 @@ export class ContractTransitionService {
private async generateRenewalReference(): Promise<string> {
const year = new Date().getFullYear();
const count = await this.contractsRepository.countByYear(year);
return `CTR-${year}-${String(count + 1).padStart(5, '0')}`;
const seq = await this.contractsRepository.maxReferenceSequence(year);
return `CTR-${year}-${String(seq + 1).padStart(5, '0')}`;
}
}