version pre testeo de descuentos

Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
fede committed 2026-11-30 01:16:31 -03:00
1 parent a9ec514687
commit ea009e276f
25 files changed
+1100 -13

No files matched your search

@@ -0,0 +1,21 @@
import { API_URL } from '$lib/env';
import { getToken } from '../token';
import type { DescuentoDto } from './crearDescuento';
export async function actualizarDescuento(id: number, dto: DescuentoDto) {
try {
const req = await fetch(`${API_URL}/descuentos/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getToken()}`
},
body: JSON.stringify(dto)
});
if (req.ok) return 'ok';
const data = await req.json().catch(() => ({}));
return data.error ?? 'No se pudo actualizar el descuento';
} catch {
return 'No se pudo alcanzar el servidor';
}
}
@@ -0,0 +1,18 @@
import { API_URL } from '$lib/env';
import { getToken } from '../token';
export async function altaDescuento(id: number) {
try {
const req = await fetch(`${API_URL}/descuentos/${id}/alta`, {
method: 'PATCH',
headers: {
Authorization: `Bearer ${getToken()}`
}
});
if (req.ok) return 'ok';
const data = await req.json().catch(() => ({}));
return data.error ?? 'No se pudo reactivar el descuento';
} catch {
return 'No se pudo alcanzar el servidor';
}
}
@@ -0,0 +1,28 @@
import { API_URL } from '$lib/env';
import { getToken } from '../token';
export interface DescuentoDto {
nombre: string;
descripcion?: string;
tipo: 'PORCENTAJE' | 'FIJO';
valor: number;
activo?: boolean;
}
export async function crearDescuento(dto: DescuentoDto) {
try {
const req = await fetch(`${API_URL}/descuentos/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getToken()}`
},
body: JSON.stringify(dto)
});
if (req.ok) return 'ok';
const data = await req.json().catch(() => ({}));
return data.error ?? 'No se pudo crear el descuento';
} catch {
return 'No se pudo alcanzar el servidor';
}
}
@@ -0,0 +1,18 @@
import { API_URL } from '$lib/env';
import { getToken } from '../token';
export async function eliminarDescuento(id: number) {
try {
const req = await fetch(`${API_URL}/descuentos/${id}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${getToken()}`
}
});
if (req.ok) return 'Ok';
const data = await req.json().catch(() => ({}));
return data.error ?? 'No se pudo eliminar el descuento';
} catch {
return 'No se pudo alcanzar el servidor';
}
}
@@ -0,0 +1,19 @@
import { API_URL } from '$lib/env';
import type { Descuento } from '../../../types';
import { getToken } from '../token';
// Listado completo (activos, inactivos y dados de baja) para la gestión.
export async function obtenerDescuentos(fetch2?: Function): Promise<Descuento[] | string> {
const fetchfn = fetch2 ? fetch2 : fetch;
try {
const req = await fetchfn(`${API_URL}/descuentos/todos`, {
method: 'GET',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
});
const data = await req.json();
if (req.ok) return data;
return data.error ?? 'No se pudieron obtener los descuentos';
} catch {
return 'No se pudo alcanzar el servidor';
}
}
+203
View File
@@ -0,0 +1,203 @@
<script lang="ts">
import Header from '$lib/components/Header.svelte';
import {
Button,
DataTableSkeleton,
InlineNotification,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableHeader,
TableRow,
Tag
} from 'carbon-components-svelte';
import { Add, ArrowUp, Edit, TrashCan } from 'carbon-icons-svelte';
import type { Descuento } from '../../types';
import CrearDescuentoForm from './CrearDescuentoForm.svelte';
import EditarDescuentoForm from './EditarDescuentoForm.svelte';
import EliminarDescuentoForm from './EliminarDescuentoForm.svelte';
import AltaDescuentoForm from './AltaDescuentoForm.svelte';
let { data }: { data: { descuentos: Descuento[] | string } } = $props();
let descuentos = $derived<Descuento[]>(Array.isArray(data.descuentos) ? data.descuentos : []);
let errorCarga = $derived(
data.descuentos !== undefined && data.descuentos !== null && !Array.isArray(data.descuentos)
? String(data.descuentos)
: ''
);
let openCrear = $state(false);
let openEdit = $state(false);
let openDelete = $state(false);
let openAlta = $state(false);
let descuentoSeleccionado = $state<Descuento | null>(null);
let descuentoAEliminar = $state<Descuento | null>(null);
let descuentoAAlta = $state<Descuento | null>(null);
const headers = [
{ key: 'ID', value: 'ID' },
{ key: 'nombre', value: 'Nombre' },
{ key: 'descripcion', value: 'Descripción' },
{ key: 'tipo', value: 'Tipo' },
{ key: 'valor', value: 'Valor' },
{ key: 'activo', value: 'Activo' },
{ key: 'CreatedAt', value: 'Creado' },
{ key: 'DeletedAt', value: 'Estado' }
] as const;
function nombreTipo(tipo: Descuento['tipo']): string {
return tipo === 'PORCENTAJE' ? 'Porcentaje' : 'Monto fijo';
}
function formatoValor(d: Descuento): string {
const valor = Number(d.valor ?? 0);
return d.tipo === 'PORCENTAJE' ? `${valor}%` : `$ ${valor.toFixed(2)}`;
}
</script>
<Header />
<div class="page-container">
<div class="flex justify-between">
<h1 class="page-title">Gestión de Descuentos</h1>
<Button
icon={Add}
onclick={() => {
openCrear = true;
}}>Nuevo Descuento</Button
>
</div>
{#if errorCarga}
<InlineNotification kind="error" title="Error" subtitle={errorCarga} hideCloseButton />
{/if}
{#if typeof data.descuentos === 'undefined' || data.descuentos === null}
<DataTableSkeleton />
{:else if descuentos.length === 0}
<TableContainer title="Descuentos">
<Table>
<TableHead>
<TableRow>
{#each headers as header}
<TableHeader>{header.value}</TableHeader>
{/each}
<TableHeader>Acciones</TableHeader>
</TableRow>
</TableHead>
<TableBody>
<TableRow>
<TableCell colspan={headers.length + 1}>
No hay descuentos para mostrar, registrá uno.
</TableCell>
</TableRow>
</TableBody>
</Table>
</TableContainer>
{:else}
<TableContainer title="Listado de Descuentos">
<Table>
<TableHead>
<TableRow>
{#each headers as header}
<TableHeader>{header.value}</TableHeader>
{/each}
<TableHeader>Acciones</TableHeader>
</TableRow>
</TableHead>
<TableBody>
{#each descuentos as d (d.ID)}
<TableRow>
<TableCell>{d.ID}</TableCell>
<TableCell>{d.nombre}</TableCell>
<TableCell class="max-w-xs truncate" title={d.descripcion ?? ''}>
{d.descripcion || '-'}
</TableCell>
<TableCell>
<Tag type={d.tipo === 'PORCENTAJE' ? 'blue' : 'green'}>
{nombreTipo(d.tipo)}
</Tag>
</TableCell>
<TableCell>{formatoValor(d)}</TableCell>
<TableCell>
<Tag type={d.activo ? 'green' : 'gray'}>{d.activo ? 'Sí' : 'No'}</Tag>
</TableCell>
<TableCell>{String(d.CreatedAt ?? '-')}</TableCell>
<TableCell>
{#if d.DeletedAt}
<Tag type="red">Eliminado</Tag>
{:else}
<Tag type="green">Habilitado</Tag>
{/if}
</TableCell>
<TableCell>
{#if d.DeletedAt}
<Button
kind="ghost"
size="small"
icon={ArrowUp}
onclick={() => {
descuentoAAlta = d;
openAlta = true;
}}>Alta</Button
>
{:else}
<Button
kind="ghost"
size="small"
icon={Edit}
onclick={() => {
descuentoSeleccionado = d;
openEdit = true;
}}>Editar</Button
>
<Button
kind="danger-ghost"
size="small"
icon={TrashCan}
onclick={() => {
descuentoAEliminar = d;
openDelete = true;
}}>Eliminar</Button
>
{/if}
</TableCell>
</TableRow>
{/each}
</TableBody>
</Table>
</TableContainer>
{/if}
</div>
<CrearDescuentoForm bind:open={openCrear} onClose={() => (openCrear = false)} />
<EditarDescuentoForm
bind:open={openEdit}
descuento={descuentoSeleccionado}
onClose={() => {
openEdit = false;
descuentoSeleccionado = null;
}}
/>
<EliminarDescuentoForm
bind:open={openDelete}
descuento={descuentoAEliminar}
onClose={() => {
openDelete = false;
descuentoAEliminar = null;
}}
/>
<AltaDescuentoForm
bind:open={openAlta}
descuento={descuentoAAlta}
onClose={() => {
openAlta = false;
descuentoAAlta = null;
}}
/>
+10
View File
@@ -0,0 +1,10 @@
import { obtenerDescuentos } from '$lib/hooks/descuentos/obtenerDescuentos';
export const ssr = false;
export async function load({ depends, fetch }) {
depends('descuentos:load');
const descuentos = await obtenerDescuentos(fetch);
return { descuentos };
}
@@ -0,0 +1,64 @@
<script lang="ts">
import { invalidate } from '$app/navigation';
import { InlineNotification, Modal } from 'carbon-components-svelte';
import type { Descuento } from '../../types';
import { altaDescuento } from '$lib/hooks/descuentos/altaDescuento';
let {
open = $bindable(),
onClose,
descuento
}: { open?: boolean; onClose?: () => void; descuento?: Descuento | null } = $props();
let error = $state('');
let enviando = $state(false);
async function handleSubmit(e: Event) {
e.preventDefault();
if (enviando) return;
enviando = true;
error = '';
if (!descuento?.ID) {
error = 'No se pudo obtener el descuento. Recargá la página.';
enviando = false;
return;
}
const result = await altaDescuento(descuento.ID);
if (result !== 'ok') {
error = result;
enviando = false;
return;
}
await invalidate('descuentos:load');
enviando = false;
onClose?.();
}
function handleClose() {
error = '';
enviando = false;
onClose?.();
}
</script>
<form id="altaDescuentoForm" onsubmit={handleSubmit}>
<Modal
formId="altaDescuentoForm"
bind:open
size="sm"
modalHeading="Dar de alta descuento"
primaryButtonText="Dar de alta"
primaryButtonDisabled={enviando}
secondaryButtonText="Cancelar"
on:click:button--secondary={handleClose}
>
{#if error}
<div class="mb-4">
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
</div>
{/if}
<p>
¿Dar de alta el descuento <strong>{descuento?.nombre ?? ''}</strong>?
</p>
</Modal>
</form>
@@ -0,0 +1,121 @@
<script lang="ts">
import { invalidate } from '$app/navigation';
import {
InlineNotification,
Modal,
NumberInput,
Select,
SelectItem,
TextArea,
TextInput,
Toggle
} from 'carbon-components-svelte';
import { crearDescuento } from '$lib/hooks/descuentos/crearDescuento';
let { open = $bindable(), onClose }: { open?: boolean; onClose?: () => void } = $props();
let nombre = $state('');
let descripcion = $state('');
let tipo = $state('PORCENTAJE');
let valor = $state(0);
let activo = $state(true);
let enviando = $state(false);
let error = $state('');
$effect(() => {
if (open) {
nombre = '';
descripcion = '';
tipo = 'PORCENTAJE';
valor = 0;
activo = true;
error = '';
enviando = false;
}
});
function validar(): string {
if (nombre.trim() === '') return 'El nombre es obligatorio.';
if (!tipo) return 'El tipo es obligatorio.';
if (!valor || valor <= 0) return 'El valor debe ser mayor a cero.';
if (tipo === 'PORCENTAJE' && valor > 100) return 'El porcentaje no puede superar el 100%.';
return '';
}
async function enviar() {
if (enviando) return;
enviando = true;
error = validar();
if (error === '') {
const result = await crearDescuento({
nombre: nombre.trim(),
descripcion: descripcion.trim(),
tipo: tipo as 'PORCENTAJE' | 'FIJO',
valor: Number(valor),
activo
});
if (result === 'ok') {
await invalidate('descuentos:load');
onClose?.();
} else {
error = result;
}
}
enviando = false;
}
</script>
<form
id="crearDescuentoForm"
onsubmit={(e) => {
e.preventDefault();
void enviar();
}}
>
<Modal
formId="crearDescuentoForm"
bind:open
size="lg"
modalHeading="Registrar descuento"
primaryButtonText="Registrar"
primaryButtonDisabled={enviando}
secondaryButtonText="Cancelar"
on:click:button--secondary={() => onClose?.()}
>
{#if error}
<div class="mb-4">
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
</div>
{/if}
<TextInput labelText="Nombre" bind:value={nombre} maxlength={100} required />
<div class="mt-1 text-sm text-gray-500">{nombre.length}/100</div>
<div class="mt-4">
<Select labelText="Tipo" bind:selected={tipo}>
<SelectItem value="PORCENTAJE" text="Porcentaje (%)" />
<SelectItem value="FIJO" text="Monto fijo ($)" />
</Select>
</div>
<div class="mt-4">
<NumberInput
labelText={tipo === 'PORCENTAJE' ? 'Porcentaje' : 'Monto fijo'}
bind:value={valor}
min={0}
step={0.01}
/>
</div>
<div class="mt-4">
<TextArea labelText="Descripción" bind:value={descripcion} maxlength={500} rows={3} />
<div class="mt-1 text-sm text-gray-500">{descripcion.length}/500</div>
</div>
<div class="mt-4">
<Toggle bind:toggled={activo} labelText="Descuento activo" />
</div>
</Modal>
</form>
@@ -0,0 +1,126 @@
<script lang="ts">
import { invalidate } from '$app/navigation';
import {
InlineNotification,
Modal,
NumberInput,
Select,
SelectItem,
TextArea,
TextInput,
Toggle
} from 'carbon-components-svelte';
import type { Descuento } from '../../types';
import { actualizarDescuento } from '$lib/hooks/descuentos/actualizarDescuento';
let {
open = $bindable(),
onClose,
descuento
}: { open?: boolean; onClose?: () => void; descuento?: Descuento | null } = $props();
let nombre = $state('');
let descripcion = $state('');
let tipo = $state('PORCENTAJE');
let valor = $state(0);
let activo = $state(true);
let enviando = $state(false);
let error = $state('');
$effect(() => {
if (descuento) {
nombre = descuento.nombre ?? '';
descripcion = descuento.descripcion ?? '';
tipo = descuento.tipo ?? 'PORCENTAJE';
valor = descuento.valor ?? 0;
activo = descuento.activo ?? true;
error = '';
enviando = false;
}
});
function validar(): string {
if (nombre.trim() === '') return 'El nombre es obligatorio.';
if (!tipo) return 'El tipo es obligatorio.';
if (!valor || valor <= 0) return 'El valor debe ser mayor a cero.';
if (tipo === 'PORCENTAJE' && valor > 100) return 'El porcentaje no puede superar el 100%.';
return '';
}
async function enviar() {
if (enviando) return;
enviando = true;
error = validar();
if (error === '' && descuento) {
const result = await actualizarDescuento(descuento.ID, {
nombre: nombre.trim(),
descripcion: descripcion.trim(),
tipo: tipo as 'PORCENTAJE' | 'FIJO',
valor: Number(valor),
activo
});
if (result === 'ok') {
await invalidate('descuentos:load');
onClose?.();
} else {
error = result;
}
}
enviando = false;
}
</script>
<form
id="editarDescuentoForm"
onsubmit={(e) => {
e.preventDefault();
void enviar();
}}
>
<Modal
formId="editarDescuentoForm"
bind:open
size="lg"
modalHeading="Editar descuento"
primaryButtonText="Guardar"
primaryButtonDisabled={enviando}
secondaryButtonText="Cancelar"
on:click:button--secondary={() => onClose?.()}
>
{#if error}
<div class="mb-4">
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
</div>
{/if}
<TextInput labelText="Nombre" bind:value={nombre} maxlength={100} required />
<div class="mt-1 text-sm text-gray-500">{nombre.length}/100</div>
<div class="mt-4">
<Select labelText="Tipo" bind:selected={tipo}>
<SelectItem value="PORCENTAJE" text="Porcentaje (%)" />
<SelectItem value="FIJO" text="Monto fijo ($)" />
</Select>
</div>
<div class="mt-4">
<NumberInput
labelText={tipo === 'PORCENTAJE' ? 'Porcentaje' : 'Monto fijo'}
bind:value={valor}
min={0}
step={0.01}
/>
</div>
<div class="mt-4">
<TextArea labelText="Descripción" bind:value={descripcion} maxlength={500} rows={3} />
<div class="mt-1 text-sm text-gray-500">{descripcion.length}/500</div>
</div>
<div class="mt-4">
<Toggle bind:toggled={activo} labelText="Descuento activo" />
</div>
</Modal>
</form>
@@ -0,0 +1,58 @@
<script lang="ts">
import { invalidate } from '$app/navigation';
import { InlineNotification, Modal } from 'carbon-components-svelte';
import type { Descuento } from '../../types';
import { eliminarDescuento } from '$lib/hooks/descuentos/eliminarDescuento';
let {
open = $bindable(),
onClose,
descuento
}: { open?: boolean; onClose?: () => void; descuento?: Descuento | null } = $props();
let error = $state('');
async function handleSubmit(e: Event) {
e.preventDefault();
error = '';
if (!descuento?.ID) {
error = 'No se pudo obtener el descuento. Recargá la página.';
return;
}
const result = await eliminarDescuento(descuento.ID);
if (result !== 'Ok') {
error = result;
return;
}
await invalidate('descuentos:load');
onClose?.();
}
function handleClose() {
error = '';
onClose?.();
}
</script>
<form id="eliminarDescuentoForm" onsubmit={handleSubmit}>
<Modal
formId="eliminarDescuentoForm"
bind:open
size="sm"
modalHeading="Eliminar descuento"
primaryButtonText="Eliminar"
secondaryButtonText="Cancelar"
danger
on:click:button--secondary={handleClose}
>
{#if error}
<div class="mb-4">
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
</div>
{/if}
<p>
¿Está seguro de que desea eliminar el descuento
<strong>{descuento?.nombre ?? ''}</strong>?
</p>
</Modal>
</form>
+3 -3
View File
@@ -72,8 +72,8 @@
let descuentoTotal = $derived.by(() => {
const d = descuentos.find((x) => x.ID === descuentoId);
if (!d) return 0;
if (d.Tipo === 'PORCENTAJE') return subtotal * (d.Valor / 100);
return Math.min(d.Valor, subtotal);
if (d.tipo === 'PORCENTAJE') return subtotal * (d.valor / 100);
return Math.min(d.valor, subtotal);
});
let baseImponible = $derived(subtotal - descuentoTotal);
@@ -182,7 +182,7 @@
{#each descuentos as d (d.ID)}
<SelectItem
value={d.ID}
text={`${d.Nombre} (${d.Tipo === 'PORCENTAJE' ? d.Valor + '%' : '$' + d.Valor})`}
text={`${d.nombre} (${d.tipo === 'PORCENTAJE' ? d.valor + '%' : '$' + d.valor})`}
/>
{/each}
</Select>
+9
View File
@@ -202,6 +202,15 @@ export interface Marca extends BaseModel {
repuestos: Repuesto[];
}
export interface Descuento extends BaseModel {
empresaId?: number;
nombre: string;
descripcion?: string;
tipo: 'PORCENTAJE' | 'FIJO';
valor: number;
activo: boolean;
}
export interface Repuesto extends BaseModel {
empresaId?: number;
nombre: string;