This commit is contained in:
David Arranz 2026-04-14 17:16:00 +02:00
parent bcf719ed4f
commit 588aacd48a
22 changed files with 313 additions and 128 deletions

View File

@ -1,5 +1,5 @@
const toSafeNumber = (value: number | null | undefined): number => { const toSafeNumber = (value: string | number | null | undefined): number => {
return value ?? 0; return Number(value ?? 0);
}; };
export const NumberHelper = { export const NumberHelper = {

View File

@ -1,28 +1,54 @@
type PickFormDirtyValuesOptions<T extends Record<string, any>> = {
replaceTopLevelArrayKeys?: Array<keyof T>;
};
/** /**
* Extrae solo los valores marcados como "dirty" por react-hook-form, * Extrae solo los valores marcados como "dirty" por react-hook-form,
* respetando la estructura anidada de dirtyFields. * respetando la estructura anidada de dirtyFields.
*
* Regla especial opcional: Si una key de primer nivel
* está configurada en `replaceTopLevelArrayKeys` y tiene
* cualquier dirty anidado, se incluye el array completo
* en lugar de intentar hacer patch recursivo
*/ */
export function pickFormDirtyValues<T extends Record<string, any>>( export function pickFormDirtyValues<T extends Record<string, any>>(
values: T, values: T,
dirtyFields: Partial<Record<keyof T, any>> dirtyFields: Partial<Record<keyof T, any>>,
options?: PickFormDirtyValuesOptions<T>
): Partial<T> { ): Partial<T> {
const result: Partial<T> = {}; const result: Partial<T> = {};
const replaceTopLevelArrayKeys = options?.replaceTopLevelArrayKeys ?? [];
for (const key in dirtyFields) { for (const key in dirtyFields) {
if (!Object.hasOwn(dirtyFields, key)) continue; if (!Object.hasOwn(dirtyFields, key)) continue;
const isDirty = dirtyFields[key]; const typedKey = key as keyof T;
const value = values[key]; const isDirty = dirtyFields[typedKey];
const value = values[typedKey];
if (isDirty === true) { if (isDirty === true) {
// 🔹 Campo "leaf": se ha tocado → copiar valor result[typedKey] = value;
result[key] = value; continue;
} else if (typeof isDirty === "object" && isDirty !== null) { }
// 🔹 Campo anidado: recursión
const nested = pickFormDirtyValues(value, isDirty); if (typeof isDirty !== "object" || isDirty === null) {
if (Object.keys(nested).length > 0) { continue;
result[key] = nested as any; }
}
const shouldReplaceTopLevelArray =
replaceTopLevelArrayKeys.includes(typedKey) &&
Array.isArray(value) &&
formHasAnyDirty(isDirty);
if (shouldReplaceTopLevelArray) {
result[typedKey] = value;
continue;
}
const nested = pickFormDirtyValues(value, isDirty as Partial<Record<keyof typeof value, any>>);
if (Object.keys(nested).length > 0) {
result[typedKey] = nested as T[keyof T];
} }
} }
@ -37,7 +63,7 @@ export function formHasAnyDirty(dirtyFields: Partial<Record<string, any>> | bool
if (dirtyFields === false || dirtyFields == null) return false; if (dirtyFields === false || dirtyFields == null) return false;
if (typeof dirtyFields === "object") { if (typeof dirtyFields === "object") {
return Object.values(dirtyFields).some((v) => formHasAnyDirty(v)); return Object.values(dirtyFields).some((value) => formHasAnyDirty(value));
} }
return false; return false;

View File

@ -3,13 +3,12 @@ import type { ICatalogs } from "@erp/core/api";
import { import {
CreateProformaInputMapper, CreateProformaInputMapper,
type ICreateProformaInputMapper, type ICreateProformaInputMapper,
type IUpdateProformaInputMapper,
UpdateProformaInputMapper, UpdateProformaInputMapper,
} from "../mappers"; } from "../mappers";
export interface IProformaInputMappers { export interface IProformaInputMappers {
createInputMapper: ICreateProformaInputMapper; createInputMapper: ICreateProformaInputMapper;
updateInputMapper: IUpdateProformaInputMapper; updateInputMapper: UpdateProformaInputMapper;
} }
export const buildProformaInputMappers = (catalogs: ICatalogs): IProformaInputMappers => { export const buildProformaInputMappers = (catalogs: ICatalogs): IProformaInputMappers => {

View File

@ -1,7 +1,7 @@
import type { ITransactionManager } from "@erp/core/api"; import type { ITransactionManager } from "@erp/core/api";
import type { IIssuedInvoicePublicServices } from "../../issued-invoices"; import type { IIssuedInvoicePublicServices } from "../../issued-invoices";
import type { ICreateProformaInputMapper, IUpdateProformaInputMapper } from "../mappers"; import type { ICreateProformaInputMapper, UpdateProformaInputMapper } from "../mappers";
import type { import type {
IProformaCreator, IProformaCreator,
IProformaFinder, IProformaFinder,
@ -97,7 +97,7 @@ export function buildIssueProformaUseCase(deps: {
export function buildUpdateProformaUseCase(deps: { export function buildUpdateProformaUseCase(deps: {
updater: IProformaUpdater; updater: IProformaUpdater;
dtoMapper: IUpdateProformaInputMapper; dtoMapper: UpdateProformaInputMapper;
fullSnapshotBuilder: IProformaFullSnapshotBuilder; fullSnapshotBuilder: IProformaFullSnapshotBuilder;
transactionManager: ITransactionManager; transactionManager: ITransactionManager;
}) { }) {

View File

@ -1,3 +1,5 @@
import { NumberHelper } from "@erp/core";
import { DiscountPercentage } from "@erp/core/api";
import { import {
CurrencyCode, CurrencyCode,
DomainError, DomainError,
@ -13,7 +15,14 @@ import {
import { Result, isNullishOrEmpty, toPatchField } from "@repo/rdx-utils"; import { Result, isNullishOrEmpty, toPatchField } from "@repo/rdx-utils";
import type { UpdateProformaByIdRequestDTO } from "../../../../common/dto"; import type { UpdateProformaByIdRequestDTO } from "../../../../common/dto";
import { InvoiceSerie, type ProformaPatchProps } from "../../../domain"; import {
InvoiceSerie,
ItemAmount,
ItemDescription,
ItemQuantity,
type ProformaItemPatchProps,
type ProformaPatchProps,
} from "../../../domain";
/** /**
* UpdateProformaPropsMapper * UpdateProformaPropsMapper
@ -37,7 +46,10 @@ export interface IUpdateProformaInputMapper {
} }
export class UpdateProformaInputMapper implements IUpdateProformaInputMapper { export class UpdateProformaInputMapper implements IUpdateProformaInputMapper {
public map(dto: UpdateProformaByIdRequestDTO, params: { companyId: UniqueID }) { public map(
dto: UpdateProformaByIdRequestDTO,
params: { companyId: UniqueID }
): Result<ProformaPatchProps> {
try { try {
const errors: ValidationErrorDetail[] = []; const errors: ValidationErrorDetail[] = [];
const props: ProformaPatchProps = {}; const props: ProformaPatchProps = {};
@ -128,15 +140,149 @@ export class UpdateProformaInputMapper implements IUpdateProformaInputMapper {
); );
}); });
if (errors.length > 0) { if (dto.items) {
return Result.fail( const itemsProps = this.mapItemsProps(dto, { errors });
new ValidationErrorCollection("Proforma invoice props mapping failed (update)", errors) props.items = itemsProps;
);
} }
this.throwIfValidationErrors(errors);
return Result.ok(props); return Result.ok(props);
} catch (err: unknown) { } catch (err: unknown) {
return Result.fail(new DomainError("Proforma invoice props mapping failed", { cause: err })); return Result.fail(new DomainError("Proforma proforma props mapping failed", { cause: err }));
} }
} }
private throwIfValidationErrors(errors: ValidationErrorDetail[]): void {
if (errors.length > 0) {
throw new ValidationErrorCollection("Customer proforma props mapping failed", errors);
}
}
private mapItemsProps(
dto: UpdateProformaByIdRequestDTO,
params: {
errors: ValidationErrorDetail[];
}
): ProformaItemPatchProps[] {
const itemsProps: ProformaItemPatchProps[] = [];
dto.items?.forEach((item, index) => {
const description = extractOrPushError(
maybeFromNullableResult(item.description, (v) => ItemDescription.create(v)),
`items[${index}].description`,
params.errors
);
const quantity = extractOrPushError(
maybeFromNullableResult(item.quantity, (v) =>
ItemQuantity.create({ value: NumberHelper.toSafeNumber(v) })
),
`items[${index}].quantity`,
params.errors
);
const unitAmount = extractOrPushError(
maybeFromNullableResult(item.unit_amount, (v) =>
ItemAmount.create({ value: NumberHelper.toSafeNumber(v) })
),
`items[${index}].unit_amount`,
params.errors
);
const discountPercentage = extractOrPushError(
maybeFromNullableResult(item.item_discount_percentage, (v) =>
DiscountPercentage.create({ value: NumberHelper.toSafeNumber(v.value) })
),
`items[${index}].discount_percentage`,
params.errors
);
/*const taxes = this.mapTaxesProps(item.taxes, {
itemIndex: index,
errors: params.errors,
});*/
this.throwIfValidationErrors(params.errors);
itemsProps.push({
description: description!,
quantity: quantity!,
unitAmount: unitAmount!,
itemDiscountPercentage: discountPercentage!,
//taxes,
});
});
return itemsProps;
}
/* Devuelve las propiedades de los impustos de una línea de detalle */
/*private mapTaxesProps(
taxesDTO: Pick<ProformaItemRequestDTO, "taxes">["taxes"],
params: { itemIndex: number; errors: ValidationErrorDetail[] }
): ProformaItemTaxesProps {
const { itemIndex, errors } = params;
const taxesProps: ProformaItemTaxesProps = {
iva: Maybe.none(),
retention: Maybe.none(),
rec: Maybe.none(),
};
// Normaliza: "" -> []
const taxStrCodes = taxesDTO
.split(",")
.map((s) => s.trim())
.filter((s) => s.length > 0);
taxStrCodes.forEach((strCode, taxIndex) => {
const taxResult = Tax.createFromCode(strCode, this.taxCatalog);
if (!taxResult.isSuccess) {
errors.push({
path: `items[${itemIndex}].taxes[${taxIndex}]`,
message: taxResult.error.message,
});
return;
}
const tax = taxResult.data;
if (tax.isVATLike()) {
if (taxesProps.iva.isSome()) {
errors.push({
path: `items[${itemIndex}].taxes`,
message: "Multiple taxes for group VAT are not allowed",
});
}
taxesProps.iva = Maybe.some(tax);
}
if (tax.isRetention()) {
if (taxesProps.retention.isSome()) {
errors.push({
path: `items[${itemIndex}].taxes`,
message: "Multiple taxes for group retention are not allowed",
});
}
taxesProps.retention = Maybe.some(tax);
}
if (tax.isRec()) {
if (taxesProps.rec.isSome()) {
errors.push({
path: `items[${itemIndex}].taxes`,
message: "Multiple taxes for group rec are not allowed",
});
}
taxesProps.rec = Maybe.some(tax);
}
});
this.throwIfValidationErrors(errors);
return taxesProps;
}*/
} }

View File

@ -1,7 +1,7 @@
import type { UniqueID } from "@repo/rdx-ddd"; import type { UniqueID } from "@repo/rdx-ddd";
import { Result } from "@repo/rdx-utils"; import { Result } from "@repo/rdx-utils";
import { type IProformaCreateProps, Proforma } from "../../../domain"; import { Proforma, type ProformaCreateProps } from "../../../domain";
import type { IProformaRepository } from "../repositories"; import type { IProformaRepository } from "../repositories";
import type { IProformaNumberGenerator } from "./proforma-number-generator.interface"; import type { IProformaNumberGenerator } from "./proforma-number-generator.interface";
@ -9,7 +9,7 @@ import type { IProformaNumberGenerator } from "./proforma-number-generator.inter
export interface IProformaCreatorParams { export interface IProformaCreatorParams {
companyId: UniqueID; companyId: UniqueID;
id: UniqueID; id: UniqueID;
props: Omit<IProformaCreateProps, "invoiceNumber">; props: Omit<ProformaCreateProps, "invoiceNumber">;
transaction: unknown; transaction: unknown;
} }

View File

@ -8,7 +8,7 @@ export interface IProformaUpdater {
update(params: { update(params: {
companyId: UniqueID; companyId: UniqueID;
id: UniqueID; id: UniqueID;
props: ProformaPatchProps; patchProps: ProformaPatchProps;
transaction: unknown; transaction: unknown;
}): Promise<Result<Proforma, Error>>; }): Promise<Result<Proforma, Error>>;
} }
@ -27,12 +27,12 @@ export class ProformaUpdater implements IProformaUpdater {
async update(params: { async update(params: {
companyId: UniqueID; companyId: UniqueID;
id: UniqueID; id: UniqueID;
props: ProformaPatchProps; patchProps: ProformaPatchProps;
transaction: unknown; transaction: unknown;
}): Promise<Result<Proforma, Error>> { }): Promise<Result<Proforma, Error>> {
const { companyId, id, props, transaction } = params; const { companyId, id, patchProps, transaction } = params;
console.log("props => ", props); console.log("patchProps => ", patchProps);
// Recuperar agregado existente // Recuperar agregado existente
const existingResult = await this.repository.getByIdInCompany(companyId, id, transaction); const existingResult = await this.repository.getByIdInCompany(companyId, id, transaction);
@ -44,14 +44,12 @@ export class ProformaUpdater implements IProformaUpdater {
const proforma = existingResult.data; const proforma = existingResult.data;
// Aplicar cambios en el agregado // Aplicar cambios en el agregado
const updateResult = proforma.update(props); const updateResult = proforma.update(patchProps);
if (updateResult.isFailure) { if (updateResult.isFailure) {
return Result.fail(updateResult.error); return Result.fail(updateResult.error);
} }
console.log(proforma.operationDate);
// Persistir cambios // Persistir cambios
const saveResult = await this.repository.update(proforma, transaction); const saveResult = await this.repository.update(proforma, transaction);

View File

@ -4,7 +4,7 @@ import { Result } from "@repo/rdx-utils";
import type { UpdateProformaByIdRequestDTO } from "../../../../common"; import type { UpdateProformaByIdRequestDTO } from "../../../../common";
import type { ProformaPatchProps } from "../../../domain"; import type { ProformaPatchProps } from "../../../domain";
import type { IUpdateProformaInputMapper } from "../mappers"; import type { UpdateProformaInputMapper } from "../mappers";
import type { IProformaUpdater } from "../services"; import type { IProformaUpdater } from "../services";
import type { IProformaFullSnapshotBuilder } from "../snapshot-builders"; import type { IProformaFullSnapshotBuilder } from "../snapshot-builders";
@ -15,14 +15,14 @@ type UpdateProformaUseCaseInput = {
}; };
type UpdateProformaUseCaseDeps = { type UpdateProformaUseCaseDeps = {
dtoMapper: IUpdateProformaInputMapper; dtoMapper: UpdateProformaInputMapper;
updater: IProformaUpdater; updater: IProformaUpdater;
fullSnapshotBuilder: IProformaFullSnapshotBuilder; fullSnapshotBuilder: IProformaFullSnapshotBuilder;
transactionManager: ITransactionManager; transactionManager: ITransactionManager;
}; };
export class UpdateProformaUseCase { export class UpdateProformaUseCase {
private readonly dtoMapper: IUpdateProformaInputMapper; private readonly dtoMapper: UpdateProformaInputMapper;
private readonly updater: IProformaUpdater; private readonly updater: IProformaUpdater;
private readonly fullSnapshotBuilder: IProformaFullSnapshotBuilder; private readonly fullSnapshotBuilder: IProformaFullSnapshotBuilder;
private readonly transactionManager: ITransactionManager; private readonly transactionManager: ITransactionManager;
@ -60,7 +60,7 @@ export class UpdateProformaUseCase {
const updateResult = await this.updater.update({ const updateResult = await this.updater.update({
companyId, companyId,
id: proformaId, id: proformaId,
props: patchProps, patchProps,
transaction, transaction,
}); });

View File

@ -24,6 +24,7 @@ import {
type IProformaItemCreateProps, type IProformaItemCreateProps,
type IProformaItems, type IProformaItems,
ProformaItem, ProformaItem,
type ProformaItemPatchProps,
ProformaItems, ProformaItems,
} from "../entities"; } from "../entities";
import { ProformaItemMismatch } from "../errors"; import { ProformaItemMismatch } from "../errors";
@ -56,6 +57,10 @@ export interface IProformaCreateProps {
globalDiscountPercentage: DiscountPercentage; globalDiscountPercentage: DiscountPercentage;
} }
export type ProformaPatchProps = Partial<Omit<IProformaCreateProps, "companyId" | "items">> & {
items?: ProformaItemPatchProps[];
};
export interface IProformaTotals { export interface IProformaTotals {
subtotalAmount: InvoiceAmount; subtotalAmount: InvoiceAmount;
@ -100,10 +105,6 @@ export interface IProforma {
totals(): IProformaTotals; totals(): IProformaTotals;
} }
export type ProformaPatchProps = Partial<Omit<IProformaCreateProps, "companyId" | "items">> & {
//items?: ProformaItems;
};
export type InternalProformaProps = Omit<IProformaCreateProps, "items">; export type InternalProformaProps = Omit<IProformaCreateProps, "items">;
export class Proforma extends AggregateRoot<InternalProformaProps> implements IProforma { export class Proforma extends AggregateRoot<InternalProformaProps> implements IProforma {
@ -156,9 +157,47 @@ export class Proforma extends AggregateRoot<InternalProformaProps> implements IP
return new Proforma(props, items, id); return new Proforma(props, items, id);
} }
private initializeItems(itemsProps: IProformaItemCreateProps[]): Result<void, Error> { // Mutabilidad
public update(patchProps: ProformaPatchProps): Result<Proforma, Error> {
const { items, ...otherProps } = patchProps;
const candidateProps: InternalProformaProps = {
...this.props,
...otherProps,
};
// Validacciones
// Aplicar cambios
Object.assign(this.props, candidateProps);
// Reemplazo de items (si se proporciona)
if (items) {
this.initializeItems(items);
}
return Result.ok();
}
private initializeItems(
itemsProps: IProformaItemCreateProps[] | ProformaItemPatchProps[]
): Result<void, Error> {
this._items.reset();
for (const [index, itemProps] of itemsProps.entries()) { for (const [index, itemProps] of itemsProps.entries()) {
const itemResult = ProformaItem.create(itemProps); const { languageCode, currencyCode, globalDiscountPercentage, ...restProps } = {
languageCode: this.languageCode,
currencyCode: this.currencyCode,
globalDiscountPercentage: this.globalDiscountPercentage,
...itemProps,
};
const itemResult = ProformaItem.create({
...restProps,
languageCode,
currencyCode,
globalDiscountPercentage,
});
if (itemResult.isFailure) { if (itemResult.isFailure) {
return Result.fail(itemResult.error); return Result.fail(itemResult.error);
@ -246,20 +285,6 @@ export class Proforma extends AggregateRoot<InternalProformaProps> implements IP
return this.paymentMethod.isSome(); return this.paymentMethod.isSome();
} }
// Mutabilidad
public update(patch: ProformaPatchProps): Result<Proforma, Error> {
const candidateProps: InternalProformaProps = {
...this.props,
...patch,
};
// Validacciones
Object.assign(this.props, candidateProps);
return Result.ok();
}
public issue(): Result<void, Error> { public issue(): Result<void, Error> {
if (!this.props.status.canTransitionTo("issued")) { if (!this.props.status.canTransitionTo("issued")) {
return Result.fail( return Result.fail(
@ -274,7 +299,6 @@ export class Proforma extends AggregateRoot<InternalProformaProps> implements IP
this.props.status = InvoiceStatus.issued(); this.props.status = InvoiceStatus.issued();
return Result.ok(); return Result.ok();
} }
// Cálculos // Cálculos
/** /**
@ -326,25 +350,6 @@ export class Proforma extends AggregateRoot<InternalProformaProps> implements IP
return Result.ok(); return Result.ok();
} }
/*public updateItem(itemId: UniqueID, props: IProformaItemProps): Result<void, Error> {
const item = this._items.find((i) => i.id.equals(itemId));
if (!item) {
return Result.fail(new Error("Item not found"));
}
return item.update(props);
}*/
/*public removeItem(itemId: UniqueID): Result<void, Error> {
const removed = this._items.removeWhere(i => i.id.equals(itemId));
if (!removed) {
return Result.fail(new Error("Item not found"));
}
return Result.ok();
}*/
// Helpers // Helpers
/** /**

View File

@ -42,6 +42,11 @@ export interface IProformaItemCreateProps {
currencyCode: CurrencyCode; // Para cálculos y formateos de moneda currencyCode: CurrencyCode; // Para cálculos y formateos de moneda
} }
export type ProformaItemPatchProps = Omit<
IProformaItemCreateProps,
"globalDiscountPercentage" | "languageCode" | "currencyCode"
>;
export interface IProformaItemTotals { export interface IProformaItemTotals {
subtotalAmount: ItemAmount; subtotalAmount: ItemAmount;

View File

@ -17,12 +17,12 @@ import {
import { Result } from "@repo/rdx-utils"; import { Result } from "@repo/rdx-utils";
import { import {
type IProformaCreateProps,
IssuedInvoiceItem, IssuedInvoiceItem,
ItemAmount, ItemAmount,
ItemDescription, ItemDescription,
ItemQuantity, ItemQuantity,
type Proforma, type Proforma,
type ProformaCreateProps,
} from "../../../../../../domain"; } from "../../../../../../domain";
export interface ICustomerInvoiceItemDomainMapper export interface ICustomerInvoiceItemDomainMapper
@ -62,7 +62,7 @@ export class CustomerInvoiceItemDomainMapper
const { errors, index, attributes } = params as { const { errors, index, attributes } = params as {
index: number; index: number;
errors: ValidationErrorDetail[]; errors: ValidationErrorDetail[];
attributes: Partial<IProformaCreateProps>; attributes: Partial<ProformaCreateProps>;
}; };
const itemId = extractOrPushError( const itemId = extractOrPushError(
@ -157,7 +157,7 @@ export class CustomerInvoiceItemDomainMapper
const { errors, index } = params as { const { errors, index } = params as {
index: number; index: number;
errors: ValidationErrorDetail[]; errors: ValidationErrorDetail[];
attributes: Partial<IProformaCreateProps>; attributes: Partial<ProformaCreateProps>;
}; };
// 1) Valores escalares (atributos generales) // 1) Valores escalares (atributos generales)

View File

@ -20,12 +20,12 @@ import { Maybe, Result, isNullishOrEmpty } from "@repo/rdx-utils";
import { import {
CustomerInvoiceItems, CustomerInvoiceItems,
type IProformaCreateProps,
InvoiceNumber, InvoiceNumber,
InvoicePaymentMethod, InvoicePaymentMethod,
InvoiceSerie, InvoiceSerie,
InvoiceStatus, InvoiceStatus,
Proforma, Proforma,
type ProformaCreateProps,
} from "../../../../../../domain"; } from "../../../../../../domain";
import type { import type {
CustomerInvoiceCreationAttributes, CustomerInvoiceCreationAttributes,
@ -249,7 +249,7 @@ export class CustomerInvoiceDomainMapper
items: itemsResults.data.getAll(), items: itemsResults.data.getAll(),
}); });
const invoiceProps: IProformaCreateProps = { const invoiceProps: ProformaCreateProps = {
companyId: attributes.companyId!, companyId: attributes.companyId!,
isProforma: attributes.isProforma, isProforma: attributes.isProforma,

View File

@ -16,9 +16,9 @@ import {
import { Maybe, Result } from "@repo/rdx-utils"; import { Maybe, Result } from "@repo/rdx-utils";
import { import {
type IProformaCreateProps,
InvoiceRecipient, InvoiceRecipient,
type Proforma, type Proforma,
type ProformaCreateProps,
} from "../../../../../../domain"; } from "../../../../../../domain";
import type { CustomerInvoiceModel } from "../../../../sequelize"; import type { CustomerInvoiceModel } from "../../../../sequelize";
@ -34,7 +34,7 @@ export class InvoiceRecipientDomainMapper {
const { errors, attributes } = params as { const { errors, attributes } = params as {
errors: ValidationErrorDetail[]; errors: ValidationErrorDetail[];
attributes: Partial<IProformaCreateProps>; attributes: Partial<ProformaCreateProps>;
}; };
const { isProforma } = attributes; const { isProforma } = attributes;

View File

@ -12,8 +12,8 @@ import {
import { Maybe, Result } from "@repo/rdx-utils"; import { Maybe, Result } from "@repo/rdx-utils";
import { import {
type IProformaCreateProps,
type Proforma, type Proforma,
type ProformaCreateProps,
VerifactuRecord, VerifactuRecord,
VerifactuRecordEstado, VerifactuRecordEstado,
} from "../../../../../../domain"; } from "../../../../../../domain";
@ -43,7 +43,7 @@ export class CustomerInvoiceVerifactuDomainMapper
): Result<Maybe<VerifactuRecord>, Error> { ): Result<Maybe<VerifactuRecord>, Error> {
const { errors, attributes } = params as { const { errors, attributes } = params as {
errors: ValidationErrorDetail[]; errors: ValidationErrorDetail[];
attributes: Partial<IProformaCreateProps>; attributes: Partial<ProformaCreateProps>;
}; };
if (!source) { if (!source) {

View File

@ -17,7 +17,6 @@ import { Maybe, Result } from "@repo/rdx-utils";
import type { CreateProformaItemRequestDTO, CreateProformaRequestDTO } from "../../../../../common"; import type { CreateProformaItemRequestDTO, CreateProformaRequestDTO } from "../../../../../common";
import { import {
type IProformaCreateProps,
type IProformaItemCreateProps, type IProformaItemCreateProps,
InvoiceNumber, InvoiceNumber,
InvoicePaymentMethod, InvoicePaymentMethod,
@ -29,6 +28,7 @@ import {
ItemAmount, ItemAmount,
ItemDescription, ItemDescription,
ItemQuantity, ItemQuantity,
type ProformaCreateProps,
} from "../../../../domain"; } from "../../../../domain";
/** /**
@ -149,7 +149,7 @@ export class CreateProformaRequestMapper {
); );
} }
const proformaProps: Omit<IProformaCreateProps, "items"> & { items: IProformaItemCreateProps[] } = { const proformaProps: Omit<ProformaCreateProps, "items"> & { items: IProformaItemCreateProps[] } = {
companyId, companyId,
status: defaultStatus!, status: defaultStatus!,

View File

@ -16,12 +16,12 @@ import {
import { Result } from "@repo/rdx-utils"; import { Result } from "@repo/rdx-utils";
import { import {
type IProformaCreateProps,
type IProformaItemCreateProps, type IProformaItemCreateProps,
ItemAmount, ItemAmount,
ItemDescription, ItemDescription,
ItemQuantity, ItemQuantity,
type Proforma, type Proforma,
type ProformaCreateProps,
ProformaItem, ProformaItem,
ProformaItemTaxes, ProformaItemTaxes,
type ProformaItemTaxesProps, type ProformaItemTaxesProps,
@ -58,7 +58,7 @@ export class SequelizeProformaItemDomainMapper extends SequelizeDomainMapper<
const { errors, index, parent } = params as { const { errors, index, parent } = params as {
index: number; index: number;
errors: ValidationErrorDetail[]; errors: ValidationErrorDetail[];
parent: Partial<IProformaCreateProps>; parent: Partial<ProformaCreateProps>;
}; };
const itemId = extractOrPushError( const itemId = extractOrPushError(
@ -139,7 +139,7 @@ export class SequelizeProformaItemDomainMapper extends SequelizeDomainMapper<
const { errors, index } = params as { const { errors, index } = params as {
index: number; index: number;
errors: ValidationErrorDetail[]; errors: ValidationErrorDetail[];
parent: Partial<IProformaCreateProps>; parent: Partial<ProformaCreateProps>;
}; };
// 1) Valores escalares (atributos generales) // 1) Valores escalares (atributos generales)

View File

@ -14,7 +14,7 @@ import {
} from "@repo/rdx-ddd"; } from "@repo/rdx-ddd";
import { Maybe, Result } from "@repo/rdx-utils"; import { Maybe, Result } from "@repo/rdx-utils";
import { type IProformaCreateProps, InvoiceRecipient } from "../../../../../../domain"; import { InvoiceRecipient, type ProformaCreateProps } from "../../../../../../domain";
import type { CustomerInvoiceModel } from "../../../../../common"; import type { CustomerInvoiceModel } from "../../../../../common";
export class SequelizeProformaRecipientDomainMapper { export class SequelizeProformaRecipientDomainMapper {
@ -28,7 +28,7 @@ export class SequelizeProformaRecipientDomainMapper {
const { errors, parent } = params as { const { errors, parent } = params as {
errors: ValidationErrorDetail[]; errors: ValidationErrorDetail[];
parent: Partial<IProformaCreateProps>; parent: Partial<ProformaCreateProps>;
}; };
const _name = source.current_customer.name; const _name = source.current_customer.name;

View File

@ -4,11 +4,14 @@ import { z } from "zod/v4";
export const UpdateProformaItemRequestSchema = z.object({ export const UpdateProformaItemRequestSchema = z.object({
id: z.uuid(), id: z.uuid(),
position: z.string(), position: z.string(),
description: z.string().optional(), description: z.string().default(""),
quantity: NumericStringSchema.optional(), quantity: NumericStringSchema.default(""),
unit_amount: NumericStringSchema.optional(), unit_amount: NumericStringSchema.default(""),
item_discount_percentage: PercentageSchema.optional(), item_discount_percentage: PercentageSchema.default({
taxes: z.string().optional(), value: "0",
scale: "2",
}),
taxes: z.string().default(""),
}); });
export const UpdateProformaByIdParamsRequestSchema = z.object({ export const UpdateProformaByIdParamsRequestSchema = z.object({

View File

@ -1,3 +1,4 @@
import { formHasAnyDirty } from "@erp/core/client";
import { useHookForm } from "@erp/core/hooks"; import { useHookForm } from "@erp/core/hooks";
import type { CustomerSelectionOption } from "@erp/customers"; import type { CustomerSelectionOption } from "@erp/customers";
import { showErrorToast, showSuccessToast, showWarningToast } from "@repo/rdx-ui/helpers"; import { showErrorToast, showSuccessToast, showWarningToast } from "@repo/rdx-ui/helpers";
@ -114,12 +115,19 @@ export const useUpdateProformaController = (
return; return;
} }
console.log(form.formState.dirtyFields);
if (!formHasAnyDirty(form.formState.dirtyFields)) {
showWarningToast(
t("proformas.update.no_changes.title"),
t("proformas.update.no_changes.message")
);
return;
}
const previousData = proformaData; const previousData = proformaData;
const patchData = buildProformaUpdatePatch(formData, form.formState.dirtyFields); const patchData = buildProformaUpdatePatch(formData, form.formState.dirtyFields);
console.log(patchData);
const params = buildUpdateProformaByIdParams(proformaId, patchData); const params = buildUpdateProformaByIdParams(proformaId, patchData);
try { try {
@ -132,7 +140,7 @@ export const useUpdateProformaController = (
keepDirty: false, keepDirty: false,
}); });
setSelectedCustomer(mapProformaToSelectedCustomer(proformaData)); setSelectedCustomer(mapProformaToSelectedCustomer(updated));
if (options?.successToasts !== false) { if (options?.successToasts !== false) {
showSuccessToast( showSuccessToast(
@ -153,6 +161,8 @@ export const useUpdateProformaController = (
{ keepDirty: false } { keepDirty: false }
); );
setSelectedCustomer(previousData ? mapProformaToSelectedCustomer(previousData) : null);
if (options?.errorToasts !== false) { if (options?.errorToasts !== false) {
showErrorToast(t("proformas.update.error.title"), normalizedError.message); showErrorToast(t("proformas.update.error.title"), normalizedError.message);
} }

View File

@ -1,14 +0,0 @@
import type { ProformaItemUpdateForm, ProformaItemUpdatePatch } from "../entities";
export const buildProformaItemsUpdatePatch = (
items: ProformaItemUpdateForm[]
): ProformaItemUpdatePatch[] => {
return items.map((item, index) => ({
id: item.id,
position: index,
description: item.description.trim(),
quantity: item.quantity,
unitAmount: item.unitAmount,
itemDiscountPercentage: item.itemDiscountPercentage,
}));
};

View File

@ -3,8 +3,6 @@ import type { FieldNamesMarkedBoolean } from "react-hook-form";
import type { ProformaUpdateForm, ProformaUpdatePatch } from "../entities"; import type { ProformaUpdateForm, ProformaUpdatePatch } from "../entities";
import { buildProformaItemsUpdatePatch } from "./build-proforma-items-update-patch";
export const buildProformaUpdatePatch = ( export const buildProformaUpdatePatch = (
formData: ProformaUpdateForm, formData: ProformaUpdateForm,
dirtyFields: FieldNamesMarkedBoolean<ProformaUpdateForm> dirtyFields: FieldNamesMarkedBoolean<ProformaUpdateForm>
@ -13,10 +11,7 @@ export const buildProformaUpdatePatch = (
return {}; return {};
} }
const itemsPatch = buildProformaItemsUpdatePatch(formData.items); return pickFormDirtyValues(formData, dirtyFields, {
replaceTopLevelArrayKeys: ["items"],
return { }) satisfies ProformaUpdatePatch;
...pickFormDirtyValues(formData, dirtyFields),
items: itemsPatch,
} as ProformaUpdatePatch;
}; };

View File

@ -23,12 +23,24 @@ export const buildUpdateProformaByIdParams = (
language_code: patch.languageCode, language_code: patch.languageCode,
currency_code: patch.currencyCode, currency_code: patch.currencyCode,
items: patch.items?.map((item) => ({
id: item.id,
position: String(item.position),
description: item.description,
quantity: item.quantity === null ? undefined : String(item.quantity),
unit_amount: item.unitAmount === null ? undefined : String(item.unitAmount),
item_discount_percentage:
item.itemDiscountPercentage === null
? undefined
: { value: String(item.itemDiscountPercentage), scale: "2" },
})),
}; };
return { return {
id, id,
data: { data: Object.fromEntries(
...Object.fromEntries(Object.entries(data).filter(([, value]) => value !== undefined)), Object.entries(data).filter(([, value]) => value !== undefined)
}, ) satisfies UpdateProformaByIdParams["data"],
}; };
}; };