Private
Public Access
commit parcial: refactor de decorator factura, añadida parcialemnte
funcionalidad de facturas tengo sueño Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
3c4bc5c008
commit
42bf987ffc
19 files changed
+525
-37
No files matched your search
@@ -97,10 +97,19 @@ func (b *FacturaResponseBuilder) Build() (*dto_facturas.FacturaResponse, error)
|
||||
UpdatedAt: b.factura.UpdatedAt,
|
||||
DeletedAt: deletedAt,
|
||||
EmpresaID: b.factura.EmpresaID,
|
||||
Numero: b.factura.Numero,
|
||||
Estado: b.factura.Estado,
|
||||
Total: b.factura.Total,
|
||||
ClienteID: b.factura.ClienteID,
|
||||
Numero: b.factura.Numero,
|
||||
Estado: b.factura.Estado,
|
||||
Total: b.factura.Total,
|
||||
Subtotal: b.factura.Subtotal,
|
||||
DescuentoTotal: b.factura.DescuentoTotal,
|
||||
Impuestos: b.factura.Impuestos,
|
||||
AlicuotaIVA: b.factura.AlicuotaIVA,
|
||||
Saldo: b.factura.Saldo,
|
||||
AlmacenID: b.factura.AlmacenID,
|
||||
FechaEmision: b.factura.FechaEmision,
|
||||
Observacion: b.factura.Observacion,
|
||||
Version: b.factura.Version,
|
||||
ClienteID: b.factura.ClienteID,
|
||||
Cliente: cliente,
|
||||
ProveedorID: b.factura.ProveedorID,
|
||||
Proveedor: proveedor,
|
||||
|
||||
@@ -21,6 +21,15 @@ type FacturaResponse struct {
|
||||
Numero string `json:"numero"`
|
||||
Estado string `json:"estado"`
|
||||
Total float64 `json:"total"`
|
||||
Subtotal float64 `json:"subtotal"`
|
||||
DescuentoTotal float64 `json:"descuentoTotal"`
|
||||
Impuestos float64 `json:"impuestos"`
|
||||
AlicuotaIVA float64 `json:"alicuotaIva"`
|
||||
Saldo float64 `json:"saldo"`
|
||||
AlmacenID uint `json:"almacenId"`
|
||||
FechaEmision time.Time `json:"fechaEmision"`
|
||||
Observacion string `json:"observacion,omitempty"`
|
||||
Version int `json:"version"`
|
||||
ClienteID uint `json:"ClienteID,omitempty"`
|
||||
Cliente dto_clientes.ClienteResumen `json:"cliente"`
|
||||
ProveedorID *uint `json:"proveedorId,omitempty"`
|
||||
|
||||
+18
-1
@@ -1,14 +1,31 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type Factura struct {
|
||||
Comprobante
|
||||
Numero string `gorm:"type:varchar(30);index" json:"numero"`
|
||||
ClienteID uint `gorm:"column:ClienteID"`
|
||||
ClienteID uint `gorm:"column:ClienteID;not null;index" json:"clienteId"`
|
||||
Cliente Cliente `gorm:"foreignKey:ClienteID" json:"cliente"`
|
||||
ProveedorID *uint `json:"proveedorId,omitempty"`
|
||||
Proveedor *Proveedor `gorm:"foreignKey:ProveedorID" json:"proveedor,omitempty"`
|
||||
AlmacenID uint `gorm:"column:almacenId;not null;default:1;index" json:"almacenId"`
|
||||
Almacen Almacen `gorm:"foreignKey:AlmacenID" json:"almacen,omitempty"`
|
||||
FechaEmision time.Time `gorm:"not null" json:"fechaEmision"`
|
||||
Subtotal float64 `gorm:"type:decimal(15,2);not null;default:0" json:"subtotal"`
|
||||
DescuentoID uint `gorm:"column:descuentoId" json:"descuentoId"`
|
||||
DescuentoTotal float64 `gorm:"type:decimal(15,2);not null;default:0" json:"descuentoTotal"`
|
||||
Impuestos float64 `gorm:"type:decimal(15,2);not null;default:0" json:"impuestos"`
|
||||
AlicuotaIVA float64 `gorm:"type:decimal(5,2);not null;default:21" json:"alicuotaIva"`
|
||||
Saldo float64 `gorm:"type:decimal(15,2);not null;default:0" json:"saldo"`
|
||||
SeAviso bool `gorm:"" json:"seAviso"`
|
||||
Detalles []FacturaDetalle `gorm:"serializer:json;type:json" json:"detalles,omitempty"`
|
||||
Historial []FacturaCambio `gorm:"serializer:json;type:json" json:"historial,omitempty"`
|
||||
Version int `gorm:"not null;default:1" json:"version"`
|
||||
EditadaPorID *uint `gorm:"column:editadaPorId" json:"editadaPorId,omitempty"`
|
||||
EditadaAt *time.Time `gorm:"column:editadaAt" json:"editadaAt,omitempty"`
|
||||
MotivoUltimaEdicion string `gorm:"type:varchar(200)" json:"motivoUltimaEdicion,omitempty"`
|
||||
Observacion string `gorm:"type:varchar(255)" json:"observacion,omitempty"`
|
||||
}
|
||||
|
||||
func (Factura) TableName() string {
|
||||
|
||||
@@ -2,9 +2,10 @@ package models
|
||||
|
||||
type FacturaDetalle struct {
|
||||
RepuestoID uint64 `json:"repuestoId"`
|
||||
Cantidad uint `json:"cantidad"`
|
||||
Cantidad float64 `json:"cantidad"`
|
||||
DescuentoID uint `json:"descuentoId"`
|
||||
Descuento float64 `json:"descuento"`
|
||||
PrecioUnitario float64 `json:"precioUnitario"`
|
||||
Subtotal float64 `json:"subtotal"`
|
||||
AlicuotaIVA float64 `json:"alicuotaIva"`
|
||||
}
|
||||
+11
-3
@@ -1,15 +1,23 @@
|
||||
package models
|
||||
|
||||
import "gorm.io/gorm"
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Pago struct {
|
||||
gorm.Model
|
||||
EmpresaID uint `gorm:"not null;default:1;index" json:"empresaId"`
|
||||
FacturaID uint `gorm:"column:facturaId;index" json:"facturaId"`
|
||||
Factura *Factura `gorm:"foreignKey:FacturaID" json:"factura,omitempty"`
|
||||
FormaDePagoID uint `gorm:"column:formaDePagoID"`
|
||||
FormaDePago FormaDePago `gorm:"foreignKey:FormaDePagoID"`
|
||||
ReciboID uint `json:"reciboId"`
|
||||
Recibo Recibo `gorm:"foreignKey:ReciboID" json:"recibo,omitempty"`
|
||||
ReciboID *uint `json:"reciboId,omitempty"`
|
||||
Recibo *Recibo `gorm:"foreignKey:ReciboID" json:"recibo,omitempty"`
|
||||
Importe float64 `gorm:"type:decimal(10,2)"`
|
||||
Fecha time.Time `gorm:"not null" json:"fecha"`
|
||||
Observacion string `gorm:"type:varchar(255)" json:"observacion,omitempty"`
|
||||
}
|
||||
|
||||
func (Pago) TableName() string {
|
||||
|
||||
@@ -10,17 +10,21 @@ import (
|
||||
)
|
||||
|
||||
type Repositorios struct {
|
||||
Permiso RepositorioPermiso
|
||||
Usuario RepositorioUsuario
|
||||
Grupo RepositorioGrupo
|
||||
Repuesto RepositorioRepuesto
|
||||
Marca RepositorioMarcas
|
||||
Logs RepositorioLogs
|
||||
Empresa RepositorioEmpresa
|
||||
Almacen RepositorioAlmacen
|
||||
Proveedor RepositorioProveedor
|
||||
Cliente RepositorioCliente
|
||||
Factura RepositorioFactura
|
||||
Permiso RepositorioPermiso
|
||||
Usuario RepositorioUsuario
|
||||
Grupo RepositorioGrupo
|
||||
Repuesto RepositorioRepuesto
|
||||
Marca RepositorioMarcas
|
||||
Logs RepositorioLogs
|
||||
Empresa RepositorioEmpresa
|
||||
Almacen RepositorioAlmacen
|
||||
Proveedor RepositorioProveedor
|
||||
Cliente RepositorioCliente
|
||||
Factura RepositorioFactura
|
||||
Pago RepositorioPago
|
||||
Secuencia RepositorioComprobanteSecuencia
|
||||
Descuento RepositorioDescuento
|
||||
FormaDePago RepositorioFormaDePago
|
||||
|
||||
Stock RepositorioStock
|
||||
MovimientoStock RepositorioMovimientoStock
|
||||
@@ -97,8 +101,12 @@ func nuevoContenedor(db *gorm.DB, empresaID uint) *Repositorios {
|
||||
Empresa: &repositorioEmpresa{db: db},
|
||||
Almacen: NuevoRepositorioAlmacen(db, empresaID),
|
||||
Proveedor: NuevoRepositorioProveedor(db, empresaID),
|
||||
Cliente: NuevoRepositorioCliente(db, empresaID),
|
||||
Factura: NuevoRepositorioFactura(db, empresaID),
|
||||
Cliente: NuevoRepositorioCliente(db, empresaID),
|
||||
Factura: NuevoRepositorioFactura(db, empresaID),
|
||||
Pago: NuevoRepositorioPago(db, empresaID),
|
||||
Secuencia: NuevoRepositorioComprobanteSecuencia(db, empresaID),
|
||||
Descuento: NuevoRepositorioDescuento(db, empresaID),
|
||||
FormaDePago: NuevoRepositorioFormaDePago(db, empresaID),
|
||||
|
||||
Stock: NuevoRepositorioStock(db, empresaID),
|
||||
MovimientoStock: NuevoRepositorioMovimientoStock(db, empresaID),
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package repositorios_decorator
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// decoradorOrdenFacturas aplica el orden por defecto cuando no se pagina.
|
||||
type decoradorOrdenFacturas struct {
|
||||
envuelto IFacturaQuery
|
||||
}
|
||||
|
||||
func (d decoradorOrdenFacturas) Aplicar(db *gorm.DB) *gorm.DB {
|
||||
consulta := d.envuelto.Aplicar(db)
|
||||
return consulta.Order("factura.created_at DESC")
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
package repositorios_decorator
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
// NuevaQueryFacturas arma la cadena de decoradores según los filtros.
|
||||
func NuevaQueryFacturas(filtros FiltrosFactura, preload bool, paginar bool) IFacturaQuery {
|
||||
var actual IFacturaQuery = FacturaQueryBase{Preload: preload}
|
||||
@@ -19,13 +17,3 @@ func NuevaQueryFacturas(filtros FiltrosFactura, preload bool, paginar bool) IFac
|
||||
|
||||
return actual
|
||||
}
|
||||
|
||||
// decoradorOrdenFacturas aplica el orden por defecto cuando no se pagina.
|
||||
type decoradorOrdenFacturas struct {
|
||||
envuelto IFacturaQuery
|
||||
}
|
||||
|
||||
func (d decoradorOrdenFacturas) Aplicar(db *gorm.DB) *gorm.DB {
|
||||
consulta := d.envuelto.Aplicar(db)
|
||||
return consulta.Order("factura.created_at DESC")
|
||||
}
|
||||
@@ -11,8 +11,15 @@ type RepositorioFactura interface {
|
||||
IRepositorio[models.Factura]
|
||||
Listar(filtros decorator.FiltrosFactura) ([]models.Factura, error)
|
||||
ObtenerConRelaciones(id uint) (*models.Factura, error)
|
||||
CrearConDetalles(tx *gorm.DB, factura *models.Factura) error
|
||||
BloquearPorID(tx *gorm.DB, id uint) (*models.Factura, error)
|
||||
ActualizarEstadoSaldo(tx *gorm.DB, id uint, estado string, saldo float64) error
|
||||
ExisteNumero(numero string) (bool, error)
|
||||
}
|
||||
|
||||
// FiltrosFactura se mantiene como alias del paquete decorator.
|
||||
type FiltrosFactura = decorator.FiltrosFactura
|
||||
|
||||
type repositorioFactura struct {
|
||||
*RepositorioBase[models.Factura]
|
||||
db *gorm.DB
|
||||
@@ -27,7 +34,7 @@ func NuevoRepositorioFactura(db *gorm.DB, empresaID uint) RepositorioFactura {
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repositorioFactura) Listar(filtros FiltrosFactura) ([]models.Factura, error) {
|
||||
func (r *repositorioFactura) Listar(filtros decorator.FiltrosFactura) ([]models.Factura, error) {
|
||||
var facturas []models.Factura
|
||||
|
||||
paginar := filtros.Pagina > 0 || filtros.PorPagina > 0
|
||||
@@ -41,8 +48,47 @@ func (r *repositorioFactura) Listar(filtros FiltrosFactura) ([]models.Factura, e
|
||||
|
||||
func (r *repositorioFactura) ObtenerConRelaciones(id uint) (*models.Factura, error) {
|
||||
var factura models.Factura
|
||||
if err := r.db.Preload("Cliente").First(&factura, id).Error; err != nil {
|
||||
if err := r.db.Preload("Cliente").Preload("Almacen").First(&factura, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &factura, nil
|
||||
}
|
||||
|
||||
func (r *repositorioFactura) CrearConDetalles(tx *gorm.DB, factura *models.Factura) error {
|
||||
if r.empresaID > 0 {
|
||||
factura.EmpresaID = r.empresaID
|
||||
}
|
||||
return tx.Create(factura).Error
|
||||
}
|
||||
|
||||
func (r *repositorioFactura) BloquearPorID(tx *gorm.DB, id uint) (*models.Factura, error) {
|
||||
var factura models.Factura
|
||||
db := tx
|
||||
if r.empresaID > 0 {
|
||||
db = db.Where("empresa_id = ?", r.empresaID)
|
||||
}
|
||||
if err := db.Set("gorm:query_option", "FOR UPDATE").Preload("Cliente").First(&factura, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &factura, nil
|
||||
}
|
||||
|
||||
func (r *repositorioFactura) ActualizarEstadoSaldo(tx *gorm.DB, id uint, estado string, saldo float64) error {
|
||||
db := tx.Model(&models.Factura{})
|
||||
if r.empresaID > 0 {
|
||||
db = db.Where("empresa_id = ?", r.empresaID)
|
||||
}
|
||||
return db.Where("id = ?", id).Updates(map[string]any{
|
||||
"estado": estado,
|
||||
"saldo": saldo,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *repositorioFactura) ExisteNumero(numero string) (bool, error) {
|
||||
var count int64
|
||||
db := r.db.Model(&models.Factura{})
|
||||
if err := db.Where("numero = ?", numero).Count(&count).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
@@ -37,6 +37,7 @@ func main() {
|
||||
&models.Stock{},
|
||||
&models.MovimientoStock{},
|
||||
&models.Factura{},
|
||||
&models.ComprobanteSecuencia{},
|
||||
&models.OrdenCompra{},
|
||||
&models.Devolucion{},
|
||||
&models.Reserva{},
|
||||
@@ -87,6 +88,8 @@ func main() {
|
||||
routes.ProveedorRoute(r)
|
||||
routes.ClienteRoute(r)
|
||||
routes.FacturaRoute(r)
|
||||
routes.DescuentoRoute(r)
|
||||
routes.FormaDePagoRoute(r)
|
||||
routes.StockRoute(r)
|
||||
|
||||
r.Run(":8080")
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
descuento "repuestera_back/controllers/descuentos"
|
||||
"repuestera_back/middleware"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func DescuentoRoute(r *gin.Engine) {
|
||||
grupo := r.Group("/descuentos")
|
||||
grupo.Use(middleware.AuthMiddleware(15))
|
||||
{
|
||||
grupo.GET("/", descuento.ObtenerDescuentos)
|
||||
}
|
||||
}
|
||||
@@ -22,5 +22,6 @@ func FacturaRoute(r *gin.Engine) {
|
||||
escritura := r.Group("/facturas")
|
||||
escritura.Use(middleware.AuthMiddleware(15))
|
||||
{
|
||||
escritura.POST("/", factura.CrearFactura)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
formapago "repuestera_back/controllers/formasPago"
|
||||
"repuestera_back/middleware"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func FormaDePagoRoute(r *gin.Engine) {
|
||||
grupo := r.Group("/formas-pago")
|
||||
grupo.Use(middleware.AuthMiddleware(15))
|
||||
{
|
||||
grupo.GET("/", formapago.ObtenerFormasPago)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export interface ItemFacturaPayload {
|
||||
repuestoId: number;
|
||||
cantidad: number;
|
||||
precioUnitario: number;
|
||||
}
|
||||
|
||||
export interface PagoFacturaPayload {
|
||||
formaDePagoId: number;
|
||||
importe: number;
|
||||
fecha?: string;
|
||||
observacion?: string;
|
||||
}
|
||||
|
||||
export interface CrearFacturaPayload {
|
||||
clienteId: number;
|
||||
almacenId: number;
|
||||
items: ItemFacturaPayload[];
|
||||
descuentoId?: number;
|
||||
pagos?: PagoFacturaPayload[];
|
||||
enviarEmail?: boolean;
|
||||
observacion?: string;
|
||||
}
|
||||
|
||||
export async function crearFactura(payload: CrearFacturaPayload) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/facturas/`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerDescuentos(fetch2?: Function) {
|
||||
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||
try {
|
||||
const req = await fetchfn(`${API_URL}/descuentos/`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerFormasPago(fetch2?: Function) {
|
||||
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||
try {
|
||||
const req = await fetchfn(`${API_URL}/formas-pago/`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -104,7 +104,7 @@
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-2">
|
||||
<h1 class="page-title">Gestión de Facturas</h1>
|
||||
{#if puedeVentas}
|
||||
<Button icon={Add} onclick={() => (info = 'La creación de facturas se implementa en CU-02.')}>
|
||||
<Button icon={Add} onclick={() => goto('/facturas/nueva')}>
|
||||
Nueva Factura
|
||||
</Button>
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import {
|
||||
Button,
|
||||
InlineNotification,
|
||||
Modal,
|
||||
NumberInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
TextInput,
|
||||
DataTable
|
||||
} from 'carbon-components-svelte';
|
||||
import { Add, TrashCan, ArrowLeft } from 'carbon-icons-svelte';
|
||||
import { goto, invalidate } from '$app/navigation';
|
||||
import { crearFactura } from '$lib/hooks/facturas/crearFactura';
|
||||
import type { Cliente, Repuesto, Almacen } from '../../../types';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
let clientes = $derived<Cliente[]>(Array.isArray(data.clientes) ? data.clientes : []);
|
||||
let repuestos = $derived<Repuesto[]>(Array.isArray(data.repuestos) ? data.repuestos : []);
|
||||
let almacenes = $derived<Almacen[]>(Array.isArray(data.almacenes) ? data.almacenes : []);
|
||||
let descuentos = $derived<any[]>(Array.isArray(data.descuentos) ? data.descuentos : []);
|
||||
let formasPago = $derived<any[]>(Array.isArray(data.formasPago) ? data.formasPago : []);
|
||||
|
||||
let clienteId = $state<number>(0);
|
||||
let almacenId = $state<number>(0);
|
||||
let descuentoId = $state<number>(0);
|
||||
let enviarEmail = $state(false);
|
||||
let observacion = $state('');
|
||||
|
||||
interface Item {
|
||||
repuestoId: number;
|
||||
cantidad: number;
|
||||
precioUnitario: number;
|
||||
}
|
||||
let items = $state<Item[]>([{ repuestoId: 0, cantidad: 1, precioUnitario: 0 }]);
|
||||
|
||||
let pagoImporte = $state<number>(0);
|
||||
let pagoFormaId = $state<number>(0);
|
||||
let registrarPago = $state(false);
|
||||
|
||||
function agregarItem() {
|
||||
items = [...items, { repuestoId: 0, cantidad: 1, precioUnitario: 0 }];
|
||||
}
|
||||
|
||||
function quitarItem(i: number) {
|
||||
items = items.filter((_, idx) => idx !== i);
|
||||
if (items.length === 0) items = [{ repuestoId: 0, cantidad: 1, precioUnitario: 0 }];
|
||||
}
|
||||
|
||||
function precioRepuesto(id: number): number {
|
||||
const r = repuestos.find((x) => x.ID === id);
|
||||
return r ? r.precio : 0;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
for (const it of items) {
|
||||
if (it.repuestoId > 0 && it.precioUnitario === 0) {
|
||||
it.precioUnitario = precioRepuesto(it.repuestoId);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let subtotal = $derived(
|
||||
items.reduce((acc, it) => acc + (it.cantidad > 0 ? it.cantidad * (it.precioUnitario || 0) : 0), 0)
|
||||
);
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
let baseImponible = $derived(subtotal - descuentoTotal);
|
||||
let impuestos = $derived(baseImponible * 0.21);
|
||||
let total = $derived(baseImponible + impuestos);
|
||||
|
||||
async function enviar() {
|
||||
if (enviando) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
if (!clienteId) { error = 'Seleccioná un cliente.'; enviando = false; return; }
|
||||
if (!almacenId) { error = 'Seleccioná un almacén.'; enviando = false; return; }
|
||||
const itemsValidos = items.filter((i) => i.repuestoId > 0 && i.cantidad > 0);
|
||||
if (itemsValidos.length === 0) { error = 'Agregá al menos un ítem válido.'; enviando = false; return; }
|
||||
|
||||
const payload = {
|
||||
clienteId,
|
||||
almacenId,
|
||||
items: itemsValidos.map((i) => ({
|
||||
repuestoId: i.repuestoId,
|
||||
cantidad: i.cantidad,
|
||||
precioUnitario: i.precioUnitario || precioRepuesto(i.repuestoId)
|
||||
})),
|
||||
descuentoId: descuentoId || undefined,
|
||||
pagos: registrarPago && pagoImporte > 0 ? [{ formaDePagoId: pagoFormaId, importe: pagoImporte }] : undefined,
|
||||
enviarEmail,
|
||||
observacion: observacion.trim() || undefined
|
||||
};
|
||||
|
||||
const res = await crearFactura(payload);
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('facturas:load');
|
||||
void goto('/facturas');
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
|
||||
<div class="page-container">
|
||||
<div class="mb-4 flex items-center gap-2">
|
||||
<Button kind="ghost" icon={ArrowLeft} onclick={() => goto('/facturas')}>Volver</Button>
|
||||
<h1 class="page-title">Crear Factura de Venta</h1>
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
<div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
<div class="space-y-4">
|
||||
<div class="rounded border p-4">
|
||||
<h2 class="mb-3 text-lg font-semibold">Datos del Cliente</h2>
|
||||
<Select labelText="Cliente" bind:selected={clienteId}>
|
||||
<SelectItem value={0} text="Seleccioná un cliente" />
|
||||
{#each clientes as c (c.ID)}
|
||||
<SelectItem value={c.ID} text={`${c.nombre} (${c.cuit ?? ''})`} />
|
||||
{/each}
|
||||
</Select>
|
||||
{#if clienteId}
|
||||
{@const c = clientes.find((x) => x.ID === clienteId)}
|
||||
{#if c}
|
||||
<p class="mt-2 text-sm text-gray-400">Email: {c.email ?? '-'} · CUIT: {c.cuit ?? '-'}</p>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="rounded border p-4">
|
||||
<h2 class="mb-3 text-lg font-semibold">Almacén</h2>
|
||||
<Select labelText="Almacén de origen" bind:selected={almacenId}>
|
||||
<SelectItem value={0} text="Seleccioná un almacén" />
|
||||
{#each almacenes as a (a.id)}
|
||||
<SelectItem value={a.id} text={a.ubicacion ? `${a.codigo} · ${a.ubicacion}` : a.codigo} />
|
||||
{/each}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="rounded border p-4">
|
||||
<h2 class="mb-3 text-lg font-semibold">Descuento</h2>
|
||||
<Select labelText="Descuento" bind:selected={descuentoId}>
|
||||
<SelectItem value={0} text="Sin descuento" />
|
||||
{#each descuentos as d (d.ID)}
|
||||
<SelectItem value={d.ID} text={`${d.Nombre} (${d.Tipo === 'PORCENTAJE' ? d.Valor + '%' : '$' + d.Valor})`} />
|
||||
{/each}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="rounded border p-4">
|
||||
<label class="flex items-center gap-2">
|
||||
<input type="checkbox" bind:checked={enviarEmail} />
|
||||
<span>Enviar comprobante por email al cliente</span>
|
||||
</label>
|
||||
<div class="mt-3">
|
||||
<TextInput labelText="Observación" bind:value={observacion} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div class="rounded border p-4">
|
||||
<div class="mb-3 flex items-center justify-between">
|
||||
<h2 class="text-lg font-semibold">Ítems de la Venta</h2>
|
||||
<Button size="small" icon={Add} onclick={agregarItem}>Agregar Ítem</Button>
|
||||
</div>
|
||||
<div class="space-y-3">
|
||||
{#each items as it, i (i)}
|
||||
<div class="grid grid-cols-12 items-end gap-2">
|
||||
<div class="col-span-5">
|
||||
<Select labelText="Producto" bind:selected={it.repuestoId}>
|
||||
<SelectItem value={0} text="Seleccioná" />
|
||||
{#each repuestos as r (r.ID)}
|
||||
<SelectItem value={r.ID} text={r.nombre} />
|
||||
{/each}
|
||||
</Select>
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<NumberInput labelText="Cantidad" bind:value={it.cantidad} min={0} step={1} />
|
||||
</div>
|
||||
<div class="col-span-3">
|
||||
<NumberInput labelText="Precio Unit." bind:value={it.precioUnitario} min={0} step={0.01} />
|
||||
</div>
|
||||
<div class="col-span-1 text-right text-sm">
|
||||
{(it.cantidad * (it.precioUnitario || 0)).toLocaleString('es-AR', { style: 'currency', currency: 'ARS' })}
|
||||
</div>
|
||||
<div class="col-span-1">
|
||||
<Button kind="danger-ghost" size="small" icon={TrashCan} onclick={() => quitarItem(i)} />
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded border p-4">
|
||||
<h2 class="mb-3 text-lg font-semibold">Totales</h2>
|
||||
<div class="space-y-1 text-sm">
|
||||
<div class="flex justify-between"><span>Subtotal</span><span>{subtotal.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' })}</span></div>
|
||||
<div class="flex justify-between"><span>Descuento</span><span>{descuentoTotal.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' })}</span></div>
|
||||
<div class="flex justify-between"><span>IVA (21%)</span><span>{impuestos.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' })}</span></div>
|
||||
<div class="flex justify-between text-lg font-bold"><span>Total</span><span>{total.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' })}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded border p-4">
|
||||
<label class="flex items-center gap-2">
|
||||
<input type="checkbox" bind:checked={registrarPago} />
|
||||
<span>Registrar pago inmediato</span>
|
||||
</label>
|
||||
{#if registrarPago}
|
||||
<div class="mt-3 grid grid-cols-2 gap-3">
|
||||
<Select labelText="Forma de pago" bind:selected={pagoFormaId}>
|
||||
<SelectItem value={0} text="Seleccioná" />
|
||||
{#each formasPago as f (f.ID)}
|
||||
<SelectItem value={f.ID} text={f.descripcion ?? f.Descripcion} />
|
||||
{/each}
|
||||
</Select>
|
||||
<NumberInput labelText="Importe" bind:value={pagoImporte} min={0} step={0.01} />
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-2">
|
||||
<Button kind="secondary" onclick={() => goto('/facturas')}>Cancelar</Button>
|
||||
<Button onclick={enviar} disabled={enviando}>
|
||||
{enviando ? 'Registrando...' : 'Registrar Venta'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,28 @@
|
||||
import { obtenerFacturas } from '$lib/hooks/facturas/obtenerFacturas';
|
||||
import { obtenerClientes } from '$lib/hooks/clientes/obtenerClientes';
|
||||
import { obtenerRepuestos } from '$lib/hooks/repuestos/obtenerRepuestos';
|
||||
import { obtenerAlmacenes } from '$lib/hooks/almacenes/obtenerAlmacenes';
|
||||
import { obtenerDescuentos } from '$lib/hooks/facturas/obtenerDescuentos';
|
||||
import { obtenerFormasPago } from '$lib/hooks/facturas/obtenerFormasPago';
|
||||
|
||||
export let ssr = false;
|
||||
|
||||
export async function load({ fetch, depends }) {
|
||||
depends('facturas:nueva:load');
|
||||
const [clientes, repuestos, almacenes, descuentos, formasPago] = await Promise.all([
|
||||
obtenerClientes(fetch),
|
||||
obtenerRepuestos(fetch),
|
||||
obtenerAlmacenes(fetch),
|
||||
obtenerDescuentos(fetch),
|
||||
obtenerFormasPago(fetch)
|
||||
]);
|
||||
return {
|
||||
clientes: Array.isArray(clientes) ? clientes : [],
|
||||
repuestos: Array.isArray(repuestos) ? repuestos : [],
|
||||
almacenes: Array.isArray(almacenes) ? almacenes : [],
|
||||
descuentos: Array.isArray(descuentos) ? descuentos : [],
|
||||
formasPago: Array.isArray(formasPago) ? formasPago : [],
|
||||
errorClientes: typeof clientes === 'string' ? clientes : '',
|
||||
errorRepuestos: typeof repuestos === 'string' ? repuestos : ''
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user