import { BaseRepository } from "@edr/api-common"; import { Injectable } from "@nestjs/common"; import { InjectRepository } from "@nestjs/typeorm"; import { IsNull, Repository } from "typeorm"; import { CargoType } from "../rule-engine/entities/cargo-type.entity"; import { BulkTemplateDirection, ContractTemplate, } from "./entities/contract-template.entity"; @Injectable() export class ContractTemplatesRepository extends BaseRepository { constructor( @InjectRepository(ContractTemplate) repository: Repository, ) { super(repository); } findByCode(code: string): Promise { return this.repository.findOne({ where: { code } }); } override findAll(): Promise { return this.repository.find({ relations: { cargoType: true }, order: { code: "ASC" }, }); } findByCargoCombo( cargoTypeId: string, tradeDirection: BulkTemplateDirection, withCustoms: boolean | null, ): Promise { return this.repository.findOne({ where: { cargoTypeId, tradeDirection, withCustoms: withCustoms ?? IsNull() }, }); } /** * The active bulk template covering this cargo type: written against the * cargo type itself or against its parent group (the two are mutually * exclusive, so at most one row matches). Intercity templates carry no * customs variant, so they are matched on a null flag. */ findActiveBulkTemplate( cargoTypeId: string, tradeDirection: BulkTemplateDirection, withCustoms: boolean | null, ): Promise { return this.repository .createQueryBuilder("t") .where("t.is_active = true") .andWhere("t.trade_direction = :tradeDirection", { tradeDirection }) .andWhere( withCustoms === null ? "t.with_customs IS NULL" : "t.with_customs = :withCustoms", withCustoms === null ? {} : { withCustoms }, ) .andWhere( `(t.cargo_type_id = :cargoTypeId OR t.cargo_type_id = ( SELECT c.parent_group_id FROM freight.cargo_types c WHERE c.id = :cargoTypeId AND c.deleted_at IS NULL ))`, { cargoTypeId }, ) .getOne(); } findCargoType(id: string): Promise { return this.repository.manager .getRepository(CargoType) .findOne({ where: { id } }); } async saveTemplate(template: ContractTemplate): Promise { return this.repository.save(template); } }