Private
Public Access
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94a4e292c4 | ||
|
|
b6b2e7d465 | ||
|
|
77b27df6dd | ||
|
|
442140e412 | ||
|
|
a6112ca23e | ||
|
|
65540d8425 | ||
|
|
3db4c9fe62 | ||
|
|
dbc445ca56 | ||
|
|
ab59bd7043 | ||
|
|
1073c69d5c | ||
|
|
6ffc398b19 | ||
|
|
09830e15ec | ||
|
|
b68db07c92 | ||
|
|
7742618bf7 | ||
|
|
320cc9c241 | ||
|
|
fcf16df5d3 | ||
|
|
bc0db6dbee | ||
|
|
12276acbd8 | ||
|
|
3587a8dbc6 | ||
|
|
0f2c438643 | ||
|
|
bda647011e | ||
|
|
6f375cee45 | ||
|
|
ea009e276f | ||
|
|
a9ec514687 | ||
|
|
0160ba90d4 | ||
|
|
837fd8fa44 | ||
|
|
fe5b5d7a00 | ||
|
|
cc80dd1467 | ||
|
|
42bf987ffc | ||
|
|
3c4bc5c008 | ||
|
|
31f8b493d0 | ||
|
|
298f3c699c | ||
|
|
61baaf14f8 | ||
|
|
15dc28ca15 | ||
|
|
72f55e6773 | ||
|
|
c93199b636 | ||
|
|
9fa5cf63f9 | ||
|
|
67ca0c8222 | ||
|
|
c3f3513853 | ||
|
|
ee050fa0b3 |
No files matched your search
@@ -14,3 +14,5 @@ comms/.idea/
|
||||
skills/
|
||||
/scripts/.idea
|
||||
/scripts/.bsp
|
||||
front/.svelte-kit.old/
|
||||
node_modules/
|
||||
@@ -1,145 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// tablasTenant son las tablas de negocio que se filtran por empresa_id.
|
||||
var tablasTenant = []string{
|
||||
"groupos",
|
||||
"almacen",
|
||||
"marca",
|
||||
"repuesto",
|
||||
"stock",
|
||||
"movimiento_stock",
|
||||
"clientes",
|
||||
"descuentos",
|
||||
"forma_de_pago",
|
||||
"proveedors",
|
||||
"pago",
|
||||
"logs",
|
||||
"reservas",
|
||||
"factura",
|
||||
"recibo",
|
||||
"remitos",
|
||||
"diferencia_remito",
|
||||
"nota_credito",
|
||||
"nota_debito",
|
||||
"orden_compra",
|
||||
"devolucion",
|
||||
"asiento_contables",
|
||||
"movimiento_contables",
|
||||
"cuenta_contables",
|
||||
}
|
||||
|
||||
// MigrarMultitenant hace el backfill necesario para pasar de una instalación
|
||||
// de una sola empresa a una base compartida con empresa_id. Es idempotente.
|
||||
func MigrarMultitenant() error {
|
||||
empresaID, err := empresaDefault()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, tabla := range tablasTenant {
|
||||
if !DB.Migrator().HasTable(tabla) || !DB.Migrator().HasColumn(tabla, "empresa_id") {
|
||||
continue
|
||||
}
|
||||
if err := DB.Exec("UPDATE `"+tabla+"` SET empresa_id = ? WHERE empresa_id IS NULL OR empresa_id = 0", empresaID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := migrarJoinAntiguo(); err != nil {
|
||||
log.Printf("multitenant: no se pudo migrar el join antiguo usuario_grupos: %v", err)
|
||||
}
|
||||
|
||||
if err := asegurarMembresias(empresaID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func empresaDefault() (uint, error) {
|
||||
var empresa models_seguridad.Empresa
|
||||
err := DB.Order("id ASC").First(&empresa).Error
|
||||
if err == nil {
|
||||
return empresa.ID, nil
|
||||
}
|
||||
if err != gorm.ErrRecordNotFound {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
empresa = models_seguridad.Empresa{
|
||||
ID: 1,
|
||||
Nombre: "Repuestera",
|
||||
Slug: "repuestera",
|
||||
Activa: true,
|
||||
}
|
||||
if err := DB.Create(&empresa).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return empresa.ID, nil
|
||||
}
|
||||
|
||||
func migrarJoinAntiguo() error {
|
||||
if !DB.Migrator().HasTable("usuario_grupos") || !DB.Migrator().HasTable("usuarios_grupos") {
|
||||
return nil
|
||||
}
|
||||
return DB.Exec(
|
||||
"INSERT IGNORE INTO usuarios_grupos (usuario_id, grupo_id) SELECT usuario_id, grupo_id FROM usuario_grupos",
|
||||
).Error
|
||||
}
|
||||
|
||||
// asegurarMembresias garantiza que todos los usuarios existentes tengan
|
||||
// membresía en la empresa default. El primer usuario queda como OWNER.
|
||||
func asegurarMembresias(empresaID uint) error {
|
||||
var usuarios []models_seguridad.Usuario
|
||||
if err := DB.Order("id ASC").Find(&usuarios).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for i, usuario := range usuarios {
|
||||
var count int64
|
||||
if err := DB.Model(&models_seguridad.EmpresaUsuario{}).
|
||||
Where("empresa_id = ? AND usuario_id = ?", empresaID, usuario.ID).
|
||||
Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
rol := models_seguridad.RolMiembro
|
||||
if i == 0 {
|
||||
rol = models_seguridad.RolOwner
|
||||
}
|
||||
if err := DB.Create(&models_seguridad.EmpresaUsuario{
|
||||
EmpresaID: empresaID,
|
||||
UsuarioID: usuario.ID,
|
||||
Rol: rol,
|
||||
Activo: true,
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Si no hay ningún owner, promover al usuario más antiguo de la empresa.
|
||||
var owners int64
|
||||
DB.Model(&models_seguridad.EmpresaUsuario{}).
|
||||
Where("empresa_id = ? AND rol = ? AND activo = ?", empresaID, models_seguridad.RolOwner, true).
|
||||
Count(&owners)
|
||||
if owners > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var primera models_seguridad.EmpresaUsuario
|
||||
if err := DB.Where("empresa_id = ?", empresaID).Order("usuario_id ASC").First(&primera).Error; err != nil {
|
||||
return nil
|
||||
}
|
||||
return DB.Model(&primera).Update("rol", models_seguridad.RolOwner).Error
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
)
|
||||
|
||||
// MigrarAlmacen convierte la vieja tabla almacen (id varchar) al nuevo esquema
|
||||
// con id numérico y codigo. Se ejecuta antes de AutoMigrate para que GORM no
|
||||
// intente cambiar una PK referenciada por claves foráneas incompatibles.
|
||||
func MigrarAlmacen() error {
|
||||
if !DB.Migrator().HasTable("almacen") || !DB.Migrator().HasColumn("almacen", "id") {
|
||||
return nil
|
||||
}
|
||||
|
||||
var tipo string
|
||||
if err := DB.Raw(`
|
||||
SELECT DATA_TYPE FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'almacen' AND COLUMN_NAME = 'id'
|
||||
`).Scan(&tipo).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if tipo != "varchar" && tipo != "char" {
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Println("migrando almacen a id numérico...")
|
||||
|
||||
if err := DB.Exec("SET FOREIGN_KEY_CHECKS = 0").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
defer DB.Exec("SET FOREIGN_KEY_CHECKS = 1")
|
||||
|
||||
type fk struct {
|
||||
Tabla string
|
||||
Nombre string
|
||||
}
|
||||
var claves []fk
|
||||
if err := DB.Raw(`
|
||||
SELECT TABLE_NAME AS tabla, CONSTRAINT_NAME AS nombre
|
||||
FROM information_schema.KEY_COLUMN_USAGE
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND REFERENCED_TABLE_NAME = 'almacen'
|
||||
AND REFERENCED_COLUMN_NAME = 'id'
|
||||
`).Scan(&claves).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, clave := range claves {
|
||||
if err := DB.Exec(fmt.Sprintf(
|
||||
"ALTER TABLE `%s` DROP FOREIGN KEY `%s`", clave.Tabla, clave.Nombre,
|
||||
)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
tieneEmpresa := DB.Migrator().HasColumn("almacen", "empresa_id")
|
||||
empresaExpr := "1"
|
||||
if tieneEmpresa {
|
||||
empresaExpr = "COALESCE(empresa_id, 1)"
|
||||
}
|
||||
|
||||
if err := DB.Exec("DROP TABLE IF EXISTS almacen_nuevo").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DB.Exec(`
|
||||
CREATE TABLE almacen_nuevo (
|
||||
id bigint unsigned NOT NULL AUTO_INCREMENT,
|
||||
empresa_id bigint unsigned NOT NULL DEFAULT 1,
|
||||
codigo varchar(5) NOT NULL,
|
||||
ubicacion varchar(40) NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uq_almacen_empresa_codigo (empresa_id, codigo)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := DB.Exec(fmt.Sprintf(
|
||||
"INSERT INTO almacen_nuevo (empresa_id, codigo, ubicacion) SELECT %s, id, ubicacion FROM almacen",
|
||||
empresaExpr,
|
||||
)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := DB.Exec("DROP TABLE IF EXISTS tmp_almacen_map").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DB.Exec(`
|
||||
CREATE TABLE tmp_almacen_map (
|
||||
old_id varchar(5) NOT NULL,
|
||||
new_id bigint unsigned NOT NULL
|
||||
) ENGINE=InnoDB
|
||||
`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DB.Exec(`
|
||||
INSERT INTO tmp_almacen_map (old_id, new_id)
|
||||
SELECT a.id, n.id
|
||||
FROM almacen a
|
||||
JOIN almacen_nuevo n ON n.codigo = a.id AND n.empresa_id = ` + empresaExpr + `
|
||||
`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if DB.Migrator().HasTable("stock") && DB.Migrator().HasColumn("stock", "almacen_id") {
|
||||
if err := DB.Exec(`
|
||||
UPDATE stock s JOIN tmp_almacen_map m ON s.almacen_id = m.old_id
|
||||
SET s.almacen_id = m.new_id
|
||||
`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if DB.Migrator().HasTable("reservas") && DB.Migrator().HasColumn("reservas", "almacen_id") {
|
||||
if err := DB.Exec(`
|
||||
UPDATE reservas r JOIN tmp_almacen_map m ON r.almacen_id = m.old_id
|
||||
SET r.almacen_id = m.new_id
|
||||
`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if DB.Migrator().HasTable("remitos") && DB.Migrator().HasColumn("remitos", "almacen_origen_id") {
|
||||
if err := DB.Exec(`
|
||||
UPDATE remitos r JOIN tmp_almacen_map m ON r.almacen_origen_id = m.old_id
|
||||
SET r.almacen_origen_id = m.new_id
|
||||
`).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := DB.Exec("RENAME TABLE almacen TO almacen_viejo, almacen_nuevo TO almacen").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DB.Exec("DROP TABLE almacen_viejo").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DB.Exec("DROP TABLE tmp_almacen_map").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Println("almacen migrado")
|
||||
return nil
|
||||
}
|
||||
@@ -1,363 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"repuestera_back/models"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// columnasDecimalesStock son las columnas de stock que deben ser decimales.
|
||||
// GORM no las convierte solo con AutoMigrate porque su heuristica de
|
||||
// MigrateColumn no detecta el cambio de tipo cuando el default coincide.
|
||||
var columnasDecimalesStock = map[string]bool{
|
||||
"cantidad": true,
|
||||
"cantidad_reservada": true,
|
||||
}
|
||||
|
||||
// columnasMovimientosLegado son las columnas JSON historicas de stock.
|
||||
// "movmientos" es el typo original y "movimientos" el nombre corregido.
|
||||
var columnasMovimientosLegado = []string{"movmientos", "movimientos"}
|
||||
|
||||
// MigrarStock completa la preparacion de datos posterior a AutoMigrate:
|
||||
// - garantiza los almacenes por defecto por empresa;
|
||||
// - convierte las cantidades de stock a decimal;
|
||||
// - migra el JSON historico de stock a la tabla movimiento_stock;
|
||||
// - elimina la columna con el typo historico.
|
||||
//
|
||||
// Es idempotente: las filas ya migradas quedan con movimientos = NULL y la
|
||||
// columna legada se elimina una sola vez.
|
||||
func MigrarStock() error {
|
||||
if !DB.Migrator().HasTable("stock") {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := sembrarAlmacenDefault(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := migrarTiposStock(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := migrarMovimientosLegado(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := migrarDetallesDevolucion(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return eliminarColumnaMovmientos()
|
||||
}
|
||||
|
||||
func sembrarAlmacenDefault() error {
|
||||
if _, err := empresaDefault(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var empresas []models_seguridad.Empresa
|
||||
if err := DB.Find(&empresas).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, empresa := range empresas {
|
||||
almacenes := []models.Almacen{
|
||||
{Codigo: "A1", Ubicacion: "Deposito principal"},
|
||||
{Codigo: "A2", Ubicacion: "Deposito secundario"},
|
||||
}
|
||||
|
||||
for _, almacen := range almacenes {
|
||||
var count int64
|
||||
if err := DB.Model(&models.Almacen{}).
|
||||
Where("empresa_id = ? AND codigo = ?", empresa.ID, almacen.Codigo).
|
||||
Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
almacen.EmpresaID = empresa.ID
|
||||
if err := DB.Create(&almacen).Error; err != nil {
|
||||
return fmt.Errorf("crear almacen %s de empresa %d: %w", almacen.Codigo, empresa.ID, err)
|
||||
}
|
||||
log.Printf("stock: almacen %s creado para empresa %d", almacen.Codigo, empresa.ID)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// migrarTiposStock convierte a decimal las columnas de cantidad si quedaron
|
||||
// como enteros de una version anterior.
|
||||
func migrarTiposStock() error {
|
||||
columnas, err := DB.Migrator().ColumnTypes(&models.Stock{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("leer columnas de stock: %w", err)
|
||||
}
|
||||
|
||||
for _, columna := range columnas {
|
||||
if !columnasDecimalesStock[columna.Name()] {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(columna.DatabaseTypeName(), "decimal") {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := DB.Migrator().AlterColumn(&models.Stock{}, columna.Name()); err != nil {
|
||||
return fmt.Errorf("convertir stock.%s a decimal: %w", columna.Name(), err)
|
||||
}
|
||||
log.Printf("stock: columna stock.%s convertida a decimal", columna.Name())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrarMovimientosLegado() error {
|
||||
if !DB.Migrator().HasTable("movimiento_stock") {
|
||||
return nil
|
||||
}
|
||||
|
||||
columnas := columnasLegadoExistentes()
|
||||
if len(columnas) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
type stockLegado struct {
|
||||
ID uint64
|
||||
EmpresaID uint64
|
||||
RepuestoID uint64
|
||||
AlmacenID uint
|
||||
Movmientos []byte
|
||||
Movimientos []byte
|
||||
}
|
||||
|
||||
condiciones := make([]string, len(columnas))
|
||||
for i, columna := range columnas {
|
||||
condiciones[i] = columna + " IS NOT NULL"
|
||||
}
|
||||
|
||||
var filas []stockLegado
|
||||
if err := DB.Table("stock").
|
||||
Select("id, empresa_id, repuesto_id, almacen_id, " + strings.Join(columnas, ", ")).
|
||||
Where(strings.Join(condiciones, " OR ")).
|
||||
Scan(&filas).Error; err != nil {
|
||||
return fmt.Errorf("leer movimientos legados de stock: %w", err)
|
||||
}
|
||||
|
||||
migradas := 0
|
||||
for _, fila := range filas {
|
||||
movs, err := parsearMovimientosLegados(fila.Movmientos)
|
||||
if err != nil {
|
||||
return fmt.Errorf("stock %d (movmientos): %w", fila.ID, err)
|
||||
}
|
||||
otros, err := parsearMovimientosLegados(fila.Movimientos)
|
||||
if err != nil {
|
||||
return fmt.Errorf("stock %d (movimientos): %w", fila.ID, err)
|
||||
}
|
||||
movs = append(movs, otros...)
|
||||
|
||||
if len(movs) == 0 {
|
||||
if err := limpiarMovimientosLegados(DB, fila.ID, columnas); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if err := migrarFilaMovimientos(fila.ID, fila.EmpresaID, fila.RepuestoID, fila.AlmacenID, columnas, movs); err != nil {
|
||||
return err
|
||||
}
|
||||
migradas++
|
||||
}
|
||||
|
||||
if migradas > 0 {
|
||||
log.Printf("stock: %d filas con movimientos migradas a movimiento_stock", migradas)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func columnasLegadoExistentes() []string {
|
||||
var columnas []string
|
||||
for _, columna := range columnasMovimientosLegado {
|
||||
if DB.Migrator().HasColumn("stock", columna) {
|
||||
columnas = append(columnas, columna)
|
||||
}
|
||||
}
|
||||
return columnas
|
||||
}
|
||||
|
||||
func parsearMovimientosLegados(raw []byte) ([]models.MovimientoStockLegacy, error) {
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var movs []models.MovimientoStockLegacy
|
||||
if err := json.Unmarshal(raw, &movs); err != nil {
|
||||
return nil, fmt.Errorf("json de movimientos invalido: %w", err)
|
||||
}
|
||||
return movs, nil
|
||||
}
|
||||
|
||||
func migrarFilaMovimientos(stockID, empresaID, repuestoID uint64, almacenID uint, columnas []string, movs []models.MovimientoStockLegacy) error {
|
||||
return DB.Transaction(func(tx *gorm.DB) error {
|
||||
var pendientes int64
|
||||
condiciones := make([]string, len(columnas))
|
||||
for i, columna := range columnas {
|
||||
condiciones[i] = columna + " IS NOT NULL"
|
||||
}
|
||||
if err := tx.Table("stock").
|
||||
Where("id = ? AND ("+strings.Join(condiciones, " OR ")+")", stockID).
|
||||
Count(&pendientes).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if pendientes == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
empresa := empresaID
|
||||
if empresa == 0 {
|
||||
empresa = 1
|
||||
}
|
||||
|
||||
for _, legado := range movs {
|
||||
tipo := strings.ToUpper(strings.TrimSpace(legado.Tipo))
|
||||
if tipo == "" {
|
||||
tipo = string(models.MovimientoLegado)
|
||||
}
|
||||
|
||||
fecha := legado.Fecha
|
||||
if fecha.IsZero() {
|
||||
fecha = time.Now()
|
||||
}
|
||||
|
||||
movimiento := models.MovimientoStock{
|
||||
EmpresaID: empresa,
|
||||
StockID: stockID,
|
||||
RepuestoID: repuestoID,
|
||||
AlmacenID: almacenID,
|
||||
Tipo: models.TipoMovimientoStock(tipo),
|
||||
Cantidad: legado.Cantidad,
|
||||
ReferenciaTipo: "LEGACY",
|
||||
ReferenciaID: stockID,
|
||||
UsuarioID: legado.UsuarioID,
|
||||
Observacion: "Migrado desde stock.movimientos (JSON legado)",
|
||||
Fecha: fecha,
|
||||
CreatedAt: fecha,
|
||||
}
|
||||
if err := tx.Create(&movimiento).Error; err != nil {
|
||||
return fmt.Errorf("stock %d: crear movimiento: %w", stockID, err)
|
||||
}
|
||||
}
|
||||
|
||||
return limpiarMovimientosLegados(tx, stockID, columnas)
|
||||
})
|
||||
}
|
||||
|
||||
// migrarDetallesDevolucion pasa los renglones de la tabla devolucion_detalle
|
||||
// a la columna JSON devolucion.detalles y elimina la tabla vieja.
|
||||
func migrarDetallesDevolucion() error {
|
||||
if !DB.Migrator().HasTable("devolucion") || !DB.Migrator().HasColumn("devolucion", "detalles") {
|
||||
return nil
|
||||
}
|
||||
if !DB.Migrator().HasTable("devolucion_detalle") {
|
||||
return nil
|
||||
}
|
||||
|
||||
type filaDetalle struct {
|
||||
DevolucionID uint
|
||||
RepuestoID uint64
|
||||
Cantidad float64
|
||||
PrecioUnitario float64
|
||||
Subtotal float64
|
||||
}
|
||||
|
||||
var filas []filaDetalle
|
||||
if err := DB.Table("devolucion_detalle").
|
||||
Select("devolucion_id, repuesto_id, cantidad, precio_unitario, subtotal").
|
||||
Order("devolucion_id ASC, id ASC").
|
||||
Scan(&filas).Error; err != nil {
|
||||
return fmt.Errorf("leer devolucion_detalle: %w", err)
|
||||
}
|
||||
|
||||
agrupadas := make(map[uint][]models.DevolucionDetalle)
|
||||
for _, fila := range filas {
|
||||
agrupadas[fila.DevolucionID] = append(agrupadas[fila.DevolucionID], models.DevolucionDetalle{
|
||||
RepuestoID: fila.RepuestoID,
|
||||
Cantidad: fila.Cantidad,
|
||||
PrecioUnitario: fila.PrecioUnitario,
|
||||
Subtotal: fila.Subtotal,
|
||||
})
|
||||
}
|
||||
|
||||
migradas := 0
|
||||
for devolucionID, detalles := range agrupadas {
|
||||
var actual string
|
||||
if err := DB.Table("devolucion").
|
||||
Select("COALESCE(detalles, '[]')").
|
||||
Where("id = ?", devolucionID).
|
||||
Scan(&actual).Error; err != nil {
|
||||
return fmt.Errorf("leer devolucion %d: %w", devolucionID, err)
|
||||
}
|
||||
if actual != "" && actual != "[]" && actual != "null" {
|
||||
continue
|
||||
}
|
||||
|
||||
jsonDetalles, err := json.Marshal(detalles)
|
||||
if err != nil {
|
||||
return fmt.Errorf("serializar detalles de devolucion %d: %w", devolucionID, err)
|
||||
}
|
||||
if err := DB.Exec("UPDATE devolucion SET detalles = ? WHERE id = ?", string(jsonDetalles), devolucionID).Error; err != nil {
|
||||
return fmt.Errorf("actualizar devolucion %d: %w", devolucionID, err)
|
||||
}
|
||||
migradas++
|
||||
}
|
||||
|
||||
if err := DB.Migrator().DropTable("devolucion_detalle"); err != nil {
|
||||
return fmt.Errorf("eliminar tabla devolucion_detalle: %w", err)
|
||||
}
|
||||
if migradas > 0 {
|
||||
log.Printf("stock: %d devoluciones migradas a detalles JSON", migradas)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func limpiarMovimientosLegados(tx *gorm.DB, stockID uint64, columnas []string) error {
|
||||
asignaciones := make([]string, len(columnas))
|
||||
for i, columna := range columnas {
|
||||
asignaciones[i] = columna + " = NULL"
|
||||
}
|
||||
return tx.Exec(
|
||||
"UPDATE stock SET "+strings.Join(asignaciones, ", ")+" WHERE id = ?",
|
||||
stockID,
|
||||
).Error
|
||||
}
|
||||
|
||||
// eliminarColumnaMovmientos borra la columna con el typo historico una vez
|
||||
// que sus datos ya fueron migrados a movimiento_stock.
|
||||
func eliminarColumnaMovmientos() error {
|
||||
const columna = "movmientos"
|
||||
if !DB.Migrator().HasColumn("stock", columna) {
|
||||
return nil
|
||||
}
|
||||
|
||||
var pendientes int64
|
||||
if err := DB.Table("stock").Where(columna + " IS NOT NULL").Count(&pendientes).Error; err != nil {
|
||||
return fmt.Errorf("verificar stock.%s antes de eliminarla: %w", columna, err)
|
||||
}
|
||||
if pendientes > 0 {
|
||||
return fmt.Errorf("stock.%s tiene %d filas sin migrar; no se elimina", columna, pendientes)
|
||||
}
|
||||
|
||||
if err := DB.Migrator().DropColumn(&models.Stock{}, columna); err != nil {
|
||||
return fmt.Errorf("eliminar columna stock.%s: %w", columna, err)
|
||||
}
|
||||
log.Printf("stock: columna stock.%s eliminada", columna)
|
||||
return nil
|
||||
}
|
||||
+24
-16
@@ -29,6 +29,10 @@ var permisosSemilla = []permisoSemilla{
|
||||
{10, "Gestión de Almacenes", "almacenes", "Consultar y administrar los almacenes de la empresa."},
|
||||
{11, "Gestión de Proveedores", "proveedores", "Consultar y administrar los proveedores de la empresa."},
|
||||
{12, "Gestión de Clientes", "clientes", "Consultar y administrar los clientes de la empresa."},
|
||||
{14, "Generar Reporte de Stock", "stock/reportes", "Generar y consultar reportes de stock."},
|
||||
{15, "Gestión de Ventas y Facturación", "facturas", "Consultar y operar la facturación y ventas de la empresa."},
|
||||
{16, "Gestión de Descuentos", "descuentos", "Crear, editar y eliminar descuentos."},
|
||||
{17, "Gestión de Formas de Pago", "formas-pago", "Crear, editar y eliminar formas de pago."},
|
||||
}
|
||||
|
||||
// InitPermisos crea el catálogo global de permisos y garantiza que cada
|
||||
@@ -75,28 +79,32 @@ func AsegurarGruposEmpresa(db *gorm.DB, empresaID uint) (uint, uint, error) {
|
||||
}
|
||||
|
||||
permisosAdmin := []uint{
|
||||
models_seguridad.PermisoGestionGrupos,
|
||||
models_seguridad.PermisoGestionUsuarios,
|
||||
models_seguridad.PermisoGestionRepuestos,
|
||||
models_seguridad.PermisoGestionLogs,
|
||||
models_seguridad.PermisoGestionMarcas,
|
||||
models_seguridad.PermisoGestionEmpresa,
|
||||
models_seguridad.PermisoGestionStock,
|
||||
models_seguridad.PermisoGestionAlmacenes,
|
||||
models_seguridad.PermisoGestionProveedores,
|
||||
models_seguridad.PermisoGestionClientes,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
6,
|
||||
5,
|
||||
7,
|
||||
9,
|
||||
10,
|
||||
11,
|
||||
12,
|
||||
13,
|
||||
14,
|
||||
16,
|
||||
}
|
||||
if err := asignarPermisosFaltantes(db, admin.ID, permisosAdmin); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
permisosUsuario := []uint{
|
||||
models_seguridad.PermisoGestionRepuestos,
|
||||
models_seguridad.PermisoGestionMarcas,
|
||||
models_seguridad.PermisoGestionStock,
|
||||
models_seguridad.PermisoGestionAlmacenes,
|
||||
models_seguridad.PermisoGestionProveedores,
|
||||
models_seguridad.PermisoGestionClientes,
|
||||
4,
|
||||
5,
|
||||
9,
|
||||
10,
|
||||
11,
|
||||
12,
|
||||
13,
|
||||
}
|
||||
if err := asignarPermisosFaltantes(db, usuario.ID, permisosUsuario); err != nil {
|
||||
return 0, 0, err
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package almacen
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
dto "repuestera_back/dto/Almacenes"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ActualizarAlmacen(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
did := uint(id)
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Almacen
|
||||
almacen, err := repo.ObtenerPorID(did)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Almacén no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
var data dto.AlmacenDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
input, err := dto_directors.NewAlmacenDirector().Actualizar(data)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if existing, _ := repo.BuscarPorCodigo(input.Codigo); existing != nil && existing.ID != almacen.ID {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un almacén con ese código"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := repo.ActualizarCompleto(almacen, *input, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
actualizado, err := repo.ObtenerPorID(did)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, almacen)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, actualizado)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package almacen
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func AltaAlmacen(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Almacen
|
||||
almacen, err := repo.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Almacén no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
if !almacen.DeletedAt.Valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "El almacén no está eliminado"})
|
||||
return
|
||||
}
|
||||
|
||||
almacen.DeletedAt = gorm.DeletedAt{}
|
||||
if err := repo.Alta(almacen, *almacen, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -4,23 +4,29 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
dto "repuestera_back/dto/Almacenes"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto "repuestera_back/dto/Almacenes"
|
||||
"repuestera_back/models"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func CrearAlmacen(c *gin.Context) {
|
||||
var data dto.CrearAlmacenDto
|
||||
var data dto.AlmacenDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
almacen, err := dto_directors.NewAlmacenDirector().Crear(data)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Almacen
|
||||
if _, err := repo.BuscarPorCodigo(data.Codigo); err == nil {
|
||||
if _, err := repo.BuscarPorCodigo(almacen.Codigo); err == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un almacén con ese código"})
|
||||
return
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
@@ -28,17 +34,16 @@ func CrearAlmacen(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
almacen := models.Almacen{Codigo: data.Codigo, Ubicacion: data.Ubicacion}
|
||||
if err := repo.Crear(almacen, c.GetUint("userID")); err != nil {
|
||||
if err := repo.Crear(*almacen, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
creado, err := repo.BuscarPorCodigo(data.Codigo)
|
||||
creado, err := repo.BuscarPorCodigo(almacen.Codigo)
|
||||
if err != nil {
|
||||
c.Status(http.StatusCreated)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, creado)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package almacen
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func EliminarAlmacen(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios(c).Almacen.Baja(uint(id), c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package almacen
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ObtenerTodosLosAlmacenes(c *gin.Context) {
|
||||
almacenes, err := r.ObtenerRepositorios(c).Almacen.ObtenerTodos()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, almacenes)
|
||||
}
|
||||
@@ -57,7 +57,7 @@ func CambiarContraseña(c *gin.Context) {
|
||||
empresaID := utils.EmpresaID(c)
|
||||
rolCaller := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
||||
|
||||
esAdmin := utils.UsuarioTienePermiso(c, models_seguridad.PermisoGestionUsuarios) || rolCaller.EsAdministrador()
|
||||
esAdmin := utils.UsuarioTienePermiso(c, 3) || rolCaller.EsAdministrador()
|
||||
if !esAdmin {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para cambiar la contraseña de otro usuario"})
|
||||
return
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package descuento
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
dto "repuestera_back/dto/Descuentos"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ActualizarDescuento(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
did := uint(id)
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Descuento
|
||||
descuento, err := repo.ObtenerPorID(did)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Descuento no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
var data dto.DescuentoDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
input, err := dto_directors.NewDescuentoDirector().Actualizar(data, descuento.Activo)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if existing, _ := repo.ObtenerPorNombre(input.Nombre); existing != nil && existing.ID != descuento.ID {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un descuento con ese nombre"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := repo.ActualizarCompleto(descuento, *input, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
actualizado, err := repo.ObtenerPorID(did)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, descuento)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, actualizado)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package descuento
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// AltaDescuento reactiva un descuento dado de baja lógicamente.
|
||||
func AltaDescuento(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Descuento
|
||||
descuento, err := repo.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Descuento no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
if !descuento.DeletedAt.Valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "El descuento no está eliminado"})
|
||||
return
|
||||
}
|
||||
|
||||
descuento.DeletedAt = gorm.DeletedAt{}
|
||||
if err := repo.Alta(descuento, *descuento, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package descuento
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
dto "repuestera_back/dto/Descuentos"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func CrearDescuento(c *gin.Context) {
|
||||
var data dto.DescuentoDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
descuento, err := dto_directors.NewDescuentoDirector().Crear(data)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Descuento
|
||||
if _, err := repo.ObtenerPorNombre(descuento.Nombre); err == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un descuento con ese nombre"})
|
||||
return
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := repo.Crear(*descuento, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
creado, err := repo.ObtenerPorNombre(descuento.Nombre)
|
||||
if err != nil {
|
||||
c.Status(http.StatusCreated)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, creado)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package descuento
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func EliminarDescuento(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios(c).Descuento.Baja(uint(id), c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package descuento
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func ObtenerDescuentos(c *gin.Context) {
|
||||
descuentos, err := r.ObtenerRepositorios(c).Descuento.ListarActivos()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, descuentos)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package descuento
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ObtenerTodosLosDescuentos lista todos los descuentos de la empresa,
|
||||
// incluyendo los inactivos y los dados de baja, para la pantalla de gestión.
|
||||
func ObtenerTodosLosDescuentos(c *gin.Context) {
|
||||
descuentos, err := r.ObtenerRepositorios(c).Descuento.ObtenerTodos()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, descuentos)
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"strings"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
|
||||
@@ -14,9 +13,10 @@ import (
|
||||
|
||||
func ActualizarEmpresa(c *gin.Context) {
|
||||
var req struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit string `json:"cuit"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit string `json:"cuit"`
|
||||
EmailAlertaStock *[]string `json:"email_alerta_stock"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
@@ -30,13 +30,31 @@ func ActualizarEmpresa(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
input := models_seguridad.Empresa{Nombre: strings.TrimSpace(req.Nombre), Slug: strings.TrimSpace(req.Slug)}
|
||||
if req.Cuit != "" {
|
||||
if strings.TrimSpace(req.Nombre) != "" {
|
||||
empresa.Nombre = strings.TrimSpace(req.Nombre)
|
||||
}
|
||||
if strings.TrimSpace(req.Slug) != "" {
|
||||
empresa.Slug = strings.TrimSpace(req.Slug)
|
||||
}
|
||||
if strings.TrimSpace(req.Cuit) != "" {
|
||||
cuit := strings.TrimSpace(req.Cuit)
|
||||
input.Cuit = &cuit
|
||||
empresa.Cuit = &cuit
|
||||
}
|
||||
if req.EmailAlertaStock != nil {
|
||||
limpios := make([]string, 0, len(*req.EmailAlertaStock))
|
||||
vistos := make(map[string]bool)
|
||||
for _, email := range *req.EmailAlertaStock {
|
||||
email = strings.TrimSpace(email)
|
||||
if email == "" || vistos[email] {
|
||||
continue
|
||||
}
|
||||
vistos[email] = true
|
||||
limpios = append(limpios, email)
|
||||
}
|
||||
empresa.EmailAlertaStock = limpios
|
||||
}
|
||||
|
||||
if err := repo.Empresa.Actualizar(empresa, input); err != nil {
|
||||
if err := repo.Empresa.Actualizar(empresa, *empresa); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package factura
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
// Esto tendria que cancelar la factura en caso de que no este pagada y ademas crear una nota de credito
|
||||
func CancelarFactura(c *gin.Context) {
|
||||
c.Status(200)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
func CrearFactura(c *gin.Context) {
|
||||
var data dto.CrearFacturaDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resultado, err := services.CrearFactura(
|
||||
repositorios.BaseDeDatos(),
|
||||
repositorios.ObtenerRepositorios(c),
|
||||
utils.EmpresaID(c),
|
||||
c.GetUint("userID"),
|
||||
data,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, resultado)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
)
|
||||
|
||||
// EnviarEmailComprobante envía por email el comprobante de venta al cliente
|
||||
// de la factura indicada. Requiere que el cliente tenga email registrado.
|
||||
func EnviarEmailComprobante(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c)
|
||||
factura, err := repo.Factura.ObtenerConRelaciones(uint(id))
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "factura no encontrada"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if factura.Cliente.Email == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "el cliente no tiene email registrado"})
|
||||
return
|
||||
}
|
||||
|
||||
// Nombres reales de repuestos desde la base de datos.
|
||||
nombres := make(map[uint64]string, len(factura.Detalles))
|
||||
for _, d := range factura.Detalles {
|
||||
repuesto, err := repo.Repuesto.ObtenerPorID(uint(d.RepuestoID))
|
||||
if err == nil && repuesto != nil && *repuesto != nil {
|
||||
nombres[d.RepuestoID] = (*repuesto).Nombre
|
||||
} else {
|
||||
nombres[d.RepuestoID] = fmt.Sprintf("Repuesto %d", d.RepuestoID)
|
||||
}
|
||||
}
|
||||
|
||||
// Pagos realizados de esta factura.
|
||||
pagos, err := repo.Pago.ListarPorFactura(factura.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
mensaje, err := dto_directors.NewEmailDirector().ComprobanteVenta(
|
||||
factura, nombres, pagos, factura.Cliente.Email,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := c.GetUint("userID")
|
||||
if !services.EnviarEmail(*mensaje, userID) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "no se pudo enviar el email"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"mensaje": "email enviado correctamente"})
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package factura
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
func ModificarFactura(c *gin.Context) {
|
||||
c.Status(200)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
dto_facturas "repuestera_back/dto/Facturas"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
// ObtenerComprobante devuelve el detalle de una factura junto con sus pagos,
|
||||
// listo para renderizar el comprobante de venta.
|
||||
func ObtenerComprobante(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c)
|
||||
factura, err := repo.Factura.ObtenerConRelaciones(uint(id))
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "factura no encontrada"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
pagos, err := repo.Pago.ListarPorFactura(factura.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
respuesta, err := dto_directors.NewFacturaDirector().DesdeFactura(factura)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Los nombres se resuelven desde la base de datos: las facturas anteriores
|
||||
// al campo RepuestoNombre no lo tienen guardado en el detalle.
|
||||
for i := range respuesta.Detalles {
|
||||
detalle := &respuesta.Detalles[i]
|
||||
repuesto, err := repo.Repuesto.ObtenerPorID(uint(detalle.RepuestoID))
|
||||
if err == nil && repuesto != nil && *repuesto != nil {
|
||||
detalle.RepuestoNombre = (*repuesto).Nombre
|
||||
} else {
|
||||
detalle.RepuestoNombre = fmt.Sprintf("Repuesto %d", detalle.RepuestoID)
|
||||
}
|
||||
}
|
||||
|
||||
pagosResumen := make([]dto_facturas.PagoResumen, 0, len(pagos))
|
||||
for _, p := range pagos {
|
||||
forma := ""
|
||||
if p.FormaDePago.ID != 0 {
|
||||
forma = p.FormaDePago.Descripcion
|
||||
}
|
||||
pagosResumen = append(pagosResumen, dto_facturas.PagoResumen{
|
||||
ID: p.ID,
|
||||
FacturaID: p.FacturaID,
|
||||
FormaDePagoID: p.FormaDePagoID,
|
||||
FormaDePago: forma,
|
||||
Importe: p.Importe,
|
||||
Fecha: p.Fecha,
|
||||
Observacion: p.Observacion,
|
||||
})
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto_facturas.ComprobanteResponse{
|
||||
FacturaResponse: respuesta,
|
||||
Pagos: pagosResumen,
|
||||
})
|
||||
}
|
||||
@@ -15,6 +15,7 @@ func ObtenerFacturas(c *gin.Context) {
|
||||
filtros := r.FiltrosFactura{
|
||||
Numero: c.Query("numero"),
|
||||
Cliente: c.Query("cliente"),
|
||||
Estado: c.Query("estado"),
|
||||
}
|
||||
|
||||
if raw := c.Query("clienteId"); raw != "" {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
// ObtenerStockDisponible devuelve por repuesto y almacén cuánto stock se puede
|
||||
// vender. Se usa en el alta de factura para mostrar la disponibilidad antes de
|
||||
// vender. Si no se pasa almacenId, devuelve el stock de toda la empresa.
|
||||
func ObtenerStockDisponible(c *gin.Context) {
|
||||
almacenID := uint(0)
|
||||
if raw := c.Query("almacenId"); raw != "" {
|
||||
id, err := strconv.ParseUint(raw, 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "almacenId inválido"})
|
||||
return
|
||||
}
|
||||
almacenID = uint(id)
|
||||
}
|
||||
|
||||
stocks, err := r.ObtenerRepositorios(c).Stock.ListarStockPorAlmacen(almacenID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
respuesta := make([]dto.StockDisponibleResponse, 0, len(stocks))
|
||||
for _, stock := range stocks {
|
||||
disponible := stock.Cantidad - stock.CantidadReservada
|
||||
if disponible < 0 {
|
||||
disponible = 0
|
||||
}
|
||||
respuesta = append(respuesta, dto.StockDisponibleResponse{
|
||||
RepuestoID: stock.RepuestoID,
|
||||
AlmacenID: stock.AlmacenID,
|
||||
Cantidad: redondearStock(stock.Cantidad),
|
||||
CantidadReservada: redondearStock(stock.CantidadReservada),
|
||||
Disponible: redondearStock(disponible),
|
||||
})
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, respuesta)
|
||||
}
|
||||
|
||||
func redondearStock(valor float64) float64 {
|
||||
return math.Round(valor*1000) / 1000
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
// RegistrarPago registra un cobro sobre una factura existente.
|
||||
func RegistrarPago(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
var data dto.RegistrarPagoDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resultado, err := services.RegistrarPagoFactura(
|
||||
repositorios.BaseDeDatos(),
|
||||
repositorios.ObtenerRepositorios(c),
|
||||
utils.EmpresaID(c),
|
||||
c.GetUint("userID"),
|
||||
uint(id),
|
||||
data,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, resultado)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package formapago
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"repuestera_back/models"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ActualizarFormaDePago actualiza una forma de pago existente.
|
||||
func ActualizarFormaDePago(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
if id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||
return
|
||||
}
|
||||
|
||||
// Obtener la forma de pago actual
|
||||
fp, err := r.ObtenerRepositorios(c).FormaDePago.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Forma de pago no encontrada"})
|
||||
return
|
||||
}
|
||||
|
||||
var input models.FormaDePago
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if input.Descripcion == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "La descripción no puede estar vacía"})
|
||||
return
|
||||
}
|
||||
|
||||
// Verificar que no exista otra forma de pago con la misma descripción
|
||||
if existing, _ := r.ObtenerRepositorios(c).FormaDePago.ObtenerPorDescripcion(input.Descripcion); existing != nil && existing.ID != fp.ID {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe una forma de pago con esa descripción"})
|
||||
return
|
||||
}
|
||||
|
||||
uid := c.GetUint("userID")
|
||||
if err := r.ObtenerRepositorios(c).FormaDePago.Actualizar(fp, input, uid); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, fp)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package formapago
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func AltaFormaDePago(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
if id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||
return
|
||||
}
|
||||
|
||||
uid := c.GetUint("userID")
|
||||
fp, err := r.ObtenerRepositorios(c).FormaDePago.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Forma de pago no encontrada"})
|
||||
return
|
||||
}
|
||||
|
||||
if !fp.DeletedAt.Valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Forma de pago no está eliminada"})
|
||||
return
|
||||
}
|
||||
|
||||
fp.DeletedAt = gorm.DeletedAt{}
|
||||
if err := r.ObtenerRepositorios(c).FormaDePago.Alta(fp, *fp, uid); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package formapago
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"repuestera_back/models"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func CrearFormaDePago(c *gin.Context) {
|
||||
var fp models.FormaDePago
|
||||
if err := c.ShouldBindJSON(&fp); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if fp.Descripcion == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "La descripción es obligatoria"})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c).FormaDePago
|
||||
if _, err := repo.ObtenerPorDescripcion(fp.Descripcion); err == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe una forma de pago con esa descripción"})
|
||||
return
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := repo.Crear(fp, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusCreated)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package formapago
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func EliminarFormaDePago(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
if id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||
return
|
||||
}
|
||||
|
||||
uid := c.GetUint("userID")
|
||||
err = r.ObtenerRepositorios(c).FormaDePago.Baja(uint(id), uid)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package formapago
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ObtenerFormaDePago(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
if id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||
return
|
||||
}
|
||||
|
||||
fp, err := r.ObtenerRepositorios(c).FormaDePago.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Forma de pago no encontrada"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, fp)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package formapago
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"repuestera_back/models"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func ObtenerFormasPago(c *gin.Context) {
|
||||
repo := r.ObtenerRepositorios(c).FormaDePago
|
||||
|
||||
var (
|
||||
formas []models.FormaDePago
|
||||
err error
|
||||
)
|
||||
if c.Query("activas") == "true" {
|
||||
formas, err = repo.ListarActivas()
|
||||
} else {
|
||||
formas, err = repo.ObtenerTodos()
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, formas)
|
||||
}
|
||||
@@ -18,10 +18,11 @@ func ActualizarEmpresa(c *gin.Context) {
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit"`
|
||||
Activa *bool `json:"activa"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit"`
|
||||
EmailAlertaStock *[]string `json:"email_alerta_stock"`
|
||||
Activa *bool `json:"activa"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
@@ -49,6 +50,19 @@ func ActualizarEmpresa(c *gin.Context) {
|
||||
empresa.Cuit = &cuit
|
||||
}
|
||||
}
|
||||
if req.EmailAlertaStock != nil {
|
||||
limpios := make([]string, 0, len(*req.EmailAlertaStock))
|
||||
vistos := make(map[string]bool)
|
||||
for _, email := range *req.EmailAlertaStock {
|
||||
email = strings.TrimSpace(email)
|
||||
if email == "" || vistos[email] {
|
||||
continue
|
||||
}
|
||||
vistos[email] = true
|
||||
limpios = append(limpios, email)
|
||||
}
|
||||
empresa.EmailAlertaStock = limpios
|
||||
}
|
||||
if req.Activa != nil {
|
||||
empresa.Activa = *req.Activa
|
||||
}
|
||||
|
||||
@@ -16,12 +16,13 @@ import (
|
||||
|
||||
func CrearEmpresa(c *gin.Context) {
|
||||
var req struct {
|
||||
Nombre string `json:"nombre" binding:"required"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit string `json:"cuit"`
|
||||
OwnerEmail string `json:"owner_email" binding:"required,email"`
|
||||
OwnerName string `json:"owner_name"`
|
||||
OwnerPassword string `json:"owner_password"`
|
||||
Nombre string `json:"nombre" binding:"required"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit string `json:"cuit"`
|
||||
EmailAlertaStock []string `json:"email_alerta_stock"`
|
||||
OwnerEmail string `json:"owner_email" binding:"required,email"`
|
||||
OwnerName string `json:"owner_name"`
|
||||
OwnerPassword string `json:"owner_password"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
@@ -82,6 +83,17 @@ func CrearEmpresa(c *gin.Context) {
|
||||
cuit := strings.TrimSpace(req.Cuit)
|
||||
empresa.Cuit = &cuit
|
||||
}
|
||||
limpios := make([]string, 0, len(req.EmailAlertaStock))
|
||||
vistos := make(map[string]bool)
|
||||
for _, email := range req.EmailAlertaStock {
|
||||
email = strings.TrimSpace(email)
|
||||
if email == "" || vistos[email] {
|
||||
continue
|
||||
}
|
||||
vistos[email] = true
|
||||
limpios = append(limpios, email)
|
||||
}
|
||||
empresa.EmailAlertaStock = limpios
|
||||
|
||||
if err := repo.Empresa.Crear(&empresa, owner.ID); err != nil {
|
||||
if creado {
|
||||
|
||||
@@ -3,6 +3,7 @@ package stock
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
applog "log"
|
||||
"math"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
"repuestera_back/models"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
@@ -52,6 +54,7 @@ func ajustarStock(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuar
|
||||
|
||||
cantidadReal := redondearCantidad(entrada.CantidadReal)
|
||||
var resultado *models.Stock
|
||||
var saldoAnterior float64
|
||||
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
stock, err := repo.Stock.BloquearPorID(tx, entrada.StockID)
|
||||
@@ -65,7 +68,7 @@ func ajustarStock(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuar
|
||||
return fmt.Errorf("%w: reservado %.3f", ErrAjusteBajoReserva, stock.CantidadReservada)
|
||||
}
|
||||
|
||||
saldoAnterior := stock.Cantidad
|
||||
saldoAnterior = stock.Cantidad
|
||||
diferencia := redondearCantidad(cantidadReal - saldoAnterior)
|
||||
stock.Cantidad = cantidadReal
|
||||
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||
@@ -95,5 +98,15 @@ func ajustarStock(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuar
|
||||
{NombreTabla: "stock", Columna: "cantidadReal", ValorNuevo: fmt.Sprintf("%.3f", cantidadReal)},
|
||||
{NombreTabla: "stock", Columna: "motivo", ValorNuevo: entrada.Motivo},
|
||||
})
|
||||
|
||||
// La alerta (A3.1) se dispara fuera de la transacción: si comms falla, el
|
||||
// ajuste ya quedó confirmado y el intento se registra en auditoría.
|
||||
repuesto, err := repo.Repuesto.ObtenerPorID(uint(resultado.RepuestoID))
|
||||
if err != nil || repuesto == nil || *repuesto == nil {
|
||||
applog.Printf("stock: no se pudo cargar el repuesto %d para evaluar el stock bajo: %v", resultado.RepuestoID, err)
|
||||
} else {
|
||||
services.NotificarStockBajo(repo, empresaID, usuarioID, resultado, *repuesto, saldoAnterior)
|
||||
}
|
||||
|
||||
return resultado, nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"repuestera_back/strategy/reporte"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
func ExportarReporte(c *gin.Context) {
|
||||
formato := strings.ToLower(strings.TrimSpace(c.DefaultQuery("formato", "csv")))
|
||||
if formato == "" {
|
||||
formato = "csv"
|
||||
}
|
||||
|
||||
if _, autenticado := utils.PermisosDelContexto(c); autenticado &&
|
||||
!utils.UsuarioTienePermiso(c, 14) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para generar reportes de stock"})
|
||||
return
|
||||
}
|
||||
|
||||
datos, err := obtenerDatosReporte(c)
|
||||
if err != nil {
|
||||
if strings.HasPrefix(err.Error(), "validación:") {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": strings.TrimPrefix(err.Error(), "validación: ")})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
exportador, err := reporte.NuevoExportador(formato)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
timestamp := time.Now().Format("20060102-1504")
|
||||
nombreArchivo := fmt.Sprintf("reporte-stock-%s.%s", timestamp, formato)
|
||||
|
||||
if err := exportador.Exportar(c.Writer, datos.movimientos, datos.resumen, nombreArchivo); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "no se pudo generar el archivo"})
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
dto "repuestera_back/dto/Stock"
|
||||
"repuestera_back/models"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
// parsearFechaReporte acepta varios formatos habituales de fecha.
|
||||
func parsearFechaReporte(valor string) (*time.Time, bool) {
|
||||
valor = strings.TrimSpace(valor)
|
||||
if valor == "" {
|
||||
return nil, false
|
||||
}
|
||||
formatos := []string{
|
||||
time.RFC3339,
|
||||
"2006-01-02",
|
||||
"2006-01-02 15:04:05",
|
||||
"02/01/2006",
|
||||
}
|
||||
for _, formato := range formatos {
|
||||
if t, err := time.Parse(formato, valor); err == nil {
|
||||
return &t, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// parsearFiltrosReporte valida y convierte la query en filtros de repositorio.
|
||||
func parsearFiltrosReporte(c *gin.Context) (r.FiltrosMovimiento, error) {
|
||||
var q dto.FiltrosReporteQuery
|
||||
if err := c.ShouldBindQuery(&q); err != nil {
|
||||
return r.FiltrosMovimiento{}, fmt.Errorf("validación: %w", err)
|
||||
}
|
||||
|
||||
desdeStr := q.Desde
|
||||
if desdeStr == "" {
|
||||
desdeStr = q.FechaDesde
|
||||
}
|
||||
if desdeStr == "" {
|
||||
desdeStr = q.DesdeAlt
|
||||
}
|
||||
hastaStr := q.Hasta
|
||||
if hastaStr == "" {
|
||||
hastaStr = q.FechaHasta
|
||||
}
|
||||
if hastaStr == "" {
|
||||
hastaStr = q.HastaAlt
|
||||
}
|
||||
|
||||
filtros := r.FiltrosMovimiento{
|
||||
StockID: q.StockID,
|
||||
RepuestoID: q.RepuestoID,
|
||||
AlmacenID: q.AlmacenID,
|
||||
Pagina: q.Pagina,
|
||||
PorPagina: q.PorPagina,
|
||||
}
|
||||
if q.Tipo != "" {
|
||||
filtros.Tipo = models.TipoMovimientoStock(strings.ToUpper(strings.TrimSpace(q.Tipo)))
|
||||
}
|
||||
|
||||
var desde, hasta *time.Time
|
||||
if desdeStr != "" {
|
||||
t, ok := parsearFechaReporte(desdeStr)
|
||||
if !ok {
|
||||
return r.FiltrosMovimiento{}, fmt.Errorf("validación: fecha 'desde' inválida")
|
||||
}
|
||||
desde = t
|
||||
}
|
||||
if hastaStr != "" {
|
||||
t, ok := parsearFechaReporte(hastaStr)
|
||||
if !ok {
|
||||
return r.FiltrosMovimiento{}, fmt.Errorf("validación: fecha 'hasta' inválida")
|
||||
}
|
||||
hasta = t
|
||||
}
|
||||
if desde != nil && hasta != nil && desde.After(*hasta) {
|
||||
return r.FiltrosMovimiento{}, fmt.Errorf("validación: el rango de fechas es inválido: 'desde' no puede ser mayor a 'hasta'")
|
||||
}
|
||||
filtros.Desde = desde
|
||||
filtros.Hasta = hasta
|
||||
|
||||
return filtros, nil
|
||||
}
|
||||
|
||||
// datosReporte agrupa la información generada por el caso de uso.
|
||||
type datosReporte struct {
|
||||
movimientos []models.MovimientoStock
|
||||
resumen []dto.ResumenMovimientoResponse
|
||||
tipos []models.TipoMovimientoStock
|
||||
}
|
||||
|
||||
// obtenerDatosReporte ejecuta la consulta y arma la respuesta de dominio.
|
||||
func obtenerDatosReporte(c *gin.Context) (datosReporte, error) {
|
||||
filtros, err := parsearFiltrosReporte(c)
|
||||
if err != nil {
|
||||
return datosReporte{}, err
|
||||
}
|
||||
|
||||
repositorio := r.ObtenerRepositorios(c)
|
||||
|
||||
movimientos, err := repositorio.MovimientoStock.ListarPorRango(filtros)
|
||||
if err != nil {
|
||||
return datosReporte{}, err
|
||||
}
|
||||
resumen, err := repositorio.MovimientoStock.Sumarizar(filtros)
|
||||
if err != nil {
|
||||
return datosReporte{}, err
|
||||
}
|
||||
|
||||
resumenDTO := make([]dto.ResumenMovimientoResponse, 0, len(resumen))
|
||||
for _, item := range resumen {
|
||||
resumenDTO = append(resumenDTO, dto.ResumenMovimientoResponse{
|
||||
Tipo: item.Tipo,
|
||||
Cantidad: item.Cantidad,
|
||||
})
|
||||
}
|
||||
|
||||
tipos := []models.TipoMovimientoStock{
|
||||
models.MovimientoIngreso,
|
||||
models.MovimientoAjuste,
|
||||
models.MovimientoTrasladoSalida,
|
||||
models.MovimientoTrasladoEntrada,
|
||||
models.MovimientoReserva,
|
||||
models.MovimientoLiberacion,
|
||||
models.MovimientoDevolucion,
|
||||
models.MovimientoVenta,
|
||||
models.MovimientoLegado,
|
||||
}
|
||||
|
||||
return datosReporte{
|
||||
movimientos: movimientos,
|
||||
resumen: resumenDTO,
|
||||
tipos: tipos,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func GenerarReporte(c *gin.Context) {
|
||||
if _, autenticado := utils.PermisosDelContexto(c); autenticado &&
|
||||
!utils.UsuarioTienePermiso(c, 14) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para generar reportes de stock"})
|
||||
return
|
||||
}
|
||||
|
||||
datos, err := obtenerDatosReporte(c)
|
||||
if err != nil {
|
||||
if strings.HasPrefix(err.Error(), "validación:") {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": strings.TrimPrefix(err.Error(), "validación: ")})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
director := dto_directors.NewReporteStockDirector()
|
||||
respuesta, err := director.Generar(datos.movimientos, datos.resumen, datos.tipos)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, respuesta)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
"repuestera_back/models"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
"repuestera_back/repositorios"
|
||||
@@ -28,18 +29,8 @@ func notificarDiferencias(
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]string, 0, len(diferencias))
|
||||
detalles := make([]models_logs.LogDetalle, 0, len(diferencias)+5)
|
||||
for _, diferencia := range diferencias {
|
||||
nombre := fmt.Sprintf("Repuesto %d", diferencia.RepuestoID)
|
||||
if repuesto, ok := repuestos[diferencia.RepuestoID]; ok && repuesto != nil {
|
||||
nombre = repuesto.Nombre
|
||||
}
|
||||
|
||||
items = append(items, fmt.Sprintf(
|
||||
"%s | Esperado: %.3f | Recibido: %.3f | Diferencia: %.3f",
|
||||
nombre, diferencia.CantidadEsperada, diferencia.CantidadRecibida, diferencia.Diferencia,
|
||||
))
|
||||
detalles = append(detalles, models_logs.LogDetalle{
|
||||
NombreTabla: "diferencia_remito",
|
||||
Columna: fmt.Sprintf("repuesto_%d", diferencia.RepuestoID),
|
||||
@@ -50,22 +41,17 @@ func notificarDiferencias(
|
||||
})
|
||||
}
|
||||
|
||||
destinatarios := destinatariosDiferencias(repo, empresaID, usuarioID)
|
||||
destinatarios := destinatariosAlertaStock(repo, empresaID, usuarioID)
|
||||
enviado := false
|
||||
if len(destinatarios) > 0 {
|
||||
enviado = services.EnviarEmail(services.MensajeEmail{
|
||||
Titulo: fmt.Sprintf("Diferencia en remito %s", remito.Numero),
|
||||
Descripcion: fmt.Sprintf(
|
||||
"<p>Se detectaron <strong>%d</strong> diferencias al ingresar el remito "+
|
||||
"<strong>%s</strong> del proveedor <strong>%s</strong>.</p>"+
|
||||
"<p>Fecha de emisión: %s</p>"+
|
||||
"<p>Usuario responsable: %d</p>",
|
||||
len(diferencias), remito.Numero, proveedor,
|
||||
remito.FechaEmision.Format("02/01/2006"), usuarioID,
|
||||
),
|
||||
Items: items,
|
||||
Destinatarios: destinatarios,
|
||||
}, usuarioID)
|
||||
mensaje, err := dto_directors.NewEmailDirector().DiferenciasRemito(
|
||||
remito, proveedor, diferencias, repuestos, destinatarios, usuarioID,
|
||||
)
|
||||
if err != nil {
|
||||
applog.Printf("stock: no se pudo construir el aviso de diferencias del remito %s: %v", remito.Numero, err)
|
||||
} else {
|
||||
enviado = services.EnviarEmail(*mensaje, usuarioID)
|
||||
}
|
||||
}
|
||||
|
||||
if enviado {
|
||||
@@ -91,14 +77,20 @@ func notificarDiferencias(
|
||||
registrarLog(repo, empresaID, usuarioID, "DIFERENCIA_REMITO", detalles)
|
||||
}
|
||||
|
||||
// destinatariosDiferencias usa STOCK_ALERT_EMAILS si está configurado. Si no,
|
||||
// destinatariosAlertaStock usa STOCK_ALERT_EMAILS si está configurado. Si no,
|
||||
// avisa a los owners/admins activos de la empresa y, como último recurso, al
|
||||
// usuario que registró el ingreso.
|
||||
func destinatariosDiferencias(repo *repositorios.Repositorios, empresaID, usuarioID uint) []string {
|
||||
// usuario que registró la operación.
|
||||
func destinatariosAlertaStock(repo *repositorios.Repositorios, empresaID, usuarioID uint) []string {
|
||||
if raw := strings.TrimSpace(os.Getenv("STOCK_ALERT_EMAILS")); raw != "" {
|
||||
return limpiarDestinatarios(strings.Split(raw, ","))
|
||||
}
|
||||
|
||||
if empresaID > 0 {
|
||||
if empresa, err := repo.Empresa.ObtenerPorID(empresaID); err == nil && empresa != nil && len(empresa.EmailAlertaStock) > 0 {
|
||||
return limpiarDestinatarios([]string(empresa.EmailAlertaStock))
|
||||
}
|
||||
}
|
||||
|
||||
var destinatarios []string
|
||||
if empresaID > 0 {
|
||||
miembros, _, err := repo.Empresa.ListarMiembros(empresaID, 0, 100)
|
||||
|
||||
@@ -51,7 +51,7 @@ func registrarDevolucion(db *gorm.DB, repo *repositorios.Repositorios, empresaID
|
||||
return nil, fmt.Errorf("%w: la devolución debe tener al menos un ítem", ErrCantidadInvalida)
|
||||
}
|
||||
|
||||
factura, err := repo.Factura.ObtenerPorID(entrada.FacturaID)
|
||||
factura, err := repo.Factura.ObtenerConRelaciones(entrada.FacturaID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: factura %d", ErrItemNoEncontrado, entrada.FacturaID)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package dto
|
||||
|
||||
// AlmacenDto es el cuerpo aceptado para crear o actualizar un almacén.
|
||||
type AlmacenDto struct {
|
||||
Codigo string `json:"codigo"`
|
||||
Ubicacion string `json:"ubicacion"`
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
dto "repuestera_back/dto/Almacenes"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
type AlmacenBuilder struct {
|
||||
dto *dto.AlmacenDto
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[models.Almacen] = (*AlmacenBuilder)(nil)
|
||||
|
||||
func NewAlmacenBuilder() *AlmacenBuilder {
|
||||
return &AlmacenBuilder{}
|
||||
}
|
||||
|
||||
func (b *AlmacenBuilder) ConDto(data dto.AlmacenDto) *AlmacenBuilder {
|
||||
b.dto = &data
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *AlmacenBuilder) Build() (*models.Almacen, error) {
|
||||
if b.dto == nil {
|
||||
return nil, errors.New("faltan los datos del almacén")
|
||||
}
|
||||
|
||||
codigo, ok := ValidarTexto(b.dto.Codigo, "El código", &b.err)
|
||||
if ok {
|
||||
if len([]rune(codigo)) > 5 {
|
||||
AcumularError(&b.err, "El código no puede superar los 5 caracteres")
|
||||
} else {
|
||||
b.dto.Codigo = codigo
|
||||
}
|
||||
}
|
||||
|
||||
ubicacion := strings.TrimSpace(b.dto.Ubicacion)
|
||||
if len([]rune(ubicacion)) > 40 {
|
||||
AcumularError(&b.err, "La ubicación no puede superar los 40 caracteres")
|
||||
} else {
|
||||
b.dto.Ubicacion = ubicacion
|
||||
}
|
||||
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
|
||||
return &models.Almacen{
|
||||
Codigo: b.dto.Codigo,
|
||||
Ubicacion: b.dto.Ubicacion,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
htmlutil "html"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
dto_email "repuestera_back/dto/Email"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// ComprobanteVentaEmailBuilder arma el email de comprobante de venta. Acá viven los
|
||||
// detalles de presentación (tabla, estilos inline y formato de importes); el
|
||||
// director sólo decide qué builder usar.
|
||||
type ComprobanteVentaEmailBuilder struct {
|
||||
factura *models.Factura
|
||||
nombres map[uint64]string
|
||||
pagos []models.Pago
|
||||
destinatario string
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[dto_email.MensajeEmail] = (*ComprobanteVentaEmailBuilder)(nil)
|
||||
|
||||
func NewComprobanteVentaEmailBuilder() *ComprobanteVentaEmailBuilder {
|
||||
return &ComprobanteVentaEmailBuilder{}
|
||||
}
|
||||
|
||||
func (b *ComprobanteVentaEmailBuilder) ConFactura(factura *models.Factura) *ComprobanteVentaEmailBuilder {
|
||||
if factura == nil {
|
||||
AcumularError(&b.err, "la factura no puede ser nula")
|
||||
}
|
||||
b.factura = factura
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *ComprobanteVentaEmailBuilder) ConNombresRepuestos(nombres map[uint64]string) *ComprobanteVentaEmailBuilder {
|
||||
b.nombres = nombres
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *ComprobanteVentaEmailBuilder) ConPagos(pagos []models.Pago) *ComprobanteVentaEmailBuilder {
|
||||
b.pagos = pagos
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *ComprobanteVentaEmailBuilder) ConDestinatario(destinatario string) *ComprobanteVentaEmailBuilder {
|
||||
b.destinatario = strings.TrimSpace(destinatario)
|
||||
if b.destinatario == "" {
|
||||
AcumularError(&b.err, "el destinatario es obligatorio")
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *ComprobanteVentaEmailBuilder) Build() (*dto_email.MensajeEmail, error) {
|
||||
if b.factura == nil && b.err == nil {
|
||||
AcumularError(&b.err, "falta la factura")
|
||||
}
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
|
||||
return NewMensajeEmailBuilder().
|
||||
ConTitulo("Comprobante de venta " + b.factura.Numero).
|
||||
ConDescripcion(htmlComprobanteVenta(b.factura, b.nombres, b.pagos)).
|
||||
ConItems([]string{}).
|
||||
ConDestinatarios([]string{b.destinatario}).
|
||||
Build()
|
||||
}
|
||||
|
||||
const (
|
||||
comprobanteColorPrimary = "#0f62fe"
|
||||
comprobanteColorText = "#161616"
|
||||
comprobanteColorMuted = "#525252"
|
||||
comprobanteColorBorder = "#e0e0e0"
|
||||
comprobanteColorSoft = "#f2f4f8"
|
||||
)
|
||||
|
||||
// htmlComprobanteVenta genera el cuerpo HTML del comprobante. Usa tablas y
|
||||
// estilos inline porque los clientes de correo suelen ignorar las hojas de
|
||||
// estilo.
|
||||
func htmlComprobanteVenta(factura *models.Factura, nombres map[uint64]string, pagos []models.Pago) string {
|
||||
var b strings.Builder
|
||||
|
||||
b.WriteString(`<div style="max-width:640px;margin:0 auto;font-family:Arial,Helvetica,sans-serif;color:` + comprobanteColorText + `;">`)
|
||||
b.WriteString(`<div style="background:` + comprobanteColorPrimary + `;color:#ffffff;padding:24px 28px;border-radius:8px 8px 0 0;">`)
|
||||
b.WriteString(`<p style="margin:0;font-size:11px;letter-spacing:2px;text-transform:uppercase;opacity:.85;">Repuestera</p>`)
|
||||
b.WriteString(`<h1 style="margin:8px 0 4px;font-size:24px;">Tu comprobante de venta</h1>`)
|
||||
fmt.Fprintf(&b, `<p style="margin:0;font-size:14px;">Factura <strong>%s</strong></p>`, htmlutil.EscapeString(factura.Numero))
|
||||
b.WriteString(`</div>`)
|
||||
|
||||
b.WriteString(`<div style="border:1px solid ` + comprobanteColorBorder + `;border-top:0;padding:24px 28px;border-radius:0 0 8px 8px;background:#ffffff;">`)
|
||||
b.WriteString(`<table width="100%" cellpadding="0" cellspacing="0" style="font-size:13px;margin-bottom:24px;">`)
|
||||
cliente := htmlutil.EscapeString(factura.Cliente.Nombre)
|
||||
if strings.TrimSpace(cliente) == "" {
|
||||
cliente = "-"
|
||||
}
|
||||
fmt.Fprintf(&b, `<tr><td style="padding:4px 0;color:%s;">Cliente</td><td align="right" style="padding:4px 0;font-weight:600;">%s</td></tr>`, comprobanteColorMuted, cliente)
|
||||
if cuit := strings.TrimSpace(factura.Cliente.Cuit); cuit != "" {
|
||||
fmt.Fprintf(&b, `<tr><td style="padding:4px 0;color:%s;">CUIT</td><td align="right" style="padding:4px 0;">%s</td></tr>`, comprobanteColorMuted, htmlutil.EscapeString(cuit))
|
||||
}
|
||||
fmt.Fprintf(&b, `<tr><td style="padding:4px 0;color:%s;">Fecha de emisión</td><td align="right" style="padding:4px 0;">%s</td></tr>`, comprobanteColorMuted, factura.FechaEmision.Format("02/01/2006"))
|
||||
fmt.Fprintf(&b, `<tr><td style="padding:4px 0;color:%s;">Estado</td><td align="right" style="padding:4px 0;font-weight:600;">%s</td></tr>`, comprobanteColorMuted, htmlutil.EscapeString(factura.Estado))
|
||||
b.WriteString(`</table>`)
|
||||
|
||||
b.WriteString(`<h2 style="margin:0 0 10px;font-size:14px;letter-spacing:1px;text-transform:uppercase;color:` + comprobanteColorMuted + `;">Detalle de la compra</h2>`)
|
||||
b.WriteString(`<table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;font-size:13px;">`)
|
||||
b.WriteString(`<thead><tr style="background:` + comprobanteColorSoft + `;color:` + comprobanteColorMuted + `;text-align:left;">`)
|
||||
b.WriteString(`<th style="padding:10px 8px;">Repuesto</th>`)
|
||||
b.WriteString(`<th align="right" style="padding:10px 8px;">Cant.</th>`)
|
||||
b.WriteString(`<th align="right" style="padding:10px 8px;">Precio unit.</th>`)
|
||||
b.WriteString(`<th align="right" style="padding:10px 8px;">Subtotal</th>`)
|
||||
b.WriteString(`</tr></thead><tbody>`)
|
||||
|
||||
if len(factura.Detalles) == 0 {
|
||||
b.WriteString(`<tr><td colspan="4" style="padding:12px 8px;color:` + comprobanteColorMuted + `;">Sin detalles</td></tr>`)
|
||||
}
|
||||
for _, detalle := range factura.Detalles {
|
||||
nombre := detalle.RepuestoID // placeholder, se reemplaza abajo
|
||||
_ = nombre
|
||||
nombreRepuesto := fmt.Sprintf("Repuesto %d", detalle.RepuestoID)
|
||||
if n := strings.TrimSpace(nombres[detalle.RepuestoID]); n != "" {
|
||||
nombreRepuesto = n
|
||||
}
|
||||
fmt.Fprintf(&b,
|
||||
`<tr style="border-bottom:1px solid %s;"><td style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;font-weight:600;">%s</td></tr>`,
|
||||
comprobanteColorBorder, htmlutil.EscapeString(nombreRepuesto),
|
||||
formatoCantidad(detalle.Cantidad),
|
||||
montoComprobante(detalle.PrecioUnitario), montoComprobante(detalle.Subtotal),
|
||||
)
|
||||
}
|
||||
b.WriteString(`</tbody></table>`)
|
||||
|
||||
b.WriteString(`<table width="100%" cellpadding="0" cellspacing="0" style="margin-top:18px;font-size:13px;">`)
|
||||
fmt.Fprintf(&b, `<tr><td style="padding:4px 8px;color:%s;">Subtotal</td><td align="right" style="padding:4px 8px;">%s</td></tr>`, comprobanteColorMuted, montoComprobante(factura.Subtotal))
|
||||
if factura.DescuentoTotal > 0 {
|
||||
fmt.Fprintf(&b, `<tr><td style="padding:4px 8px;color:%s;">Descuento</td><td align="right" style="padding:4px 8px;color:#da1e28;">-%s</td></tr>`, comprobanteColorMuted, montoComprobante(factura.DescuentoTotal))
|
||||
}
|
||||
alicuota := factura.AlicuotaIVA
|
||||
if alicuota == 0 {
|
||||
alicuota = 21
|
||||
}
|
||||
fmt.Fprintf(&b, `<tr><td style="padding:4px 8px;color:%s;">IVA (%.0f%%)</td><td align="right" style="padding:4px 8px;">%s</td></tr>`, comprobanteColorMuted, alicuota, montoComprobante(factura.Impuestos))
|
||||
fmt.Fprintf(&b,
|
||||
`<tr><td style="padding:12px 8px 4px;border-top:2px solid %s;font-size:18px;font-weight:700;">Total</td><td align="right" style="padding:12px 8px 4px;border-top:2px solid %s;font-size:18px;font-weight:700;color:%s;">%s</td></tr>`,
|
||||
comprobanteColorBorder, comprobanteColorBorder, comprobanteColorPrimary, montoComprobante(factura.Total),
|
||||
)
|
||||
if factura.Saldo > 0 {
|
||||
fmt.Fprintf(&b, `<tr><td style="padding:4px 8px;color:%s;">Saldo a pagar</td><td align="right" style="padding:4px 8px;font-weight:600;">%s</td></tr>`, comprobanteColorMuted, montoComprobante(factura.Saldo))
|
||||
}
|
||||
b.WriteString(`</table>`)
|
||||
|
||||
// Sección de pagos realizados
|
||||
if len(pagos) > 0 {
|
||||
b.WriteString(`<h2 style="margin:24px 0 10px;font-size:14px;letter-spacing:1px;text-transform:uppercase;color:` + comprobanteColorMuted + `;">Pagos realizados</h2>`)
|
||||
b.WriteString(`<table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;font-size:13px;">`)
|
||||
b.WriteString(`<thead><tr style="background:` + comprobanteColorSoft + `;color:` + comprobanteColorMuted + `;text-align:left;">`)
|
||||
b.WriteString(`<th style="padding:10px 8px;">Fecha</th>`)
|
||||
b.WriteString(`<th align="right" style="padding:10px 8px;">Forma de pago</th>`)
|
||||
b.WriteString(`<th align="right" style="padding:10px 8px;">Importe</th>`)
|
||||
b.WriteString(`<th align="right" style="padding:10px 8px;">Observación</th>`)
|
||||
b.WriteString(`</tr></thead><tbody>`)
|
||||
for _, pago := range pagos {
|
||||
forma := "-"
|
||||
if pago.FormaDePago.ID != 0 {
|
||||
forma = pago.FormaDePago.Descripcion
|
||||
}
|
||||
fechaStr := pago.Fecha.Format("02/01/2006 15:04")
|
||||
obs := pago.Observacion
|
||||
if obs == "" {
|
||||
obs = "-"
|
||||
}
|
||||
fmt.Fprintf(&b,
|
||||
`<tr style="border-bottom:1px solid %s;"><td style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;font-weight:600;">%s</td><td style="padding:10px 8px;color:%s;">%s</td></tr>`,
|
||||
comprobanteColorBorder, fechaStr, htmlutil.EscapeString(forma), montoComprobante(pago.Importe), comprobanteColorMuted, htmlutil.EscapeString(obs),
|
||||
)
|
||||
}
|
||||
b.WriteString(`</tbody></table>`)
|
||||
}
|
||||
|
||||
if observacion := strings.TrimSpace(factura.Observacion); observacion != "" {
|
||||
fmt.Fprintf(&b, `<p style="margin:20px 0 0;font-size:12px;color:%s;"><strong>Observación:</strong> %s</p>`, comprobanteColorMuted, htmlutil.EscapeString(observacion))
|
||||
}
|
||||
|
||||
b.WriteString(`<p style="margin:24px 0 0;padding-top:16px;border-top:1px solid ` + comprobanteColorBorder + `;font-size:12px;color:` + comprobanteColorMuted + `;">Gracias por elegirnos. Si tenés consultas sobre esta factura, respondé a este correo.</p>`)
|
||||
b.WriteString(`</div></div>`)
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// formatoCantidad devuelve la cantidad como número entero si no tiene decimales,
|
||||
// o con coma decimal si los tiene (formato AR).
|
||||
func formatoCantidad(cantidad float64) string {
|
||||
if cantidad == float64(int64(cantidad)) {
|
||||
return strconv.FormatInt(int64(cantidad), 10)
|
||||
}
|
||||
// Tiene decimales: mostrar con coma
|
||||
centavos := int64(math.Round(cantidad * 100))
|
||||
entero := centavos / 100
|
||||
dec := centavos % 100
|
||||
if dec == 0 {
|
||||
return strconv.FormatInt(entero, 10)
|
||||
}
|
||||
return fmt.Sprintf("%d,%02d", entero, dec)
|
||||
}
|
||||
|
||||
// montoComprobante formatea importes con separador de miles y coma decimal.
|
||||
func montoComprobante(valor float64) string {
|
||||
negativo := valor < 0
|
||||
if negativo {
|
||||
valor = -valor
|
||||
}
|
||||
centavos := int64(math.Round(valor * 100))
|
||||
digits := strconv.FormatInt(centavos/100, 10)
|
||||
|
||||
var conPuntos strings.Builder
|
||||
for i, ch := range digits {
|
||||
if i > 0 && (len(digits)-i)%3 == 0 {
|
||||
conPuntos.WriteByte('.')
|
||||
}
|
||||
conPuntos.WriteRune(ch)
|
||||
}
|
||||
|
||||
signo := ""
|
||||
if negativo {
|
||||
signo = "-"
|
||||
}
|
||||
return fmt.Sprintf("%s$ %s,%02d", signo, conPuntos.String(), centavos%100)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
type CrearFacturaBuilder struct {
|
||||
datos *dto.FacturaCalculada
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[models.Factura] = (*CrearFacturaBuilder)(nil)
|
||||
|
||||
func NewCrearFacturaBuilder() *CrearFacturaBuilder {
|
||||
return &CrearFacturaBuilder{}
|
||||
}
|
||||
|
||||
func (b *CrearFacturaBuilder) ConDatos(datos dto.FacturaCalculada) *CrearFacturaBuilder {
|
||||
b.datos = &datos
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CrearFacturaBuilder) Build() (*models.Factura, error) {
|
||||
if b.datos == nil {
|
||||
return nil, errors.New("faltan los datos de la factura")
|
||||
}
|
||||
|
||||
datos := b.datos
|
||||
if strings.TrimSpace(datos.Numero) == "" {
|
||||
AcumularError(&b.err, "el número de factura es obligatorio")
|
||||
}
|
||||
if datos.ClienteID == 0 {
|
||||
AcumularError(&b.err, "el cliente es obligatorio")
|
||||
}
|
||||
if datos.AlmacenID == 0 {
|
||||
AcumularError(&b.err, "el almacén es obligatorio")
|
||||
}
|
||||
if datos.ResponsableID == 0 {
|
||||
AcumularError(&b.err, "el responsable es obligatorio")
|
||||
}
|
||||
if datos.FechaEmision.IsZero() {
|
||||
AcumularError(&b.err, "la fecha de emisión es obligatoria")
|
||||
}
|
||||
if len(datos.Detalles) == 0 {
|
||||
AcumularError(&b.err, "la factura debe tener al menos un detalle")
|
||||
}
|
||||
if datos.Subtotal < 0 {
|
||||
AcumularError(&b.err, "el subtotal no puede ser negativo")
|
||||
}
|
||||
if datos.DescuentoTotal < 0 {
|
||||
AcumularError(&b.err, "el descuento no puede ser negativo")
|
||||
}
|
||||
if datos.Impuestos < 0 {
|
||||
AcumularError(&b.err, "los impuestos no pueden ser negativos")
|
||||
}
|
||||
if datos.AlicuotaIVA < 0 {
|
||||
AcumularError(&b.err, "la alícuota de IVA no puede ser negativa")
|
||||
}
|
||||
if datos.Total < 0 {
|
||||
AcumularError(&b.err, "el total no puede ser negativo")
|
||||
}
|
||||
if datos.Saldo < 0 {
|
||||
AcumularError(&b.err, "el saldo no puede ser negativo")
|
||||
}
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
|
||||
factura := &models.Factura{
|
||||
Numero: strings.TrimSpace(datos.Numero),
|
||||
ClienteID: datos.ClienteID,
|
||||
AlmacenID: datos.AlmacenID,
|
||||
FechaEmision: datos.FechaEmision,
|
||||
Subtotal: datos.Subtotal,
|
||||
DescuentoID: datos.DescuentoID,
|
||||
DescuentoTotal: datos.DescuentoTotal,
|
||||
Impuestos: datos.Impuestos,
|
||||
AlicuotaIVA: datos.AlicuotaIVA,
|
||||
Saldo: datos.Saldo,
|
||||
Detalles: append([]models.FacturaDetalle{}, datos.Detalles...),
|
||||
Observacion: strings.TrimSpace(datos.Observacion),
|
||||
Version: 1,
|
||||
}
|
||||
factura.EmpresaID = datos.EmpresaID
|
||||
factura.Estado = "EMITIDA"
|
||||
factura.Total = datos.Total
|
||||
factura.ResponsableID = datos.ResponsableID
|
||||
|
||||
return factura, nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
dto "repuestera_back/dto/Descuentos"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
type DescuentoBuilder struct {
|
||||
dto *dto.DescuentoDto
|
||||
activoPorDefecto bool
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[models.Descuento] = (*DescuentoBuilder)(nil)
|
||||
|
||||
func NewDescuentoBuilder() *DescuentoBuilder {
|
||||
return &DescuentoBuilder{activoPorDefecto: true}
|
||||
}
|
||||
|
||||
func (b *DescuentoBuilder) ConDto(data dto.DescuentoDto) *DescuentoBuilder {
|
||||
b.dto = &data
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *DescuentoBuilder) ConActivoPorDefecto(activo bool) *DescuentoBuilder {
|
||||
b.activoPorDefecto = activo
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *DescuentoBuilder) Build() (*models.Descuento, error) {
|
||||
if b.dto == nil {
|
||||
return nil, errors.New("faltan los datos del descuento")
|
||||
}
|
||||
|
||||
nombre, ok := ValidarTexto(b.dto.Nombre, "El nombre", &b.err)
|
||||
if ok {
|
||||
if len([]rune(nombre)) > 100 {
|
||||
AcumularError(&b.err, "El nombre no puede superar los 100 caracteres")
|
||||
} else {
|
||||
b.dto.Nombre = nombre
|
||||
}
|
||||
}
|
||||
|
||||
descripcion := strings.TrimSpace(b.dto.Descripcion)
|
||||
if len([]rune(descripcion)) > 500 {
|
||||
AcumularError(&b.err, "La descripción no puede superar los 500 caracteres")
|
||||
} else {
|
||||
b.dto.Descripcion = descripcion
|
||||
}
|
||||
|
||||
tipo := models.TipoDescuento(strings.ToUpper(strings.TrimSpace(b.dto.Tipo)))
|
||||
if !tipo.Valido() {
|
||||
AcumularError(&b.err, "El tipo debe ser PORCENTAJE o FIJO")
|
||||
}
|
||||
|
||||
valor := math.Round(b.dto.Valor*100) / 100
|
||||
if valor <= 0 {
|
||||
AcumularError(&b.err, "El valor debe ser mayor a cero")
|
||||
}
|
||||
if tipo.Valido() && tipo == models.Porcentaje && valor > 100 {
|
||||
AcumularError(&b.err, "El porcentaje no puede superar el 100%")
|
||||
}
|
||||
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
|
||||
activo := b.activoPorDefecto
|
||||
if b.dto.Activo != nil {
|
||||
activo = *b.dto.Activo
|
||||
}
|
||||
|
||||
return &models.Descuento{
|
||||
Nombre: b.dto.Nombre,
|
||||
Descripcion: b.dto.Descripcion,
|
||||
Tipo: tipo,
|
||||
Valor: valor,
|
||||
Activo: activo,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
htmlutil "html"
|
||||
|
||||
dto_email "repuestera_back/dto/Email"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// DiferenciasRemitoEmailBuilder arma el aviso de diferencias de un remito.
|
||||
// Resuelve los nombres de repuestos y formatea cada línea en este builder.
|
||||
type DiferenciasRemitoEmailBuilder struct {
|
||||
remito *models.Remito
|
||||
proveedor string
|
||||
diferencias []models.DiferenciaRemito
|
||||
repuestos map[uint64]*models.Repuesto
|
||||
destinatarios []string
|
||||
usuarioID uint
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[dto_email.MensajeEmail] = (*DiferenciasRemitoEmailBuilder)(nil)
|
||||
|
||||
func NewDiferenciasRemitoEmailBuilder() *DiferenciasRemitoEmailBuilder {
|
||||
return &DiferenciasRemitoEmailBuilder{}
|
||||
}
|
||||
|
||||
func (b *DiferenciasRemitoEmailBuilder) ConRemito(remito *models.Remito) *DiferenciasRemitoEmailBuilder {
|
||||
if remito == nil {
|
||||
AcumularError(&b.err, "el remito no puede ser nulo")
|
||||
}
|
||||
b.remito = remito
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *DiferenciasRemitoEmailBuilder) ConProveedor(proveedor string) *DiferenciasRemitoEmailBuilder {
|
||||
b.proveedor = proveedor
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *DiferenciasRemitoEmailBuilder) ConDiferencias(diferencias []models.DiferenciaRemito) *DiferenciasRemitoEmailBuilder {
|
||||
if len(diferencias) == 0 {
|
||||
AcumularError(&b.err, "no hay diferencias para notificar")
|
||||
}
|
||||
b.diferencias = append([]models.DiferenciaRemito(nil), diferencias...)
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *DiferenciasRemitoEmailBuilder) ConRepuestos(repuestos map[uint64]*models.Repuesto) *DiferenciasRemitoEmailBuilder {
|
||||
b.repuestos = repuestos
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *DiferenciasRemitoEmailBuilder) ConDestinatarios(destinatarios []string) *DiferenciasRemitoEmailBuilder {
|
||||
b.destinatarios = destinatarios
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *DiferenciasRemitoEmailBuilder) ConUsuarioID(usuarioID uint) *DiferenciasRemitoEmailBuilder {
|
||||
b.usuarioID = usuarioID
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *DiferenciasRemitoEmailBuilder) Build() (*dto_email.MensajeEmail, error) {
|
||||
if b.remito == nil && b.err == nil {
|
||||
AcumularError(&b.err, "falta el remito")
|
||||
}
|
||||
if len(b.diferencias) == 0 && b.err == nil {
|
||||
AcumularError(&b.err, "faltan las diferencias")
|
||||
}
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
|
||||
items := make([]string, 0, len(b.diferencias))
|
||||
for _, diferencia := range b.diferencias {
|
||||
nombre := fmt.Sprintf("Repuesto %d", diferencia.RepuestoID)
|
||||
if repuesto, ok := b.repuestos[diferencia.RepuestoID]; ok && repuesto != nil {
|
||||
nombre = repuesto.Nombre
|
||||
}
|
||||
|
||||
items = append(items, fmt.Sprintf(
|
||||
"%s | Esperado: %.3f | Recibido: %.3f | Diferencia: %.3f",
|
||||
nombre, diferencia.CantidadEsperada, diferencia.CantidadRecibida, diferencia.Diferencia,
|
||||
))
|
||||
}
|
||||
|
||||
descripcion := fmt.Sprintf(
|
||||
"<p>Se detectaron <strong>%d</strong> diferencias al ingresar el remito "+
|
||||
"<strong>%s</strong> del proveedor <strong>%s</strong>.</p>"+
|
||||
"<p>Fecha de emisión: %s</p>"+
|
||||
"<p>Usuario responsable: %d</p>",
|
||||
len(b.diferencias),
|
||||
htmlutil.EscapeString(b.remito.Numero),
|
||||
htmlutil.EscapeString(b.proveedor),
|
||||
b.remito.FechaEmision.Format("02/01/2006"),
|
||||
b.usuarioID,
|
||||
)
|
||||
|
||||
return NewMensajeEmailBuilder().
|
||||
ConTitulo(fmt.Sprintf("Diferencia en remito %s", b.remito.Numero)).
|
||||
ConDescripcion(descripcion).
|
||||
ConItems(items).
|
||||
ConDestinatarios(b.destinatarios).
|
||||
Build()
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package directors
|
||||
|
||||
import (
|
||||
builders "repuestera_back/dto/Builders"
|
||||
dto "repuestera_back/dto/Almacenes"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
type AlmacenDirector struct{}
|
||||
|
||||
func NewAlmacenDirector() *AlmacenDirector {
|
||||
return &AlmacenDirector{}
|
||||
}
|
||||
|
||||
func (d *AlmacenDirector) Crear(data dto.AlmacenDto) (*models.Almacen, error) {
|
||||
return builders.NewAlmacenBuilder().
|
||||
ConDto(data).
|
||||
Build()
|
||||
}
|
||||
|
||||
func (d *AlmacenDirector) Actualizar(data dto.AlmacenDto) (*models.Almacen, error) {
|
||||
return builders.NewAlmacenBuilder().
|
||||
ConDto(data).
|
||||
Build()
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package directors
|
||||
|
||||
import (
|
||||
builders "repuestera_back/dto/Builders"
|
||||
dto "repuestera_back/dto/Descuentos"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
type DescuentoDirector struct{}
|
||||
|
||||
func NewDescuentoDirector() *DescuentoDirector {
|
||||
return &DescuentoDirector{}
|
||||
}
|
||||
|
||||
func (d *DescuentoDirector) Crear(data dto.DescuentoDto) (*models.Descuento, error) {
|
||||
return builders.NewDescuentoBuilder().
|
||||
ConDto(data).
|
||||
ConActivoPorDefecto(true).
|
||||
Build()
|
||||
}
|
||||
|
||||
func (d *DescuentoDirector) Actualizar(data dto.DescuentoDto, activoPorDefecto bool) (*models.Descuento, error) {
|
||||
return builders.NewDescuentoBuilder().
|
||||
ConDto(data).
|
||||
ConActivoPorDefecto(activoPorDefecto).
|
||||
Build()
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package directors
|
||||
|
||||
import (
|
||||
builders "repuestera_back/dto/Builders"
|
||||
dto_email "repuestera_back/dto/Email"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// EmailDirector centraliza el armado de emails. Cada método elige el builder
|
||||
// correspondiente y le pasa los datos; la presentación y las validaciones
|
||||
// específicas viven en ese builder.
|
||||
type EmailDirector struct{}
|
||||
|
||||
func NewEmailDirector() *EmailDirector {
|
||||
return &EmailDirector{}
|
||||
}
|
||||
|
||||
// ComprobanteVenta arma el email que se envía al cliente después de emitir
|
||||
// una factura.
|
||||
func (d *EmailDirector) ComprobanteVenta(
|
||||
factura *models.Factura,
|
||||
nombresRepuestos map[uint64]string,
|
||||
pagos []models.Pago,
|
||||
destinatario string,
|
||||
) (*dto_email.MensajeEmail, error) {
|
||||
return builders.NewComprobanteVentaEmailBuilder().
|
||||
ConFactura(factura).
|
||||
ConNombresRepuestos(nombresRepuestos).
|
||||
ConPagos(pagos).
|
||||
ConDestinatario(destinatario).
|
||||
Build()
|
||||
}
|
||||
|
||||
// Invitacion arma el email que se envía a un usuario invitado a una empresa.
|
||||
func (d *EmailDirector) Invitacion(empresa, rol, link, destinatario string) (*dto_email.MensajeEmail, error) {
|
||||
return builders.NewInvitacionEmailBuilder().
|
||||
ConEmpresa(empresa).
|
||||
ConRol(rol).
|
||||
ConLink(link).
|
||||
ConDestinatario(destinatario).
|
||||
Build()
|
||||
}
|
||||
|
||||
// StockBajo arma el aviso de alerta cuando un ajuste deja el stock por debajo
|
||||
// del mínimo configurado para el repuesto.
|
||||
func (d *EmailDirector) StockBajo(
|
||||
stock *models.Stock,
|
||||
repuesto *models.Repuesto,
|
||||
saldoAnterior float64,
|
||||
destinatarios []string,
|
||||
usuarioID uint,
|
||||
) (*dto_email.MensajeEmail, error) {
|
||||
return builders.NewStockBajoEmailBuilder().
|
||||
ConStock(stock).
|
||||
ConRepuesto(repuesto).
|
||||
ConSaldoAnterior(saldoAnterior).
|
||||
ConDestinatarios(destinatarios).
|
||||
ConUsuarioID(usuarioID).
|
||||
Build()
|
||||
}
|
||||
|
||||
// DiferenciasRemito arma el aviso de las diferencias detectadas al ingresar un
|
||||
// remito. Los nombres de repuestos se resuelven desde el mapa recibido.
|
||||
func (d *EmailDirector) DiferenciasRemito(
|
||||
remito *models.Remito,
|
||||
proveedor string,
|
||||
diferencias []models.DiferenciaRemito,
|
||||
repuestos map[uint64]*models.Repuesto,
|
||||
destinatarios []string,
|
||||
usuarioID uint,
|
||||
) (*dto_email.MensajeEmail, error) {
|
||||
return builders.NewDiferenciasRemitoEmailBuilder().
|
||||
ConRemito(remito).
|
||||
ConProveedor(proveedor).
|
||||
ConDiferencias(diferencias).
|
||||
ConRepuestos(repuestos).
|
||||
ConDestinatarios(destinatarios).
|
||||
ConUsuarioID(usuarioID).
|
||||
Build()
|
||||
}
|
||||
@@ -12,6 +12,10 @@ func NewFacturaDirector() *FacturaDirector {
|
||||
return &FacturaDirector{}
|
||||
}
|
||||
|
||||
func (d *FacturaDirector) Crear(datos dto_facturas.FacturaCalculada) (*models.Factura, error) {
|
||||
return builders.NewCrearFacturaBuilder().ConDatos(datos).Build()
|
||||
}
|
||||
|
||||
func (d *FacturaDirector) DesdeFactura(factura *models.Factura) (*dto_facturas.FacturaResponse, error) {
|
||||
return builders.NewFacturaResponseBuilder().ConFactura(factura).Build()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package directors
|
||||
|
||||
import (
|
||||
builders "repuestera_back/dto/Builders"
|
||||
dto "repuestera_back/dto/Stock"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
type ReporteStockDirector struct{}
|
||||
|
||||
func NewReporteStockDirector() *ReporteStockDirector {
|
||||
return &ReporteStockDirector{}
|
||||
}
|
||||
|
||||
func (d *ReporteStockDirector) Generar(movimientos []models.MovimientoStock, resumen []dto.ResumenMovimientoResponse, tipos []models.TipoMovimientoStock) (*dto.ReporteStockResponse, error) {
|
||||
return builders.NewReporteStockResponseBuilder().
|
||||
ConMovimientos(movimientos).
|
||||
ConResumen(resumen).
|
||||
ConTipos(tipos).
|
||||
Build()
|
||||
}
|
||||
@@ -48,12 +48,13 @@ func (b *EmpresaActualResponseBuilder) Build() (*dto.EmpresaActualResponse, erro
|
||||
}
|
||||
|
||||
return &dto.EmpresaActualResponse{
|
||||
ID: b.empresa.ID,
|
||||
Nombre: b.empresa.Nombre,
|
||||
Slug: b.empresa.Slug,
|
||||
Cuit: b.empresa.Cuit,
|
||||
Activa: b.empresa.Activa,
|
||||
Rol: string(b.rol),
|
||||
MiembrosActivos: b.miembros,
|
||||
ID: b.empresa.ID,
|
||||
Nombre: b.empresa.Nombre,
|
||||
Slug: b.empresa.Slug,
|
||||
Cuit: b.empresa.Cuit,
|
||||
EmailAlertaStock: ListaNoNil([]string(b.empresa.EmailAlertaStock)),
|
||||
Activa: b.empresa.Activa,
|
||||
Rol: string(b.rol),
|
||||
MiembrosActivos: b.miembros,
|
||||
}, nil
|
||||
}
|
||||
@@ -48,13 +48,14 @@ func (b *EmpresaAdminResponseBuilder) Build() (*dto.EmpresaAdminResponse, error)
|
||||
}
|
||||
|
||||
return &dto.EmpresaAdminResponse{
|
||||
ID: b.empresa.ID,
|
||||
Nombre: b.empresa.Nombre,
|
||||
Slug: b.empresa.Slug,
|
||||
Cuit: b.empresa.Cuit,
|
||||
Activa: b.empresa.Activa,
|
||||
Miembros: b.miembros,
|
||||
Owners: b.owners,
|
||||
CreatedAt: b.empresa.CreatedAt,
|
||||
ID: b.empresa.ID,
|
||||
Nombre: b.empresa.Nombre,
|
||||
Slug: b.empresa.Slug,
|
||||
Cuit: b.empresa.Cuit,
|
||||
EmailAlertaStock: ListaNoNil([]string(b.empresa.EmailAlertaStock)),
|
||||
Activa: b.empresa.Activa,
|
||||
Miembros: b.miembros,
|
||||
Owners: b.owners,
|
||||
CreatedAt: b.empresa.CreatedAt,
|
||||
}, nil
|
||||
}
|
||||
@@ -36,12 +36,13 @@ func (b *EmpresaResponseBuilder) Build() (*dto.EmpresaResponse, error) {
|
||||
}
|
||||
|
||||
return &dto.EmpresaResponse{
|
||||
ID: b.empresa.ID,
|
||||
Nombre: b.empresa.Nombre,
|
||||
Slug: b.empresa.Slug,
|
||||
Cuit: b.empresa.Cuit,
|
||||
Activa: b.empresa.Activa,
|
||||
CreatedAt: b.empresa.CreatedAt,
|
||||
UpdatedAt: b.empresa.UpdatedAt,
|
||||
ID: b.empresa.ID,
|
||||
Nombre: b.empresa.Nombre,
|
||||
Slug: b.empresa.Slug,
|
||||
Cuit: b.empresa.Cuit,
|
||||
EmailAlertaStock: ListaNoNil([]string(b.empresa.EmailAlertaStock)),
|
||||
Activa: b.empresa.Activa,
|
||||
CreatedAt: b.empresa.CreatedAt,
|
||||
UpdatedAt: b.empresa.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
htmlutil "html"
|
||||
|
||||
dto_email "repuestera_back/dto/Email"
|
||||
)
|
||||
|
||||
// InvitacionEmailBuilder arma el email de invitación a una empresa. Acá viven
|
||||
// el texto y las validaciones propias de este caso de uso.
|
||||
type InvitacionEmailBuilder struct {
|
||||
empresa string
|
||||
rol string
|
||||
link string
|
||||
destinatario string
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[dto_email.MensajeEmail] = (*InvitacionEmailBuilder)(nil)
|
||||
|
||||
func NewInvitacionEmailBuilder() *InvitacionEmailBuilder {
|
||||
return &InvitacionEmailBuilder{}
|
||||
}
|
||||
|
||||
func (b *InvitacionEmailBuilder) ConEmpresa(empresa string) *InvitacionEmailBuilder {
|
||||
b.empresa, _ = ValidarTexto(empresa, "empresa", &b.err)
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *InvitacionEmailBuilder) ConRol(rol string) *InvitacionEmailBuilder {
|
||||
b.rol, _ = ValidarTexto(rol, "rol", &b.err)
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *InvitacionEmailBuilder) ConLink(link string) *InvitacionEmailBuilder {
|
||||
b.link, _ = ValidarTexto(link, "link de invitación", &b.err)
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *InvitacionEmailBuilder) ConDestinatario(destinatario string) *InvitacionEmailBuilder {
|
||||
b.destinatario = destinatario
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *InvitacionEmailBuilder) Build() (*dto_email.MensajeEmail, error) {
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
|
||||
empresa := htmlutil.EscapeString(b.empresa)
|
||||
rol := htmlutil.EscapeString(b.rol)
|
||||
link := htmlutil.EscapeString(b.link)
|
||||
descripcion := fmt.Sprintf(
|
||||
"<p>Fuiste invitado a <strong>%s</strong> con el rol <strong>%s</strong>.</p>"+
|
||||
"<p><a href=\"%s\">Aceptar invitación</a></p>"+
|
||||
"<p>Si el enlace no funciona, copiá esta dirección: %s</p>",
|
||||
empresa, rol, link, link,
|
||||
)
|
||||
|
||||
return NewMensajeEmailBuilder().
|
||||
ConTitulo("Invitación a " + b.empresa).
|
||||
ConDescripcion(descripcion).
|
||||
ConItems([]string{}).
|
||||
ConDestinatarios([]string{b.destinatario}).
|
||||
Build()
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
dto_email "repuestera_back/dto/Email"
|
||||
)
|
||||
|
||||
type MensajeEmailBuilder struct {
|
||||
mensaje dto_email.MensajeEmail
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[dto_email.MensajeEmail] = (*MensajeEmailBuilder)(nil)
|
||||
|
||||
func NewMensajeEmailBuilder() *MensajeEmailBuilder {
|
||||
return &MensajeEmailBuilder{}
|
||||
}
|
||||
|
||||
func (b *MensajeEmailBuilder) ConTitulo(titulo string) *MensajeEmailBuilder {
|
||||
titulo = strings.TrimSpace(titulo)
|
||||
if titulo == "" {
|
||||
AcumularError(&b.err, "el título del email no puede ser nulo o vacío")
|
||||
return b
|
||||
}
|
||||
b.mensaje.Titulo = titulo
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MensajeEmailBuilder) ConDescripcion(descripcion string) *MensajeEmailBuilder {
|
||||
descripcion = strings.TrimSpace(descripcion)
|
||||
if descripcion == "" {
|
||||
AcumularError(&b.err, "la descripción del email no puede ser nula o vacía")
|
||||
return b
|
||||
}
|
||||
b.mensaje.Descripcion = descripcion
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MensajeEmailBuilder) ConItems(items []string) *MensajeEmailBuilder {
|
||||
b.mensaje.Items = items
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MensajeEmailBuilder) ConDestinatarios(destinatarios []string) *MensajeEmailBuilder {
|
||||
b.mensaje.Destinatarios = normalizarDestinatarios(destinatarios)
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MensajeEmailBuilder) Build() (*dto_email.MensajeEmail, error) {
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
if strings.TrimSpace(b.mensaje.Titulo) == "" {
|
||||
return nil, errors.New("falta el título del email")
|
||||
}
|
||||
if strings.TrimSpace(b.mensaje.Descripcion) == "" {
|
||||
return nil, errors.New("falta la descripción del email")
|
||||
}
|
||||
|
||||
b.mensaje.Items = ListaNoNil(b.mensaje.Items)
|
||||
b.mensaje.Destinatarios = ListaNoNil(b.mensaje.Destinatarios)
|
||||
return &b.mensaje, nil
|
||||
}
|
||||
|
||||
func normalizarDestinatarios(destinatarios []string) []string {
|
||||
vistos := make(map[string]bool, len(destinatarios))
|
||||
limpios := make([]string, 0, len(destinatarios))
|
||||
for _, destinatario := range destinatarios {
|
||||
destinatario = strings.TrimSpace(destinatario)
|
||||
if destinatario == "" || vistos[destinatario] {
|
||||
continue
|
||||
}
|
||||
vistos[destinatario] = true
|
||||
limpios = append(limpios, destinatario)
|
||||
}
|
||||
return limpios
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
dto "repuestera_back/dto/Stock"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
type ReporteStockResponseBuilder struct {
|
||||
movimientos []models.MovimientoStock
|
||||
resumen []dto.ResumenMovimientoResponse
|
||||
tipos []models.TipoMovimientoStock
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[dto.ReporteStockResponse] = (*ReporteStockResponseBuilder)(nil)
|
||||
|
||||
func NewReporteStockResponseBuilder() *ReporteStockResponseBuilder {
|
||||
return &ReporteStockResponseBuilder{}
|
||||
}
|
||||
|
||||
func (b *ReporteStockResponseBuilder) ConMovimientos(movimientos []models.MovimientoStock) *ReporteStockResponseBuilder {
|
||||
b.movimientos = movimientos
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *ReporteStockResponseBuilder) ConResumen(resumen []dto.ResumenMovimientoResponse) *ReporteStockResponseBuilder {
|
||||
b.resumen = resumen
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *ReporteStockResponseBuilder) ConTipos(tipos []models.TipoMovimientoStock) *ReporteStockResponseBuilder {
|
||||
b.tipos = tipos
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *ReporteStockResponseBuilder) Build() (*dto.ReporteStockResponse, error) {
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
if b.movimientos == nil {
|
||||
b.movimientos = []models.MovimientoStock{}
|
||||
}
|
||||
if b.resumen == nil {
|
||||
b.resumen = []dto.ResumenMovimientoResponse{}
|
||||
}
|
||||
if b.tipos == nil {
|
||||
b.tipos = []models.TipoMovimientoStock{}
|
||||
}
|
||||
|
||||
resumen := make([]dto.ResumenMovimientoResponse, len(b.resumen))
|
||||
copy(resumen, b.resumen)
|
||||
|
||||
tipos := make([]models.TipoMovimientoStock, len(b.tipos))
|
||||
copy(tipos, b.tipos)
|
||||
|
||||
movimientos := make([]models.MovimientoStock, len(b.movimientos))
|
||||
copy(movimientos, b.movimientos)
|
||||
|
||||
return &dto.ReporteStockResponse{
|
||||
Movimientos: movimientos,
|
||||
Resumen: resumen,
|
||||
Tipos: tipos,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
package dto_builders
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
htmlutil "html"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
dto_email "repuestera_back/dto/Email"
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// StockBajoEmailBuilder arma el aviso de stock por debajo del mínimo. Acá viven
|
||||
// los detalles de presentación (tabla, estilos inline y formato de cantidades);
|
||||
// el director sólo decide qué builder usar.
|
||||
type StockBajoEmailBuilder struct {
|
||||
stock *models.Stock
|
||||
repuesto *models.Repuesto
|
||||
saldoAnterior float64
|
||||
destinatarios []string
|
||||
usuarioID uint
|
||||
err error
|
||||
}
|
||||
|
||||
var _ IBuilder[dto_email.MensajeEmail] = (*StockBajoEmailBuilder)(nil)
|
||||
|
||||
func NewStockBajoEmailBuilder() *StockBajoEmailBuilder {
|
||||
return &StockBajoEmailBuilder{}
|
||||
}
|
||||
|
||||
func (b *StockBajoEmailBuilder) ConStock(stock *models.Stock) *StockBajoEmailBuilder {
|
||||
if stock == nil {
|
||||
AcumularError(&b.err, "el stock no puede ser nulo")
|
||||
}
|
||||
b.stock = stock
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *StockBajoEmailBuilder) ConRepuesto(repuesto *models.Repuesto) *StockBajoEmailBuilder {
|
||||
if repuesto == nil {
|
||||
AcumularError(&b.err, "el repuesto no puede ser nulo")
|
||||
}
|
||||
b.repuesto = repuesto
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *StockBajoEmailBuilder) ConSaldoAnterior(saldoAnterior float64) *StockBajoEmailBuilder {
|
||||
b.saldoAnterior = saldoAnterior
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *StockBajoEmailBuilder) ConDestinatarios(destinatarios []string) *StockBajoEmailBuilder {
|
||||
b.destinatarios = destinatarios
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *StockBajoEmailBuilder) ConUsuarioID(usuarioID uint) *StockBajoEmailBuilder {
|
||||
b.usuarioID = usuarioID
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *StockBajoEmailBuilder) Build() (*dto_email.MensajeEmail, error) {
|
||||
if b.stock == nil && b.err == nil {
|
||||
AcumularError(&b.err, "falta el stock")
|
||||
}
|
||||
if b.repuesto == nil && b.err == nil {
|
||||
AcumularError(&b.err, "falta el repuesto")
|
||||
}
|
||||
if b.err != nil {
|
||||
return nil, b.err
|
||||
}
|
||||
|
||||
return NewMensajeEmailBuilder().
|
||||
ConTitulo("Stock bajo mínimo: " + b.repuesto.Nombre).
|
||||
ConDescripcion(htmlStockBajo(b.stock, b.repuesto, b.saldoAnterior, b.usuarioID)).
|
||||
ConItems([]string{}).
|
||||
ConDestinatarios(b.destinatarios).
|
||||
Build()
|
||||
}
|
||||
|
||||
const (
|
||||
stockBajoColorPrimary = "#f1c21b"
|
||||
stockBajoColorOnPrim = "#161616"
|
||||
stockBajoColorAccent = "#8e6a00"
|
||||
stockBajoColorText = "#161616"
|
||||
stockBajoColorMuted = "#525252"
|
||||
stockBajoColorBorder = "#e0e0e0"
|
||||
stockBajoColorSoft = "#fcf4d6"
|
||||
)
|
||||
|
||||
// htmlStockBajo genera el cuerpo HTML del aviso. Usa tablas y estilos inline
|
||||
// porque los clientes de correo suelen ignorar las hojas de estilo.
|
||||
func htmlStockBajo(stock *models.Stock, repuesto *models.Repuesto, saldoAnterior float64, usuarioID uint) string {
|
||||
var b strings.Builder
|
||||
|
||||
almacen := fmt.Sprintf("%d", stock.AlmacenID)
|
||||
if stock.Almacen.Codigo != "" {
|
||||
almacen = stock.Almacen.Codigo
|
||||
}
|
||||
minimo := float64(repuesto.StockMinimo)
|
||||
faltante := minimo - stock.Cantidad
|
||||
|
||||
b.WriteString(`<div style="max-width:640px;margin:0 auto;font-family:Arial,Helvetica,sans-serif;color:` + stockBajoColorText + `;">`)
|
||||
b.WriteString(`<div style="background:` + stockBajoColorPrimary + `;color:` + stockBajoColorOnPrim + `;padding:24px 28px;border-radius:8px 8px 0 0;">`)
|
||||
b.WriteString(`<p style="margin:0;font-size:11px;letter-spacing:2px;text-transform:uppercase;opacity:.85;">Repuestera</p>`)
|
||||
b.WriteString(`<h1 style="margin:8px 0 4px;font-size:24px;">Stock bajo mínimo</h1>`)
|
||||
fmt.Fprintf(&b, `<p style="margin:0;font-size:14px;"><strong>%s</strong> en el almacén <strong>%s</strong></p>`,
|
||||
htmlutil.EscapeString(repuesto.Nombre), htmlutil.EscapeString(almacen))
|
||||
b.WriteString(`</div>`)
|
||||
|
||||
b.WriteString(`<div style="border:1px solid ` + stockBajoColorBorder + `;border-top:0;padding:24px 28px;border-radius:0 0 8px 8px;background:#ffffff;">`)
|
||||
fmt.Fprintf(&b, `<p style="margin:0 0 20px;font-size:14px;line-height:1.5;"><strong>%s</strong> quedó por debajo del mínimo configurado. Conviene reponerlo.</p>`,
|
||||
htmlutil.EscapeString(repuesto.Nombre))
|
||||
|
||||
b.WriteString(`<h2 style="margin:0 0 10px;font-size:14px;letter-spacing:1px;text-transform:uppercase;color:` + stockBajoColorMuted + `;">Detalle del stock</h2>`)
|
||||
b.WriteString(`<table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;font-size:13px;">`)
|
||||
b.WriteString(`<thead><tr style="background:` + stockBajoColorSoft + `;color:` + stockBajoColorMuted + `;text-align:left;">`)
|
||||
b.WriteString(`<th style="padding:10px 8px;">Concepto</th>`)
|
||||
b.WriteString(`<th align="right" style="padding:10px 8px;">Valor</th>`)
|
||||
b.WriteString(`</tr></thead><tbody>`)
|
||||
|
||||
filas := []struct {
|
||||
etiqueta string
|
||||
valor string
|
||||
destaca bool
|
||||
}{
|
||||
{"Repuesto", htmlutil.EscapeString(repuesto.Nombre), false},
|
||||
{"Almacén", htmlutil.EscapeString(almacen), false},
|
||||
{"Stock anterior", formatCantidad(saldoAnterior), false},
|
||||
{"Stock actual", formatCantidad(stock.Cantidad), true},
|
||||
{"Stock mínimo", formatCantidad(minimo), false},
|
||||
}
|
||||
for _, fila := range filas {
|
||||
peso := "400"
|
||||
if fila.destaca {
|
||||
peso = "600"
|
||||
}
|
||||
fmt.Fprintf(&b,
|
||||
`<tr style="border-bottom:1px solid %s;"><td style="padding:10px 8px;color:%s;">%s</td><td align="right" style="padding:10px 8px;font-weight:%s;">%s</td></tr>`,
|
||||
stockBajoColorBorder, stockBajoColorMuted, fila.etiqueta, peso, fila.valor,
|
||||
)
|
||||
}
|
||||
b.WriteString(`</tbody></table>`)
|
||||
|
||||
b.WriteString(`<table width="100%" cellpadding="0" cellspacing="0" style="margin-top:18px;font-size:13px;">`)
|
||||
fmt.Fprintf(&b,
|
||||
`<tr><td style="padding:12px 8px 4px;border-top:2px solid %s;font-size:18px;font-weight:700;">Faltante para el mínimo</td><td align="right" style="padding:12px 8px 4px;border-top:2px solid %s;font-size:18px;font-weight:700;color:%s;">%s</td></tr>`,
|
||||
stockBajoColorPrimary, stockBajoColorPrimary, stockBajoColorAccent, formatCantidad(faltante),
|
||||
)
|
||||
b.WriteString(`</table>`)
|
||||
|
||||
fmt.Fprintf(&b, `<p style="margin:24px 0 0;padding-top:16px;border-top:1px solid %s;font-size:12px;color:%s;">Usuario responsable: %d</p>`,
|
||||
stockBajoColorBorder, stockBajoColorMuted, usuarioID)
|
||||
b.WriteString(`</div></div>`)
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// formatCantidad formatea cantidades sin ceros sobrantes. Las unidades
|
||||
// enteras se muestran sin decimales; las que llevan parte decimal conservan
|
||||
// solo los dígitos necesarios.
|
||||
func formatCantidad(valor float64) string {
|
||||
if math.IsNaN(valor) || math.IsInf(valor, 0) {
|
||||
return fmt.Sprintf("%v", valor)
|
||||
}
|
||||
|
||||
redondeado := math.Round(valor*1000) / 1000
|
||||
if redondeado == math.Trunc(redondeado) {
|
||||
return strconv.FormatInt(int64(redondeado), 10)
|
||||
}
|
||||
return strconv.FormatFloat(redondeado, 'f', -1, 64)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package dto
|
||||
|
||||
// DescuentoDto es el cuerpo aceptado para crear o actualizar un descuento.
|
||||
// Activo es opcional: al crear, si no se envía, el descuento queda activo.
|
||||
type DescuentoDto struct {
|
||||
Nombre string `json:"nombre"`
|
||||
Descripcion string `json:"descripcion"`
|
||||
Tipo string `json:"tipo"`
|
||||
Valor float64 `json:"valor"`
|
||||
Activo *bool `json:"activo"`
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package dto_email
|
||||
|
||||
// MensajeEmail es el contrato que espera el servicio comms en POST /email.
|
||||
type MensajeEmail struct {
|
||||
Titulo string
|
||||
Descripcion string
|
||||
Items []string
|
||||
Destinatarios []string
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package dto
|
||||
|
||||
// ComprobanteResponse es la representación pública de una factura para
|
||||
// visualizar el comprobante. Incluye todos los datos de FacturaResponse
|
||||
// más la lista de pagos realizados.
|
||||
type ComprobanteResponse struct {
|
||||
*FacturaResponse
|
||||
Pagos []PagoResumen `json:"pagos"`
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package dto
|
||||
|
||||
type CrearFacturaDto struct {
|
||||
ClienteID uint `json:"clienteId" binding:"required"`
|
||||
AlmacenID uint `json:"almacenId" binding:"required"`
|
||||
Items []ItemFacturaDto `json:"items" binding:"required,min=1"`
|
||||
DescuentoID uint `json:"descuentoId"`
|
||||
Pagos []PagoFacturaDto `json:"pagos"`
|
||||
EnviarEmail bool `json:"enviarEmail"`
|
||||
Observacion string `json:"observacion"`
|
||||
ReservaID uint `json:"reservaId"`
|
||||
}
|
||||
|
||||
type ItemFacturaDto struct {
|
||||
RepuestoID uint64 `json:"repuestoId" binding:"required"`
|
||||
Cantidad float64 `json:"cantidad" binding:"required,gt=0"`
|
||||
PrecioUnitario float64 `json:"precioUnitario" binding:"gte=0"`
|
||||
}
|
||||
|
||||
type PagoFacturaDto struct {
|
||||
FormaDePagoID uint `json:"formaDePagoId" binding:"required"`
|
||||
Importe float64 `json:"importe" binding:"required,gt=0"`
|
||||
Fecha string `json:"fecha"`
|
||||
Observacion string `json:"observacion"`
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package dto
|
||||
|
||||
import "repuestera_back/models"
|
||||
|
||||
// CrearFacturaResponse es la respuesta de la emisión de una factura.
|
||||
type CrearFacturaResponse struct {
|
||||
Factura *FacturaResponse `json:"factura"`
|
||||
Stocks []*models.Stock `json:"stocks"`
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// FacturaCalculada reúne los datos ya validados y calculados que necesita el
|
||||
// builder para construir el modelo de factura.
|
||||
type FacturaCalculada struct {
|
||||
EmpresaID uint
|
||||
Numero string
|
||||
ClienteID uint
|
||||
AlmacenID uint
|
||||
FechaEmision time.Time
|
||||
Subtotal float64
|
||||
DescuentoID uint
|
||||
DescuentoTotal float64
|
||||
Impuestos float64
|
||||
AlicuotaIVA float64
|
||||
Total float64
|
||||
Saldo float64
|
||||
Detalles []models.FacturaDetalle
|
||||
Observacion string
|
||||
ResponsableID uint
|
||||
}
|
||||
@@ -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"`
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
// PagoResumen es la representación ligera de un pago de factura,
|
||||
// usada para mostrar el historial de pagos en el comprobante.
|
||||
type PagoResumen struct {
|
||||
ID uint `json:"id"`
|
||||
FacturaID uint `json:"facturaId,omitempty"`
|
||||
FormaDePagoID uint `json:"formaDePagoId,omitempty"`
|
||||
FormaDePago string `json:"formaDePago,omitempty"`
|
||||
Importe float64 `json:"importe"`
|
||||
Fecha time.Time `json:"fecha"`
|
||||
Observacion string `json:"observacion,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package dto
|
||||
|
||||
// RegistrarPagoDto representa el cobro de una factura existente.
|
||||
type RegistrarPagoDto struct {
|
||||
FormaDePagoID uint `json:"formaDePagoId" binding:"required"`
|
||||
Importe float64 `json:"importe" binding:"required,gt=0"`
|
||||
Fecha string `json:"fecha"`
|
||||
Observacion string `json:"observacion" binding:"max=255"`
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package dto
|
||||
|
||||
// RegistrarPagoResponse devuelve el pago creado y el estado final de la
|
||||
// factura para que el frontend refresque saldo y estado sin otra consulta.
|
||||
type RegistrarPagoResponse struct {
|
||||
Pago PagoResumen `json:"pago"`
|
||||
Factura FacturaResponse `json:"factura"`
|
||||
SaldoAnterior float64 `json:"saldoAnterior"`
|
||||
SaldoNuevo float64 `json:"saldoNuevo"`
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package dto
|
||||
|
||||
// StockDisponible resume, por repuesto y almacén, cuántas unidades se pueden
|
||||
// vender (cantidad menos las reservadas). Es la información que muestra el
|
||||
// alta de factura para avisar cuánto stock hay antes de vender.
|
||||
type StockDisponibleResponse struct {
|
||||
RepuestoID uint64 `json:"repuestoId"`
|
||||
AlmacenID uint `json:"almacenId"`
|
||||
Cantidad float64 `json:"cantidad"`
|
||||
CantidadReservada float64 `json:"cantidadReservada"`
|
||||
Disponible float64 `json:"disponible"`
|
||||
}
|
||||
@@ -2,12 +2,12 @@ package dto
|
||||
|
||||
// FiltrosReservaQuery acota el listado de reservas de stock.
|
||||
type FiltrosReservaQuery struct {
|
||||
RepuestoID uint `form:"repuestoId"`
|
||||
AlmacenID uint `form:"almacenId"`
|
||||
ClienteID uint `form:"clienteId"`
|
||||
Texto string `form:"q"`
|
||||
Cliente string `form:"cliente"`
|
||||
Estado string `form:"estado"`
|
||||
Pagina int `form:"pagina"`
|
||||
PorPagina int `form:"porPagina"`
|
||||
RepuestoID uint `form:"repuestoId"`
|
||||
AlmacenID uint `form:"almacenId"`
|
||||
ClienteID uint `form:"clienteId"`
|
||||
Texto string `form:"q"`
|
||||
ClienteNombre string `form:"cliente"`
|
||||
Estado string `form:"estado"`
|
||||
Pagina int `form:"pagina"`
|
||||
PorPagina int `form:"porPagina"`
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package dto
|
||||
|
||||
// FiltrosReporteQuery acota la generación del reporte de stock.
|
||||
type FiltrosReporteQuery struct {
|
||||
StockID uint64 `form:"stockId"`
|
||||
RepuestoID uint64 `form:"repuestoId"`
|
||||
AlmacenID uint `form:"almacenId"`
|
||||
Tipo string `form:"tipo"`
|
||||
Desde string `form:"desde"`
|
||||
Hasta string `form:"hasta"`
|
||||
FechaDesde string `form:"fechaDesde"`
|
||||
FechaHasta string `form:"fechaHasta"`
|
||||
DesdeAlt string `form:"from"`
|
||||
HastaAlt string `form:"to"`
|
||||
Pagina int `form:"pagina"`
|
||||
PorPagina int `form:"porPagina"`
|
||||
}
|
||||
|
||||
// Alias habituales para el DTO del reporte.
|
||||
type ReporteStockQuery = FiltrosReporteQuery
|
||||
type ReporteQuery = FiltrosReporteQuery
|
||||
type FiltrosReporte = FiltrosReporteQuery
|
||||
@@ -0,0 +1,16 @@
|
||||
package dto
|
||||
|
||||
import "repuestera_back/models"
|
||||
|
||||
// ResumenMovimientoResponse agrupa cantidades por tipo para el reporte.
|
||||
type ResumenMovimientoResponse struct {
|
||||
Tipo models.TipoMovimientoStock `json:"tipo"`
|
||||
Cantidad float64 `json:"cantidad"`
|
||||
}
|
||||
|
||||
// ReporteStockResponse es la respuesta del caso de uso Generar Reporte.
|
||||
type ReporteStockResponse struct {
|
||||
Movimientos []models.MovimientoStock `json:"movimientos"`
|
||||
Resumen []ResumenMovimientoResponse `json:"resumen"`
|
||||
Tipos []models.TipoMovimientoStock `json:"tipos"`
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"repuestera_back/models"
|
||||
)
|
||||
|
||||
// ResumenMovimiento agrupa cantidades por tipo para reportes.
|
||||
type ResumenMovimiento struct {
|
||||
Tipo models.TipoMovimientoStock
|
||||
Cantidad float64
|
||||
}
|
||||
@@ -4,24 +4,26 @@ import "time"
|
||||
|
||||
// EmpresaResponse es la representación pública de una empresa.
|
||||
type EmpresaResponse struct {
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit,omitempty"`
|
||||
Activa bool `json:"activa"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit,omitempty"`
|
||||
EmailAlertaStock []string `json:"email_alerta_stock,omitempty"`
|
||||
Activa bool `json:"activa"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// EmpresaActualResponse describe la empresa activa de la sesión.
|
||||
type EmpresaActualResponse struct {
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit,omitempty"`
|
||||
Activa bool `json:"activa"`
|
||||
Rol string `json:"rol"`
|
||||
MiembrosActivos int64 `json:"miembros_activos"`
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit,omitempty"`
|
||||
EmailAlertaStock []string `json:"email_alerta_stock,omitempty"`
|
||||
Activa bool `json:"activa"`
|
||||
Rol string `json:"rol"`
|
||||
MiembrosActivos int64 `json:"miembros_activos"`
|
||||
}
|
||||
|
||||
// EmpresasResponse es el envelope de empresas del usuario.
|
||||
@@ -81,14 +83,15 @@ type InvitacionCreadaResponse struct {
|
||||
|
||||
// EmpresaAdminResponse es la vista de empresa para plataforma.
|
||||
type EmpresaAdminResponse struct {
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit,omitempty"`
|
||||
Activa bool `json:"activa"`
|
||||
Miembros int64 `json:"miembros"`
|
||||
Owners int64 `json:"owners"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID uint `json:"id"`
|
||||
Nombre string `json:"nombre"`
|
||||
Slug string `json:"slug"`
|
||||
Cuit *string `json:"cuit,omitempty"`
|
||||
EmailAlertaStock []string `json:"email_alerta_stock,omitempty"`
|
||||
Activa bool `json:"activa"`
|
||||
Miembros int64 `json:"miembros"`
|
||||
Owners int64 `json:"owners"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// EmpresasAdminListadoResponse es el envelope de empresas de plataforma.
|
||||
|
||||
+10
-4
@@ -6,7 +6,7 @@ require (
|
||||
github.com/gin-gonic/gin v1.10.0
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1
|
||||
github.com/joho/godotenv v1.5.1
|
||||
golang.org/x/crypto v0.31.0
|
||||
golang.org/x/crypto v0.58.0
|
||||
gorm.io/datatypes v1.2.7
|
||||
gorm.io/driver/mysql v1.5.7
|
||||
gorm.io/gorm v1.30.0
|
||||
@@ -38,12 +38,18 @@ require (
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||
github.com/richardlehane/mscfb v1.0.9 // indirect
|
||||
github.com/richardlehane/msoleps v1.0.6 // indirect
|
||||
github.com/tiendc/go-deepcopy v1.7.2 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
github.com/xuri/efp v0.0.3-0.20260924042702-217b81952dec // indirect
|
||||
github.com/xuri/excelize/v2 v2.11.1 // indirect
|
||||
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect
|
||||
golang.org/x/arch v0.8.0 // indirect
|
||||
golang.org/x/net v0.25.0 // indirect
|
||||
golang.org/x/sys v0.28.0 // indirect
|
||||
golang.org/x/text v0.21.0 // indirect
|
||||
golang.org/x/net v0.62.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
google.golang.org/protobuf v1.34.1 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
|
||||
+21
@@ -70,6 +70,10 @@ github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6
|
||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/richardlehane/mscfb v1.0.9 h1:8xdd9auUvXbFoCw3L9h1spnQHZgjNsSX+ek46J6A9tE=
|
||||
github.com/richardlehane/mscfb v1.0.9/go.mod h1:pe0+IUIc0AHh0+teNzBlJCtSyZdFOGgV4ZK9bsoV+Jo=
|
||||
github.com/richardlehane/msoleps v1.0.6 h1:9BvkpjvD+iUBalUY4esMwv6uBkfOip/Lzvd93jvR9gg=
|
||||
github.com/richardlehane/msoleps v1.0.6/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
@@ -82,23 +86,40 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/tiendc/go-deepcopy v1.7.2 h1:Ut2yYR7W9tWjTQitganoIue4UGxZwCcJy3orjrrIj44=
|
||||
github.com/tiendc/go-deepcopy v1.7.2/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
github.com/xuri/efp v0.0.3-0.20260924042702-217b81952dec h1:sZZokRLgr8nyrzkDDCQcvEYBsTrZr6eqXa/R9qALoQA=
|
||||
github.com/xuri/efp v0.0.3-0.20260924042702-217b81952dec/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
|
||||
github.com/xuri/excelize/v2 v2.11.1 h1:tm/FVufArvfUiJXJtGv8jna/zZS1t9Uji2ImsnS9iBo=
|
||||
github.com/xuri/excelize/v2 v2.11.1/go.mod h1:NQLBThVu4BB7tYM8wJIBj2dZsptXbDW4WyrFlL8YLZQ=
|
||||
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE=
|
||||
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
||||
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
|
||||
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
||||
@@ -97,8 +97,8 @@ func AdminEmpresaMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
rol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
||||
if rol.EsAdministrador() ||
|
||||
utils.UsuarioTienePermiso(c, models_seguridad.PermisoGestionUsuarios) ||
|
||||
utils.UsuarioTienePermiso(c, models_seguridad.PermisoGestionEmpresa) {
|
||||
utils.UsuarioTienePermiso(c, 3) ||
|
||||
utils.UsuarioTienePermiso(c, 7) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
+14
-5
@@ -1,11 +1,20 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Almacen struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
EmpresaID uint `gorm:"not null;default:1;index;uniqueIndex:uq_almacen_empresa_codigo,priority:1" json:"empresaId"`
|
||||
Codigo string `gorm:"type:varchar(5);not null;uniqueIndex:uq_almacen_empresa_codigo,priority:2" json:"codigo"`
|
||||
Ubicacion string `gorm:"type:varchar(40)" json:"ubicacion"`
|
||||
Stocks []Stock `gorm:"foreignKey:AlmacenID" json:"stocks,omitempty"`
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
CreatedAt time.Time `json:"CreatedAt"`
|
||||
UpdatedAt time.Time `json:"UpdatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"DeletedAt"`
|
||||
EmpresaID uint `gorm:"not null;default:1;index;uniqueIndex:uq_almacen_empresa_codigo,priority:1" json:"empresaId"`
|
||||
Codigo string `gorm:"type:varchar(5);not null;uniqueIndex:uq_almacen_empresa_codigo,priority:2" json:"codigo"`
|
||||
Ubicacion string `gorm:"type:varchar(40)" json:"ubicacion"`
|
||||
Stocks []Stock `gorm:"foreignKey:AlmacenID" json:"stocks,omitempty"`
|
||||
}
|
||||
|
||||
func (Almacen) TableName() string {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package models
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
// ComprobanteSecuencia lleva el último número emitido por empresa y tipo.
|
||||
type ComprobanteSecuencia struct {
|
||||
gorm.Model
|
||||
EmpresaID uint `gorm:"not null;index;uniqueIndex:uq_seq_empresa_tipo,priority:1" json:"empresaId"`
|
||||
Tipo string `gorm:"type:varchar(20);not null;uniqueIndex:uq_seq_empresa_tipo,priority:2" json:"tipo"`
|
||||
UltimoNumero uint `gorm:"not null;default:0" json:"ultimoNumero"`
|
||||
}
|
||||
|
||||
func (ComprobanteSecuencia) TableName() string {
|
||||
return "comprobante_secuencia"
|
||||
}
|
||||
@@ -6,13 +6,19 @@ type Descuento struct {
|
||||
gorm.Model
|
||||
EmpresaID uint `gorm:"not null;default:1;index" json:"empresaId"`
|
||||
|
||||
Nombre string `gorm:"type:varchar(100);not null"`
|
||||
Descripcion string `gorm:"type:text"`
|
||||
Nombre string `gorm:"type:varchar(100);not null" json:"nombre"`
|
||||
Descripcion string `gorm:"type:text" json:"descripcion,omitempty"`
|
||||
|
||||
Tipo TipoDescuento `gorm:"type:varchar(20);not null"`
|
||||
Valor float64 `gorm:"type:decimal(12,2);not null"`
|
||||
Tipo TipoDescuento `gorm:"type:varchar(20);not null" json:"tipo"`
|
||||
Valor float64 `gorm:"type:decimal(12,2);not null" json:"valor"`
|
||||
|
||||
Activo bool `gorm:"not null;default:true"`
|
||||
// Sin default en GORM: el valor siempre lo define la capa de aplicación y
|
||||
// así se respeta Activo=false al crear.
|
||||
Activo bool `gorm:"not null" json:"activo"`
|
||||
}
|
||||
|
||||
func (Descuento) TableName() string {
|
||||
return "descuentos"
|
||||
}
|
||||
|
||||
type TipoDescuento string
|
||||
@@ -21,3 +27,8 @@ const (
|
||||
Porcentaje TipoDescuento = "PORCENTAJE"
|
||||
Fijo TipoDescuento = "FIJO"
|
||||
)
|
||||
|
||||
// Valido indica si el tipo de descuento es uno de los soportados.
|
||||
func (t TipoDescuento) Valido() bool {
|
||||
return t == Porcentaje || t == Fijo
|
||||
}
|
||||
+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 {
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// FacturaCambio registra una modificación sobre una factura (auditoría).
|
||||
type FacturaCambio struct {
|
||||
Fecha time.Time `json:"fecha"`
|
||||
UsuarioID uint `json:"usuarioId"`
|
||||
Motivo string `json:"motivo"`
|
||||
ItemsAnteriores []FacturaDetalle `json:"itemsAnteriores"`
|
||||
TotalAnterior float64 `json:"totalAnterior"`
|
||||
ItemsNuevos []FacturaDetalle `json:"itemsNuevos"`
|
||||
TotalNuevo float64 `json:"totalNuevo"`
|
||||
NotaTipo string `json:"notaTipo,omitempty"`
|
||||
NotaID uint `json:"notaId,omitempty"`
|
||||
}
|
||||
@@ -2,9 +2,11 @@ package models
|
||||
|
||||
type FacturaDetalle struct {
|
||||
RepuestoID uint64 `json:"repuestoId"`
|
||||
Cantidad uint `json:"cantidad"`
|
||||
RepuestoNombre string `json:"repuestoNombre"`
|
||||
Cantidad float64 `json:"cantidad"`
|
||||
DescuentoID uint `json:"descuentoId"`
|
||||
Descuento float64 `json:"descuento"`
|
||||
PrecioUnitario float64 `json:"precioUnitario"`
|
||||
Subtotal float64 `json:"subtotal"`
|
||||
AlicuotaIVA float64 `json:"alicuotaIva"`
|
||||
}
|
||||
+12
-4
@@ -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"`
|
||||
Importe float64 `gorm:"type:decimal(10,2)"`
|
||||
ReciboID *uint `json:"reciboId,omitempty"`
|
||||
Recibo *Recibo `gorm:"foreignKey:ReciboID" json:"recibo,omitempty"`
|
||||
Importe float64 `gorm:"type:decimal(15,2)"`
|
||||
Fecha time.Time `gorm:"not null" json:"fecha"`
|
||||
Observacion string `gorm:"type:varchar(255)" json:"observacion,omitempty"`
|
||||
}
|
||||
|
||||
func (Pago) TableName() string {
|
||||
|
||||
@@ -3,20 +3,22 @@ package models_seguridad
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Empresa es el tenant del sistema. Todos los datos de negocio pertenecen a
|
||||
// una empresa y se filtran por EmpresaID.
|
||||
type Empresa struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Nombre string `gorm:"type:varchar(120);not null" json:"nombre"`
|
||||
Slug string `gorm:"type:varchar(60);uniqueIndex;not null" json:"slug"`
|
||||
Cuit *string `gorm:"type:varchar(11);uniqueIndex" json:"cuit,omitempty"`
|
||||
Activa bool `gorm:"not null;default:true" json:"activa"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Nombre string `gorm:"type:varchar(120);not null" json:"nombre"`
|
||||
Slug string `gorm:"type:varchar(60);uniqueIndex;not null" json:"slug"`
|
||||
Cuit *string `gorm:"type:varchar(11);uniqueIndex" json:"cuit,omitempty"`
|
||||
EmailAlertaStock datatypes.JSONSlice[string] `gorm:"type:json" json:"email_alerta_stock,omitempty"`
|
||||
Activa bool `gorm:"not null;default:true" json:"activa"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
}
|
||||
|
||||
func (Empresa) TableName() string {
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
package models_seguridad
|
||||
|
||||
// IDs estables del catálogo global de permisos. Se mantienen fijos para no
|
||||
// romper tokens, grupos ni datos existentes.
|
||||
const (
|
||||
PermisoGestionPermisos uint = 1
|
||||
PermisoGestionGrupos uint = 2
|
||||
PermisoGestionUsuarios uint = 3
|
||||
PermisoGestionRepuestos uint = 4
|
||||
PermisoGestionLogs uint = 6
|
||||
PermisoGestionMarcas uint = 5
|
||||
PermisoGestionEmpresa uint = 7
|
||||
PermisoPlataforma uint = 8
|
||||
PermisoGestionStock uint = 9
|
||||
PermisoGestionAlmacenes uint = 10
|
||||
PermisoGestionProveedores uint = 11
|
||||
PermisoGestionClientes uint = 12
|
||||
)
|
||||
@@ -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,17 @@
|
||||
package repositorios_decorator
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
type DecoradorCliente struct {
|
||||
envuelto IFacturaQuery
|
||||
cliente string
|
||||
}
|
||||
|
||||
func (d DecoradorCliente) Aplicar(db *gorm.DB) *gorm.DB {
|
||||
consulta := d.envuelto.Aplicar(db)
|
||||
if d.cliente != "" {
|
||||
consulta = consulta.Joins("JOIN clientes ON clientes.id = factura.`ClienteID` AND clientes.deleted_at IS NULL").
|
||||
Where("clientes.nombre LIKE ?", "%"+d.cliente+"%")
|
||||
}
|
||||
return consulta
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package repositorios_decorator
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
type DecoradorClienteID struct {
|
||||
envuelto IFacturaQuery
|
||||
clienteID uint
|
||||
}
|
||||
|
||||
func (d DecoradorClienteID) Aplicar(db *gorm.DB) *gorm.DB {
|
||||
consulta := d.envuelto.Aplicar(db)
|
||||
if d.clienteID > 0 {
|
||||
consulta = consulta.Where("factura.`ClienteID` = ?", d.clienteID)
|
||||
}
|
||||
return consulta
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package repositorios_decorator
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DecoradorDesde struct {
|
||||
envuelto IFacturaQuery
|
||||
desde *time.Time
|
||||
}
|
||||
|
||||
func (d DecoradorDesde) Aplicar(db *gorm.DB) *gorm.DB {
|
||||
consulta := d.envuelto.Aplicar(db)
|
||||
if d.desde != nil {
|
||||
consulta = consulta.Where("factura.created_at >= ?", *d.desde)
|
||||
}
|
||||
return consulta
|
||||
}
|
||||
|
||||
type DecoradorHasta struct {
|
||||
envuelto IFacturaQuery
|
||||
hasta *time.Time
|
||||
}
|
||||
|
||||
func (d DecoradorHasta) Aplicar(db *gorm.DB) *gorm.DB {
|
||||
consulta := d.envuelto.Aplicar(db)
|
||||
if d.hasta != nil {
|
||||
consulta = consulta.Where("factura.created_at < ?", d.hasta.AddDate(0, 0, 1))
|
||||
}
|
||||
return consulta
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package repositorios_decorator
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DecoradorEstado struct {
|
||||
envuelto IFacturaQuery
|
||||
estado string
|
||||
}
|
||||
|
||||
func (d DecoradorEstado) Aplicar(db *gorm.DB) *gorm.DB {
|
||||
consulta := d.envuelto.Aplicar(db)
|
||||
// El estado se guarda en mayúsculas; normalizar evita que un valor en
|
||||
// minúsculas filtre de más.
|
||||
estado := strings.ToUpper(strings.TrimSpace(d.estado))
|
||||
if estado != "" {
|
||||
consulta = consulta.Where("factura.estado = ?", estado)
|
||||
}
|
||||
return consulta
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package repositorios_decorator
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
type DecoradorNumero struct {
|
||||
envuelto IFacturaQuery
|
||||
numero string
|
||||
}
|
||||
|
||||
func (d DecoradorNumero) Aplicar(db *gorm.DB) *gorm.DB {
|
||||
consulta := d.envuelto.Aplicar(db)
|
||||
if d.numero != "" {
|
||||
consulta = consulta.Where("factura.numero LIKE ?", "%"+d.numero+"%")
|
||||
}
|
||||
return consulta
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package repositorios_decorator
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
type DecoradorPaginacion struct {
|
||||
envuelto IFacturaQuery
|
||||
pagina int
|
||||
porPagina int
|
||||
}
|
||||
|
||||
func (d DecoradorPaginacion) Aplicar(db *gorm.DB) *gorm.DB {
|
||||
consulta := d.envuelto.Aplicar(db)
|
||||
pagina, porPagina := NormalizarPagina(d.pagina, d.porPagina)
|
||||
consulta = consulta.Order("factura.created_at DESC, factura.id DESC").
|
||||
Offset((pagina - 1) * porPagina).
|
||||
Limit(porPagina)
|
||||
return consulta
|
||||
}
|
||||
|
||||
func NormalizarPagina(pagina, porPagina int) (int, int) {
|
||||
if pagina < 1 {
|
||||
pagina = 1
|
||||
}
|
||||
if porPagina < 1 {
|
||||
porPagina = 50
|
||||
}
|
||||
if porPagina > 200 {
|
||||
porPagina = 200
|
||||
}
|
||||
return pagina, porPagina
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package repositorios_decorator
|
||||
|
||||
import "time"
|
||||
|
||||
// FiltrosFactura acota la consulta del listado de facturas.
|
||||
type FiltrosFactura struct {
|
||||
Numero string
|
||||
ClienteID uint
|
||||
Cliente string
|
||||
Estado string
|
||||
Desde *time.Time
|
||||
Hasta *time.Time
|
||||
Pagina int
|
||||
PorPagina int
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package repositorios_decorator
|
||||
|
||||
import (
|
||||
"repuestera_back/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// IFacturaQuery es el componente base del patrón Decorator para facturas.
|
||||
type IFacturaQuery interface {
|
||||
Aplicar(db *gorm.DB) *gorm.DB
|
||||
}
|
||||
|
||||
// FacturaQueryBase es la implementación base de la cadena.
|
||||
type FacturaQueryBase struct {
|
||||
Preload bool
|
||||
}
|
||||
|
||||
func (q FacturaQueryBase) Aplicar(db *gorm.DB) *gorm.DB {
|
||||
consulta := db.Model(&models.Factura{})
|
||||
if q.Preload {
|
||||
consulta = consulta.Preload("Cliente")
|
||||
}
|
||||
return consulta
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package repositorios_decorator
|
||||
|
||||
// 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}
|
||||
|
||||
actual = DecoradorNumero{envuelto: actual, numero: filtros.Numero}
|
||||
actual = DecoradorClienteID{envuelto: actual, clienteID: filtros.ClienteID}
|
||||
actual = DecoradorCliente{envuelto: actual, cliente: filtros.Cliente}
|
||||
actual = DecoradorEstado{envuelto: actual, estado: filtros.Estado}
|
||||
actual = DecoradorDesde{envuelto: actual, desde: filtros.Desde}
|
||||
actual = DecoradorHasta{envuelto: actual, hasta: filtros.Hasta}
|
||||
if paginar {
|
||||
actual = DecoradorPaginacion{envuelto: actual, pagina: filtros.Pagina, porPagina: filtros.PorPagina}
|
||||
} else {
|
||||
actual = decoradorOrdenFacturas{envuelto: actual}
|
||||
}
|
||||
|
||||
return actual
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package repositorios_decorator
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
type DecoradorAlmacenID struct {
|
||||
envuelto IMovimientoQuery
|
||||
almacenID uint
|
||||
}
|
||||
|
||||
func (d DecoradorAlmacenID) Aplicar(db *gorm.DB) *gorm.DB {
|
||||
consulta := d.envuelto.Aplicar(db)
|
||||
if d.almacenID > 0 {
|
||||
consulta = consulta.Where("almacen_id = ?", d.almacenID)
|
||||
}
|
||||
return consulta
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package repositorios_decorator
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DecoradorDesde struct {
|
||||
envuelto IMovimientoQuery
|
||||
desde *time.Time
|
||||
}
|
||||
|
||||
func (d DecoradorDesde) Aplicar(db *gorm.DB) *gorm.DB {
|
||||
consulta := d.envuelto.Aplicar(db)
|
||||
if d.desde != nil {
|
||||
consulta = consulta.Where("fecha >= ?", *d.desde)
|
||||
}
|
||||
return consulta
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package repositorios_decorator
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DecoradorHasta struct {
|
||||
envuelto IMovimientoQuery
|
||||
hasta *time.Time
|
||||
}
|
||||
|
||||
func (d DecoradorHasta) Aplicar(db *gorm.DB) *gorm.DB {
|
||||
consulta := d.envuelto.Aplicar(db)
|
||||
if d.hasta != nil {
|
||||
consulta = consulta.Where("fecha < ?", d.hasta.AddDate(0, 0, 1))
|
||||
}
|
||||
return consulta
|
||||
}
|
||||
Loaded 100 of 223 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user