Enhance Shift and TimeSchedule models with additional fields and relationships; update shift creation and update routes to handle new attributes and associations.
This commit is contained in:
parent
ebba27e5a2
commit
9daa2ea317
@ -2,28 +2,39 @@ from datetime import datetime
|
|||||||
from sqlalchemy import Column, Integer, String, ForeignKey, Time
|
from sqlalchemy import Column, Integer, String, ForeignKey, Time
|
||||||
from sqlalchemy.orm import relationship
|
from sqlalchemy.orm import relationship
|
||||||
from extensions import db
|
from extensions import db
|
||||||
|
from models.time_schedule import TimeSchedule # Certo!
|
||||||
|
|
||||||
|
# 🔗 Tabela de associação many-to-many
|
||||||
|
shift_time_schedule = db.Table(
|
||||||
|
'shift_time_schedule',
|
||||||
|
db.Column('shift_id', db.Integer, db.ForeignKey('shift.id'), primary_key=True),
|
||||||
|
db.Column('time_schedule_id', db.Integer, db.ForeignKey('time_schedules.id'), primary_key=True)
|
||||||
|
)
|
||||||
|
|
||||||
class Shift(db.Model):
|
class Shift(db.Model):
|
||||||
__tablename__ = 'shift'
|
__tablename__ = 'shift'
|
||||||
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
service_instance_id = db.Column(db.Integer, db.ForeignKey('service_instance.id'), nullable=False) # Relaciona com ServiceInstance
|
service_instance_id = db.Column(db.Integer, db.ForeignKey('service_instance.id'), nullable=False)
|
||||||
name = db.Column(db.String(50), nullable=False) # Nome do turno (Manhã, Tarde, etc.)
|
name = db.Column(db.String(50), nullable=False)
|
||||||
|
|
||||||
day = db.Column(db.String(20), nullable=False) # Ex: Segunda, Terça
|
|
||||||
|
|
||||||
start_time = db.Column(db.Time, nullable=False)
|
start_time = db.Column(db.Time, nullable=False)
|
||||||
end_time = db.Column(db.Time, nullable=False)
|
end_time = db.Column(db.Time, nullable=False)
|
||||||
|
|
||||||
interval_start = db.Column(db.Time, nullable=True)
|
interval_start = db.Column(db.Time, nullable=True)
|
||||||
interval_end = db.Column(db.Time, nullable=True)
|
interval_end = db.Column(db.Time, nullable=True)
|
||||||
|
|
||||||
type_interval = db.Column(db.String(50), nullable=False)
|
type_interval = db.Column(db.String(50), nullable=False)
|
||||||
|
description = db.Column(db.String(255), nullable=True) # Descrição do turno
|
||||||
|
tolerance = db.Column(db.Integer, nullable=True) # Tolerância em minutos
|
||||||
|
|
||||||
# Relacionamento com o modelo TimeSchedule
|
# 🗓️ Relacionamento com os dias (TimeSchedule usados como dias da semana)
|
||||||
time_schedules = db.relationship('TimeSchedule', backref='shifts', lazy=True)
|
time_schedules = db.relationship(
|
||||||
|
'TimeSchedule',
|
||||||
|
secondary=shift_time_schedule,
|
||||||
|
backref='shifts',
|
||||||
|
lazy='subquery'
|
||||||
|
)
|
||||||
|
|
||||||
# Relacionamento com o modelo Record, utilizando a chave estrangeira corretamente
|
# Relacionamento com records
|
||||||
records = db.relationship("Record", back_populates="shifts", lazy=True)
|
records = db.relationship("Record", back_populates="shifts", lazy=True)
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
|
|||||||
@ -6,11 +6,9 @@ class TimeSchedule(db.Model):
|
|||||||
__tablename__ = 'time_schedules'
|
__tablename__ = 'time_schedules'
|
||||||
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
shift_id = db.Column(db.Integer, db.ForeignKey('shift.id'), nullable=False) # Relaciona com Shift
|
name = db.Column(db.String(20), nullable=False, unique=True) # Ex: Segunda, Terça, etc.
|
||||||
start_time = db.Column(db.Time, nullable=False) # Hora de início do time slot
|
|
||||||
end_time = db.Column(db.Time, nullable=False) # Hora de término do time slot
|
|
||||||
description = db.Column(db.String(255)) # Descrição do time schedule (ex: 'Almoço')
|
|
||||||
records = db.relationship("Record", back_populates="schedule")
|
records = db.relationship("Record", back_populates="schedule")
|
||||||
|
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f'<TimeSchedule {self.description} ({self.start_time} - {self.end_time})>'
|
return f'<TimeSchedule {self.name}>'
|
||||||
|
|||||||
@ -2,31 +2,36 @@ from flask import Blueprint, request, jsonify
|
|||||||
from flasgger.utils import swag_from
|
from flasgger.utils import swag_from
|
||||||
from models.shifts import Shift, db
|
from models.shifts import Shift, db
|
||||||
from models.service_instance import ServiceInstance
|
from models.service_instance import ServiceInstance
|
||||||
|
from models.time_schedule import TimeSchedule
|
||||||
|
|
||||||
shift_bp = Blueprint('shift', __name__, url_prefix='/shift/')
|
shift_bp = Blueprint('shift', __name__, url_prefix='/shift/')
|
||||||
|
|
||||||
# Criar um turno
|
# Criar um turno
|
||||||
@shift_bp.route('/', methods=['POST'])
|
@shift_bp.route('/', methods=['POST'])
|
||||||
@swag_from('../docs/shifts/create.yml')
|
|
||||||
def create_shift():
|
def create_shift():
|
||||||
"""Cria um novo turno."""
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
|
|
||||||
# Verifica se a service_instance existe
|
|
||||||
service_instance_id = data.get('service_instance_id')
|
service_instance_id = data.get('service_instance_id')
|
||||||
ServiceInstance.query.get_or_404(service_instance_id)
|
ServiceInstance.query.get_or_404(service_instance_id)
|
||||||
|
|
||||||
# Cria o turno
|
# Cria o turno
|
||||||
shift = Shift(
|
shift = Shift(
|
||||||
name=data['name'],
|
name=data['name'],
|
||||||
day=data['day'],
|
|
||||||
start_time=data['start_time'],
|
start_time=data['start_time'],
|
||||||
end_time=data['end_time'],
|
end_time=data['end_time'],
|
||||||
interval_start=data['interval_start'],
|
interval_start=data.get('interval_start'),
|
||||||
interval_end=data['interval_end'],
|
interval_end=data.get('interval_end'),
|
||||||
type_interval=data['type_interval'],
|
type_interval=data['type_interval'],
|
||||||
service_instance_id=data['service_instance_id']
|
service_instance_id=service_instance_id,
|
||||||
|
description=data.get('description'), # Adicionando a descrição
|
||||||
|
tolerance=data.get('tolerance'), # Adicionando a tolerância
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Associa os dias (TimeSchedules)
|
||||||
|
time_schedule_ids = data.get('time_schedule_ids', [])
|
||||||
|
if time_schedule_ids:
|
||||||
|
shift.time_schedules = TimeSchedule.query.filter(TimeSchedule.id.in_(time_schedule_ids)).all()
|
||||||
|
|
||||||
db.session.add(shift)
|
db.session.add(shift)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
@ -39,15 +44,13 @@ def create_shift():
|
|||||||
def update_shift(shift_id):
|
def update_shift(shift_id):
|
||||||
"""Atualiza um turno existente."""
|
"""Atualiza um turno existente."""
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
print(data)
|
|
||||||
# Localiza o turno ou retorna 404
|
# Localiza o turno ou retorna 404
|
||||||
shift = Shift.query.get_or_404(shift_id)
|
shift = Shift.query.get_or_404(shift_id)
|
||||||
|
|
||||||
# Atualiza os campos fornecidos no body
|
# Atualiza os campos fornecidos no body
|
||||||
if 'name' in data:
|
if 'name' in data:
|
||||||
shift.name = data['name']
|
shift.name = data['name']
|
||||||
if 'day' in data:
|
|
||||||
shift.days = data['day']
|
|
||||||
if 'start_time' in data:
|
if 'start_time' in data:
|
||||||
shift.start_time = data['start_time']
|
shift.start_time = data['start_time']
|
||||||
if 'end_time' in data:
|
if 'end_time' in data:
|
||||||
@ -58,15 +61,28 @@ def update_shift(shift_id):
|
|||||||
shift.interval_end = data['interval_end']
|
shift.interval_end = data['interval_end']
|
||||||
if 'type_interval' in data:
|
if 'type_interval' in data:
|
||||||
shift.type_interval = data['type_interval']
|
shift.type_interval = data['type_interval']
|
||||||
|
if 'description' in data:
|
||||||
|
shift.description = data['description']
|
||||||
|
if 'tolerance' in data:
|
||||||
|
shift.tolerance = data['tolerance']
|
||||||
|
|
||||||
if 'service_instance_id' in data:
|
if 'service_instance_id' in data:
|
||||||
ServiceInstance.query.get_or_404(data['service_instance_id']) # Valida a existência
|
ServiceInstance.query.get_or_404(data['service_instance_id']) # Valida a existência
|
||||||
shift.service_instance_id = data['service_instance_id']
|
shift.service_instance_id = data['service_instance_id']
|
||||||
|
|
||||||
|
# Atualiza os dias (TimeSchedules)
|
||||||
|
if 'time_schedule_ids' in data:
|
||||||
|
# Recebe a lista de IDs dos dias a serem associados ao turno
|
||||||
|
time_schedule_ids = data['time_schedule_ids']
|
||||||
|
# Verifica se os IDs existem no banco e atualiza a associação
|
||||||
|
shift.time_schedules = TimeSchedule.query.filter(TimeSchedule.id.in_(time_schedule_ids)).all()
|
||||||
|
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
return jsonify({'message': 'Shift updated successfully'}), 200
|
return jsonify({'message': 'Shift updated successfully'}), 200
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Listar turnos
|
# Listar turnos
|
||||||
@shift_bp.route('/', methods=['GET'])
|
@shift_bp.route('/', methods=['GET'])
|
||||||
@swag_from('../docs/shifts/list.yml')
|
@swag_from('../docs/shifts/list.yml')
|
||||||
@ -84,17 +100,22 @@ def list_shifts():
|
|||||||
shift_list = [{
|
shift_list = [{
|
||||||
'id': shift.id,
|
'id': shift.id,
|
||||||
'name': shift.name,
|
'name': shift.name,
|
||||||
'day': shift.day,
|
|
||||||
"start_time": shift.start_time.strftime("%H:%M"),
|
"start_time": shift.start_time.strftime("%H:%M"),
|
||||||
"end_time": shift.end_time.strftime("%H:%M"),
|
"end_time": shift.end_time.strftime("%H:%M"),
|
||||||
"interval_start": shift.interval_start.strftime("%H:%M") if shift.interval_start else None,
|
"interval_start": shift.interval_start.strftime("%H:%M") if shift.interval_start else None,
|
||||||
"interval_end": shift.interval_end.strftime("%H:%M") if shift.interval_end else None,
|
"interval_end": shift.interval_end.strftime("%H:%M") if shift.interval_end else None,
|
||||||
'type_interval': shift.type_interval,
|
'type_interval': shift.type_interval,
|
||||||
'service_instance_id': shift.service_instance_id
|
'service_instance_id': shift.service_instance_id,
|
||||||
|
|
||||||
|
# Adicionando os dias associados (TimeSchedules)
|
||||||
|
'time_schedules': [
|
||||||
|
{'id': ts.id, 'name': ts.name} for ts in shift.time_schedules
|
||||||
|
]
|
||||||
} for shift in shifts]
|
} for shift in shifts]
|
||||||
|
|
||||||
return jsonify(shift_list), 200
|
return jsonify(shift_list), 200
|
||||||
|
|
||||||
|
|
||||||
@shift_bp.route('/<int:shift_id>', methods=['GET'])
|
@shift_bp.route('/<int:shift_id>', methods=['GET'])
|
||||||
@swag_from('../docs/shifts/get.yml')
|
@swag_from('../docs/shifts/get.yml')
|
||||||
def get_shift_id(shift_id):
|
def get_shift_id(shift_id):
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user