clinic/netforce_clinic/models/hd_case.py

1107 lines
40 KiB
Python

import time
from datetime import datetime
from netforce.model import Model, fields, get_model
from netforce.utils import get_data_path, get_file_path
from netforce.access import get_active_user,set_active_user
from netforce.access import get_active_company
class HDCase(Model):
_name="clinic.hd.case"
_string="HD Case"
_audit_log=True
_name_field="number"
_multi_company=True
def _get_duration(self,ids,context={}):
res={}
fmt="%Y-%m-%d %H:%M:%S"
for obj in self.browse(ids):
diff=datetime.strptime(obj.time_stop,fmt)-datetime.strptime(obj.time_start,fmt)
total_time=round(diff.seconds/3600,2)
res[obj.id]=total_time
return res
def _get_pay_amount(self,ids,context={}):
res={}
for obj in self.browse(ids):
res[obj.id]=obj.amount
return res
def _get_all(self,ids,context={}):
vals={}
for obj in self.browse(ids):
total_amt=0
rmb_amt=0
due_amt=0
for line in obj.lines:
if line.reimbursable=='yes':
rmb_amt+=line.amount or 0.0
else:
due_amt+=line.amount or 0.0
total_amt+=line.amount or 0.0
for line in obj.payment_lines:
due_amt-=line.amount or 0.0
vals[obj.id]={
"total_amount": total_amt,
"due_amount": due_amt,
'rmb_amount': rmb_amt,
'hd_case_id': obj.id,
}
return vals
def _get_patient_type(self,ids,context={}):
res={}
for obj in self.browse(ids):
patient=obj.patient_id
res[obj.id]=patient.type_id.id
return res
def _get_hct_include(self,ids,context={}):
res={}
for obj in self.browse(ids):
include=False
if obj.patient_id.type_id.hct_include:
include=True
res[obj.id]=include
return res
_fields={
"number": fields.Char("Number",required=True,search=True),
'sickbed_id': fields.Many2One("clinic.sickbed",'Sickbed'),
"ref": fields.Char("Ref",search=True),
"time_start": fields.DateTime("Start Time",required=True),
"time_stop": fields.DateTime("Finish Time",required=True),
"date": fields.Date("Date",required=True,search=True),
"patient_id": fields.Many2One("clinic.patient","Patient",required=True,search=True),
"patient_type_id": fields.Many2One("clinic.patient.type", "Type",function="_get_patient_type"),
"nurse_id": fields.Many2One("clinic.staff","Approve By", domain=[['type','=','nurse']]),
"department_id": fields.Many2One("clinic.department", "Department",search=True),
"wt_start": fields.Float("Start Wt (kg.)"),
"wt_stop": fields.Float("Finish Wt (kg.)"),
"bp_start": fields.Char("Start BP"),
"bp_stop": fields.Char("Finish BP"),
"membrane_type": fields.Selection([("unsub","Unsub cellul"),("sub","Sub cellul"),("synthetic","Synthetic")],"Member Type"),
"hd_acc": fields.Selection([("o","OPD"),("i","IPD")],"HD Acc"),
"hd_mode": fields.Selection([("chronic","Chronic"),("acute","Acute")],"HD Moode"),
"vascular_acc": fields.Many2One("clinic.vascular.access","Vascular Ac."),
"bid_flow_rate": fields.Integer("Bid Flow Rate (ml/min)"),
"ultrafittration": fields.Float("Ultrafittration (kg.)"),
"hct": fields.Integer("Hct",required=True),
"hct_msg" : fields.Char(""),
'hct_include': fields.Boolean("HCT Include", function="_get_hct_include",store=True),
"state": fields.Selection([("draft","Draft"),('waiting_treatment','Waiting Treatment'),("in_progress","In Progress"),("completed","Finish Treatment"),('paid','Paid'),("waiting_payment","Waiting Payment"),("discountinued","Discountinued"),("cancelled","Cancelled")],"Status",required=True),
"staffs": fields.One2Many("clinic.hd.case.staff","hd_case_id","Staffs"),
"comments": fields.One2Many("message","related_id","Comments"), "company_id": fields.Many2One("company","Company"),
"dialyzers": fields.One2Many("clinic.hd.case.dialyzer","hd_case_id","Dialyzers"),
"lines": fields.One2Many("clinic.hd.case.line","hd_case_id","Lines"),
"invoices": fields.One2Many("account.invoice","related_id","Invoices"),
"pickings": fields.One2Many("stock.picking","related_id","Pickings"),
"payments": fields.One2Many("account.payment","related_id","Payments"),
"payment_lines": fields.One2Many("clinic.payment","hd_case_id","Payment Lines"),
"expenes": fields.One2Many("clinic.hd.case.expense","hd_case_id","Expenses"),
'visit_id': fields.Many2One("clinic.visit", "Visit"),
'duration': fields.Integer("Duration (Hours)",function="_get_duration"),
"total_amount": fields.Float("Total",function="_get_all",readonly=True,function_multi=True),
"rmb_amount": fields.Float("Reimbursable",function="_get_all",readonly=True,function_multi=True),
"due_amount": fields.Float("Due Amount",function="_get_all",readonly=True,function_multi=True),
'fee_partner_id': fields.Many2One("partner","Contact Fee"),
'note': fields.Text("Note"),
'complication': fields.Text("Complication"),
"cycle_id": fields.Many2One("clinic.cycle","Cycle"),
'cycle_item_id': fields.Many2One("clinic.cycle.item","Cycle Item (Nurses)"), # on_delete="cascade" -> will rm visit from cycle item
'pay_amount': fields.Float("Amount",function="_get_pay_amount"),
'pay_date': fields.Date("Pay Date"),
'pay_account_id': fields.Many2One("account.account","Account"),
'payment_id': fields.Many2One("account.payment","Payment"), # for print
'dlz_id': fields.Many2One("clinic.dialyzer","Dialyzer"), # for link
"total_doctor": fields.Integer("Total Doctor",function="get_staff",function_multi=True),
"total_nurse": fields.Integer("Total Nurse",function="get_staff",function_multi=True),
'doctor_id': fields.Many2One("clinic.staff","Doctor",domain=[['type','=','doctor']],function="get_staff",function_multi=True),
'nu': fields.Char("N/U"),
"invoice_policy": fields.Selection([("fee","Only Fee"),("fee_mdc","Fee & Medicine")],"Government pay for:"),
"invoice_option": fields.Selection([("fee_mdc_plus","Combine Fee & Medicine"),("fee_mdc_split","Split Fee & Medicine")],"Invoice:"),
'req_fee': fields.Integer("Request Expense"),
'hd_case_id': fields.Many2One("clinic.hd.case","HD",function="_get_all",function_multi=True), # XXX
'company_id': fields.Many2One("company","Company"),
'branch_id': fields.Many2One("clinic.branch","Branch"),
}
def _get_number(self,context={}):
while 1:
seq_id=get_model("sequence").find_sequence(name="Clinic HD Case")
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)
_defaults={
"state": "draft",
"date": lambda *a: time.strftime("%Y-%m-%d"),
"time_start": lambda *a: time.strftime("%Y-%m-%d %H:%M:%S"),
"time_stop": lambda *a: time.strftime("%Y-%m-%d %H:%M:%S"),
'number': '/',
"company_id": lambda *a: get_active_company(),
'wt_start': 0.0,
'wt_stop': 0.0,
'bp_start': '0/0',
'bp_stop': '0/0',
"bid_flow_rate": 0.0,
"ultrafittration": 0.0,
'hd_acc': 'o',
'hd_mode': 'chronic',
'hct': 0,
'hct_msg': "สามารถเบิกค่ายาสูงสุดไม่เกิน 1,125บาท ต่อ สัปดาห์",
'invoice_option': 'fee',
'invoice_policy': 'fee',
'req_fee': 0,
'hct_include': False,
}
_order="date desc,number desc"
def onchange_dialyzer(self,context={}):
data=context["data"]
path=context["path"]
line=get_data_path(data,path,parent=True)
dialyzer_id=line.get("dialyzer_id")
if not dialyzer_id:
return {}
dialyzer=get_model("clinic.dialyzer").browse(dialyzer_id)
use_time=dialyzer.use_time or 0
max_time=dialyzer.max_use_time or 0
if use_time > max_time:
dialyzer.write({
'state': 'expire',
})
raise Exception("%s is expired"%dialyzer.number)
use_time+=1
line["description"]=dialyzer.name or dialyzer.product_id.name or ""
line["use_time"]=use_time
line["max_use_time"]=dialyzer.max_use_time
line["dialyzer_type"]=dialyzer.dialyzer_type
data['dlz_id']=dialyzer.id
return data
def onchange_cycle(self,context={}):
data=context['data']
cycle_id=data['cycle_id']
cycle=get_model("clinic.cycle").browse(cycle_id)
date=data['time_start'][0:10]
data['time_start']='%s %s'%(date, cycle.time_start)
data['time_stop']='%s %s'%(date, cycle.time_stop)
fmt="%Y-%m-%d %H:%M"
diff=datetime.strptime(data['time_stop'],fmt)-datetime.strptime(data['time_start'],fmt)
total_time=round(diff.seconds/3600,2)
data['duration']=total_time
#XXX get nurse team
return data
def onchange_patient(self,context={}):
data=context['data']
patient_id=data['patient_id']
if patient_id:
patient=get_model('clinic.patient').browse(patient_id)
department=patient.department_id
branch=patient.branch_id
cycle=patient.cycle_id
partner=patient.type_id.contact_id
if partner:
data['fee_partner_id']=partner.id
else:
data['fee_partner_id']=None
data['department_id']=department.id
data['branch_id']=branch.id
data['cycle_id']=cycle.id
data['patient_type_id']=patient.type_id.id
if patient.type_id.hct_include:
data['hct_include']=True
else:
data['hct_include']=False
data['dialyzers']=[]
doctor=patient.doctor_id
data['staffs']=[] # XXX
data['staffs'].append({
'staff_id': doctor.id,
'type': 'doctor',
'priop': 'owner',
})
return data
def onchange_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.0
line['amount']=qty*price
data=self.update_amount(context)
#bug show button
return data
def onchange_product(self,context={}):
data=context['data']
path=context['path']
line=get_data_path(data,path,parent=True)
product_id=line.get('product_id')
prod=get_model("product").browse(product_id)
line['uom_id']=prod.uom_id.id
line['description']=prod.name
line['product_categ_id']=prod.categ_id.id
qty=1
price=prod.sale_price or 0.0
amt=qty*price
line['qty']=qty
line['price']=price
line['amount']=amt
data=self.update_amount(context)
return data
def onchange_pay(self,context={}):
data=context['data']
pay_amount=data['pay_amount'] or 0
amount=data['amount'] or 0
if pay_amount > amount:
data['pay_amount']=0
return data
def update_amount(self,context={}):
data=context['data']
due_amt=0.0
rmb_amt=0.0
for line in data['lines']:
amt=line['amount'] or 0.0
reimbursable=line['reimbursable']
if reimbursable=='yes':
rmb_amt+=amt
else:
due_amt+=amt
data['rmb_amount']=rmb_amt
data['due_amount']=due_amt
data['total_amount']=due_amt+rmb_amt
data['req_fee']=0
if due_amt:
data['req_fee']=1
return data
def make_payment(self,ids,context={}):
obj=self.browse(ids)[0]
if not obj.total_amount:
return
remaining_amt=0.0
for line in obj.lines:
remaining_amt+=line.amount or 0.0
for line in obj.payment_lines:
remaining_amt-=line.amount or 0.0
partner=obj.patient_id.partner_id
if not partner:
raise Exception("Not partner")
st=get_model('settings').browse(1)
cash_account_id=st.cash_account_id.id
income_account_id=st.income_account_id.id
if not cash_account_id:
raise Exception("No Cash Account")
if not income_account_id:
raise Exception("No Income Account")
pay_amount=obj.pay_amount
if context.get("amount",0):
pay_amount=context['amount'] or 0.0
company_id=get_active_company()
vals={
"partner_id": partner.id,
"company_id": company_id,
"type": "in",
"pay_type": "direct",
'date': time.strftime("%Y-%m-%d"),
"account_id": cash_account_id,
'related_id': "clinic.hd.case,%s"%obj.id,
'ref': obj.number,
'direct_lines': [],
}
vals['direct_lines'].append(('create',{
'description': 'Payment; %s'%obj.number,
'account_id': income_account_id,
'qty': 1,
'unit_price': pay_amount,
'amount': pay_amount,
}))
payment_id=get_model("account.payment").create(vals,context={"type":"in"})
obj.write({
'state': 'paid',
'payment_lines': [('create',{
'payment_id': payment_id,
'amount': pay_amount,
})],
})
payment=get_model('account.payment').browse(payment_id)
payment.post()
return {
'next': {
'name': 'clinic_hd_case',
'mode': 'form',
'active_id': obj.id,
},
'flash': 'Pay OK',
}
def cancelled(self,ids,context={}):
obj=self.browse(ids)[0]
obj.write({" state":"cancelled"})
def make_invoices(self,ids,context={}):
setting=get_model("settings").browse(1,context)
currency_id=setting.currency_id.id
if not currency_id:
raise Exception("Currency not found in account settings")
company_id=get_active_company()
uom=get_model("uom").search_browse([['name','ilike','%Unit%']])
if not uom:
raise Exception("Unit not found in uom")
obj=self.browse(ids[0])
if obj.invoices:
for inv in obj.invoices:
inv.void()
due_date=obj.date[1:10] # XXX
# cash, credit
is_credit=context.get('is_credit') or False
context['type']='out'
context['inv_type']='invoice'
rmb_lines=[] #yes
normb_lines=[] #no
cst=get_model('clinic.setting').browse(1)
for line in obj.lines:
if line.state!='draft':
continue
prod=line.product_id
# 1.find in line
account_id=line.account_id.id
if not account_id:
# 2.find in clinic setting
for sline in cst.products:
stype=sline.patient_type_id
if stype.id==obj.patient_type_id.id and prod.id==sline.product_id.id:
account_id=sline.account_id.id
break
# 3.find in product(tab accounting)
if not account_id:
account_id=prod.sale_account_id.id
if not account_id:
raise Exception("Please define sale account for product [%s] %s"%(prod.code, prod.name))
if line.reimbursable=='yes':
rmb_lines.append(('create',{
"product_id": prod.id,
"description": line.description or "",
"qty": line.qty,
"uom_id": line.uom_id.id,
"unit_price": line.price or 0,
"amount": line.amount or 0,
'account_id': account_id,
}))
else:
normb_lines.append(('create',{
"product_id": prod.id,
"description": line.description or "",
"qty": line.qty,
"uom_id": line.uom_id.id,
"unit_price": line.price or 0,
"amount": line.amount or 0,
'account_id': account_id,
}))
patient=obj.patient_id
if rmb_lines:
ptype=patient.type_id
partner=ptype.contact_id
if not partner:
raise Exception("No contact for patient type %s"%obj.ptype.name)
account_mdc_id=partner.account_mdc_id.id
account_fee_id=partner.account_fee_id.id
account_service_id=partner.account_service_id.id
print('>>>> ', partner.id, account_service_id, account_mdc_id, account_fee_id, ' <<<')
vals={
"type": "out",
"inv_type": "invoice",
"tax_type": "tax_in",
'due_date': due_date,
"ref": obj.number,
"related_id": "clinic.hd.case,%s"%obj.id,
"currency_id": currency_id,
"company_id": company_id,
"lines": [],
"company_id": company_id,
}
vals["partner_id"]=partner.id
vals['lines']=rmb_lines
get_model("account.invoice").create(vals,context)
if normb_lines and is_credit:
partner=patient.partner_id
if not partner:
raise Exception("No contact for this patient %s"%obj.partner.name)
vals={
"type": "out",
"inv_type": "invoice",
"tax_type": "tax_in",
'due_date': due_date,
"ref": obj.number,
"related_id": "clinic.hd.case,%s"%obj.id,
"currency_id": currency_id,
"company_id": company_id,
"lines": [],
"company_id": company_id,
'partner_id':partner.id,
}
vals['lines']=normb_lines
get_model("account.invoice").create(vals,context) # create alway
obj.make_pickings()
# prevent douplicate create invoice & picking
for line in obj.lines:
line.write({
'state': 'done',
})
def make_pickings(self,ids,context={}):
obj=self.browse(ids[0])
# no picking
if not obj.lines:
return
patient=obj.patient_id
partner=patient.partner_id
if not partner:
raise Exception("Contact not for this patient")
ship_address_id=None
for address in partner.addresses:
if address.type=="shipping":
ship_address_id=address.id
break
if not ship_address_id:
patient.simple_address()
#raise Exception("contact %s dont'have address with type shipping"%partner.name)
# default journal
cust_loc_id=None
wh_loc_id=None
# find location
# 1. from department -> branch -> stock journal -> from, to
department=obj.department_id
if department:
stock_journal=department.pick_out_journal_id
if stock_journal:
wh_loc_id=stock_journal.location_from_id.id
cust_loc_id=stock_journal.location_to_id.id
print("get location from stock journal %s "%(stock_journal.name))
pick_vals={
"type": "out",
"ref": obj.number,
"related_id": "clinic.hd.case,%s"%obj.id,
"partner_id": obj.patient_id.partner_id.id,
"ship_address_id": ship_address_id,
"state": "draft",
"lines": [],
}
if not cust_loc_id:
res=get_model("stock.location").search([["type","=","customer"]])
if not res:
raise Exception("Customer location not found")
cust_loc_id=res[0]
#XXX
no_lines=context.get('no_line') or False
if no_lines:
return
prod_ids=context.get('prod_ids') or []
prod_exist_ids=[]
for line in obj.lines:
if line.state!='draft':
continue
prod=line.product_id
if prod.type != 'stock':
continue
#XXX
if prod_ids and prod.id not in prod_ids or prod.id in prod_exist_ids:
continue
prod_exist_ids.append(prod.id)
if not wh_loc_id:
wh_loc_id=prod.location_id.id
if not wh_loc_id:
res=get_model("stock.location").search([["type","=","internal"]])
if not res:
raise Exception("Warehouse not found")
wh_loc_id=res[0]
line_vals={
"product_id": prod.id,
"qty": 1,
"uom_id": prod.uom_id.id,
"location_from_id": wh_loc_id,
"location_to_id": cust_loc_id,
}
pick_vals["lines"].append(("create",line_vals))
if not pick_vals["lines"]:
return {
"flash": "Nothing left to deliver",
}
picking_obj=get_model("stock.picking")
pick_id=picking_obj.create(pick_vals,context={"pick_type": "out"})
pick=picking_obj.browse(pick_id)
pick.set_done([pick_id])
def post_invoices(self,ids,context={}):
obj=self.browse(ids[0])
for inv in obj.invoices:
#XXX
if inv.amount_total<1:
continue
inv.post()
print("Post!")
def do_treatment(self,ids,context={}):
obj=self.browse(ids)[0]
#TODO should find dlz when confirm visit
if not obj.dialyzers:
raise Exception("Please input dialyzer!")
vals={
'state': 'in_progress',
}
if obj.number=='/':
number=self._get_number()
vals['number']=number
# update start time
st=get_model("clinic.setting").browse(1)
if st.real_time:
timenow=time.strftime("%H:%M:%S")
date=obj.date
vals['time_start']='%s %s'%(date,timenow)
vals['time_stop']='%s %s'%(date,timenow)
obj.write(vals)
def discontinue(self,ids,context={}):
obj=self.browse(ids)[0]
# TODO pop to note
obj.write({"state":"cancelled"})
def update_usetime(self,ids,context={}):
for obj in self.browse(ids):
is_decrease=context.get('is_decrease')
for dlz_line in obj.dialyzers:
dlz=dlz_line.dialyzer_id
use_time=dlz_line.use_time or 0
if is_decrease:
use_time-=1
print("decrease ok")
print("use_time ", use_time)
if dlz_line.use_time < dlz.max_use_time:
dlz.write({
'use_time': use_time,
})
elif dlz_line.use_time==dlz.max_use_time:
dlz.write({
'use_time': use_time,
'state': 'expire',
})
else:
raise Exception("Dialyzer is expired!")
return True
def create_cycle_item(self,ids,context={}):
for obj in self.browse(ids):
cycle_item=get_model("clinic.cycle.item")
datenow=obj.time_start[0:10]
if not datenow:
datenow=time.strftime('%Y-%m-%d')
cycle_id=obj.cycle_id.id
branch_id=obj.branch_id.id
dom=[]
if datenow:
dom.append(['date','=',datenow])
if cycle_id:
dom.append(['cycle_id','=',cycle_id])
if branch_id:
dom.append(['branch_id','=',branch_id])
cycle_item_ids=cycle_item.search(dom)
cycle_item_id=None
if cycle_item_ids:
cycle_item_id=cycle_item_ids[0]
else:
cycle_item_id=cycle_item.create({
'date': obj.date,
'cycle_id': obj.cycle_id.id,
})
obj.write({
'cycle_item_id': cycle_item_id,
})
return True
def do_expense(self,ids,context={}):
for obj in self.browse(ids):
# clear old expense
for exp in obj.expenes:
exp.delete()
exp_lines=[]
fee=0.0
mdc=0.0
srv=0.0
other=0.0
for line in obj.lines:
amt=line.amount or 0.0
if line.reimbursable=='no':
amt=0
categ=line.product_categ_id
if categ.code=='FEE':
fee+=amt
elif categ.code=='EPO':
mdc+=amt
elif categ.code=='SRV':
srv+=amt
else:
other+=amt
exp_lines.append(('create',{
'date': obj.date,
'patient_id': obj.patient_id.id,
'hd_case_id': obj.id,
'fee_amt': fee,
'mdc_amt': mdc,
'srv_amt': srv,
'state': 'waiting_matching',
}))
obj.write({
'expenes': exp_lines,
})
def complete(self,ids,context={}):
obj=self.browse(ids)[0]
obj.make_invoices(context=context)
obj.post_invoices(context=context)
obj.create_cycle_item()
obj.do_expense(context=context)
vals={
"state":"waiting_payment", # for government
}
st=get_model("clinic.setting").browse(1)
if st.real_time:
timenow=time.strftime("%H:%M:%S")
date=obj.date
vals['time_stop']='%s %s'%(date,timenow)
obj.write(vals)
if context.get("called"):
return obj.id
return {
'next': {
'name': 'clinic_hd_case',
'mode': 'form',
'active_id': obj.id,
},
'flash': '%s is completed'%obj.number,
}
def delete(self,ids,context={}):
for obj in self.browse(ids):
if obj.state != 'draft':
raise Exception("Can not delete HD Case %s because state is not draft"%obj.number)
super().delete(ids)
def onchange_hct(self,context={}):
data=context['data']
if not data.get("hct"):
data['hct']=0
hct=data["hct"]
msg=""
# XXX do not hard code
if(hct<=36):
msg="สามารถเบิกค่ายาสูงสุดไม่เกิน 1,125บาท ต่อ สัปดาห์"
elif(hct>36 and hct<=39):
msg="สามารถเบิกค่ายาสูงสุดไม่เกิน 750บาท ต่อ สัปดาห์"
elif(hct> 39):
msg="ไม่สามารถเบิกค่ายาฉีดได้ทุกตัว"
data['hct_msg']=msg
return data
def undo(self,ids,context={}):
obj=self.browse(ids)[0]
context['is_decrease']=True
obj.update_usetime(context=context)
for line in obj.lines:
line.write({
'state': 'draft',
})
for inv in obj.invoices:
inv.write({
'state': 'draft',
})
inv.move_id.to_draft()
inv.move_id.delete()
inv.delete()
for pick in obj.pickings:
pick.write({
'state': 'draft',
})
pick.delete()
for payment in obj.payments:
payment.to_draft()
payment.delete()
for pm_line in obj.payment_lines:
pm_line.delete()
for exp in obj.expenes:
exp.delete()
state=context.get("state","in_progress") #force state
obj.write({
'state': state,
})
return {
'next': {
'name': 'clinic_hd_case',
'mode': 'form',
'active_id': obj.id,
},
'flash': '%s has been undo'%obj.number,
}
def view_payment(self,ids,context={}):
print("clinic_view_payment")
return {
'next': {
'name': 'payment',
'mode': 'form',
'active_id': ids[0],
},
}
def request_fee(self,ids,context={}):
obj=self.browse(ids)[0]
#obj.update_usetime()
obj.complete()
# send some message to anyboby: patient
return {
'next': {
'name': 'clinic_hd_case',
'mode': 'form',
'active_id': obj.id,
}
}
def pay(self,ids,context={}):
return {
'next': {
'name': 'clinic_payment',
'refer_id': ids[0], #XXX
}
}
def done(self,ids,context={}):
obj=self.browse(ids)[0]
obj.update_usetime()
obj.write({
'state': 'completed',
})
obj.sickbed_id.write({
'state': 'available',
})
return {
'next': {
'name': 'clinic_hd_case',
'mode': 'form',
'active_id': obj.id,
},
'flash': 'Finish treatment!',
}
def get_report_payment_data(self,context={}):
settings=get_model("settings").browse(1)
refer_id=context.get("refer_id")
payment_id=context.get("payment_id")
data={
'settings_address_text': settings.default_address_id and settings.default_address_id.get_address_text()[settings.default_address_id.id] or "",
'logo': get_file_path(settings.logo) or "",
}
if refer_id:
pass
if payment_id:
#context['refer_id']=payment_id
#data=get_model("account.payment").get_report_data(context=context)
payment=get_model("account.payment").browse(int(payment_id))
partner_address_id=payment.partner_id.default_address_id
data['number']=payment.number
data['ref']=payment.related_id.number
data['date']=payment.date
data['partner_name']=payment.partner_id.name or 0
data['partner_address_text']=partner_address_id and partner_address_id.get_address_text()[partner_address_id.id] or "",
lines=[]
for line in payment.direct_lines:
lines.append({
'description': line.description or '',
'qty': line.qty,
'unit_price': line.unit_price or 0.0,
'amount': line.amount or 0.0,
})
data['lines']=lines
data['amount_subtotal']=payment.amount_subtotal or 0.0
data['amount_tax']=payment.amount_tax or 0.0
data['amount_total']=payment.amount_total or 0.0
return data
def new_dialyzer(self,ids,context={}):
obj=self.browse(ids)[0]
is_wiz=context.get("is_wiz")
dlz_vals={}
if is_wiz:
pop_id=context.get('pop_id')
if pop_id:
pop=get_model("clinic.hd.case.popup.dlz").browse(pop_id)
prod=pop.product_id
dlz_vals={
'product_id': prod.id,
'name': prod.name or "",
'note': pop.note or '',
'use_time': 0,
'max_use_time': pop.max_use_time,
'dialyzer_type': pop.dialyzer_type,
'exp_date': pop.exp_date,
'department_id': obj.department_id.id,
'patient_id': obj.patient_id.id,
'visit_id': obj.visit_id.id,
}
else:
dlz_vals=get_model("clinic.dialyzer").default_get()
dlz_vals['patient_id']=obj.patient_id.id
dlz_vals['company_id']=dlz_vals['company_id'][0]
product_name=dlz_vals['product_id'][1]
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()
vals={
'dlz_id': dlz_id,
'dialyzers': [],
}
vals['dialyzers'].append(('create',{
'dialyzer_id': dlz_id,
'description': dialyzer.name or product_name,
'use_time': 1,
'max_use_time': dialyzer.max_use_time,
'dialyzer_type': dialyzer.dialyzer_type,
}))
obj.write(vals)
if context.get('called'):
return obj.id
return {
'next': {
'name': 'clinic_hd_case',
'mode': 'form',
'active_id': obj.id,
},
'flash': 'Create new dialyzer successfully',
}
def to_draft(self,ids,context={}):
obj=self.browse(ids)[0]
context['state']='draft'
obj.undo(context=context)
def get_staff(self,ids,context={}):
res={}
for obj in self.browse(ids):
doctor=0
nurse=0
doctor_id=None
for ps in obj.staffs:
if ps.type=="doctor":
if ps.priop=='owner':
doctor_id=ps.staff_id.id
doctor+= 1
else:
nurse+=1
res[obj.id]={
'total_doctor': doctor,
'total_nurse': nurse,
'doctor_id': doctor_id,
}
return res
def get_staff_line(self,vals,patient_id=None):
if not patient_id:
return vals
# staff
patient=get_model("clinic.patient").browse(patient_id)
if not vals.get('staffs'):
vals['staffs']=[]
doctor=patient.doctor_id
if doctor:
vals['staffs'].append(('create',{
'staff_id': doctor.id,
'type': 'doctor',
'priop': 'owner',
}))
# fee
st=get_model("clinic.setting").browse(1)
if st.auto_gen:
return vals
if not vals.get('lines'):
vals['lines']=[]
for st_prod in st.products:
if patient.type_id.id==st_prod.patient_type_id.id:
prod=st_prod.product_id
price=st_prod.price
qty=st_prod.qty
amt=st_prod.amount
account_id=st_prod.account_id.id
if not account_id:
account_id=prod.sale_account_id.id
if not account_id:
raise Exception("Please define sale account for product [%s] %s"%(prod.code, prod.name))
if not amt:
amt=qty*price
categ=st_prod.product_categ_id
vals['lines'].append(('create',{
'product_id': prod.id,
'uom_id': st_prod.uom_id.id,
'product_categ_id': categ.id,
'description': st_prod.description,
'price': price,
'qty': qty,
'reimbursable': st_prod.reimbursable,
'amount': amt,
'account_id': account_id,
}))
# XXX need to get default
partner=patient.type_id.contact_id
if partner:
vals['fee_partner_id']=partner.id
if not partner:
raise Exception("Not found contact %s at menu: Patiens -> Type"%patient.type_id.name)
return vals
def get_invoice_policy(self,vals={},patient_id=None):
if patient_id:
patient=get_model("clinic.patient").browse(patient_id)
st=get_model("clinic.setting").browse(1)
for pl in st.invoice_policies:
policy=pl.invoice_policy
patient_type=pl.patient_type_id
opt=pl.invoice_option
if patient.type_id.id==patient_type.id:
vals['invoice_policy']=policy
vals['invoice_option']=opt
break
return vals
def create(self,vals,**kw):
patient_id=vals['patient_id']
vals=self.get_staff_line(vals,patient_id)
new_id=super().create(vals,**kw)
self.function_store([new_id])
return new_id
def write(self,ids,vals,**kw):
obj=self.browse(ids)[0]
############ to show pay button ###########
total_amt=0
due_amt=0
if 'lines' in vals.keys():
for line in vals['lines']:
mode=line[0]
amt=0
rmb='no'
if mode=='create':
line_vals=line[1]
amt=line_vals.get("amount",0)
elif mode=='delete':
continue
else:
mode=line[0]
if mode=='create':
prod_id=line[1]['product_id']
prod=get_model("product").browse(prod_id)
line['uom_id']=prod.uom_id.id
continue
line_id=line[1][0]
line_vals=line[2]
rmb=line_vals.get("reimbursable","no")
line=get_model('clinic.hd.case.line').browse(line_id)
amt=line.amount or 0
total_amt+=amt
if rmb=='no':
due_amt+=amt
else:
for line in obj.lines:
amt=line.amount or 0
total_amt+=amt
if line.reimbursable=='no':
due_amt+=amt
pay_amt=0
if 'payment_lines' in vals.keys():
for line in vals['payment_lines']:
mode=line[0]
if mode=='create':
line_vals=line[1]
else:
line_vals=line[2]
pay_amt+=line_vals.get("amount",0)
for pline in obj.payment_lines:
pay_amt+=pline.amount or 0
due_amt-=pay_amt
vals['req_fee']=0
if due_amt<=0:
vals['req_fee']=0
elif due_amt>0:
vals['req_fee']=1
#################################################3
if 'sickbed_id' in vals.keys():
if vals['sickbed_id']!=obj.sickbed_id.id and obj.state!='draft':
if obj.sickbed_id:
obj.sickbed_id.write({
'state': 'available',
})
sb=get_model("clinic.sickbed").browse(vals['sickbed_id'])
sb.write({
'state': 'not_available',
})
self.function_store(ids)
super().write(ids,vals,**kw)
def approve(self,ids,context={}):
obj=self.browse(ids)[0]
obj.write({
'state': 'completed',
})
return {
'next': {
'name': 'clinic_hd_case',
'mode': 'form',
'active_id': obj.id,
},
'flash': '%s has been approval'%obj.number,
}
HDCase.register()