PROFORMAS DELETE

This commit is contained in:
David Arranz 2026-04-05 21:02:00 +02:00
parent 8bbbe93d87
commit e32dbfa3f1
13 changed files with 210 additions and 186 deletions

View File

@ -13,8 +13,10 @@ if (rootElement) {
createRoot(rootElement).render(
<StrictMode>
<ThemeProvider defaultTheme="light" storageKey="vite-ui-theme">
<App />
<TailwindIndicator />
<>
<App />
<TailwindIndicator />
</>
</ThemeProvider>
</StrictMode>
);

View File

@ -1,60 +1,52 @@
// proformas/delete/controllers/use-delete-proforma-dialog-controller.ts
import { showErrorToast, showSuccessToast } from "@repo/rdx-ui/helpers";
import React from "react";
import * as React from "react";
import { useTranslation } from "../../../i18n";
import { type ProformaListRow, useDeleteProformaMutation } from "../../shared";
import type { DeleteProformaByIdParams } from "../../shared";
import { useProformaDeleteMutation } from "../../shared";
import type { DeleteProformaTarget } from "../entities";
type ConfirmStep = "initial" | "second";
interface DeleteProformaDialogState {
open: boolean;
proformas: ProformaListRow[];
isSubmitting: boolean;
requiresSecondConfirm: boolean;
confirmStep: "initial" | "second";
targets: DeleteProformaTarget[];
confirmStep: ConfirmStep;
}
const INITIAL_STATE: DeleteProformaDialogState = {
open: false,
proformas: [],
isSubmitting: false,
requiresSecondConfirm: false,
targets: [],
confirmStep: "initial",
};
const SECOND_CONFIRM_THRESHOLD = 5;
const buildDeleteParams = (target: DeleteProformaTarget): DeleteProformaByIdParams => ({
id: target.id,
});
function canSubmitDelete(isSubmitting: boolean, proformas: ProformaListRow[]): boolean {
return !isSubmitting && proformas.length > 0;
}
const getProformaLabel = (target: DeleteProformaTarget) => target.reference || `#${target.id}`;
function shouldMoveToSecondConfirmStep(
requiresSecondConfirm: boolean,
confirmStep: "initial" | "second"
): boolean {
return requiresSecondConfirm && confirmStep === "initial";
}
export function useDeleteProformaDialogController() {
export const useDeleteProformaDialogController = () => {
const { t } = useTranslation();
const { deleteProforma } = useDeleteProformaMutation();
const deleteMutation = useProformaDeleteMutation();
const [state, setState] = React.useState<DeleteProformaDialogState>(INITIAL_STATE);
const { isSubmitting, proformas, requiresSecondConfirm, confirmStep } = state;
const openDialog = React.useCallback((proformas: ProformaListRow[]) => {
const requiresSecondConfirm = proformas.length > SECOND_CONFIRM_THRESHOLD;
const openDialog = React.useCallback((targets: DeleteProformaTarget[]) => {
if (targets.length === 0) return;
setState({
open: true,
proformas,
isSubmitting: false,
requiresSecondConfirm,
targets,
confirmStep: "initial",
});
}, []);
const closeDialog = React.useCallback(() => {
if (deleteMutation.isPending) return;
setState(INITIAL_STATE);
}, []);
}, [deleteMutation.isPending]);
const moveToSecondConfirmStep = React.useCallback(() => {
setState((current) => ({
@ -63,124 +55,109 @@ export function useDeleteProformaDialogController() {
}));
}, []);
const deleteSelectedProformas = React.useCallback(
async (proformas: ProformaListRow[]) => {
const results = await Promise.allSettled(
proformas.map((proforma) =>
deleteProforma({
proformaId: proforma.id,
})
)
);
const successCount = results.filter((result) => result.status === "fulfilled").length;
const errorCount = results.length - successCount;
return {
successCount,
errorCount,
};
},
[deleteProforma]
);
const notifyDeleteResult = React.useCallback(
(proformas: ProformaListRow[], successCount: number, errorCount: number) => {
if (proformas.length === 1 && successCount === 1) {
const proforma = proformas[0];
const notifySuccess = React.useCallback(
(targets: DeleteProformaTarget[]) => {
if (targets.length === 1) {
showSuccessToast(
t("pages.proformas.delete.successTitle"),
t("pages.proformas.delete.successSingleMessage", {
reference: proforma.reference || `#${proforma.id}`,
})
);
} else if (successCount > 0) {
showSuccessToast(
t("pages.proformas.delete.successTitle"),
t("pages.proformas.delete.successMultipleMessage", {
count: successCount,
reference: getProformaLabel(targets[0]),
})
);
return;
}
if (errorCount > 0) {
showSuccessToast(
t("pages.proformas.delete.successTitle"),
t("pages.proformas.delete.successMultipleMessage", {
count: targets.length,
})
);
},
[t]
);
const notifyPartialError = React.useCallback(
(targets: DeleteProformaTarget[], errorCount: number) => {
if (targets.length === 1) {
showErrorToast(
t("pages.proformas.delete.errorTitle"),
proformas.length === 1
? t("pages.proformas.delete.errorSingleMessage")
: t("pages.proformas.delete.errorMultipleMessage", {
count: errorCount,
})
t("pages.proformas.delete.errorSingleMessage")
);
return;
}
showErrorToast(
t("pages.proformas.delete.errorTitle"),
t("pages.proformas.delete.errorMultipleMessage", {
count: errorCount,
})
);
},
[t]
);
const submitDelete = React.useCallback(async () => {
setState((current) => ({
...current,
isSubmitting: true,
}));
const { targets } = state;
try {
const { successCount, errorCount } = await deleteSelectedProformas(proformas);
const results = await Promise.allSettled(
targets.map((target) => deleteMutation.mutateAsync(buildDeleteParams(target)))
);
notifyDeleteResult(proformas, successCount, errorCount);
const successCount = results.filter((result) => result.status === "fulfilled").length;
const errorCount = results.length - successCount;
if (errorCount === 0) {
closeDialog();
return;
if (successCount > 0) {
const fulfilledTargets = targets.filter((_, index) => results[index]?.status === "fulfilled");
const rejectedTargets = targets.filter((_, index) => results[index]?.status === "rejected");
if (fulfilledTargets.length > 0) {
notifySuccess(fulfilledTargets);
}
setState((current) => ({
...current,
isSubmitting: false,
}));
if (rejectedTargets.length > 0) {
notifyPartialError(targets, rejectedTargets.length);
return;
}
}
if (errorCount > 0) {
notifyPartialError(targets, errorCount);
return;
}
setState(INITIAL_STATE);
}, [deleteMutation, notifyPartialError, notifySuccess, state]);
const confirmDelete = React.useCallback(async () => {
if (deleteMutation.isPending || state.targets.length === 0) {
return;
}
if (state.confirmStep === "initial") {
moveToSecondConfirmStep();
return;
}
try {
await submitDelete();
} catch {
showErrorToast(
t("pages.proformas.delete.errorTitle"),
t("pages.proformas.delete.errorUnexpectedMessage")
);
setState((current) => ({
...current,
isSubmitting: false,
}));
}
}, [closeDialog, deleteSelectedProformas, notifyDeleteResult, proformas, t]);
const confirmDelete = React.useCallback(async () => {
if (!canSubmitDelete(isSubmitting, proformas)) {
return;
}
if (shouldMoveToSecondConfirmStep(requiresSecondConfirm, confirmStep)) {
moveToSecondConfirmStep();
return;
}
await submitDelete();
}, [
moveToSecondConfirmStep,
submitDelete,
isSubmitting,
proformas,
requiresSecondConfirm,
confirmStep,
]);
}, [deleteMutation.isPending, moveToSecondConfirmStep, state, submitDelete, t]);
return {
open: state.open,
proformas: state.proformas,
isSubmitting: state.isSubmitting,
requiresSecondConfirm: state.requiresSecondConfirm,
targets: state.targets,
isSubmitting: deleteMutation.isPending,
isSecondConfirmStep: state.confirmStep === "second",
isBulkDelete: state.proformas.length > 1,
isBulkDelete: state.targets.length > 1,
openDialog,
closeDialog,
confirmDelete,
};
}
};

View File

@ -0,0 +1,4 @@
export interface DeleteProformaTarget {
id: string;
reference?: string;
}

View File

@ -0,0 +1 @@
export * from "./delete-proforma-target.entity";

View File

@ -10,46 +10,60 @@ import {
} from "@repo/shadcn-ui/components";
import { useTranslation } from "../../../../i18n";
import type { ProformaListRow } from "../../../shared";
import type { DeleteProformaTarget } from "../../entities";
interface DeleteProformaDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
proformas: ProformaListRow[];
targets: DeleteProformaTarget[];
isSubmitting: boolean;
onConfirm: () => void;
requiresSecondConfirm: boolean;
isSecondConfirmStep: boolean;
}
export function DeleteProformaDialog({
const getTargetLabel = (target: DeleteProformaTarget) => target.reference || `#${target.id}`;
export const DeleteProformaDialog = ({
open,
onOpenChange,
proformas,
targets,
isSubmitting,
onConfirm,
requiresSecondConfirm,
isSecondConfirmStep,
}: DeleteProformaDialogProps) {
}: DeleteProformaDialogProps) => {
const { t } = useTranslation();
const total = proformas.length;
const total = targets.length;
const isSingle = total === 1;
const firstProforma = proformas[0];
const firstTarget = targets[0];
const title = isSecondConfirmStep
? t("proformas.delete_proforma_dialog.second_confirm_title", { count: total })
: isSingle
? t("proformas.delete_proforma_dialog.single_title", {
reference: firstProforma?.reference ?? `#${firstProforma?.id}`,
? isSingle
? t("components.delete_proforma_dialog.second_confirm_single_title", {
reference: getTargetLabel(firstTarget),
})
: t("proformas.delete_proforma_dialog.multiple_title", { count: total });
: t("components.delete_proforma_dialog.second_confirm_multiple_title", {
count: total,
})
: isSingle
? t("components.delete_proforma_dialog.single_title", {
reference: getTargetLabel(firstTarget),
})
: t("components.delete_proforma_dialog.multiple_title", {
count: total,
});
const description = isSecondConfirmStep
? t("proformas.delete_proforma_dialog.second_confirm_description", { count: total })
? isSingle
? t("components.delete_proforma_dialog.second_confirm_single_description")
: t("components.delete_proforma_dialog.second_confirm_multiple_description", {
count: total,
})
: isSingle
? t("proformas.delete_proforma_dialog.single_description")
: t("proformas.delete_proforma_dialog.multiple_description", { count: total });
? t("components.delete_proforma_dialog.single_description")
: t("components.delete_proforma_dialog.multiple_description", {
count: total,
});
return (
<AlertDialog
@ -65,45 +79,39 @@ export function DeleteProformaDialog({
<AlertDialogDescription>{description}</AlertDialogDescription>
</AlertDialogHeader>
{!isSecondConfirmStep && total > 1 && (
{!isSecondConfirmStep && total > 1 ? (
<div className="mt-4 max-h-48 overflow-y-auto rounded-md border p-3 text-sm">
<ul className="space-y-1">
{proformas.map((proforma) => (
<li className="flex justify-between text-muted-foreground" key={proforma.id}>
<span>
{t("proformas.delete_proforma_dialog.list_item", {
reference: proforma.reference ?? `#${proforma.id}`,
})}
</span>
{targets.map((target) => (
<li className="text-muted-foreground" key={target.id}>
{t("components.delete_proforma_dialog.list_item", {
reference: getTargetLabel(target),
})}
</li>
))}
</ul>
</div>
)}
) : null}
<AlertDialogFooter className="sm:justify-between">
<Button disabled={isSubmitting} onClick={() => onOpenChange(false)} variant="outline">
{t("proformas.delete_proforma_dialog.cancel")}
{t("components.delete_proforma_dialog.cancel")}
</Button>
<Button disabled={isSubmitting} onClick={onConfirm} variant="destructive">
<Button disabled={isSubmitting || total === 0} onClick={onConfirm} variant="destructive">
{isSubmitting ? (
<>
<Spinner className="mr-2 size-4" />
{t("proformas.delete_proforma_dialog.deleting")}
{t("components.delete_proforma_dialog.deleting")}
</>
) : isSecondConfirmStep ? (
t("proformas.delete_proforma_dialog.confirm_mass_delete")
) : isSingle ? (
t("proformas.delete_proforma_dialog.delete")
) : requiresSecondConfirm ? (
t("proformas.delete_proforma_dialog.continue")
t("components.delete_proforma_dialog.confirm_delete")
) : (
t("proformas.delete_proforma_dialog.delete_plural")
t("components.delete_proforma_dialog.continue")
)}
</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
};

View File

@ -0,0 +1,18 @@
import type { Proforma, ProformaListRow } from "../../shared";
import type { DeleteProformaTarget } from "../entities";
export const buildDeleteProformaTargetFromListRow = (
proforma: ProformaListRow
): DeleteProformaTarget => ({
id: proforma.id,
reference: proforma.reference,
});
export const buildDeleteProformaTargetFromEntity = (proforma: Proforma): DeleteProformaTarget => ({
id: proforma.id,
reference: proforma.reference,
});
export const buildDeleteProformaTargetsFromListRows = (
proformas: ProformaListRow[]
): DeleteProformaTarget[] => proformas.map(buildDeleteProformaTargetFromListRow);

View File

@ -0,0 +1 @@
export * from "./build-delete-proforma-targets";

View File

@ -32,7 +32,7 @@ export const useListProformasController = () => {
pageNumber: pageIndex,
pageSize,
order: "desc",
orderBy: "invoiceDate",
orderBy: "invoice_date",
filters:
statusFilter === "all" ? [] : [{ field: "status", operator: "eq", value: statusFilter }],
}),

View File

@ -22,6 +22,7 @@ interface ProformasGridProps {
export const ProformasGrid = ({
data,
loading,
fetching,
columns,
pageIndex,
pageSize,
@ -32,7 +33,7 @@ export const ProformasGrid = ({
const { t } = useTranslation();
const { items, totalItems } = data || { items: [], totalItems: 0 };
if (loading)
if (loading) {
return (
<SkeletonDataTable
columns={columns.length}
@ -41,6 +42,7 @@ export const ProformasGrid = ({
showFooter
/>
);
}
return (
<DataTable
@ -51,7 +53,6 @@ export const ProformasGrid = ({
manualPagination
onPageChange={onPageChange}
onPageSizeChange={onPageSizeChange}
onRowClick={(row, _index) => onRowClick?.(row.id)}
pageIndex={pageIndex}
pageSize={pageSize}
totalItems={totalItems}

View File

@ -96,7 +96,6 @@ export function useProformasGridColumns(
return (
<div className="flex items-center gap-2">
<ProformaStatusBadge status={proforma.status} />
{/* Enlace discreto a factura real */}
{isIssued && (
<TooltipProvider>
@ -105,12 +104,13 @@ export function useProformasGridColumns(
<Button
asChild
className="size-6 text-foreground hover:text-primary"
onClick={() => actionHandlers.onLinkedInvoiceClick?.(proforma)}
size="icon"
variant="ghost"
>
<ExternalLinkIcon />
<span className="sr-only">Ver factura {invoiceId}</span>
<a href={`/facturas/${invoiceId}`}>
<ExternalLinkIcon />
<span className="sr-only">Ver factura {invoiceId}</span>
</a>
</Button>
</TooltipTrigger>
<TooltipContent>Ver factura {invoiceId}</TooltipContent>
@ -148,8 +148,6 @@ export function useProformasGridColumns(
>
{proforma.recipient.name}
</button>
<br />
<div className="text-xs text-muted-foreground">{proforma.recipient.tin}</div>
</div>
);

View File

@ -15,8 +15,9 @@ import { FilterIcon, PlusIcon } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "../../../../i18n";
import { ChangeStatusDialog } from "../../../change-status";
import { ProformaIssueDialog } from "../../../issue-proforma";
import { DeleteProformaDialog, useDeleteProformaDialogController } from "../../../delete";
import { buildDeleteProformaTargetFromListRow } from "../../../delete/utils";
import type { ProformaListRow } from "../../../shared";
import { useListProformasPageController } from "../../controllers";
import { ProformaSummaryPanel, ProformasGrid, useProformasGridColumns } from "../blocks";
@ -25,12 +26,17 @@ export const ListProformasPage = () => {
const navigate = useNavigate();
const { listCtrl, panelCtrl } = useListProformasPageController();
const deleteDialogCtrl = useDeleteProformaDialogController();
const handleDeleteProforma = (proforma: ProformaListRow) => {
deleteDialogCtrl.openDialog([buildDeleteProformaTargetFromListRow(proforma)]);
};
const columns = useProformasGridColumns({
onEditClick: (proforma) => navigate(`/proformas/${proforma.id}/edit`),
onIssueClick: handleIssueProforma,
//onIssueClick: handleIssueProforma,
onDeleteClick: handleDeleteProforma,
onChangeStatusClick: handleChangeStatusProforma,
//onChangeStatusClick: handleChangeStatusProforma,
});
const isPanelOpen = panelCtrl.panelState.isOpen;
@ -143,32 +149,18 @@ export const ListProformasPage = () => {
<div className="flex min-h-0 flex-1 overflow-hidden">{listContent}</div>
)}
<>
{/* Emitir factura */}
<ProformaIssueDialog
isSubmitting={issueDialogCtrl.isSubmitting}
onConfirm={issueDialogCtrl.confirmIssue}
onOpenChange={(open) => !open && issueDialogCtrl.closeDialog()}
open={issueDialogCtrl.open}
proforma={issueDialogCtrl.proforma}
/>
{/* Cambiar estado */}
<ChangeStatusDialog
isSubmitting={changeStatusDialogCtrl.isSubmitting}
onConfirm={changeStatusDialogCtrl.confirmChangeStatus}
onOpenChange={(open) => !open && changeStatusDialogCtrl.closeDialog()}
open={changeStatusDialogCtrl.open}
proformas={changeStatusDialogCtrl.proformas} // ← recibe el status seleccionado
/>
{/* Eliminar */}
<DeleteProformaDialog
isSecondConfirmStep={deleteDialogCtrl.isSecondConfirmStep}
isSubmitting={deleteDialogCtrl.isSubmitting}
onConfirm={deleteDialogCtrl.confirmDelete}
onOpenChange={(open) => !open && deleteDialogCtrl.closeDialog()}
onOpenChange={(open) => {
if (!open) {
deleteDialogCtrl.closeDialog();
}
}}
open={deleteDialogCtrl.open}
proformas={deleteDialogCtrl.proformas}
requireSecondConfirm={true}
targets={deleteDialogCtrl.targets}
/>
</>
</AppContent>

View File

@ -192,6 +192,16 @@
}
},
"components": {
"delete_proforma_dialog": {
"single_title": "Eliminar proforoma",
"single_description": "",
"second_confirm_single_title": "Confirmar eliminación",
"second_confirm_single_description": "",
"confirm_delete": "Confirmar eliminación",
"deleting": "Eliminando...",
"cancel": "Cancelar",
"continue": "Eliminar"
},
"entity_selector": {
"close": "Close",
"select_entity": "Select entity",

View File

@ -194,6 +194,18 @@
}
},
"components": {
"delete_proforma_dialog": {
"single_title": "Eliminar proforoma",
"single_description": "",
"second_confirm_single_title": "Confirmar eliminación",
"second_confirm_single_description": "",
"multiple_description": "",
"confirm_delete": "Confirmar eliminación",
"deleting": "Eliminando...",
"cancel": "Cancelar",
"continue": "Eliminar",
"list_item": ""
},
"entity_selector": {
"close": "Cerrar",
"select_entity": "Seleccionar entidad",