Private
Public Access
Merge pull request 'hecha hasta el primer caso de uso' (#43) from dev into master
Tests post-merge / tests (push) Failing after 10m58s
Tests post-merge / tests (push) Failing after 10m58s
Reviewed-on: #43
This commit was merged in pull request #43.
This commit is contained in:
commit
b64f8452f0
677 files changed
+34524
-2012
No files matched your search
@@ -0,0 +1 @@
|
|||||||
|
docs/**/*.png filter=lfs diff=lfs merge=lfs -text
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
name: Tests post-merge
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
tests:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout código
|
||||||
|
run: |
|
||||||
|
git clone https://${{ secrets.GIT_USER }}:${{ secrets.REGISTRY_PASS }}@fedesrv.ddns.net/git/${{ github.repository }}.git .
|
||||||
|
git checkout ${{ github.sha }}
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.27'
|
||||||
|
|
||||||
|
- name: Tests backend
|
||||||
|
working-directory: ./back
|
||||||
|
run: go test ./...
|
||||||
+14
@@ -1,2 +1,16 @@
|
|||||||
back/.env
|
back/.env
|
||||||
back/repuestera_back
|
back/repuestera_back
|
||||||
|
mysql/.env
|
||||||
|
comms/.env
|
||||||
|
.metals/
|
||||||
|
back/tmp/main
|
||||||
|
comms/.bsp/sbt.json
|
||||||
|
comms/project/project/
|
||||||
|
comms/project/target/
|
||||||
|
comms/target/
|
||||||
|
comms/.bloop/
|
||||||
|
comms/.idea/
|
||||||
|
/scripts/.scala-build
|
||||||
|
skills/
|
||||||
|
/scripts/.idea
|
||||||
|
/scripts/.bsp
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
#:schema https://json.schemastore.org/any.json
|
||||||
|
|
||||||
|
env_files = []
|
||||||
|
root = "."
|
||||||
|
testdata_dir = "testdata"
|
||||||
|
tmp_dir = "tmp"
|
||||||
|
|
||||||
|
[build]
|
||||||
|
args_bin = []
|
||||||
|
bin = "./tmp/main"
|
||||||
|
cmd = "go build -o ./tmp/main ."
|
||||||
|
delay = 1000
|
||||||
|
entrypoint = ["./tmp/main"]
|
||||||
|
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
|
||||||
|
exclude_file = []
|
||||||
|
exclude_regex = ["_test.go"]
|
||||||
|
exclude_unchanged = false
|
||||||
|
follow_symlink = false
|
||||||
|
full_bin = ""
|
||||||
|
ignore_dangerous_root_dir = false
|
||||||
|
include_dir = []
|
||||||
|
include_ext = ["go", "tpl", "tmpl", "html"]
|
||||||
|
include_file = []
|
||||||
|
kill_delay = "0s"
|
||||||
|
log = "build-errors.log"
|
||||||
|
poll = false
|
||||||
|
poll_interval = 0
|
||||||
|
post_cmd = []
|
||||||
|
pre_cmd = []
|
||||||
|
rerun = false
|
||||||
|
rerun_delay = 500
|
||||||
|
send_interrupt = false
|
||||||
|
stop_on_error = false
|
||||||
|
|
||||||
|
[color]
|
||||||
|
app = ""
|
||||||
|
build = "yellow"
|
||||||
|
main = "magenta"
|
||||||
|
mode = ""
|
||||||
|
runner = "green"
|
||||||
|
watcher = "cyan"
|
||||||
|
|
||||||
|
[log]
|
||||||
|
main_only = false
|
||||||
|
silent = false
|
||||||
|
time = false
|
||||||
|
|
||||||
|
[misc]
|
||||||
|
clean_on_exit = false
|
||||||
|
|
||||||
|
[proxy]
|
||||||
|
app_port = 0
|
||||||
|
app_start_timeout = 0
|
||||||
|
enabled = false
|
||||||
|
proxy_port = 0
|
||||||
|
|
||||||
|
[screen]
|
||||||
|
clear_on_rebuild = false
|
||||||
|
keep_scroll = true
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
.gitea
|
||||||
|
repuestera_back
|
||||||
|
.env
|
||||||
+3
-3
@@ -1,13 +1,13 @@
|
|||||||
# syntax=docker/dockerfile:1
|
# syntax=docker/dockerfile:1
|
||||||
FROM golang:1.26-alpine AS builder
|
FROM golang:1.27-alpine AS builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o server .
|
RUN CGO_ENABLED=0 GOOS=linux go build -o server .
|
||||||
|
# -ldflags="-s -w"
|
||||||
# ---
|
# ---
|
||||||
FROM scratch
|
FROM scratch
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
FROM golang:1.27-alpine
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN go install github.com/air-verse/air@latest
|
||||||
|
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
CMD ["air", "-c", ".air.toml"]
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,363 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type permisoSemilla struct {
|
||||||
|
ID uint
|
||||||
|
Nombre string
|
||||||
|
Alias string
|
||||||
|
Descripcion string
|
||||||
|
}
|
||||||
|
|
||||||
|
var permisosSemilla = []permisoSemilla{
|
||||||
|
{1, "Gestión de Permisos", "permisos", "Administrar el catálogo global de permisos. Solo plataforma."},
|
||||||
|
{2, "Gestión de Grupos", "grupos", "Crear, editar y eliminar grupos de la empresa."},
|
||||||
|
{3, "Gestión de Usuarios", "usuarios", "Administrar miembros, invitaciones y cuentas de la empresa."},
|
||||||
|
{4, "Gestión de Repuestos", "repuestos", "Crear, editar y eliminar repuestos."},
|
||||||
|
{5, "Gestión de Marcas", "marcas", "Crear, editar y eliminar marcas."},
|
||||||
|
{6, "Gestión de Logs", "logs", "Consultar la auditoría de la empresa."},
|
||||||
|
{7, "Gestión de Empresa", "empresa", "Editar los datos de la empresa y sus miembros."},
|
||||||
|
{8, "Administración de Plataforma", "plataforma", "Administrar empresas y administradores globales."},
|
||||||
|
{9, "Gestión de Stock", "stock", "Consultar y operar el stock de la empresa."},
|
||||||
|
{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."},
|
||||||
|
}
|
||||||
|
|
||||||
|
// InitPermisos crea el catálogo global de permisos y garantiza que cada
|
||||||
|
// empresa tenga sus grupos base. Es idempotente.
|
||||||
|
func InitPermisos() {
|
||||||
|
for _, semilla := range permisosSemilla {
|
||||||
|
permiso := models_seguridad.Permiso{ID: semilla.ID}
|
||||||
|
DB.Where("id = ?", semilla.ID).FirstOrCreate(&permiso, models_seguridad.Permiso{
|
||||||
|
ID: semilla.ID,
|
||||||
|
Nombre: semilla.Nombre,
|
||||||
|
Alias: semilla.Alias,
|
||||||
|
Descripcion: semilla.Descripcion,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
var empresas []models_seguridad.Empresa
|
||||||
|
if err := DB.Find(&empresas).Error; err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, empresa := range empresas {
|
||||||
|
adminID, _, err := AsegurarGruposEmpresa(DB, empresa.ID)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
asegurarOwnersEnAdmin(DB, empresa.ID, adminID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AsegurarGruposEmpresa crea los grupos base "Admin" y "Usuario" de una
|
||||||
|
// empresa y les asigna los permisos que corresponden. Devuelve sus IDs.
|
||||||
|
func AsegurarGruposEmpresa(db *gorm.DB, empresaID uint) (uint, uint, error) {
|
||||||
|
if empresaID == 0 {
|
||||||
|
return 0, 0, errors.New("empresa inválida")
|
||||||
|
}
|
||||||
|
|
||||||
|
admin, err := primerGrupo(db, empresaID, "Admin", "Administrador de la empresa")
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
usuario, err := primerGrupo(db, empresaID, "Usuario", "Usuario común de la empresa")
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
if err := asignarPermisosFaltantes(db, usuario.ID, permisosUsuario); err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return admin.ID, usuario.ID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func primerGrupo(db *gorm.DB, empresaID uint, nombre, descripcion string) (*models_seguridad.Grupo, error) {
|
||||||
|
grupo := models_seguridad.Grupo{}
|
||||||
|
err := db.Where("empresa_id = ? AND nombre = ?", empresaID, nombre).First(&grupo).Error
|
||||||
|
if err == nil {
|
||||||
|
return &grupo, nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
grupo = models_seguridad.Grupo{
|
||||||
|
EmpresaID: empresaID,
|
||||||
|
Nombre: nombre,
|
||||||
|
Descripcion: descripcion,
|
||||||
|
}
|
||||||
|
if err := db.Create(&grupo).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &grupo, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func asignarPermisosFaltantes(db *gorm.DB, grupoID uint, ids []uint) error {
|
||||||
|
var actuales []models_seguridad.Permiso
|
||||||
|
if err := db.Model(&models_seguridad.Grupo{ID: grupoID}).Association("Permisos").Find(&actuales); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
existentes := make(map[uint]bool, len(actuales))
|
||||||
|
for _, permiso := range actuales {
|
||||||
|
existentes[permiso.ID] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
var faltantes []models_seguridad.Permiso
|
||||||
|
for _, id := range ids {
|
||||||
|
if existentes[id] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var permiso models_seguridad.Permiso
|
||||||
|
if err := db.First(&permiso, id).Error; err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
faltantes = append(faltantes, permiso)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(faltantes) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return db.Model(&models_seguridad.Grupo{ID: grupoID}).Association("Permisos").Append(faltantes)
|
||||||
|
}
|
||||||
|
|
||||||
|
func asegurarOwnersEnAdmin(db *gorm.DB, empresaID, adminID uint) {
|
||||||
|
var owners []models_seguridad.EmpresaUsuario
|
||||||
|
if err := db.Where("empresa_id = ? AND rol = ? AND activo = ?", empresaID, models_seguridad.RolOwner, true).
|
||||||
|
Find(&owners).Error; err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, owner := range owners {
|
||||||
|
var count int64
|
||||||
|
db.Table("usuarios_grupos").
|
||||||
|
Where("usuario_id = ? AND grupo_id = ?", owner.UsuarioID, adminID).
|
||||||
|
Count(&count)
|
||||||
|
if count > 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
db.Exec(
|
||||||
|
"INSERT IGNORE INTO usuarios_grupos (usuario_id, grupo_id) VALUES (?, ?)",
|
||||||
|
owner.UsuarioID, adminID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Slugify genera un slug estable a partir de un nombre.
|
||||||
|
func Slugify(nombre string) string {
|
||||||
|
nombre = strings.ToLower(strings.TrimSpace(nombre))
|
||||||
|
var b strings.Builder
|
||||||
|
guion := false
|
||||||
|
for _, r := range nombre {
|
||||||
|
switch {
|
||||||
|
case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
|
||||||
|
b.WriteRune(r)
|
||||||
|
guion = false
|
||||||
|
case r == 'á' || r == 'à' || r == 'ä' || r == 'â':
|
||||||
|
b.WriteRune('a')
|
||||||
|
guion = false
|
||||||
|
case r == 'é' || r == 'è' || r == 'ë' || r == 'ê':
|
||||||
|
b.WriteRune('e')
|
||||||
|
guion = false
|
||||||
|
case r == 'í' || r == 'ì' || r == 'ï' || r == 'î':
|
||||||
|
b.WriteRune('i')
|
||||||
|
guion = false
|
||||||
|
case r == 'ó' || r == 'ò' || r == 'ö' || r == 'ô':
|
||||||
|
b.WriteRune('o')
|
||||||
|
guion = false
|
||||||
|
case r == 'ú' || r == 'ù' || r == 'ü' || r == 'û':
|
||||||
|
b.WriteRune('u')
|
||||||
|
guion = false
|
||||||
|
case r == 'ñ':
|
||||||
|
b.WriteRune('n')
|
||||||
|
guion = false
|
||||||
|
case r == ' ' || r == '-' || r == '_' || r == '.':
|
||||||
|
if !guion && b.Len() > 0 {
|
||||||
|
b.WriteRune('-')
|
||||||
|
guion = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Trim(b.String(), "-")
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package almacen
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"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
|
||||||
|
if err := c.ShouldBindJSON(&data); 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 {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un almacén con ese código"})
|
||||||
|
return
|
||||||
|
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
almacen := models.Almacen{Codigo: data.Codigo, Ubicacion: data.Ubicacion}
|
||||||
|
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)
|
||||||
|
if err != nil {
|
||||||
|
c.Status(http.StatusCreated)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, creado)
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package almacen
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerAlmacenes(c *gin.Context) {
|
||||||
|
almacenes, err := r.ObtenerRepositorios(c).Almacen.Listar()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, almacenes)
|
||||||
|
}
|
||||||
@@ -3,29 +3,27 @@ package auth
|
|||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"repuestera_back/dto"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
"repuestera_back/repositories"
|
r "repuestera_back/repositorios"
|
||||||
"repuestera_back/utils"
|
"repuestera_back/utils"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
var usuarioRepo repositories.RepositorioUsuario
|
|
||||||
|
|
||||||
func InitUsuarioRepository(repo repositories.RepositorioUsuario) {
|
|
||||||
usuarioRepo = repo
|
|
||||||
}
|
|
||||||
|
|
||||||
func CambiarContraseña(c *gin.Context) {
|
func CambiarContraseña(c *gin.Context) {
|
||||||
var req dto.CambiarContraseñaRequest
|
var req struct {
|
||||||
|
UserID uint `json:"user_id"`
|
||||||
|
OldPassword string `json:"old_password"`
|
||||||
|
NewPassword string `json:"new_password" binding:"required"`
|
||||||
|
}
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(req.NewPassword) < 8 {
|
if len(req.NewPassword) < 8 {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "La nueva contraseña debe tener mas de 8 caracteres"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "La nueva contraseña debe tener al menos 8 caracteres"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,30 +31,47 @@ func CambiarContraseña(c *gin.Context) {
|
|||||||
authUserIDUint, _ := authUserID.(uint)
|
authUserIDUint, _ := authUserID.(uint)
|
||||||
|
|
||||||
targetID := authUserIDUint
|
targetID := authUserIDUint
|
||||||
if req.UserID != 0 {
|
esPropia := req.UserID == 0 || req.UserID == authUserIDUint
|
||||||
|
if !esPropia {
|
||||||
targetID = req.UserID
|
targetID = req.UserID
|
||||||
}
|
}
|
||||||
|
|
||||||
esAdmin := utils.UsuarioTienePermiso(c, 3)
|
repo := r.ObtenerRepositorios()
|
||||||
|
user, err := repo.Usuario.ObtenerPorID(targetID)
|
||||||
if targetID != authUserIDUint && !esAdmin {
|
|
||||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tienes permiso para cambiar la contraseña de otro usuario"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
user, err := usuarioRepo.ObtenerPorID(targetID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "usuario no encontrado"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !esAdmin {
|
// Cambiar la contraseña propia siempre exige la contraseña actual.
|
||||||
|
if esPropia {
|
||||||
if req.OldPassword == "" {
|
if req.OldPassword == "" {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Se requiere la contraseña actual"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Se requiere la contraseña actual"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
|
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "contraseña actual incorrecta"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Contraseña actual incorrecta"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
rolCaller := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
||||||
|
|
||||||
|
esAdmin := utils.UsuarioTienePermiso(c, models_seguridad.PermisoGestionUsuarios) || rolCaller.EsAdministrador()
|
||||||
|
if !esAdmin {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para cambiar la contraseña de otro usuario"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
membresia, err := repo.Empresa.Membresia(empresaID, targetID)
|
||||||
|
if err != nil || !membresia.Activo {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "El usuario no pertenece a esta empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Solo un owner (o plataforma) puede resetear a otro administrador.
|
||||||
|
if !esPropia && rolCaller != models_seguridad.RolOwner && membresia.Rol.EsAdministrador() {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "Solo el owner puede cambiar la contraseña de un administrador"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -67,7 +82,8 @@ func CambiarContraseña(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := usuarioRepo.ActualizarContraseña(user.ID, string(hashedPassword)); err != nil {
|
// Un reset administrativo obliga al usuario a definir su propia clave.
|
||||||
|
if err := repo.Usuario.ActualizarContraseña(user.ID, string(hashedPassword), !esPropia); err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al actualizar la contraseña"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al actualizar la contraseña"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,168 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
"repuestera_back/jwtutils"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ObtenerInvitacion es pública: permite mostrar los datos antes de aceptar.
|
||||||
|
func ObtenerInvitacion(c *gin.Context) {
|
||||||
|
token := strings.TrimSpace(c.Param("token"))
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
|
||||||
|
invitacion, err := repo.Empresa.ObtenerInvitacionPorToken(token)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Invitación no encontrada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_, errUsuario := repo.Usuario.ObtenerPorEmail(invitacion.Email)
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewInvitacionDirector().Info(invitacion, errUsuario == nil)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AceptarInvitacion suma al usuario a la empresa. Si la cuenta no existe, la
|
||||||
|
// crea con nombre y contraseña. Si ya existe, exige la contraseña actual (o
|
||||||
|
// una sesión válida del mismo usuario).
|
||||||
|
func AceptarInvitacion(c *gin.Context) {
|
||||||
|
token := strings.TrimSpace(c.Param("token"))
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
invitacion, err := repo.Empresa.ObtenerInvitacionPorToken(token)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Invitación no encontrada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if invitacion.UsadaEn != nil {
|
||||||
|
c.JSON(http.StatusGone, gin.H{"error": "La invitación ya fue utilizada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if time.Now().After(invitacion.ExpiraEn) {
|
||||||
|
c.JSON(http.StatusGone, gin.H{"error": "La invitación expiró"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !invitacion.Empresa.Activa {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "La empresa está deshabilitada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
email := strings.ToLower(strings.TrimSpace(invitacion.Email))
|
||||||
|
usuario, err := repo.Usuario.ObtenerPorEmail(email)
|
||||||
|
creado := false
|
||||||
|
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
if strings.TrimSpace(req.Name) == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "El nombre es obligatorio"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(req.Password) < 8 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "La contraseña debe tener al menos 8 caracteres"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contraseña"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
usuario = &models_seguridad.Usuario{
|
||||||
|
Email: email,
|
||||||
|
Name: strings.TrimSpace(req.Name),
|
||||||
|
Password: string(hash),
|
||||||
|
Activo: true,
|
||||||
|
}
|
||||||
|
if err := repo.Usuario.Crear(usuario); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
creado = true
|
||||||
|
} else if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
if !usuario.Activo {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "La cuenta está deshabilitada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !sesionCorrespondeAlUsuario(c, usuario.ID) {
|
||||||
|
if req.Password == "" {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Ingresá tu contraseña para aceptar la invitación"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := bcrypt.CompareHashAndPassword([]byte(usuario.Password), []byte(req.Password)); err != nil {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Contraseña incorrecta"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.AgregarMiembro(invitacion.EmpresaID, usuario.ID, invitacion.Rol, invitacion.GrupoID); err != nil {
|
||||||
|
if creado {
|
||||||
|
_ = repo.Usuario.Eliminar(usuario.ID)
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.MarcarInvitacionUsada(invitacion.ID); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := services.ConstruirSesion(usuario.ID, invitacion.EmpresaID)
|
||||||
|
if err != nil {
|
||||||
|
aceptada, buildErr := dto_directors.NewInvitacionDirector().Aceptada(usuario.ID, invitacion.EmpresaID)
|
||||||
|
if buildErr != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": buildErr.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, aceptada)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
status := http.StatusOK
|
||||||
|
if creado {
|
||||||
|
status = http.StatusCreated
|
||||||
|
}
|
||||||
|
c.JSON(status, respuesta)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sesionCorrespondeAlUsuario(c *gin.Context, usuarioID uint) bool {
|
||||||
|
header := c.GetHeader("Authorization")
|
||||||
|
partes := strings.Split(header, " ")
|
||||||
|
if len(partes) != 2 || !strings.EqualFold(partes[0], "Bearer") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
claims, err := jwtutils.ValidarTokenDeTipo(partes[1], jwtutils.TokenTypeAccess)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
sub, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimSubject)
|
||||||
|
return ok && sub == usuarioID
|
||||||
|
}
|
||||||
@@ -1,67 +1,105 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
"repuestera_back/dto"
|
r "repuestera_back/repositorios"
|
||||||
"repuestera_back/jwtutils"
|
"repuestera_back/services"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type loginRequest struct {
|
||||||
|
Email string `json:"email" binding:"required,email"`
|
||||||
|
Password string `json:"password" binding:"required"`
|
||||||
|
EmpresaID uint `json:"empresa_id"`
|
||||||
|
EmpresaSlug string `json:"empresa_slug"`
|
||||||
|
}
|
||||||
|
|
||||||
func Login(c *gin.Context) {
|
func Login(c *gin.Context) {
|
||||||
var req dto.LoginRequest
|
var req loginRequest
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
email := strings.ToLower(strings.TrimSpace(req.Email))
|
email := strings.ToLower(strings.TrimSpace(req.Email))
|
||||||
user, err := usuarioRepo.ObtenerPorEmail(email)
|
repo := r.ObtenerRepositorios()
|
||||||
|
user, err := repo.Usuario.ObtenerPorEmail(email)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Mail Invalido"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Mail o contraseña inválidos"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
|
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Contrasena invalida"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Mail o contraseña inválidos"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
accessToken, err := generarToken(*user, 15*time.Minute)
|
if !user.Activo {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "La cuenta está deshabilitada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresaID, err := seleccionarEmpresa(user.ID, req.EmpresaID, req.EmpresaSlug)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
refreshToken, err := generarToken(*user, 24*time.Hour)
|
respuesta, err := services.ConstruirSesion(user.ID, empresaID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate refresh token"})
|
status := http.StatusForbidden
|
||||||
|
if err == services.ErrEmpresaInactiva {
|
||||||
|
status = http.StatusForbidden
|
||||||
|
}
|
||||||
|
if err == services.ErrSinEmpresas || err == services.ErrSinAcceso {
|
||||||
|
status = http.StatusForbidden
|
||||||
|
}
|
||||||
|
if err != services.ErrSinAcceso && err != services.ErrSinEmpresas && err != services.ErrEmpresaInactiva && err != services.ErrUsuarioInactivo {
|
||||||
|
log.Printf("login: error construyendo sesión del usuario %d: %v", user.ID, err)
|
||||||
|
status = http.StatusInternalServerError
|
||||||
|
}
|
||||||
|
c.JSON(status, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, dto.TokenResponse{
|
c.JSON(http.StatusOK, respuesta)
|
||||||
AccessToken: accessToken,
|
|
||||||
RefreshToken: refreshToken,
|
|
||||||
TokenType: "Bearer",
|
|
||||||
ExpiresIn: 900,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func generarToken(user models_seguridad.Usuario, duration time.Duration) (string, error) {
|
func seleccionarEmpresa(usuarioID, empresaID uint, slug string) (uint, error) {
|
||||||
claims := jwt.MapClaims{
|
repo := r.ObtenerRepositorios()
|
||||||
"sub": user.ID,
|
|
||||||
"email": user.Email,
|
if empresaID != 0 {
|
||||||
"name": user.Name,
|
membresia, err := repo.Empresa.Membresia(empresaID, usuarioID)
|
||||||
"exp": time.Now().Add(duration).Unix(),
|
if err != nil || !membresia.Activo {
|
||||||
"iat": time.Now().Unix(),
|
return 0, services.ErrSinAcceso
|
||||||
|
}
|
||||||
|
return empresaID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
if slug != "" {
|
||||||
return token.SignedString(jwtutils.JWTSecret)
|
empresa, err := repo.Empresa.ObtenerPorSlug(strings.TrimSpace(slug))
|
||||||
|
if err != nil {
|
||||||
|
return 0, services.ErrSinAcceso
|
||||||
|
}
|
||||||
|
membresia, err := repo.Empresa.Membresia(empresa.ID, usuarioID)
|
||||||
|
if err != nil || !membresia.Activo {
|
||||||
|
return 0, services.ErrSinAcceso
|
||||||
|
}
|
||||||
|
return empresa.ID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
empresas, err := services.ListarEmpresasDeUsuario(usuarioID)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if len(empresas) > 0 {
|
||||||
|
return empresas[0].ID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0, services.ErrSinEmpresas
|
||||||
}
|
}
|
||||||
+78
-41
@@ -2,63 +2,100 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"repuestera_back/dto"
|
"repuestera_back/dto"
|
||||||
"repuestera_back/jwtutils"
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func Me(c *gin.Context) {
|
func Me(c *gin.Context) {
|
||||||
authHeader := c.GetHeader("Authorization")
|
userID, ok := c.Get("userID")
|
||||||
if authHeader == "" {
|
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "authorization header required"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
parts := strings.Split(authHeader, " ")
|
|
||||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header format"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
tokenString := parts[1]
|
|
||||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
|
||||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
||||||
return nil, jwt.ErrSignatureInvalid
|
|
||||||
}
|
|
||||||
return jwtutils.JWTSecret, nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil || !token.Valid {
|
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
claims, ok := token.Claims.(jwt.MapClaims)
|
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "usuario no autenticado"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
sub, ok := claims["sub"].(string)
|
id, ok := userID.(uint)
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "token inválido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
userID, _ := strconv.ParseUint(sub, 10, 32)
|
|
||||||
user, err := usuarioRepo.ObtenerPorID(uint(userID))
|
empresaID := utils.EmpresaID(c)
|
||||||
|
sesion, err := services.ConstruirSesion(id, empresaID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, dto.MeResponse{
|
respuesta, err := dto_directors.NewMeDirector().DesdeSesion(sesion)
|
||||||
ID: user.ID,
|
if err != nil {
|
||||||
Email: user.Email,
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
Name: user.Name,
|
return
|
||||||
})
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ObtenerMisEmpresas devuelve las empresas donde el usuario es miembro.
|
||||||
|
func ObtenerMisEmpresas(c *gin.Context) {
|
||||||
|
userID, _ := c.Get("userID")
|
||||||
|
id, _ := userID.(uint)
|
||||||
|
|
||||||
|
empresas, err := services.ListarEmpresasDeUsuario(id)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, dto.EmpresasResponse{Empresas: empresas})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CambiarEmpresa emite una sesión nueva para otra empresa del usuario.
|
||||||
|
func CambiarEmpresa(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
EmpresaID uint `json:"empresa_id" binding:"required"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
userID, _ := c.Get("userID")
|
||||||
|
id, _ := userID.(uint)
|
||||||
|
|
||||||
|
respuesta, err := services.ConstruirSesion(id, req.EmpresaID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ObtenerEmpresaActual devuelve los datos de la empresa activa.
|
||||||
|
func ObtenerEmpresaActual(c *gin.Context) {
|
||||||
|
userID, _ := c.Get("userID")
|
||||||
|
id, _ := userID.(uint)
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
|
||||||
|
empresa, rol, err := services.EmpresaDeUsuario(id, empresaID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
miembros, _ := r.ObtenerRepositorios().Empresa.ContarMiembros(empresa.ID)
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewEmpresaActualDirector().DesdeEmpresa(empresa, rol, miembros)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
}
|
}
|
||||||
@@ -1,69 +1,55 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
|
||||||
|
|
||||||
"repuestera_back/dto"
|
|
||||||
"repuestera_back/jwtutils"
|
"repuestera_back/jwtutils"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func Refresh(c *gin.Context) {
|
func Refresh(c *gin.Context) {
|
||||||
var req dto.RefreshRequest
|
var req struct {
|
||||||
|
RefreshToken string `json:"refresh_token" binding:"required"`
|
||||||
|
}
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
tokenString := req.RefreshToken
|
claims, err := jwtutils.ValidarTokenDeTipo(req.RefreshToken, jwtutils.TokenTypeRefresh)
|
||||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
if err != nil {
|
||||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "refresh token inválido"})
|
||||||
return nil, jwt.ErrSignatureInvalid
|
|
||||||
}
|
|
||||||
return jwtutils.JWTSecret, nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil || !token.Valid {
|
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid refresh token"})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
claims, ok := token.Claims.(jwt.MapClaims)
|
sub, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimSubject)
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "refresh token inválido"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
sub, ok := claims["sub"].(float64)
|
user, err := r.ObtenerRepositorios().Usuario.ObtenerPorID(sub)
|
||||||
if !ok {
|
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
user, err := usuarioRepo.ObtenerPorID(uint(sub))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "usuario no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !user.Activo {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": "la cuenta está deshabilitada"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
accessToken, err := generarToken(*user, 15*time.Minute)
|
empresaID, _ := jwtutils.ClaimUint(claims, jwtutils.ClaimEmpresaID)
|
||||||
|
|
||||||
|
respuesta, err := services.ConstruirSesion(user.ID, empresaID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
|
log.Printf("refresh: no se pudo renovar la sesión del usuario %d: %v", user.ID, err)
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
newRefreshToken, err := generarToken(*user, 24*time.Hour)
|
c.JSON(http.StatusOK, respuesta)
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate refresh token"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, dto.TokenResponse{
|
|
||||||
AccessToken: accessToken,
|
|
||||||
RefreshToken: newRefreshToken,
|
|
||||||
TokenType: "Bearer",
|
|
||||||
ExpiresIn: 900,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
@@ -4,47 +4,84 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"repuestera_back/dto"
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Register(c *gin.Context) {
|
func Register(c *gin.Context) {
|
||||||
var req dto.RegisterRequest
|
var req struct {
|
||||||
|
Email string `json:"email" binding:"required,email"`
|
||||||
|
Password string `json:"password" binding:"required,min=8"`
|
||||||
|
Name string `json:"name" binding:"required"`
|
||||||
|
EmpresaNombre string `json:"empresa_nombre"`
|
||||||
|
EmpresaSlug string `json:"empresa_slug"`
|
||||||
|
EmpresaCuit string `json:"empresa_cuit"`
|
||||||
|
}
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
email := strings.ToLower(strings.TrimSpace(req.Email))
|
email := strings.ToLower(strings.TrimSpace(req.Email))
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
|
||||||
if _, err := usuarioRepo.ObtenerPorEmail(email); err == nil {
|
if _, err := repo.Usuario.ObtenerPorEmail(email); err == nil {
|
||||||
c.JSON(http.StatusConflict, gin.H{"error": "El email ya esta registrado"})
|
c.JSON(http.StatusConflict, gin.H{"error": "El email ya está registrado"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contrasena"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contraseña"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
user := models_seguridad.Usuario{
|
user := models_seguridad.Usuario{
|
||||||
Email: email,
|
Email: email,
|
||||||
Password: string(hashedPassword),
|
Password: string(hashedPassword),
|
||||||
Name: req.Name,
|
Name: strings.TrimSpace(req.Name),
|
||||||
|
Activo: true,
|
||||||
}
|
}
|
||||||
|
if err := repo.Usuario.Crear(&user); err != nil {
|
||||||
if err := usuarioRepo.Crear(&user); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusCreated, dto.RegisterResponse{
|
nombreEmpresa := strings.TrimSpace(req.EmpresaNombre)
|
||||||
ID: user.ID,
|
if nombreEmpresa == "" {
|
||||||
Email: user.Email,
|
nombreEmpresa = "Empresa de " + user.Name
|
||||||
Name: user.Name,
|
}
|
||||||
})
|
empresa := models_seguridad.Empresa{
|
||||||
|
Nombre: nombreEmpresa,
|
||||||
|
Slug: req.EmpresaSlug,
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.EmpresaCuit) != "" {
|
||||||
|
cuit := strings.TrimSpace(req.EmpresaCuit)
|
||||||
|
empresa.Cuit = &cuit
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.Crear(&empresa, user.ID); err != nil {
|
||||||
|
// Si falla la creación de la empresa no dejamos una cuenta huérfana.
|
||||||
|
_ = repo.Usuario.Eliminar(user.ID)
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := services.ConstruirSesion(user.ID, empresa.ID)
|
||||||
|
if err != nil {
|
||||||
|
registro, buildErr := dto_directors.NewRegisterDirector().DesdeUsuario(&user)
|
||||||
|
if buildErr != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": buildErr.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusCreated, registro)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, respuesta)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package cliente
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repuestera_back/models"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
dto "repuestera_back/dto/Clientes"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ActualizarCliente(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
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios(c).Cliente
|
||||||
|
cliente, err := repo.ObtenerPorID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Cliente no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var data dto.CrearClienteDto
|
||||||
|
if err := c.ShouldBindJSON(&data); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if existing, _ := repo.BuscarPorCuit(data.Cuit); existing != nil && existing.ID != cliente.ID {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un cliente con ese CUIT"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
input := models.Cliente{
|
||||||
|
Nombre: data.Nombre,
|
||||||
|
Cuit: data.Cuit,
|
||||||
|
Email: data.Email,
|
||||||
|
}
|
||||||
|
uid := c.GetUint("userID")
|
||||||
|
if err := repo.Actualizar(cliente, input, uid); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
actualizado, err := repo.ObtenerPorID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusOK, cliente)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, actualizado)
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package cliente
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AltaCliente reactiva un cliente dado de baja lógicamente.
|
||||||
|
func AltaCliente(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
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios(c).Cliente
|
||||||
|
cliente, err := repo.ObtenerPorID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Cliente no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !cliente.DeletedAt.Valid {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "El cliente no está eliminado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
cliente.DeletedAt = gorm.DeletedAt{}
|
||||||
|
uid := c.GetUint("userID")
|
||||||
|
if err := repo.Alta(cliente, *cliente, uid); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Status(http.StatusOK)
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package cliente
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
dto "repuestera_back/dto/Clientes"
|
||||||
|
"repuestera_back/models"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CrearCliente(c *gin.Context) {
|
||||||
|
var data dto.CrearClienteDto
|
||||||
|
if err := c.ShouldBindJSON(&data); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios(c).Cliente
|
||||||
|
if _, err := repo.BuscarPorCuit(data.Cuit); err == nil {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un cliente con ese CUIT"})
|
||||||
|
return
|
||||||
|
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
cliente := models.Cliente{
|
||||||
|
Nombre: data.Nombre,
|
||||||
|
Cuit: data.Cuit,
|
||||||
|
Email: data.Email,
|
||||||
|
}
|
||||||
|
if err := repo.Crear(cliente, c.GetUint("userID")); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
creado, err := repo.BuscarPorCuit(data.Cuit)
|
||||||
|
if err != nil {
|
||||||
|
c.Status(http.StatusCreated)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, creado)
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package cliente
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func EliminarCliente(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")
|
||||||
|
if err := r.ObtenerRepositorios(c).Cliente.Baja(uint(id), uid); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Status(http.StatusOK)
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package cliente
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerClientes(c *gin.Context) {
|
||||||
|
clientes, err := r.ObtenerRepositorios(c).Cliente.Listar(c.Query("q"))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, clientes)
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package empresa
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ActualizarEmpresa(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Cuit string `json:"cuit"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
empresa, err := repo.Empresa.ObtenerPorID(utils.EmpresaID(c))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Empresa no encontrada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
input := models_seguridad.Empresa{Nombre: strings.TrimSpace(req.Nombre), Slug: strings.TrimSpace(req.Slug)}
|
||||||
|
if req.Cuit != "" {
|
||||||
|
cuit := strings.TrimSpace(req.Cuit)
|
||||||
|
input.Cuit = &cuit
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.Actualizar(empresa, input); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewEmpresaDirector().DesdeEmpresa(empresa)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package empresa
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repuestera_back/controllers/empresa/miembros"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AltaMiembro(c *gin.Context) {
|
||||||
|
usuarioID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
callerRol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
||||||
|
|
||||||
|
miembro, err := repo.Empresa.MiembrosIncluyendoEliminados(empresaID, uint(usuarioID))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "El usuario no pertenece a esta empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := miembros.PuedeModificarMiembro(c, callerRol, miembro.Rol); err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !miembro.DeletedAt.Valid {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "El miembro ya está activo"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.RestaurarMiembro(empresaID, uint(usuarioID)); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
miembro.DeletedAt = gorm.DeletedAt{}
|
||||||
|
miembro.Activo = true
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewMiembroDirector().DesdeMembresia(*miembro)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package invitaciones
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"repuestera_back/controllers/empresa/miembros"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CrearInvitacion(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
Email string `json:"email" binding:"required,email"`
|
||||||
|
Rol string `json:"rol"`
|
||||||
|
GrupoID uint `json:"grupo_id"`
|
||||||
|
ExpiraHoras int `json:"expira_horas"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
callerRol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
||||||
|
rol, err := miembros.RolSolicitado(c, callerRol, req.Rol)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.GrupoID > 0 {
|
||||||
|
grupo, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorID(req.GrupoID)
|
||||||
|
if err != nil || grupo.EmpresaID != empresaID {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Grupo inválido para la empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
email := strings.ToLower(strings.TrimSpace(req.Email))
|
||||||
|
|
||||||
|
usuario, err := repo.Usuario.ObtenerPorEmail(email)
|
||||||
|
if err == nil {
|
||||||
|
if _, err := repo.Empresa.Membresia(empresaID, usuario.ID); err == nil {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "El usuario ya pertenece a esta empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
expira := time.Now().Add(7 * 24 * time.Hour)
|
||||||
|
if req.ExpiraHoras > 0 {
|
||||||
|
if req.ExpiraHoras > 24*30 {
|
||||||
|
req.ExpiraHoras = 24 * 30
|
||||||
|
}
|
||||||
|
expira = time.Now().Add(time.Duration(req.ExpiraHoras) * time.Hour)
|
||||||
|
}
|
||||||
|
|
||||||
|
userID, _ := c.Get("userID")
|
||||||
|
creadorID, _ := userID.(uint)
|
||||||
|
|
||||||
|
invitacion := models_seguridad.InvitacionEmpresa{
|
||||||
|
EmpresaID: empresaID,
|
||||||
|
Email: email,
|
||||||
|
Rol: rol,
|
||||||
|
GrupoID: req.GrupoID,
|
||||||
|
ExpiraEn: expira,
|
||||||
|
CreadaPor: creadorID,
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := repo.Empresa.CrearInvitacion(&invitacion)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresa, err := repo.Empresa.ObtenerPorID(empresaID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
link := construirLinkInvitacion(token)
|
||||||
|
enviado := services.EnviarEmailInvitacion(email, empresa.Nombre, string(rol), link, creadorID)
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewInvitacionDirector().Creada(&invitacion, token, link, enviado)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package invitaciones
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func EliminarInvitacion(c *gin.Context) {
|
||||||
|
parsed, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.ObtenerRepositorios().Empresa.EliminarInvitacion(utils.EmpresaID(c), uint(parsed)); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Invitación cancelada"})
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package invitaciones
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func construirLinkInvitacion(token string) string {
|
||||||
|
base := strings.TrimRight(os.Getenv("APP_URL"), "/")
|
||||||
|
if base == "" {
|
||||||
|
base = "http://localhost:3000"
|
||||||
|
}
|
||||||
|
return base + "/invitaciones/" + token
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package invitaciones
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ListarInvitaciones(c *gin.Context) {
|
||||||
|
invitaciones, err := r.ObtenerRepositorios().Empresa.ListarInvitaciones(utils.EmpresaID(c))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewInvitacionDirector().ListarEnvelope(invitaciones)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package miembros
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ActualizarMiembro(c *gin.Context) {
|
||||||
|
usuarioID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Rol string `json:"rol"`
|
||||||
|
GrupoID uint `json:"grupo_id"`
|
||||||
|
Activo *bool `json:"activo"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
callerRol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
||||||
|
|
||||||
|
miembro, err := repo.Empresa.Membresia(empresaID, uint(usuarioID))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "El usuario no pertenece a esta empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := PuedeModificarMiembro(c, callerRol, miembro.Rol); err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
usuario, err := repo.Usuario.ObtenerPorID(uint(usuarioID))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.Name != "" {
|
||||||
|
usuario.Name = strings.TrimSpace(req.Name)
|
||||||
|
}
|
||||||
|
if req.Email != "" {
|
||||||
|
email := strings.ToLower(strings.TrimSpace(req.Email))
|
||||||
|
if email != usuario.Email {
|
||||||
|
if existente, err := repo.Usuario.ObtenerPorEmail(email); err == nil && existente.ID != usuario.ID {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "El email ya está registrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
usuario.Email = email
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := repo.Usuario.Guardar(usuario); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.Rol != "" {
|
||||||
|
nuevoRol, err := RolSolicitado(c, callerRol, req.Rol)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if miembro.Rol == models_seguridad.RolOwner && nuevoRol != models_seguridad.RolOwner {
|
||||||
|
if err := ValidarUltimoOwner(empresaID); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := repo.Empresa.ActualizarRolMiembro(empresaID, usuario.ID, nuevoRol); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
miembro.Rol = nuevoRol
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.Activo != nil {
|
||||||
|
if !*req.Activo && miembro.Rol == models_seguridad.RolOwner {
|
||||||
|
if err := ValidarUltimoOwner(empresaID); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if *req.Activo {
|
||||||
|
if err := repo.Empresa.AgregarMiembro(empresaID, usuario.ID, miembro.Rol, 0); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err := repo.Empresa.DesactivarMiembro(empresaID, usuario.ID); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
miembro.Usuario = *usuario
|
||||||
|
if req.Activo != nil {
|
||||||
|
miembro.Activo = *req.Activo
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewMiembroDirector().DesdeMembresia(*miembro)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
package miembros
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CrearMiembro(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name" binding:"required"`
|
||||||
|
Email string `json:"email" binding:"required,email"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
Rol string `json:"rol"`
|
||||||
|
GrupoID uint `json:"grupo_id"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
callerRol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
||||||
|
rol, err := RolSolicitado(c, callerRol, req.Rol)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.GrupoID > 0 {
|
||||||
|
grupo, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorID(req.GrupoID)
|
||||||
|
if err != nil || grupo.EmpresaID != empresaID {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Grupo inválido para la empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
email := strings.ToLower(strings.TrimSpace(req.Email))
|
||||||
|
|
||||||
|
usuario, err := repo.Usuario.ObtenerPorEmail(email)
|
||||||
|
passwordTemporal := ""
|
||||||
|
creado := false
|
||||||
|
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
password := req.Password
|
||||||
|
if password == "" {
|
||||||
|
password, err = services.GenerarPasswordTemporal()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "No se pudo generar la contraseña"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
passwordTemporal = password
|
||||||
|
}
|
||||||
|
if len(password) < 8 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "La contraseña debe tener al menos 8 caracteres"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contraseña"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
usuario = &models_seguridad.Usuario{
|
||||||
|
Email: email,
|
||||||
|
Name: strings.TrimSpace(req.Name),
|
||||||
|
Password: string(hash),
|
||||||
|
Activo: true,
|
||||||
|
DebeCambiarPassword: true,
|
||||||
|
}
|
||||||
|
if err := repo.Usuario.Crear(usuario); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
creado = true
|
||||||
|
} else if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
if _, err := repo.Empresa.Membresia(empresaID, usuario.ID); err == nil {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "El usuario ya pertenece a esta empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.AgregarMiembro(empresaID, usuario.ID, rol, req.GrupoID); err != nil {
|
||||||
|
if creado {
|
||||||
|
_ = repo.Usuario.Eliminar(usuario.ID)
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewMiembroDirector().Creado(models_seguridad.EmpresaUsuario{
|
||||||
|
Usuario: *usuario,
|
||||||
|
Rol: rol,
|
||||||
|
Activo: true,
|
||||||
|
}, passwordTemporal, !creado)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package miembros
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func EliminarMiembro(c *gin.Context) {
|
||||||
|
usuarioID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
callerRol := models_seguridad.RolEmpresa(utils.EmpresaRol(c))
|
||||||
|
|
||||||
|
miembro, err := repo.Empresa.Membresia(empresaID, uint(usuarioID))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "El usuario no pertenece a esta empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := PuedeModificarMiembro(c, callerRol, miembro.Rol); err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if miembro.Rol == models_seguridad.RolOwner {
|
||||||
|
if err := ValidarUltimoOwner(empresaID); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.EliminarMiembro(empresaID, uint(usuarioID)); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "El usuario fue removido de la empresa"})
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package miembros
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerMiembro(c *gin.Context) {
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
usuarioID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
miembro, err := r.ObtenerRepositorios().Empresa.Membresia(empresaID, uint(usuarioID))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "El usuario no pertenece a esta empresa"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewMiembroDirector().DesdeMembresia(*miembro)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package miembros
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerMiembros(c *gin.Context) {
|
||||||
|
empresaID := utils.EmpresaID(c)
|
||||||
|
pagina, _ := strconv.Atoi(c.DefaultQuery("p", "0"))
|
||||||
|
tamano, _ := strconv.Atoi(c.DefaultQuery("s", "10"))
|
||||||
|
|
||||||
|
miembros, total, err := r.ObtenerRepositorios().Empresa.ListarMiembros(empresaID, pagina, tamano)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewMiembroDirector().ListarPaginado(miembros, total)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package miembros
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RolSolicitado valida y normaliza el rol pedido para un miembro.
|
||||||
|
func RolSolicitado(c *gin.Context, callerRol models_seguridad.RolEmpresa, solicitado string) (models_seguridad.RolEmpresa, error) {
|
||||||
|
rol := models_seguridad.RolEmpresa(strings.ToUpper(strings.TrimSpace(solicitado)))
|
||||||
|
if rol == "" {
|
||||||
|
rol = models_seguridad.RolMiembro
|
||||||
|
}
|
||||||
|
if !rol.Valido() {
|
||||||
|
return "", errors.New("rol inválido")
|
||||||
|
}
|
||||||
|
|
||||||
|
if rol == models_seguridad.RolOwner && callerRol != models_seguridad.RolOwner {
|
||||||
|
return "", errors.New("solo el owner puede asignar el rol OWNER")
|
||||||
|
}
|
||||||
|
return rol, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PuedeModificarMiembro valida la jerarquía entre el que opera y el objetivo.
|
||||||
|
func PuedeModificarMiembro(c *gin.Context, callerRol, targetRol models_seguridad.RolEmpresa) error {
|
||||||
|
if callerRol == models_seguridad.RolOwner {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if targetRol == models_seguridad.RolOwner {
|
||||||
|
return errors.New("solo el owner puede administrar a otro owner")
|
||||||
|
}
|
||||||
|
if callerRol == models_seguridad.RolAdmin && targetRol == models_seguridad.RolAdmin {
|
||||||
|
return errors.New("un administrador no puede modificar a otro administrador")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidarUltimoOwner impide dejar a la empresa sin ningún owner activo.
|
||||||
|
func ValidarUltimoOwner(empresaID uint) error {
|
||||||
|
owners, err := r.ObtenerRepositorios().Empresa.ContarOwners(empresaID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if owners <= 1 {
|
||||||
|
return errors.New("la empresa debe conservar al menos un owner activo")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package factura
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerFactura(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
|
||||||
|
}
|
||||||
|
|
||||||
|
factura, err := r.ObtenerRepositorios(c).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
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewFacturaDirector().DesdeFactura(factura)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package factura
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerFacturas(c *gin.Context) {
|
||||||
|
filtros := r.FiltrosFactura{
|
||||||
|
Numero: c.Query("numero"),
|
||||||
|
Cliente: c.Query("cliente"),
|
||||||
|
}
|
||||||
|
|
||||||
|
if raw := c.Query("clienteId"); raw != "" {
|
||||||
|
id, err := strconv.ParseUint(raw, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "clienteId inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
filtros.ClienteID = uint(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
desde, err := fechaQuery(c.Query("desde"))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "desde inválido, se espera YYYY-MM-DD"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hasta, err := fechaQuery(c.Query("hasta"))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "hasta inválido, se espera YYYY-MM-DD"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
filtros.Desde = desde
|
||||||
|
filtros.Hasta = hasta
|
||||||
|
|
||||||
|
facturas, err := r.ObtenerRepositorios(c).Factura.Listar(filtros)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewFacturaDirector().Listar(facturas)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
|
|
||||||
|
func fechaQuery(valor string) (*time.Time, error) {
|
||||||
|
if valor == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
fecha, err := time.Parse("2006-01-02", valor)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &fecha, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package grupo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ActualizarGrupo(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
|
||||||
|
}
|
||||||
|
grupo, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var input models_seguridad.Grupo
|
||||||
|
if err := c.ShouldBindJSON(&input); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := r.ObtenerRepositorios(c).Grupo.Actualizar(grupo, input); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewGrupoDirector().DesdeGrupo(grupo)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package grupo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AgregarGrupoAUsuario(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
GrupoID uint `json:"grupo_id" binding:"required"`
|
||||||
|
UsuarioID uint `json:"usuario_id" binding:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.ObtenerRepositorios(c).Usuario.AgregarGrupoAUsuario(req.UsuarioID, req.GrupoID); err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "no se pudo añadir el grupo al usuario"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Status(http.StatusCreated)
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package grupo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AgregarPermisoAGrupo(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
PermisoID uint `json:"permission_id"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
grupoID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.ObtenerRepositorios(c).Grupo.AgregarPermiso(uint(grupoID), req.PermisoID); err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Permiso asignado al grupo"})
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package grupo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AgregarSubGrupo(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
ChildGroupID uint `json:"child_group_id"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
padreID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.ObtenerRepositorios(c).Grupo.AgregarSubGrupo(uint(padreID), req.ChildGroupID); err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Subgrupo agregado"})
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package grupo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CrearGrupo(c *gin.Context) {
|
||||||
|
var grupo models_seguridad.Grupo
|
||||||
|
if err := c.ShouldBindJSON(&grupo); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := r.ObtenerRepositorios(c).Grupo.Crear(&grupo); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewGrupoDirector().DesdeGrupo(&grupo)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package grupo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func EliminarGrupo(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 err := r.ObtenerRepositorios(c).Grupo.Eliminar(uint(id)); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Grupo eliminado"})
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package grupo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerGrupo(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
|
||||||
|
}
|
||||||
|
grupo, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorIDConRelaciones(uint(id), true)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewGrupoSimpleDirector().DesdeGrupo(grupo)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package grupo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerGrupos(c *gin.Context) {
|
||||||
|
grupos, err := r.ObtenerRepositorios(c).Grupo.ObtenerTodosConRelaciones()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewGrupoDirector().Listar(grupos)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package grupo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerGruposDeUsuario(c *gin.Context) {
|
||||||
|
usuarioIDStr := c.Param("id")
|
||||||
|
|
||||||
|
usuarioID, err := strconv.ParseUint(usuarioIDStr, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "id invalido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
grupos, err := r.ObtenerRepositorios(c).Usuario.ObtenerGruposPorUsuarioID(uint(usuarioID))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "no se ha podido obtener los grupos del usuario"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewGrupoDirector().Listar(grupos)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package grupo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerGruposYPermisosPorEmail(c *gin.Context) {
|
||||||
|
var request struct {
|
||||||
|
Email string `json:"email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.ShouldBindJSON(&request); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Formato de solicitud invalido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
jwtEmail := c.GetString("email")
|
||||||
|
if jwtEmail == "" {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Email no encontrado en el token"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if jwtEmail != request.Email {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado: El email no coincide con el token JWT"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
usuario, err := r.ObtenerRepositorios(c).Usuario.ObtenerPorEmailConGrupos(request.Email)
|
||||||
|
if err != nil {
|
||||||
|
if err == gorm.ErrRecordNotFound {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
grupos := make([]*models_seguridad.Grupo, 0, len(usuario.Grupos))
|
||||||
|
for i := range usuario.Grupos {
|
||||||
|
grupoCompleto, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorIDConRelaciones(usuario.Grupos[i].ID, true)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
grupos = append(grupos, grupoCompleto)
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewGrupoSimpleDirector().Listar(grupos)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
envelope, err := dto_directors.NewGrupoDirector().GruposYPermisos(usuario.Email, respuesta)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, envelope)
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package grupo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func QuitarGrupoAUsuario(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
GrupoID uint `json:"grupo_id" binding:"required"`
|
||||||
|
UsuarioID uint `json:"usuario_id" binding:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.ObtenerRepositorios(c).Usuario.QuitarGrupoDeUsuario(req.UsuarioID, req.GrupoID); err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "no se pudo quitar el grupo al usuario"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Status(http.StatusOK)
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package grupo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func QuitarPermisoAGrupo(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
PermisoID uint `json:"permission_id"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
grupoID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.ObtenerRepositorios(c).Grupo.QuitarPermiso(uint(grupoID), req.PermisoID); err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Permiso quitado del grupo"})
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package grupo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func QuitarSubGrupo(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
ChildGroupID uint `json:"child_group_id"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
padreID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.ObtenerRepositorios(c).Grupo.QuitarSubGrupo(uint(padreID), req.ChildGroupID); err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Subgrupo quitado"})
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package logs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
dto "repuestera_back/dto/Logs"
|
||||||
|
"repuestera_back/models/logs"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func BusquedaLogs(c *gin.Context) {
|
||||||
|
pag, err := strconv.ParseUint(c.Param("p"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var filtros dto.BusquedaLogsDto
|
||||||
|
if err := c.ShouldBindJSON(&filtros); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var logs []logs.Log
|
||||||
|
|
||||||
|
if logs, err = r.ObtenerRepositorios(c).Logs.ObtenerConFiltros(int(pag), filtros); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
logsdto, err := dto_directors.NewLogTablaDirector().Listar(logs)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
cantpags, err := r.ObtenerRepositorios(c).Logs.CantPaginasConFiltros(filtros)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"logs": logsdto,
|
||||||
|
"maxlenght": cantpags,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package logs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerLog(c *gin.Context) {
|
||||||
|
pag, err := strconv.ParseUint(c.Param("p"), 10, 64)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
logs, err := r.ObtenerRepositorios(c).Logs.ObtenerPorPaginas(uint(pag))
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewLogResponseDirector().Listar(logs)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package logs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerLogs(c *gin.Context) {
|
||||||
|
pag, err := strconv.ParseUint(c.Param("p"), 10, 64)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
repo := r.ObtenerRepositorios(c).Logs
|
||||||
|
|
||||||
|
logs, err := repo.ObtenerPorPaginas(uint(pag))
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
cantpags, err := repo.CantPaginas()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
logsdto, err := dto_directors.NewLogTablaDirector().Listar(logs)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"logs": logsdto,
|
||||||
|
"maxlenght": cantpags,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package marca
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repuestera_back/models"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ActualizarMarca actualiza una marca existente.
|
||||||
|
func ActualizarMarca(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 marca actual
|
||||||
|
marca, err := r.ObtenerRepositorios(c).Marca.ObtenerPorID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Marca no encontrada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var input models.Marca
|
||||||
|
if err := c.ShouldBindJSON(&input); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if input.Nombre == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "El nombre no puede estar vacío"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verificar que no exista otra marca con el mismo nombre
|
||||||
|
if existing, _ := r.ObtenerRepositorios(c).Marca.ObtenerPorNombre(input.Nombre); existing != nil && existing.ID != marca.ID {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ya existe una marca con ese nombre"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uid := c.GetUint("userID")
|
||||||
|
if err := r.ObtenerRepositorios(c).Marca.Actualizar(marca, input, uid); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, marca)
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package marca
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AltaMarca(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")
|
||||||
|
marca, err := r.ObtenerRepositorios(c).Marca.ObtenerPorID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Marca no encontrada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !marca.DeletedAt.Valid {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Marca no está eliminada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
marca.DeletedAt = gorm.DeletedAt{}
|
||||||
|
if err := r.ObtenerRepositorios(c).Marca.Alta(marca, *marca, uid); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Status(http.StatusOK)
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package marca
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"repuestera_back/models"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CrearMarca(c *gin.Context) {
|
||||||
|
var marca models.Marca
|
||||||
|
if err := c.ShouldBindJSON(&marca); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := r.ObtenerRepositorios(c).Marca.ObtenerPorNombre(marca.Nombre)
|
||||||
|
if err == nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ya existe una marca con ese nombre"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uid := c.GetUint("userID")
|
||||||
|
|
||||||
|
err = r.ObtenerRepositorios(c).Marca.Crear(marca, uid)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Status(http.StatusCreated)
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package marca
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func EliminarMarca(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).Marca.Baja(uint(id), uid)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Status(http.StatusOK)
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package marca
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerMarcas(c *gin.Context) {
|
||||||
|
marcas, err := r.ObtenerRepositorios(c).Marca.ObtenerTodos()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, marcas)
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package permiso
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ActualizarPermiso(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
|
||||||
|
}
|
||||||
|
permiso, err := r.ObtenerRepositorios(c).Permiso.ObtenerPorID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Permiso no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var input models_seguridad.Permiso
|
||||||
|
if err := c.ShouldBindJSON(&input); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := r.ObtenerRepositorios(c).Permiso.Actualizar(permiso, input); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewPermisoDirector().DesdePermiso(permiso)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package permiso
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CrearPermiso(c *gin.Context) {
|
||||||
|
var permiso models_seguridad.Permiso
|
||||||
|
if err := c.ShouldBindJSON(&permiso); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := r.ObtenerRepositorios(c).Permiso.Crear(&permiso); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewPermisoDirector().DesdePermiso(&permiso)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package permiso
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func EliminarPermiso(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 err := r.ObtenerRepositorios(c).Permiso.Eliminar(uint(id)); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Permiso eliminado"})
|
||||||
|
}
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
package permiso
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
|
||||||
"repuestera_back/repositories"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
grupoRepo repositories.RepositorioGrupo
|
|
||||||
permisoRepo repositories.RepositorioPermiso
|
|
||||||
usuarioRepo repositories.RepositorioUsuario
|
|
||||||
)
|
|
||||||
|
|
||||||
func InitRepositories(gr repositories.RepositorioGrupo, pr repositories.RepositorioPermiso, ur repositories.RepositorioUsuario) {
|
|
||||||
grupoRepo = gr
|
|
||||||
permisoRepo = pr
|
|
||||||
usuarioRepo = ur
|
|
||||||
}
|
|
||||||
|
|
||||||
func ObtenerGrupos(c *gin.Context) {
|
|
||||||
grupos, err := grupoRepo.ObtenerTodosConRelaciones()
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, grupos)
|
|
||||||
}
|
|
||||||
|
|
||||||
func ObtenerGrupo(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
|
|
||||||
}
|
|
||||||
grupo, err := grupoRepo.ObtenerPorIDConRelaciones(uint(id))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo no encontrado"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, grupo)
|
|
||||||
}
|
|
||||||
|
|
||||||
func CrearGrupo(c *gin.Context) {
|
|
||||||
var grupo models_seguridad.Grupo
|
|
||||||
if err := c.ShouldBindJSON(&grupo); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := grupoRepo.Crear(&grupo); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusCreated, grupo)
|
|
||||||
}
|
|
||||||
|
|
||||||
func ActualizarGrupo(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
|
|
||||||
}
|
|
||||||
grupo, err := grupoRepo.ObtenerPorID(uint(id))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo no encontrado"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var input models_seguridad.Grupo
|
|
||||||
if err := c.ShouldBindJSON(&input); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
grupoRepo.Actualizar(grupo, input)
|
|
||||||
c.JSON(http.StatusOK, grupo)
|
|
||||||
}
|
|
||||||
|
|
||||||
func EliminarGrupo(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 err := grupoRepo.Eliminar(uint(id)); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "Grupo eliminado"})
|
|
||||||
}
|
|
||||||
@@ -1,142 +0,0 @@
|
|||||||
package permiso
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"repuestera_back/dto"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func AgregarPermisoAGrupo(c *gin.Context) {
|
|
||||||
var req dto.GrupoPermisoRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
grupoID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := grupoRepo.AgregarPermiso(uint(grupoID), req.PermisoID); err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "Permiso asignado al grupo"})
|
|
||||||
}
|
|
||||||
|
|
||||||
func QuitarPermisoAGrupo(c *gin.Context) {
|
|
||||||
var req dto.GrupoPermisoRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
grupoID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := grupoRepo.QuitarPermiso(uint(grupoID), req.PermisoID); err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "Permiso quitado del grupo"})
|
|
||||||
}
|
|
||||||
|
|
||||||
func AgregarSubGrupo(c *gin.Context) {
|
|
||||||
var req dto.GrupoHijoRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
padreID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := grupoRepo.AgregarSubGrupo(uint(padreID), req.ChildGroupID); err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "Subgrupo agregado"})
|
|
||||||
}
|
|
||||||
|
|
||||||
func QuitarSubGrupo(c *gin.Context) {
|
|
||||||
var req dto.GrupoHijoRequest
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
padreID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := grupoRepo.QuitarSubGrupo(uint(padreID), req.ChildGroupID); err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "Subgrupo quitado"})
|
|
||||||
}
|
|
||||||
|
|
||||||
func AgregarGrupoAUsuario(c *gin.Context) {
|
|
||||||
var req dto.GrupoUsuarioRelacion
|
|
||||||
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := usuarioRepo.AgregarGrupoAUsuario(req.UsuarioID, req.GrupoID); err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "no se pudo añadir el grupo al usuario"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.Status(http.StatusCreated)
|
|
||||||
}
|
|
||||||
|
|
||||||
func QuitarGrupoAUsuario(c *gin.Context) {
|
|
||||||
var req dto.GrupoUsuarioRelacion
|
|
||||||
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := usuarioRepo.QuitarGrupoDeUsuario(req.UsuarioID, req.GrupoID); err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "no se pudo quitar el grupo al usuario"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.Status(http.StatusOK)
|
|
||||||
}
|
|
||||||
|
|
||||||
func ObtenerGruposDeUsuario(c *gin.Context) {
|
|
||||||
usuarioIDStr := c.Param("id")
|
|
||||||
|
|
||||||
usuarioID, err := strconv.ParseUint(usuarioIDStr, 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(400, gin.H{"error": "id invalido"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
grupos, err := usuarioRepo.ObtenerGruposPorUsuarioID(uint(usuarioID))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "no se ha podido obtener los grupos del usuario"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, grupos)
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package permiso
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerPermisos(c *gin.Context) {
|
||||||
|
permisos, err := r.ObtenerRepositorios(c).Permiso.ObtenerTodos()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewPermisoDirector().Listar(permisos)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package permiso
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerPermisosUsuario(c *gin.Context) {
|
||||||
|
userID, err := strconv.ParseUint(c.Param("userId"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
usuario, err := r.ObtenerRepositorios(c).Usuario.PrecargarGruposPermisosPorID(uint(userID))
|
||||||
|
if err != nil {
|
||||||
|
if err == gorm.ErrRecordNotFound {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewPermisosUsuarioDirector().DesdeGrupos(usuario.Grupos)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
package permiso
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ObtenerPermisos(c *gin.Context) {
|
|
||||||
permisos, err := permisoRepo.ObtenerTodos()
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, permisos)
|
|
||||||
}
|
|
||||||
|
|
||||||
func CrearPermiso(c *gin.Context) {
|
|
||||||
var permiso models_seguridad.Permiso
|
|
||||||
if err := c.ShouldBindJSON(&permiso); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := permisoRepo.Crear(&permiso); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusCreated, permiso)
|
|
||||||
}
|
|
||||||
|
|
||||||
func ActualizarPermiso(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
|
|
||||||
}
|
|
||||||
permiso, err := permisoRepo.ObtenerPorID(uint(id))
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Permiso no encontrado"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var input models_seguridad.Permiso
|
|
||||||
if err := c.ShouldBindJSON(&input); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
permisoRepo.Actualizar(permiso, input)
|
|
||||||
c.JSON(http.StatusOK, permiso)
|
|
||||||
}
|
|
||||||
|
|
||||||
func EliminarPermiso(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 err := permisoRepo.Eliminar(uint(id)); err != nil {
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "Permiso eliminado"})
|
|
||||||
}
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
package permiso
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"repuestera_back/dto"
|
|
||||||
models_seguridad "repuestera_back/models/seguridad"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ObtenerPermisosUsuario(c *gin.Context) {
|
|
||||||
userID, err := strconv.ParseUint(c.Param("userId"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
usuario, err := usuarioRepo.PrecargarGruposPermisosPorID(uint(userID))
|
|
||||||
if err != nil {
|
|
||||||
if err == gorm.ErrRecordNotFound {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
permisoMap := make(map[string]bool)
|
|
||||||
var permisos []string
|
|
||||||
|
|
||||||
for _, grupo := range usuario.Grupos {
|
|
||||||
for _, permiso := range grupo.Permisos {
|
|
||||||
if !permisoMap[permiso.Nombre] {
|
|
||||||
permisoMap[permiso.Nombre] = true
|
|
||||||
permisos = append(permisos, permiso.Nombre)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, grupoHijo := range grupo.Grupos {
|
|
||||||
for _, permiso := range grupoHijo.Permisos {
|
|
||||||
if !permisoMap[permiso.Nombre] {
|
|
||||||
permisoMap[permiso.Nombre] = true
|
|
||||||
permisos = append(permisos, permiso.Nombre)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, dto.PermisosUsuarioResponse{Permisos: permisos})
|
|
||||||
}
|
|
||||||
|
|
||||||
func ObtenerGruposYPermisosPorEmail(c *gin.Context) {
|
|
||||||
var request struct {
|
|
||||||
Email string `json:"email"`
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := c.ShouldBindJSON(&request); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Formato de solicitud invalido"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
jwtEmail := c.GetString("email")
|
|
||||||
if jwtEmail == "" {
|
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Email no encontrado en el token"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if jwtEmail != request.Email {
|
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado: El email no coincide con el token JWT"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
usuario, err := usuarioRepo.ObtenerPorEmailConGrupos(request.Email)
|
|
||||||
if err != nil {
|
|
||||||
if err == gorm.ErrRecordNotFound {
|
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
grupoPermisoMap := make(map[uint]*dto.GrupoInfo)
|
|
||||||
permisoSet := make(map[string]bool)
|
|
||||||
|
|
||||||
for _, grupo := range usuario.Grupos {
|
|
||||||
if _, ok := grupoPermisoMap[grupo.ID]; !ok {
|
|
||||||
grupoPermisoMap[grupo.ID] = &dto.GrupoInfo{
|
|
||||||
ID: grupo.ID,
|
|
||||||
Name: grupo.Nombre,
|
|
||||||
Permissions: []models_seguridad.Permiso{},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, permiso := range grupo.Permisos {
|
|
||||||
if !permisoSet[permiso.Nombre] {
|
|
||||||
permisoSet[permiso.Nombre] = true
|
|
||||||
grupoPermisoMap[grupo.ID].Permissions = append(grupoPermisoMap[grupo.ID].Permissions, permiso)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, subGrupo := range grupo.Grupos {
|
|
||||||
if _, ok := grupoPermisoMap[subGrupo.ID]; !ok {
|
|
||||||
grupoPermisoMap[subGrupo.ID] = &dto.GrupoInfo{
|
|
||||||
ID: subGrupo.ID,
|
|
||||||
Name: subGrupo.Nombre,
|
|
||||||
Permissions: []models_seguridad.Permiso{},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, permiso := range subGrupo.Permisos {
|
|
||||||
if !permisoSet[permiso.Nombre] {
|
|
||||||
permisoSet[permiso.Nombre] = true
|
|
||||||
grupoPermisoMap[subGrupo.ID].Permissions = append(grupoPermisoMap[subGrupo.ID].Permissions, permiso)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
grupos := make([]dto.GrupoInfo, 0, len(grupoPermisoMap))
|
|
||||||
for _, grupo := range grupoPermisoMap {
|
|
||||||
grupos = append(grupos, *grupo)
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, dto.GruposYPermisosResponse{
|
|
||||||
Email: usuario.Email,
|
|
||||||
Groups: grupos,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package plataforma
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ActualizarEmpresa(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
|
||||||
|
}
|
||||||
|
|
||||||
|
var req struct {
|
||||||
|
Nombre string `json:"nombre"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Cuit *string `json:"cuit"`
|
||||||
|
Activa *bool `json:"activa"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
empresa, err := repo.Empresa.ObtenerPorID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Empresa no encontrada"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(req.Nombre) != "" {
|
||||||
|
empresa.Nombre = strings.TrimSpace(req.Nombre)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Slug) != "" {
|
||||||
|
empresa.Slug = strings.TrimSpace(req.Slug)
|
||||||
|
}
|
||||||
|
if req.Cuit != nil {
|
||||||
|
cuit := strings.TrimSpace(*req.Cuit)
|
||||||
|
if cuit == "" {
|
||||||
|
empresa.Cuit = nil
|
||||||
|
} else {
|
||||||
|
empresa.Cuit = &cuit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if req.Activa != nil {
|
||||||
|
empresa.Activa = *req.Activa
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.Guardar(empresa); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
miembros, _ := repo.Empresa.ContarMiembros(empresa.ID)
|
||||||
|
owners, _ := repo.Empresa.ContarOwners(empresa.ID)
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewEmpresaAdminDirector().DesdeEmpresa(empresa, miembros, owners)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
package plataforma
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
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"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
email := strings.ToLower(strings.TrimSpace(req.OwnerEmail))
|
||||||
|
owner, err := repo.Usuario.ObtenerPorEmail(email)
|
||||||
|
passwordTemporal := ""
|
||||||
|
creado := false
|
||||||
|
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
password := req.OwnerPassword
|
||||||
|
if password == "" {
|
||||||
|
password, err = services.GenerarPasswordTemporal()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "No se pudo generar la contraseña"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
passwordTemporal = password
|
||||||
|
}
|
||||||
|
if len(password) < 8 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "La contraseña del owner debe tener al menos 8 caracteres"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al procesar la contraseña"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
nombre := strings.TrimSpace(req.OwnerName)
|
||||||
|
if nombre == "" {
|
||||||
|
nombre = strings.Split(email, "@")[0]
|
||||||
|
}
|
||||||
|
owner = &models_seguridad.Usuario{
|
||||||
|
Email: email,
|
||||||
|
Name: nombre,
|
||||||
|
Password: string(hash),
|
||||||
|
Activo: true,
|
||||||
|
DebeCambiarPassword: true,
|
||||||
|
}
|
||||||
|
if err := repo.Usuario.Crear(owner); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
creado = true
|
||||||
|
} else if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
empresa := models_seguridad.Empresa{
|
||||||
|
Nombre: strings.TrimSpace(req.Nombre),
|
||||||
|
Slug: strings.TrimSpace(req.Slug),
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(req.Cuit) != "" {
|
||||||
|
cuit := strings.TrimSpace(req.Cuit)
|
||||||
|
empresa.Cuit = &cuit
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.Empresa.Crear(&empresa, owner.ID); err != nil {
|
||||||
|
if creado {
|
||||||
|
_ = repo.Usuario.Eliminar(owner.ID)
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
miembros, _ := repo.Empresa.ContarMiembros(empresa.ID)
|
||||||
|
owners, _ := repo.Empresa.ContarOwners(empresa.ID)
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewEmpresaAdminDirector().Creada(
|
||||||
|
&empresa,
|
||||||
|
owner,
|
||||||
|
models_seguridad.RolOwner,
|
||||||
|
miembros,
|
||||||
|
owners,
|
||||||
|
passwordTemporal,
|
||||||
|
!creado,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package plataforma
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func DesactivarEmpresa(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
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.ObtenerRepositorios().Empresa.Desactivar(uint(id)); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Empresa desactivada"})
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package plataforma
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ListarEmpresas(c *gin.Context) {
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
empresas, err := repo.Empresa.ListarTodas()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
contadores := make(map[uint]dto_directors.ContadoresEmpresa, len(empresas))
|
||||||
|
for _, empresa := range empresas {
|
||||||
|
miembros, _ := repo.Empresa.ContarMiembros(empresa.ID)
|
||||||
|
owners, _ := repo.Empresa.ContarOwners(empresa.ID)
|
||||||
|
contadores[empresa.ID] = dto_directors.ContadoresEmpresa{Miembros: miembros, Owners: owners}
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewEmpresaAdminDirector().Listar(empresas, contadores)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package plataforma
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ListarUsuarios(c *gin.Context) {
|
||||||
|
pagina, _ := strconv.Atoi(c.DefaultQuery("p", "0"))
|
||||||
|
tamano, _ := strconv.Atoi(c.DefaultQuery("s", "20"))
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios()
|
||||||
|
usuarios, total, err := repo.Usuario.ListarGlobales(pagina, tamano)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
cantidadEmpresas := make(map[uint]int, len(usuarios))
|
||||||
|
for _, usuario := range usuarios {
|
||||||
|
empresas, _ := repo.Empresa.ListarDeUsuario(usuario.ID)
|
||||||
|
cantidadEmpresas[usuario.ID] = len(empresas)
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewUsuarioAdminDirector().Listar(usuarios, cantidadEmpresas, total)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package proveedor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"repuestera_back/models"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ActualizarProveedor(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
|
||||||
|
}
|
||||||
|
|
||||||
|
proveedor, err := r.ObtenerRepositorios(c).Proveedor.ObtenerPorID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Proveedor no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var input models.Proveedor
|
||||||
|
if err := c.ShouldBindJSON(&input); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if input.Nombre == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "El nombre no puede estar vacío"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if existing, _ := r.ObtenerRepositorios(c).Proveedor.BuscarPorNombre(input.Nombre); existing != nil && existing.ID != proveedor.ID {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un proveedor con ese nombre"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uid := c.GetUint("userID")
|
||||||
|
if err := r.ObtenerRepositorios(c).Proveedor.Actualizar(proveedor, input, uid); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, proveedor)
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package proveedor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AltaProveedor reactiva un proveedor dado de baja lógicamente.
|
||||||
|
func AltaProveedor(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
|
||||||
|
}
|
||||||
|
|
||||||
|
proveedor, err := r.ObtenerRepositorios(c).Proveedor.ObtenerPorID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Proveedor no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !proveedor.DeletedAt.Valid {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "El proveedor no está eliminado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
proveedor.DeletedAt = gorm.DeletedAt{}
|
||||||
|
uid := c.GetUint("userID")
|
||||||
|
if err := r.ObtenerRepositorios(c).Proveedor.Alta(proveedor, *proveedor, uid); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Status(http.StatusOK)
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package proveedor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
dto "repuestera_back/dto/Proveedores"
|
||||||
|
"repuestera_back/models"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CrearProveedor(c *gin.Context) {
|
||||||
|
var data dto.CrearProveedorDto
|
||||||
|
if err := c.ShouldBindJSON(&data); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios(c).Proveedor
|
||||||
|
if _, err := repo.BuscarPorNombre(data.Nombre); err == nil {
|
||||||
|
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un proveedor con ese nombre"})
|
||||||
|
return
|
||||||
|
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
proveedor := models.Proveedor{
|
||||||
|
Nombre: data.Nombre,
|
||||||
|
Cuit: data.Cuit,
|
||||||
|
Email: data.Email,
|
||||||
|
Telefono: data.Telefono,
|
||||||
|
}
|
||||||
|
if err := repo.Crear(proveedor, c.GetUint("userID")); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
creado, err := repo.BuscarPorNombre(data.Nombre)
|
||||||
|
if err != nil {
|
||||||
|
c.Status(http.StatusCreated)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, creado)
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package proveedor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func EliminarProveedor(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).Proveedor.Baja(uint(id), uid)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Status(http.StatusOK)
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package proveedor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerProveedores(c *gin.Context) {
|
||||||
|
proveedores, err := r.ObtenerRepositorios(c).Proveedor.Listar(c.Query("q"))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, proveedores)
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package repuestos
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
dto "repuestera_back/dto/Repuestos"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ActualizarRepuesto(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
|
||||||
|
}
|
||||||
|
|
||||||
|
var data dto.ActualizarRepuestoDto
|
||||||
|
if err := c.ShouldBindJSON(&data); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
data.ID = &id
|
||||||
|
|
||||||
|
marca, err := r.ObtenerRepositorios(c).Marca.ObtenerPorID(data.Marca)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repuesto, err := dto_directors.NewRepuestoDirector().Actualizar(data, marca.ID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
entity, err := r.ObtenerRepositorios(c).Repuesto.ObtenerPorID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uid, _ := c.Get("userID")
|
||||||
|
if err := r.ObtenerRepositorios(c).Repuesto.Actualizar(entity, repuesto, uid.(uint)); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, repuesto)
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package repuestos
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AltaRepuestos(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.MustGet("userID").(uint)
|
||||||
|
if _, err := r.ObtenerRepositorios(c).Repuesto.AltaRepuesto(uint(id), uint(uid)); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Status(http.StatusOK)
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package repuestos
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
dto "repuestera_back/dto/Repuestos"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CrearRepuesto(c *gin.Context) {
|
||||||
|
var data dto.CrearRepuestoDto
|
||||||
|
if err := c.ShouldBindJSON(&data); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
marca, err := r.ObtenerRepositorios(c).Marca.ObtenerPorID(data.Marca)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.ObtenerRepositorios(c).Marca.CrearFaltante(*marca); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repuesto, err := dto_directors.NewRepuestoDirector().Crear(data, marca.ID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uid, _ := c.Get("userID")
|
||||||
|
if err := r.ObtenerRepositorios(c).Repuesto.Crear(repuesto, uid.(uint)); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, repuesto)
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package repuestos
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func EliminarRepuesto(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.Get("userID")
|
||||||
|
if err := r.ObtenerRepositorios(c).Repuesto.Baja(uint(id), uid.(uint)); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Status(http.StatusOK)
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package repuestos
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerRepuesto(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
|
||||||
|
}
|
||||||
|
|
||||||
|
repuesto, err := r.ObtenerRepositorios(c).Repuesto.ObtenerPorID(uint(id))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, repuesto)
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package repuestos
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerRepuestos(c *gin.Context) {
|
||||||
|
repuestos, err := r.ObtenerRepositorios(c).Repuesto.ObtenerTodosConMarca()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, repuestos)
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
dto "repuestera_back/dto/Stock"
|
||||||
|
models_logs "repuestera_back/models/logs"
|
||||||
|
"repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ActualizarObservacion(c *gin.Context) {
|
||||||
|
id, err := parseUintParam(c, "id")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var data dto.ObservacionDto
|
||||||
|
if err := c.ShouldBindJSON(&data); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
texto := strings.TrimSpace(data.Observacion)
|
||||||
|
if err := validarObservacion(texto); err != nil {
|
||||||
|
responderError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repos := repositorios.ObtenerRepositorios(c)
|
||||||
|
resultado, err := repos.Stock.ActualizarObservacion(id, texto)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
responderError(c, ErrStockNoEncontrado)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
responderError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
registrarLog(repos, utils.EmpresaID(c), c.GetUint("userID"), "COMENTAR_STOCK", []models_logs.LogDetalle{
|
||||||
|
{NombreTabla: "stock", Columna: "stockId", ValorNuevo: fmt.Sprintf("%d", id)},
|
||||||
|
{NombreTabla: "stock", Columna: "observacion", ValorNuevo: texto},
|
||||||
|
})
|
||||||
|
c.JSON(http.StatusOK, resultado)
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
dto "repuestera_back/dto/Stock"
|
||||||
|
"repuestera_back/models"
|
||||||
|
models_logs "repuestera_back/models/logs"
|
||||||
|
"repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AjustarStock(c *gin.Context) {
|
||||||
|
var data dto.AjusteDto
|
||||||
|
if err := c.ShouldBindJSON(&data); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado, err := ajustarStock(
|
||||||
|
repositorios.BaseDeDatos(),
|
||||||
|
repositorios.ObtenerRepositorios(c),
|
||||||
|
utils.EmpresaID(c),
|
||||||
|
c.GetUint("userID"),
|
||||||
|
data,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
responderError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, resultado)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ajustarStock deja el stock en la cantidad real indicada y registra la diferencia.
|
||||||
|
func ajustarStock(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuarioID uint, entrada dto.AjusteDto) (*models.Stock, error) {
|
||||||
|
if entrada.CantidadReal < 0 || math.IsNaN(entrada.CantidadReal) || math.IsInf(entrada.CantidadReal, 0) {
|
||||||
|
return nil, ErrCantidadInvalida
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(entrada.Motivo) == "" {
|
||||||
|
return nil, ErrMotivoRequerido
|
||||||
|
}
|
||||||
|
if err := validarObservacion(entrada.Observacion); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
cantidadReal := redondearCantidad(entrada.CantidadReal)
|
||||||
|
var resultado *models.Stock
|
||||||
|
|
||||||
|
err := db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
stock, err := repo.Stock.BloquearPorID(tx, entrada.StockID)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrStockNoEncontrado
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if cantidadReal < stock.CantidadReservada {
|
||||||
|
return fmt.Errorf("%w: reservado %.3f", ErrAjusteBajoReserva, stock.CantidadReservada)
|
||||||
|
}
|
||||||
|
|
||||||
|
saldoAnterior := stock.Cantidad
|
||||||
|
diferencia := redondearCantidad(cantidadReal - saldoAnterior)
|
||||||
|
stock.Cantidad = cantidadReal
|
||||||
|
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
observacion := strings.TrimSpace(strings.Join([]string{entrada.Motivo, entrada.Observacion}, " - "))
|
||||||
|
if err := registrarMovimiento(tx, repo, usuarioID, stock, models.MovimientoAjuste, diferencia, saldoAnterior, stock.Cantidad, "AJUSTE", stock.ID, observacion); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if diferencia != 0 {
|
||||||
|
if err := asientoAjuste(tx, repo, stock, diferencia); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado = stock
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
registrarLog(repo, empresaID, usuarioID, "AJUSTE_STOCK", []models_logs.LogDetalle{
|
||||||
|
{NombreTabla: "stock", Columna: "stockId", ValorNuevo: fmt.Sprintf("%d", entrada.StockID)},
|
||||||
|
{NombreTabla: "stock", Columna: "cantidadReal", ValorNuevo: fmt.Sprintf("%.3f", cantidadReal)},
|
||||||
|
{NombreTabla: "stock", Columna: "motivo", ValorNuevo: entrada.Motivo},
|
||||||
|
})
|
||||||
|
return resultado, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"net/http"
|
||||||
|
"sort"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
dto "repuestera_back/dto/Stock"
|
||||||
|
"repuestera_back/models"
|
||||||
|
models_logs "repuestera_back/models/logs"
|
||||||
|
"repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
type resultadoIngreso struct {
|
||||||
|
Remito *models.Remito
|
||||||
|
Diferencias []models.DiferenciaRemito
|
||||||
|
Stocks []*models.Stock
|
||||||
|
}
|
||||||
|
|
||||||
|
func IngresarStock(c *gin.Context) {
|
||||||
|
var data dto.IngresoDto
|
||||||
|
if err := c.ShouldBindJSON(&data); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado, err := ingresarStock(
|
||||||
|
repositorios.BaseDeDatos(),
|
||||||
|
repositorios.ObtenerRepositorios(c),
|
||||||
|
utils.EmpresaID(c),
|
||||||
|
c.GetUint("userID"),
|
||||||
|
data,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
responderError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusCreated, resultado)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ingresarStock crea el remito, actualiza stock, registra diferencias y asiento.
|
||||||
|
func ingresarStock(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuarioID uint, entrada dto.IngresoDto) (*resultadoIngreso, error) {
|
||||||
|
if entrada.ProveedorID == 0 {
|
||||||
|
return nil, ErrProveedorNoEncontrado
|
||||||
|
}
|
||||||
|
if entrada.AlmacenDestinoID == 0 {
|
||||||
|
return nil, ErrAlmacenInvalido
|
||||||
|
}
|
||||||
|
if entrada.FechaEmision.IsZero() {
|
||||||
|
return nil, fmt.Errorf("%w: fecha de emisión obligatoria", ErrMotivoRequerido)
|
||||||
|
}
|
||||||
|
if len(entrada.Items) == 0 {
|
||||||
|
return nil, fmt.Errorf("%w: el remito debe tener al menos un ítem", ErrCantidadInvalida)
|
||||||
|
}
|
||||||
|
if err := validarObservacion(entrada.Observacion); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
proveedor, err := repo.Proveedor.ObtenerPorID(entrada.ProveedorID)
|
||||||
|
if err != nil || proveedor == nil {
|
||||||
|
return nil, ErrProveedorNoEncontrado
|
||||||
|
}
|
||||||
|
if _, err := repo.Almacen.ObtenerPorID(entrada.AlmacenDestinoID); err != nil {
|
||||||
|
return nil, ErrAlmacenInvalido
|
||||||
|
}
|
||||||
|
|
||||||
|
items := append([]dto.ItemIngresoDto(nil), entrada.Items...)
|
||||||
|
// Ordenar por repuesto para bloquear filas siempre en el mismo orden.
|
||||||
|
sort.Slice(items, func(i, j int) bool { return items[i].RepuestoID < items[j].RepuestoID })
|
||||||
|
|
||||||
|
repuestos := make(map[uint64]*models.Repuesto, len(items))
|
||||||
|
vistos := make(map[uint64]bool, len(items))
|
||||||
|
for _, item := range items {
|
||||||
|
if item.RepuestoID == 0 {
|
||||||
|
return nil, ErrRepuestoNoEncontrado
|
||||||
|
}
|
||||||
|
if vistos[item.RepuestoID] {
|
||||||
|
return nil, fmt.Errorf("%w: %d", ErrItemDuplicado, item.RepuestoID)
|
||||||
|
}
|
||||||
|
vistos[item.RepuestoID] = true
|
||||||
|
if math.IsNaN(item.CantidadEsperada) || item.CantidadEsperada < 0 || math.IsNaN(item.CantidadRecibida) || item.CantidadRecibida < 0 {
|
||||||
|
return nil, ErrCantidadInvalida
|
||||||
|
}
|
||||||
|
if item.CantidadEsperada == 0 && item.CantidadRecibida == 0 {
|
||||||
|
return nil, ErrCantidadInvalida
|
||||||
|
}
|
||||||
|
if err := validarObservacion(item.Observacion); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
repuestoPtr, err := repo.Repuesto.ObtenerPorID(uint(item.RepuestoID))
|
||||||
|
if err != nil || repuestoPtr == nil || *repuestoPtr == nil {
|
||||||
|
return nil, fmt.Errorf("%w: %d", ErrRepuestoNoEncontrado, item.RepuestoID)
|
||||||
|
}
|
||||||
|
repuestos[item.RepuestoID] = *repuestoPtr
|
||||||
|
}
|
||||||
|
|
||||||
|
var resultado resultadoIngreso
|
||||||
|
err = db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
existe, err := repo.Remito.ExisteNumeroProveedor(tx, entrada.Numero, entrada.ProveedorID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if existe {
|
||||||
|
return ErrRemitoDuplicado
|
||||||
|
}
|
||||||
|
|
||||||
|
remito := &models.Remito{
|
||||||
|
Numero: entrada.Numero,
|
||||||
|
FechaEmision: entrada.FechaEmision,
|
||||||
|
TipoOperacion: models.OperacionCompra,
|
||||||
|
EmisorID: entrada.ProveedorID,
|
||||||
|
ReceptorID: empresaID,
|
||||||
|
ProveedorID: &entrada.ProveedorID,
|
||||||
|
AlmacenDestinoID: &entrada.AlmacenDestinoID,
|
||||||
|
Observacion: entrada.Observacion,
|
||||||
|
}
|
||||||
|
remito.Estado = "confirmado"
|
||||||
|
remito.ResponsableID = usuarioID
|
||||||
|
|
||||||
|
var total float64
|
||||||
|
for _, item := range items {
|
||||||
|
repuesto := repuestos[item.RepuestoID]
|
||||||
|
recibida := redondearCantidad(item.CantidadRecibida)
|
||||||
|
total += redondearCantidad(recibida * repuesto.Precio)
|
||||||
|
remito.Detalles = append(remito.Detalles, models.RemitoDetalle{
|
||||||
|
ProductoID: uint(item.RepuestoID),
|
||||||
|
CantidadEsperada: redondearCantidad(item.CantidadEsperada),
|
||||||
|
CantidadRecibida: recibida,
|
||||||
|
UnidadMedida: item.UnidadMedida,
|
||||||
|
Observacion: item.Observacion,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
total = redondearCantidad(total)
|
||||||
|
remito.Total = total
|
||||||
|
|
||||||
|
if err := repo.Remito.CrearConDetalles(tx, remito); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range items {
|
||||||
|
recibida := redondearCantidad(item.CantidadRecibida)
|
||||||
|
if recibida > 0 {
|
||||||
|
stock, err := repo.Stock.BloquearOCrearPorRepuestoAlmacen(tx, item.RepuestoID, entrada.AlmacenDestinoID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
saldoAnterior := stock.Cantidad
|
||||||
|
stock.Cantidad = redondearCantidad(stock.Cantidad + recibida)
|
||||||
|
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := registrarMovimiento(tx, repo, usuarioID, stock, models.MovimientoIngreso, recibida, saldoAnterior, stock.Cantidad, "REMITO", uint64(remito.ID), remito.Numero); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
resultado.Stocks = append(resultado.Stocks, stock)
|
||||||
|
}
|
||||||
|
|
||||||
|
esperada := redondearCantidad(item.CantidadEsperada)
|
||||||
|
if esperada != recibida {
|
||||||
|
diferencia := &models.DiferenciaRemito{
|
||||||
|
RemitoID: remito.ID,
|
||||||
|
RepuestoID: item.RepuestoID,
|
||||||
|
CantidadEsperada: esperada,
|
||||||
|
CantidadRecibida: recibida,
|
||||||
|
Diferencia: redondearCantidad(recibida - esperada),
|
||||||
|
UsuarioID: usuarioID,
|
||||||
|
Observacion: item.Observacion,
|
||||||
|
}
|
||||||
|
if err := repo.DiferenciaRemito.Registrar(tx, diferencia); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
resultado.Diferencias = append(resultado.Diferencias, *diferencia)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if total > 0 {
|
||||||
|
if err := registrarAsiento(tx, repo, "REMITO", remito.ID, []lineaAsiento{
|
||||||
|
{cuenta: cuentaInventario, tipo: tipoActivo, debe: total, descripcion: "Ingreso de mercadería"},
|
||||||
|
{cuenta: cuentaProveedores, tipo: tipoPasivo, haber: total, descripcion: "Compra con remito"},
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado.Remito = remito
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
registrarLog(repo, empresaID, usuarioID, "INGRESO_STOCK", []models_logs.LogDetalle{
|
||||||
|
{NombreTabla: "remito", Columna: "remitoId", ValorNuevo: fmt.Sprintf("%d", resultado.Remito.ID)},
|
||||||
|
{NombreTabla: "remito", Columna: "numero", ValorNuevo: entrada.Numero},
|
||||||
|
{NombreTabla: "remito", Columna: "items", ValorNuevo: fmt.Sprintf("%d", len(items))},
|
||||||
|
{NombreTabla: "diferencia_remito", Columna: "diferencias", ValorNuevo: fmt.Sprintf("%d", len(resultado.Diferencias))},
|
||||||
|
})
|
||||||
|
if len(resultado.Diferencias) > 0 {
|
||||||
|
notificarDiferencias(repo, empresaID, usuarioID, resultado.Remito, proveedor.Nombre, resultado.Diferencias, repuestos)
|
||||||
|
}
|
||||||
|
return &resultado, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"repuestera_back/models"
|
||||||
|
models_logs "repuestera_back/models/logs"
|
||||||
|
"repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
func LiberarReserva(c *gin.Context) {
|
||||||
|
id, err := parseUintParam(c, "id")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado, err := liberarReserva(
|
||||||
|
repositorios.BaseDeDatos(),
|
||||||
|
repositorios.ObtenerRepositorios(c),
|
||||||
|
utils.EmpresaID(c),
|
||||||
|
c.GetUint("userID"),
|
||||||
|
uint(id),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
responderError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, resultado)
|
||||||
|
}
|
||||||
|
|
||||||
|
// liberarReserva devuelve el disponible de una reserva activa.
|
||||||
|
func liberarReserva(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuarioID uint, reservaID uint) (*models.Reserva, error) {
|
||||||
|
var reserva *models.Reserva
|
||||||
|
|
||||||
|
err := db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
actual, err := repo.Reserva.ObtenerPorID(reservaID)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrReservaInexistente
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if actual.Estado != models.ReservaActiva {
|
||||||
|
return ErrReservaYaLiberada
|
||||||
|
}
|
||||||
|
|
||||||
|
stock, err := repo.Stock.BloquearPorRepuestoAlmacen(tx, uint64(actual.RepuestoID), actual.AlmacenID)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrStockNoEncontrado
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
liberada, err := repo.Reserva.Liberar(tx, reservaID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !liberada {
|
||||||
|
return ErrReservaYaLiberada
|
||||||
|
}
|
||||||
|
|
||||||
|
saldoAnterior := stock.CantidadReservada
|
||||||
|
stock.CantidadReservada = redondearCantidad(math.Max(0, stock.CantidadReservada-actual.Cantidad))
|
||||||
|
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := registrarMovimiento(tx, repo, usuarioID, stock, models.MovimientoLiberacion, -actual.Cantidad, saldoAnterior, stock.CantidadReservada, "RESERVA", uint64(actual.ID), "Liberación de reserva"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
reserva = actual
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
registrarLog(repo, empresaID, usuarioID, "LIBERAR_RESERVA", []models_logs.LogDetalle{
|
||||||
|
{NombreTabla: "reserva", Columna: "reservaId", ValorNuevo: fmt.Sprintf("%d", reserva.ID)},
|
||||||
|
{NombreTabla: "reserva", Columna: "cantidad", ValorNuevo: fmt.Sprintf("%.3f", reserva.Cantidad)},
|
||||||
|
})
|
||||||
|
return reserva, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
applog "log"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"repuestera_back/models"
|
||||||
|
models_logs "repuestera_back/models/logs"
|
||||||
|
"repuestera_back/repositorios"
|
||||||
|
"repuestera_back/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
// notificarDiferencias avisa por email las diferencias detectadas en un
|
||||||
|
// ingreso y deja una entrada de auditoría. Nunca revierte el ingreso: si el
|
||||||
|
// envío falla, las diferencias quedan sin NotificadaAt.
|
||||||
|
func notificarDiferencias(
|
||||||
|
repo *repositorios.Repositorios,
|
||||||
|
empresaID, usuarioID uint,
|
||||||
|
remito *models.Remito,
|
||||||
|
proveedor string,
|
||||||
|
diferencias []models.DiferenciaRemito,
|
||||||
|
repuestos map[uint64]*models.Repuesto,
|
||||||
|
) {
|
||||||
|
if remito == nil || len(diferencias) == 0 {
|
||||||
|
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),
|
||||||
|
ValorNuevo: fmt.Sprintf(
|
||||||
|
"esperado %.3f, recibido %.3f, diferencia %.3f",
|
||||||
|
diferencia.CantidadEsperada, diferencia.CantidadRecibida, diferencia.Diferencia,
|
||||||
|
),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
destinatarios := destinatariosDiferencias(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)
|
||||||
|
}
|
||||||
|
|
||||||
|
if enviado {
|
||||||
|
ids := make([]uint64, 0, len(diferencias))
|
||||||
|
for _, diferencia := range diferencias {
|
||||||
|
ids = append(ids, diferencia.ID)
|
||||||
|
}
|
||||||
|
if err := repo.DiferenciaRemito.MarcarNotificadas(ids, time.Now()); err != nil {
|
||||||
|
applog.Printf("stock: no se pudieron marcar las diferencias del remito %s como notificadas: %v", remito.Numero, err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
applog.Printf("stock: no se pudo enviar el aviso de diferencias del remito %s", remito.Numero)
|
||||||
|
}
|
||||||
|
|
||||||
|
detalles = append([]models_logs.LogDetalle{
|
||||||
|
{NombreTabla: "remito", Columna: "remitoId", ValorNuevo: fmt.Sprintf("%d", remito.ID)},
|
||||||
|
{NombreTabla: "remito", Columna: "numero", ValorNuevo: remito.Numero},
|
||||||
|
{NombreTabla: "remito", Columna: "proveedor", ValorNuevo: proveedor},
|
||||||
|
{NombreTabla: "diferencia_remito", Columna: "emailEnviado", ValorNuevo: fmt.Sprintf("%t", enviado)},
|
||||||
|
{NombreTabla: "diferencia_remito", Columna: "destinatarios", ValorNuevo: strings.Join(destinatarios, ", ")},
|
||||||
|
}, detalles...)
|
||||||
|
|
||||||
|
registrarLog(repo, empresaID, usuarioID, "DIFERENCIA_REMITO", detalles)
|
||||||
|
}
|
||||||
|
|
||||||
|
// destinatariosDiferencias 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 {
|
||||||
|
if raw := strings.TrimSpace(os.Getenv("STOCK_ALERT_EMAILS")); raw != "" {
|
||||||
|
return limpiarDestinatarios(strings.Split(raw, ","))
|
||||||
|
}
|
||||||
|
|
||||||
|
var destinatarios []string
|
||||||
|
if empresaID > 0 {
|
||||||
|
miembros, _, err := repo.Empresa.ListarMiembros(empresaID, 0, 100)
|
||||||
|
if err == nil {
|
||||||
|
for _, miembro := range miembros {
|
||||||
|
if !miembro.Activo || !miembro.Rol.EsAdministrador() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
destinatarios = append(destinatarios, miembro.Usuario.Email)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
destinatarios = limpiarDestinatarios(destinatarios)
|
||||||
|
if len(destinatarios) > 0 {
|
||||||
|
return destinatarios
|
||||||
|
}
|
||||||
|
|
||||||
|
usuario, err := repo.Usuario.ObtenerPorID(usuarioID)
|
||||||
|
if err == nil && usuario != nil {
|
||||||
|
return limpiarDestinatarios([]string{usuario.Email})
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func limpiarDestinatarios(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,53 @@
|
|||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
applog "log"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
dto "repuestera_back/dto/Stock"
|
||||||
|
"repuestera_back/models"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerReservas(c *gin.Context) {
|
||||||
|
var q dto.FiltrosReservaQuery
|
||||||
|
if err := c.ShouldBindQuery(&q); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !estadoReservaValido(q.Estado) {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "estado de reserva inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := r.ObtenerRepositorios(c)
|
||||||
|
|
||||||
|
// D9: las reservas vencidas se procesan de forma lazy al consultar.
|
||||||
|
if err := marcarReservasVencidas(r.BaseDeDatos(), repo, c.GetUint("userID"), time.Now()); err != nil {
|
||||||
|
applog.Printf("stock: no se pudieron procesar las reservas vencidas: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
reservas, err := repo.Reserva.ListarActivas(q)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, reservas)
|
||||||
|
}
|
||||||
|
|
||||||
|
func estadoReservaValido(estado string) bool {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(estado)) {
|
||||||
|
case "", "todas",
|
||||||
|
string(models.ReservaActiva),
|
||||||
|
string(models.ReservaVencida),
|
||||||
|
string(models.ReservaLiberada),
|
||||||
|
string(models.ReservaConsumida):
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
dto "repuestera_back/dto/Stock"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerStock(c *gin.Context) {
|
||||||
|
var q dto.FiltrosStockQuery
|
||||||
|
if err := c.ShouldBindQuery(&q); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
filtros := r.FiltrosStock{
|
||||||
|
RepuestoID: q.RepuestoID,
|
||||||
|
AlmacenID: q.AlmacenID,
|
||||||
|
Texto: q.Texto,
|
||||||
|
SoloBajoMinimo: q.SoloBajoMinimo,
|
||||||
|
Pagina: q.Pagina,
|
||||||
|
PorPagina: q.PorPagina,
|
||||||
|
}
|
||||||
|
stocks, err := r.ObtenerRepositorios(c).Stock.Listar(filtros)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
director := dto_directors.NewStockDirector()
|
||||||
|
|
||||||
|
respuesta, err := director.Listar(stocks)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if q.Estado != "" {
|
||||||
|
filtrado := make([]dto.StockResponse, 0, len(respuesta))
|
||||||
|
for _, item := range respuesta {
|
||||||
|
if strings.EqualFold(item.Estado, q.Estado) {
|
||||||
|
filtrado = append(filtrado, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
respuesta = filtrado
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ObtenerStockPorID(c *gin.Context) {
|
||||||
|
uid, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || uid == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
stock, err := r.ObtenerRepositorios(c).Stock.ObtenerPorID(uint(uid))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "stock no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewStockDirector().DesdeStock(stock)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
dto "repuestera_back/dto/Stock"
|
||||||
|
"repuestera_back/models"
|
||||||
|
models_logs "repuestera_back/models/logs"
|
||||||
|
"repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
type resultadoDevolucion struct {
|
||||||
|
Devolucion *models.Devolucion
|
||||||
|
Stocks []*models.Stock
|
||||||
|
}
|
||||||
|
|
||||||
|
func RegistrarDevolucion(c *gin.Context) {
|
||||||
|
var data dto.DevolucionDto
|
||||||
|
if err := c.ShouldBindJSON(&data); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado, err := registrarDevolucion(
|
||||||
|
repositorios.BaseDeDatos(),
|
||||||
|
repositorios.ObtenerRepositorios(c),
|
||||||
|
utils.EmpresaID(c),
|
||||||
|
c.GetUint("userID"),
|
||||||
|
data,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
responderError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusCreated, resultado)
|
||||||
|
}
|
||||||
|
|
||||||
|
// registrarDevolucion valida contra lo vendido, repone stock y registra el comprobante.
|
||||||
|
func registrarDevolucion(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuarioID uint, entrada dto.DevolucionDto) (*resultadoDevolucion, error) {
|
||||||
|
if strings.TrimSpace(entrada.Motivo) == "" {
|
||||||
|
return nil, ErrMotivoRequerido
|
||||||
|
}
|
||||||
|
if len(entrada.Items) == 0 {
|
||||||
|
return nil, fmt.Errorf("%w: la devolución debe tener al menos un ítem", ErrCantidadInvalida)
|
||||||
|
}
|
||||||
|
|
||||||
|
factura, err := repo.Factura.ObtenerPorID(entrada.FacturaID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%w: factura %d", ErrItemNoEncontrado, entrada.FacturaID)
|
||||||
|
}
|
||||||
|
if strings.EqualFold(strings.TrimSpace(factura.Estado), "anulada") {
|
||||||
|
return nil, ErrFacturaAnulada
|
||||||
|
}
|
||||||
|
|
||||||
|
almacenID := entrada.AlmacenID
|
||||||
|
if almacenID == 0 {
|
||||||
|
almacenes, err := repo.Almacen.Listar()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(almacenes) == 0 {
|
||||||
|
return nil, ErrSinAlmacen
|
||||||
|
}
|
||||||
|
almacenID = almacenes[0].ID
|
||||||
|
} else if _, err := repo.Almacen.ObtenerPorID(almacenID); err != nil {
|
||||||
|
return nil, ErrAlmacenInvalido
|
||||||
|
}
|
||||||
|
|
||||||
|
items := append([]dto.ItemDevolucionDto(nil), entrada.Items...)
|
||||||
|
sort.Slice(items, func(i, j int) bool { return items[i].RepuestoID < items[j].RepuestoID })
|
||||||
|
|
||||||
|
vendidos := make(map[uint64]float64)
|
||||||
|
precios := make(map[uint64]float64)
|
||||||
|
for _, detalle := range factura.Detalles {
|
||||||
|
vendidos[detalle.RepuestoID] += float64(detalle.Cantidad)
|
||||||
|
precios[detalle.RepuestoID] = detalle.PrecioUnitario
|
||||||
|
}
|
||||||
|
|
||||||
|
anteriores, err := repo.Devolucion.ListarPorFactura(factura.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var resultado resultadoDevolucion
|
||||||
|
err = db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
devueltos := make(map[uint64]float64)
|
||||||
|
for _, devolucion := range anteriores {
|
||||||
|
for _, detalle := range devolucion.Detalles {
|
||||||
|
devueltos[detalle.RepuestoID] += detalle.Cantidad
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
devolucion := &models.Devolucion{
|
||||||
|
Motivo: entrada.Motivo,
|
||||||
|
FacturaOrigenID: factura.ID,
|
||||||
|
}
|
||||||
|
devolucion.Estado = "confirmada"
|
||||||
|
devolucion.ResponsableID = usuarioID
|
||||||
|
|
||||||
|
detalles := make([]models.DevolucionDetalle, 0, len(items))
|
||||||
|
for _, item := range items {
|
||||||
|
if err := validarCantidad(item.Cantidad); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
vendido, ok := vendidos[item.RepuestoID]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("%w: %d", ErrItemNoEncontrado, item.RepuestoID)
|
||||||
|
}
|
||||||
|
cantidad := redondearCantidad(item.Cantidad)
|
||||||
|
if cantidad > redondearCantidad(vendido-devueltos[item.RepuestoID]) {
|
||||||
|
return fmt.Errorf("%w: repuesto %d, vendido %.3f, ya devuelto %.3f", ErrDevolucionExcedeVendido, item.RepuestoID, vendido, devueltos[item.RepuestoID])
|
||||||
|
}
|
||||||
|
|
||||||
|
precio := item.PrecioUnitario
|
||||||
|
if precio <= 0 {
|
||||||
|
precio = precios[item.RepuestoID]
|
||||||
|
}
|
||||||
|
detalles = append(detalles, models.DevolucionDetalle{
|
||||||
|
RepuestoID: item.RepuestoID,
|
||||||
|
Cantidad: cantidad,
|
||||||
|
PrecioUnitario: precio,
|
||||||
|
Subtotal: redondearCantidad(cantidad * precio),
|
||||||
|
})
|
||||||
|
devolucion.Total = redondearCantidad(devolucion.Total + cantidad*precio)
|
||||||
|
}
|
||||||
|
devolucion.Detalles = detalles
|
||||||
|
|
||||||
|
if err := repo.Devolucion.CrearConDetalles(tx, devolucion); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, detalle := range detalles {
|
||||||
|
stock, err := repo.Stock.BloquearOCrearPorRepuestoAlmacen(tx, detalle.RepuestoID, almacenID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
saldoAnterior := stock.Cantidad
|
||||||
|
stock.Cantidad = redondearCantidad(stock.Cantidad + detalle.Cantidad)
|
||||||
|
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := registrarMovimiento(tx, repo, usuarioID, stock, models.MovimientoDevolucion, detalle.Cantidad, saldoAnterior, stock.Cantidad, "DEVOLUCION", uint64(devolucion.ID), entrada.Motivo); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
resultado.Stocks = append(resultado.Stocks, stock)
|
||||||
|
}
|
||||||
|
|
||||||
|
if devolucion.Total > 0 {
|
||||||
|
if err := registrarAsiento(tx, repo, "DEVOLUCION", devolucion.ID, []lineaAsiento{
|
||||||
|
{cuenta: cuentaInventario, tipo: tipoActivo, debe: devolucion.Total, descripcion: "Devolución de mercadería"},
|
||||||
|
{cuenta: cuentaDevoluciones, tipo: tipoResultado, haber: devolucion.Total, descripcion: "Devoluciones sobre ventas"},
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado.Devolucion = devolucion
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
registrarLog(repo, empresaID, usuarioID, "DEVOLUCION_STOCK", []models_logs.LogDetalle{
|
||||||
|
{NombreTabla: "devolucion", Columna: "devolucionId", ValorNuevo: fmt.Sprintf("%d", resultado.Devolucion.ID)},
|
||||||
|
{NombreTabla: "devolucion", Columna: "facturaId", ValorNuevo: fmt.Sprintf("%d", factura.ID)},
|
||||||
|
{NombreTabla: "devolucion", Columna: "total", ValorNuevo: fmt.Sprintf("%.2f", resultado.Devolucion.Total)},
|
||||||
|
})
|
||||||
|
return &resultado, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
dto "repuestera_back/dto/Stock"
|
||||||
|
"repuestera_back/models"
|
||||||
|
models_logs "repuestera_back/models/logs"
|
||||||
|
"repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ReservarStock(c *gin.Context) {
|
||||||
|
var data dto.ReservaDto
|
||||||
|
if err := c.ShouldBindJSON(&data); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado, err := reservarStock(
|
||||||
|
repositorios.BaseDeDatos(),
|
||||||
|
repositorios.ObtenerRepositorios(c),
|
||||||
|
utils.EmpresaID(c),
|
||||||
|
c.GetUint("userID"),
|
||||||
|
data,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
responderError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusCreated, resultado)
|
||||||
|
}
|
||||||
|
|
||||||
|
// reservarStock bloquea stock, incrementa lo reservado y crea la reserva activa.
|
||||||
|
func reservarStock(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuarioID uint, entrada dto.ReservaDto) (*models.Reserva, error) {
|
||||||
|
if err := validarCantidad(entrada.Cantidad); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validarObservacion(entrada.Observacion); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if entrada.FechaVencimiento != nil && !entrada.FechaVencimiento.After(time.Now()) {
|
||||||
|
return nil, ErrFechaVencimiento
|
||||||
|
}
|
||||||
|
if _, err := repo.Cliente.ObtenerPorID(entrada.ClienteID); err != nil {
|
||||||
|
return nil, fmt.Errorf("%w: cliente %d", ErrClienteNoEncontrado, entrada.ClienteID)
|
||||||
|
}
|
||||||
|
|
||||||
|
cantidad := redondearCantidad(entrada.Cantidad)
|
||||||
|
var reserva *models.Reserva
|
||||||
|
|
||||||
|
err := db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
stock, err := repo.Stock.BloquearPorRepuestoAlmacen(tx, entrada.RepuestoID, entrada.AlmacenID)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrStockNoEncontrado
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if disponible(stock) < cantidad {
|
||||||
|
return fmt.Errorf("%w: disponible %.3f, solicitado %.3f", ErrStockInsuficiente, disponible(stock), cantidad)
|
||||||
|
}
|
||||||
|
|
||||||
|
saldoReservado := stock.CantidadReservada
|
||||||
|
stock.CantidadReservada = redondearCantidad(stock.CantidadReservada + cantidad)
|
||||||
|
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
clienteID := entrada.ClienteID
|
||||||
|
reserva = &models.Reserva{
|
||||||
|
RepuestoID: uint(entrada.RepuestoID),
|
||||||
|
AlmacenID: entrada.AlmacenID,
|
||||||
|
Cantidad: cantidad,
|
||||||
|
Estado: models.ReservaActiva,
|
||||||
|
ClienteID: &clienteID,
|
||||||
|
FechaVencimiento: entrada.FechaVencimiento,
|
||||||
|
CreadoPorID: usuarioID,
|
||||||
|
Observacion: entrada.Observacion,
|
||||||
|
}
|
||||||
|
if err := repo.Reserva.CrearTx(tx, reserva); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return registrarMovimiento(tx, repo, usuarioID, stock, models.MovimientoReserva, cantidad, saldoReservado, stock.CantidadReservada, "RESERVA", uint64(reserva.ID), entrada.Observacion)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
registrarLog(repo, empresaID, usuarioID, "RESERVAR_STOCK", []models_logs.LogDetalle{
|
||||||
|
{NombreTabla: "reserva", Columna: "reservaId", ValorNuevo: fmt.Sprintf("%d", reserva.ID)},
|
||||||
|
{NombreTabla: "reserva", Columna: "repuestoId", ValorNuevo: fmt.Sprintf("%d", entrada.RepuestoID)},
|
||||||
|
{NombreTabla: "reserva", Columna: "almacenId", ValorNuevo: fmt.Sprintf("%d", entrada.AlmacenID)},
|
||||||
|
{NombreTabla: "reserva", Columna: "cantidad", ValorNuevo: fmt.Sprintf("%.3f", cantidad)},
|
||||||
|
})
|
||||||
|
return reserva, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"math"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
"repuestera_back/models"
|
||||||
|
"repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
// marcarReservasVencidas pasa a vencidas las reservas activas cuya fecha ya
|
||||||
|
// paso y devuelve al disponible la cantidad que tenian reservada. Se ejecuta de
|
||||||
|
// forma lazy al consultar reservas (D9) para no depender de un cron.
|
||||||
|
func marcarReservasVencidas(db *gorm.DB, repo *repositorios.Repositorios, usuarioID uint, ahora time.Time) error {
|
||||||
|
if db == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
vencidas, err := repo.Reserva.BloquearVencidas(tx, ahora)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, reserva := range vencidas {
|
||||||
|
stock, err := repo.Stock.BloquearPorRepuestoAlmacen(tx, uint64(reserva.RepuestoID), reserva.AlmacenID)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
// La reserva igual debe dejar de figurar como activa.
|
||||||
|
if _, err := repo.Reserva.MarcarVencida(tx, reserva.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
liberar := math.Min(reserva.Cantidad, stock.CantidadReservada)
|
||||||
|
if liberar > 0 {
|
||||||
|
saldoAnterior := stock.CantidadReservada
|
||||||
|
stock.CantidadReservada = redondearCantidad(stock.CantidadReservada - liberar)
|
||||||
|
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := registrarMovimiento(tx, repo, usuarioID, stock, models.MovimientoLiberacion, -liberar, saldoAnterior, stock.CantidadReservada, "RESERVA", uint64(reserva.ID), "Vencimiento de reserva"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
marcada, err := repo.Reserva.MarcarVencida(tx, reserva.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !marcada {
|
||||||
|
return ErrReservaYaLiberada
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
dto "repuestera_back/dto/Stock"
|
||||||
|
"repuestera_back/models"
|
||||||
|
models_logs "repuestera_back/models/logs"
|
||||||
|
"repuestera_back/repositorios"
|
||||||
|
"repuestera_back/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
type resultadoTraslado struct {
|
||||||
|
Origen *models.Stock
|
||||||
|
Destino *models.Stock
|
||||||
|
}
|
||||||
|
|
||||||
|
func TrasladarStock(c *gin.Context) {
|
||||||
|
var data dto.TrasladoDto
|
||||||
|
if err := c.ShouldBindJSON(&data); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado, err := trasladarStock(
|
||||||
|
repositorios.BaseDeDatos(),
|
||||||
|
repositorios.ObtenerRepositorios(c),
|
||||||
|
utils.EmpresaID(c),
|
||||||
|
c.GetUint("userID"),
|
||||||
|
data,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
responderError(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, resultado)
|
||||||
|
}
|
||||||
|
|
||||||
|
// trasladarStock descuenta el origen y suma el destino en una sola transacción.
|
||||||
|
func trasladarStock(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuarioID uint, entrada dto.TrasladoDto) (*resultadoTraslado, error) {
|
||||||
|
if err := validarCantidad(entrada.Cantidad); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if entrada.RepuestoID == 0 || entrada.AlmacenOrigenID == 0 || entrada.AlmacenDestinoID == 0 {
|
||||||
|
return nil, ErrStockNoEncontrado
|
||||||
|
}
|
||||||
|
if entrada.AlmacenOrigenID == entrada.AlmacenDestinoID {
|
||||||
|
return nil, ErrMismoAlmacen
|
||||||
|
}
|
||||||
|
if err := validarObservacion(entrada.Observacion); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
cantidad := redondearCantidad(entrada.Cantidad)
|
||||||
|
var resultado resultadoTraslado
|
||||||
|
|
||||||
|
err := db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
origen, err := repo.Stock.BuscarPorRepuestoAlmacen(tx, entrada.RepuestoID, entrada.AlmacenOrigenID)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrStockNoEncontrado
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
destino, errDestino := repo.Stock.BuscarPorRepuestoAlmacen(tx, entrada.RepuestoID, entrada.AlmacenDestinoID)
|
||||||
|
existeDestino := errDestino == nil
|
||||||
|
if errDestino != nil && !errors.Is(errDestino, gorm.ErrRecordNotFound) {
|
||||||
|
return errDestino
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bloquear siempre en orden ascendente de ID para evitar deadlocks
|
||||||
|
// cuando dos traslados cruzan el mismo par de filas.
|
||||||
|
if existeDestino && destino.ID < origen.ID {
|
||||||
|
destino, err = repo.Stock.BloquearPorID(tx, destino.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
origen, err = repo.Stock.BloquearPorID(tx, origen.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
origen, err = repo.Stock.BloquearPorID(tx, origen.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if existeDestino {
|
||||||
|
destino, err = repo.Stock.BloquearPorID(tx, destino.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
destino, err = repo.Stock.BloquearOCrearPorRepuestoAlmacen(tx, entrada.RepuestoID, entrada.AlmacenDestinoID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if disponible(origen) < cantidad {
|
||||||
|
return fmt.Errorf("%w: disponible %.3f, solicitado %.3f", ErrStockInsuficiente, disponible(origen), cantidad)
|
||||||
|
}
|
||||||
|
|
||||||
|
saldoOrigen := origen.Cantidad
|
||||||
|
saldoDestino := destino.Cantidad
|
||||||
|
|
||||||
|
origen.Cantidad = redondearCantidad(origen.Cantidad - cantidad)
|
||||||
|
destino.Cantidad = redondearCantidad(destino.Cantidad + cantidad)
|
||||||
|
if err := repo.Stock.ActualizarCantidades(tx, origen); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := repo.Stock.ActualizarCantidades(tx, destino); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
referencia := fmt.Sprintf("Traslado %d → %d", entrada.AlmacenOrigenID, entrada.AlmacenDestinoID)
|
||||||
|
if err := registrarMovimiento(tx, repo, usuarioID, origen, models.MovimientoTrasladoSalida, -cantidad, saldoOrigen, origen.Cantidad, "TRASLADO", entrada.RepuestoID, referencia); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := registrarMovimiento(tx, repo, usuarioID, destino, models.MovimientoTrasladoEntrada, cantidad, saldoDestino, destino.Cantidad, "TRASLADO", entrada.RepuestoID, referencia); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado = resultadoTraslado{Origen: origen, Destino: destino}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
registrarLog(repo, empresaID, usuarioID, "TRASLADO_STOCK", []models_logs.LogDetalle{
|
||||||
|
{NombreTabla: "stock", Columna: "repuestoId", ValorNuevo: fmt.Sprintf("%d", entrada.RepuestoID)},
|
||||||
|
{NombreTabla: "stock", Columna: "origenId", ValorNuevo: fmt.Sprintf("%d", entrada.AlmacenOrigenID)},
|
||||||
|
{NombreTabla: "stock", Columna: "destinoId", ValorNuevo: fmt.Sprintf("%d", entrada.AlmacenDestinoID)},
|
||||||
|
{NombreTabla: "stock", Columna: "cantidad", ValorNuevo: fmt.Sprintf("%.3f", cantidad)},
|
||||||
|
})
|
||||||
|
return &resultado, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
package stock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
applog "log"
|
||||||
|
"math"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
"repuestera_back/models"
|
||||||
|
"repuestera_back/models/contabilidad"
|
||||||
|
models_logs "repuestera_back/models/logs"
|
||||||
|
"repuestera_back/repositorios"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Errores de negocio del módulo. Los controllers los traducen a códigos HTTP.
|
||||||
|
var (
|
||||||
|
ErrCantidadInvalida = errors.New("la cantidad debe ser mayor a cero")
|
||||||
|
ErrStockInsuficiente = errors.New("stock insuficiente")
|
||||||
|
ErrMismoAlmacen = errors.New("el almacén de origen y destino deben ser distintos")
|
||||||
|
ErrStockNoEncontrado = errors.New("stock no encontrado")
|
||||||
|
ErrReservaInexistente = errors.New("reserva inexistente")
|
||||||
|
ErrReservaYaLiberada = errors.New("la reserva ya no está activa")
|
||||||
|
ErrComentarioLargo = errors.New("el comentario no puede superar los 60 caracteres")
|
||||||
|
ErrFacturaAnulada = errors.New("la factura está anulada")
|
||||||
|
ErrDevolucionExcedeVendido = errors.New("la devolución excede lo vendido")
|
||||||
|
ErrMotivoRequerido = errors.New("el motivo es obligatorio")
|
||||||
|
ErrItemDuplicado = errors.New("el repuesto está repetido en la operación")
|
||||||
|
ErrItemNoEncontrado = errors.New("el repuesto no pertenece a la factura")
|
||||||
|
ErrAlmacenInvalido = errors.New("el almacén no existe o no pertenece a la empresa")
|
||||||
|
ErrProveedorNoEncontrado = errors.New("el proveedor no existe o no pertenece a la empresa")
|
||||||
|
ErrClienteNoEncontrado = errors.New("el cliente no existe o no pertenece a la empresa")
|
||||||
|
ErrRepuestoNoEncontrado = errors.New("el repuesto no existe o no pertenece a la empresa")
|
||||||
|
ErrRemitoDuplicado = errors.New("ya existe un remito con ese número para el proveedor")
|
||||||
|
ErrFechaVencimiento = errors.New("la fecha de vencimiento debe ser futura")
|
||||||
|
ErrAjusteBajoReserva = errors.New("el stock no puede quedar por debajo de lo reservado")
|
||||||
|
ErrSinAlmacen = errors.New("no hay almacenes cargados en la empresa")
|
||||||
|
)
|
||||||
|
|
||||||
|
func codigoHTTP(err error) int {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||||
|
return http.StatusNotFound
|
||||||
|
case errors.Is(err, ErrStockNoEncontrado),
|
||||||
|
errors.Is(err, ErrReservaInexistente),
|
||||||
|
errors.Is(err, ErrItemNoEncontrado),
|
||||||
|
errors.Is(err, ErrAlmacenInvalido),
|
||||||
|
errors.Is(err, ErrProveedorNoEncontrado),
|
||||||
|
errors.Is(err, ErrClienteNoEncontrado),
|
||||||
|
errors.Is(err, ErrRepuestoNoEncontrado),
|
||||||
|
errors.Is(err, ErrSinAlmacen):
|
||||||
|
return http.StatusNotFound
|
||||||
|
case errors.Is(err, ErrReservaYaLiberada),
|
||||||
|
errors.Is(err, ErrFacturaAnulada),
|
||||||
|
errors.Is(err, ErrItemDuplicado),
|
||||||
|
errors.Is(err, ErrRemitoDuplicado):
|
||||||
|
return http.StatusConflict
|
||||||
|
case errors.Is(err, ErrComentarioLargo),
|
||||||
|
errors.Is(err, ErrMotivoRequerido),
|
||||||
|
errors.Is(err, ErrCantidadInvalida),
|
||||||
|
errors.Is(err, ErrFechaVencimiento),
|
||||||
|
errors.Is(err, ErrAjusteBajoReserva):
|
||||||
|
return http.StatusBadRequest
|
||||||
|
case errors.Is(err, ErrStockInsuficiente),
|
||||||
|
errors.Is(err, ErrMismoAlmacen),
|
||||||
|
errors.Is(err, ErrDevolucionExcedeVendido):
|
||||||
|
return http.StatusUnprocessableEntity
|
||||||
|
default:
|
||||||
|
return http.StatusInternalServerError
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func responderError(c *gin.Context, err error) {
|
||||||
|
c.JSON(codigoHTTP(err), gin.H{"error": err.Error()})
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseUintParam(c *gin.Context, name string) (uint64, error) {
|
||||||
|
uid, err := strconv.ParseUint(c.Param(name), 10, 64)
|
||||||
|
if err != nil || uid == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"})
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return uid, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// disponible es la cantidad que puede usarse sin afectar reservas.
|
||||||
|
func disponible(stock *models.Stock) float64 {
|
||||||
|
if stock == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return redondearCantidad(stock.Cantidad - stock.CantidadReservada)
|
||||||
|
}
|
||||||
|
|
||||||
|
// validarCantidad acepta solo cantidades positivas y finitas.
|
||||||
|
func validarCantidad(cantidad float64) error {
|
||||||
|
if math.IsNaN(cantidad) || math.IsInf(cantidad, 0) || cantidad <= 0 {
|
||||||
|
return ErrCantidadInvalida
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validarObservacion limita el texto a 60 caracteres (runas, no bytes).
|
||||||
|
func validarObservacion(texto string) error {
|
||||||
|
if utf8.RuneCountInString(texto) > 60 {
|
||||||
|
return ErrComentarioLargo
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func redondearCantidad(valor float64) float64 {
|
||||||
|
return math.Round(valor*1000) / 1000
|
||||||
|
}
|
||||||
|
|
||||||
|
func registrarMovimiento(
|
||||||
|
tx *gorm.DB,
|
||||||
|
repo *repositorios.Repositorios,
|
||||||
|
usuarioID uint,
|
||||||
|
stock *models.Stock,
|
||||||
|
tipo models.TipoMovimientoStock,
|
||||||
|
cantidad float64,
|
||||||
|
saldoAnterior float64,
|
||||||
|
saldoPosterior float64,
|
||||||
|
referenciaTipo string,
|
||||||
|
referenciaID uint64,
|
||||||
|
observacion string,
|
||||||
|
) error {
|
||||||
|
movimiento := &models.MovimientoStock{
|
||||||
|
StockID: stock.ID,
|
||||||
|
RepuestoID: stock.RepuestoID,
|
||||||
|
AlmacenID: stock.AlmacenID,
|
||||||
|
Tipo: tipo,
|
||||||
|
Cantidad: redondearCantidad(cantidad),
|
||||||
|
SaldoAnterior: redondearCantidad(saldoAnterior),
|
||||||
|
SaldoPosterior: redondearCantidad(saldoPosterior),
|
||||||
|
ReferenciaTipo: referenciaTipo,
|
||||||
|
ReferenciaID: referenciaID,
|
||||||
|
UsuarioID: usuarioID,
|
||||||
|
Observacion: observacion,
|
||||||
|
Fecha: time.Now(),
|
||||||
|
}
|
||||||
|
return repo.MovimientoStock.Registrar(tx, movimiento)
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
cuentaInventario = "Inventario"
|
||||||
|
cuentaProveedores = "Proveedores"
|
||||||
|
cuentaPerdida = "Pérdida por ajuste"
|
||||||
|
cuentaDevoluciones = "Devoluciones sobre ventas"
|
||||||
|
|
||||||
|
tipoActivo = "activo"
|
||||||
|
tipoPasivo = "pasivo"
|
||||||
|
tipoResultado = "resultado"
|
||||||
|
)
|
||||||
|
|
||||||
|
type lineaAsiento struct {
|
||||||
|
cuenta string
|
||||||
|
tipo string
|
||||||
|
debe float64
|
||||||
|
haber float64
|
||||||
|
descripcion string
|
||||||
|
}
|
||||||
|
|
||||||
|
// asientoAjuste registra la pérdida o recuperación de valor de un ajuste.
|
||||||
|
func asientoAjuste(tx *gorm.DB, repo *repositorios.Repositorios, stock *models.Stock, diferencia float64) error {
|
||||||
|
repuestoPtr, err := repo.Repuesto.ObtenerPorID(uint(stock.RepuestoID))
|
||||||
|
if err != nil || repuestoPtr == nil || *repuestoPtr == nil {
|
||||||
|
return fmt.Errorf("%w: %d", ErrRepuestoNoEncontrado, stock.RepuestoID)
|
||||||
|
}
|
||||||
|
monto := redondearCantidad(math.Abs(diferencia) * (*repuestoPtr).Precio)
|
||||||
|
if monto == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if diferencia < 0 {
|
||||||
|
return registrarAsiento(tx, repo, "AJUSTE", uint(stock.ID), []lineaAsiento{
|
||||||
|
{cuenta: cuentaPerdida, tipo: tipoResultado, debe: monto, descripcion: "Faltante de inventario"},
|
||||||
|
{cuenta: cuentaInventario, tipo: tipoActivo, haber: monto, descripcion: "Ajuste negativo de stock"},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return registrarAsiento(tx, repo, "AJUSTE", uint(stock.ID), []lineaAsiento{
|
||||||
|
{cuenta: cuentaInventario, tipo: tipoActivo, debe: monto, descripcion: "Ajuste positivo de stock"},
|
||||||
|
{cuenta: cuentaPerdida, tipo: tipoResultado, haber: monto, descripcion: "Sobrante de inventario"},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// registrarAsiento crea las cuentas si faltan y persiste el asiento completo.
|
||||||
|
func registrarAsiento(tx *gorm.DB, repo *repositorios.Repositorios, comprobanteTipo string, comprobanteID uint, lineas []lineaAsiento) error {
|
||||||
|
if len(lineas) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
asiento := &contabilidad.AsientoContable{
|
||||||
|
ComprobanteTipo: comprobanteTipo,
|
||||||
|
ComprobanteID: comprobanteID,
|
||||||
|
}
|
||||||
|
for _, linea := range lineas {
|
||||||
|
if linea.debe == 0 && linea.haber == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cuenta := &contabilidad.CuentaContable{Nombre: linea.cuenta, Tipo: linea.tipo}
|
||||||
|
if err := repo.Contabilidad.GuardarCuenta(tx, cuenta); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
asiento.Movimientos = append(asiento.Movimientos, contabilidad.MovimientoContable{
|
||||||
|
CuentaID: cuenta.ID,
|
||||||
|
Debe: redondearCantidad(linea.debe),
|
||||||
|
Haber: redondearCantidad(linea.haber),
|
||||||
|
Descripcion: linea.descripcion,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if len(asiento.Movimientos) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return repo.Contabilidad.CrearAsientoConMovimientos(tx, asiento)
|
||||||
|
}
|
||||||
|
|
||||||
|
// registrarLog guarda la auditoría fuera de la transacción: si falla, la
|
||||||
|
// operación de negocio ya confirmada no se revierte.
|
||||||
|
func registrarLog(repo *repositorios.Repositorios, empresaID, usuarioID uint, accion string, detalles []models_logs.LogDetalle) {
|
||||||
|
log, err := dto_directors.NewLogDirector().Custom(usuarioID, accion, detalles)
|
||||||
|
if err != nil {
|
||||||
|
applog.Printf("stock: no se pudo construir el log de %s: %v", accion, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.EmpresaID = empresaID
|
||||||
|
if err := repo.Logs.Crear(log, usuarioID); err != nil {
|
||||||
|
applog.Printf("stock: no se pudo registrar el log de %s: %v", accion, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package usuarios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ActualizarUsuario(c *gin.Context) {
|
||||||
|
id := c.Param("id")
|
||||||
|
|
||||||
|
var usuarioReq models_seguridad.Usuario
|
||||||
|
|
||||||
|
if err := c.ShouldBind(&usuarioReq); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if usuarioReq.Email == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "El email no puede estar vacío"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if usuarioReq.Name == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "El nombre no puede estar vacío"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
idconv, _ := strconv.ParseUint(id, 10, 64)
|
||||||
|
|
||||||
|
usuario, err := r.ObtenerRepositorios(c).Usuario.ObtenerPorID(uint(idconv))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
usuario.Email = usuarioReq.Email
|
||||||
|
usuario.Name = usuarioReq.Name
|
||||||
|
|
||||||
|
if err := r.ObtenerRepositorios(c).Usuario.Guardar(usuario); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewUsuarioDirector().DesdeUsuario(usuario)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package usuarios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
models_seguridad "repuestera_back/models/seguridad"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
|
||||||
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func CrearUsuario(c *gin.Context) {
|
||||||
|
var usuario models_seguridad.Usuario
|
||||||
|
if err := c.ShouldBind(&usuario); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.ObtenerRepositorios(c).Usuario.Crear(&usuario); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respuesta, err := dto_directors.NewUsuarioDirector().DesdeUsuario(&usuario)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, respuesta)
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package usuarios
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
r "repuestera_back/repositorios"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func EliminarUsuario(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 err := r.ObtenerRepositorios(c).Usuario.Eliminar(uint(id)); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "Usuario eliminado"})
|
||||||
|
}
|
||||||
Loaded 100 of 677 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user