fix/tipo-de-cambio

This commit is contained in:
2026-04-24 15:09:01 -06:00
parent d7eacb1761
commit 7e4985af5d
2 changed files with 44 additions and 25 deletions

View File

@@ -320,6 +320,7 @@
exchange_rate: pedimento?.exchange_rate ?? null,
// Date fields - Cargamos convirtiendo a local para el usuario
entry_date: loadServerDate(datesData?.entry_date) || currentDate,
start_date: loadServerDate(datesData?.start_date) || null,
end_date: loadServerDate(datesData?.end_date) || end_date,
payment_date: loadServerDate(datesData?.payment_date) || payment_date,
extraction_date: loadServerDate(datesData?.entry_date) || null,
@@ -367,46 +368,63 @@
return locale === 'en' ? mode.transport_en : mode.transport_es;
}
let refreshTrigger = $state(0);
/**
* Obtiene la fecha que determina el tipo de cambio
* Regla: Siempre usar fecha de inicio, sin importar el método de transporte.
*/
function getEffectiveExchangeDate(): string | null {
const entryMethod = getTransportByCode(formData?.pedimento_transport_means?.entry_exit);
const paymentCode = (entryMethod?.payment_date_code || 'E').toUpperCase();
if (paymentCode === 'P') {
return formData?.payment_date || null;
}
return formData?.entry_date || null;
return formData?.start_date || null;
}
function getEffectiveDateLabel(): string {
const entryMethod = getTransportByCode(formData?.pedimento_transport_means?.entry_exit);
const paymentCode = (entryMethod?.payment_date_code || 'E').toUpperCase();
return paymentCode === 'P' ? 'fecha de pago' : 'fecha de entrada';
return 'Inicio';
}
let lastTrigger = 0;
// Obtener automáticamente el tipo de cambio cuando cambie la fecha efectiva
$effect(() => {
const effectiveDate = getEffectiveExchangeDate();
const companyId = companyStore.activeCompany?.id;
// Acceder a refreshTrigger para reactividad
const currentTrigger = refreshTrigger;
// Solo ejecutar si los valores clave cambiaron
if (
formData &&
effectiveDate &&
companyId &&
(effectiveDate !== lastFetchedDate || companyId !== lastCompanyId)
(effectiveDate !== lastFetchedDate || companyId !== lastCompanyId || currentTrigger !== lastTrigger)
) {
lastFetchedDate = effectiveDate;
lastCompanyId = companyId;
lastTrigger = currentTrigger;
console.log(`[TIPO CAMBIO] Obteniendo para ${getEffectiveDateLabel()}:`, effectiveDate);
getExchangeRateByDate(effectiveDate, companyId)
.then((usdRate) => {
if (usdRate && formData) {
console.log('[TIPO CAMBIO] Encontrado:', usdRate.value);
formData.exchange_rate = usdRate.value;
} else {
console.warn('⚠️ [TIPO CAMBIO] No encontrado para fecha:', effectiveDate);
if (formData) {
formData.exchange_rate = null;
// Mostrar el diálogo automáticamente si no existe el tipo de cambio
missingExchangeRateDate = effectiveDate;
showExchangeRateDialog = true;
}
}
})
.catch((err) => {
console.error('❌ [TIPO CAMBIO] Error:', err);
if (formData) {
formData.exchange_rate = null;
}
});
}
});
@@ -610,9 +628,7 @@
class="cursor-not-allowed bg-muted"
/>
<p class="text-xs text-muted-foreground">
Tipo de fecha para TC: {getEffectiveDateLabel() === 'fecha de pago'
? 'FECHA PAGO'
: 'FECHA ENTRADA'}
Tipo de fecha para TC: <span class="font-bold">FECHA {getEffectiveDateLabel().toUpperCase()}</span>
{#if formData.pedimento_type === 'consolidated' && getEffectiveExchangeDate() > getCurrentLocalDate()}
<span class="ml-1 block font-medium text-amber-600 dark:text-amber-400">
(Opcional por fecha futura en consolidado)
@@ -997,6 +1013,12 @@
{#if activeSection === 'fechas'}
<!-- Fechas -->
<div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
<!-- Fecha de Inicio -->
<div class="space-y-2">
<Label for="start_date">Fecha de Inicio <span class="text-red-500">*</span></Label>
<Input id="start_date" type="date" bind:value={formData.start_date} />
</div>
<!-- Fecha de Entrada -->
<div class="space-y-2">
<Label for="entry_date">Fecha de Entrada <span class="text-red-500">*</span></Label>
@@ -1389,6 +1411,6 @@
initialDate={missingExchangeRateDate}
overlayClass="bg-black/20"
onSuccess={() => {
/* Optional: maybe refresh something or just let user continue */
refreshTrigger++;
}}
/>

View File

@@ -162,15 +162,10 @@
}
function getExchangeDateForPedimento(formData: any): { date: string | null; label: string } {
const catalog = (data.pedimentoTransportCatalog || []) as PedimentoTransportCatalog[];
const entryMethod = catalog.find(
(item) => item.code === formData?.pedimento_transport_means?.entry_exit
);
const paymentDateCode = (entryMethod?.payment_date_code || 'E').toUpperCase();
if (paymentDateCode === 'P') {
return { date: formData?.payment_date || null, label: 'fecha de pago' };
}
return { date: formData?.entry_date || null, label: 'fecha de entrada' };
return {
date: formData?.start_date || null,
label: 'fecha de inicio'
};
}
// ID del pedimento
@@ -441,6 +436,7 @@
customs_office: 'Aduana',
license: 'Patente',
pedimento_number: 'Número de Pedimento',
start_date: 'Fecha de Inicio',
pedimento_code: 'Clave',
regime: 'Régimen'
};
@@ -527,6 +523,7 @@
if (generalFormData) {
const hasDatesValue =
generalFormData.entry_date ||
generalFormData.start_date ||
generalFormData.pedimento_date ||
generalFormData.extraction_date ||
generalFormData.rectification_payment_date ||
@@ -536,6 +533,7 @@
if (hasDatesValue) {
payload.pedimento_dates = {
entry_date: generalFormData.entry_date || null,
start_date: generalFormData.start_date || null,
pedimento_date: generalFormData.pedimento_date || null,
payment_date: generalFormData.payment_date || null,
rectification_payment_date: generalFormData.rectification_payment_date || null,
@@ -1068,8 +1066,7 @@
// Interceptar error de tipo de cambio
console.log('Interceptor: Exchange rate missing error caught (Pedimento).');
const dateMatch = errorStr.match(/(\d{4}-\d{2}-\d{2})/);
const missingDate = dateMatch ? dateMatch[0] : generalFormData?.payment_date || '';
const missingDate = dateMatch ? dateMatch[0] : (generalFormData?.start_date || '');
missingExchangeRateDate = missingDate;
showExchangeRateDialog = true;