152 lines
6.5 KiB
Python
152 lines
6.5 KiB
Python
# -*- coding: utf-8 -*-
|
|
|
|
from odoo import models, fields, api, _
|
|
from odoo.exceptions import ValidationError
|
|
|
|
from ..clinic_settings import get_recursos
|
|
|
|
# Motivos predefinidos (el legacy usaba 7 = Vacaciones y 8 = Horario de comida)
|
|
MOTIVO_SELECTION = [
|
|
('vacaciones', 'Vacaciones'),
|
|
('junta', 'Junta'),
|
|
('comida', 'Comida'),
|
|
('personal', 'Personal'),
|
|
('otro', 'Otro'),
|
|
]
|
|
|
|
|
|
class SkeenCitaBloqueo(models.Model):
|
|
"""Bloqueo de agenda: de un médico y/o de un recurso físico, en una fecha.
|
|
|
|
Un registro = una fecha, con un médico (opcional) y/o recursos (opcional).
|
|
Los bloqueos creados juntos (varios médicos/recursos y/o un rango de fechas
|
|
con repetición semanal) comparten el campo `grupo`, lo que permite editarlos
|
|
o eliminarlos como serie.
|
|
|
|
`doctor_id` dejó de ser obligatorio para poder bloquear una cabina, sala o
|
|
equipo sin médico (módulo de recursos). Debe haber al menos uno de los dos.
|
|
"""
|
|
_name = 'skeen.cita.bloqueo'
|
|
_description = 'Bloqueo de Agenda'
|
|
_order = 'date desc, time_from'
|
|
|
|
doctor_id = fields.Many2one('hr.employee', string='Médico')
|
|
recurso_ids = fields.Many2many(
|
|
'skeen.recurso', 'skeen_bloqueo_recurso_rel', 'bloqueo_id', 'recurso_id',
|
|
string='Recursos')
|
|
date = fields.Date(string='Fecha', required=True, index=True)
|
|
all_day = fields.Boolean(string='Todo el día', default=False)
|
|
time_from = fields.Float(string='Desde', default=9.0)
|
|
time_to = fields.Float(string='Hasta', default=10.0)
|
|
motivo_tipo = fields.Selection(MOTIVO_SELECTION, string='Motivo', default='otro')
|
|
motivo = fields.Char(string='Detalle del motivo')
|
|
grupo = fields.Char(string='Grupo', index=True, copy=False,
|
|
help='Identificador de la serie (médicos/recursos y fechas creados juntos).')
|
|
created_by = fields.Char(string='Creado por', readonly=True, copy=False)
|
|
|
|
@api.constrains('time_from', 'time_to', 'all_day')
|
|
def _check_horas(self):
|
|
for b in self:
|
|
if not b.all_day:
|
|
if b.time_to <= b.time_from:
|
|
raise ValidationError(_('La hora final debe ser mayor a la inicial'))
|
|
if b.time_from < 0 or b.time_to > 24:
|
|
raise ValidationError(_('Las horas deben estar dentro del día'))
|
|
|
|
@api.constrains('doctor_id', 'recurso_ids')
|
|
def _check_destino(self):
|
|
"""Un bloqueo se hace para un médico y/o un recurso: sin destino no
|
|
tiene sentido (y no bloquearía nada)."""
|
|
for b in self:
|
|
if not b.doctor_id and not b.recurso_ids:
|
|
raise ValidationError(_(
|
|
'Selecciona al menos un médico o un recurso para bloquear.'))
|
|
|
|
@api.constrains('doctor_id', 'date', 'all_day', 'time_from', 'time_to')
|
|
def _check_sin_citas(self):
|
|
"""No se puede bloquear un rango que ya tiene citas activas del médico.
|
|
|
|
Evita "cerrar la agenda" dejando citas dentro del bloqueo. Al editar un
|
|
bloqueo se ignora a sí mismo (no tiene citas asociadas, pero el dominio
|
|
es el mismo que usa la validación de citas).
|
|
"""
|
|
Citas = self.env['skeen.cita']
|
|
if self.env.context.get('skeen_skip_bloqueo_citas'):
|
|
return
|
|
for b in self:
|
|
if not b.doctor_id or not b.date:
|
|
continue
|
|
domain = [
|
|
('doctor_id', '=', b.doctor_id.id),
|
|
('date', '=', b.date),
|
|
('state', 'not in', ('cancelled', 'no_show', 'waitlist')),
|
|
]
|
|
if not b.all_day:
|
|
domain += [('time', '<', b.time_to)]
|
|
citas = Citas.search(domain).filtered(
|
|
lambda c: b.all_day or (c.time + c._duracion() / 60.0) > b.time_from
|
|
)
|
|
if citas:
|
|
raise ValidationError(_(
|
|
'Hay %(n)s cita(s) agendadas en ese horario con %(doc)s. '
|
|
'Reprograma o cancela esas citas antes de bloquear.'
|
|
) % {'n': len(citas), 'doc': b.doctor_id.name})
|
|
|
|
@api.constrains('recurso_ids', 'date', 'all_day', 'time_from', 'time_to')
|
|
def _check_recursos(self):
|
|
"""Un recurso no se puede bloquear si tiene citas activas dentro, ni
|
|
solaparse con otro bloqueo del mismo recurso.
|
|
|
|
Sólo corre con `recursos.activo` (default apagado → sin cambios). El
|
|
solape con otro bloqueo respeta además `validar_solape`.
|
|
"""
|
|
if self.env.context.get('skeen_skip_recursos_solape'):
|
|
return
|
|
cfg = get_recursos(self.env)
|
|
if not cfg['activo']:
|
|
return
|
|
Citas = self.env['skeen.cita']
|
|
for b in self:
|
|
if not b.date or not b.recurso_ids:
|
|
continue
|
|
if b.all_day:
|
|
ini_c, fin_c = 0.0, 24.0
|
|
else:
|
|
ini_c, fin_c = b.time_from, b.time_to
|
|
for recurso in b.recurso_ids:
|
|
citas = Citas.search([
|
|
('date', '=', b.date),
|
|
('state', 'not in', ('cancelled', 'no_show', 'waitlist')),
|
|
('recurso_ids', 'in', recurso.id),
|
|
]).filtered(
|
|
lambda c: b.all_day or (
|
|
c.time < fin_c and c.time + c._duracion() / 60.0 > ini_c)
|
|
)
|
|
if citas:
|
|
raise ValidationError(_(
|
|
'%(rec)s tiene %(n)s cita(s) en ese horario. Reprograma o '
|
|
'cancela esas citas antes de bloquear.'
|
|
) % {'rec': recurso.name, 'n': len(citas)})
|
|
if not cfg['validar_solape']:
|
|
continue
|
|
otros = self.search([
|
|
('id', '!=', b.id),
|
|
('date', '=', b.date),
|
|
('recurso_ids', 'in', recurso.id),
|
|
]).filtered(
|
|
lambda o: (o.all_day or b.all_day)
|
|
or (ini_c < o.time_to and fin_c > o.time_from)
|
|
)
|
|
if otros:
|
|
raise ValidationError(_(
|
|
'%(rec)s ya tiene un bloqueo en ese horario (%(motivo)s).'
|
|
) % {'rec': recurso.name, 'motivo': otros[0].nombre_motivo()})
|
|
|
|
def nombre_motivo(self):
|
|
"""Texto legible del motivo para la UI y los mensajes de validación."""
|
|
self.ensure_one()
|
|
etiqueta = dict(MOTIVO_SELECTION).get(self.motivo_tipo or '', '')
|
|
if self.motivo and etiqueta:
|
|
return '%s — %s' % (etiqueta, self.motivo)
|
|
return self.motivo or etiqueta or 'agenda bloqueada'
|