84 lines
2.4 KiB
TypeScript
84 lines
2.4 KiB
TypeScript
import { ValidationErrorCollection, ValidationErrorDetail } from "@erp/core/api";
|
|
import { CreateCustomerInvoiceCommandDTO } from "@erp/customer-invoices/common/dto";
|
|
import { Result } from "@repo/rdx-utils";
|
|
import {
|
|
CustomerInvoiceItem,
|
|
CustomerInvoiceItemDescription,
|
|
CustomerInvoiceItemDiscount,
|
|
CustomerInvoiceItemQuantity,
|
|
CustomerInvoiceItemUnitAmount,
|
|
} from "../../domain";
|
|
import { extractOrPushError } from "./extract-or-push-error";
|
|
import { hasNoUndefinedFields } from "./has-no-undefined-fields";
|
|
|
|
export function mapDTOToCustomerInvoiceItemsProps(
|
|
dtoItems: Pick<CreateCustomerInvoiceCommandDTO, "items">["items"]
|
|
): Result<CustomerInvoiceItem[], ValidationErrorCollection> {
|
|
const errors: ValidationErrorDetail[] = [];
|
|
const items: CustomerInvoiceItem[] = [];
|
|
|
|
dtoItems.forEach((item, index) => {
|
|
const path = (field: string) => `items[${index}].${field}`;
|
|
|
|
const description = extractOrPushError(
|
|
CustomerInvoiceItemDescription.create(item.description),
|
|
path("description"),
|
|
errors
|
|
);
|
|
|
|
const quantity = extractOrPushError(
|
|
CustomerInvoiceItemQuantity.create({
|
|
amount: item.quantity.amount,
|
|
scale: item.quantity.scale,
|
|
}),
|
|
path("quantity"),
|
|
errors
|
|
);
|
|
|
|
const unitPrice = extractOrPushError(
|
|
CustomerInvoiceItemUnitAmount.create({
|
|
value: item.unitPrice.amount,
|
|
scale: item.unitPrice.scale,
|
|
currency_code: item.unitPrice.currency,
|
|
}),
|
|
path("unit_price"),
|
|
errors
|
|
);
|
|
|
|
const discount = extractOrPushError(
|
|
CustomerInvoiceItemDiscount.create({
|
|
value: item.discount.amount,
|
|
scale: item.discount.scale,
|
|
}),
|
|
path("discount"),
|
|
errors
|
|
);
|
|
|
|
if (errors.length === 0) {
|
|
const itemProps = {
|
|
description: description,
|
|
quantity: quantity,
|
|
unitPrice: unitPrice,
|
|
discount: discount,
|
|
};
|
|
|
|
if (hasNoUndefinedFields(itemProps)) {
|
|
// Validar y crear el item de factura
|
|
const itemOrError = CustomerInvoiceItem.create(itemProps);
|
|
|
|
if (itemOrError.isSuccess) {
|
|
items.push(itemOrError.data);
|
|
} else {
|
|
errors.push({ path: `items[${index}]`, message: itemOrError.error.message });
|
|
}
|
|
}
|
|
}
|
|
|
|
if (errors.length > 0) {
|
|
return Result.fail(new ValidationErrorCollection(errors));
|
|
}
|
|
});
|
|
|
|
return Result.ok(items);
|
|
}
|