Files
reservas/resources/js/components/recurring-conflict-modal.tsx
João Miranda fb04d71a8d
Some checks failed
tests / ci (push) Has been cancelled
first commit
2026-10-27 11:01:11 +00:00

691 lines
46 KiB
TypeScript

import {
AlertTriangle,
ArrowRight,
Calendar,
CheckCircle2,
Clock,
Package,
RefreshCw,
Trash2,
Undo2,
X,
} from 'lucide-react';
import { useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import type { Asset, OccurrenceCheck } from '@/types';
type RecurringConflictModalProps = {
isOpen: boolean;
onClose: () => void;
isLoading: boolean;
checkResult: {
occurrences: OccurrenceCheck[];
total_occurrences: number;
conflicts_count: number;
} | null;
initialAssetIds: number[];
isSubmitting: boolean;
onConfirmSubmit: (
occurrencesToSubmit: Array<{
starts_at: string;
ends_at: string;
asset_ids: number[];
}>,
) => void;
};
export function RecurringConflictModal({
isOpen,
onClose,
isLoading,
checkResult,
initialAssetIds,
isSubmitting,
onConfirmSubmit,
}: RecurringConflictModalProps) {
const [omittedIndexes, setOmittedIndexes] = useState<number[]>([]);
// Key format: `${occurrenceIndex}_${originalAssetId}` -> replacement Asset
const [replacements, setReplacements] = useState<Record<string, Asset>>({});
const [activeSelectorKey, setActiveSelectorKey] = useState<string | null>(
null,
);
const occurrences = checkResult?.occurrences ?? [];
function toggleOmit(index: number) {
setOmittedIndexes((prev) =>
prev.includes(index)
? prev.filter((i) => i !== index)
: [...prev, index],
);
}
function toggleReplacementSelector(key: string) {
setActiveSelectorKey((prev) => (prev === key ? null : key));
}
function selectReplacement(
occIndex: number,
originalAssetId: number,
replacement: Asset,
) {
setReplacements((prev) => ({
...prev,
[`${occIndex}_${originalAssetId}`]: replacement,
}));
setActiveSelectorKey(null);
}
function removeReplacement(occIndex: number, originalAssetId: number) {
setReplacements((prev) => {
const next = { ...prev };
delete next[`${occIndex}_${originalAssetId}`];
return next;
});
}
const activeOccurrences = occurrences.filter(
(_, idx) => !omittedIndexes.includes(idx),
);
const omittedCount = occurrences.length - activeOccurrences.length;
// Check if there are unresolved conflicts in active occurrences
const hasUnresolvedConflicts = occurrences.some((check, idx) => {
if (omittedIndexes.includes(idx) || !check.has_conflict) {
return false;
}
return check.conflicted_assets.some(
(ca) => !replacements[`${idx}_${ca.id}`],
);
});
const canSubmit =
!isLoading &&
activeOccurrences.length > 0 &&
!hasUnresolvedConflicts &&
!isSubmitting;
function handleConfirm() {
const payload = occurrences
.map((check, index) => ({ check, index }))
.filter(({ index }) => !omittedIndexes.includes(index))
.map(({ check, index }) => {
const finalAssetIds = initialAssetIds.map((origId) => {
const replacement = replacements[`${index}_${origId}`];
return replacement ? replacement.id : origId;
});
return {
starts_at: check.starts_at,
ends_at: check.ends_at,
asset_ids: finalAssetIds,
};
});
onConfirmSubmit(payload);
}
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="flex max-h-[90vh] max-w-3xl flex-col overflow-hidden p-0 sm:max-w-3xl">
<DialogHeader className="border-b p-6 pb-4">
<DialogTitle className="flex items-center gap-2 text-xl font-semibold">
<Calendar className="size-5 text-primary" />
Confirmação de Série Semanal
</DialogTitle>
<DialogDescription>
Análise de disponibilidade de todas as semanas da sua
requisição recorrente.
</DialogDescription>
</DialogHeader>
<div className="flex-1 space-y-6 overflow-y-auto p-6">
{isLoading ? (
<div className="space-y-4 py-16 text-center">
<RefreshCw className="mx-auto size-8 animate-spin text-primary" />
<p className="text-sm font-medium text-foreground">
A verificar disponibilidade semana a semana…
</p>
<p className="text-xs text-muted-foreground">
A cruzar horários com o inventário e requisições
existentes.
</p>
</div>
) : checkResult ? (
<>
{/* Summary banner */}
<div className="grid gap-3 sm:grid-cols-3">
<div className="rounded-lg border bg-card p-3 shadow-xs">
<span className="text-xs text-muted-foreground">
Semanas totais
</span>
<p className="text-2xl font-bold">
{checkResult.total_occurrences}
</p>
</div>
<div className="rounded-lg border bg-card p-3 shadow-xs">
<span className="text-xs text-muted-foreground">
A requisitar
</span>
<p className="text-2xl font-bold text-primary">
{activeOccurrences.length}
</p>
</div>
<div className="rounded-lg border bg-card p-3 shadow-xs">
<span className="text-xs text-muted-foreground">
Conflitos detetados
</span>
<p
className={`text-2xl font-bold ${
checkResult.conflicts_count > 0
? 'text-amber-600 dark:text-amber-500'
: 'text-emerald-600 dark:text-emerald-500'
}`}
>
{checkResult.conflicts_count}
</p>
</div>
</div>
{/* Informative alert */}
{checkResult.conflicts_count > 0 ? (
<div className="rounded-lg border border-amber-500/30 bg-amber-500/10 p-4 text-sm text-amber-900 dark:text-amber-200">
<div className="flex items-start gap-2.5">
<AlertTriangle className="mt-0.5 size-5 shrink-0 text-amber-600" />
<div className="space-y-1">
<p className="font-semibold">
Existem conflitos de horário com
outros pedidos!
</p>
<p className="text-xs leading-relaxed opacity-90">
Para cada dia assinalado,
escolha se prefere{' '}
<strong>
apagar a reserva desse dia
</strong>{' '}
(excluindo-o da série) ou{' '}
<strong>
trocar o material
</strong>{' '}
por outro equipamento
disponível.
</p>
</div>
</div>
</div>
) : (
<div className="rounded-lg border border-emerald-500/30 bg-emerald-500/10 p-4 text-sm text-emerald-900 dark:text-emerald-200">
<div className="flex items-center gap-2.5">
<CheckCircle2 className="size-4 shrink-0 text-emerald-600" />
<p className="font-semibold">
Todos os equipamentos estão
disponíveis para todas as semanas da
série!
</p>
</div>
</div>
)}
{/* Occurrence Cards List */}
<div className="space-y-3">
{occurrences.map((check, index) => {
const isOmitted =
omittedIndexes.includes(index);
const hasConflicts = check.has_conflict;
const allConflictsResolved =
hasConflicts &&
check.conflicted_assets.every(
(ca) =>
replacements[
`${index}_${ca.id}`
],
);
return (
<div
key={check.index}
className={`rounded-xl border p-4 transition-all ${
isOmitted
? 'border-dashed bg-slate-50 opacity-50 dark:bg-slate-900/50'
: hasConflicts &&
!allConflictsResolved
? 'border-amber-400 bg-amber-50/40 shadow-xs dark:border-amber-700/60 dark:bg-amber-950/20'
: 'border-slate-200 bg-card dark:border-slate-800'
}`}
>
<div className="flex flex-col justify-between gap-3 sm:flex-row sm:items-center">
<div className="space-y-1">
<div className="flex flex-wrap items-center gap-2">
<span className="rounded-md bg-muted px-2 py-0.5 text-xs font-semibold text-muted-foreground">
Semana {index + 1}
</span>
<p
className={`text-sm font-semibold ${
isOmitted
? 'text-muted-foreground line-through'
: 'text-foreground'
}`}
>
{
check.date_formatted
}
</p>
<span className="flex items-center gap-1 text-xs text-muted-foreground">
<Clock className="size-3" />
{
check.time_formatted
}
</span>
</div>
<div className="flex flex-wrap items-center gap-2 pt-1">
{isOmitted ? (
<Badge
variant="outline"
className="border-dashed text-muted-foreground"
>
Dia apagado /
ignorado
</Badge>
) : allConflictsResolved ? (
<Badge
variant="default"
className="bg-emerald-600 text-white"
>
Conflito
resolvido com
troca
</Badge>
) : hasConflicts ? (
<Badge
variant="destructive"
className="bg-amber-600 text-white"
>
Conflito de
material
</Badge>
) : (
<Badge
variant="outline"
className="border-emerald-300 text-emerald-700 dark:border-emerald-800 dark:text-emerald-400"
>
Equipamento
disponível
</Badge>
)}
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
{isOmitted ? (
<Button
type="button"
variant="outline"
size="sm"
onClick={() =>
toggleOmit(
index,
)
}
className="h-8 gap-1"
>
<Undo2 className="size-3.5" />
Restaurar este dia
</Button>
) : (
<Button
type="button"
variant="ghost"
size="sm"
onClick={() =>
toggleOmit(
index,
)
}
className="h-8 gap-1 text-rose-600 hover:bg-rose-50 hover:text-rose-700 dark:hover:bg-rose-950/40"
>
<Trash2 className="size-3.5" />
Apagar este dia
</Button>
)}
</div>
</div>
{/* Details of items & conflicts */}
{!isOmitted && (
<div className="mt-3 space-y-2 border-t pt-3 text-xs">
{check.conflicted_assets.map(
(cAsset) => {
const key = `${index}_${cAsset.id}`;
const replacement =
replacements[
key
];
const isSelecting =
activeSelectorKey ===
key;
return (
<div
key={
cAsset.id
}
className="space-y-2 rounded-lg border border-amber-300/80 bg-amber-50/60 p-3 dark:border-amber-800/80 dark:bg-amber-950/30"
>
<div className="flex flex-col justify-between gap-2 sm:flex-row sm:items-center">
<div>
<span className="font-semibold text-amber-900 dark:text-amber-200">
Material
em
conflito:{' '}
</span>
<span className="font-medium text-foreground">
{
cAsset.name
}{' '}
(
{
cAsset.asset_tag
}
)
</span>
<p className="mt-0.5 text-[11px] text-muted-foreground">
Já
se
encontra
reservado
por
outro
utilizador
para
este
horário.
</p>
</div>
<div className="flex items-center gap-2">
{replacement ? (
<Button
type="button"
variant="outline"
size="sm"
onClick={() =>
removeReplacement(
index,
cAsset.id,
)
}
className="h-7 text-xs"
>
<Undo2 className="mr-1 size-3" />{' '}
Reverter
troca
</Button>
) : (
<Button
type="button"
variant="default"
size="sm"
onClick={() =>
toggleReplacementSelector(
key,
)
}
className="h-7 gap-1 text-xs"
>
<RefreshCw className="size-3" />
{isSelecting
? 'Fechar lista'
: 'Trocar material'}
</Button>
)}
</div>
</div>
{/* Replacement indicator */}
{replacement && (
<div className="flex items-center justify-between rounded-md border border-emerald-400 bg-emerald-50 p-2 text-emerald-900 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200">
<div className="flex items-center gap-2">
<CheckCircle2 className="size-4 shrink-0 text-emerald-600" />
<span>
Substituído
por:{' '}
<strong>
{
replacement.name
}
</strong>{' '}
(
{
replacement.asset_tag
}
)
</span>
</div>
</div>
)}
{/* Interactive Alternatives Selector */}
{isSelecting &&
!replacement && (
<div className="mt-2 space-y-2 rounded-md border bg-background p-3">
<div className="flex items-center justify-between">
<span className="text-xs font-semibold text-foreground">
Equipamentos
disponíveis
para
este
dia
(
{
cAsset
.alternatives
.length
}
):
</span>
<button
type="button"
onClick={() =>
toggleReplacementSelector(
key,
)
}
className="text-muted-foreground hover:text-foreground"
>
<X className="size-3.5" />
</button>
</div>
{cAsset
.alternatives
.length ===
0 ? (
<p className="py-1 text-muted-foreground italic">
Não
foram
encontrados
equipamentos
alternativos
livres
para
este
horário.
Sugerimos
apagar
a
reserva
deste
dia.
</p>
) : (
<div className="grid max-h-40 gap-1.5 overflow-y-auto">
{cAsset.alternatives.map(
(
alt,
) => (
<div
key={
alt.id
}
className="flex cursor-pointer items-center justify-between rounded border p-2 transition-colors hover:bg-muted/50"
onClick={() =>
selectReplacement(
index,
cAsset.id,
alt,
)
}
>
<div>
<span className="font-medium text-foreground">
{
alt.name
}
</span>
<span className="ml-2 font-mono text-[10px] text-muted-foreground">
{
alt.asset_tag
}
</span>
{alt.category_name && (
<span className="ml-1 text-[10px] text-muted-foreground">
·{' '}
{
alt.category_name
}
</span>
)}
</div>
<Button
type="button"
size="sm"
variant="secondary"
className="h-6 text-xs"
onClick={(
e,
) => {
e.stopPropagation();
selectReplacement(
index,
cAsset.id,
alt,
);
}}
>
Escolher
</Button>
</div>
),
)}
</div>
)}
</div>
)}
</div>
);
},
)}
{/* Available assets for this occurrence */}
{check.available_assets
.length > 0 && (
<div className="flex items-center gap-1.5 text-muted-foreground">
<Package className="size-3.5 shrink-0 text-emerald-600" />
<span>
Disponíveis:
</span>
<span className="font-medium text-foreground">
{check.available_assets
.map(
(a) =>
`${a.name} (${a.asset_tag})`,
)
.join(', ')}
</span>
</div>
)}
</div>
)}
</div>
);
})}
</div>
</>
) : null}
</div>
<DialogFooter className="flex flex-col justify-between gap-3 border-t bg-slate-50 p-4 sm:flex-row sm:items-center dark:bg-slate-900/60">
<div className="text-xs text-muted-foreground">
{activeOccurrences.length > 0 ? (
<span>
A submeter{' '}
<strong>{activeOccurrences.length}</strong>{' '}
requisições
{omittedCount > 0
? ` (${omittedCount} dias ignorados)`
: ''}
.
</span>
) : (
<span className="font-medium text-rose-600">
Todos os dias foram apagados. Restaure pelo
menos um dia para submeter.
</span>
)}
{hasUnresolvedConflicts && (
<span className="mt-0.5 block font-medium text-amber-600 dark:text-amber-400">
⚠ Resolva os conflitos pendentes (trocando o
material ou apagando o dia).
</span>
)}
</div>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
onClick={onClose}
disabled={isSubmitting}
>
Cancelar
</Button>
<Button
type="button"
onClick={handleConfirm}
disabled={!canSubmit}
className="gap-2"
>
{isSubmitting ? (
<>
<RefreshCw className="size-4 animate-spin" />
A submeter…
</>
) : (
<>
Confirmar e submeter série
<ArrowRight className="size-4" />
</>
)}
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}