refactor: simplify pedidos item management by removing modalidade from item configuration and validation, ensuring all items use the same ata while enhancing code clarity and maintainability

This commit is contained in:
2025-12-18 08:48:40 -03:00
parent 69914170bf
commit 94373c6b94
3 changed files with 91 additions and 295 deletions

View File

@@ -514,30 +514,23 @@
if (!pedido || !newItem.objetoId || !newItem.valorEstimado) return;
// Validação no front: garantir que todos os itens existentes do pedido
// utilizem a mesma combinação de modalidade e ata (quando houver).
// utilizem a mesma ata (quando houver).
if (items.length > 0) {
const referenceItem = items[0];
const referenceModalidade = (referenceItem.modalidade as Modalidade | undefined) ?? undefined;
const referenceAtaId = (('ataId' in referenceItem ? referenceItem.ataId : undefined) ??
null) as string | null;
const newAtaId = newItem.ataId || null;
const sameModalidade = !referenceModalidade || newItem.modalidade === referenceModalidade;
const sameAta = referenceAtaId === newAtaId;
if (!sameModalidade || !sameAta) {
const refModalidadeLabel = referenceModalidade
? formatModalidade(referenceModalidade)
: 'Não definida';
if (!sameAta) {
const refAtaLabel =
referenceAtaId === null ? 'sem Ata vinculada' : 'com uma Ata específica';
toast.error(
`Não é possível adicionar este item com esta combinação de modalidade e ata.\n\n` +
`Este pedido já está utilizando Modalidade: ${refModalidadeLabel} e está ${refAtaLabel}.\n` +
`Todos os itens do pedido devem usar a mesma modalidade e a mesma ata (quando houver).`
`Não é possível adicionar este item com esta ata.\n\n` +
`Este pedido já está vinculado a: ${refAtaLabel}.\n` +
`Todos os itens do pedido devem usar a mesma ata (quando houver).`
);
return;
}
@@ -550,7 +543,6 @@
objetoId: newItem.objetoId as Id<'objetos'>,
valorEstimado: newItem.valorEstimado,
quantidade: newItem.quantidade,
modalidade: newItem.modalidade,
acaoId: newItem.acaoId ? (newItem.acaoId as Id<'acoes'>) : undefined,
ataId: newItem.ataId ? (newItem.ataId as Id<'atas'>) : undefined
});
@@ -1664,22 +1656,8 @@
placeholder="R$ 0,00"
/>
</div>
<div>
<label for="modalidade-select" class="mb-1 block text-xs font-medium text-gray-500"
>Modalidade</label
>
<select
id="modalidade-select"
bind:value={newItem.modalidade}
class="w-full rounded-md border-gray-300 text-sm shadow-sm"
>
<option value="consumo">Consumo</option>
<option value="dispensa">Dispensa</option>
<option value="inexgibilidade">Inexigibilidade</option>
<option value="adesao">Adesão</option>
</select>
</div>
{#if newItem.objetoId}
{#if newItem.objetoId && permissions?.canEditAta}
<div>
<label for="ata-select" class="mb-1 block text-xs font-medium text-gray-500"
>Ata (Opcional)</label
@@ -1900,7 +1878,7 @@
{/if}
</td>
<td class="px-6 py-4 text-sm whitespace-nowrap text-gray-600">
{#if pedido.status === 'em_rascunho' || pedido.status === 'precisa_ajustes' || pedido.status === 'em_analise' || pedido.status === 'aguardando_aceite'}
{#if permissions?.canEditModalidade}
<select
class="rounded border px-2 py-1 text-xs"
value={ensureEditingItem(item).modalidade}
@@ -1919,7 +1897,7 @@
<option value="adesao">Adesão</option>
</select>
{:else}
{item.modalidade}
{formatModalidade(item.modalidade as Modalidade) || '-'}
{/if}
</td>
<td class="px-6 py-4 text-sm whitespace-nowrap text-gray-600">
@@ -1942,7 +1920,7 @@
{/if}
</td>
<td class="px-6 py-4 text-sm whitespace-nowrap text-gray-600">
{#if pedido.status === 'em_rascunho' || pedido.status === 'precisa_ajustes' || pedido.status === 'em_analise' || pedido.status === 'aguardando_aceite'}
{#if permissions?.canEditAta}
<select
class="rounded border px-2 py-1 text-xs"
value={ensureEditingItem(item).ataId}

View File

@@ -1,12 +1,10 @@
<script lang="ts">
import { api } from '@sgse-app/backend/convex/_generated/api';
import type { Doc, Id } from '@sgse-app/backend/convex/_generated/dataModel';
import type { FunctionReturnType } from 'convex/server';
import { useConvexClient, useQuery } from 'convex-svelte';
import { Plus, Trash2, X, Info } from 'lucide-svelte';
import { goto } from '$app/navigation';
import { resolve } from '$app/paths';
import { formatarDataBR } from '$lib/utils/datas';
const client = useConvexClient();
@@ -27,40 +25,28 @@
let warning = $state<string | null>(null);
// Item selection state
// Nota: modalidade é opcional aqui pois será definida pelo Setor de Compras posteriormente
type SelectedItem = {
objeto: Doc<'objetos'>;
quantidade: number;
modalidade: 'dispensa' | 'inexgibilidade' | 'adesao' | 'consumo';
acaoId?: Id<'acoes'>;
ataId?: Id<'atas'>;
ataNumero?: string; // For display
ata?: FunctionReturnType<typeof api.objetos.getAtasComLimite>[number]; // dados mínimos p/ exibir detalhes
};
let selectedItems = $state<SelectedItem[]>([]);
let selectedObjetoIds = $derived(selectedItems.map((i) => i.objeto._id));
let hasMixedModalidades = $derived(new Set(selectedItems.map((i) => i.modalidade)).size > 1);
// Item configuration modal
let showItemModal = $state(false);
let itemConfig = $state<{
objeto: Doc<'objetos'> | null;
quantidade: number;
modalidade: 'dispensa' | 'inexgibilidade' | 'adesao' | 'consumo';
acaoId: string; // using string to handle empty select
ataId: string; // using string to handle empty select
}>({
objeto: null,
quantidade: 1,
modalidade: 'consumo',
acaoId: '',
ataId: ''
acaoId: ''
});
type AtasComLimite = FunctionReturnType<typeof api.objetos.getAtasComLimite>;
let availableAtas = $state<AtasComLimite>([]);
// Item Details Modal
let showDetailsModal = $state(false);
let detailsItem = $state<SelectedItem | null>(null);
@@ -75,16 +61,10 @@
}
async function openItemModal(objeto: Doc<'objetos'>) {
// Fetch linked Atas for this object
const linkedAtas = await client.query(api.objetos.getAtasComLimite, { objetoId: objeto._id });
availableAtas = linkedAtas;
itemConfig = {
objeto,
quantidade: 1,
modalidade: 'consumo',
acaoId: '',
ataId: ''
acaoId: ''
};
showItemModal = true;
searchQuery = ''; // Clear search
@@ -93,24 +73,17 @@
function closeItemModal() {
showItemModal = false;
itemConfig.objeto = null;
availableAtas = [];
}
function confirmAddItem() {
if (!itemConfig.objeto) return;
const selectedAta = availableAtas.find((a) => a._id === itemConfig.ataId);
selectedItems = [
...selectedItems,
{
objeto: itemConfig.objeto,
quantidade: itemConfig.quantidade,
modalidade: itemConfig.modalidade,
acaoId: itemConfig.acaoId ? (itemConfig.acaoId as Id<'acoes'>) : undefined,
ataId: itemConfig.ataId ? (itemConfig.ataId as Id<'atas'>) : undefined,
ataNumero: selectedAta?.numero,
ata: selectedAta
acaoId: itemConfig.acaoId ? (itemConfig.acaoId as Id<'acoes'>) : undefined
}
];
checkExisting();
@@ -131,7 +104,6 @@
criadoEm: number;
matchingItems?: {
objetoId: Id<'objetos'>;
modalidade: SelectedItem['modalidade'];
quantidade: number;
}[];
}[]
@@ -157,36 +129,6 @@
}
}
function formatModalidade(modalidade: SelectedItem['modalidade']) {
switch (modalidade) {
case 'consumo':
return 'Consumo';
case 'dispensa':
return 'Dispensa';
case 'inexgibilidade':
return 'Inexigibilidade';
case 'adesao':
return 'Adesão';
default:
return modalidade;
}
}
function getModalidadeBadgeClasses(modalidade: SelectedItem['modalidade']) {
switch (modalidade) {
case 'consumo':
return 'bg-blue-100 text-blue-800';
case 'dispensa':
return 'bg-yellow-100 text-yellow-800';
case 'inexgibilidade':
return 'bg-purple-100 text-purple-800';
case 'adesao':
return 'bg-green-100 text-green-800';
default:
return 'bg-gray-100 text-gray-800';
}
}
function getAcaoNome(acaoId: Id<'acoes'> | undefined) {
if (!acaoId) return '-';
const acao = acoes.find((a) => a._id === acaoId);
@@ -206,8 +148,7 @@
.map((match) => {
// Find name from selected items (might be multiple with same object, just pick one name)
const item = selectedItems.find((p) => p.objeto._id === match.objetoId);
const modalidadeLabel = formatModalidade(match.modalidade);
return `${item?.objeto.nome} (${modalidadeLabel}): ${match.quantidade} un.`;
return `${item?.objeto.nome}: ${match.quantidade} un.`;
})
.join(', ');
@@ -218,9 +159,7 @@
if (!pedido.matchingItems || pedido.matchingItems.length === 0) return null;
for (const match of pedido.matchingItems) {
const item = selectedItems.find(
(p) => p.objeto._id === match.objetoId && p.modalidade === match.modalidade
);
const item = selectedItems.find((p) => p.objeto._id === match.objetoId);
if (item) {
return item;
}
@@ -239,16 +178,11 @@
const params = new URLSearchParams();
params.set('obj', matchedItem.objeto._id);
params.set('qtd', String(matchedItem.quantidade));
params.set('mod', matchedItem.modalidade);
if (matchedItem.acaoId) {
params.set('acao', matchedItem.acaoId);
}
if (matchedItem.ataId) {
params.set('ata', matchedItem.ataId);
}
return `/pedidos/${pedido._id}?${params.toString()}` as `/pedidos/${string}`;
}
@@ -261,13 +195,11 @@
checking = true;
try {
// Importante: ação (acaoId) NÃO entra no filtro de similaridade.
// O filtro considera apenas combinação de objeto + modalidade.
// Importante: O filtro considera apenas objetoId (modalidade não é mais usada na criação).
const itensFiltro =
selectedItems.length > 0
? selectedItems.map((item) => ({
objetoId: item.objeto._id,
modalidade: item.modalidade
objetoId: item.objeto._id
}))
: undefined;
@@ -292,11 +224,6 @@
async function handleSubmit(e: Event) {
e.preventDefault();
if (hasMixedModalidades) {
error =
'Não é possível criar o pedido com itens de modalidades diferentes. Ajuste os itens antes de continuar.';
return;
}
creating = true;
error = null;
try {
@@ -312,9 +239,7 @@
objetoId: item.objeto._id,
valorEstimado: item.objeto.valorEstimado,
quantidade: item.quantidade,
modalidade: item.modalidade,
acaoId: item.acaoId,
ataId: item.ataId
acaoId: item.acaoId
})
)
);
@@ -417,20 +342,6 @@
<div class="flex-1 space-y-2">
<div class="flex flex-wrap items-center gap-2">
<p class="font-semibold text-gray-900">{item.objeto.nome}</p>
<span
class={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold ${getModalidadeBadgeClasses(
item.modalidade
)}`}
>
{formatModalidade(item.modalidade)}
</span>
{#if item.ataNumero}
<span
class="inline-flex items-center rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-800"
>
Ata {item.ataNumero}
</span>
{/if}
{#if item.acaoId}
<span
class="inline-flex items-center rounded-full bg-indigo-100 px-2.5 py-0.5 text-xs font-medium text-indigo-800"
@@ -480,15 +391,6 @@
</div>
<!-- Warnings Section -->
{#if hasMixedModalidades}
<div class="mb-3 rounded-lg border border-red-400 bg-red-50 px-4 py-3 text-sm text-red-800">
<p class="font-semibold">Modalidades diferentes detectadas</p>
<p>
Não é possível criar o pedido com itens de modalidades diferentes. Ajuste os itens para
usar uma única modalidade.
</p>
</div>
{/if}
{#if warning}
<div
@@ -508,22 +410,13 @@
<p class="mb-3 font-semibold text-yellow-900">Pedidos similares encontrados:</p>
<ul class="space-y-2">
{#each existingPedidos as pedido (pedido._id)}
{@const first = getFirstMatchingSelectedItem(pedido)}
<li class="flex flex-col rounded-lg bg-white px-4 py-3 shadow-sm">
<div class="flex items-center justify-between gap-3">
<div class="space-y-1">
<p class="text-sm font-medium text-gray-900">
Pedido {pedido.numeroSei || 'sem número SEI'}{formatStatus(pedido.status)}
</p>
{#if first}
<span
class={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold ${getModalidadeBadgeClasses(
first.modalidade
)}`}
>
Modalidade: {formatModalidade(first.modalidade)}
</span>
{/if}
{#if getMatchingInfo(pedido)}
<p class="mt-1 text-xs text-blue-700">
{getMatchingInfo(pedido)}
@@ -553,7 +446,7 @@
</a>
<button
type="submit"
disabled={creating || selectedItems.length === 0 || hasMixedModalidades}
disabled={creating || selectedItems.length === 0}
class="rounded-lg bg-blue-600 px-6 py-2.5 font-semibold text-white shadow-md transition hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
>
{creating ? 'Criando...' : 'Criar Pedido'}
@@ -600,62 +493,6 @@
/>
</div>
<div>
<label class="mb-2 block text-sm font-medium text-gray-700" for="modalidade">
Modalidade
</label>
<select
id="modalidade"
class="w-full rounded-lg border border-gray-300 px-4 py-2.5 transition focus:border-blue-500 focus:ring-2 focus:ring-blue-200 focus:outline-none"
bind:value={itemConfig.modalidade}
>
<option value="consumo">Consumo</option>
<option value="dispensa">Dispensa</option>
<option value="inexgibilidade">Inexigibilidade</option>
<option value="adesao">Adesão</option>
</select>
</div>
{#if availableAtas.length > 0}
<div class="rounded-lg border-2 border-green-200 bg-green-50 p-4">
<div class="mb-2 flex items-center gap-2">
<span class="rounded-full bg-green-600 px-2 py-0.5 text-xs font-bold text-white">
{availableAtas.length}
{availableAtas.length === 1 ? 'Ata' : 'Atas'}
</span>
<span class="text-sm font-semibold text-green-900">disponível para este objeto</span
>
</div>
<label class="mb-2 block text-sm font-medium text-gray-700" for="itemAta">
Selecionar Ata (Opcional)
</label>
<select
id="itemAta"
class="w-full rounded-lg border border-green-300 bg-white px-4 py-2.5 transition focus:border-green-500 focus:ring-2 focus:ring-green-200 focus:outline-none"
bind:value={itemConfig.ataId}
>
<option value="">Nenhuma</option>
{#each availableAtas as ata (ata._id)}
{@const reason =
ata.lockReason === 'nao_configurada'
? 'não configurada'
: ata.lockReason === 'limite_atingido'
? 'limite atingido'
: ata.lockReason === 'vigencia_expirada'
? `vigência encerrada em ${
ata.dataFimEfetiva || ata.dataFim
? formatarDataBR((ata.dataFimEfetiva || ata.dataFim) as string)
: '-'
}`
: null}
<option value={ata._id} disabled={ata.isLocked}>
Ata {ata.numero} (SEI: {ata.numeroSei}){reason ? ` (${reason})` : ''}
</option>
{/each}
</select>
</div>
{/if}
<div>
<label class="mb-2 block text-sm font-medium text-gray-700" for="itemAcao">
Ação (Opcional)
@@ -723,7 +560,7 @@
<div class="rounded-lg bg-gray-50 p-4">
<h4 class="mb-2 font-semibold text-gray-800">Pedido</h4>
<p class="text-gray-700"><strong>Quantidade:</strong> {detailsItem.quantidade}</p>
<p class="text-gray-700"><strong>Modalidade:</strong> {detailsItem.modalidade}</p>
{#if detailsItem.acaoId}
<p class="text-gray-700">
<strong>Ação:</strong>
@@ -731,32 +568,6 @@
</p>
{/if}
</div>
{#if detailsItem.ata}
<div class="rounded-lg border border-green-100 bg-green-50 p-4">
<h4 class="mb-2 font-semibold text-green-900">Ata de Registro de Preços</h4>
<p class="text-green-800"><strong>Número:</strong> {detailsItem.ata.numero}</p>
<p class="text-green-800">
<strong>Processo SEI:</strong>
{detailsItem.ata.numeroSei}
</p>
{#if detailsItem.ata.dataInicio}
<p class="text-green-800">
<strong>Vigência:</strong>
{formatarDataBR(detailsItem.ata.dataInicio)} até {detailsItem.ata
.dataFimEfetiva || detailsItem.ata.dataFim
? formatarDataBR(
(detailsItem.ata.dataFimEfetiva || detailsItem.ata.dataFim) as string
)
: 'Indefinido'}
</p>
{/if}
</div>
{:else}
<div class="rounded-lg bg-gray-50 p-4">
<p class="text-sm text-gray-500 italic">Nenhuma Ata vinculada a este item.</p>
</div>
{/if}
</div>
<div class="mt-6 flex justify-end">