clinic/netforce_clinic/models/patient.py

581 lines
24 KiB
Python

import time
from netforce.model import Model, fields, get_model
from netforce.access import get_active_company, get_active_user, set_active_user
from netforce.database import get_connection
from . import utils
class Patient(Model):
_name="clinic.patient"
_string="Patient"
_audit_log=True
_multi_company=True
def _get_age(self,ids,context):
res={}
year_now=int(time.strftime("%Y"))
for obj in self.browse(ids):
age=0
if obj.birthday:
year_bd=int(obj.birthday[0:4])
age=year_now-year_bd
res[obj.id]=age
return res # -> {1: 30, 2: 45,.....}
def _get_last_cycle(self,ids,context={}):
res={}
for obj in self.browse(ids):
cycle_id=None
for vs in obj.visits:
cycle=vs.cycle_id
cycle_id=cycle.id
res[obj.id]=cycle_id
return res
def _get_hn_no(self,ids,context={}):
res={}
for obj in self.browse(ids):
hn=''.join(x for x in (obj.number or "") if x.isdigit())
res[obj.id]=hn
return res
def _get_name(self,ids,context={}):
res={}
for obj in self.browse(ids):
name=''
title=obj.title_id
title_name=''
if title:
title_name=title.name or ""
title_name=title_name.replace(" ","")
if title_name.lower()!='notitle':
name+=obj.title_id.name or ""
if obj.first_name:
name+=obj.first_name or ""
name+=" "
if obj.last_name:
name+=obj.last_name or ""
if not obj.active:
name+='__'
elif context.get('active'):
name+='__'
name_check=name.replace(" ","")
name_check=name_check.replace(title_name,"")
res[obj.id]={
'name': name,
'name_check': name_check,
}
return res
def _get_location(self,ids,context={}):
res={}
for obj in self.browse(ids):
dpt_codes=set()
# main department
dpt_codes.update({obj.department_id.code})
# cycle settings
for cline in obj.cycles:
dpt_codes.update({cline.department_id.code})
res[obj.id]=','.join([code for code in dpt_codes if code])
return res
def _get_department_names(self,ids,context={}):
res={}
user_id=get_active_user()
set_active_user(1)
for obj in self.browse(ids):
res[obj.id]=','.join([dpt.name for dpt in obj.departments])
set_active_user(user_id)
return res
def _get_log(self,ids,context={}):
res={}
db=get_connection()
for obj in self.browse(ids):
for r in db.query("select create_time,create_uid,write_time,write_uid from clinic_patient where id = %s",obj.id):
res[obj.id]={
'c_time': r['create_time'],
'c_uid': r['create_uid'],
'w_uid': r['write_uid'],
'w_time': r['write_time'],
}
return res
_fields={
'c_time': fields.DateTime("Created",function="_get_log", function_multi=True),
'c_uid': fields.Many2One("base.user","Create By",function="_get_log", function_multi=True),
'w_time': fields.DateTime("Edited",function="_get_log", function_multi=True),
'w_uid': fields.Many2One("base.user","Lasted Edit",function="_get_log", function_multi=True),
"number": fields.Char("HN Number",required=True,search=True),
"trt_no": fields.Char("TRT",search=True),
"hn_no": fields.Char("HN",function="_get_hn_no",store=True),
"hn": fields.Char("REF/HN",search=False),
'title_id': fields.Many2One("clinic.name.title","Title"),
"first_name": fields.Char("First Name"),
"last_name": fields.Char("Last Name"),
"name": fields.Char("Name",function="_get_name",function_multi=True,store=True,search=True),
"name_check": fields.Char("Name",function="_get_name",function_multi=True,store=True), # prevent duplicate
'type_id': fields.Many2One("clinic.patient.type","Type",search=True,required=True),
"reg_date": fields.Date("Reg. Date",required=False,search=True),
"birthday": fields.Date("Birthday",required=False,search=True),
"phone": fields.Char("Phone",required=False,search=True),
"mobile": fields.Char("Mobile",required=False,search=True),
"job": fields.Char("Job/Position"),
"age": fields.Integer("Age", function="_get_age"),
'image': fields.File("Image"),
'email': fields.Char("Email"),
"weight": fields.Float("Weight (kg.)"),
"height": fields.Float("Height (cm.)"),
"card_type": fields.Selection([("identification","Identification"),("passport","Passport")],"Card Type"),
'card_no' : fields.Char("ID Card",size=13, search=True),
'card_exp' : fields.Date("Card Exp."),
"app_no": fields.Char("Application No."),
"salary": fields.Selection([["20000","5,001-20,000"],["50000","20,001-50,000"],["100000","50,001-100,000"],["100001","100,000+"]], "Salary"),
"addresses": fields.One2Many("address","patient_id","Addresses"),
"gender": fields.Selection([("male","Male"),("female","Female")],"Gender",search=True),
"marital_status": fields.Selection([("single","Single"),("marry","Marry"),("divorce","Divorce"),("separated","Saparated"),("widowed","Widowed")],"Marital Status",required=False),
"nation_id": fields.Many2One("clinic.nation","Nationality"),
"race_id": fields.Many2One("clinic.race","Race"),
"grad_id": fields.Many2One("clinic.graduation","Graduation"),
"smoke": fields.Selection([("never","Never"),("stopped","Stopped"),("smoked","Smoked")],"Smoking"),
"withdrawal" : fields.Selection([("social_security","Social Security"),("health_insurance","Health Insurance"),("etc","ETC.")],"Right of withdrawal"),
"first_treatment" : fields.Selection([("hd","HD"),("test","Test")], "First treatment"),
"first_hemodialysis": fields.Date("First time Hemodialysis",required=False),
"hemodialysis": fields.Char("First Hemodialysis",required=False),
"clinic_after": fields.Selection([("small","Small"),("medium","Medium"),("large","Large")],"Clinic Lastime",required=False),
"clinic_after_name": fields.Char("Clinic after name",required=False),
"first_permanent_vascular_access": fields.Date("First time Permanent Vascular",required=False),
"first_tenckhoff_catheters": fields.Date("First time Tenckhoff Catheters",required=False),
"start_date_clinic": fields.Date("Start Date Clinic",required=False),
"waiting_transplantation": fields.Selection([("yes","Yes"),("no","No")],"Kidney Transplantation Waiting ?"),
"who_transplantation": fields.Char("Who is Transplantation?"),
"reason_of_chronic_renal_failure": fields.Char("Reason chronic renal failure ?"),
'causes': fields.One2Many("clinic.patient.cause","patient_id","Cause Of Chronic Renal Failure"),
'comorbilities': fields.One2Many("clinic.patient.comorbidity","patient_id","Comorbilities"),
'morbilities': fields.One2Many("clinic.patient.morbidity","patient_id","Morbilities"),
"comments": fields.One2Many("message","related_id","Comments"),
"company_id": fields.Many2One("company","Company",search=True),
"visits": fields.One2Many("clinic.visit","patient_id","Visits"),
"hd_cases": fields.One2Many("clinic.hd.case","patient_id","HD Cases"),
"partner_id": fields.Many2One("partner","Contact"),
"dialyzers": fields.One2Many("clinic.dialyzer","patient_id","Dialyzers"),
"active":fields.Boolean("Active"),
"dispose":fields.Boolean("Dispose",search=True),
'note': fields.Text("Note"),
'categ_id': fields.Many2One("clinic.patient.categ","Category"),
'doctor_id': fields.Many2One("clinic.staff","Doctor",domain=[['type','=','doctor']]),
"documents": fields.One2Many("document","related_id","Documents"),
'resign_date': fields.Date("Dispose Date", search=True),
'rm_remain_visit': fields.Boolean("Auto Remove Remaining Visit"),
'department_id': fields.Many2One("clinic.department","Main Department",search=True),
'cycle_id': fields.Many2One("clinic.cycle","Last Cycle",function="_get_last_cycle"),
'branch_id': fields.Many2One("clinic.branch","Branch",search=True),
'cycles': fields.One2Many("clinic.patient.cycle","patient_id", "Cycles"),
"vascular_acc": fields.Many2One("clinic.vascular.access","Vascular Ac."),
'state': fields.Selection([['admit','Admit'],['dispose','Dispose']],'State'),
'walkin': fields.Selection([['yes','Yes'],['no','No']],"Walkin"),
'location': fields.Char("Share Department"), #to filter
'cw_time': fields.DateTime("Cycle Updated"),
'cw_uid': fields.Many2One("base.user"," Cycle Edit"),
"moves": fields.One2Many("clinic.patient.move","patient_id","Moves"),
}
def _get_number(self,context={}):
while 1:
seq_id=get_model("sequence").find_sequence(name="Clinic Patient")
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)
# reformat number: month-running num-year thai(2 digit)
monthnow=int(time.strftime("%m"))
yearnow=utils.date2thai(time.strftime("%Y-%m-%d"),"%(By)s")
num="%s-%s-%s"%(monthnow,num,yearnow)
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_cause_line(self,context={}):
cause_ids=get_model("clinic.cause.chronic").search([])
return cause_ids
def _get_type(self,context={}):
ptype_id=None
for ptype in get_model("clinic.patient.type").search_browse([]):
if ptype.default:
ptype_id=ptype.id
break
return ptype_id
def _get_departments(self,context={}):
res=get_model('select.company').get_select()
if res:
if res.get("department_ids"):
return res['department_ids']
else:
return [res['department_id']]
dpts=get_model("clinic.department").search([])
return dpts
def _get_department(self,context={}):
res=get_model('select.company').get_select()
if res:
if res.get("department_ids"):
return res['department_ids'][0]
else:
return res['department_id']
def _get_branch(self,context={}):
res=get_model('select.company').get_select()
if res:
return res['branch_id']
def _get_default_location(self,context={}):
res=get_model('select.company').get_select()
code=''
if res:
dpt_ids=[]
if res.get("department_ids"):
dpt_ids=res['department_ids']
else:
dpt_ids=[res['department_id']]
dpts=get_model("clinic.department").browse(dpt_ids)
code=','.join([dpt.code for dpt in dpts])
return code
def _get_nation(self,context={}):
nid=None
for nt in get_model("clinic.nation").search_browse([['default','=',True]]):
nid=nt.id
return nid
_defaults={
#"number": _get_number,
"number": "",
"reg_date": lambda *a: time.strftime("%Y-%m-%d"),
"company_id": lambda *a: get_active_company(),
'branch_id': _get_branch,
'department_id': _get_department,
'card_type': 'identification',
'type_id': _get_type,
"active" : True,
'state': 'admit',
'walkin': 'no',
'departments': _get_departments,
'location': _get_default_location,
'nation_id': _get_nation,
'dispose': False,
}
_sql_constraints=("clinic_patient_key_uniq","unique(name_check)","name should be unique"),
def check_idcard(self,card_type,idcard=''):
res=True
if not idcard:
return False
if card_type!='identification':
return False
if idcard=='/':
return True
if not idcard:
res=False
elif idcard.isalpha():
res=False
elif len(idcard)!=13:
res=False
if not res:
raise Exception("Wrong ID Card!")
def create(self, vals,**kw):
if 'card_no' in vals.keys():
self.check_idcard(vals.get("card_type",""),vals['card_no'])
obj_id=super().create(vals,**kw)
self.function_store([obj_id])
obj=self.browse(obj_id)
partner_id=obj.partner_id
if not partner_id:
partner_name='%s %s'%(obj.first_name or "",obj.last_name or "") # XXX
for partner in get_model("partner").search_browse([['name', '=', partner_name]]):
if partner.name==obj.name:
partner_id=partner.id
break
if not partner_id:
partner_id=get_model("partner").create({
'first_name': obj.first_name or "",
'last_name': obj.last_name or "",
'type': 'person',
'is_patient': True,
})
address_id=get_model('address').create({
'type': 'shipping',
'partner_id': partner_id,
'patient_id': obj.id,
'address': ' ',
'address2': ' ',
'city': ' ',
'postal_code': ' ',
'country_id': 1,
})
get_model('address').browse(address_id).write({
'related_id': "clinic.patient,%s"%obj.id,
})
obj.write({
'partner_id': partner_id,
})
#TODO create patient.move
return obj_id
def delete(self,ids,context={}):
partner_ids=[]
for obj in self.browse(ids):
partner_ids.append(obj.partner_id.id)
address_ids=[addr.id for addr in obj.partner_id.addresses]
get_model("partner").delete(partner_ids)
get_model("address").delete(address_ids)
vids=get_model("clinic.visit").search([['patient_id','in',ids],['state','in',['draft','pending']]])
get_model('clinic.visit').delete(vids)
for pt in get_model('clinic.setting.account.patient').search_browse([['patient_id','=',obj.id]]):
pt.delete()
super().delete(ids)
def check_vals(self,vals):
return vals
def write(self,ids,vals,**kw):
if 'cycles' in vals.keys():
datenow=time.strftime("%Y-%m-%d")
vdom=[
['patient_id','in',ids],
['visit_date','>=',datenow],
['state','=','pending'],
['manual','=',False],
]
visit_ids=get_model("clinic.visit").search(vdom)
get_model("clinic.visit").delete(visit_ids)
vals['cw_time']=time.strftime("%Y-%m-%d %H:%M:%S")
vals['cw_uid']=get_active_user()
if 'type_id' in vals.keys():
#update patient in hd case which state is condition below
for obj in self.browse(ids):
for hdcase in get_model('clinic.hd.case').search_browse([['patient_id','in',ids],['state','in',['draft','waiting_treatment']]]):
hdcase.write({
'patient_type_id': vals['type_id'],
})
if 'dispose' in vals.keys():
if vals['dispose']:
vals['state']='dispose'
if not vals.get("resign_date"):
vals['resign_date']=time.strftime("%Y-%m-%d")
vals['rm_remain_visit']=True
else:
vals['state']='admit'
vals['rm_remain_visit']=False
vals['resign_date']=None
ctx={}
if 'active' in vals.keys():
if not vals['active']:
vals['resign_date']=time.strftime("%Y-%m-%d")
vals['rm_remain_visit']=True
ctx['active']=False
else:
vals['rm_remain_visit']=False
def update_visit_pending(obj,visit_vals):
vids=get_model("clinic.visit").search([['patient_id','=',obj.id],['state','in',['draft','pending']]])
for visit in get_model('clinic.visit').browse(vids):
visit.write(visit_vals)
if visit_vals.get("doctor_id"):
for hdcase in visit.hd_cases:
for shdcase in hdcase.staffs:
shdcase.write({
'staff_id': visit_vals['doctor_id'],
})
for obj in self.browse(ids):
if obj.state=='treatment':
vals['note']=''
vals['resign_date']=None
visit_vals={}
if 'department_id' in vals.keys():
visit_vals.update({
'department_id': vals['department_id'],
})
if 'branch_id' in vals.keys():
visit_vals.update({
'branch_id': vals['branch_id'],
})
if 'doctor_id' in vals.keys():
visit_vals.update({
'doctor_id': vals['doctor_id'],
})
if visit_vals:
update_visit_pending(obj,visit_vals)
# create partner if not found
partner_id=obj.partner_id
if not partner_id and not vals.get('partner_id'):
partner_name='%s %s'%(obj.first_name or "", obj.last_name or "") # XXX
for partner in get_model("partner").search_browse([['name', '=', partner_name]]):
if partner.name==obj.name:
partner_id=partner.id
break
if not partner_id:
partner_id=get_model("partner").create({
'first_name': obj.first_name or "",
'last_name': obj.last_name or "",
'type': 'person',
'is_patient': True,
})
vals['partner_id']=partner_id
#add to account setting
get_model("clinic.setting.account.patient").create({
'setting_id': 1,
'type_id': obj.type_id.id,
'patient_id': obj.id,
'partner_id': partner_id,
'hn': obj.hn_no,
})
if not isinstance(partner_id,int):
partner_id=partner_id.id
if obj.addresses:
addr=obj.addresses[0]
get_model("address").browse(addr.id).write({
'partner_id': partner_id,
'patient_id': obj.id,
'related_id': "clinic.patient,%s"%obj.id,
})
else:
# in case add more one address
if vals.get("addresses"):
addr_vals=vals.get("addresses")[0][1]
addr_id=get_model("address").create(addr_vals)
get_model("address").browse(addr_id).write({
'patient_id': obj.id,
'partner_id': partner_id,
'related_id': "clinic.patient,%s"%obj.id,
})
del vals['addresses']
else:
obj.simple_address()
if obj.rm_remain_visit or vals.get('rm_remain_visit'):
visit_ids=get_model('clinic.visit').search([['patient_id','=',obj.id],['state','in',('draft','pending')]])
get_model('clinic.visit').delete(visit_ids)
print('remove visit auto %s'%visit_ids)
super().write(ids,vals,**kw)
self.function_store(ids,context=ctx)
# update name of partner
for obj in self.browse(ids):
if obj.card_type=='identification':
self.check_idcard(obj.card_type, obj.card_no)
obj.partner_id.write({
'type': 'person',
'first_name': obj.first_name or "",
'last_name': obj.last_name or "",
})
def name_get(self,ids,context={}):
vals=[]
for obj in self.browse(ids):
name=obj.name or ''
nick_name=obj.nick_name or ""
if nick_name:
name+=" (%s)"%nick_name
if obj.hn_no:
name+=" / %s"%obj.hn_no
vals.append((obj.id,name,obj.image))
return vals
def name_search(self,name,domain=None,context={},**kw):
dom=[["name","ilike","%"+name+"%"]]
if domain:
dom=[dom,domain]
ids1=self.search(dom)
dom=[["hn_no","ilike","%"+name+"%"]]
if domain:
dom=[dom,domain]
ids2=self.search(dom)
ids=list(set(ids1+ids2))
return self.name_get(ids,context=context)
def simple_address(self,ids,context={}):
print("call simple address ")
for obj in self.browse(ids):
if not obj.addresses:
address_id=get_model("address").create({
'patient_id': obj.id,
'partner_id': obj.partner_id.id,
'type': 'shipping',
'address': 'xxxx',
'address2': 'xxxx',
'city': 'BKK',
'country_id': 1,
'postal_code': '12000',
})
if context.get('called'):
return obj.id
return {
'next': {
'name': 'clinic_patient',
'mode': 'form',
'active_id': obj.id,
},'flash': 'Simple Address OK',
}
def new_dialyzer(self,ids,context={}):
dlz_id=None
for obj in self.browse(ids):
dlz_vals=get_model("clinic.dialyzer").default_get(context=context)
dlz_vals['patient_id']=obj.id
dlz_vals['company_id']=dlz_vals['company_id'][0]
dlz_vals['product_id']=dlz_vals['product_id'][0]
dlz_id=get_model('clinic.dialyzer').create(dlz_vals)
dialyzer=get_model("clinic.dialyzer").browse(dlz_id)
dialyzer.confirm()
if context.get('called'):
return dlz_id
return {
'next': {
'name': 'clinic_patient',
'mode': 'form',
'active_id': obj.id,
},'flash': 'New Dialyzer successfully',
}
def onchange_state(self,ids,context={}):
pass
def onchange_nation(self,context={}):
data=context['data']
nation_id=data['nation_id']
if nation_id:
nation=get_model("clinic.nation").browse(nation_id)
if nation.code:
if nation.code=='TH':
data['card_type']='identification'
else:
data['card_type']=''
else:
data['card_type']=''
return data
def onchange_walkin(self,context={}):
data=context['data']
if data['walkin']=='yes':
res=get_model('clinic.staff').search([['number','=','walkin'],['type','=','doctor']])
if res:
data['doctor_id']=res[0]
#else:
#data['doctor_id']=None
return data
Patient.register()