diff --git a/back/dto/Builders/FacturaResponseBuilder.go b/back/dto/Builders/FacturaResponseBuilder.go index a9e5919..57853b6 100644 --- a/back/dto/Builders/FacturaResponseBuilder.go +++ b/back/dto/Builders/FacturaResponseBuilder.go @@ -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, diff --git a/back/dto/Facturas/FacturaResponse.go b/back/dto/Facturas/FacturaResponse.go index abbb0f9..88b5ada 100644 --- a/back/dto/Facturas/FacturaResponse.go +++ b/back/dto/Facturas/FacturaResponse.go @@ -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"` diff --git a/back/models/factura.go b/back/models/factura.go index 762c08a..f69bc63 100644 --- a/back/models/factura.go +++ b/back/models/factura.go @@ -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 { diff --git a/back/models/factura_detalle.go b/back/models/factura_detalle.go index aa5c495..4004caa 100644 --- a/back/models/factura_detalle.go +++ b/back/models/factura_detalle.go @@ -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"` } diff --git a/back/models/pago.go b/back/models/pago.go index 66defda..dc2edfc 100644 --- a/back/models/pago.go +++ b/back/models/pago.go @@ -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 { diff --git a/back/repositorios/ContenedorRepositorios.go b/back/repositorios/ContenedorRepositorios.go index ea2054e..93737c3 100644 --- a/back/repositorios/ContenedorRepositorios.go +++ b/back/repositorios/ContenedorRepositorios.go @@ -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), diff --git a/back/repositorios/Decorator/facturas/DecoradorOrdenFacturas.go b/back/repositorios/Decorator/facturas/DecoradorOrdenFacturas.go new file mode 100644 index 0000000..8081fd8 --- /dev/null +++ b/back/repositorios/Decorator/facturas/DecoradorOrdenFacturas.go @@ -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") +} diff --git a/back/repositorios/Decorator/facturas/NuevaQueryFacturas.go b/back/repositorios/Decorator/facturas/NuevaQueryFacturas.go index 295250d..e98949e 100644 --- a/back/repositorios/Decorator/facturas/NuevaQueryFacturas.go +++ b/back/repositorios/Decorator/facturas/NuevaQueryFacturas.go @@ -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") -} diff --git a/back/repositorios/RepositorioFactura.go b/back/repositorios/RepositorioFactura.go index df909f5..fc044cc 100644 --- a/back/repositorios/RepositorioFactura.go +++ b/back/repositorios/RepositorioFactura.go @@ -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 +} diff --git a/back/router.go b/back/router.go index 63ea366..3c91a87 100644 --- a/back/router.go +++ b/back/router.go @@ -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") diff --git a/back/routes/DescuentoRoute.go b/back/routes/DescuentoRoute.go new file mode 100644 index 0000000..27b78c1 --- /dev/null +++ b/back/routes/DescuentoRoute.go @@ -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) + } +} diff --git a/back/routes/FacturaRoute.go b/back/routes/FacturaRoute.go index 568cef5..499c1c6 100644 --- a/back/routes/FacturaRoute.go +++ b/back/routes/FacturaRoute.go @@ -22,5 +22,6 @@ func FacturaRoute(r *gin.Engine) { escritura := r.Group("/facturas") escritura.Use(middleware.AuthMiddleware(15)) { + escritura.POST("/", factura.CrearFactura) } } diff --git a/back/routes/FormaDePagoRoute.go b/back/routes/FormaDePagoRoute.go new file mode 100644 index 0000000..88967de --- /dev/null +++ b/back/routes/FormaDePagoRoute.go @@ -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) + } +} diff --git a/front/src/lib/hooks/facturas/crearFactura.ts b/front/src/lib/hooks/facturas/crearFactura.ts new file mode 100644 index 0000000..4da2343 --- /dev/null +++ b/front/src/lib/hooks/facturas/crearFactura.ts @@ -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'; + } +} diff --git a/front/src/lib/hooks/facturas/obtenerDescuentos.ts b/front/src/lib/hooks/facturas/obtenerDescuentos.ts new file mode 100644 index 0000000..3cbbedc --- /dev/null +++ b/front/src/lib/hooks/facturas/obtenerDescuentos.ts @@ -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'; + } +} diff --git a/front/src/lib/hooks/facturas/obtenerFormasPago.ts b/front/src/lib/hooks/facturas/obtenerFormasPago.ts new file mode 100644 index 0000000..362932f --- /dev/null +++ b/front/src/lib/hooks/facturas/obtenerFormasPago.ts @@ -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'; + } +} diff --git a/front/src/routes/facturas/+page.svelte b/front/src/routes/facturas/+page.svelte index 4653aa2..aecaca7 100644 --- a/front/src/routes/facturas/+page.svelte +++ b/front/src/routes/facturas/+page.svelte @@ -104,7 +104,7 @@