Uecko_ERP/modules/customers/src/api/application/create-customer/create-customer.use-case.ts

58 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-08-11 17:49:52 +00:00
import { DuplicateEntityError, ITransactionManager } from "@erp/core/api";
import { CreateCustomerCommandDTO } from "@erp/customers/common/dto";
import { Result } from "@repo/rdx-utils";
import { Transaction } from "sequelize";
import { ICustomerService } from "../../domain";
import { mapDTOToCustomerProps } from "../helpers";
import { CreateCustomersAssembler } from "./assembler";
2025-08-11 17:49:52 +00:00
export class CreateCustomerUseCase {
constructor(
private readonly service: ICustomerService,
private readonly transactionManager: ITransactionManager,
private readonly assembler: CreateCustomersAssembler
2025-08-11 17:49:52 +00:00
) {}
public execute(dto: CreateCustomerCommandDTO) {
2025-08-21 07:44:07 +00:00
const customerPropsOrError = mapDTOToCustomerProps(dto);
2025-08-11 17:49:52 +00:00
2025-08-21 07:44:07 +00:00
if (customerPropsOrError.isFailure) {
return Result.fail(customerPropsOrError.error);
2025-08-11 17:49:52 +00:00
}
2025-08-21 07:44:07 +00:00
const { props, id } = customerPropsOrError.data;
2025-08-11 17:49:52 +00:00
2025-08-21 07:44:07 +00:00
const customerOrError = this.service.build(props, id);
2025-08-11 17:49:52 +00:00
2025-08-21 07:44:07 +00:00
if (customerOrError.isFailure) {
return Result.fail(customerOrError.error);
2025-08-11 17:49:52 +00:00
}
2025-08-21 07:44:07 +00:00
const newCustomer = customerOrError.data;
2025-08-11 17:49:52 +00:00
return this.transactionManager.complete(async (transaction: Transaction) => {
try {
const duplicateCheck = await this.service.existsById(id, transaction);
if (duplicateCheck.isFailure) {
return Result.fail(duplicateCheck.error);
}
if (duplicateCheck.data) {
return Result.fail(new DuplicateEntityError("Customer", id.toString()));
}
2025-08-21 07:44:07 +00:00
const result = await this.service.save(newCustomer, transaction);
2025-08-11 17:49:52 +00:00
if (result.isFailure) {
return Result.fail(result.error);
}
2025-08-21 07:44:07 +00:00
const viewDTO = this.assembler.toDTO(newCustomer);
2025-08-11 17:49:52 +00:00
return Result.ok(viewDTO);
} catch (error: unknown) {
return Result.fail(error as Error);
}
});
}
}