clinic/netforce_clinic/models/visit.py

366 lines
13 KiB
Python

import time
from datetime import datetime, timedelta
from netforce.model import Model, fields, get_model
from netforce.access import get_active_company, get_active_user, set_active_user
FMT_DATE="%Y-%m-%d %H:%M:%S"
class Visit(Model):
_name="clinic.visit"
_string="Visit"
_audit_log=True
_name_field="number"
_multi_company=True
def _get_print_date(self,ids,context={}):
res={}
for obj in self.browse(ids):
res[obj.id]=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return res
def _get_color(self,ids,context={}):
res={}
for obj in self.browse(ids):
color=get_model("clinic.cycle").browse(obj.cycle_id.id).color
res[obj.id]=color
return res
_fields={
"number": fields.Char("Number",required=True,search=True),
"time_start": fields.DateTime("Time Start",required=True),
"time_stop": fields.DateTime("Time Stop",required=True),
"patient_id": fields.Many2One("clinic.patient","Patient",required=True,search=True),
"doctor_id": fields.Many2One("clinic.personal","Doctor", domain=[['type','=','doctor']],search=True),
"nurse_id": fields.Many2One("clinic.personal","Confirm By", domain=[['type','=','nurse']],search=True),
"department_id": fields.Many2One("clinic.department", "Department",search=True),
"comments": fields.One2Many("message","related_id","Comments"),
"company_id": fields.Many2One("company","Company"),
'hd_cases': fields.One2Many('clinic.hd.case','visit_id',"HD Cases",readonly=True),
"cycle_id": fields.Many2One("clinic.cycle","Cycle"),
'cycle_color': fields.Char('Color',function="_get_color"),
"state": fields.Selection([["draft","Draft"],["confirmed","Confirmed"],["cancelled","Cancelled"]],"Status",required=True),
"comments": fields.One2Many("message","related_id","Comments"),
'visit_date': fields.Date('Visit Date'),
'print_date': fields.Date('Print Date',function="_get_print_date"),
'cycle_item_id': fields.Many2One("clinic.cycle.item","Cycle Item"), #XXX on_delete="cascade" -> rm visit from cycle item
'sequence': fields.Char("Sequence"),
'note': fields.Text('Note'),
}
def _get_number(self,context={}):
while 1:
seq_name='Clinic Visit'
seq_id=get_model("sequence").find_sequence(name=seq_name)
if not seq_id:
raise Exception("Can not found sequence %s"%seq_name)
num=get_model("sequence").get_next_number(seq_id,context=context)
if not num:
return None
user_id=get_active_user()
set_active_user(1)
res=self.search([["number","=",num]])
set_active_user(user_id)
if not res:
return num
get_model("sequence").increment_number(seq_id,context=context)
def _get_nurse(self,context={}):
user_id=get_active_user()
nurse_ids=get_model("clinic.personal").search([['user_id','=',user_id],['type','=','nurse']])
if nurse_ids:
return nurse_ids[0]
return None
def _get_time_start(self,context={}):
now=datetime.now()
starttime=now.strftime("%Y-%m-%d %H:%M:%S")
print(":>> ", starttime)
return starttime
def _get_time_stop(self,context={}):
hr=timedelta(seconds=3600)
now=datetime.now()
stoptime=(now+hr).strftime("%Y-%m-%d %H:%M:%S")
print('::: ', stoptime)
return stoptime
_defaults={
"state": "draft",
'time_start': _get_time_start,
'time_stop': _get_time_stop,
"number": "/",
"company_id": lambda *a: get_active_company(),
'nurse_id': _get_nurse,
}
_order="sequence"
def confirm(self,ids,context={}):
obj=self.browse(ids[0])
number=obj.number
if number=="/" or not number:
number=self._get_number(context)
vals={
'number': number,
'state': 'confirmed',
}
obj.write(vals)
hd_case_obj=get_model("clinic.hd.case")
obj=self.browse(ids)[0]
vals={
'patient_id': obj.patient_id.id,
'nurse_id': obj.nurse_id.id,
'department_id': obj.department_id.id,
'time_start': obj.time_start,
'time_stop': obj.time_stop,
'cycle_id' : obj.cycle_id.id,
'visit_id': obj.id,
'cycle_id': obj.cycle_id.id,
'lines':[],
'dialyzers': [],
'personals': [],
'state': 'draft',
}
vals['personals'].append(('create',{
'personal_id': obj.doctor_id.id,
'type': 'doctor',
'priop': 'owner',
}))
products=get_model("product").search_browse([['code','=','FEE']])
for product in products:
vals['lines'].append(('create',{
'type': 'fee',
'product_id': product.id,
'description': product.name or "",
'qty': 1,
'price': product.sale_price or 0.0,
'amount': product.sale_price or 0.0,
'uom_id': product.uom_id.id,
}))
if obj.patient_id.type=='sc':
products=get_model("product").search_browse([['code','=','S0001']]) #XXX
for product in products:
vals['lines'].append(('create',{
'type': 'fee',
'product_id': product.id,
'description': product.name or "",
'qty': 1,
'price': product.sale_price or 0.0,
'amount': product.sale_price or 0.0,
'uom_id': product.uom_id.id,
}))
patient_type={
"mg":"Medical Government",
"sc":"Social Security",
"nhso":"NHSO (30฿)",
"personal": "Personal",
"others": "Others",
}
categ_name=patient_type.get(obj.patient_id.type)
categ_ids=get_model("partner.categ").search([['name','=',categ_name]])
if not categ_ids:
raise Exception("Partner Category: %s not found"%categ_name)
partner_id=None
if obj.patient_id.type in ("mg","sc","nhso"):
partner_obj=get_model("partner")
for partner in partner_obj.search_browse([]):
if partner.categ_id.id in categ_ids:
partner_id=partner.id
vals['fee_partner_id']=partner_id
break
hd_case_id=hd_case_obj.create(vals)
if context.get("called"): #XXX call outside
return hd_case_id
return {
'next': {
'name': 'clinic_hd_case',
'mode': 'form',
'active_id': hd_case_id,
},
'flash': 'Visit %s has been confirmed'%obj.number,
}
def discard(self,ids,context={}):
obj=self.browse(ids)[0]
obj.write({"state":"cancelled"})
def reopen(self,ids,context={ }):
obj=self.browse(ids)[0]
obj.write({"state":"draf t"})
def onchange_patient(self,context={}):
data=context['data']
patient_id=data['patient_id']
visits=self.search_browse([['patient_id','=',patient_id]],order="number desc")
if visits:
visit=visits[0]
data['doctor_id']=visit.doctor_id.id
data['department_id']=visit.department_id.id
else:
data['doctor_id']=None
data['department_id']=None
return data
def copy(self,ids,context={}) :
obj=self.browse(ids[0])
vals={
'patient_id': obj.patient_id.id,
'doctor_id': obj.doctor_id.id,
'nurse_id': obj.nurse_id.id,
'department_id': obj.department_id.id,
'cycle': obj.cycle,
}
new_id=self.create(vals,context=context)
new_obj=self.browse(new_id)
return {
'next':{
'name': 'clinic_visit',
'mode': 'form',
'active_id': new_id,
},
'flash': 'Visit %s is copy to %s'%(obj.number,new_obj.number),
}
def delete(self,ids,context={}):
for obj in self.browse(ids):
if obj.state!='draft':
raise Exception("Can not delete visit %s because state is not draft!"%obj.number)
super().delete(ids,context=context)
def get_data(self,context={}):
ref_id=context.get("refer_id")
if not ref_id:
return {}
ref_id=int(ref_id)
obj=self.browse(ref_id)
data={
'number': obj.number,
'date_visit': obj.date_visit,
'department_name': obj.department_id.name or "",
'patient_name': obj.patient_id.name or "",
'doctor_name': obj.doctor_id.name or "",
'nurse_name': obj.nurse_id.name or "",
'print_date': time.strftime("%d/%m/%Y"),
'cycle_name': obj.cycle_id.name or "",
}
return data
def onchange_time(self,context={}):
data=context['data']
cycle_id=data['cycle_id']
duration=1
if cycle_id:
cycle=get_model('clinic.cycle').browse(cycle_id)
duration=cycle.duration or 0
seconds=duration*3600
time_start=data['time_start']
data['time_stop']=(datetime.strptime(time_start,FMT_DATE)+timedelta(seconds=seconds)).strftime(FMT_DATE)
return data
def to_draft(self,ids,context={}):
obj=self.browse(ids)[0]
for hd_case in obj.hd_cases:
# XXX
hd_case.write({
'state': 'draft',
})
hd_case.delete()
obj.write({
'state': 'draft',
})
def gen_no(self,ids,context={}):
obj=self.browse(ids)[0]
if obj.number != '/':
return
number=self._get_number(context)
obj.write({
'number': number,
})
return {
'next': {
'name': 'clinic_visit',
'mode': 'form',
'active_id': obj.id,
},
'flash': 'Gen No OK',
}
def create(self, vals,**kw):
date=vals['time_start'][0:10]
cycle_id=vals['cycle_id']
cycle=get_model("clinic.cycle").browse(cycle_id)
dom=[]
dom.append(['date','=',date])
dom.append(['cycle_id','=',cycle_id])
item_obj=get_model('clinic.cycle.item')
item_ids=item_obj.search(dom)
item_id=None
nurse_vals=[]
if 'nurse_vals' in vals.keys():
nurse_vals=vals['nurse_vals']
del vals['nurse_vals']
if not item_ids:
item_vals={
'cycle_id': cycle_id,
'date': date,
'nurses': [],
}
for nurse_val in nurse_vals:
item_vals['nurses'].append(('create',{
'nurse_id': nurse_val['id'],
'level_id': nurse_val['level_id'],
}))
item_id=item_obj.create(item_vals)
else:
item_id=item_ids[0]
item_nurse_obj=get_model("clinic.cycle.item.nurse")
item_nurse_ids=item_nurse_obj.search([['cycle_item_id','=',item_id]])
item_nurse_obj.delete(item_nurse_ids)
for nurse_val in nurse_vals:
item_nurse_obj.create({
'cycle_item_id': item_id,
'nurse_id': nurse_val['id'],
'level_id': nurse_val['level_id'],
})
vals['cycle_item_id']=item_id
vals['sequence']='%s-%s'%(vals['time_start'][0:10],cycle.sequence) #date-sequence
vals['visit_date']=vals['time_start'][0:10]
obj_id=super().create(vals,**kw)
return obj_id
def cancel(self,ids,context={}):
obj=self.browse(ids)[0]
obj.write({
'state': 'cancelled',
})
return {
'next': {
'name': 'clinic_visit',
'mode': 'form',
'active_id': obj.id,
},
'flash': 'Visit\'s %s has been cancelled'%obj.patient_id.name
}
def write(self,ids,vals,**kw):
obj=self.browse(ids)[0]
cycle=obj.cycle_id
vals['sequence']='%s-%s'%(obj.time_start[0:10],cycle.sequence) #date-sequence
vals['visit_date']=obj.time_start[0:10]
super().write(ids,vals,**kw)
Visit.register()