Private
Public Access
Compare commits
247
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94a4e292c4 | ||
|
|
b6b2e7d465 | ||
|
|
77b27df6dd | ||
|
|
442140e412 | ||
|
|
a6112ca23e | ||
|
|
65540d8425 | ||
|
|
3db4c9fe62 | ||
|
|
dbc445ca56 | ||
|
|
ab59bd7043 | ||
|
|
1073c69d5c | ||
|
|
6ffc398b19 | ||
|
|
09830e15ec | ||
|
|
b68db07c92 | ||
|
|
7742618bf7 | ||
|
|
320cc9c241 | ||
|
|
fcf16df5d3 | ||
|
|
bc0db6dbee | ||
|
|
12276acbd8 | ||
|
|
3587a8dbc6 | ||
|
|
0f2c438643 | ||
|
|
bda647011e | ||
|
|
6f375cee45 | ||
|
|
ea009e276f | ||
|
|
a9ec514687 | ||
|
|
0160ba90d4 | ||
|
|
837fd8fa44 | ||
|
|
fe5b5d7a00 | ||
|
|
cc80dd1467 | ||
|
|
42bf987ffc | ||
|
|
3c4bc5c008 | ||
|
|
31f8b493d0 | ||
|
|
298f3c699c | ||
|
|
61baaf14f8 | ||
|
|
15dc28ca15 | ||
|
|
72f55e6773 | ||
|
|
c93199b636 | ||
|
|
9fa5cf63f9 | ||
|
|
67ca0c8222 | ||
|
|
c3f3513853 | ||
|
|
ee050fa0b3 | ||
|
|
3931d77c6b | ||
|
|
654c498fcb | ||
|
|
37d357357a | ||
|
|
5a8d4bc2d6 | ||
|
|
288a1e18f9 | ||
|
|
ce83c494c9 | ||
|
|
ff21aa4264 | ||
|
|
4e7992ba2b | ||
|
|
d75b99d3ee | ||
|
|
066be6c293 | ||
|
|
f0e5468079 | ||
|
|
2488c9f659 | ||
|
|
1a1aeaeba9 | ||
|
|
b6a71e158a | ||
|
|
3825492899 | ||
|
|
4704777050 | ||
|
|
f2cf7927eb | ||
|
|
7ba7d379ec | ||
|
|
52eb324514 | ||
|
|
1e23895e38 | ||
|
|
d9b76701e9 | ||
|
|
1948f1f426 | ||
|
|
405eaca25c | ||
|
|
37f1741a77 | ||
|
|
1e74e4363e | ||
|
|
6467147af5 | ||
|
|
0cc3db865d | ||
|
|
3079a70026 | ||
|
|
7a61f35682 | ||
|
|
61ca620c8e | ||
|
|
9205fea8d8 | ||
|
|
6ed8805e21 | ||
|
|
24e746b1b7 | ||
|
|
fec57d4886 | ||
|
|
fe1411437b | ||
|
|
770aa7d6ed | ||
|
|
4e082e8767 | ||
|
|
34ad4424f9 | ||
|
|
6dddfdb9ab | ||
|
|
3d52f00e24 | ||
|
|
6b9cd844e4 | ||
|
|
6c900f0afd | ||
|
|
b2df1a1204 | ||
|
|
cec07f51f9 | ||
|
|
00f140480d | ||
|
|
e784fb6ec8 | ||
|
|
441e2f5833 | ||
|
|
38afdcc742 | ||
|
|
5f741b3cc7 | ||
|
|
e7b5f5508f | ||
|
|
7d8b172ee3 | ||
|
|
2f1f294638 | ||
|
|
9807fce378 | ||
|
|
f06ea4007f | ||
|
|
6c6d9d9d97 | ||
|
|
5bb45c0077 | ||
|
|
6bb3326861 | ||
|
|
884fd6ff24 | ||
|
|
478fe331aa | ||
|
|
109642de39 | ||
|
|
2b31712f22 | ||
|
|
63689f0e9c | ||
|
|
a0ce1fb43b | ||
|
|
3a9dcdfce7 | ||
|
|
4625f75a45 | ||
|
|
9e847396e3 | ||
|
|
d0fbbd0a64 | ||
|
|
ee3935763c | ||
|
|
e0b9be6147 | ||
|
|
8d5e191d7d | ||
|
|
fce21846bc | ||
|
|
643242e4af | ||
|
|
dc76b638ab | ||
|
|
a6823302d5 | ||
|
|
2bbd8adbaf | ||
|
|
ff926c7914 | ||
|
|
95e09f0a3c | ||
|
|
87d21b2b50 | ||
|
|
83bc0b43b1 | ||
|
|
36144ae4da | ||
|
|
ff83e19710 | ||
|
|
bea97be3bf | ||
|
|
650d399494 | ||
|
|
4f60813f41 | ||
|
|
a142d0825a | ||
|
|
a0d899eb92 | ||
|
|
7a126a978f | ||
|
|
c6ee29fb9e | ||
|
|
46043796ae | ||
|
|
3d7944ffe6 | ||
|
|
f31ed062bd | ||
|
|
085d7fcd94 | ||
|
|
b78adf8488 | ||
|
|
3cd4218d54 | ||
|
|
2ab239e144 | ||
|
|
de28a83d5a | ||
|
|
de1ab28dc0 | ||
|
|
86a5313ba4 | ||
|
|
2c93c6ce8b | ||
|
|
f3a497d34d | ||
|
|
3f8adad0ab | ||
|
|
40153e702f | ||
|
|
312a4a2a95 | ||
|
|
814c2ba5e3 | ||
|
|
796322f2b0 | ||
|
|
9fa44cf89b | ||
|
|
6de6cee6ee | ||
|
|
8b056228e0 | ||
|
|
d333543619 | ||
|
|
7b89f1562e | ||
|
|
66d964e779 | ||
|
|
4cb7d17837 | ||
|
|
f0bb9beefd | ||
|
|
ef142dc60e | ||
|
|
737ebc4e3b | ||
|
|
59ffe628a9 | ||
|
|
0162022c82 | ||
|
|
e4ec11f5d8 | ||
|
|
ccaa1d35ab | ||
|
|
f143a92287 | ||
|
|
b393b37765 | ||
|
|
a85af05dae | ||
|
|
bd65f3477a | ||
|
|
99f0d7a11d | ||
|
|
56f959a63d | ||
|
|
b722522bf0 | ||
|
|
258d4f9f8f | ||
|
|
ab9a306a90 | ||
|
|
d53de5ae77 | ||
|
|
f978b5b2eb | ||
|
|
e0345bc3dd | ||
|
|
7ecbd2a643 | ||
|
|
a951d16883 | ||
|
|
80e148c0a1 | ||
|
|
2d85c6788a | ||
|
|
75d19b57c0 | ||
|
|
8305084db2 | ||
|
|
63f01c253f | ||
|
|
7f22570076 | ||
|
|
b0daadf5bf | ||
|
|
34cbb7c1d3 | ||
|
|
94191209cd | ||
|
|
6fa3849dc0 | ||
|
|
2a042857f5 | ||
|
|
799faab80b | ||
|
|
104b5d854b | ||
|
|
8ca58a42d8 | ||
|
|
0babe7b44e | ||
|
|
00e55d9146 | ||
|
|
4b18873cd3 | ||
|
|
2982ffb8fe | ||
|
|
4dc208f6fc | ||
|
|
7efee3c82e | ||
|
|
1f3e7ad7e3 | ||
|
|
a1169c7234 | ||
|
|
3f3175b615 | ||
|
|
4085adc6c2 | ||
|
|
724e984e0a | ||
|
|
cef5913b19 | ||
|
|
c1254d816a | ||
|
|
09084653ec | ||
|
|
23837de653 | ||
|
|
1eed19b604 | ||
|
|
59dd842d33 | ||
|
|
cd817dcc7b | ||
|
|
0fbacc1434 | ||
|
|
e86889dcaa | ||
|
|
fd19ddd246 | ||
|
|
66cf526979 | ||
|
|
88361d6939 | ||
|
|
009a32fcf0 | ||
|
|
9f0213c30b | ||
|
|
e469d82eb8 | ||
|
|
ae3435f2fd | ||
|
|
71d25dfbb3 | ||
|
|
ba220e40f8 | ||
|
|
246c511bc6 | ||
|
|
535c71dd76 | ||
|
|
8a1ea71805 | ||
|
|
152a40ca19 | ||
|
|
de33352618 | ||
|
|
e9cfb1adba | ||
|
|
e4c062e130 | ||
|
|
2840d48d1d | ||
|
|
10cf56856c | ||
|
|
d5dd03fff5 | ||
|
|
4c0dbaa91c | ||
|
|
73f9cef8ce | ||
|
|
2c9ffe9822 | ||
|
|
2f82feb518 | ||
|
|
e5ddf09575 | ||
|
|
b2b1eb7e59 | ||
|
|
5c44642aa5 | ||
|
|
d3cd3feb70 | ||
|
|
3e680cb21e | ||
|
|
a25afa1750 | ||
|
|
1c0da9d70f | ||
|
|
605d2e763f | ||
|
|
6d123ea01d | ||
|
|
c906dd4511 | ||
|
|
461c381f12 | ||
|
|
3af069e9e8 | ||
|
|
aac88856ac | ||
|
|
06ed4a518b | ||
|
|
f9cf001fca | ||
|
|
266365ae0f | ||
|
|
e345b4ccf8 |
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 ./...
|
||||
+15
@@ -1,3 +1,18 @@
|
||||
back/.env
|
||||
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
|
||||
front/.svelte-kit.old/
|
||||
node_modules/
|
||||
@@ -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
|
||||
FROM golang:1.26-alpine AS builder
|
||||
FROM golang:1.27-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -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"]
|
||||
+208
-57
@@ -1,73 +1,224 @@
|
||||
package config
|
||||
|
||||
import models_seguridad "repuestera_back/models/seguridad"
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
func InitPermisos(){
|
||||
var cantidadGrupos int64
|
||||
DB.Model(&models_seguridad.Grupo{}).Count(&cantidadGrupos)
|
||||
if (cantidadGrupos < 1) {
|
||||
DB.Create(&models_seguridad.Grupo{
|
||||
ID: 1,
|
||||
Nombre: "Admin",
|
||||
Descripcion: "Usuario Administrador Del sistema",
|
||||
})
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
|
||||
DB.Create(&models_seguridad.Grupo{
|
||||
ID: 2,
|
||||
Nombre: "Usuario",
|
||||
Descripcion: "Usuario Común",
|
||||
"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."},
|
||||
{14, "Generar Reporte de Stock", "stock/reportes", "Generar y consultar reportes de stock."},
|
||||
{15, "Gestión de Ventas y Facturación", "facturas", "Consultar y operar la facturación y ventas de la empresa."},
|
||||
{16, "Gestión de Descuentos", "descuentos", "Crear, editar y eliminar descuentos."},
|
||||
{17, "Gestión de Formas de Pago", "formas-pago", "Crear, editar y eliminar formas de pago."},
|
||||
}
|
||||
|
||||
// InitPermisos crea el catálogo global de permisos y garantiza que cada
|
||||
// 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 cantidadPermisos int64
|
||||
DB.Model(&models_seguridad.Permiso{}).Count(&cantidadPermisos)
|
||||
if (cantidadPermisos < 1){
|
||||
permisos := []models_seguridad.Permiso{
|
||||
{
|
||||
ID: 1,
|
||||
Nombre: "Gestion Permisos",
|
||||
Descripcion: "Crear, Editar y Eliminar Permisos.",
|
||||
Alias: "permisos",
|
||||
},
|
||||
{
|
||||
ID: 2,
|
||||
Nombre: "Gestion Grupos",
|
||||
Descripcion: "Crear, Editar y Eliminar Grupos.",
|
||||
Alias: "grupos",
|
||||
},
|
||||
{
|
||||
ID: 3,
|
||||
Nombre: "Gestion Usuarios",
|
||||
Descripcion: "Crear, Modificar y Eliminar Cuentas de Usuario.",
|
||||
Alias: "usuarios",
|
||||
},
|
||||
{
|
||||
ID: 4,
|
||||
Nombre: "Gestionar Repuestos",
|
||||
Descripcion: "Crear, Editar y Eliminar Repuestos.",
|
||||
Alias: "repuesto",
|
||||
},
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
DB.Create(&permisos)
|
||||
// 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")
|
||||
}
|
||||
|
||||
var admin models_seguridad.Grupo
|
||||
DB.First(&admin, 1)
|
||||
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
|
||||
}
|
||||
|
||||
DB.Model(&admin).Association("Permisos").Append(
|
||||
&permisos[0],
|
||||
&permisos[1],
|
||||
&permisos[2],
|
||||
)
|
||||
var usu models_seguridad.Grupo
|
||||
DB.First(&usu, 2)
|
||||
permisosAdmin := []uint{
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
6,
|
||||
5,
|
||||
7,
|
||||
9,
|
||||
10,
|
||||
11,
|
||||
12,
|
||||
13,
|
||||
14,
|
||||
16,
|
||||
}
|
||||
if err := asignarPermisosFaltantes(db, admin.ID, permisosAdmin); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
DB.Model(&usu).Association("Permisos").Append(
|
||||
&permisos[3],
|
||||
)
|
||||
permisosUsuario := []uint{
|
||||
4,
|
||||
5,
|
||||
9,
|
||||
10,
|
||||
11,
|
||||
12,
|
||||
13,
|
||||
}
|
||||
if err := asignarPermisosFaltantes(db, usuario.ID, permisosUsuario); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
DB.Model(&admin).Association("Grupos").Append(
|
||||
&usu,
|
||||
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,58 @@
|
||||
package almacen
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
dto "repuestera_back/dto/Almacenes"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ActualizarAlmacen(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
did := uint(id)
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Almacen
|
||||
almacen, err := repo.ObtenerPorID(did)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Almacén no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
var data dto.AlmacenDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
input, err := dto_directors.NewAlmacenDirector().Actualizar(data)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if existing, _ := repo.BuscarPorCodigo(input.Codigo); existing != nil && existing.ID != almacen.ID {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un almacén con ese código"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := repo.ActualizarCompleto(almacen, *input, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
actualizado, err := repo.ObtenerPorID(did)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, almacen)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, actualizado)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package almacen
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func AltaAlmacen(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Almacen
|
||||
almacen, err := repo.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Almacén no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
if !almacen.DeletedAt.Valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "El almacén no está eliminado"})
|
||||
return
|
||||
}
|
||||
|
||||
almacen.DeletedAt = gorm.DeletedAt{}
|
||||
if err := repo.Alta(almacen, *almacen, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package almacen
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
dto "repuestera_back/dto/Almacenes"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func CrearAlmacen(c *gin.Context) {
|
||||
var data dto.AlmacenDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
almacen, err := dto_directors.NewAlmacenDirector().Crear(data)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Almacen
|
||||
if _, err := repo.BuscarPorCodigo(almacen.Codigo); err == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un almacén con ese código"})
|
||||
return
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := repo.Crear(*almacen, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
creado, err := repo.BuscarPorCodigo(almacen.Codigo)
|
||||
if err != nil {
|
||||
c.Status(http.StatusCreated)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, creado)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package almacen
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func EliminarAlmacen(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios(c).Almacen.Baja(uint(id), c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package almacen
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"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)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package almacen
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ObtenerTodosLosAlmacenes(c *gin.Context) {
|
||||
almacenes, err := r.ObtenerRepositorios(c).Almacen.ObtenerTodos()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, almacenes)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package auth
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
|
||||
@@ -22,7 +23,7 @@ func CambiarContraseña(c *gin.Context) {
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -30,30 +31,47 @@ func CambiarContraseña(c *gin.Context) {
|
||||
authUserIDUint, _ := authUserID.(uint)
|
||||
|
||||
targetID := authUserIDUint
|
||||
if req.UserID != 0 {
|
||||
esPropia := req.UserID == 0 || req.UserID == authUserIDUint
|
||||
if !esPropia {
|
||||
targetID = req.UserID
|
||||
}
|
||||
|
||||
esAdmin := utils.UsuarioTienePermiso(c, 3)
|
||||
|
||||
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 := r.ObtenerRepositorios().Usuario.ObtenerPorID(targetID)
|
||||
repo := r.ObtenerRepositorios()
|
||||
user, err := repo.Usuario.ObtenerPorID(targetID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "usuario no encontrado"})
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
if !esAdmin {
|
||||
// Cambiar la contraseña propia siempre exige la contraseña actual.
|
||||
if esPropia {
|
||||
if req.OldPassword == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Se requiere la contraseña actual"})
|
||||
return
|
||||
}
|
||||
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, 3) || rolCaller.EsAdministrador()
|
||||
if !esAdmin {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "No tenés permiso para cambiar la contraseña de otro usuario"})
|
||||
return
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -64,7 +82,8 @@ func CambiarContraseña(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Usuario.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"})
|
||||
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,71 +1,105 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"repuestera_back/dto"
|
||||
"repuestera_back/jwtutils"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"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) {
|
||||
var req struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
var req loginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
email := strings.ToLower(strings.TrimSpace(req.Email))
|
||||
user, err := r.ObtenerRepositorios().Usuario.ObtenerPorEmail(email)
|
||||
repo := r.ObtenerRepositorios()
|
||||
user, err := repo.Usuario.ObtenerPorEmail(email)
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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 {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
refreshToken, err := generarToken(*user, 24*time.Hour)
|
||||
respuesta, err := services.ConstruirSesion(user.ID, empresaID)
|
||||
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
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.TokenResponse{
|
||||
AccessToken: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
TokenType: "Bearer",
|
||||
ExpiresIn: 900,
|
||||
})
|
||||
c.JSON(http.StatusOK, respuesta)
|
||||
}
|
||||
|
||||
func generarToken(user models_seguridad.Usuario, duration time.Duration) (string, error) {
|
||||
claims := jwt.MapClaims{
|
||||
"sub": user.ID,
|
||||
"email": user.Email,
|
||||
"name": user.Name,
|
||||
"exp": time.Now().Add(duration).Unix(),
|
||||
"iat": time.Now().Unix(),
|
||||
func seleccionarEmpresa(usuarioID, empresaID uint, slug string) (uint, error) {
|
||||
repo := r.ObtenerRepositorios()
|
||||
|
||||
if empresaID != 0 {
|
||||
membresia, err := repo.Empresa.Membresia(empresaID, usuarioID)
|
||||
if err != nil || !membresia.Activo {
|
||||
return 0, services.ErrSinAcceso
|
||||
}
|
||||
return empresaID, nil
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(jwtutils.JWTSecret)
|
||||
if slug != "" {
|
||||
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
|
||||
}
|
||||
+77
-41
@@ -2,64 +2,100 @@ package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"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/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func Me(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
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)
|
||||
userID, ok := c.Get("userID")
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "usuario no autenticado"})
|
||||
return
|
||||
}
|
||||
|
||||
sub, ok := claims["sub"].(string)
|
||||
id, ok := userID.(uint)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "token inválido"})
|
||||
return
|
||||
}
|
||||
userID, _ := strconv.ParseUint(sub, 10, 32)
|
||||
user, err := r.ObtenerRepositorios().Usuario.ObtenerPorID(uint(userID))
|
||||
|
||||
empresaID := utils.EmpresaID(c)
|
||||
sesion, err := services.ConstruirSesion(id, empresaID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.MeResponse{
|
||||
ID: user.ID,
|
||||
Email: user.Email,
|
||||
Name: user.Name,
|
||||
})
|
||||
respuesta, err := dto_directors.NewMeDirector().DesdeSesion(sesion)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
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,15 +1,14 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"repuestera_back/dto"
|
||||
"repuestera_back/jwtutils"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func Refresh(c *gin.Context) {
|
||||
@@ -21,52 +20,36 @@ func Refresh(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := req.RefreshToken
|
||||
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 refresh token"})
|
||||
claims, err := jwtutils.ValidarTokenDeTipo(req.RefreshToken, jwtutils.TokenTypeRefresh)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "refresh token inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
sub, ok := jwtutils.ClaimUint(claims, jwtutils.ClaimSubject)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "refresh token inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
sub, ok := claims["sub"].(float64)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||
return
|
||||
}
|
||||
user, err := r.ObtenerRepositorios().Usuario.ObtenerPorID(uint(sub))
|
||||
user, err := r.ObtenerRepositorios().Usuario.ObtenerPorID(sub)
|
||||
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
|
||||
}
|
||||
|
||||
accessToken, err := generarToken(*user, 15*time.Minute)
|
||||
empresaID, _ := jwtutils.ClaimUint(claims, jwtutils.ClaimEmpresaID)
|
||||
|
||||
respuesta, err := services.ConstruirSesion(user.ID, empresaID)
|
||||
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
|
||||
}
|
||||
|
||||
newRefreshToken, err := generarToken(*user, 24*time.Hour)
|
||||
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,
|
||||
})
|
||||
c.JSON(http.StatusOK, respuesta)
|
||||
}
|
||||
@@ -4,9 +4,10 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"repuestera_back/dto"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
@@ -14,9 +15,12 @@ import (
|
||||
|
||||
func Register(c *gin.Context) {
|
||||
var req struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
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 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
@@ -24,44 +28,60 @@ func Register(c *gin.Context) {
|
||||
}
|
||||
|
||||
email := strings.ToLower(strings.TrimSpace(req.Email))
|
||||
repo := r.ObtenerRepositorios()
|
||||
|
||||
if _, err := r.ObtenerRepositorios().Usuario.ObtenerPorEmail(email); err == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "El email ya esta registrado"})
|
||||
if _, err := repo.Usuario.ObtenerPorEmail(email); err == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "El email ya está registrado"})
|
||||
return
|
||||
}
|
||||
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
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
|
||||
}
|
||||
|
||||
user := models_seguridad.Usuario{
|
||||
Email: email,
|
||||
Password: string(hashedPassword),
|
||||
Name: req.Name,
|
||||
Name: strings.TrimSpace(req.Name),
|
||||
Activo: true,
|
||||
}
|
||||
|
||||
//checkeo para ver si hay usuarios añadidos
|
||||
var cantUsuarios int64
|
||||
r.ObtenerRepositorios().Usuario.CantidadUsuarios(&cantUsuarios)
|
||||
if (cantUsuarios < 1){
|
||||
admin, err := r.ObtenerRepositorios().Grupo.ObtenerPorID(1)
|
||||
if err != nil{
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Hay un problema con la base de datos: Faltan Grupos?"})
|
||||
return
|
||||
}
|
||||
user.Grupos = append(user.Grupos, *admin)
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Usuario.Crear(&user); err != nil {
|
||||
if err := repo.Usuario.Crear(&user); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, dto.RegisterResponse{
|
||||
ID: user.ID,
|
||||
Email: user.Email,
|
||||
Name: user.Name,
|
||||
})
|
||||
nombreEmpresa := strings.TrimSpace(req.EmpresaNombre)
|
||||
if nombreEmpresa == "" {
|
||||
nombreEmpresa = "Empresa de " + 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,58 @@
|
||||
package descuento
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
dto "repuestera_back/dto/Descuentos"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ActualizarDescuento(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
did := uint(id)
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Descuento
|
||||
descuento, err := repo.ObtenerPorID(did)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Descuento no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
var data dto.DescuentoDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
input, err := dto_directors.NewDescuentoDirector().Actualizar(data, descuento.Activo)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if existing, _ := repo.ObtenerPorNombre(input.Nombre); existing != nil && existing.ID != descuento.ID {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un descuento con ese nombre"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := repo.ActualizarCompleto(descuento, *input, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
actualizado, err := repo.ObtenerPorID(did)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, descuento)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, actualizado)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package descuento
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// AltaDescuento reactiva un descuento dado de baja lógicamente.
|
||||
func AltaDescuento(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Descuento
|
||||
descuento, err := repo.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Descuento no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
if !descuento.DeletedAt.Valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "El descuento no está eliminado"})
|
||||
return
|
||||
}
|
||||
|
||||
descuento.DeletedAt = gorm.DeletedAt{}
|
||||
if err := repo.Alta(descuento, *descuento, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package descuento
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
dto "repuestera_back/dto/Descuentos"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func CrearDescuento(c *gin.Context) {
|
||||
var data dto.DescuentoDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
descuento, err := dto_directors.NewDescuentoDirector().Crear(data)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c).Descuento
|
||||
if _, err := repo.ObtenerPorNombre(descuento.Nombre); err == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe un descuento con ese nombre"})
|
||||
return
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := repo.Crear(*descuento, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
creado, err := repo.ObtenerPorNombre(descuento.Nombre)
|
||||
if err != nil {
|
||||
c.Status(http.StatusCreated)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, creado)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package descuento
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func EliminarDescuento(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios(c).Descuento.Baja(uint(id), c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package descuento
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func ObtenerDescuentos(c *gin.Context) {
|
||||
descuentos, err := r.ObtenerRepositorios(c).Descuento.ListarActivos()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, descuentos)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package descuento
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ObtenerTodosLosDescuentos lista todos los descuentos de la empresa,
|
||||
// incluyendo los inactivos y los dados de baja, para la pantalla de gestión.
|
||||
func ObtenerTodosLosDescuentos(c *gin.Context) {
|
||||
descuentos, err := r.ObtenerRepositorios(c).Descuento.ObtenerTodos()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, descuentos)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package empresa
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
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"`
|
||||
EmailAlertaStock *[]string `json:"email_alerta_stock"`
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
if strings.TrimSpace(req.Nombre) != "" {
|
||||
empresa.Nombre = strings.TrimSpace(req.Nombre)
|
||||
}
|
||||
if strings.TrimSpace(req.Slug) != "" {
|
||||
empresa.Slug = strings.TrimSpace(req.Slug)
|
||||
}
|
||||
if strings.TrimSpace(req.Cuit) != "" {
|
||||
cuit := strings.TrimSpace(req.Cuit)
|
||||
empresa.Cuit = &cuit
|
||||
}
|
||||
if req.EmailAlertaStock != nil {
|
||||
limpios := make([]string, 0, len(*req.EmailAlertaStock))
|
||||
vistos := make(map[string]bool)
|
||||
for _, email := range *req.EmailAlertaStock {
|
||||
email = strings.TrimSpace(email)
|
||||
if email == "" || vistos[email] {
|
||||
continue
|
||||
}
|
||||
vistos[email] = true
|
||||
limpios = append(limpios, email)
|
||||
}
|
||||
empresa.EmailAlertaStock = limpios
|
||||
}
|
||||
|
||||
if err := repo.Empresa.Actualizar(empresa, *empresa); 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,8 @@
|
||||
package factura
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
// Esto tendria que cancelar la factura en caso de que no este pagada y ademas crear una nota de credito
|
||||
func CancelarFactura(c *gin.Context) {
|
||||
c.Status(200)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
func CrearFactura(c *gin.Context) {
|
||||
var data dto.CrearFacturaDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resultado, err := services.CrearFactura(
|
||||
repositorios.BaseDeDatos(),
|
||||
repositorios.ObtenerRepositorios(c),
|
||||
utils.EmpresaID(c),
|
||||
c.GetUint("userID"),
|
||||
data,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, resultado)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
)
|
||||
|
||||
// EnviarEmailComprobante envía por email el comprobante de venta al cliente
|
||||
// de la factura indicada. Requiere que el cliente tenga email registrado.
|
||||
func EnviarEmailComprobante(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c)
|
||||
factura, err := repo.Factura.ObtenerConRelaciones(uint(id))
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "factura no encontrada"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if factura.Cliente.Email == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "el cliente no tiene email registrado"})
|
||||
return
|
||||
}
|
||||
|
||||
// Nombres reales de repuestos desde la base de datos.
|
||||
nombres := make(map[uint64]string, len(factura.Detalles))
|
||||
for _, d := range factura.Detalles {
|
||||
repuesto, err := repo.Repuesto.ObtenerPorID(uint(d.RepuestoID))
|
||||
if err == nil && repuesto != nil && *repuesto != nil {
|
||||
nombres[d.RepuestoID] = (*repuesto).Nombre
|
||||
} else {
|
||||
nombres[d.RepuestoID] = fmt.Sprintf("Repuesto %d", d.RepuestoID)
|
||||
}
|
||||
}
|
||||
|
||||
// Pagos realizados de esta factura.
|
||||
pagos, err := repo.Pago.ListarPorFactura(factura.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
mensaje, err := dto_directors.NewEmailDirector().ComprobanteVenta(
|
||||
factura, nombres, pagos, factura.Cliente.Email,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := c.GetUint("userID")
|
||||
if !services.EnviarEmail(*mensaje, userID) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "no se pudo enviar el email"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"mensaje": "email enviado correctamente"})
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package factura
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
func ModificarFactura(c *gin.Context) {
|
||||
c.Status(200)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
dto_facturas "repuestera_back/dto/Facturas"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
// ObtenerComprobante devuelve el detalle de una factura junto con sus pagos,
|
||||
// listo para renderizar el comprobante de venta.
|
||||
func ObtenerComprobante(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c)
|
||||
factura, err := repo.Factura.ObtenerConRelaciones(uint(id))
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "factura no encontrada"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
pagos, err := repo.Pago.ListarPorFactura(factura.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
respuesta, err := dto_directors.NewFacturaDirector().DesdeFactura(factura)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Los nombres se resuelven desde la base de datos: las facturas anteriores
|
||||
// al campo RepuestoNombre no lo tienen guardado en el detalle.
|
||||
for i := range respuesta.Detalles {
|
||||
detalle := &respuesta.Detalles[i]
|
||||
repuesto, err := repo.Repuesto.ObtenerPorID(uint(detalle.RepuestoID))
|
||||
if err == nil && repuesto != nil && *repuesto != nil {
|
||||
detalle.RepuestoNombre = (*repuesto).Nombre
|
||||
} else {
|
||||
detalle.RepuestoNombre = fmt.Sprintf("Repuesto %d", detalle.RepuestoID)
|
||||
}
|
||||
}
|
||||
|
||||
pagosResumen := make([]dto_facturas.PagoResumen, 0, len(pagos))
|
||||
for _, p := range pagos {
|
||||
forma := ""
|
||||
if p.FormaDePago.ID != 0 {
|
||||
forma = p.FormaDePago.Descripcion
|
||||
}
|
||||
pagosResumen = append(pagosResumen, dto_facturas.PagoResumen{
|
||||
ID: p.ID,
|
||||
FacturaID: p.FacturaID,
|
||||
FormaDePagoID: p.FormaDePagoID,
|
||||
FormaDePago: forma,
|
||||
Importe: p.Importe,
|
||||
Fecha: p.Fecha,
|
||||
Observacion: p.Observacion,
|
||||
})
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto_facturas.ComprobanteResponse{
|
||||
FacturaResponse: respuesta,
|
||||
Pagos: pagosResumen,
|
||||
})
|
||||
}
|
||||
@@ -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,67 @@
|
||||
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"),
|
||||
Estado: c.Query("estado"),
|
||||
}
|
||||
|
||||
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,54 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
// ObtenerStockDisponible devuelve por repuesto y almacén cuánto stock se puede
|
||||
// vender. Se usa en el alta de factura para mostrar la disponibilidad antes de
|
||||
// vender. Si no se pasa almacenId, devuelve el stock de toda la empresa.
|
||||
func ObtenerStockDisponible(c *gin.Context) {
|
||||
almacenID := uint(0)
|
||||
if raw := c.Query("almacenId"); raw != "" {
|
||||
id, err := strconv.ParseUint(raw, 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "almacenId inválido"})
|
||||
return
|
||||
}
|
||||
almacenID = uint(id)
|
||||
}
|
||||
|
||||
stocks, err := r.ObtenerRepositorios(c).Stock.ListarStockPorAlmacen(almacenID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
respuesta := make([]dto.StockDisponibleResponse, 0, len(stocks))
|
||||
for _, stock := range stocks {
|
||||
disponible := stock.Cantidad - stock.CantidadReservada
|
||||
if disponible < 0 {
|
||||
disponible = 0
|
||||
}
|
||||
respuesta = append(respuesta, dto.StockDisponibleResponse{
|
||||
RepuestoID: stock.RepuestoID,
|
||||
AlmacenID: stock.AlmacenID,
|
||||
Cantidad: redondearStock(stock.Cantidad),
|
||||
CantidadReservada: redondearStock(stock.CantidadReservada),
|
||||
Disponible: redondearStock(disponible),
|
||||
})
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, respuesta)
|
||||
}
|
||||
|
||||
func redondearStock(valor float64) float64 {
|
||||
return math.Round(valor*1000) / 1000
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
// RegistrarPago registra un cobro sobre una factura existente.
|
||||
func RegistrarPago(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
var data dto.RegistrarPagoDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resultado, err := services.RegistrarPagoFactura(
|
||||
repositorios.BaseDeDatos(),
|
||||
repositorios.ObtenerRepositorios(c),
|
||||
utils.EmpresaID(c),
|
||||
c.GetUint("userID"),
|
||||
uint(id),
|
||||
data,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, resultado)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package formapago
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"repuestera_back/models"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ActualizarFormaDePago actualiza una forma de pago existente.
|
||||
func ActualizarFormaDePago(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
if id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||
return
|
||||
}
|
||||
|
||||
// Obtener la forma de pago actual
|
||||
fp, err := r.ObtenerRepositorios(c).FormaDePago.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Forma de pago no encontrada"})
|
||||
return
|
||||
}
|
||||
|
||||
var input models.FormaDePago
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if input.Descripcion == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "La descripción no puede estar vacía"})
|
||||
return
|
||||
}
|
||||
|
||||
// Verificar que no exista otra forma de pago con la misma descripción
|
||||
if existing, _ := r.ObtenerRepositorios(c).FormaDePago.ObtenerPorDescripcion(input.Descripcion); existing != nil && existing.ID != fp.ID {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe una forma de pago con esa descripción"})
|
||||
return
|
||||
}
|
||||
|
||||
uid := c.GetUint("userID")
|
||||
if err := r.ObtenerRepositorios(c).FormaDePago.Actualizar(fp, input, uid); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, fp)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package formapago
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func AltaFormaDePago(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
if id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||
return
|
||||
}
|
||||
|
||||
uid := c.GetUint("userID")
|
||||
fp, err := r.ObtenerRepositorios(c).FormaDePago.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Forma de pago no encontrada"})
|
||||
return
|
||||
}
|
||||
|
||||
if !fp.DeletedAt.Valid {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Forma de pago no está eliminada"})
|
||||
return
|
||||
}
|
||||
|
||||
fp.DeletedAt = gorm.DeletedAt{}
|
||||
if err := r.ObtenerRepositorios(c).FormaDePago.Alta(fp, *fp, uid); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package formapago
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"repuestera_back/models"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func CrearFormaDePago(c *gin.Context) {
|
||||
var fp models.FormaDePago
|
||||
if err := c.ShouldBindJSON(&fp); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if fp.Descripcion == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "La descripción es obligatoria"})
|
||||
return
|
||||
}
|
||||
|
||||
repo := r.ObtenerRepositorios(c).FormaDePago
|
||||
if _, err := repo.ObtenerPorDescripcion(fp.Descripcion); err == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "ya existe una forma de pago con esa descripción"})
|
||||
return
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := repo.Crear(fp, c.GetUint("userID")); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusCreated)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package formapago
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func EliminarFormaDePago(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
if id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||
return
|
||||
}
|
||||
|
||||
uid := c.GetUint("userID")
|
||||
err = r.ObtenerRepositorios(c).FormaDePago.Baja(uint(id), uid)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package formapago
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ObtenerFormaDePago(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
if id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||
return
|
||||
}
|
||||
|
||||
fp, err := r.ObtenerRepositorios(c).FormaDePago.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Forma de pago no encontrada"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, fp)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package formapago
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"repuestera_back/models"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func ObtenerFormasPago(c *gin.Context) {
|
||||
repo := r.ObtenerRepositorios(c).FormaDePago
|
||||
|
||||
var (
|
||||
formas []models.FormaDePago
|
||||
err error
|
||||
)
|
||||
if c.Query("activas") == "true" {
|
||||
formas, err = repo.ListarActivas()
|
||||
} else {
|
||||
formas, err = repo.ObtenerTodos()
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, formas)
|
||||
}
|
||||
@@ -2,9 +2,11 @@ package grupo
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -15,7 +17,7 @@ func ActualizarGrupo(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
grupo, err := r.ObtenerRepositorios().Grupo.ObtenerPorID(uint(id))
|
||||
grupo, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo no encontrado"})
|
||||
return
|
||||
@@ -25,6 +27,16 @@ func ActualizarGrupo(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
r.ObtenerRepositorios().Grupo.Actualizar(grupo, input)
|
||||
c.JSON(http.StatusOK, grupo)
|
||||
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)
|
||||
}
|
||||
@@ -18,7 +18,7 @@ func AgregarGrupoAUsuario(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Usuario.AgregarGrupoAUsuario(req.UsuarioID, req.GrupoID); err != nil {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ func AgregarPermisoAGrupo(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Grupo.AgregarPermiso(uint(grupoID), req.PermisoID); err != nil {
|
||||
if err := r.ObtenerRepositorios(c).Grupo.AgregarPermiso(uint(grupoID), req.PermisoID); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ func AgregarSubGrupo(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Grupo.AgregarSubGrupo(uint(padreID), req.ChildGroupID); err != nil {
|
||||
if err := r.ObtenerRepositorios(c).Grupo.AgregarSubGrupo(uint(padreID), req.ChildGroupID); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package grupo
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
@@ -14,9 +16,16 @@ func CrearGrupo(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if err := r.ObtenerRepositorios().Grupo.Crear(&grupo); err != nil {
|
||||
if err := r.ObtenerRepositorios(c).Grupo.Crear(&grupo); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, grupo)
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -14,7 +14,7 @@ func EliminarGrupo(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
if err := r.ObtenerRepositorios().Grupo.Eliminar(uint(id)); err != nil {
|
||||
if err := r.ObtenerRepositorios(c).Grupo.Eliminar(uint(id)); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package grupo
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
dto_builders "repuestera_back/dto/Builders"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
@@ -15,15 +15,17 @@ func ObtenerGrupo(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
grupo, err := r.ObtenerRepositorios().Grupo.ObtenerPorIDConRelaciones(uint(id), true)
|
||||
grupo, err := r.ObtenerRepositorios(c).Grupo.ObtenerPorIDConRelaciones(uint(id), true)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Grupo no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
dto := dto_builders.
|
||||
NewGrupoSimpleBuilder(grupo).
|
||||
Build()
|
||||
respuesta, err := dto_directors.NewGrupoSimpleDirector().DesdeGrupo(grupo)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto)
|
||||
c.JSON(http.StatusOK, respuesta)
|
||||
}
|
||||
@@ -2,16 +2,25 @@ 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().Grupo.ObtenerTodosConRelaciones()
|
||||
grupos, err := r.ObtenerRepositorios(c).Grupo.ObtenerTodosConRelaciones()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, grupos)
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -2,9 +2,11 @@ package grupo
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -13,14 +15,21 @@ func ObtenerGruposDeUsuario(c *gin.Context) {
|
||||
|
||||
usuarioID, err := strconv.ParseUint(usuarioIDStr, 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"error": "id invalido"})
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "id invalido"})
|
||||
return
|
||||
}
|
||||
|
||||
grupos, err := r.ObtenerRepositorios().Usuario.ObtenerGruposPorUsuarioID(uint(usuarioID))
|
||||
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
|
||||
}
|
||||
c.JSON(http.StatusOK, grupos)
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -2,8 +2,9 @@ package grupo
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"repuestera_back/dto"
|
||||
dto_builders "repuestera_back/dto/Builders"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -31,7 +32,7 @@ func ObtenerGruposYPermisosPorEmail(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
usuario, err := r.ObtenerRepositorios().Usuario.ObtenerPorEmailConGrupos(request.Email)
|
||||
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"})
|
||||
@@ -41,20 +42,27 @@ func ObtenerGruposYPermisosPorEmail(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
grupos := make([]dto.GrupoSimpleDTO, 0, len(usuario.Grupos))
|
||||
grupos := make([]*models_seguridad.Grupo, 0, len(usuario.Grupos))
|
||||
for i := range usuario.Grupos {
|
||||
grupoCompleto, err := r.ObtenerRepositorios().Grupo.ObtenerPorIDConRelaciones(usuario.Grupos[i].ID, true)
|
||||
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
|
||||
}
|
||||
g := dto_builders.NewGrupoSimpleBuilder(grupoCompleto).Build()
|
||||
g.ID = grupoCompleto.ID
|
||||
grupos = append(grupos, g)
|
||||
grupos = append(grupos, grupoCompleto)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.GruposYPermisosResponse{
|
||||
Email: usuario.Email,
|
||||
Groups: grupos,
|
||||
})
|
||||
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)
|
||||
}
|
||||
@@ -18,7 +18,7 @@ func QuitarGrupoAUsuario(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Usuario.QuitarGrupoDeUsuario(req.UsuarioID, req.GrupoID); err != nil {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ func QuitarPermisoAGrupo(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Grupo.QuitarPermiso(uint(grupoID), req.PermisoID); err != nil {
|
||||
if err := r.ObtenerRepositorios(c).Grupo.QuitarPermiso(uint(grupoID), req.PermisoID); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ func QuitarSubGrupo(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Grupo.QuitarSubGrupo(uint(padreID), req.ChildGroupID); err != nil {
|
||||
if err := r.ObtenerRepositorios(c).Grupo.QuitarSubGrupo(uint(padreID), req.ChildGroupID); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -2,9 +2,11 @@ package permiso
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -15,7 +17,7 @@ func ActualizarPermiso(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
permiso, err := r.ObtenerRepositorios().Permiso.ObtenerPorID(uint(id))
|
||||
permiso, err := r.ObtenerRepositorios(c).Permiso.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Permiso no encontrado"})
|
||||
return
|
||||
@@ -25,6 +27,16 @@ func ActualizarPermiso(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
r.ObtenerRepositorios().Permiso.Actualizar(permiso, input)
|
||||
c.JSON(http.StatusOK, permiso)
|
||||
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)
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package permiso
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
r "repuestera_back/repositorios"
|
||||
|
||||
@@ -14,9 +16,16 @@ func CrearPermiso(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if err := r.ObtenerRepositorios().Permiso.Crear(&permiso); err != nil {
|
||||
if err := r.ObtenerRepositorios(c).Permiso.Crear(&permiso); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, permiso)
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -14,7 +14,7 @@ func EliminarPermiso(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalido"})
|
||||
return
|
||||
}
|
||||
if err := r.ObtenerRepositorios().Permiso.Eliminar(uint(id)); err != nil {
|
||||
if err := r.ObtenerRepositorios(c).Permiso.Eliminar(uint(id)); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2,16 +2,25 @@ 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().Permiso.ObtenerTodos()
|
||||
permisos, err := r.ObtenerRepositorios(c).Permiso.ObtenerTodos()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, permisos)
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
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"
|
||||
"net/http"
|
||||
"repuestera_back/dto"
|
||||
r "repuestera_back/repositorios"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func ObtenerPermisosUsuario(c *gin.Context) {
|
||||
@@ -16,7 +18,7 @@ func ObtenerPermisosUsuario(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
usuario, err := r.ObtenerRepositorios().Usuario.PrecargarGruposPermisosPorID(uint(userID))
|
||||
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"})
|
||||
@@ -26,25 +28,11 @@ func ObtenerPermisosUsuario(c *gin.Context) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
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, dto.PermisosUsuarioResponse{Permisos: permisos})
|
||||
c.JSON(http.StatusOK, respuesta)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
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"`
|
||||
EmailAlertaStock *[]string `json:"email_alerta_stock"`
|
||||
Activa *bool `json:"activa"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
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.EmailAlertaStock != nil {
|
||||
limpios := make([]string, 0, len(*req.EmailAlertaStock))
|
||||
vistos := make(map[string]bool)
|
||||
for _, email := range *req.EmailAlertaStock {
|
||||
email = strings.TrimSpace(email)
|
||||
if email == "" || vistos[email] {
|
||||
continue
|
||||
}
|
||||
vistos[email] = true
|
||||
limpios = append(limpios, email)
|
||||
}
|
||||
empresa.EmailAlertaStock = limpios
|
||||
}
|
||||
if req.Activa != nil {
|
||||
empresa.Activa = *req.Activa
|
||||
}
|
||||
|
||||
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,124 @@
|
||||
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"`
|
||||
EmailAlertaStock []string `json:"email_alerta_stock"`
|
||||
OwnerEmail string `json:"owner_email" binding:"required,email"`
|
||||
OwnerName string `json:"owner_name"`
|
||||
OwnerPassword string `json:"owner_password"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
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
|
||||
}
|
||||
limpios := make([]string, 0, len(req.EmailAlertaStock))
|
||||
vistos := make(map[string]bool)
|
||||
for _, email := range req.EmailAlertaStock {
|
||||
email = strings.TrimSpace(email)
|
||||
if email == "" || vistos[email] {
|
||||
continue
|
||||
}
|
||||
vistos[email] = true
|
||||
limpios = append(limpios, email)
|
||||
}
|
||||
empresa.EmailAlertaStock = limpios
|
||||
|
||||
if err := repo.Empresa.Crear(&empresa, owner.ID); err != nil {
|
||||
if creado {
|
||||
_ = 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)
|
||||
}
|
||||
@@ -1,9 +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){
|
||||
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)
|
||||
}
|
||||
@@ -2,37 +2,40 @@ package repuestos
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
dto_builders "repuestera_back/dto/Builders"
|
||||
dto_directors "repuestera_back/dto/Builders/Directors"
|
||||
dto "repuestera_back/dto/Repuestos"
|
||||
"repuestera_back/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
|
||||
|
||||
func CrearRepuesto(c *gin.Context){
|
||||
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
|
||||
}
|
||||
var marca models.Marca
|
||||
marca = models.Marca{Nombre: data.Marca, ID: data.Marca[:3]}
|
||||
|
||||
if err := r.ObtenerRepositorios().Marca.CrearFaltante(marca); err != nil {
|
||||
marca, err := r.ObtenerRepositorios(c).Marca.ObtenerPorID(data.Marca)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
repuesto := dto_builders.NewRepuestoBuilder().
|
||||
ConDto(data).
|
||||
ConMarca(marca.ID).
|
||||
Build()
|
||||
if err := r.ObtenerRepositorios(c).Marca.CrearFaltante(*marca); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Repuesto.Crear(&repuesto); err != nil {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -8,19 +8,20 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func EliminarRepuesto(c *gin.Context){
|
||||
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){
|
||||
if id < 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID no puede ser menor que 1"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.ObtenerRepositorios().Repuesto.Eliminar(uint(id)); err != nil {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -9,14 +9,14 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ObtenerRepuesto(c *gin.Context){
|
||||
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().Repuesto.ObtenerPorID(uint(id))
|
||||
repuesto, err := r.ObtenerRepositorios(c).Repuesto.ObtenerPorID(uint(id))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func ObtenerRepuestos(c *gin.Context){
|
||||
repuestos, err := r.ObtenerRepositorios().Repuesto.ObtenerTodos()
|
||||
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
|
||||
|
||||
Loaded 100 of 786 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user