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="Treatment" _audit_log=True _name_field="number" _multi_company=True def get_hrs(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 _fields={ "number": fields.Char("Number",required=True,search=True), "time_start": fields.DateTime("Time start",required=True,search=True), "time_stop": fields.DateTime("Time stop",required=True,search=True), "date": fields.Date("Time stop",required=True,search=True), "patient_id": fields.Many2One("clinic.patient","Patient",required=True,search=True), "doctor_id": fields.Many2One("clinic.doctor","Doctor", required=False,search=True), "nurse_id": fields.Many2One("clinic.nurse","Nurse", required=True,search=True), "department_id": fields.Many2One("clinic.department", "Department",search=True), "wh_start": fields.Float("Wt.Kg start"), "wh_stop": fields.Float("Wt.Kg stop"), "bp_start": fields.Integer("BP mmHG start"), "per_bp_start": fields.Integer("/Per start"), "bp_stop": fields.Integer("BP mmHG stop"), "per_bp_stop": fields.Integer("/Per stop"), "epo_tn" : fields.Char("EpoTn (Drug name)"), "epo_unit" : fields.Integer("EpoUnit (Unit of Used drug)"), "hct": fields.Integer("HCT %"), "hct_msg" : fields.Char("HCT message"), "check_goverment_pay" : fields.Boolean("The Government Pay"), "check_personal_pay" : fields.Boolean("Pay yourself"), "state": fields.Selection([("draft","Draft"),("in_progress","In Progress"),("completed","Completed"),("waiting_payment","Waiting Payment"),("discountinued","Discountinued"),("in_completed","In completed")],"Status",required=True), "dialyzers": fields.One2Many("clinic.dialyzer.line","hd_case_id","Dialyzers"), "lines": fields.One2Many("clinic.hd.case.line","hd_case_id","Lines"), "comments": fields.One2Many("message","related_id","Comments"), "company_id": fields.Many2One("company","Company"), "amount": fields.Float("Due Amount",function="get_total",readonly=True,function_multi=True), "total": fields.Float("Total",function="get_total",readonly=True,function_multi=True), "reconcile_id": fields.Many2One("account.reconcile","Reconcile Id",readonly=True), "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"), 'visit_id': fields.Many2One("clinic.visit", "Visit"), 'duration': fields.Integer("Duration (hrs)",function="get_hrs"), 'fee_partner_id': fields.Many2One("partner","Contact Fee"), "fee_amount": fields.Float("Fee",function="get_total",readonly=True,function_multi=True), 'fee_paid': fields.Boolean("Fee Paid"), 'note': fields.Text("Note"), "cycle_id": fields.Many2One("clinic.cycle","Cycle"), "cycle_item_id": fields.Many2One("clinic.cycle.item","Cycle Item",on_delete="cascade"), # compute labor cost '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 } 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) def _get_nurse(self,context={}): user_id=get_active_user() print("user_id ",user_id) nurse_ids=get_model("clinic.nurse").search([['user_id','=',user_id]]) if nurse_ids: return nurse_ids[0] return None _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"), 'nurse_id': _get_nurse, "number": _get_number, "company_id": lambda *a: get_active_company(), 'hct': 0, 'hct_msg': "Reimbursement of medicines : 1,125/Week", 'fee_paid': 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.description or dialyzer.product_id.name or "" line["use_time"]=use_time line["max_use_time"]=dialyzer.max_use_time line["member_type"]=dialyzer.member_type line["dialyzer_type"]=dialyzer.dialyzer_type line["bid_flow_rate"]=dialyzer.bid_flow_rate line["ultrafittration"]=dialyzer.ultrafittration line["state"]=dialyzer.state data['dlz_id']=dialyzer.id return data def onchange_patient(self,context={}): data=context['data'] patient_id=data['patient_id'] hd_cases=self.search_browse([['patient_id','=',patient_id]]) # TODO reset dialyzer if hd_cases: hd_case=hd_cases[-1] data['doctor_id']=hd_case.doctor_id.id data['department_id']=hd_case.department_id.id else: data['doctor_id']=None data['department_id']=None 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') if not product_id: return prod=get_model("product").browse(product_id) line['uom_id']=prod.uom_id.id line['description']=prod.name line['qty']=1 line['price']=prod.sale_price or 0.0 line['amount']=prod.sale_price or 0.0 self.onchange_line(context) return data def onchange_line(self,context={}): data=context['data'] total=0.0 fee_amt=0.0 for line in data['lines']: price=line.get('price') or 0 qty=line.get('qty') or 0 amt=qty * price line['amount']=amt if line['type']=='fee': fee_amt+=amt else: total+=amt data['total']=total+fee_amt data['fee_amount']=fee_amt for line in data['payment_lines']: total-=line['amount'] or 0.0 data['amount']=total if not data.get('pay_date'): data['pay_date']=time.strftime("%Y-%m-%d") if not data.get('pay_account_id'): patient_id=data['patient_id'] if patient_id: patient=get_model("clinic.patient").browse(patient_id) partner=patient.partner_id if partner: account_id=partner.account_payable_id if not account_id: settings=get_model("settings").browse(1) account_id=settings.account_receivable_id data['pay_account_id']=account_id.id 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 make_payment(self,ids,context={}): obj=self.browse(ids)[0] if not obj.total: 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_id=obj.patient_id.partner_id.id if not partner_id: raise Exception("No contact on this patient") company_id=get_active_company() account_id=obj.pay_account_id.id if not account_id: raise Exception("No Account for payment") pay_amount=obj.pay_amount # XXX get from popup if context.get("amount",0): pay_amount=context['amount'] or 0.0 vals={ "partner_id": partner_id, "company_id": company_id, "type": "in", "pay_type": "direct", "date": obj.pay_date, "account_id": account_id, 'related_id': "clinic.hd.case,%s"%obj.id, 'direct_lines': [], } vals['direct_lines'].append(('create',{ 'description': 'Payment; %s'%obj.number, 'account_id': account_id, 'qty': 1, 'unit_price': pay_amount, 'amount': pay_amount, })) payment_id=get_model("account.payment").create(vals,context={"type":"in"}) obj.write({ '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 onchange_gmproduct(self,context={}): data=context['data'] path=context["path"] line=get_data_path(data,path,parent=True) product_id=line.get('product_id') if not product_id: return prod=get_model("product").browse(product_id) line['uom_id']=prod.uom_id.id line['description']=prod.name line['qty']=1 line['price']=prod.sale_price or 0.0 line['amount']=prod.sale_price or 0.0 data=self.onchange_gmline(context) return data def make_invoices(self,ids,context={}): setting=get_model("settings").browse(1) currency_id=setting.currency_id.id account_receivable_id=setting.account_receivable_id.id 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]) due_date=obj.date[0:10] # cash, credit make_invoice=context.get('make_invoice',True) context['type']='out' context['inv_type']='invoice' fee_lines=[] if obj.lines: 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=obj.patient_id.partner_id if not partner: raise Exception("No contact for patient %s"%obj.patient_id.name) vals["partner_id"]=partner.id for line in obj.lines: if line.product_id: account_id=line.product_id.sale_account_id.id or account_receivable_id else: account_id=account_receivable_id inv_line={ "product_id": line.product_id.id, "description": line.description, "qty": line.qty, "uom_id": line.uom_id.id, "unit_price": line.price, "amount": line.amount, 'account_id': account_id, } if line.type=='fee': fee_lines.append(inv_line) else: vals['lines'].append(('create',inv_line)) if obj.amount and make_invoice: ## not pay yet inv_id=get_model("account.invoice").create(vals,context) # create picking obj.make_pickings() if fee_lines and not obj.fee_paid: 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"]=obj.fee_partner_id.id account_id=account_receivable_id patient_type=obj.patient_id.type if patient_type=='mg': account_id=setting.ar_mg_id.id elif patient_type=='sc': account_id=setting.ar_sc_id.id elif patient_type=='nhso': account_id=setting.ar_nhso_id.id for fee_line in fee_lines: fee_line['account_id']=account_id vals['lines'].append(('create',fee_line)) inv_id=get_model("account.invoice").create(vals,context) obj.write({ 'fee_paid': True, }) def make_pickings(self,ids,context={}): obj=self.browse(ids[0]) # no picking if not obj.lines: return partner=obj.patient_id.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: raise Exception("contact %s dont'have address with type shipping"%partner.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": [], } res=get_model("stock.location").search([["type","=","customer"]]) if not res: raise Exception("Customer location not found") cust_loc_id=res[0] for line in obj.lines: prod=line.product_id if prod.type != 'stock': print("continue ") continue 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: inv.post() print("Post!") def do_treatment(self,ids,context={}): obj=self.browse(ids)[0] if not obj.dialyzers: raise Exception("Can not do treatment without dialyzer!") obj.write({"state":"in_progress"}) def discontinue(self,ids,context={}): obj=self.browse(ids)[0] # TODO pop to note obj.write({"state":"in_completed"}) def update_usetime(self,ids,context={}): for obj in self.browse(ids): for dlz_line in obj.dialyzers: dlz=dlz_line.dialyzer_id #XXX if dlz_line.use_time > dlz.use_time: dlz.write({ 'use_time': dlz_line.use_time, }) return True def create_cycle_item(self,ids,context={}): for obj in self.browse(ids): cycle_item=get_model("clinic.cycle.item") datenow=obj.start_time[0:10] if not datenow: datenow=time.strftime('%Y-%m-%d') cycle_id=obj.cycle_id.id cycle_item_ids=cycle_item.search([['date','=',datenow],['cycle_id','=',cycle_id]]) cycle_item_id=None if cycle_item_ids: cycle_item_id=cycle_item_ids[0] else: cycle_item_id=cycle_item.create({ 'cycle_id': obj.cycle_id.id, }) obj.write({ 'cycle_item_id': cycle_item_id, }) return True def complete(self,ids,context={}): obj=self.browse(ids)[0] obj.make_invoices() obj.post_invoices() obj.update_usetime() obj.create_cycle_item() obj.write({ "state":"completed", }) return { 'next': { 'name': 'clinic_hd_case', 'mode': 'form', 'active_id': obj.id, }, 'flash': '%s is completed'%obj.number, } def journal_report(self,ids,context={}): obj=self.browse(ids[0]) move_id = get_model("account.move").search([["narration","=",obj.number]]) if not move_id: raise Exception("Order is not post or nove have jounal entry.") return { "next": { "name": "journal_entry", "mode":"form", "active_id":move_id[0], } } def get_total(self,ids,context={}): vals={} for obj in self.browse(ids): total=0 due_amt=0 fee_amt=0 for line in obj.lines: if line.type=='fee': fee_amt+=line.amount or 0.0 total+=line.amount or 0.0 due_amt=total-fee_amt for line in obj.payment_lines: due_amt-=line.amount or 0.0 vals[obj.id]={ "total": total, "amount": due_amt, 'fee_amount': fee_amt, } return vals 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="" if(hct<=36): msg="Reimbursement of medicines : 1,125/Week" elif(hct>36 and hct<39): msg="Reimbursement of medicines : 750/Week" elif(hct>=39): msg="Can not be drawn" data['hct_msg']=msg return data def undo(self,ids,context={}): obj=self.browse(ids)[0] for inv in obj.invoices: inv.write({ 'state': 'draft', }) 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() state=context.get("state","in_progress") #force state obj.write({ 'state': state, 'fee_paid': False, }) 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 done(self,ids,context={}): obj=self.browse(ids)[0] obj.update_usetime() state='waiting_payment' if not obj.amount: obj.complete() else: obj.write({ 'state': state, }) 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] 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.description or product_name, 'use_time': 1, 'max_use_time': dialyzer.max_use_time, 'member_type': dialyzer.member_type, 'dialyzer_type': dialyzer.dialyzer_type, 'bid_flow_rate': dialyzer.bid_flow_rate, 'ultrafittration': dialyzer.ultrafittration, 'state': dialyzer.state, })) obj.write(vals) 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) HDCase.register()