Skip to content

Commit

Permalink
Trigger bitacora operador eliminado y bitacora clientes creada
Browse files Browse the repository at this point in the history
  • Loading branch information
Drago177 committed Nov 22, 2024
1 parent 7a47c76 commit 399cc11
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 11 deletions.
2 changes: 2 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from extensiones import db, bcrypt
from routes.asig_operador_vehiculo import asig_operador_vehiculo
from routes.asignaciones_repuestos import asignaciones_repuestos
from routes.bitacora_clientes import bitacora_clientes
from routes.marcas_vehiculos import marcas_vehiculos
from routes.modelos_vehiculos import modelos_vehiculos
from routes.ordenes_compra import ordenes_compras
Expand Down Expand Up @@ -61,6 +62,7 @@ def load_user(user_id):
app.register_blueprint(modelos_vehiculos)
app.register_blueprint(proveedores_repuesto)
app.register_blueprint(clientes)
app.register_blueprint(bitacora_clientes)

def crear_triggers():
with open('triggers.sql', 'r') as file:
Expand Down
55 changes: 55 additions & 0 deletions models/bitacora_asig_clientes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
from datetime import datetime
from sqlalchemy import ForeignKey, func
from sqlalchemy.orm import Mapped, mapped_column, relationship
from extensiones import db
from models.cliente import Cliente
from models.usuario import Usuario
from models.vehiculo import Vehiculo

class BitacoraAsigClientes(db.Model):
id: Mapped[int] = mapped_column(primary_key=True)
id_cliente: Mapped[int] = mapped_column(ForeignKey('cliente.id'))
id_operador: Mapped[int] = mapped_column(ForeignKey('usuario.id'))
id_vehiculo: Mapped[int] = mapped_column(ForeignKey('vehiculo.id'))
fecha_hora_asignacion: Mapped[datetime] = mapped_column(default=func.now())
fecha_hora_desasignacion: Mapped[datetime] = mapped_column(nullable=True)

cliente: Mapped['Cliente'] = relationship('Cliente', backref='asig_operadores')
operador: Mapped['Usuario'] = relationship('Usuario', backref='asig_clientes')
vehiculo: Mapped['Vehiculo'] = relationship('Vehiculo', backref='bit_asig')

def serialize(self):
return {
'id': self.id,
'fecha_hora_asignacion': self.fecha_hora_asignacion,
'fecha_hora_desasignacion': self.fecha_hora_desasignacion,
'cliente': self.cliente.serialize() if self.cliente else None,
'operador': self.operador.serialize() if self.operador else None,
'vehiculo': self.vehiculo.serialize() if self.vehiculo else None
}

@staticmethod
def listar():
return BitacoraAsigClientes.query.all()

@staticmethod
def listar_json():
return [asignacion.serialize() for asignacion in BitacoraAsigClientes.listar()]

@staticmethod
def agregar(asignacion):
db.session.add(asignacion)
db.session.commit()

@staticmethod
def eliminar(asignacion):
db.session.delete(asignacion)
db.session.commit()

@staticmethod
def actualizar():
db.session.commit()

@staticmethod
def encontrarPorId(id):
return db.session.get(BitacoraAsigClientes, id)
2 changes: 1 addition & 1 deletion models/cliente.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
class Cliente(db.Model):
id: Mapped[int] = mapped_column(primary_key=True)
id_operador:Mapped[int] = mapped_column(ForeignKey('usuario.id'), nullable=True)
cuit: Mapped[int] = mapped_column(unique=True)
cuit: Mapped[str] = mapped_column(unique=True)
nombre: Mapped[str] = mapped_column(nullable=True)
direccion: Mapped[str] = mapped_column(nullable=True)
email: Mapped[str] = mapped_column(nullable=True)
Expand Down
17 changes: 17 additions & 0 deletions routes/bitacora_clientes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from flask import Blueprint

from models.bitacora_asig_clientes import BitacoraAsigClientes

bitacora_clientes = Blueprint('bitacora_clientes', __name__)

@bitacora_clientes.route('/bitacora/clientes/')
def listar_bitacora():
return BitacoraAsigClientes.listar_json()

@bitacora_clientes.route('/bitacora/clientes/<int:id>', methods=['DELETE'])
def baja_bitacora(id):
asignacion = BitacoraAsigClientes.encontrarPorId(id)
if asignacion is None:
return 'Asignación no encontrada', 404
BitacoraAsigClientes.eliminar(asignacion)
return 'OK', 202
25 changes: 15 additions & 10 deletions triggers.sql
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,33 @@ BEFORE UPDATE ON repuesto
FOR EACH ROW
EXECUTE FUNCTION generarOrdenCompra();

CREATE OR REPLACE FUNCTION actualizar_bitacora_asignaciones() RETURNS TRIGGER AS $$
CREATE OR REPLACE FUNCTION actualizar_bitacora_asig_clientes() RETURNS TRIGGER AS $$
DECLARE
id_vehic_aux int;
BEGIN
IF NEW.id_operador IS NOT NULL THEN
INSERT INTO bitacora_asignaciones (id_vehiculo, id_usuario, fecha_hora_asignacion)
VALUES (NEW.id, NEW.id_operador, NOW());
SELECT id
INTO id_vehic_aux
FROM vehiculo
WHERE id_operador = NEW.id_operador;

INSERT INTO bitacora_asig_clientes (id_cliente, id_operador, id_vehiculo,fecha_hora_asignacion)
VALUES (NEW.id, NEW.id_operador, id_vehic_aux, NOW());
ELSE
UPDATE bitacora_asignaciones
UPDATE bitacora_asig_clientes
SET fecha_hora_desasignacion = NOW()
WHERE id = (SELECT id
FROM bitacora_asignaciones
WHERE id_vehiculo = NEW.id
ORDER BY fecha_hora_desasignacion DESC
FROM bitacora_asig_clientes
WHERE id_cliente = NEW.id
ORDER BY fecha_hora_asignacion DESC
LIMIT 1
);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE TRIGGER actualizar_bitacora_asignaciones_trg
AFTER UPDATE ON vehiculo
CREATE OR REPLACE TRIGGER actualizar_bitacora_asig_clientes_trg
AFTER UPDATE ON cliente
FOR EACH ROW
WHEN (OLD.id_operador IS DISTINCT FROM NEW.id_operador)
EXECUTE FUNCTION actualizar_bitacora_asignaciones();
EXECUTE FUNCTION actualizar_bitacora_asig_clientes();

0 comments on commit 399cc11

Please sign in to comment.