changed sql to webnotes.conn.sql to avoid errors due to closing of connections in scheduler/push patch

This commit is contained in:
Anand Doshi 2012-01-27 12:25:09 +05:30
parent 46848a48fe
commit 74d1b65105
4 changed files with 123 additions and 131 deletions

View File

@ -8,8 +8,6 @@ from webnotes.model.doclist import getlist, copy_doclist, clone
from webnotes.model.code import get_obj from webnotes.model.code import get_obj
from webnotes import session, form, is_testing, msgprint, errprint from webnotes import session, form, is_testing, msgprint, errprint
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists convert_to_lists = webnotes.conn.convert_to_lists
@ -24,7 +22,7 @@ class DocType:
# Get Company List # Get Company List
# ---------------- # ----------------
def get_companies(self,arg=''): def get_companies(self,arg=''):
ret = sql("select name, abbr from tabCompany where docstatus != 2") ret = webnotes.conn.sql("select name, abbr from tabCompany where docstatus != 2")
return {'cl':[r[0] for r in ret]} return {'cl':[r[0] for r in ret]}
def get_company_currency(self,arg=''): def get_company_currency(self,arg=''):
@ -35,7 +33,7 @@ class DocType:
# -------------------- # --------------------
def get_bal(self,arg): def get_bal(self,arg):
ac, fy = arg.split('~~~') ac, fy = arg.split('~~~')
det = sql("select t1.balance, t2.debit_or_credit from `tabAccount Balance` t1, `tabAccount` t2 where t1.period = %s and t2.name=%s and t1.account = t2.name", (fy, ac)) det = webnotes.conn.sql("select t1.balance, t2.debit_or_credit from `tabAccount Balance` t1, `tabAccount` t2 where t1.period = %s and t2.name=%s and t1.account = t2.name", (fy, ac))
bal = det and flt(det[0][0]) or 0 bal = det and flt(det[0][0]) or 0
dr_or_cr = det and flt(det[0][1]) or '' dr_or_cr = det and flt(det[0][1]) or ''
return fmt_money(bal) + ' ' + dr_or_cr return fmt_money(bal) + ' ' + dr_or_cr
@ -44,10 +42,10 @@ class DocType:
acc, f, t = arg.split('~~~') acc, f, t = arg.split('~~~')
c, fy = '', get_defaults()['fiscal_year'] c, fy = '', get_defaults()['fiscal_year']
det = sql("select debit_or_credit, lft, rgt, is_pl_account from tabAccount where name=%s", acc) det = webnotes.conn.sql("select debit_or_credit, lft, rgt, is_pl_account from tabAccount where name=%s", acc)
if f: c += (' and t1.posting_date >= "%s"' % f) if f: c += (' and t1.posting_date >= "%s"' % f)
if t: c += (' and t1.posting_date <= "%s"' % t) if t: c += (' and t1.posting_date <= "%s"' % t)
bal = sql("select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) from `tabGL Entry` t1 where t1.account='%s' and ifnull(is_opening, 'No') = 'No' %s" % (acc, c)) bal = webnotes.conn.sql("select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) from `tabGL Entry` t1 where t1.account='%s' and ifnull(is_opening, 'No') = 'No' %s" % (acc, c))
bal = bal and flt(bal[0][0]) or 0 bal = bal and flt(bal[0][0]) or 0
if det[0][0] != 'Debit': if det[0][0] != 'Debit':
@ -55,7 +53,7 @@ class DocType:
# add opening for balance sheet accounts # add opening for balance sheet accounts
if det[0][3] == 'No': if det[0][3] == 'No':
opening = flt(sql("select opening from `tabAccount Balance` where account=%s and period=%s", (acc, fy))[0][0]) opening = flt(webnotes.conn.sql("select opening from `tabAccount Balance` where account=%s and period=%s", (acc, fy))[0][0])
bal = bal + opening bal = bal + opening
return flt(bal) return flt(bal)
@ -67,11 +65,11 @@ class DocType:
acc, f, t = arg.split('~~~') acc, f, t = arg.split('~~~')
c, fy = '', get_defaults()['fiscal_year'] c, fy = '', get_defaults()['fiscal_year']
det = sql("select debit_or_credit, lft, rgt, is_pl_account from tabAccount where name=%s", acc) det = webnotes.conn.sql("select debit_or_credit, lft, rgt, is_pl_account from tabAccount where name=%s", acc)
if f: c += (' and t1.posting_date >= "%s"' % f) if f: c += (' and t1.posting_date >= "%s"' % f)
if t: c += (' and t1.posting_date <= "%s"' % t) if t: c += (' and t1.posting_date <= "%s"' % t)
if cost_center: c += (' and t1.cost_center = "%s"' % cost_center) if cost_center: c += (' and t1.cost_center = "%s"' % cost_center)
bal = sql("select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) from `tabGL Entry` t1 where t1.account='%s' %s" % (acc, c)) bal = webnotes.conn.sql("select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) from `tabGL Entry` t1 where t1.account='%s' %s" % (acc, c))
bal = bal and flt(bal[0][0]) or 0 bal = bal and flt(bal[0][0]) or 0
if det[0][0] != 'Debit': if det[0][0] != 'Debit':
@ -91,9 +89,9 @@ class DocType:
if parent=='Root Node': if parent=='Root Node':
cl = sql("select t1.name, t1.group_or_ledger, t1.debit_or_credit, t2.balance, t1.account_name from tabAccount t1, `tabAccount Balance` t2 where ifnull(t1.parent_account, '') = '' and t1.docstatus != 2 and t1.company=%s and t1.name = t2.account and t2.period = %s order by t1.name asc", (company, fy),as_dict=1) cl = webnotes.conn.sql("select t1.name, t1.group_or_ledger, t1.debit_or_credit, t2.balance, t1.account_name from tabAccount t1, `tabAccount Balance` t2 where ifnull(t1.parent_account, '') = '' and t1.docstatus != 2 and t1.company=%s and t1.name = t2.account and t2.period = %s order by t1.name asc", (company, fy),as_dict=1)
else: else:
cl = sql("select t1.name, t1.group_or_ledger, t1.debit_or_credit, t2.balance, t1.account_name from tabAccount t1, `tabAccount Balance` t2 where ifnull(t1.parent_account, '')=%s and t1.docstatus != 2 and t1.company=%s and t1.name = t2.account and t2.period = %s order by t1.name asc",(parent, company, fy) ,as_dict=1) cl = webnotes.conn.sql("select t1.name, t1.group_or_ledger, t1.debit_or_credit, t2.balance, t1.account_name from tabAccount t1, `tabAccount Balance` t2 where ifnull(t1.parent_account, '')=%s and t1.docstatus != 2 and t1.company=%s and t1.name = t2.account and t2.period = %s order by t1.name asc",(parent, company, fy) ,as_dict=1)
# remove Decimals # remove Decimals
for c in cl: c['balance'] = flt(c['balance']) for c in cl: c['balance'] = flt(c['balance'])
@ -101,9 +99,9 @@ class DocType:
# get children cost center details # get children cost center details
elif type=='Cost Center': elif type=='Cost Center':
if parent=='Root Node': if parent=='Root Node':
cl = sql("select name,group_or_ledger, cost_center_name from `tabCost Center` where ifnull(parent_cost_center, '')='' and docstatus != 2 and company_name=%s order by name asc",(company),as_dict=1) cl = webnotes.conn.sql("select name,group_or_ledger, cost_center_name from `tabCost Center` where ifnull(parent_cost_center, '')='' and docstatus != 2 and company_name=%s order by name asc",(company),as_dict=1)
else: else:
cl = sql("select name,group_or_ledger,cost_center_name from `tabCost Center` where ifnull(parent_cost_center, '')=%s and docstatus != 2 and company_name=%s order by name asc",(parent,company),as_dict=1) cl = webnotes.conn.sql("select name,group_or_ledger,cost_center_name from `tabCost Center` where ifnull(parent_cost_center, '')=%s and docstatus != 2 and company_name=%s order by name asc",(parent,company),as_dict=1)
return {'parent':parent, 'parent_acc_name':parent_acc_name, 'cl':cl} return {'parent':parent, 'parent_acc_name':parent_acc_name, 'cl':cl}
# Add a new account # Add a new account
@ -130,7 +128,7 @@ class DocType:
for d in arg.keys(): for d in arg.keys():
cc.fields[d] = arg[d] cc.fields[d] = arg[d]
# map company abbr # map company abbr
other_info = sql("select company_abbr from `tabCost Center` where name='%s'"%arg['parent_cost_center']) other_info = webnotes.conn.sql("select company_abbr from `tabCost Center` where name='%s'"%arg['parent_cost_center'])
cc.company_abbr = other_info and other_info[0][0] or arg['company_abbr'] cc.company_abbr = other_info and other_info[0][0] or arg['company_abbr']
cc_obj = get_obj(doc=cc) cc_obj = get_obj(doc=cc)
@ -167,7 +165,7 @@ class DocType:
# Check budget before gl entry # Check budget before gl entry
#check budget only if account is expense account #check budget only if account is expense account
is_expense_acct = sql("select name from tabAccount where is_pl_account='Yes' and debit_or_credit='Debit' and name=%s",self.get_val(le_map['account'], d, parent)) is_expense_acct = webnotes.conn.sql("select name from tabAccount where is_pl_account='Yes' and debit_or_credit='Debit' and name=%s",self.get_val(le_map['account'], d, parent))
if is_expense_acct and self.get_val(le_map['cost_center'], d, parent): if is_expense_acct and self.get_val(le_map['cost_center'], d, parent):
get_obj('Budget Control').check_budget([self.get_val(le_map[k], d, parent) for k in flist if k in ['account','cost_center','debit','credit','posting_date','fiscal_year','company']],cancel) get_obj('Budget Control').check_budget([self.get_val(le_map[k], d, parent) for k in flist if k in ['account','cost_center','debit','credit','posting_date','fiscal_year','company']],cancel)
@ -214,7 +212,7 @@ class DocType:
def make_gl_entries(self, doc, doclist, cancel=0, adv_adj = 0, use_mapper='', merge_entries = 1, update_outstanding='Yes'): def make_gl_entries(self, doc, doclist, cancel=0, adv_adj = 0, use_mapper='', merge_entries = 1, update_outstanding='Yes'):
self.entries = [] self.entries = []
# get entries # get entries
le_map_list = sql("select * from `tabGL Mapper Detail` where parent = %s", use_mapper or doc.doctype, as_dict=1) le_map_list = webnotes.conn.sql("select * from `tabGL Mapper Detail` where parent = %s", use_mapper or doc.doctype, as_dict=1)
self.td, self.tc = 0.0, 0.0 self.td, self.tc = 0.0, 0.0
for le_map in le_map_list: for le_map in le_map_list:
if le_map['table_field']: if le_map['table_field']:
@ -237,17 +235,17 @@ class DocType:
# set as cancelled # set as cancelled
if cancel: if cancel:
vt, vn = self.get_val(le_map['voucher_type'], doc, doc), self.get_val(le_map['voucher_no'], doc, doc) vt, vn = self.get_val(le_map['voucher_type'], doc, doc), self.get_val(le_map['voucher_no'], doc, doc)
sql("update `tabGL Entry` set is_cancelled='Yes' where voucher_type=%s and voucher_no=%s", (vt, vn)) webnotes.conn.sql("update `tabGL Entry` set is_cancelled='Yes' where voucher_type=%s and voucher_no=%s", (vt, vn))
# Get account balance on any date # Get account balance on any date
# ------------------------------- # -------------------------------
def get_as_on_balance(self, account_name, fiscal_year, as_on, credit_or_debit, lft, rgt): def get_as_on_balance(self, account_name, fiscal_year, as_on, credit_or_debit, lft, rgt):
# initialization # initialization
det = sql("select start_date, opening from `tabAccount Balance` where period = %s and account = %s", (fiscal_year, account_name)) det = webnotes.conn.sql("select start_date, opening from `tabAccount Balance` where period = %s and account = %s", (fiscal_year, account_name))
from_date, opening, debit_bal, credit_bal, closing_bal = det and det[0][0] or getdate(nowdate()), det and flt(det[0][1]) or 0, 0, 0, det and flt(det[0][1]) or 0 from_date, opening, debit_bal, credit_bal, closing_bal = det and det[0][0] or getdate(nowdate()), det and flt(det[0][1]) or 0, 0, 0, det and flt(det[0][1]) or 0
# prev month closing # prev month closing
prev_month_det = sql("select end_date, debit, credit, balance from `tabAccount Balance` where account = %s and end_date <= %s and fiscal_year = %s order by end_date desc limit 1", (account_name, as_on, fiscal_year)) prev_month_det = webnotes.conn.sql("select end_date, debit, credit, balance from `tabAccount Balance` where account = %s and end_date <= %s and fiscal_year = %s order by end_date desc limit 1", (account_name, as_on, fiscal_year))
if prev_month_det: if prev_month_det:
from_date = getdate(add_days(prev_month_det[0][0].strftime('%Y-%m-%d'), 1)) from_date = getdate(add_days(prev_month_det[0][0].strftime('%Y-%m-%d'), 1))
opening = 0 opening = 0
@ -257,7 +255,7 @@ class DocType:
# curr month transaction # curr month transaction
if getdate(as_on) >= from_date: if getdate(as_on) >= from_date:
curr_month_bal = sql("select SUM(t1.debit), SUM(t1.credit) from `tabGL Entry` t1, `tabAccount` t2 WHERE t1.posting_date >= %s AND t1.posting_date <= %s and ifnull(t1.is_opening, 'No') = 'No' AND t1.account = t2.name AND t2.lft >= %s AND t2.rgt <= %s and ifnull(t1.is_cancelled, 'No') = 'No'", (from_date, as_on, lft, rgt)) curr_month_bal = webnotes.conn.sql("select SUM(t1.debit), SUM(t1.credit) from `tabGL Entry` t1, `tabAccount` t2 WHERE t1.posting_date >= %s AND t1.posting_date <= %s and ifnull(t1.is_opening, 'No') = 'No' AND t1.account = t2.name AND t2.lft >= %s AND t2.rgt <= %s and ifnull(t1.is_cancelled, 'No') = 'No'", (from_date, as_on, lft, rgt))
curr_debit_amt, curr_credit_amt = flt(curr_month_bal[0][0]), flt(curr_month_bal[0][1]) curr_debit_amt, curr_credit_amt = flt(curr_month_bal[0][0]), flt(curr_month_bal[0][1])
debit_bal = curr_month_bal and debit_bal + curr_debit_amt or debit_bal debit_bal = curr_month_bal and debit_bal + curr_debit_amt or debit_bal
credit_bal = curr_month_bal and credit_bal + curr_credit_amt or credit_bal credit_bal = curr_month_bal and credit_bal + curr_credit_amt or credit_bal
@ -272,7 +270,7 @@ class DocType:
# ADVANCE ALLOCATION # ADVANCE ALLOCATION
#------------------- #-------------------
def get_advances(self, obj, account_head, table_name,table_field_name, dr_or_cr): def get_advances(self, obj, account_head, table_name,table_field_name, dr_or_cr):
jv_detail = sql("select t1.name, t1.remark, t2.%s, t2.name, t1.ded_amount from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 where t1.name = t2.parent and (t2.against_voucher is null or t2.against_voucher = '') and (t2.against_invoice is null or t2.against_invoice = '') and (t2.against_jv is null or t2.against_jv = '') and t2.account = '%s' and t2.is_advance = 'Yes' and t1.docstatus = 1 order by t1.voucher_date " % (dr_or_cr,account_head)) jv_detail = webnotes.conn.sql("select t1.name, t1.remark, t2.%s, t2.name, t1.ded_amount from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 where t1.name = t2.parent and (t2.against_voucher is null or t2.against_voucher = '') and (t2.against_invoice is null or t2.against_invoice = '') and (t2.against_jv is null or t2.against_jv = '') and t2.account = '%s' and t2.is_advance = 'Yes' and t1.docstatus = 1 order by t1.voucher_date " % (dr_or_cr,account_head))
# clear advance table # clear advance table
obj.doc.clear_table(obj.doclist,table_field_name) obj.doc.clear_table(obj.doclist,table_field_name)
# Create advance table # Create advance table
@ -291,7 +289,7 @@ class DocType:
def clear_advances(self, obj,table_name,table_field_name): def clear_advances(self, obj,table_name,table_field_name):
for d in getlist(obj.doclist,table_field_name): for d in getlist(obj.doclist,table_field_name):
if not flt(d.allocated_amount): if not flt(d.allocated_amount):
sql("update `tab%s` set parent = '' where name = '%s' and parent = '%s'" % (table_name, d.name, d.parent)) webnotes.conn.sql("update `tab%s` set parent = '' where name = '%s' and parent = '%s'" % (table_name, d.name, d.parent))
d.parent = '' d.parent = ''
# Update aginst document in journal voucher # Update aginst document in journal voucher
@ -305,7 +303,7 @@ class DocType:
get_obj(dt='GL Control').make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel =1, adv_adj =1) get_obj(dt='GL Control').make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel =1, adv_adj =1)
# update ref in JV Detail # update ref in JV Detail
sql("update `tabJournal Voucher Detail` set %s = '%s' where name = '%s'" % (doctype=='Payable Voucher' and 'against_voucher' or 'against_invoice', cstr(against_document_no), d.jv_detail_no)) webnotes.conn.sql("update `tabJournal Voucher Detail` set %s = '%s' where name = '%s'" % (doctype=='Payable Voucher' and 'against_voucher' or 'against_invoice', cstr(against_document_no), d.jv_detail_no))
# re-submit JV # re-submit JV
jv_obj = get_obj('Journal Voucher', d.journal_voucher, with_children =1) jv_obj = get_obj('Journal Voucher', d.journal_voucher, with_children =1)
@ -332,12 +330,12 @@ class DocType:
def add_extra_entry(self,jv_obj,jv,jv_detail_no, allocate, account_head, doctype, dr_or_cr, against_document_no): def add_extra_entry(self,jv_obj,jv,jv_detail_no, allocate, account_head, doctype, dr_or_cr, against_document_no):
# get old entry details # get old entry details
jvd = sql("select %s, cost_center, balance, against_account from `tabJournal Voucher Detail` where name = '%s'" % (dr_or_cr,jv_detail_no)) jvd = webnotes.conn.sql("select %s, cost_center, balance, against_account from `tabJournal Voucher Detail` where name = '%s'" % (dr_or_cr,jv_detail_no))
advance = jvd and flt(jvd[0][0]) or 0 advance = jvd and flt(jvd[0][0]) or 0
balance = flt(advance) - flt(allocate) balance = flt(advance) - flt(allocate)
# update old entry # update old entry
sql("update `tabJournal Voucher Detail` set %s = '%s', %s = '%s' where name = '%s'" % (dr_or_cr, flt(allocate), doctype == "Payable Voucher" and 'against_voucher' or 'against_invoice',cstr(against_document_no), jv_detail_no)) webnotes.conn.sql("update `tabJournal Voucher Detail` set %s = '%s', %s = '%s' where name = '%s'" % (dr_or_cr, flt(allocate), doctype == "Payable Voucher" and 'against_voucher' or 'against_invoice',cstr(against_document_no), jv_detail_no))
# new entry with balance amount # new entry with balance amount
add = addchild(jv_obj.doc, 'entries', 'Journal Voucher Detail', 1, jv_obj.doclist) add = addchild(jv_obj.doc, 'entries', 'Journal Voucher Detail', 1, jv_obj.doclist)
@ -356,7 +354,7 @@ class DocType:
# 2. check if amount is same # 2. check if amount is same
# 3. check if is_advance is 'Yes' # 3. check if is_advance is 'Yes'
# 4. check if jv is submitted # 4. check if jv is submitted
ret = sql("select t2.%s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 where t1.name = t2.parent and ifnull(t2.against_voucher, '') = '' and ifnull(t2.against_invoice, '') = '' and t2.account = '%s' and t1.name = '%s' and t2.name = '%s' and t2.is_advance = 'Yes' and t1.docstatus=1 and t2.%s = %s" % (dr_or_cr, account_head, d.journal_voucher, d.jv_detail_no, dr_or_cr, d.advance_amount)) ret = webnotes.conn.sql("select t2.%s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 where t1.name = t2.parent and ifnull(t2.against_voucher, '') = '' and ifnull(t2.against_invoice, '') = '' and t2.account = '%s' and t1.name = '%s' and t2.name = '%s' and t2.is_advance = 'Yes' and t1.docstatus=1 and t2.%s = %s" % (dr_or_cr, account_head, d.journal_voucher, d.jv_detail_no, dr_or_cr, d.advance_amount))
if (not ret): if (not ret):
msgprint("Please click on 'Get Advances Paid' button as the advance entries have been changed.") msgprint("Please click on 'Get Advances Paid' button as the advance entries have been changed.")
raise Exception raise Exception
@ -399,13 +397,13 @@ class DocType:
Updates against document, if partial amount splits into rows Updates against document, if partial amount splits into rows
""" """
sql(""" webnotes.conn.sql("""
update `tabJournal Voucher Detail` t1, `tabJournal Voucher` t2 update `tabJournal Voucher Detail` t1, `tabJournal Voucher` t2
set t1.%(dr_or_cr)s = '%(allocated_amt)s', t1.%(against_fld)s = '%(against_voucher)s', t2.modified = now() set t1.%(dr_or_cr)s = '%(allocated_amt)s', t1.%(against_fld)s = '%(against_voucher)s', t2.modified = now()
where t1.name = '%(voucher_detail_no)s' and t1.parent = t2.name""" % d) where t1.name = '%(voucher_detail_no)s' and t1.parent = t2.name""" % d)
if d['allocated_amt'] < d['unadjusted_amt']: if d['allocated_amt'] < d['unadjusted_amt']:
jvd = sql("select cost_center, balance, against_account, is_advance from `tabJournal Voucher Detail` where name = '%s'" % d['voucher_detail_no']) jvd = webnotes.conn.sql("select cost_center, balance, against_account, is_advance from `tabJournal Voucher Detail` where name = '%s'" % d['voucher_detail_no'])
# new entry with balance amount # new entry with balance amount
ch = addchild(jv_obj.doc, 'entries', 'Journal Voucher Detail', 1) ch = addchild(jv_obj.doc, 'entries', 'Journal Voucher Detail', 1)
ch.account = d['account'] ch.account = d['account']
@ -425,7 +423,7 @@ class DocType:
check if amount is same check if amount is same
check if jv is submitted check if jv is submitted
""" """
ret = sql(""" ret = webnotes.conn.sql("""
select t2.%(dr_or_cr)s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 select t2.%(dr_or_cr)s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2
where t1.name = t2.parent and t2.account = '%(account)s' where t1.name = t2.parent and t2.account = '%(account)s'
and ifnull(t2.against_voucher, '')='' and ifnull(t2.against_invoice, '')='' and ifnull(t2.against_jv, '')='' and ifnull(t2.against_voucher, '')='' and ifnull(t2.against_invoice, '')='' and ifnull(t2.against_jv, '')=''
@ -446,7 +444,7 @@ class DocType:
msg = [] msg = []
# Get Balance from GL Entries # Get Balance from GL Entries
bal = sql("select sum(debit)-sum(credit) from `tabGL Entry` where against_voucher=%s and against_voucher_type=%s", (voucher_obj.doc.name , voucher_obj.doc.doctype)) bal = webnotes.conn.sql("select sum(debit)-sum(credit) from `tabGL Entry` where against_voucher=%s and against_voucher_type=%s", (voucher_obj.doc.name , voucher_obj.doc.doctype))
bal = bal and flt(bal[0][0]) or 0.0 bal = bal and flt(bal[0][0]) or 0.0
if cstr(voucher_obj.doc.doctype) == 'Payable Voucher': if cstr(voucher_obj.doc.doctype) == 'Payable Voucher':
bal = -bal bal = -bal
@ -457,7 +455,7 @@ class DocType:
msg.append('<div style="color: RED"> Difference found in Outstanding Amount of %s : %s (Before : %s; After : %s) </div>' % (voucher_obj.doc.doctype, voucher_obj.doc.name, voucher_obj.doc.outstanding_amount, bal)) msg.append('<div style="color: RED"> Difference found in Outstanding Amount of %s : %s (Before : %s; After : %s) </div>' % (voucher_obj.doc.doctype, voucher_obj.doc.name, voucher_obj.doc.outstanding_amount, bal))
# set voucher balance # set voucher balance
#sql("update `tab%s` set outstanding_amount=%s where name='%s'" % (voucher_obj.doc.doctype, bal, voucher_obj.doc.name)) #webnotes.conn.sql("update `tab%s` set outstanding_amount=%s where name='%s'" % (voucher_obj.doc.doctype, bal, voucher_obj.doc.name))
webnotes.conn.set(voucher_obj.doc, 'outstanding_amount', flt(bal)) webnotes.conn.set(voucher_obj.doc, 'outstanding_amount', flt(bal))
# Send Mail # Send Mail
@ -468,7 +466,7 @@ In Account := %s User := %s has Repaired Outstanding Amount For %s : %s and foll
%s %s
""" % (get_value('Control Panel', None,'account_id'), session['user'], voucher_obj.doc.doctype, voucher_obj.doc.name, '\n'.join(msg)) """ % (webnotes.conn.get_value('Control Panel', None,'account_id'), session['user'], voucher_obj.doc.doctype, voucher_obj.doc.name, '\n'.join(msg))
sendmail(['support@iwebnotes.com'], subject='Repair Outstanding Amount', parts = [('text/plain', email_msg)]) sendmail(['support@iwebnotes.com'], subject='Repair Outstanding Amount', parts = [('text/plain', email_msg)])
# Acknowledge User # Acknowledge User
@ -478,7 +476,7 @@ In Account := %s User := %s has Repaired Outstanding Amount For %s : %s and foll
""" """
Find vouchers that are not cancelled correctly and repost them Find vouchers that are not cancelled correctly and repost them
""" """
vl = sql(""" vl = webnotes.conn.sql("""
select voucher_type, voucher_no, account, sum(debit) as sum_debit, sum(credit) as sum_credit select voucher_type, voucher_no, account, sum(debit) as sum_debit, sum(credit) as sum_credit
from `tabGL Entry` from `tabGL Entry`
where is_cancelled='Yes' and creation > %s where is_cancelled='Yes' and creation > %s
@ -490,7 +488,7 @@ In Account := %s User := %s has Repaired Outstanding Amount For %s : %s and foll
if v['sum_debit'] != 0 or v['sum_credit'] != 0: if v['sum_debit'] != 0 or v['sum_credit'] != 0:
ac_list.append(v['account']) ac_list.append(v['account'])
fy_list = sql("""select name from `tabFiscal Year` fy_list = webnotes.conn.sql("""select name from `tabFiscal Year`
where (%s between year_start_date and date_sub(date_add(year_start_date,interval 1 year), interval 1 day)) where (%s between year_start_date and date_sub(date_add(year_start_date,interval 1 year), interval 1 day))
or year_start_date > %s or year_start_date > %s
order by year_start_date ASC""", (after_date, after_date)) order by year_start_date ASC""", (after_date, after_date))
@ -539,7 +537,7 @@ def send_notification(new_rv):
"""Notify concerned persons about recurring invoice generation""" """Notify concerned persons about recurring invoice generation"""
subject = "Invoice : " + new_rv.doc.name subject = "Invoice : " + new_rv.doc.name
com = new_rv.doc.company # get_value('Control Panel', '', 'letter_head') com = new_rv.doc.company # webnotes.conn.get_value('Control Panel', '', 'letter_head')
hd = '''<div><h2>%s</h2></div> hd = '''<div><h2>%s</h2></div>
<div><h3>Invoice: %s</h3></div> <div><h3>Invoice: %s</h3></div>

View File

@ -9,9 +9,6 @@ from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updated
from webnotes import session, form, is_testing, msgprint, errprint from webnotes import session, form, is_testing, msgprint, errprint
from webnotes.utils.scheduler import set_event, cancel_event, Scheduler from webnotes.utils.scheduler import set_event, cancel_event, Scheduler
set = webnotes.conn.set
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists convert_to_lists = webnotes.conn.convert_to_lists
@ -39,25 +36,25 @@ class DocType(TransactionBase):
#Set retail related fields from pos settings #Set retail related fields from pos settings
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
def set_pos_fields(self): def set_pos_fields(self):
pos = sql("select * from `tabPOS Setting` where ifnull(user,'') = '%s' and company = '%s'" % (session['user'], self.doc.company), as_dict=1) pos = webnotes.conn.sql("select * from `tabPOS Setting` where ifnull(user,'') = '%s' and company = '%s'" % (session['user'], self.doc.company), as_dict=1)
if not pos: if not pos:
pos = sql("select * from `tabPOS Setting` where ifnull(user,'') = '' and company = '%s'" % (self.doc.company), as_dict=1) pos = webnotes.conn.sql("select * from `tabPOS Setting` where ifnull(user,'') = '' and company = '%s'" % (self.doc.company), as_dict=1)
if pos: if pos:
val = sql("select name from `tabAccount` where name = %s and docstatus != 2", (cstr(self.doc.customer) + " - " + self.get_company_abbr())) val = webnotes.conn.sql("select name from `tabAccount` where name = %s and docstatus != 2", (cstr(self.doc.customer) + " - " + self.get_company_abbr()))
val = val and val[0][0] or '' val = val and val[0][0] or ''
if not val: val = pos and pos[0]['customer_account'] or '' if not val: val = pos and pos[0]['customer_account'] or ''
if not self.doc.debit_to: if not self.doc.debit_to:
set(self.doc,'debit_to',val) webnotes.conn.set(self.doc,'debit_to',val)
lst = ['territory','naming_series','currency','charge','letter_head','tc_name','price_list_name','company','select_print_heading','cash_bank_account'] lst = ['territory','naming_series','currency','charge','letter_head','tc_name','price_list_name','company','select_print_heading','cash_bank_account']
for i in lst: for i in lst:
val = pos and pos[0][i] or '' val = pos and pos[0][i] or ''
set(self.doc,i,val) webnotes.conn.set(self.doc,i,val)
self.set_pos_item_values() self.set_pos_item_values()
val = pos and flt(pos[0]['conversion_rate']) or 0 val = pos and flt(pos[0]['conversion_rate']) or 0
set(self.doc,'conversion_rate',val) webnotes.conn.set(self.doc,'conversion_rate',val)
#fetch terms #fetch terms
if self.doc.tc_name: self.get_tc_details() if self.doc.tc_name: self.get_tc_details()
@ -70,9 +67,9 @@ class DocType(TransactionBase):
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
def set_pos_item_values(self): def set_pos_item_values(self):
if cint(self.doc.is_pos) ==1: if cint(self.doc.is_pos) ==1:
dtl = sql("select income_account, warehouse, cost_center from `tabPOS Setting` where ifnull(user,'') = '%s' and company = '%s'" % (session['user'], self.doc.company), as_dict=1) dtl = webnotes.conn.sql("select income_account, warehouse, cost_center from `tabPOS Setting` where ifnull(user,'') = '%s' and company = '%s'" % (session['user'], self.doc.company), as_dict=1)
if not dtl: if not dtl:
dtl = sql("select income_account, warehouse, cost_center from `tabPOS Setting` where ifnull(user,'') = '' and company = '%s'" % (self.doc.company), as_dict=1) dtl = webnotes.conn.sql("select income_account, warehouse, cost_center from `tabPOS Setting` where ifnull(user,'') = '' and company = '%s'" % (self.doc.company), as_dict=1)
for d in getlist(self.doclist,'entries'): for d in getlist(self.doclist,'entries'):
if dtl and dtl[0]['income_account']: d.income_account = dtl[0]['income_account'] if dtl and dtl[0]['income_account']: d.income_account = dtl[0]['income_account']
if dtl and dtl[0]['cost_center']: d.cost_center = dtl[0]['cost_center'] if dtl and dtl[0]['cost_center']: d.cost_center = dtl[0]['cost_center']
@ -82,7 +79,7 @@ class DocType(TransactionBase):
# Get Account Head to which amount needs to be Debited based on Customer # Get Account Head to which amount needs to be Debited based on Customer
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
def get_customer_account(self): def get_customer_account(self):
acc_head = sql("select name from `tabAccount` where (name = %s or (master_name = %s and master_type = 'customer')) and docstatus != 2", (cstr(self.doc.customer) + " - " + self.get_company_abbr(),self.doc.customer)) acc_head = webnotes.conn.sql("select name from `tabAccount` where (name = %s or (master_name = %s and master_type = 'customer')) and docstatus != 2", (cstr(self.doc.customer) + " - " + self.get_company_abbr(),self.doc.customer))
if acc_head and acc_head[0][0]: if acc_head and acc_head[0][0]:
return acc_head[0][0] return acc_head[0][0]
else: else:
@ -99,17 +96,17 @@ class DocType(TransactionBase):
def get_cust_and_due_date(self): def get_cust_and_due_date(self):
credit_days = 0 credit_days = 0
if self.doc.debit_to: if self.doc.debit_to:
credit_days = sql("select credit_days from `tabAccount` where name='%s' and docstatus != 2" % self.doc.debit_to) credit_days = webnotes.conn.sql("select credit_days from `tabAccount` where name='%s' and docstatus != 2" % self.doc.debit_to)
credit_days = credit_days and cint(credit_days[0][0]) or 0 credit_days = credit_days and cint(credit_days[0][0]) or 0
if self.doc.company and not credit_days: if self.doc.company and not credit_days:
credit_days = sql("select credit_days from `tabCompany` where name='%s'" % self.doc.company) credit_days = webnotes.conn.sql("select credit_days from `tabCompany` where name='%s'" % self.doc.company)
credit_days = credit_days and cint(credit_days[0][0]) or 0 credit_days = credit_days and cint(credit_days[0][0]) or 0
# Customer has higher priority than company # Customer has higher priority than company
# i.e.if not entered in customer will take credit days from company # i.e.if not entered in customer will take credit days from company
self.doc.due_date = add_days(cstr(self.doc.posting_date), credit_days) self.doc.due_date = add_days(cstr(self.doc.posting_date), credit_days)
if self.doc.debit_to: if self.doc.debit_to:
self.doc.customer = get_value('Account',self.doc.debit_to,'master_name') self.doc.customer = webnotes.conn.get_value('Account',self.doc.debit_to,'master_name')
# get_obj('Sales Common').get_customer_details(self, inv_det_reqd = 0) # get_obj('Sales Common').get_customer_details(self, inv_det_reqd = 0)
@ -144,7 +141,7 @@ class DocType(TransactionBase):
def get_income_account(self,doctype): def get_income_account(self,doctype):
for d in getlist(self.doclist, doctype): for d in getlist(self.doclist, doctype):
if d.item_code: if d.item_code:
item = sql("select default_income_account, default_sales_cost_center from tabItem where name = '%s'" %(d.item_code), as_dict=1) item = webnotes.conn.sql("select default_income_account, default_sales_cost_center from tabItem where name = '%s'" %(d.item_code), as_dict=1)
d.income_account = item and item[0]['default_income_account'] or '' d.income_account = item and item[0]['default_income_account'] or ''
d.cost_center = item and item[0]['default_sales_cost_center'] or '' d.cost_center = item and item[0]['default_sales_cost_center'] or ''
@ -153,14 +150,14 @@ class DocType(TransactionBase):
def get_item_details(self, item_code): def get_item_details(self, item_code):
ret = get_obj('Sales Common').get_item_details(item_code, self) ret = get_obj('Sales Common').get_item_details(item_code, self)
if item_code and cint(self.doc.is_pos) == 1: if item_code and cint(self.doc.is_pos) == 1:
dtl = sql("select income_account, warehouse, cost_center from `tabPOS Setting` where user = '%s' and company = '%s'" % (session['user'], self.doc.company), as_dict=1) dtl = webnotes.conn.sql("select income_account, warehouse, cost_center from `tabPOS Setting` where user = '%s' and company = '%s'" % (session['user'], self.doc.company), as_dict=1)
if not dtl: if not dtl:
dtl = sql("select income_account, warehouse, cost_center from `tabPOS Setting` where ifnull(user,'') = '' and company = '%s'" % (self.doc.company), as_dict=1) dtl = webnotes.conn.sql("select income_account, warehouse, cost_center from `tabPOS Setting` where ifnull(user,'') = '' and company = '%s'" % (self.doc.company), as_dict=1)
if dtl and dtl[0]['income_account']: ret['income_account'] = dtl and dtl[0]['income_account'] if dtl and dtl[0]['income_account']: ret['income_account'] = dtl and dtl[0]['income_account']
if dtl and dtl[0]['cost_center']: ret['cost_center'] = dtl and dtl[0]['cost_center'] if dtl and dtl[0]['cost_center']: ret['cost_center'] = dtl and dtl[0]['cost_center']
if dtl and dtl[0]['warehouse']: ret['warehouse'] = dtl and dtl[0]['warehouse'] if dtl and dtl[0]['warehouse']: ret['warehouse'] = dtl and dtl[0]['warehouse']
if ret['warehouse']: if ret['warehouse']:
actual_qty = sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (item_code, ret['warehouse'])) actual_qty = webnotes.conn.sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (item_code, ret['warehouse']))
ret['actual_qty']= actual_qty and flt(actual_qty[0][0]) or 0 ret['actual_qty']= actual_qty and flt(actual_qty[0][0]) or 0
return ret return ret
@ -205,7 +202,7 @@ class DocType(TransactionBase):
#pull project customer #pull project customer
#------------------------- #-------------------------
def pull_project_customer(self): def pull_project_customer(self):
res = sql("select customer from `tabProject` where name = '%s'"%self.doc.project_name) res = webnotes.conn.sql("select customer from `tabProject` where name = '%s'"%self.doc.project_name)
if res: if res:
get_obj('DocType Mapper', 'Project-Receivable Voucher').dt_map('Project', 'Receivable Voucher', self.doc.project_name, self.doc, self.doclist, "[['Project', 'Receivable Voucher']]") get_obj('DocType Mapper', 'Project-Receivable Voucher').dt_map('Project', 'Receivable Voucher', self.doc.project_name, self.doc, self.doclist, "[['Project', 'Receivable Voucher']]")
@ -214,7 +211,7 @@ class DocType(TransactionBase):
# Get Company Abbr. # Get Company Abbr.
# ------------------ # ------------------
def get_company_abbr(self): def get_company_abbr(self):
return sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0] return webnotes.conn.sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0]
# Check whether sales order / delivery note items already pulled # Check whether sales order / delivery note items already pulled
@ -267,7 +264,7 @@ class DocType(TransactionBase):
dt = d.delivery_note and 'Delivery Note' or d.sales_order and 'Sales Order' or '' dt = d.delivery_note and 'Delivery Note' or d.sales_order and 'Sales Order' or ''
if dt: if dt:
dt_no = d.delivery_note or d.sales_order dt_no = d.delivery_note or d.sales_order
cust = sql("select customer from `tab%s` where name = %s" % (dt, '%s'), dt_no) cust = webnotes.conn.sql("select customer from `tab%s` where name = %s" % (dt, '%s'), dt_no)
if cust and cstr(cust[0][0]) != cstr(self.doc.customer): if cust and cstr(cust[0][0]) != cstr(self.doc.customer):
msgprint("Customer %s does not match with customer of %s: %s." %(self.doc.customer, dt, dt_no), raise_exception=1) msgprint("Customer %s does not match with customer of %s: %s." %(self.doc.customer, dt, dt_no), raise_exception=1)
@ -276,7 +273,7 @@ class DocType(TransactionBase):
# ------------------------------------------------ # ------------------------------------------------
def validate_debit_to_acc(self): def validate_debit_to_acc(self):
if self.doc.customer and not cint(self.doc.is_pos): if self.doc.customer and not cint(self.doc.is_pos):
acc_head = sql("select name from `tabAccount` where name = %s and docstatus != 2", (cstr(self.doc.customer) + " - " + self.get_company_abbr())) acc_head = webnotes.conn.sql("select name from `tabAccount` where name = %s and docstatus != 2", (cstr(self.doc.customer) + " - " + self.get_company_abbr()))
if acc_head and acc_head[0][0]: if acc_head and acc_head[0][0]:
if not cstr(acc_head[0][0]) == cstr(self.doc.debit_to): if not cstr(acc_head[0][0]) == cstr(self.doc.debit_to):
msgprint("Debit To %s do not match with Customer %s for Company %s i.e. %s" %(self.doc.debit_to,self.doc.customer,self.doc.company,cstr(acc_head[0][0]))) msgprint("Debit To %s do not match with Customer %s for Company %s i.e. %s" %(self.doc.debit_to,self.doc.customer,self.doc.company,cstr(acc_head[0][0])))
@ -292,7 +289,7 @@ class DocType(TransactionBase):
# 3. Is a PL Account # 3. Is a PL Account
# --------------------------- # ---------------------------
def validate_debit_acc(self): def validate_debit_acc(self):
acc = sql("select debit_or_credit, is_pl_account from tabAccount where name = '%s' and docstatus != 2" % self.doc.debit_to) acc = webnotes.conn.sql("select debit_or_credit, is_pl_account from tabAccount where name = '%s' and docstatus != 2" % self.doc.debit_to)
if not acc: if not acc:
msgprint("Account: "+ self.doc.debit_to + " does not exist") msgprint("Account: "+ self.doc.debit_to + " does not exist")
raise Exception raise Exception
@ -308,8 +305,8 @@ class DocType(TransactionBase):
# ----------------------------------------------------------------------- # -----------------------------------------------------------------------
def validate_fixed_asset_account(self): def validate_fixed_asset_account(self):
for d in getlist(self.doclist,'entries'): for d in getlist(self.doclist,'entries'):
item = sql("select name,is_asset_item,is_sales_item from `tabItem` where name = '%s' and (ifnull(end_of_life,'')='' or end_of_life = '0000-00-00' or end_of_life > now())"% d.item_code) item = webnotes.conn.sql("select name,is_asset_item,is_sales_item from `tabItem` where name = '%s' and (ifnull(end_of_life,'')='' or end_of_life = '0000-00-00' or end_of_life > now())"% d.item_code)
acc = sql("select account_type from `tabAccount` where name = '%s' and docstatus != 2" % d.income_account) acc = webnotes.conn.sql("select account_type from `tabAccount` where name = '%s' and docstatus != 2" % d.income_account)
if not acc: if not acc:
msgprint("Account: "+d.income_account+" does not exist in the system") msgprint("Account: "+d.income_account+" does not exist in the system")
raise Exception raise Exception
@ -358,7 +355,7 @@ class DocType(TransactionBase):
def so_dn_required(self): def so_dn_required(self):
dict = {'Sales Order':'so_required','Delivery Note':'dn_required'} dict = {'Sales Order':'so_required','Delivery Note':'dn_required'}
for i in dict: for i in dict:
res = sql("select value from `tabSingles` where doctype = 'Manage Account' and field = '%s'"%dict[i]) res = webnotes.conn.sql("select value from `tabSingles` where doctype = 'Manage Account' and field = '%s'"%dict[i])
if res and res[0][0] == 'Yes': if res and res[0][0] == 'Yes':
for d in getlist(self.doclist,'entries'): for d in getlist(self.doclist,'entries'):
if not d.fields[i.lower().replace(' ','_')]: if not d.fields[i.lower().replace(' ','_')]:
@ -369,7 +366,7 @@ class DocType(TransactionBase):
#------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------
def validate_proj_cust(self): def validate_proj_cust(self):
if self.doc.project_name and self.doc.customer: if self.doc.project_name and self.doc.customer:
res = sql("select name from `tabProject` where name = '%s' and (customer = '%s' or ifnull(customer,'')='')"%(self.doc.project_name, self.doc.customer)) res = webnotes.conn.sql("select name from `tabProject` where name = '%s' and (customer = '%s' or ifnull(customer,'')='')"%(self.doc.project_name, self.doc.customer))
if not res: if not res:
msgprint("Customer - %s does not belong to project - %s. \n\nIf you want to use project for multiple customers then please make customer details blank in that project."%(self.doc.customer,self.doc.project_name)) msgprint("Customer - %s does not belong to project - %s. \n\nIf you want to use project for multiple customers then please make customer details blank in that project."%(self.doc.customer,self.doc.project_name))
raise Exception raise Exception
@ -386,7 +383,7 @@ class DocType(TransactionBase):
# ********* UPDATE CURRENT STOCK ***************************** # ********* UPDATE CURRENT STOCK *****************************
def update_current_stock(self): def update_current_stock(self):
for d in getlist(self.doclist, 'entries'): for d in getlist(self.doclist, 'entries'):
bin = sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1) bin = webnotes.conn.sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
d.actual_qty = bin and flt(bin[0]['actual_qty']) or 0 d.actual_qty = bin and flt(bin[0]['actual_qty']) or 0
def validate_item_code(self): def validate_item_code(self):
@ -405,10 +402,10 @@ class DocType(TransactionBase):
def validate_c_form(self): def validate_c_form(self):
""" Blank C-form no if C-form applicable marked as 'No'""" """ Blank C-form no if C-form applicable marked as 'No'"""
if self.doc.amended_from and self.doc.c_form_applicable == 'No' and self.doc.c_form_no: if self.doc.amended_from and self.doc.c_form_applicable == 'No' and self.doc.c_form_no:
sql("""delete from `tabC-Form Invoice Detail` where invoice_no = %s webnotes.conn.sql("""delete from `tabC-Form Invoice Detail` where invoice_no = %s
and parent = %s""", (self.doc.amended_from, self.doc.c_form_no)) and parent = %s""", (self.doc.amended_from, self.doc.c_form_no))
set(self.doc, 'c_form_no', '') webnotes.conn.set(self.doc, 'c_form_no', '')
# VALIDATE # VALIDATE
# ==================================================================================== # ====================================================================================
@ -453,13 +450,13 @@ class DocType(TransactionBase):
def check_prev_docstatus(self): def check_prev_docstatus(self):
for d in getlist(self.doclist,'entries'): for d in getlist(self.doclist,'entries'):
if d.sales_order: if d.sales_order:
submitted = sql("select name from `tabSales Order` where docstatus = 1 and name = '%s'" % d.sales_order) submitted = webnotes.conn.sql("select name from `tabSales Order` where docstatus = 1 and name = '%s'" % d.sales_order)
if not submitted: if not submitted:
msgprint("Sales Order : "+ cstr(d.sales_order) +" is not submitted") msgprint("Sales Order : "+ cstr(d.sales_order) +" is not submitted")
raise Exception , "Validation Error." raise Exception , "Validation Error."
if d.delivery_note: if d.delivery_note:
submitted = sql("select name from `tabDelivery Note` where docstatus = 1 and name = '%s'" % d.delivery_note) submitted = webnotes.conn.sql("select name from `tabDelivery Note` where docstatus = 1 and name = '%s'" % d.delivery_note)
if not submitted: if not submitted:
msgprint("Delivery Note : "+ cstr(d.delivery_note) +" is not submitted") msgprint("Delivery Note : "+ cstr(d.delivery_note) +" is not submitted")
raise Exception , "Validation Error." raise Exception , "Validation Error."
@ -469,17 +466,17 @@ class DocType(TransactionBase):
def set_actual_qty(self): def set_actual_qty(self):
for d in getlist(self.doclist, 'delivery_note_details'): for d in getlist(self.doclist, 'delivery_note_details'):
if d.item_code and d.warehouse: if d.item_code and d.warehouse:
actual_qty = sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (d.item_code, d.warehouse)) actual_qty = webnotes.conn.sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (d.item_code, d.warehouse))
d.actual_qty = actual_qty and flt(actual_qty[0][0]) or 0 d.actual_qty = actual_qty and flt(actual_qty[0][0]) or 0
# Check qty in stock depends on item code and warehouse # Check qty in stock depends on item code and warehouse
#------------------------------------------------------- #-------------------------------------------------------
def check_qty_in_stock(self): def check_qty_in_stock(self):
for d in getlist(self.doclist, 'entries'): for d in getlist(self.doclist, 'entries'):
is_stock_item = sql("select is_stock_item from `tabItem` where name = '%s'" % d.item_code)[0][0] is_stock_item = webnotes.conn.sql("select is_stock_item from `tabItem` where name = '%s'" % d.item_code)[0][0]
actual_qty = 0 actual_qty = 0
if d.item_code and d.warehouse: if d.item_code and d.warehouse:
actual_qty = sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (d.item_code, d.warehouse)) actual_qty = webnotes.conn.sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (d.item_code, d.warehouse))
actual_qty = actual_qty and flt(actual_qty[0][0]) or 0 actual_qty = actual_qty and flt(actual_qty[0][0]) or 0
if is_stock_item == 'Yes' and flt(d.qty) > flt(actual_qty): if is_stock_item == 'Yes' and flt(d.qty) > flt(actual_qty):
@ -490,7 +487,7 @@ class DocType(TransactionBase):
# ********************** Make Stock Entry ************************************ # ********************** Make Stock Entry ************************************
def make_sl_entry(self, d, wh, qty, in_value, update_stock): def make_sl_entry(self, d, wh, qty, in_value, update_stock):
st_uom = sql("select stock_uom from `tabItem` where name = '%s'"%d.item_code) st_uom = webnotes.conn.sql("select stock_uom from `tabItem` where name = '%s'"%d.item_code)
self.values.append({ self.values.append({
'item_code' : d.item_code, 'item_code' : d.item_code,
'warehouse' : wh, 'warehouse' : wh,
@ -516,7 +513,7 @@ class DocType(TransactionBase):
def update_stock_ledger(self, update_stock, clear = 0): def update_stock_ledger(self, update_stock, clear = 0):
self.values = [] self.values = []
for d in getlist(self.doclist, 'entries'): for d in getlist(self.doclist, 'entries'):
stock_item = sql("SELECT is_stock_item, is_sample_item FROM tabItem where name = '%s'"%(d.item_code), as_dict = 1) # stock ledger will be updated only if it is a stock item stock_item = webnotes.conn.sql("SELECT is_stock_item, is_sample_item FROM tabItem where name = '%s'"%(d.item_code), as_dict = 1) # stock ledger will be updated only if it is a stock item
if stock_item[0]['is_stock_item'] == "Yes": if stock_item[0]['is_stock_item'] == "Yes":
# Reduce actual qty from warehouse # Reduce actual qty from warehouse
self.make_sl_entry( d, d.warehouse, - flt(d.qty) , 0, update_stock) self.make_sl_entry( d, d.warehouse, - flt(d.qty) , 0, update_stock)
@ -531,7 +528,7 @@ class DocType(TransactionBase):
# ********** Get Actual Qty of item in warehouse selected ************* # ********** Get Actual Qty of item in warehouse selected *************
def get_actual_qty(self,args): def get_actual_qty(self,args):
args = eval(args) args = eval(args)
actual_qty = sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (args['item_code'], args['warehouse']), as_dict=1) actual_qty = webnotes.conn.sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (args['item_code'], args['warehouse']), as_dict=1)
ret = { ret = {
'actual_qty' : actual_qty and flt(actual_qty[0]['actual_qty']) or 0 'actual_qty' : actual_qty and flt(actual_qty[0]['actual_qty']) or 0
} }
@ -574,7 +571,7 @@ class DocType(TransactionBase):
def update_c_form(self): def update_c_form(self):
"""Update amended id in C-form""" """Update amended id in C-form"""
if self.doc.c_form_no and self.doc.amended_from: if self.doc.c_form_no and self.doc.amended_from:
sql("""update `tabC-Form Invoice Detail` set invoice_no = %s, webnotes.conn.sql("""update `tabC-Form Invoice Detail` set invoice_no = %s,
invoice_date = %s, territory = %s, net_total = %s, invoice_date = %s, territory = %s, net_total = %s,
grand_total = %s where invoice_no = %s and parent = %s""", (self.doc.name, self.doc.amended_from, self.doc.c_form_no)) grand_total = %s where invoice_no = %s and parent = %s""", (self.doc.name, self.doc.amended_from, self.doc.c_form_no))
@ -584,7 +581,7 @@ class DocType(TransactionBase):
# Check Next Document's docstatus # Check Next Document's docstatus
# -------------------------------- # --------------------------------
def check_next_docstatus(self): def check_next_docstatus(self):
submit_jv = sql("select t1.name from `tabJournal Voucher` t1,`tabJournal Voucher Detail` t2 where t1.name = t2.parent and t2.against_invoice = '%s' and t1.docstatus = 1" % (self.doc.name)) submit_jv = webnotes.conn.sql("select t1.name from `tabJournal Voucher` t1,`tabJournal Voucher Detail` t2 where t1.name = t2.parent and t2.against_invoice = '%s' and t1.docstatus = 1" % (self.doc.name))
if submit_jv: if submit_jv:
msgprint("Journal Voucher : " + cstr(submit_jv[0][0]) + " has been created against " + cstr(self.doc.doctype) + ". So " + cstr(self.doc.doctype) + " cannot be Cancelled.") msgprint("Journal Voucher : " + cstr(submit_jv[0][0]) + " has been created against " + cstr(self.doc.doctype) + ". So " + cstr(self.doc.doctype) + " cannot be Cancelled.")
raise Exception, "Validation Error." raise Exception, "Validation Error."
@ -607,10 +604,10 @@ class DocType(TransactionBase):
# Get Warehouse # Get Warehouse
def get_warehouse(self): def get_warehouse(self):
w = sql("select warehouse from `tabPOS Setting` where ifnull(user,'') = '%s' and company = '%s'" % (session['user'], self.doc.company)) w = webnotes.conn.sql("select warehouse from `tabPOS Setting` where ifnull(user,'') = '%s' and company = '%s'" % (session['user'], self.doc.company))
w = w and w[0][0] or '' w = w and w[0][0] or ''
if not w: if not w:
ps = sql("select name, warehouse from `tabPOS Setting` where ifnull(user,'') = '' and company = '%s'" % self.doc.company) ps = webnotes.conn.sql("select name, warehouse from `tabPOS Setting` where ifnull(user,'') = '' and company = '%s'" % self.doc.company)
if not ps: if not ps:
msgprint("To make POS entry, please create POS Setting from Setup --> Accounts --> POS Setting and refresh the system.") msgprint("To make POS entry, please create POS Setting from Setup --> Accounts --> POS Setting and refresh the system.")
raise Exception raise Exception
@ -633,12 +630,12 @@ class DocType(TransactionBase):
d.warehouse = cstr(w) d.warehouse = cstr(w)
if flt(self.doc.paid_amount) == 0: if flt(self.doc.paid_amount) == 0:
set(self.doc,'paid_amount',(flt(self.doc.grand_total) - flt(self.doc.write_off_amount))) webnotes.conn.set(self.doc,'paid_amount',(flt(self.doc.grand_total) - flt(self.doc.write_off_amount)))
else: else:
set(self.doc,'paid_amount',0) webnotes.conn.set(self.doc,'paid_amount',0)
set(self.doc,'outstanding_amount',flt(self.doc.grand_total) - flt(self.doc.total_advance) - flt(self.doc.paid_amount) - flt(self.doc.write_off_amount)) webnotes.conn.set(self.doc,'outstanding_amount',flt(self.doc.grand_total) - flt(self.doc.total_advance) - flt(self.doc.paid_amount) - flt(self.doc.write_off_amount))
######################################################################## ########################################################################
# Repair Outstanding # Repair Outstanding
@ -656,9 +653,9 @@ class DocType(TransactionBase):
if self.doc.convert_into_recurring_invoice: if self.doc.convert_into_recurring_invoice:
self.set_next_date() self.set_next_date()
if not self.doc.recurring_id: if not self.doc.recurring_id:
set(self.doc, 'recurring_id', make_autoname('RECINV/.#####')) webnotes.conn.set(self.doc, 'recurring_id', make_autoname('RECINV/.#####'))
elif self.doc.recurring_id: elif self.doc.recurring_id:
sql("""update `tabReceivable Voucher` set convert_into_recurring_invoice = 0 where recurring_id = %s""", self.doc.recurring_id) webnotes.conn.sql("""update `tabReceivable Voucher` set convert_into_recurring_invoice = 0 where recurring_id = %s""", self.doc.recurring_id)
self.manage_scheduler() self.manage_scheduler()
@ -666,7 +663,7 @@ class DocType(TransactionBase):
""" set/cancel event in scheduler """ """ set/cancel event in scheduler """
event = 'accounts.doctype.gl_control.gl_control.manage_recurring_invoices' event = 'accounts.doctype.gl_control.gl_control.manage_recurring_invoices'
if sql("select name from `tabReceivable Voucher` where ifnull(convert_into_recurring_invoice, 0) = 1 and next_date <= end_date"): if webnotes.conn.sql("select name from `tabReceivable Voucher` where ifnull(convert_into_recurring_invoice, 0) = 1 and next_date <= end_date"):
if not self.check_event_exists(event): if not self.check_event_exists(event):
set_event(event, interval = 60*60, recurring = 1) set_event(event, interval = 60*60, recurring = 1)
else: else:
@ -703,4 +700,4 @@ class DocType(TransactionBase):
next_date = datetime.date(y, m, last_day) next_date = datetime.date(y, m, last_day)
next_date = next_date.strftime("%Y-%m-%d") next_date = next_date.strftime("%Y-%m-%d")
set(self.doc, 'next_date', next_date) webnotes.conn.set(self.doc, 'next_date', next_date)

View File

@ -8,7 +8,6 @@ from webnotes.model.doclist import getlist, copy_doclist
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
from webnotes import session, form, is_testing, msgprint, errprint from webnotes import session, form, is_testing, msgprint, errprint
sql = webnotes.conn.sql
get_value = webnotes.conn.get_value get_value = webnotes.conn.get_value
in_transaction = webnotes.conn.in_transaction in_transaction = webnotes.conn.in_transaction
convert_to_lists = webnotes.conn.convert_to_lists convert_to_lists = webnotes.conn.convert_to_lists
@ -44,7 +43,7 @@ class DocType(TransactionBase):
if obj.doc.doctype != 'Quotation': if obj.doc.doctype != 'Quotation':
obj.doc.clear_table(obj.doclist,'sales_team') obj.doc.clear_table(obj.doclist,'sales_team')
idx = 0 idx = 0
for d in sql("select sales_person, allocated_percentage, allocated_amount, incentives from `tabSales Team` where parent = '%s'" % obj.doc.customer): for d in webnotes.conn.sql("select sales_person, allocated_percentage, allocated_amount, incentives from `tabSales Team` where parent = '%s'" % obj.doc.customer):
ch = addchild(obj.doc, 'sales_team', 'Sales Team', 1, obj.doclist) ch = addchild(obj.doc, 'sales_team', 'Sales Team', 1, obj.doclist)
ch.sales_person = d and cstr(d[0]) or '' ch.sales_person = d and cstr(d[0]) or ''
ch.allocated_percentage = d and flt(d[1]) or 0 ch.allocated_percentage = d and flt(d[1]) or 0
@ -59,7 +58,7 @@ class DocType(TransactionBase):
def get_contact_details(self, obj = '', primary = 0): def get_contact_details(self, obj = '', primary = 0):
cond = " and contact_name = '"+cstr(obj.doc.contact_person)+"'" cond = " and contact_name = '"+cstr(obj.doc.contact_person)+"'"
if primary: cond = " and is_primary_contact = 'Yes'" if primary: cond = " and is_primary_contact = 'Yes'"
contact = sql("select contact_name, contact_no, email_id, contact_address from `tabContact` where customer = '%s' and docstatus != 2 %s" %(obj.doc.customer, cond), as_dict = 1) contact = webnotes.conn.sql("select contact_name, contact_no, email_id, contact_address from `tabContact` where customer = '%s' and docstatus != 2 %s" %(obj.doc.customer, cond), as_dict = 1)
if not contact: if not contact:
return return
c = contact[0] c = contact[0]
@ -74,7 +73,7 @@ class DocType(TransactionBase):
# Get customer's primary shipping details # Get customer's primary shipping details
# ============================================================== # ==============================================================
def get_shipping_details(self, obj = ''): def get_shipping_details(self, obj = ''):
det = sql("select name, ship_to, shipping_address from `tabShipping Address` where customer = '%s' and docstatus != 2 and ifnull(is_primary_address, 'Yes') = 'Yes'" %(obj.doc.customer), as_dict = 1) det = webnotes.conn.sql("select name, ship_to, shipping_address from `tabShipping Address` where customer = '%s' and docstatus != 2 and ifnull(is_primary_address, 'Yes') = 'Yes'" %(obj.doc.customer), as_dict = 1)
obj.doc.ship_det_no = det and det[0]['name'] or '' obj.doc.ship_det_no = det and det[0]['name'] or ''
obj.doc.ship_to = det and det[0]['ship_to'] or '' obj.doc.ship_to = det and det[0]['ship_to'] or ''
obj.doc.shipping_address = det and det[0]['shipping_address'] or '' obj.doc.shipping_address = det and det[0]['shipping_address'] or ''
@ -84,14 +83,14 @@ class DocType(TransactionBase):
# ==================== # ====================
def get_invoice_details(self, obj = ''): def get_invoice_details(self, obj = ''):
if obj.doc.company: if obj.doc.company:
acc_head = sql("select name from `tabAccount` where name = '%s' and docstatus != 2" % (cstr(obj.doc.customer) + " - " + get_value('Company', obj.doc.company, 'abbr'))) acc_head = webnotes.conn.sql("select name from `tabAccount` where name = '%s' and docstatus != 2" % (cstr(obj.doc.customer) + " - " + get_value('Company', obj.doc.company, 'abbr')))
obj.doc.debit_to = acc_head and acc_head[0][0] or '' obj.doc.debit_to = acc_head and acc_head[0][0] or ''
# Get Customer Details along with its primary contact details # Get Customer Details along with its primary contact details
# ============================================================== # ==============================================================
def get_customer_details(self, obj = '', inv_det_reqd = 1): def get_customer_details(self, obj = '', inv_det_reqd = 1):
details = sql("select customer_name,address, territory, customer_group, default_sales_partner, default_commission_rate from `tabCustomer` where name = '%s' and docstatus != 2" %(obj.doc.customer), as_dict = 1) details = webnotes.conn.sql("select customer_name,address, territory, customer_group, default_sales_partner, default_commission_rate from `tabCustomer` where name = '%s' and docstatus != 2" %(obj.doc.customer), as_dict = 1)
obj.doc.customer_name = details and details[0]['customer_name'] or '' obj.doc.customer_name = details and details[0]['customer_name'] or ''
obj.doc.customer_address = details and details[0]['address'] or '' obj.doc.customer_address = details and details[0]['address'] or ''
obj.doc.territory = details and details[0]['territory'] or '' obj.doc.territory = details and details[0]['territory'] or ''
@ -113,8 +112,8 @@ class DocType(TransactionBase):
if not obj.doc.price_list_name: if not obj.doc.price_list_name:
msgprint("Please Select Price List before selecting Items") msgprint("Please Select Price List before selecting Items")
raise Exception raise Exception
item = sql("select description, item_name, brand, item_group, stock_uom, default_warehouse, default_income_account, default_sales_cost_center, description_html from `tabItem` where name = '%s' and (ifnull(end_of_life,'')='' or end_of_life > now() or end_of_life = '0000-00-00') and (is_sales_item = 'Yes' or is_service_item = 'Yes')" %(item_code), as_dict=1) item = webnotes.conn.sql("select description, item_name, brand, item_group, stock_uom, default_warehouse, default_income_account, default_sales_cost_center, description_html from `tabItem` where name = '%s' and (ifnull(end_of_life,'')='' or end_of_life > now() or end_of_life = '0000-00-00') and (is_sales_item = 'Yes' or is_service_item = 'Yes')" %(item_code), as_dict=1)
tax = sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , item_code) tax = webnotes.conn.sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , item_code)
t = {} t = {}
for x in tax: t[x[0]] = flt(x[1]) for x in tax: t[x[0]] = flt(x[1])
ret = { ret = {
@ -145,7 +144,7 @@ class DocType(TransactionBase):
# ***************** Get Ref rate as entered in Item Master ******************** # ***************** Get Ref rate as entered in Item Master ********************
def get_ref_rate(self, item_code, price_list_name, price_list_currency, plc_conv_rate): def get_ref_rate(self, item_code, price_list_name, price_list_currency, plc_conv_rate):
ref_rate = sql("select ref_rate from `tabRef Rate Detail` where parent = %s and price_list_name = %s and ref_currency = %s", (item_code, price_list_name, price_list_currency)) ref_rate = webnotes.conn.sql("select ref_rate from `tabRef Rate Detail` where parent = %s and price_list_name = %s and ref_currency = %s", (item_code, price_list_name, price_list_currency))
base_ref_rate = ref_rate and flt(ref_rate[0][0]) * flt(plc_conv_rate) or 0 base_ref_rate = ref_rate and flt(ref_rate[0][0]) * flt(plc_conv_rate) or 0
return base_ref_rate return base_ref_rate
@ -175,7 +174,7 @@ class DocType(TransactionBase):
if default: add_cond = 'ifnull(t2.is_default,0) = 1' if default: add_cond = 'ifnull(t2.is_default,0) = 1'
else: add_cond = 't1.parent = "'+cstr(obj.doc.charge)+'"' else: add_cond = 't1.parent = "'+cstr(obj.doc.charge)+'"'
idx = 0 idx = 0
other_charge = sql("select t1.charge_type,t1.row_id,t1.description,t1.account_head,t1.rate,t1.tax_amount,t1.included_in_print_rate from `tabRV Tax Detail` t1, `tabOther Charges` t2 where t1.parent = t2.name and t2.company = '%s' and %s order by t1.idx" % (obj.doc.company, add_cond), as_dict = 1) other_charge = webnotes.conn.sql("select t1.charge_type,t1.row_id,t1.description,t1.account_head,t1.rate,t1.tax_amount,t1.included_in_print_rate from `tabRV Tax Detail` t1, `tabOther Charges` t2 where t1.parent = t2.name and t2.company = '%s' and %s order by t1.idx" % (obj.doc.company, add_cond), as_dict = 1)
for other in other_charge: for other in other_charge:
d = addchild(obj.doc, 'other_charges', 'RV Tax Detail', 1, obj.doclist) d = addchild(obj.doc, 'other_charges', 'RV Tax Detail', 1, obj.doclist)
d.charge_type = other['charge_type'] d.charge_type = other['charge_type']
@ -192,12 +191,12 @@ class DocType(TransactionBase):
# Get TERMS AND CONDITIONS # Get TERMS AND CONDITIONS
# ======================================================================================= # =======================================================================================
def get_tc_details(self,obj): def get_tc_details(self,obj):
r = sql("select terms from `tabTerm` where name = %s", obj.doc.tc_name) r = webnotes.conn.sql("select terms from `tabTerm` where name = %s", obj.doc.tc_name)
if r: obj.doc.terms = r[0][0] if r: obj.doc.terms = r[0][0]
#---------------------------------------- Get Tax Details -------------------------------# #---------------------------------------- Get Tax Details -------------------------------#
def get_tax_details(self, item_code, obj): def get_tax_details(self, item_code, obj):
tax = sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , item_code) tax = webnotes.conn.sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , item_code)
t = {} t = {}
for x in tax: t[x[0]] = flt(x[1]) for x in tax: t[x[0]] = flt(x[1])
ret = { ret = {
@ -208,8 +207,8 @@ class DocType(TransactionBase):
# Get Serial No Details # Get Serial No Details
# ========================================================================== # ==========================================================================
def get_serial_details(self, serial_no, obj): def get_serial_details(self, serial_no, obj):
item = sql("select item_code, make, label,brand, description from `tabSerial No` where name = '%s' and docstatus != 2" %(serial_no), as_dict=1) item = webnotes.conn.sql("select item_code, make, label,brand, description from `tabSerial No` where name = '%s' and docstatus != 2" %(serial_no), as_dict=1)
tax = sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , item[0]['item_code']) tax = webnotes.conn.sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , item[0]['item_code'])
t = {} t = {}
for x in tax: t[x[0]] = flt(x[1]) for x in tax: t[x[0]] = flt(x[1])
ret = { ret = {
@ -226,7 +225,7 @@ class DocType(TransactionBase):
# ======================================================================= # =======================================================================
def get_comm_rate(self, sales_partner, obj): def get_comm_rate(self, sales_partner, obj):
comm_rate = sql("select commission_rate from `tabSales Partner` where name = '%s' and docstatus != 2" %(sales_partner), as_dict=1) comm_rate = webnotes.conn.sql("select commission_rate from `tabSales Partner` where name = '%s' and docstatus != 2" %(sales_partner), as_dict=1)
if comm_rate: if comm_rate:
total_comm = flt(comm_rate[0]['commission_rate']) * flt(obj.doc.net_total) / 100 total_comm = flt(comm_rate[0]['commission_rate']) * flt(obj.doc.net_total) / 100
ret = { ret = {
@ -243,7 +242,7 @@ class DocType(TransactionBase):
# ======================================================================================= # =======================================================================================
def validate_max_discount(self,obj, detail_table): def validate_max_discount(self,obj, detail_table):
for d in getlist(obj.doclist, detail_table): for d in getlist(obj.doclist, detail_table):
discount = sql("select max_discount from tabItem where name = '%s'" %(d.item_code),as_dict = 1) discount = webnotes.conn.sql("select max_discount from tabItem where name = '%s'" %(d.item_code),as_dict = 1)
if discount and discount[0]['max_discount'] and (flt(d.adj_rate)>flt(discount[0]['max_discount'])): if discount and discount[0]['max_discount'] and (flt(d.adj_rate)>flt(discount[0]['max_discount'])):
msgprint("You cannot give more than " + cstr(discount[0]['max_discount']) + " % discount on Item Code : "+cstr(d.item_code)) msgprint("You cannot give more than " + cstr(discount[0]['max_discount']) + " % discount on Item Code : "+cstr(d.item_code))
raise Exception raise Exception
@ -279,7 +278,7 @@ class DocType(TransactionBase):
# ========================================================================= # =========================================================================
def get_rate(self, arg): def get_rate(self, arg):
arg = eval(arg) arg = eval(arg)
rate = sql("select account_type, tax_rate from `tabAccount` where name = '%s' and docstatus != 2" %(arg['account_head']), as_dict=1) rate = webnotes.conn.sql("select account_type, tax_rate from `tabAccount` where name = '%s' and docstatus != 2" %(arg['account_head']), as_dict=1)
ret = {'rate' : 0} ret = {'rate' : 0}
if arg['charge_type'] == 'Actual' and rate[0]['account_type'] == 'Tax': if arg['charge_type'] == 'Actual' and rate[0]['account_type'] == 'Tax':
msgprint("You cannot select ACCOUNT HEAD of type TAX as your CHARGE TYPE is 'ACTUAL'") msgprint("You cannot select ACCOUNT HEAD of type TAX as your CHARGE TYPE is 'ACTUAL'")
@ -296,10 +295,10 @@ class DocType(TransactionBase):
# Make Packing List from Sales BOM # Make Packing List from Sales BOM
# ======================================================================= # =======================================================================
def has_sales_bom(self, item_code): def has_sales_bom(self, item_code):
return sql("select name from `tabSales BOM` where name=%s and docstatus != 2", item_code) return webnotes.conn.sql("select name from `tabSales BOM` where name=%s and docstatus != 2", item_code)
def get_sales_bom_items(self, item_code): def get_sales_bom_items(self, item_code):
return sql("select item_code, qty, uom from `tabSales BOM Detail` where parent=%s", item_code) return webnotes.conn.sql("select item_code, qty, uom from `tabSales BOM Detail` where parent=%s", item_code)
# -------------- # --------------
@ -339,14 +338,14 @@ class DocType(TransactionBase):
def get_curr_and_ref_doc_details(self, curr_doctype, ref_tab_fname, ref_tab_dn, ref_doc_tname, curr_parent_name, curr_parent_doctype): def get_curr_and_ref_doc_details(self, curr_doctype, ref_tab_fname, ref_tab_dn, ref_doc_tname, curr_parent_name, curr_parent_doctype):
# Get total qty, amt of current doctype (eg RV) except for qty, amt of this transaction # Get total qty, amt of current doctype (eg RV) except for qty, amt of this transaction
if curr_parent_doctype == 'Installation Note': if curr_parent_doctype == 'Installation Note':
curr_det = sql("select sum(qty) from `tab%s` where %s = '%s' and docstatus = 1 and parent != '%s'"% (curr_doctype, ref_tab_fname, ref_tab_dn, curr_parent_name)) curr_det = webnotes.conn.sql("select sum(qty) from `tab%s` where %s = '%s' and docstatus = 1 and parent != '%s'"% (curr_doctype, ref_tab_fname, ref_tab_dn, curr_parent_name))
qty, amt = curr_det and flt(curr_det[0][0]) or 0, 0 qty, amt = curr_det and flt(curr_det[0][0]) or 0, 0
else: else:
curr_det = sql("select sum(qty), sum(amount) from `tab%s` where %s = '%s' and docstatus = 1 and parent != '%s'"% (curr_doctype, ref_tab_fname, ref_tab_dn, curr_parent_name)) curr_det = webnotes.conn.sql("select sum(qty), sum(amount) from `tab%s` where %s = '%s' and docstatus = 1 and parent != '%s'"% (curr_doctype, ref_tab_fname, ref_tab_dn, curr_parent_name))
qty, amt = curr_det and flt(curr_det[0][0]) or 0, curr_det and flt(curr_det[0][1]) or 0 qty, amt = curr_det and flt(curr_det[0][0]) or 0, curr_det and flt(curr_det[0][1]) or 0
# get total qty of ref doctype # get total qty of ref doctype
ref_det = sql("select qty, amount from `tab%s` where name = '%s' and docstatus = 1"% (ref_doc_tname, ref_tab_dn)) ref_det = webnotes.conn.sql("select qty, amount from `tab%s` where name = '%s' and docstatus = 1"% (ref_doc_tname, ref_tab_dn))
max_qty, max_amt = ref_det and flt(ref_det[0][0]) or 0, ref_det and flt(ref_det[0][1]) or 0 max_qty, max_amt = ref_det and flt(ref_det[0][0]) or 0, ref_det and flt(ref_det[0][1]) or 0
return qty, max_qty, amt, max_amt return qty, max_qty, amt, max_amt
@ -359,10 +358,10 @@ class DocType(TransactionBase):
# add packing list items # add packing list items
# ----------------------- # -----------------------
def get_packing_item_details(self, item): def get_packing_item_details(self, item):
return sql("select item_name, description, stock_uom from `tabItem` where name = %s", item, as_dict = 1)[0] return webnotes.conn.sql("select item_name, description, stock_uom from `tabItem` where name = %s", item, as_dict = 1)[0]
def get_bin_qty(self, item, warehouse): def get_bin_qty(self, item, warehouse):
det = sql("select actual_qty, projected_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (item, warehouse), as_dict = 1) det = webnotes.conn.sql("select actual_qty, projected_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (item, warehouse), as_dict = 1)
return det and det[0] or '' return det and det[0] or ''
def add_packing_list_item(self,obj, item_code, qty, warehouse, line): def add_packing_list_item(self,obj, item_code, qty, warehouse, line):
@ -424,7 +423,7 @@ class DocType(TransactionBase):
elif d.fields.has_key('sales_order') and d.sales_order and not d.delivery_note: elif d.fields.has_key('sales_order') and d.sales_order and not d.delivery_note:
ref_doc_name = d.sales_order ref_doc_name = d.sales_order
if ref_doc_name: if ref_doc_name:
so_status = sql("select status from `tabSales Order` where name = %s",ref_doc_name) so_status = webnotes.conn.sql("select status from `tabSales Order` where name = %s",ref_doc_name)
so_status = so_status and so_status[0][0] or '' so_status = so_status and so_status[0][0] or ''
if so_status == 'Stopped': if so_status == 'Stopped':
msgprint("You cannot do any transaction against Sales Order : '%s' as it is Stopped." %(ref_doc_name)) msgprint("You cannot do any transaction against Sales Order : '%s' as it is Stopped." %(ref_doc_name))
@ -435,7 +434,7 @@ class DocType(TransactionBase):
def check_active_sales_items(self,obj): def check_active_sales_items(self,obj):
for d in getlist(obj.doclist, obj.fname): for d in getlist(obj.doclist, obj.fname):
if d.item_code: # extra condn coz item_code is not mandatory in RV if d.item_code: # extra condn coz item_code is not mandatory in RV
valid_item = sql("select docstatus,is_sales_item, is_service_item from tabItem where name = %s",d.item_code) valid_item = webnotes.conn.sql("select docstatus,is_sales_item, is_service_item from tabItem where name = %s",d.item_code)
if valid_item and valid_item[0][0] == 2: if valid_item and valid_item[0][0] == 2:
msgprint("Item : '%s' does not exist in system." %(d.item_code)) msgprint("Item : '%s' does not exist in system." %(d.item_code))
raise Exception raise Exception
@ -449,10 +448,10 @@ class DocType(TransactionBase):
# ************************************************************************************************************************************************** # **************************************************************************************************************************************************
def check_credit(self,obj,grand_total): def check_credit(self,obj,grand_total):
acc_head = sql("select name from `tabAccount` where company = '%s' and master_name = '%s'"%(obj.doc.company, obj.doc.customer)) acc_head = webnotes.conn.sql("select name from `tabAccount` where company = '%s' and master_name = '%s'"%(obj.doc.company, obj.doc.customer))
if acc_head: if acc_head:
tot_outstanding = 0 tot_outstanding = 0
dbcr = sql("select sum(debit), sum(credit) from `tabGL Entry` where account = '%s' and ifnull(is_cancelled, 'No')='No'" % acc_head[0][0]) dbcr = webnotes.conn.sql("select sum(debit), sum(credit) from `tabGL Entry` where account = '%s' and ifnull(is_cancelled, 'No')='No'" % acc_head[0][0])
if dbcr: if dbcr:
tot_outstanding = flt(dbcr[0][0])-flt(dbcr[0][1]) tot_outstanding = flt(dbcr[0][0])-flt(dbcr[0][1])
@ -460,7 +459,7 @@ class DocType(TransactionBase):
get_obj('Account',acc_head[0][0]).check_credit_limit(acc_head[0][0], obj.doc.company, exact_outstanding) get_obj('Account',acc_head[0][0]).check_credit_limit(acc_head[0][0], obj.doc.company, exact_outstanding)
def validate_fiscal_year(self,fiscal_year,transaction_date,dn): def validate_fiscal_year(self,fiscal_year,transaction_date,dn):
fy=sql("select year_start_date from `tabFiscal Year` where name='%s'"%fiscal_year) fy=webnotes.conn.sql("select year_start_date from `tabFiscal Year` where name='%s'"%fiscal_year)
ysd=fy and fy[0][0] or "" ysd=fy and fy[0][0] or ""
yed=add_days(str(ysd),365) yed=add_days(str(ysd),365)
if str(transaction_date) < str(ysd) or str(transaction_date) > str(yed): if str(transaction_date) < str(ysd) or str(transaction_date) > str(yed):
@ -475,9 +474,9 @@ class DocType(TransactionBase):
for d in getlist(obj.doclist, obj.fname): for d in getlist(obj.doclist, obj.fname):
if d.prevdoc_doctype and d.prevdoc_docname: if d.prevdoc_doctype and d.prevdoc_docname:
if d.prevdoc_doctype == 'Receivable Voucher': if d.prevdoc_doctype == 'Receivable Voucher':
dt = sql("select posting_date from `tab%s` where name = '%s'" % (d.prevdoc_doctype, d.prevdoc_docname)) dt = webnotes.conn.sql("select posting_date from `tab%s` where name = '%s'" % (d.prevdoc_doctype, d.prevdoc_docname))
else: else:
dt = sql("select transaction_date from `tab%s` where name = '%s'" % (d.prevdoc_doctype, d.prevdoc_docname)) dt = webnotes.conn.sql("select transaction_date from `tab%s` where name = '%s'" % (d.prevdoc_doctype, d.prevdoc_docname))
d.prevdoc_date = dt and dt[0][0].strftime('%Y-%m-%d') or '' d.prevdoc_date = dt and dt[0][0].strftime('%Y-%m-%d') or ''
def update_prevdoc_detail(self, is_submit, obj): def update_prevdoc_detail(self, is_submit, obj):
@ -607,7 +606,7 @@ class StatusUpdater:
args['name'] = d.fields[args['join_field']] args['name'] = d.fields[args['join_field']]
# get all qty where qty > compare_field # get all qty where qty > compare_field
item = sql(""" item = webnotes.conn.sql("""
select item_code, `%(compare_ref_field)s`, `%(compare_field)s`, parenttype, parent from `tab%(target_dt)s` select item_code, `%(compare_ref_field)s`, `%(compare_field)s`, parenttype, parent from `tab%(target_dt)s`
where `%(compare_ref_field)s` < `%(compare_field)s` and name="%(name)s" and docstatus=1 where `%(compare_ref_field)s` < `%(compare_field)s` and name="%(name)s" and docstatus=1
""" % args, as_dict=1) """ % args, as_dict=1)
@ -712,7 +711,7 @@ class StatusUpdater:
args['detail_id'] = d.fields.get(args['join_field']) args['detail_id'] = d.fields.get(args['join_field'])
if args['detail_id']: if args['detail_id']:
sql(""" webnotes.conn.sql("""
update update
`tab%(target_dt)s` `tab%(target_dt)s`
set set
@ -727,7 +726,7 @@ class StatusUpdater:
args['name'] = name args['name'] = name
# update percent complete in the parent table # update percent complete in the parent table
sql(""" webnotes.conn.sql("""
update update
`tab%(target_parent_dt)s` `tab%(target_parent_dt)s`
set set
@ -740,7 +739,7 @@ class StatusUpdater:
# update field # update field
if args['status_field']: if args['status_field']:
sql(""" webnotes.conn.sql("""
update update
`tab%(target_parent_dt)s` `tab%(target_parent_dt)s`
set set

View File

@ -4,8 +4,6 @@ from webnotes.model.doc import Document, addchild, removechild, getchildren
from webnotes.model.doclist import getlist, copy_doclist from webnotes.model.doclist import getlist, copy_doclist
from webnotes import msgprint from webnotes import msgprint
sql = webnotes.conn.sql
class TransactionBase: class TransactionBase:
# Get Customer Default Primary Address - first load # Get Customer Default Primary Address - first load
@ -66,9 +64,9 @@ class TransactionBase:
cond = 'name="%s"' % address_name cond = 'name="%s"' % address_name
if is_shipping_address: if is_shipping_address:
details = sql("select name, address_line1, address_line2, city, country, pincode, state, phone from `tabAddress` where %s and docstatus != 2 order by is_shipping_address desc limit 1" % cond, as_dict = 1) details = webnotes.conn.sql("select name, address_line1, address_line2, city, country, pincode, state, phone from `tabAddress` where %s and docstatus != 2 order by is_shipping_address desc limit 1" % cond, as_dict = 1)
else: else:
details = sql("select name, address_line1, address_line2, city, country, pincode, state, phone from `tabAddress` where %s and docstatus != 2 order by is_primary_address desc limit 1" % cond, as_dict = 1) details = webnotes.conn.sql("select name, address_line1, address_line2, city, country, pincode, state, phone from `tabAddress` where %s and docstatus != 2 order by is_primary_address desc limit 1" % cond, as_dict = 1)
extract = lambda x: details and details[0] and details[0].get(x,'') or '' extract = lambda x: details and details[0] and details[0].get(x,'') or ''
address_fields = [('','address_line1'),('\n','address_line2'),('\n','city'),(' ','pincode'),('\n','state'),('\n','country'),('\nPhone: ','phone')] address_fields = [('','address_line1'),('\n','address_line2'),('\n','city'),(' ','pincode'),('\n','state'),('\n','country'),('\nPhone: ','phone')]
@ -88,7 +86,7 @@ class TransactionBase:
else: else:
cond = 'name="%s"' % contact_name cond = 'name="%s"' % contact_name
details = sql("select name, first_name, last_name, email_id, phone, mobile_no, department, designation from `tabContact` where %s and docstatus != 2 order by is_primary_contact desc limit 1" % cond, as_dict = 1) details = webnotes.conn.sql("select name, first_name, last_name, email_id, phone, mobile_no, department, designation from `tabContact` where %s and docstatus != 2 order by is_primary_contact desc limit 1" % cond, as_dict = 1)
extract = lambda x: details and details[0] and details[0].get(x,'') or '' extract = lambda x: details and details[0] and details[0].get(x,'') or ''
contact_fields = [('','first_name'),(' ','last_name')] contact_fields = [('','first_name'),(' ','last_name')]
@ -103,7 +101,7 @@ class TransactionBase:
# Get Customer Details # Get Customer Details
# ----------------------- # -----------------------
def get_customer_details(self, name): def get_customer_details(self, name):
customer_details = sql("select customer_name, customer_group, territory, default_sales_partner, default_commission_rate from tabCustomer where name = '%s' and docstatus != 2" %(name), as_dict = 1) customer_details = webnotes.conn.sql("select customer_name, customer_group, territory, default_sales_partner, default_commission_rate from tabCustomer where name = '%s' and docstatus != 2" %(name), as_dict = 1)
if customer_details: if customer_details:
self.doc.customer_name = customer_details[0]['customer_name'] or '' self.doc.customer_name = customer_details[0]['customer_name'] or ''
self.doc.customer_group = customer_details[0]['customer_group'] or '' self.doc.customer_group = customer_details[0]['customer_group'] or ''
@ -114,7 +112,7 @@ class TransactionBase:
# Get Customer Shipping Address # Get Customer Shipping Address
# ----------------------- # -----------------------
def get_shipping_address(self, name): def get_shipping_address(self, name):
details = sql("select name, address_line1, address_line2, city, country, pincode, state, phone from `tabAddress` where customer = '%s' and docstatus != 2 order by is_shipping_address desc limit 1" %(name), as_dict = 1) details = webnotes.conn.sql("select name, address_line1, address_line2, city, country, pincode, state, phone from `tabAddress` where customer = '%s' and docstatus != 2 order by is_shipping_address desc limit 1" %(name), as_dict = 1)
extract = lambda x: details and details[0] and details[0].get(x,'') or '' extract = lambda x: details and details[0] and details[0].get(x,'') or ''
address_fields = [('','address_line1'),('\n','address_line2'),('\n','city'),(' ','pincode'),('\n','state'),('\n','country'),('\nPhone: ','phone')] address_fields = [('','address_line1'),('\n','address_line2'),('\n','city'),(' ','pincode'),('\n','state'),('\n','country'),('\nPhone: ','phone')]
@ -130,7 +128,7 @@ class TransactionBase:
# Get Lead Details # Get Lead Details
# ----------------------- # -----------------------
def get_lead_details(self, name): def get_lead_details(self, name):
details = sql("select name, lead_name, address_line1, address_line2, city, country, state, pincode, territory, contact_no, mobile_no, email_id from `tabLead` where name = '%s'" %(name), as_dict = 1) details = webnotes.conn.sql("select name, lead_name, address_line1, address_line2, city, country, state, pincode, territory, contact_no, mobile_no, email_id from `tabLead` where name = '%s'" %(name), as_dict = 1)
extract = lambda x: details and details[0] and details[0].get(x,'') or '' extract = lambda x: details and details[0] and details[0].get(x,'') or ''
address_fields = [('','address_line1'),('\n','address_line2'),('\n','city'),(' ','pincode'),('\n','state'),('\n','country'),('\nPhone: ','contact_no')] address_fields = [('','address_line1'),('\n','address_line2'),('\n','city'),(' ','pincode'),('\n','state'),('\n','country'),('\nPhone: ','contact_no')]
@ -183,7 +181,7 @@ class TransactionBase:
# Get Supplier Details # Get Supplier Details
# ----------------------- # -----------------------
def get_supplier_details(self, name): def get_supplier_details(self, name):
supplier_details = sql("select supplier_name from tabSupplier where name = '%s' and docstatus != 2" %(name), as_dict = 1) supplier_details = webnotes.conn.sql("select supplier_name from tabSupplier where name = '%s' and docstatus != 2" %(name), as_dict = 1)
ret = { ret = {
'supplier_name' : supplier_details and supplier_details[0]['supplier_name'] or '' 'supplier_name' : supplier_details and supplier_details[0]['supplier_name'] or ''
} }
@ -194,7 +192,7 @@ class TransactionBase:
def get_sales_person(self, name): def get_sales_person(self, name):
self.doc.clear_table(self.doclist,'sales_team') self.doc.clear_table(self.doclist,'sales_team')
idx = 0 idx = 0
for d in sql("select sales_person, allocated_percentage, allocated_amount, incentives from `tabSales Team` where parent = '%s'" % name): for d in webnotes.conn.sql("select sales_person, allocated_percentage, allocated_amount, incentives from `tabSales Team` where parent = '%s'" % name):
ch = addchild(self.doc, 'sales_team', 'Sales Team', 1, self.doclist) ch = addchild(self.doc, 'sales_team', 'Sales Team', 1, self.doclist)
ch.sales_person = d and cstr(d[0]) or '' ch.sales_person = d and cstr(d[0]) or ''
ch.allocated_percentage = d and flt(d[1]) or 0 ch.allocated_percentage = d and flt(d[1]) or 0
@ -206,6 +204,6 @@ class TransactionBase:
# Get Company Specific Default Currency # Get Company Specific Default Currency
# ------------------------------------- # -------------------------------------
def get_company_currency(self, name): def get_company_currency(self, name):
ret = sql("select default_currency from tabCompany where name = '%s'" %(name)) ret = webnotes.conn.sql("select default_currency from tabCompany where name = '%s'" %(name))
dcc = ret and ret[0][0] or get_defaults()['currency'] dcc = ret and ret[0][0] or get_defaults()['currency']
return dcc return dcc