150 lines
5.4 KiB
TypeScript
150 lines
5.4 KiB
TypeScript
|
|
import { Criteria } from "@repo/rdx-criteria/server";
|
||
|
|
import { UniqueID } from "@repo/rdx-ddd";
|
||
|
|
import { Collection, Result } from "@repo/rdx-utils";
|
||
|
|
import { Transaction } from "sequelize";
|
||
|
|
import { Customer, CustomerProps } from "../aggregates";
|
||
|
|
import { ICustomerRepository } from "../repositories";
|
||
|
|
import { ICustomerService } from "./customer-service.interface";
|
||
|
|
|
||
|
|
export class CustomerService implements ICustomerService {
|
||
|
|
constructor(private readonly repository: ICustomerRepository) {}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Construye un nuevo agregado Customer a partir de props validadas.
|
||
|
|
*
|
||
|
|
* @param props - Las propiedades ya validadas para crear la factura.
|
||
|
|
* @param id - Identificador UUID de la factura (opcional).
|
||
|
|
* @returns Result<Customer, Error> - El agregado construido o un error si falla la creación.
|
||
|
|
*/
|
||
|
|
build(props: CustomerProps, id?: UniqueID): Result<Customer, Error> {
|
||
|
|
return Customer.create(props, id);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Guarda una instancia de Customer en persistencia.
|
||
|
|
*
|
||
|
|
* @param invoice - El agregado a guardar.
|
||
|
|
* @param transaction - Transacción activa para la operación.
|
||
|
|
* @returns Result<Customer, Error> - El agregado guardado o un error si falla la operación.
|
||
|
|
*/
|
||
|
|
async save(invoice: Customer, transaction: any): Promise<Result<Customer, Error>> {
|
||
|
|
const saved = await this.repository.save(invoice, transaction);
|
||
|
|
return saved.isSuccess ? Result.ok(invoice) : Result.fail(saved.error);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
*
|
||
|
|
* Comprueba si existe o no en persistencia una factura con el ID proporcionado
|
||
|
|
*
|
||
|
|
* @param id - Identificador UUID de la factura.
|
||
|
|
* @param transaction - Transacción activa para la operación.
|
||
|
|
* @returns Result<Boolean, Error> - Existe la factura o no.
|
||
|
|
*/
|
||
|
|
|
||
|
|
async existsById(id: UniqueID, transaction?: any): Promise<Result<boolean, Error>> {
|
||
|
|
return this.repository.existsById(id, transaction);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Obtiene una colección de facturas que cumplen con los filtros definidos en un objeto Criteria.
|
||
|
|
*
|
||
|
|
* @param criteria - Objeto con condiciones de filtro, paginación y orden.
|
||
|
|
* @param transaction - Transacción activa para la operación.
|
||
|
|
* @returns Result<Collection<Customer>, Error> - Colección de facturas o error.
|
||
|
|
*/
|
||
|
|
async findByCriteria(
|
||
|
|
criteria: Criteria,
|
||
|
|
transaction?: Transaction
|
||
|
|
): Promise<Result<Collection<Customer>, Error>> {
|
||
|
|
const customersOrError = await this.repository.findByCriteria(criteria, transaction);
|
||
|
|
if (customersOrError.isFailure) {
|
||
|
|
console.error(customersOrError.error);
|
||
|
|
return Result.fail(customersOrError.error);
|
||
|
|
}
|
||
|
|
|
||
|
|
// Solo devolver usuarios activos
|
||
|
|
//const allCustomers = customersOrError.data.filter((customer) => customer.isActive);
|
||
|
|
//return Result.ok(new Collection(allCustomers));
|
||
|
|
|
||
|
|
return customersOrError;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Recupera una factura por su identificador único.
|
||
|
|
*
|
||
|
|
* @param id - Identificador UUID de la factura.
|
||
|
|
* @param transaction - Transacción activa para la operación.
|
||
|
|
* @returns Result<Customer, Error> - Factura encontrada o error.
|
||
|
|
*/
|
||
|
|
async getById(id: UniqueID, transaction?: Transaction): Promise<Result<Customer>> {
|
||
|
|
return await this.repository.findById(id, transaction);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Actualiza parcialmente una factura existente con nuevos datos.
|
||
|
|
*
|
||
|
|
* @param id - Identificador de la factura a actualizar.
|
||
|
|
* @param changes - Subconjunto de props válidas para aplicar.
|
||
|
|
* @param transaction - Transacción activa para la operación.
|
||
|
|
* @returns Result<Customer, Error> - Factura actualizada o error.
|
||
|
|
*/
|
||
|
|
async updateById(
|
||
|
|
customerId: UniqueID,
|
||
|
|
changes: Partial<CustomerProps>,
|
||
|
|
transaction?: Transaction
|
||
|
|
): Promise<Result<Customer, Error>> {
|
||
|
|
// Verificar si la factura existe
|
||
|
|
const customerOrError = await this.repository.findById(customerId, transaction);
|
||
|
|
if (customerOrError.isFailure) {
|
||
|
|
return Result.fail(new Error("Customer not found"));
|
||
|
|
}
|
||
|
|
|
||
|
|
return Result.fail(new Error("No implementado"));
|
||
|
|
|
||
|
|
/*const updatedCustomerOrError = Customer.update(customerOrError.data, data);
|
||
|
|
if (updatedCustomerOrError.isFailure) {
|
||
|
|
return Result.fail(
|
||
|
|
new Error(`Error updating customer: ${updatedCustomerOrError.error.message}`)
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
const updateCustomer = updatedCustomerOrError.data;
|
||
|
|
|
||
|
|
await this.repo.update(updateCustomer, transaction);
|
||
|
|
return Result.ok(updateCustomer);*/
|
||
|
|
}
|
||
|
|
|
||
|
|
async createCustomer(
|
||
|
|
customerId: UniqueID,
|
||
|
|
data: CustomerProps,
|
||
|
|
transaction?: Transaction
|
||
|
|
): Promise<Result<Customer, Error>> {
|
||
|
|
// Verificar si la factura existe
|
||
|
|
const customerOrError = await this.repository.findById(customerId, transaction);
|
||
|
|
if (customerOrError.isSuccess) {
|
||
|
|
return Result.fail(new Error("Customer exists"));
|
||
|
|
}
|
||
|
|
|
||
|
|
const newCustomerOrError = Customer.create(data, customerId);
|
||
|
|
if (newCustomerOrError.isFailure) {
|
||
|
|
return Result.fail(new Error(`Error creating customer: ${newCustomerOrError.error.message}`));
|
||
|
|
}
|
||
|
|
|
||
|
|
const newCustomer = newCustomerOrError.data;
|
||
|
|
|
||
|
|
await this.repository.create(newCustomer, transaction);
|
||
|
|
return Result.ok(newCustomer);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Elimina (o marca como eliminada) una factura según su ID.
|
||
|
|
*
|
||
|
|
* @param id - Identificador UUID de la factura.
|
||
|
|
* @param transaction - Transacción activa para la operación.
|
||
|
|
* @returns Result<boolean, Error> - Resultado de la operación.
|
||
|
|
*/
|
||
|
|
async deleteById(id: UniqueID, transaction?: Transaction): Promise<Result<void, Error>> {
|
||
|
|
return this.repository.deleteById(id, transaction);
|
||
|
|
}
|
||
|
|
}
|