clinic/netforce_clinic/models/setting.py

350 lines
13 KiB
Python

import time
import random
import datetime
import xlrd
import xmltodict
from netforce.model import Model, fields, get_model
from netforce.utils import get_file_path, get_data_path
from netforce.access import get_active_company
class ClinicSetting(Model):
_name="clinic.setting"
_string="Setting"
_fields={
"var_k": fields.Float("K"),
'file': fields.File("File"),
'levels': fields.One2Many("clinic.setting.level","setting_id","Levels"),
'products': fields.One2Many("clinic.setting.product","setting_id","Products"),
'invoice_policies': fields.One2Many("clinic.setting.policy","setting_id","Invoice Policies"),
'cost_per_case': fields.Float("Cost Per Case"),
'company_id': fields.Many2One("company", 'Company'),
'period_id': fields.Many2One("clinic.period","Period"),
'waiting_approval': fields.Boolean("Waiting Approval"),
}
_defaults={
"company_id": lambda *a: get_active_company(),
}
def read_excel(self,fpath=None):
data={}
if fpath:
suffix=fpath.split(".")[-1]
if suffix not in ('xls', 'xlsx'):
raise Exception("ERROR : please should file xls or xlsx")
wb=xlrd.open_workbook(fpath)
sheet=wb.sheet_by_name("Sheet1")
# read header values into the list
keys = [sheet.cell(0, col_index).value for col_index in range(sheet.ncols)]
data=[]
for row_index in range(1, sheet.nrows):
#d = {(keys[col_index] or "").lower(): sheet.cell(row_index, col_index).value for col_index in range(sheet.ncols)}
d={}
for col_index in range(sheet.ncols):
ctype=sheet.cell(row_index,col_index).ctype
if ctype==3:
value=sheet.cell(row_index, col_index).value
year, month, day, hour, minute, second = xlrd.xldate_as_tuple(value,wb.datemode)
value=datetime.datetime(year, month, day, hour, minute,second)
value=value.strftime("%Y-%m-%d")
else:
value=sheet.cell(row_index, col_index).value
d.update({(keys[col_index] or "").lower():value})
data.append(d)
return data
def make_visit(self,ids,context={}):
obj=self.browse(ids)[0]
fname=obj.file
fpath=get_file_path(fname)
lines=self.read_excel(fpath)
if not lines:
raise Exception("Wrong File")
for line in lines:
hcode=line.get('hcode18','0')
if not hcode:
hcode='0'
hcode=int(hcode)
hcode=str(hcode)
if obj.hcode==hcode:
invno=line.get("invno","")
name=line.get("name14")
hn=line.get('hn',"")
hct=line.get("HCT","")
amount=line.get("amount23",0)
dttran=line.get("dttran","")
#==== product =====
prod_code=line.get("code31","")
prod_name=line.get('eponame',"")
prod_qty=line.get("qty",0)
prod_unit=line.get("unit32","")
prod_ids=get_model("product").search([['code','=',prod_code]])
if not prod_ids:
print('create')
vals={
'code': prod_code,
'name': prod_name,
'type': 'stock',
}
unit_ids=get_model("uom").search([['name','=',prod_unit]])
if not unit_ids:
prod_unit_id=get_model("uom").create({
'name': prod_unit,
'type': 'unit',
})
else:
prod_unit_id=unit_ids[0]
vals['uom_id']=prod_unit_id
prod_id=get_model("product").create(vals)
print("create product ", prod_id, prod_name)
# ================
print(dttran, invno, hcode, hn, name, hct, amount)
return
def _make_visit(self,ids,context={}):
obj=self.browse(ids)[0]
fname=obj.file
fpath=get_file_path(fname)
lines=self.read_excel(fpath)
if not lines:
raise Exception("Wrong File")
medicals=[]
patients=[]
for line in lines:
medical=line.get('medical') or line.get('eponame') or ""
if not medical in medicals:
medicals.append(medical)
patient=line.get('hn','')
name14=line.get('name14') or ""
value=(patient,name14)
if not value in patients:
patients.append(value)
products=[p['name'] for p in get_model("product").search_read([],['name'])]
print('generate product')
print("="*50)
seq=6
for md in medicals:
md=md.replace(" ","")
if not md:
continue
if not md in products:
vals={
'code': "m"+("%s"%seq).zfill(4),
'name':md,
'uom_id': 2,
'type': 'stock',
}
seq+=1
prod_id=get_model("product").create(vals)
print(prod_id)
print("="*50)
print('generate patient')
hns=[pt['hn'] for pt in get_model("clinic.patient").search_read([],['hn'])]
for hn, name in patients:
hn=hn.replace(' ',"")
if not hn:
continue
if not hn in hns:
vals={
'hn': hn,
'name': name,
'type': 'sc',
}
pt_id=get_model("clinic.patient").create(vals)
print('hn ', pt_id)
print("="*50)
patients=get_model("clinic.patient").search_read([],['name','hn'])
visits=get_model("clinic.visit").search_read([],['number','time_start','cycle_id','state'])
doctor_ids=[dt['id'] for dt in get_model("clinic.staff").search_read([['type','=','doctor']],['name'])]
nurse_ids=[ns['id'] for ns in get_model("clinic.staff").search_read([['type','=','nurse']],['name'])]
cycle_ids=[cc['id'] for cc in get_model("clinic.cycle").search_read([],['name'])]
department_ids=[dp['id'] for dp in get_model("clinic.department").search_read([],['name'])]
#db=get_connection()
def get_patient(hn):
for pt in patients:
if hn==pt['hn']:
return pt
return None
def get_visit(date,state=None):
for visit in visits:
if date==visit['time_start'][0:10]:
if state:
if visit['state']==state:
return visit
else:
return None
return visit
print("="*50)
print("create simple visit")
timenow=time.strftime("%H:%M:%S")
timenow2="%s:%s:%s" % (int(time.strftime("%H"))+1, time.strftime("%M"), time.strftime("%S"))
time_start=timenow
for line in lines:
hn=line['hn']
date=line['dttran']
visit=get_visit(date)
if not visit:
patient=get_patient(hn)
if patient:
time_start="%s %s"%(date,timenow)
time_stop="%s %s"%(date,timenow2)
vals={
'time_start': time_start,
'time_stop': time_stop,
'patient_id': patient['id'],
'cycle_id': random.choice(cycle_ids),
'nurse_id': random.choice(nurse_ids),
'doctor_id': random.choice(doctor_ids),
'department_id': random.choice(department_ids),
}
visit_id=get_model("clinic.visit").create(vals)
print("create visit %s ", visit_id)
print("="*50)
print("visit with state is draft")
return #XXXX
count=0
for line in lines:
date=line['dttran']
# prevent timeout
if count > 10:
break
visit=get_visit(date=date,state='draft')
print(date, ' ', visit)
if visit:
visit_id=visit['id']
context['called']=True
hd_case_id=get_model("clinic.visit").browse(visit_id).confirm(context=context)
#allow37=line['allow37']
hct=line.get('hct')
medical=line.get('medical') or line.get("eponame") or ""
vals={
'hct': hct and hct or 0,
}
hd_case=get_model("clinic.hd.case").browse(hd_case_id)
hd_case.write(vals)
count+=1
print("#%s write hd_case %s ok and visit %s" % (count,hd_case_id,hd_case.visit_id.number))
print("="*50)
print("Done")
return
def make_done(self,ids,context={}):
obj=self.browse(ids)[0]
fname=obj.file
fpath=get_file_path(fname)
lines=self.read_excel(fpath)
if not lines:
raise Exception("Wrong File")
def get_line(hn,date):
for line in lines:
if hn==line['hn'] and date==line['dttran']:
return line
count=0
for visit in get_model("clinic.visit").search_browse([['state','=','draft']]):
if count > 200:
break
count+=1
context['called']=True
hd_case_id=visit.confirm(context=context)
hn=visit.patient_id.hn
date_visit=visit.time_start[0:10]
line=get_line(hn,date_visit)
if line:
hct=line.get('hct')
medical=line.get('medical') or line.get('eponame') or ""
medical_cost=line.get('medical_cost') or line.get("allow37") or ""
inject_service=line.get('inject_service') or line.get("EPOadm29") or ""
vals={
'hct': hct and hct or 0,
}
if medical:
prods=get_model("product").search_browse([['name','=',medical]])
if prods:
prod=prods[0]
vals['lines'].append(('create',{
'type': 'fee',
'product_id': prod.id,
'description': prod.name,
'uom_id': prod.uom_id.id,
'qty': 1,
'price': medical_cost,
'amount': medical_cost,
}))
if inject_service:
prod=get_model("product").browse(55)
vals['lines'].append(('create',{
'type': 'other',
'product_id': 55, #XXX
'description': prod.name,
'uom_id': prod.uom_id.id,
'qty': 1,
'price': medical_cost,
'amount': medical_cost,
}))
hd_case=get_model("clinic.hd.case").browse(hd_case_id)
hd_case.write(vals)
print("#%s make hd_case %s ok "%(count,hd_case.number))
def make_complete(self,ids,context={}):
context['called']=True
count=0
for hd_case in get_model('clinic.hd.case').search_browse(['state','=','draft']):
if count > 100:
break
if not hd_case.dialyzers:
patient=hd_case.patient_id
if not patient.addresses:
patient.simple_address()
hd_case.new_dialyzer(context=context)
hd_case.complete()
print("%s is completed"%hd_case.number)
count+=1
def onchange_line(self,context={}):
data=context['data']
path=context['path']
line=get_data_path(data,path,parent=True)
var_a=line['var_a'] or ''
var_b=line['var_b'] or ''
op=line['op'] or ''
line['formular']='%sX%s%s'%(var_a,op,var_b)
return data
def onchange_product(self,context={}):
data=context['data']
path=context['path']
line=get_data_path(data,path,parent=True)
product_id=line['product_id']
if product_id:
prod=get_model("product").browse(product_id)
uom=prod.uom_id
if not uom:
uom=get_model("uom").browse(1)
if not uom:
raise Exception("Not found uom 'Unit'")
line['uom_id']=uom.id
line['description']=prod.name
price=prod.sale_price or 0.0
line['price']=price
qty=line['qty'] or 0
amt=qty*price
line['amount']=amt
return data
def onchange_setting_line(self,context={}):
data=context['data']
path=context['path']
line=get_data_path(data,path,parent=True)
qty=line['qty'] or 0
price=line['price'] or 0
amt=qty*price
line['amount']=amt
return data
ClinicSetting.register()