Private
Public Access
version pre testeo de descuentos
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
a9ec514687
commit
ea009e276f
25 files changed
+1100
-13
No files matched your search
@@ -31,6 +31,7 @@ var permisosSemilla = []permisoSemilla{
|
|||||||
{12, "Gestión de Clientes", "clientes", "Consultar y administrar los clientes 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."},
|
{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."},
|
{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."},
|
||||||
}
|
}
|
||||||
|
|
||||||
// InitPermisos crea el catálogo global de permisos y garantiza que cada
|
// InitPermisos crea el catálogo global de permisos y garantiza que cada
|
||||||
@@ -89,6 +90,7 @@ func AsegurarGruposEmpresa(db *gorm.DB, empresaID uint) (uint, uint, error) {
|
|||||||
12,
|
12,
|
||||||
13,
|
13,
|
||||||
14,
|
14,
|
||||||
|
16,
|
||||||
}
|
}
|
||||||
if err := asignarPermisosFaltantes(db, admin.ID, permisosAdmin); err != nil {
|
if err := asignarPermisosFaltantes(db, admin.ID, permisosAdmin); err != nil {
|
||||||
return 0, 0, err
|
return 0, 0, err
|
||||||
|
|||||||
@@ -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,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)
|
||||||
|
}
|
||||||
@@ -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,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,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"`
|
||||||
|
}
|
||||||
@@ -6,13 +6,19 @@ type Descuento struct {
|
|||||||
gorm.Model
|
gorm.Model
|
||||||
EmpresaID uint `gorm:"not null;default:1;index" json:"empresaId"`
|
EmpresaID uint `gorm:"not null;default:1;index" json:"empresaId"`
|
||||||
|
|
||||||
Nombre string `gorm:"type:varchar(100);not null"`
|
Nombre string `gorm:"type:varchar(100);not null" json:"nombre"`
|
||||||
Descripcion string `gorm:"type:text"`
|
Descripcion string `gorm:"type:text" json:"descripcion,omitempty"`
|
||||||
|
|
||||||
Tipo TipoDescuento `gorm:"type:varchar(20);not null"`
|
Tipo TipoDescuento `gorm:"type:varchar(20);not null" json:"tipo"`
|
||||||
Valor float64 `gorm:"type:decimal(12,2);not null"`
|
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
|
type TipoDescuento string
|
||||||
@@ -21,3 +27,8 @@ const (
|
|||||||
Porcentaje TipoDescuento = "PORCENTAJE"
|
Porcentaje TipoDescuento = "PORCENTAJE"
|
||||||
Fijo TipoDescuento = "FIJO"
|
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
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package repositorios
|
package repositorios
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
"repuestera_back/models"
|
"repuestera_back/models"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
@@ -9,6 +10,8 @@ import (
|
|||||||
type RepositorioDescuento interface {
|
type RepositorioDescuento interface {
|
||||||
IRepositorio[models.Descuento]
|
IRepositorio[models.Descuento]
|
||||||
ListarActivos() ([]models.Descuento, error)
|
ListarActivos() ([]models.Descuento, error)
|
||||||
|
ObtenerPorNombre(nombre string) (*models.Descuento, error)
|
||||||
|
ActualizarCompleto(entidad *models.Descuento, input models.Descuento, usuarioID uint) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type repositorioDescuento struct {
|
type repositorioDescuento struct {
|
||||||
@@ -25,10 +28,60 @@ func NuevoRepositorioDescuento(db *gorm.DB, empresaID uint) RepositorioDescuento
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repositorioDescuento) ListarActivos() ([]models.Descuento, error) {
|
// ObtenerTodos lista todos los descuentos de la empresa, incluidos los dados de
|
||||||
|
// baja, ordenados por nombre. Sobrescribe el genérico para fijar el orden.
|
||||||
|
func (r *repositorioDescuento) ObtenerTodos() ([]models.Descuento, error) {
|
||||||
var ds []models.Descuento
|
var ds []models.Descuento
|
||||||
if err := r.db.Unscoped().Where("activo = ?", true).Find(&ds).Error; err != nil {
|
if err := r.db.Unscoped().Order("nombre ASC").Find(&ds).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return ds, nil
|
return ds, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListarActivos devuelve los descuentos activos y no eliminados. Es el listado
|
||||||
|
// que consume la pantalla de facturación.
|
||||||
|
func (r *repositorioDescuento) ListarActivos() ([]models.Descuento, error) {
|
||||||
|
var ds []models.Descuento
|
||||||
|
if err := r.db.Where("activo = ?", true).Order("nombre ASC").Find(&ds).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ds, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ObtenerPorNombre busca un descuento por nombre dentro de la empresa. Incluye
|
||||||
|
// los eliminados lógicamente para poder validar duplicados al reactivarlos.
|
||||||
|
func (r *repositorioDescuento) ObtenerPorNombre(nombre string) (*models.Descuento, error) {
|
||||||
|
var descuento models.Descuento
|
||||||
|
if err := r.db.Unscoped().Where("nombre = ?", nombre).First(&descuento).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &descuento, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ActualizarCompleto actualiza todos los campos editables, incluso los valores
|
||||||
|
// cero (por ejemplo Activo=false o una descripción vacía), que el Updates
|
||||||
|
// genérico de GORM ignoraría.
|
||||||
|
func (r *repositorioDescuento) ActualizarCompleto(entidad *models.Descuento, input models.Descuento, usuarioID uint) error {
|
||||||
|
anterior := models.Descuento{}
|
||||||
|
if err := r.db.Unscoped().First(&anterior, entidad.ID).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.empresaID > 0 {
|
||||||
|
input.EmpresaID = r.empresaID
|
||||||
|
}
|
||||||
|
if err := r.db.Unscoped().Model(entidad).
|
||||||
|
Select("nombre", "descripcion", "tipo", "valor", "activo").
|
||||||
|
Updates(input).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
actual := models.Descuento{}
|
||||||
|
if err := r.db.Unscoped().First(&actual, entidad.ID).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
log, err := dto_directors.NewLogDirector().Modificar(usuarioID, r.tabla(), anterior, actual)
|
||||||
|
r.registrarLog(log, err, usuarioID, "modificación")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -8,9 +8,21 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func DescuentoRoute(r *gin.Engine) {
|
func DescuentoRoute(r *gin.Engine) {
|
||||||
grupo := r.Group("/descuentos")
|
// Lectura: facturación (15) necesita los descuentos activos, y gestión de
|
||||||
grupo.Use(middleware.AuthMiddleware(15))
|
// descuentos (16) necesita el listado completo.
|
||||||
|
lectura := r.Group("/descuentos")
|
||||||
|
lectura.Use(middleware.AuthMiddleware(15, 16))
|
||||||
{
|
{
|
||||||
grupo.GET("/", descuento.ObtenerDescuentos)
|
lectura.GET("/", descuento.ObtenerDescuentos)
|
||||||
|
lectura.GET("/todos", descuento.ObtenerTodosLosDescuentos)
|
||||||
|
}
|
||||||
|
|
||||||
|
gestion := r.Group("/descuentos")
|
||||||
|
gestion.Use(middleware.AuthMiddleware(16))
|
||||||
|
{
|
||||||
|
gestion.POST("/", descuento.CrearDescuento)
|
||||||
|
gestion.PUT("/:id", descuento.ActualizarDescuento)
|
||||||
|
gestion.DELETE("/:id", descuento.EliminarDescuento)
|
||||||
|
gestion.PATCH("/:id/alta", descuento.AltaDescuento)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { API_URL } from '$lib/env';
|
||||||
|
import { getToken } from '../token';
|
||||||
|
import type { DescuentoDto } from './crearDescuento';
|
||||||
|
|
||||||
|
export async function actualizarDescuento(id: number, dto: DescuentoDto) {
|
||||||
|
try {
|
||||||
|
const req = await fetch(`${API_URL}/descuentos/${id}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${getToken()}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify(dto)
|
||||||
|
});
|
||||||
|
if (req.ok) return 'ok';
|
||||||
|
const data = await req.json().catch(() => ({}));
|
||||||
|
return data.error ?? 'No se pudo actualizar el descuento';
|
||||||
|
} catch {
|
||||||
|
return 'No se pudo alcanzar el servidor';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { API_URL } from '$lib/env';
|
||||||
|
import { getToken } from '../token';
|
||||||
|
|
||||||
|
export async function altaDescuento(id: number) {
|
||||||
|
try {
|
||||||
|
const req = await fetch(`${API_URL}/descuentos/${id}/alta`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${getToken()}`
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (req.ok) return 'ok';
|
||||||
|
const data = await req.json().catch(() => ({}));
|
||||||
|
return data.error ?? 'No se pudo reactivar el descuento';
|
||||||
|
} catch {
|
||||||
|
return 'No se pudo alcanzar el servidor';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { API_URL } from '$lib/env';
|
||||||
|
import { getToken } from '../token';
|
||||||
|
|
||||||
|
export interface DescuentoDto {
|
||||||
|
nombre: string;
|
||||||
|
descripcion?: string;
|
||||||
|
tipo: 'PORCENTAJE' | 'FIJO';
|
||||||
|
valor: number;
|
||||||
|
activo?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function crearDescuento(dto: DescuentoDto) {
|
||||||
|
try {
|
||||||
|
const req = await fetch(`${API_URL}/descuentos/`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${getToken()}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify(dto)
|
||||||
|
});
|
||||||
|
if (req.ok) return 'ok';
|
||||||
|
const data = await req.json().catch(() => ({}));
|
||||||
|
return data.error ?? 'No se pudo crear el descuento';
|
||||||
|
} catch {
|
||||||
|
return 'No se pudo alcanzar el servidor';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { API_URL } from '$lib/env';
|
||||||
|
import { getToken } from '../token';
|
||||||
|
|
||||||
|
export async function eliminarDescuento(id: number) {
|
||||||
|
try {
|
||||||
|
const req = await fetch(`${API_URL}/descuentos/${id}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${getToken()}`
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (req.ok) return 'Ok';
|
||||||
|
const data = await req.json().catch(() => ({}));
|
||||||
|
return data.error ?? 'No se pudo eliminar el descuento';
|
||||||
|
} catch {
|
||||||
|
return 'No se pudo alcanzar el servidor';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { API_URL } from '$lib/env';
|
||||||
|
import type { Descuento } from '../../../types';
|
||||||
|
import { getToken } from '../token';
|
||||||
|
|
||||||
|
// Listado completo (activos, inactivos y dados de baja) para la gestión.
|
||||||
|
export async function obtenerDescuentos(fetch2?: Function): Promise<Descuento[] | string> {
|
||||||
|
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||||
|
try {
|
||||||
|
const req = await fetchfn(`${API_URL}/descuentos/todos`, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||||
|
});
|
||||||
|
const data = await req.json();
|
||||||
|
if (req.ok) return data;
|
||||||
|
return data.error ?? 'No se pudieron obtener los descuentos';
|
||||||
|
} catch {
|
||||||
|
return 'No se pudo alcanzar el servidor';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import Header from '$lib/components/Header.svelte';
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
DataTableSkeleton,
|
||||||
|
InlineNotification,
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableContainer,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
Tag
|
||||||
|
} from 'carbon-components-svelte';
|
||||||
|
import { Add, ArrowUp, Edit, TrashCan } from 'carbon-icons-svelte';
|
||||||
|
import type { Descuento } from '../../types';
|
||||||
|
import CrearDescuentoForm from './CrearDescuentoForm.svelte';
|
||||||
|
import EditarDescuentoForm from './EditarDescuentoForm.svelte';
|
||||||
|
import EliminarDescuentoForm from './EliminarDescuentoForm.svelte';
|
||||||
|
import AltaDescuentoForm from './AltaDescuentoForm.svelte';
|
||||||
|
|
||||||
|
let { data }: { data: { descuentos: Descuento[] | string } } = $props();
|
||||||
|
|
||||||
|
let descuentos = $derived<Descuento[]>(Array.isArray(data.descuentos) ? data.descuentos : []);
|
||||||
|
let errorCarga = $derived(
|
||||||
|
data.descuentos !== undefined && data.descuentos !== null && !Array.isArray(data.descuentos)
|
||||||
|
? String(data.descuentos)
|
||||||
|
: ''
|
||||||
|
);
|
||||||
|
|
||||||
|
let openCrear = $state(false);
|
||||||
|
let openEdit = $state(false);
|
||||||
|
let openDelete = $state(false);
|
||||||
|
let openAlta = $state(false);
|
||||||
|
|
||||||
|
let descuentoSeleccionado = $state<Descuento | null>(null);
|
||||||
|
let descuentoAEliminar = $state<Descuento | null>(null);
|
||||||
|
let descuentoAAlta = $state<Descuento | null>(null);
|
||||||
|
|
||||||
|
const headers = [
|
||||||
|
{ key: 'ID', value: 'ID' },
|
||||||
|
{ key: 'nombre', value: 'Nombre' },
|
||||||
|
{ key: 'descripcion', value: 'Descripción' },
|
||||||
|
{ key: 'tipo', value: 'Tipo' },
|
||||||
|
{ key: 'valor', value: 'Valor' },
|
||||||
|
{ key: 'activo', value: 'Activo' },
|
||||||
|
{ key: 'CreatedAt', value: 'Creado' },
|
||||||
|
{ key: 'DeletedAt', value: 'Estado' }
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
function nombreTipo(tipo: Descuento['tipo']): string {
|
||||||
|
return tipo === 'PORCENTAJE' ? 'Porcentaje' : 'Monto fijo';
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatoValor(d: Descuento): string {
|
||||||
|
const valor = Number(d.valor ?? 0);
|
||||||
|
return d.tipo === 'PORCENTAJE' ? `${valor}%` : `$ ${valor.toFixed(2)}`;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Header />
|
||||||
|
<div class="page-container">
|
||||||
|
<div class="flex justify-between">
|
||||||
|
<h1 class="page-title">Gestión de Descuentos</h1>
|
||||||
|
<Button
|
||||||
|
icon={Add}
|
||||||
|
onclick={() => {
|
||||||
|
openCrear = true;
|
||||||
|
}}>Nuevo Descuento</Button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if errorCarga}
|
||||||
|
<InlineNotification kind="error" title="Error" subtitle={errorCarga} hideCloseButton />
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if typeof data.descuentos === 'undefined' || data.descuentos === null}
|
||||||
|
<DataTableSkeleton />
|
||||||
|
{:else if descuentos.length === 0}
|
||||||
|
<TableContainer title="Descuentos">
|
||||||
|
<Table>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
{#each headers as header}
|
||||||
|
<TableHeader>{header.value}</TableHeader>
|
||||||
|
{/each}
|
||||||
|
<TableHeader>Acciones</TableHeader>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colspan={headers.length + 1}>
|
||||||
|
No hay descuentos para mostrar, registrá uno.
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</TableContainer>
|
||||||
|
{:else}
|
||||||
|
<TableContainer title="Listado de Descuentos">
|
||||||
|
<Table>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
{#each headers as header}
|
||||||
|
<TableHeader>{header.value}</TableHeader>
|
||||||
|
{/each}
|
||||||
|
<TableHeader>Acciones</TableHeader>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{#each descuentos as d (d.ID)}
|
||||||
|
<TableRow>
|
||||||
|
<TableCell>{d.ID}</TableCell>
|
||||||
|
<TableCell>{d.nombre}</TableCell>
|
||||||
|
<TableCell class="max-w-xs truncate" title={d.descripcion ?? ''}>
|
||||||
|
{d.descripcion || '-'}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Tag type={d.tipo === 'PORCENTAJE' ? 'blue' : 'green'}>
|
||||||
|
{nombreTipo(d.tipo)}
|
||||||
|
</Tag>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{formatoValor(d)}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Tag type={d.activo ? 'green' : 'gray'}>{d.activo ? 'Sí' : 'No'}</Tag>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{String(d.CreatedAt ?? '-')}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{#if d.DeletedAt}
|
||||||
|
<Tag type="red">Eliminado</Tag>
|
||||||
|
{:else}
|
||||||
|
<Tag type="green">Habilitado</Tag>
|
||||||
|
{/if}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{#if d.DeletedAt}
|
||||||
|
<Button
|
||||||
|
kind="ghost"
|
||||||
|
size="small"
|
||||||
|
icon={ArrowUp}
|
||||||
|
onclick={() => {
|
||||||
|
descuentoAAlta = d;
|
||||||
|
openAlta = true;
|
||||||
|
}}>Alta</Button
|
||||||
|
>
|
||||||
|
{:else}
|
||||||
|
<Button
|
||||||
|
kind="ghost"
|
||||||
|
size="small"
|
||||||
|
icon={Edit}
|
||||||
|
onclick={() => {
|
||||||
|
descuentoSeleccionado = d;
|
||||||
|
openEdit = true;
|
||||||
|
}}>Editar</Button
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
kind="danger-ghost"
|
||||||
|
size="small"
|
||||||
|
icon={TrashCan}
|
||||||
|
onclick={() => {
|
||||||
|
descuentoAEliminar = d;
|
||||||
|
openDelete = true;
|
||||||
|
}}>Eliminar</Button
|
||||||
|
>
|
||||||
|
{/if}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
{/each}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</TableContainer>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<CrearDescuentoForm bind:open={openCrear} onClose={() => (openCrear = false)} />
|
||||||
|
|
||||||
|
<EditarDescuentoForm
|
||||||
|
bind:open={openEdit}
|
||||||
|
descuento={descuentoSeleccionado}
|
||||||
|
onClose={() => {
|
||||||
|
openEdit = false;
|
||||||
|
descuentoSeleccionado = null;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<EliminarDescuentoForm
|
||||||
|
bind:open={openDelete}
|
||||||
|
descuento={descuentoAEliminar}
|
||||||
|
onClose={() => {
|
||||||
|
openDelete = false;
|
||||||
|
descuentoAEliminar = null;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<AltaDescuentoForm
|
||||||
|
bind:open={openAlta}
|
||||||
|
descuento={descuentoAAlta}
|
||||||
|
onClose={() => {
|
||||||
|
openAlta = false;
|
||||||
|
descuentoAAlta = null;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { obtenerDescuentos } from '$lib/hooks/descuentos/obtenerDescuentos';
|
||||||
|
|
||||||
|
export const ssr = false;
|
||||||
|
|
||||||
|
export async function load({ depends, fetch }) {
|
||||||
|
depends('descuentos:load');
|
||||||
|
const descuentos = await obtenerDescuentos(fetch);
|
||||||
|
|
||||||
|
return { descuentos };
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { invalidate } from '$app/navigation';
|
||||||
|
import { InlineNotification, Modal } from 'carbon-components-svelte';
|
||||||
|
import type { Descuento } from '../../types';
|
||||||
|
import { altaDescuento } from '$lib/hooks/descuentos/altaDescuento';
|
||||||
|
|
||||||
|
let {
|
||||||
|
open = $bindable(),
|
||||||
|
onClose,
|
||||||
|
descuento
|
||||||
|
}: { open?: boolean; onClose?: () => void; descuento?: Descuento | null } = $props();
|
||||||
|
|
||||||
|
let error = $state('');
|
||||||
|
let enviando = $state(false);
|
||||||
|
|
||||||
|
async function handleSubmit(e: Event) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (enviando) return;
|
||||||
|
enviando = true;
|
||||||
|
error = '';
|
||||||
|
if (!descuento?.ID) {
|
||||||
|
error = 'No se pudo obtener el descuento. Recargá la página.';
|
||||||
|
enviando = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = await altaDescuento(descuento.ID);
|
||||||
|
if (result !== 'ok') {
|
||||||
|
error = result;
|
||||||
|
enviando = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await invalidate('descuentos:load');
|
||||||
|
enviando = false;
|
||||||
|
onClose?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClose() {
|
||||||
|
error = '';
|
||||||
|
enviando = false;
|
||||||
|
onClose?.();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<form id="altaDescuentoForm" onsubmit={handleSubmit}>
|
||||||
|
<Modal
|
||||||
|
formId="altaDescuentoForm"
|
||||||
|
bind:open
|
||||||
|
size="sm"
|
||||||
|
modalHeading="Dar de alta descuento"
|
||||||
|
primaryButtonText="Dar de alta"
|
||||||
|
primaryButtonDisabled={enviando}
|
||||||
|
secondaryButtonText="Cancelar"
|
||||||
|
on:click:button--secondary={handleClose}
|
||||||
|
>
|
||||||
|
{#if error}
|
||||||
|
<div class="mb-4">
|
||||||
|
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<p>
|
||||||
|
¿Dar de alta el descuento <strong>{descuento?.nombre ?? ''}</strong>?
|
||||||
|
</p>
|
||||||
|
</Modal>
|
||||||
|
</form>
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { invalidate } from '$app/navigation';
|
||||||
|
import {
|
||||||
|
InlineNotification,
|
||||||
|
Modal,
|
||||||
|
NumberInput,
|
||||||
|
Select,
|
||||||
|
SelectItem,
|
||||||
|
TextArea,
|
||||||
|
TextInput,
|
||||||
|
Toggle
|
||||||
|
} from 'carbon-components-svelte';
|
||||||
|
import { crearDescuento } from '$lib/hooks/descuentos/crearDescuento';
|
||||||
|
|
||||||
|
let { open = $bindable(), onClose }: { open?: boolean; onClose?: () => void } = $props();
|
||||||
|
|
||||||
|
let nombre = $state('');
|
||||||
|
let descripcion = $state('');
|
||||||
|
let tipo = $state('PORCENTAJE');
|
||||||
|
let valor = $state(0);
|
||||||
|
let activo = $state(true);
|
||||||
|
let enviando = $state(false);
|
||||||
|
let error = $state('');
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (open) {
|
||||||
|
nombre = '';
|
||||||
|
descripcion = '';
|
||||||
|
tipo = 'PORCENTAJE';
|
||||||
|
valor = 0;
|
||||||
|
activo = true;
|
||||||
|
error = '';
|
||||||
|
enviando = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function validar(): string {
|
||||||
|
if (nombre.trim() === '') return 'El nombre es obligatorio.';
|
||||||
|
if (!tipo) return 'El tipo es obligatorio.';
|
||||||
|
if (!valor || valor <= 0) return 'El valor debe ser mayor a cero.';
|
||||||
|
if (tipo === 'PORCENTAJE' && valor > 100) return 'El porcentaje no puede superar el 100%.';
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function enviar() {
|
||||||
|
if (enviando) return;
|
||||||
|
enviando = true;
|
||||||
|
error = validar();
|
||||||
|
|
||||||
|
if (error === '') {
|
||||||
|
const result = await crearDescuento({
|
||||||
|
nombre: nombre.trim(),
|
||||||
|
descripcion: descripcion.trim(),
|
||||||
|
tipo: tipo as 'PORCENTAJE' | 'FIJO',
|
||||||
|
valor: Number(valor),
|
||||||
|
activo
|
||||||
|
});
|
||||||
|
if (result === 'ok') {
|
||||||
|
await invalidate('descuentos:load');
|
||||||
|
onClose?.();
|
||||||
|
} else {
|
||||||
|
error = result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enviando = false;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<form
|
||||||
|
id="crearDescuentoForm"
|
||||||
|
onsubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
void enviar();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Modal
|
||||||
|
formId="crearDescuentoForm"
|
||||||
|
bind:open
|
||||||
|
size="lg"
|
||||||
|
modalHeading="Registrar descuento"
|
||||||
|
primaryButtonText="Registrar"
|
||||||
|
primaryButtonDisabled={enviando}
|
||||||
|
secondaryButtonText="Cancelar"
|
||||||
|
on:click:button--secondary={() => onClose?.()}
|
||||||
|
>
|
||||||
|
{#if error}
|
||||||
|
<div class="mb-4">
|
||||||
|
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<TextInput labelText="Nombre" bind:value={nombre} maxlength={100} required />
|
||||||
|
<div class="mt-1 text-sm text-gray-500">{nombre.length}/100</div>
|
||||||
|
|
||||||
|
<div class="mt-4">
|
||||||
|
<Select labelText="Tipo" bind:selected={tipo}>
|
||||||
|
<SelectItem value="PORCENTAJE" text="Porcentaje (%)" />
|
||||||
|
<SelectItem value="FIJO" text="Monto fijo ($)" />
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-4">
|
||||||
|
<NumberInput
|
||||||
|
labelText={tipo === 'PORCENTAJE' ? 'Porcentaje' : 'Monto fijo'}
|
||||||
|
bind:value={valor}
|
||||||
|
min={0}
|
||||||
|
step={0.01}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-4">
|
||||||
|
<TextArea labelText="Descripción" bind:value={descripcion} maxlength={500} rows={3} />
|
||||||
|
<div class="mt-1 text-sm text-gray-500">{descripcion.length}/500</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-4">
|
||||||
|
<Toggle bind:toggled={activo} labelText="Descuento activo" />
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</form>
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { invalidate } from '$app/navigation';
|
||||||
|
import {
|
||||||
|
InlineNotification,
|
||||||
|
Modal,
|
||||||
|
NumberInput,
|
||||||
|
Select,
|
||||||
|
SelectItem,
|
||||||
|
TextArea,
|
||||||
|
TextInput,
|
||||||
|
Toggle
|
||||||
|
} from 'carbon-components-svelte';
|
||||||
|
import type { Descuento } from '../../types';
|
||||||
|
import { actualizarDescuento } from '$lib/hooks/descuentos/actualizarDescuento';
|
||||||
|
|
||||||
|
let {
|
||||||
|
open = $bindable(),
|
||||||
|
onClose,
|
||||||
|
descuento
|
||||||
|
}: { open?: boolean; onClose?: () => void; descuento?: Descuento | null } = $props();
|
||||||
|
|
||||||
|
let nombre = $state('');
|
||||||
|
let descripcion = $state('');
|
||||||
|
let tipo = $state('PORCENTAJE');
|
||||||
|
let valor = $state(0);
|
||||||
|
let activo = $state(true);
|
||||||
|
let enviando = $state(false);
|
||||||
|
let error = $state('');
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (descuento) {
|
||||||
|
nombre = descuento.nombre ?? '';
|
||||||
|
descripcion = descuento.descripcion ?? '';
|
||||||
|
tipo = descuento.tipo ?? 'PORCENTAJE';
|
||||||
|
valor = descuento.valor ?? 0;
|
||||||
|
activo = descuento.activo ?? true;
|
||||||
|
error = '';
|
||||||
|
enviando = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function validar(): string {
|
||||||
|
if (nombre.trim() === '') return 'El nombre es obligatorio.';
|
||||||
|
if (!tipo) return 'El tipo es obligatorio.';
|
||||||
|
if (!valor || valor <= 0) return 'El valor debe ser mayor a cero.';
|
||||||
|
if (tipo === 'PORCENTAJE' && valor > 100) return 'El porcentaje no puede superar el 100%.';
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function enviar() {
|
||||||
|
if (enviando) return;
|
||||||
|
enviando = true;
|
||||||
|
error = validar();
|
||||||
|
|
||||||
|
if (error === '' && descuento) {
|
||||||
|
const result = await actualizarDescuento(descuento.ID, {
|
||||||
|
nombre: nombre.trim(),
|
||||||
|
descripcion: descripcion.trim(),
|
||||||
|
tipo: tipo as 'PORCENTAJE' | 'FIJO',
|
||||||
|
valor: Number(valor),
|
||||||
|
activo
|
||||||
|
});
|
||||||
|
if (result === 'ok') {
|
||||||
|
await invalidate('descuentos:load');
|
||||||
|
onClose?.();
|
||||||
|
} else {
|
||||||
|
error = result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enviando = false;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<form
|
||||||
|
id="editarDescuentoForm"
|
||||||
|
onsubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
void enviar();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Modal
|
||||||
|
formId="editarDescuentoForm"
|
||||||
|
bind:open
|
||||||
|
size="lg"
|
||||||
|
modalHeading="Editar descuento"
|
||||||
|
primaryButtonText="Guardar"
|
||||||
|
primaryButtonDisabled={enviando}
|
||||||
|
secondaryButtonText="Cancelar"
|
||||||
|
on:click:button--secondary={() => onClose?.()}
|
||||||
|
>
|
||||||
|
{#if error}
|
||||||
|
<div class="mb-4">
|
||||||
|
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<TextInput labelText="Nombre" bind:value={nombre} maxlength={100} required />
|
||||||
|
<div class="mt-1 text-sm text-gray-500">{nombre.length}/100</div>
|
||||||
|
|
||||||
|
<div class="mt-4">
|
||||||
|
<Select labelText="Tipo" bind:selected={tipo}>
|
||||||
|
<SelectItem value="PORCENTAJE" text="Porcentaje (%)" />
|
||||||
|
<SelectItem value="FIJO" text="Monto fijo ($)" />
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-4">
|
||||||
|
<NumberInput
|
||||||
|
labelText={tipo === 'PORCENTAJE' ? 'Porcentaje' : 'Monto fijo'}
|
||||||
|
bind:value={valor}
|
||||||
|
min={0}
|
||||||
|
step={0.01}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-4">
|
||||||
|
<TextArea labelText="Descripción" bind:value={descripcion} maxlength={500} rows={3} />
|
||||||
|
<div class="mt-1 text-sm text-gray-500">{descripcion.length}/500</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-4">
|
||||||
|
<Toggle bind:toggled={activo} labelText="Descuento activo" />
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</form>
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { invalidate } from '$app/navigation';
|
||||||
|
import { InlineNotification, Modal } from 'carbon-components-svelte';
|
||||||
|
import type { Descuento } from '../../types';
|
||||||
|
import { eliminarDescuento } from '$lib/hooks/descuentos/eliminarDescuento';
|
||||||
|
|
||||||
|
let {
|
||||||
|
open = $bindable(),
|
||||||
|
onClose,
|
||||||
|
descuento
|
||||||
|
}: { open?: boolean; onClose?: () => void; descuento?: Descuento | null } = $props();
|
||||||
|
|
||||||
|
let error = $state('');
|
||||||
|
|
||||||
|
async function handleSubmit(e: Event) {
|
||||||
|
e.preventDefault();
|
||||||
|
error = '';
|
||||||
|
if (!descuento?.ID) {
|
||||||
|
error = 'No se pudo obtener el descuento. Recargá la página.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = await eliminarDescuento(descuento.ID);
|
||||||
|
if (result !== 'Ok') {
|
||||||
|
error = result;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await invalidate('descuentos:load');
|
||||||
|
onClose?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClose() {
|
||||||
|
error = '';
|
||||||
|
onClose?.();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<form id="eliminarDescuentoForm" onsubmit={handleSubmit}>
|
||||||
|
<Modal
|
||||||
|
formId="eliminarDescuentoForm"
|
||||||
|
bind:open
|
||||||
|
size="sm"
|
||||||
|
modalHeading="Eliminar descuento"
|
||||||
|
primaryButtonText="Eliminar"
|
||||||
|
secondaryButtonText="Cancelar"
|
||||||
|
danger
|
||||||
|
on:click:button--secondary={handleClose}
|
||||||
|
>
|
||||||
|
{#if error}
|
||||||
|
<div class="mb-4">
|
||||||
|
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<p>
|
||||||
|
¿Está seguro de que desea eliminar el descuento
|
||||||
|
<strong>{descuento?.nombre ?? ''}</strong>?
|
||||||
|
</p>
|
||||||
|
</Modal>
|
||||||
|
</form>
|
||||||
@@ -72,8 +72,8 @@
|
|||||||
let descuentoTotal = $derived.by(() => {
|
let descuentoTotal = $derived.by(() => {
|
||||||
const d = descuentos.find((x) => x.ID === descuentoId);
|
const d = descuentos.find((x) => x.ID === descuentoId);
|
||||||
if (!d) return 0;
|
if (!d) return 0;
|
||||||
if (d.Tipo === 'PORCENTAJE') return subtotal * (d.Valor / 100);
|
if (d.tipo === 'PORCENTAJE') return subtotal * (d.valor / 100);
|
||||||
return Math.min(d.Valor, subtotal);
|
return Math.min(d.valor, subtotal);
|
||||||
});
|
});
|
||||||
|
|
||||||
let baseImponible = $derived(subtotal - descuentoTotal);
|
let baseImponible = $derived(subtotal - descuentoTotal);
|
||||||
@@ -182,7 +182,7 @@
|
|||||||
{#each descuentos as d (d.ID)}
|
{#each descuentos as d (d.ID)}
|
||||||
<SelectItem
|
<SelectItem
|
||||||
value={d.ID}
|
value={d.ID}
|
||||||
text={`${d.Nombre} (${d.Tipo === 'PORCENTAJE' ? d.Valor + '%' : '$' + d.Valor})`}
|
text={`${d.nombre} (${d.tipo === 'PORCENTAJE' ? d.valor + '%' : '$' + d.valor})`}
|
||||||
/>
|
/>
|
||||||
{/each}
|
{/each}
|
||||||
</Select>
|
</Select>
|
||||||
|
|||||||
Vendored
+9
@@ -202,6 +202,15 @@ export interface Marca extends BaseModel {
|
|||||||
repuestos: Repuesto[];
|
repuestos: Repuesto[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface Descuento extends BaseModel {
|
||||||
|
empresaId?: number;
|
||||||
|
nombre: string;
|
||||||
|
descripcion?: string;
|
||||||
|
tipo: 'PORCENTAJE' | 'FIJO';
|
||||||
|
valor: number;
|
||||||
|
activo: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface Repuesto extends BaseModel {
|
export interface Repuesto extends BaseModel {
|
||||||
empresaId?: number;
|
empresaId?: number;
|
||||||
nombre: string;
|
nombre: string;
|
||||||
|
|||||||
Reference in new issue
Block a user