clinic/netforce_clinic/models/import_payment.py

443 lines
14 KiB
Python

import time
import xlrd
from netforce.model import Model, fields, get_model
from netforce.access import get_active_company
from netforce.utils import get_file_path
from netforce.utils import get_data_path
from netforce.database import get_connection
PAMENT_TYPE={
"mg":"Medical Government",
"sc":"Social Security",
"nhso":"NHSO (30฿)",
"personal": "Personal",
"others": "Others",
}
class ImportPayment(Model):
_name="clinic.import.payment"
_string="Import Payment"
_fields={
'name': fields.Char("Name"),
"type": fields.Selection([("mg","Medical Government"),("sc","Social Security"),("nhso","NHSO (30฿)")],"Type"),
'date_import': fields.DateTime("Date"),
'file': fields.File("File"),
'sheets': fields.One2Many("clinic.file.sheet","imp_id", "Sheets"),
'mg_payment_id': fields.Many2One("account.payment","Payment"),
'mg_move_id': fields.Many2One("account.move","Journal Entry"),
'sc_payment_id': fields.Many2One("account.payment","Payment"),
'sc_move_id': fields.Many2One("account.move","Journal Entry"),
'nhso_payment_id': fields.Many2One("account.payment","Payment"),
'nhso_move_id': fields.Many2One("account.move","Journal Entry"),
"state": fields.Selection([("draft","Draft"),("success","Succes"),("fail","Fail"),('close','Close')],"Status"),
'note': fields.Text("Note"),
'partner_id': fields.Many2One("partner","Contact"),
'input_id': fields.Many2One("clinic.input.data", "Data"),
}
_order="date_import desc"
def _get_name(self,context={}):
timenow=time.strftime("%Y-%m-%d")
return 'Import Payment - %s'%timenow
_defaults={
'date_import': lambda *a: time.strftime("%Y-%m-%d %H:%M:%S"),
'name': _get_name,
'state': 'draft',
'type': 'mg',
}
def load_data(self,ids,context):
obj=self.browse(ids[0])
fname=obj.file
if not fname:
raise Exception("Please select file!")
fpath=get_file_path(fname)
suffix=fpath.split(".")[-1]
if suffix not in ('xls', 'xlsx'):
raise Exception("ERROR : file support only xls, xlsx")
wb=xlrd.open_workbook(fpath)
worksheet=wb.sheet_by_name("Sheet1")
num_rows=worksheet.nrows-1
curr_row=-1
cols={
'hn': 38,
'dttran': 71,
'name14': 39,
'hcode18': 65, # remove -1
'amount23': 74,
'cur': 91,
'epoadm29': 93,
'eponame': 98,
'ln': 99,
'st': 101,
'allow37': 109,
}
while curr_row < num_rows:
curr_row +=1
vals={
'date': worksheet.cell_value(curr_row,cols['dttran']),
'name': worksheet.cell_value(curr_row,cols['name14']),
'hn': worksheet.cell_value(curr_row,cols['hn']),
'amount': worksheet.cell_value(curr_row,cols['amount23']),
'hct': worksheet.cell_value(curr_row,cols['amount23']),
}
def load_sheet(self,ids,context={}):
obj=self.browse(ids[0])
fname=obj.file
if not fname:
raise Exception("Please select file!")
fpath=get_file_path(fname)
suffix=fpath.split(".")[-1]
if suffix not in ('xls', 'xlsx'):
raise Exception("ERROR : file support only xls, xlsx")
wb=xlrd.open_workbook(fpath)
sheets=wb.sheet_names()
index=0
# XXX clear old sheet
for sheet in obj.sheets:
sheet.delete()
vals={
'sheets': [],
}
for sheet in sheets:
line={
'index': index,
'name': sheet,
}
vals["sheets"].append(("create",line))
#vals['state']='sheet_loaded'
obj.write(vals)
return {
'next': {
'name': "clinic_import_payment",
'mode': 'form',
'active_id': obj.id,
},
'flash': "Load sheet successfully",
}
def onchange_sheet(self,context={}):
data=context["data"]
path=context["path"]
line=get_data_path(data,path,parent=True)
for sheet in data['sheets']:
if sheet['name']!=line['name']:
sheet['select']=None
return data
def onchange_file(self,context={}):
data=context['data']
data['sheets']=[]
print("data ", data)
return data
def clear_sheet(self,ids,context={}):
obj=self.browse(ids)[0]
for sheet in obj.sheets:
sheet.delete()
return {
'next': {
'name': 'clinic_import_payment',
'mode': 'form',
'active_id': obj.id,
},
'flash': "Clear Sheet OK",
}
def find_invoice(self,ids,context={}):
# return invoice line
obj=self.browse(ids[0])
partner_id=None
setting=get_model("clinic.setting").browse(1)
if obj.type=='sc':
partner_id=setting.sc_partner_id.id
elif obj.type=='mg':
partner_id=setting.mg_partner_id.id
elif obj.type=='nhso':
partner_id=setting.nhso_partner_id.id
if not partner_id:
raise Exception("No partner")
# XXX
if obj.payment_lines:
for line in obj.payment_lines:
line.delete()
dom=[]
dom.append(['state','=','waiting_payment'])
dom.append(['partner_id','=',partner_id])
invoice_lines=[]
for invoice in get_model("account.invoice").search_browse(dom):
print(invoice)
line={
'invoice_id': invoice.id,
'amount': invoice.amount_total,
}
#invoice_lines.append(('create',line))
invoice_lines.append(('create',line))
return invoice_lines
def make_payment(self,ids,context={}):
obj=self.browse(ids[0])
company_id=get_active_company()
timenow=time.strftime("%Y-%m-%d")
setting=get_model("clinic.setting").browse(1)
account_id=None
partner_id=None
if obj.type=='sc':
account_id=setting.ar_sc_id.id
partner_id=setting.sc_partner_id.id
elif obj.type=='mg':
account_id=setting.ar_mg_id.id
partner_id=setting.mg_partner_id.id
elif obj.type=='nhso':
account_id=setting.ar_nhso_id.id
partner_id=setting.nhso_partner_id.id
vals={
"partner_id": partner_id,
"company_id": company_id,
"type": "in",
"pay_type": "invoice",
"date": timenow,
"account_id": account_id,
'lines': [], # TODO find invoice matching
}
#db=get_connection()
if obj.type=='sc':
if not obj.sc_payment_id:
payment_id=get_model("account.payment").create(vals,context={'type': 'in'})
obj.write({
'sc_payment_id': payment_id,
})
## XX
#sql="update clinic_import_payment set sc_payment_id=%s where id = %s" % (payment_id,obj.id)
#import pdb; pdb.set_trace()
#db.query(sql)
#db.commit()
invoice_lines=obj.find_invoice()
print("="*30)
for line in invoice_lines:
print(line)
print("="*30)
# TODO update payment
# remove invoice, udpate invoice
if invoice_lines:
if obj.sc_payment_id.invoice_lines:
# clear old invoice lines
for line in obj.sc_payment_id.invoice_lines:
line.delete()
# update new
obj.sc_payment_id.write({
'invoice_lines': invoice_lines,
})
elif obj.type=='mg':
if not obj.mg_payment_id:
payment_id=get_model("account.payment").create(vals,context={'type': 'in'})
obj.write({
'mg_payment_id': payment_id,
})
invoice_lines=obj.find_invoice()
print("="*30)
for line in invoice_lines:
print(line)
print("="*30)
if invoice_lines:
# clear old invoice lines
if obj.mg_payment_id.invoice_lines:
for line in obj.mg_payment_id.invoice_lines:
line.delete()
# update new
obj.mg_payment_id.write({
'invoice_lines': invoice_lines,
})
elif obj.type=='nhso':
if not obj.nhso_payment_id:
payment_id=get_model("account.payment").create(vals,context={'type': 'in'})
obj.write({
'nhso_payment_id': payment_id,
})
invoice_lines=obj.find_invoice()
if invoice_lines:
# clear old invoice lines
if obj.nhso_payment_id.invoice_lines:
for line in obj.nhso_payment_id.invoice_lines:
line.delete()
# update new
obj.nhso_payment_id.write({
'invoice_lines': invoice_lines,
})
def import_payment(self,ids,context={}):
obj=self.browse(ids)[0]
obj.make_payment()
return {
'next': {
'name': 'clinic_import_payment',
'mode': 'form',
'active_id': obj.id,
},
'flash': 'Import Payment OK',
}
def post_mg(self,ids,context={}):
obj=self.browse(ids)[0]
payment_id=obj.mg_payment_id
if not payment_id:
raise Exception("Payment not create yet.")
if payment_id.state=='posted':
raise Exception("%s has been posted."%payment_id.number)
payment_id.post()
# XXX
db=get_connection()
res=db.query("select move_id from account_payment where id =%s"%payment_id.id)
if res:
move_id=res[0]['move_id']
obj.write({
'mg_move_id': move_id,
})
return {
'next': {
'name': 'clinic_import_payment',
'mode': 'form',
'active_id': obj.id,
},
'flash': "%s has been posted"%payment_id.number,
}
pass
def undo_mg(self,ids,context={}):
obj=self.browse(ids)[0]
move_id=obj.mg_move_id
payment_id=obj.mg_payment_id
if not move_id:
raise Exception("%s is not post yet"%(payment_id.number or "Payment"))
payment_id.to_draft()
obj.write({
'mg_move_id': None,
})
return {
'next': {
'name': 'clinic_import_payment',
'mode': 'form',
'active_id': obj.id,
},
'flash': "Undo OK",
}
pass
def post_sc(self,ids,context={}):
obj=self.browse(ids)[0]
payment_id=obj.sc_payment_id
if not payment_id:
raise Exception("Payment not create yet.")
if payment_id.state=='posted':
raise Exception("%s has been posted."%payment_id.number)
payment_id.post()
# XXX
db=get_connection()
res=db.query("select move_id from account_payment where id =%s"%payment_id.id)
if res:
move_id=res[0]['move_id']
obj.write({
'sc_move_id': move_id,
})
return {
'next': {
'name': 'clinic_import_payment',
'mode': 'form',
'active_id': obj.id,
},
'flash': "%s has been posted"%payment_id.number,
}
def undo_sc(self,ids,context={}):
obj=self.browse(ids)[0]
move_id=obj.sc_move_id
payment_id=obj.sc_payment_id
if not move_id:
raise Exception("%s is not post yet"%(payment_id.number or "Payment"))
payment_id.to_draft()
obj.write({
'sc_move_id': None,
})
return {
'next': {
'name': 'clinic_import_payment',
'mode': 'form',
'active_id': obj.id,
},
'flash': "Undo OK",
}
def post_nhso(self,ids,context={}):
obj=self.browse(ids)[0]
payment_id=obj.nhso_payment_id
if not payment_id:
raise Exception("Payment not create yet.")
if payment_id.state=='posted':
raise Exception("%s has been posted."%payment_id.number)
payment_id.post()
# XXX
db=get_connection()
res=db.query("select move_id from account_payment where id =%s"%payment_id.id)
if res:
move_id=res[0]['move_id']
obj.write({
'nhso_move_id': move_id,
})
return {
'next': {
'name': 'clinic_import_payment',
'mode': 'form',
'active_id': obj.id,
},
'flash': "%s has been posted"%payment_id.number,
}
pass
def undo_nhso(self,ids,context={}):
obj=self.browse(ids)[0]
move_id=obj.nhso_move_id
payment_id=obj.nhso_payment_id
if not move_id:
raise Exception("%s is not post yet"%(payment_id.number or "Payment"))
payment_id.to_draft()
obj.write({
'nhso_move_id': None,
})
return {
'next': {
'name': 'clinic_import_payment',
'mode': 'form',
'active_id': obj.id,
},
'flash': "Undo OK",
}
pass
def close(self,ids,context={}):
obj=self.browse(ids)[0]
obj.write({'state': 'close'})
def to_draft(self,ids,context={}):
obj=self.browse(ids)[0]
obj.write({'state': 'draft'})
def onchange_type(self,context={}):
data=context['data']
# find partner and set to partner_id
return data
ImportPayment.register()