Changed frappe.conn to frappe.db

This commit is contained in:
Anand Doshi 2014-02-26 12:35:33 +05:30
parent 901f4434fd
commit e9baaa68e7
191 changed files with 1375 additions and 1375 deletions

View File

@ -1,5 +1,5 @@
{%- if doc.letter_head -%}
{{ frappe.conn.get_value("Letter Head", doc.letter_head, "content") }}
{{ frappe.db.get_value("Letter Head", doc.letter_head, "content") }}
{%- endif -%}
<!-- Page Layout Settings -->
<div class='common page-header'>

View File

@ -7,7 +7,7 @@ import frappe
from frappe.utils import flt, fmt_money, cstr, cint
from frappe import msgprint, throw, _
get_value = frappe.conn.get_value
get_value = frappe.db.get_value
class DocType:
def __init__(self,d,dl):
@ -16,11 +16,11 @@ class DocType:
def autoname(self):
self.doc.name = self.doc.account_name.strip() + ' - ' + \
frappe.conn.get_value("Company", self.doc.company, "abbr")
frappe.db.get_value("Company", self.doc.company, "abbr")
def get_address(self):
return {
'address': frappe.conn.get_value(self.doc.master_type,
'address': frappe.db.get_value(self.doc.master_type,
self.doc.master_name, "address")
}
@ -41,14 +41,14 @@ class DocType:
if self.doc.master_type in ('Customer', 'Supplier') or self.doc.account_type == "Warehouse":
if not self.doc.master_name:
msgprint(_("Please enter Master Name once the account is created."))
elif not frappe.conn.exists(self.doc.master_type or self.doc.account_type,
elif not frappe.db.exists(self.doc.master_type or self.doc.account_type,
self.doc.master_name):
throw(_("Invalid Master Name"))
def validate_parent(self):
"""Fetch Parent Details and validation for account not to be created under ledger"""
if self.doc.parent_account:
par = frappe.conn.sql("""select name, group_or_ledger, is_pl_account, debit_or_credit
par = frappe.db.sql("""select name, group_or_ledger, is_pl_account, debit_or_credit
from tabAccount where name =%s""", self.doc.parent_account)
if not par:
throw(_("Parent account does not exists"))
@ -72,15 +72,15 @@ class DocType:
def validate_max_root_accounts(self):
"""Raise exception if there are more than 4 root accounts"""
if frappe.conn.sql("""select count(*) from tabAccount where
if frappe.db.sql("""select count(*) from tabAccount where
company=%s and ifnull(parent_account,'')='' and docstatus != 2""",
self.doc.company)[0][0] > 4:
throw(_("One company cannot have more than 4 root Accounts"))
def validate_duplicate_account(self):
if self.doc.fields.get('__islocal') or not self.doc.name:
company_abbr = frappe.conn.get_value("Company", self.doc.company, "abbr")
if frappe.conn.sql("""select name from tabAccount where name=%s""",
company_abbr = frappe.db.get_value("Company", self.doc.company, "abbr")
if frappe.db.sql("""select name from tabAccount where name=%s""",
(self.doc.account_name + " - " + company_abbr)):
throw("{name}: {acc_name} {exist}, {rename}".format(**{
"name": _("Account Name"),
@ -91,14 +91,14 @@ class DocType:
def validate_root_details(self):
#does not exists parent
if frappe.conn.exists("Account", self.doc.name):
if not frappe.conn.get_value("Account", self.doc.name, "parent_account"):
if frappe.db.exists("Account", self.doc.name):
if not frappe.db.get_value("Account", self.doc.name, "parent_account"):
throw(_("Root cannot be edited."))
def validate_frozen_accounts_modifier(self):
old_value = frappe.conn.get_value("Account", self.doc.name, "freeze_account")
old_value = frappe.db.get_value("Account", self.doc.name, "freeze_account")
if old_value and old_value != self.doc.freeze_account:
frozen_accounts_modifier = frappe.conn.get_value( 'Accounts Settings', None,
frozen_accounts_modifier = frappe.db.get_value( 'Accounts Settings', None,
'frozen_accounts_modifier')
if not frozen_accounts_modifier or \
frozen_accounts_modifier not in frappe.user.get_roles():
@ -131,10 +131,10 @@ class DocType:
# Check if any previous balance exists
def check_gle_exists(self):
return frappe.conn.get_value("GL Entry", {"account": self.doc.name})
return frappe.db.get_value("GL Entry", {"account": self.doc.name})
def check_if_child_exists(self):
return frappe.conn.sql("""select name from `tabAccount` where parent_account = %s
return frappe.db.sql("""select name from `tabAccount` where parent_account = %s
and docstatus != 2""", self.doc.name)
def validate_mandatory(self):
@ -148,7 +148,7 @@ class DocType:
return
if self.doc.account_type == "Warehouse":
old_warehouse = cstr(frappe.conn.get_value("Account", self.doc.name, "master_name"))
old_warehouse = cstr(frappe.db.get_value("Account", self.doc.name, "master_name"))
if old_warehouse != cstr(self.doc.master_name):
if old_warehouse:
self.validate_warehouse(old_warehouse)
@ -158,7 +158,7 @@ class DocType:
throw(_("Master Name is mandatory if account type is Warehouse"))
def validate_warehouse(self, warehouse):
if frappe.conn.get_value("Stock Ledger Entry", {"warehouse": warehouse}):
if frappe.db.get_value("Stock Ledger Entry", {"warehouse": warehouse}):
throw(_("Stock transactions exist against warehouse ") + warehouse +
_(" .You can not assign / modify / remove Master Name"))
@ -174,7 +174,7 @@ class DocType:
def get_authorized_user(self):
# Check logged-in user is authorized
if frappe.conn.get_value('Accounts Settings', None, 'credit_controller') \
if frappe.db.get_value('Accounts Settings', None, 'credit_controller') \
in frappe.user.get_roles():
return 1
@ -182,11 +182,11 @@ class DocType:
# Get credit limit
credit_limit_from = 'Customer'
cr_limit = frappe.conn.sql("""select t1.credit_limit from tabCustomer t1, `tabAccount` t2
cr_limit = frappe.db.sql("""select t1.credit_limit from tabCustomer t1, `tabAccount` t2
where t2.name=%s and t1.name = t2.master_name""", self.doc.name)
credit_limit = cr_limit and flt(cr_limit[0][0]) or 0
if not credit_limit:
credit_limit = frappe.conn.get_value('Company', self.doc.company, 'credit_limit')
credit_limit = frappe.db.get_value('Company', self.doc.company, 'credit_limit')
credit_limit_from = 'Company'
# If outstanding greater than credit limit and not authorized person raise exception
@ -219,10 +219,10 @@ class DocType:
# Validate properties before merging
if merge:
if not frappe.conn.exists("Account", new):
if not frappe.db.exists("Account", new):
throw(_("Account ") + new +_(" does not exists"))
val = list(frappe.conn.get_value("Account", new_account,
val = list(frappe.db.get_value("Account", new_account,
["group_or_ledger", "debit_or_credit", "is_pl_account", "company"]))
if val != [self.doc.group_or_ledger, self.doc.debit_or_credit, self.doc.is_pl_account, self.doc.company]:
@ -234,7 +234,7 @@ class DocType:
def after_rename(self, old, new, merge=False):
if not merge:
frappe.conn.set_value("Account", new, "account_name",
frappe.db.set_value("Account", new, "account_name",
" - ".join(new.split(" - ")[:-1]))
else:
from frappe.utils.nestedset import rebuild_tree
@ -243,13 +243,13 @@ class DocType:
def get_master_name(doctype, txt, searchfield, start, page_len, filters):
conditions = (" and company='%s'"% filters["company"]) if doctype == "Warehouse" else ""
return frappe.conn.sql("""select name from `tab%s` where %s like %s %s
return frappe.db.sql("""select name from `tab%s` where %s like %s %s
order by name limit %s, %s""" %
(filters["master_type"], searchfield, "%s", conditions, "%s", "%s"),
("%%%s%%" % txt, start, page_len), as_list=1)
def get_parent_account(doctype, txt, searchfield, start, page_len, filters):
return frappe.conn.sql("""select name from tabAccount
return frappe.db.sql("""select name from tabAccount
where group_or_ledger = 'Group' and docstatus != 2 and company = %s
and %s like %s order by name limit %s, %s""" %
("%s", searchfield, "%s", "%s", "%s"),

View File

@ -13,15 +13,15 @@ class DocType:
self.doc, self.doclist = d, dl
def on_update(self):
frappe.conn.set_default("auto_accounting_for_stock", self.doc.auto_accounting_for_stock)
frappe.db.set_default("auto_accounting_for_stock", self.doc.auto_accounting_for_stock)
if cint(self.doc.auto_accounting_for_stock):
# set default perpetual account in company
for company in frappe.conn.sql("select name from tabCompany"):
for company in frappe.db.sql("select name from tabCompany"):
frappe.bean("Company", company[0]).save()
# Create account head for warehouses
warehouse_list = frappe.conn.sql("select name, company from tabWarehouse", as_dict=1)
warehouse_list = frappe.db.sql("select name, company from tabWarehouse", as_dict=1)
warehouse_with_no_company = [d.name for d in warehouse_list if not d.company]
if warehouse_with_no_company:
frappe.throw(_("Company is missing in following warehouses") + ": \n" +

View File

@ -22,7 +22,7 @@ class DocType:
msgprint("Bank Account, From Date and To Date are Mandatory")
return
dl = frappe.conn.sql("select t1.name, t1.cheque_no, t1.cheque_date, t2.debit, t2.credit, t1.posting_date, t2.against_account from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 where t2.parent = t1.name and t2.account = %s and (clearance_date is null or clearance_date = '0000-00-00' or clearance_date = '') and t1.posting_date >= %s and t1.posting_date <= %s and t1.docstatus=1", (self.doc.bank_account, self.doc.from_date, self.doc.to_date))
dl = frappe.db.sql("select t1.name, t1.cheque_no, t1.cheque_date, t2.debit, t2.credit, t1.posting_date, t2.against_account from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 where t2.parent = t1.name and t2.account = %s and (clearance_date is null or clearance_date = '0000-00-00' or clearance_date = '') and t1.posting_date >= %s and t1.posting_date <= %s and t1.docstatus=1", (self.doc.bank_account, self.doc.from_date, self.doc.to_date))
self.doclist = self.doc.clear_table(self.doclist, 'entries')
self.doc.total_amount = 0.0
@ -46,7 +46,7 @@ class DocType:
msgprint("Clearance Date can not be before Cheque Date (Row #%s)" %
d.idx, raise_exception=1)
frappe.conn.sql("""update `tabJournal Voucher`
frappe.db.sql("""update `tabJournal Voucher`
set clearance_date = %s, modified = %s where name=%s""",
(d.clearance_date, nowdate(), d.voucher_id))
vouchers.append(d.voucher_id)

View File

@ -16,7 +16,7 @@ class DocType:
for d in getlist(self.doclist, 'invoice_details'):
if d.invoice_no:
inv = frappe.conn.sql("""select c_form_applicable, c_form_no from
inv = frappe.db.sql("""select c_form_applicable, c_form_no from
`tabSales Invoice` where name = %s and docstatus = 1""", d.invoice_no)
if not inv:
@ -42,17 +42,17 @@ class DocType:
def before_cancel(self):
# remove cform reference
frappe.conn.sql("""update `tabSales Invoice` set c_form_no=null
frappe.db.sql("""update `tabSales Invoice` set c_form_no=null
where c_form_no=%s""", self.doc.name)
def set_cform_in_sales_invoices(self):
inv = [d.invoice_no for d in getlist(self.doclist, 'invoice_details')]
if inv:
frappe.conn.sql("""update `tabSales Invoice` set c_form_no=%s, modified=%s
frappe.db.sql("""update `tabSales Invoice` set c_form_no=%s, modified=%s
where name in (%s)""" % ('%s', '%s', ', '.join(['%s'] * len(inv))),
tuple([self.doc.name, self.doc.modified] + inv))
frappe.conn.sql("""update `tabSales Invoice` set c_form_no = null, modified = %s
frappe.db.sql("""update `tabSales Invoice` set c_form_no = null, modified = %s
where name not in (%s) and ifnull(c_form_no, '') = %s""" %
('%s', ', '.join(['%s']*len(inv)), '%s'),
tuple([self.doc.modified] + inv + [self.doc.name]))
@ -61,12 +61,12 @@ class DocType:
def set_total_invoiced_amount(self):
total = sum([flt(d.grand_total) for d in getlist(self.doclist, 'invoice_details')])
frappe.conn.set(self.doc, 'total_invoiced_amount', total)
frappe.db.set(self.doc, 'total_invoiced_amount', total)
def get_invoice_details(self, invoice_no):
""" Pull details from invoices for referrence """
inv = frappe.conn.sql("""select posting_date, territory, net_total, grand_total
inv = frappe.db.sql("""select posting_date, territory, net_total, grand_total
from `tabSales Invoice` where name = %s""", invoice_no)
return {
'invoice_date' : inv and getdate(inv[0][0]).strftime('%Y-%m-%d') or '',
@ -79,7 +79,7 @@ def get_invoice_nos(doctype, txt, searchfield, start, page_len, filters):
from erpnext.utilities import build_filter_conditions
conditions, filter_values = build_filter_conditions(filters)
return frappe.conn.sql("""select name from `tabSales Invoice` where docstatus = 1
return frappe.db.sql("""select name from `tabSales Invoice` where docstatus = 1
and c_form_applicable = 'Yes' and ifnull(c_form_no, '') = '' %s
and %s like %s order by name limit %s, %s""" %
(conditions, searchfield, "%s", "%s", "%s"),

View File

@ -14,7 +14,7 @@ class DocType(DocTypeNestedSet):
self.nsm_parent_field = 'parent_cost_center'
def autoname(self):
company_abbr = frappe.conn.sql("select abbr from tabCompany where name=%s",
company_abbr = frappe.db.sql("select abbr from tabCompany where name=%s",
self.doc.company)[0][0]
self.doc.name = self.doc.cost_center_name.strip() + ' - ' + company_abbr
@ -46,10 +46,10 @@ class DocType(DocTypeNestedSet):
return 1
def check_gle_exists(self):
return frappe.conn.get_value("GL Entry", {"cost_center": self.doc.name})
return frappe.db.get_value("GL Entry", {"cost_center": self.doc.name})
def check_if_child_exists(self):
return frappe.conn.sql("select name from `tabCost Center` where \
return frappe.db.sql("select name from `tabCost Center` where \
parent_cost_center = %s and docstatus != 2", self.doc.name)
def validate_budget_details(self):
@ -67,7 +67,7 @@ class DocType(DocTypeNestedSet):
"""
Cost Center name must be unique
"""
if (self.doc.fields.get("__islocal") or not self.doc.name) and frappe.conn.sql("select name from `tabCost Center` where cost_center_name = %s and company=%s", (self.doc.cost_center_name, self.doc.company)):
if (self.doc.fields.get("__islocal") or not self.doc.name) and frappe.db.sql("select name from `tabCost Center` where cost_center_name = %s and company=%s", (self.doc.cost_center_name, self.doc.company)):
msgprint("Cost Center Name already exists, please rename", raise_exception=1)
self.validate_mandatory()
@ -85,7 +85,7 @@ class DocType(DocTypeNestedSet):
def after_rename(self, olddn, newdn, merge=False):
if not merge:
frappe.conn.set_value("Cost Center", newdn, "cost_center_name",
frappe.db.set_value("Cost Center", newdn, "cost_center_name",
" - ".join(newdn.split(" - ")[:-1]))
else:
super(DocType, self).after_rename(olddn, newdn, merge)

View File

@ -11,7 +11,7 @@ class DocType:
self.doc, self.doclist = d, dl
def set_as_default(self):
frappe.conn.set_value("Global Defaults", None, "current_fiscal_year", self.doc.name)
frappe.db.set_value("Global Defaults", None, "current_fiscal_year", self.doc.name)
frappe.get_obj("Global Defaults").on_update()
# clear cache
@ -21,7 +21,7 @@ class DocType:
Please refresh your browser for the change to take effect."""))
def validate(self):
year_start_end_dates = frappe.conn.sql("""select year_start_date, year_end_date
year_start_end_dates = frappe.db.sql("""select year_start_date, year_end_date
from `tabFiscal Year` where name=%s""", (self.doc.name))
if year_start_end_dates:
@ -36,7 +36,7 @@ class DocType:
if (getdate(self.doc.year_end_date) - getdate(self.doc.year_start_date)).days > 366:
frappe.throw(_("Year Start Date and Year End Date are not within Fiscal Year."))
year_start_end_dates = frappe.conn.sql("""select name, year_start_date, year_end_date
year_start_end_dates = frappe.db.sql("""select name, year_start_date, year_end_date
from `tabFiscal Year` where name!=%s""", (self.doc.name))
for fiscal_year, ysd, yed in year_start_end_dates:

View File

@ -42,7 +42,7 @@ class DocType:
self.doc.account)
def pl_must_have_cost_center(self):
if frappe.conn.get_value("Account", self.doc.account, "is_pl_account") == "Yes":
if frappe.db.get_value("Account", self.doc.account, "is_pl_account") == "Yes":
if not self.doc.cost_center and self.doc.voucher_type != 'Period Closing Voucher':
frappe.throw(_("Cost Center must be specified for PL Account: ") +
self.doc.account)
@ -55,13 +55,13 @@ class DocType:
def check_pl_account(self):
if self.doc.is_opening=='Yes' and \
frappe.conn.get_value("Account", self.doc.account, "is_pl_account") == "Yes":
frappe.db.get_value("Account", self.doc.account, "is_pl_account") == "Yes":
frappe.throw(_("For opening balance entry account can not be a PL account"))
def validate_account_details(self, adv_adj):
"""Account must be ledger, active and not freezed"""
ret = frappe.conn.sql("""select group_or_ledger, docstatus, company
ret = frappe.db.sql("""select group_or_ledger, docstatus, company
from tabAccount where name=%s""", self.doc.account, as_dict=1)[0]
if ret.group_or_ledger=='Group':
@ -80,7 +80,7 @@ class DocType:
def _get_cost_center_company():
if not self.cost_center_company.get(self.doc.cost_center):
self.cost_center_company[self.doc.cost_center] = frappe.conn.get_value(
self.cost_center_company[self.doc.cost_center] = frappe.db.get_value(
"Cost Center", self.doc.cost_center, "company")
return self.cost_center_company[self.doc.cost_center]
@ -91,10 +91,10 @@ class DocType:
def check_negative_balance(account, adv_adj=False):
if not adv_adj and account:
account_details = frappe.conn.get_value("Account", account,
account_details = frappe.db.get_value("Account", account,
["allow_negative_balance", "debit_or_credit"], as_dict=True)
if not account_details["allow_negative_balance"]:
balance = frappe.conn.sql("""select sum(debit) - sum(credit) from `tabGL Entry`
balance = frappe.db.sql("""select sum(debit) - sum(credit) from `tabGL Entry`
where account = %s""", account)
balance = account_details["debit_or_credit"] == "Debit" and \
flt(balance[0][0]) or -1*flt(balance[0][0])
@ -108,9 +108,9 @@ def check_freezing_date(posting_date, adv_adj=False):
except authorized person
"""
if not adv_adj:
acc_frozen_upto = frappe.conn.get_value('Accounts Settings', None, 'acc_frozen_upto')
acc_frozen_upto = frappe.db.get_value('Accounts Settings', None, 'acc_frozen_upto')
if acc_frozen_upto:
bde_auth_role = frappe.conn.get_value( 'Accounts Settings', None,'bde_auth_role')
bde_auth_role = frappe.db.get_value( 'Accounts Settings', None,'bde_auth_role')
if getdate(posting_date) <= getdate(acc_frozen_upto) \
and not bde_auth_role in frappe.user.get_roles():
frappe.throw(_("You are not authorized to do/modify back dated entries before ")
@ -118,7 +118,7 @@ def check_freezing_date(posting_date, adv_adj=False):
def update_outstanding_amt(account, against_voucher_type, against_voucher, on_cancel=False):
# get final outstanding amt
bal = flt(frappe.conn.sql("""select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
bal = flt(frappe.db.sql("""select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
from `tabGL Entry`
where against_voucher_type=%s and against_voucher=%s and account = %s""",
(against_voucher_type, against_voucher, account))[0][0] or 0.0)
@ -126,7 +126,7 @@ def update_outstanding_amt(account, against_voucher_type, against_voucher, on_ca
if against_voucher_type == 'Purchase Invoice':
bal = -bal
elif against_voucher_type == "Journal Voucher":
against_voucher_amount = flt(frappe.conn.sql("""
against_voucher_amount = flt(frappe.db.sql("""
select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
from `tabGL Entry` where voucher_type = 'Journal Voucher' and voucher_no = %s
and account = %s and ifnull(against_voucher, '') = ''""",
@ -143,13 +143,13 @@ def update_outstanding_amt(account, against_voucher_type, against_voucher, on_ca
# Update outstanding amt on against voucher
if against_voucher_type in ["Sales Invoice", "Purchase Invoice"]:
frappe.conn.sql("update `tab%s` set outstanding_amount=%s where name='%s'" %
frappe.db.sql("update `tab%s` set outstanding_amount=%s where name='%s'" %
(against_voucher_type, bal, against_voucher))
def validate_frozen_account(account, adv_adj=None):
frozen_account = frappe.conn.get_value("Account", account, "freeze_account")
frozen_account = frappe.db.get_value("Account", account, "freeze_account")
if frozen_account == 'Yes' and not adv_adj:
frozen_accounts_modifier = frappe.conn.get_value( 'Accounts Settings', None,
frozen_accounts_modifier = frappe.db.get_value( 'Accounts Settings', None,
'frozen_accounts_modifier')
if not frozen_accounts_modifier:

View File

@ -75,7 +75,7 @@ class DocType(AccountsController):
for d in getlist(self.doclist,'entries'):
if not d.is_advance and not d.against_voucher and \
not d.against_invoice and not d.against_jv:
master_type = frappe.conn.get_value("Account", d.account, "master_type")
master_type = frappe.db.get_value("Account", d.account, "master_type")
if (master_type == 'Customer' and flt(d.credit) > 0) or \
(master_type == 'Supplier' and flt(d.debit) > 0):
msgprint("Message: Please check Is Advance as 'Yes' against \
@ -87,7 +87,7 @@ class DocType(AccountsController):
if d.against_jv == self.doc.name:
msgprint("You can not enter current voucher in 'Against JV' column",
raise_exception=1)
elif not frappe.conn.sql("""select name from `tabJournal Voucher Detail`
elif not frappe.db.sql("""select name from `tabJournal Voucher Detail`
where account = '%s' and docstatus = 1 and parent = '%s'""" %
(d.account, d.against_jv)):
msgprint("Against JV: %s is not valid." % d.against_jv, raise_exception=1)
@ -125,12 +125,12 @@ class DocType(AccountsController):
for d in getlist(self.doclist, 'entries'):
if d.against_invoice and d.credit:
currency = frappe.conn.get_value("Sales Invoice", d.against_invoice, "currency")
currency = frappe.db.get_value("Sales Invoice", d.against_invoice, "currency")
r.append('%s %s against Invoice: %s' %
(cstr(currency), fmt_money(flt(d.credit)), d.against_invoice))
if d.against_voucher and d.debit:
bill_no = frappe.conn.sql("""select bill_no, bill_date, currency
bill_no = frappe.db.sql("""select bill_no, bill_date, currency
from `tabPurchase Invoice` where name=%s""", d.against_voucher)
if bill_no and bill_no[0][0] and bill_no[0][0].lower().strip() \
not in ['na', 'not applicable', 'none']:
@ -153,7 +153,7 @@ class DocType(AccountsController):
# check account type whether supplier or customer
exists = False
for d in getlist(self.doclist, 'entries'):
account_type = frappe.conn.get_value("Account", d.account, "account_type")
account_type = frappe.db.get_value("Account", d.account, "account_type")
if account_type in ["Supplier", "Customer"]:
exists = True
break
@ -166,12 +166,12 @@ class DocType(AccountsController):
def set_print_format_fields(self):
for d in getlist(self.doclist, 'entries'):
account_type, master_type = frappe.conn.get_value("Account", d.account,
account_type, master_type = frappe.db.get_value("Account", d.account,
["account_type", "master_type"])
if master_type in ['Supplier', 'Customer']:
if not self.doc.pay_to_recd_from:
self.doc.pay_to_recd_from = frappe.conn.get_value(master_type,
self.doc.pay_to_recd_from = frappe.db.get_value(master_type,
' - '.join(d.account.split(' - ')[:-1]),
master_type == 'Customer' and 'customer_name' or 'supplier_name')
@ -190,7 +190,7 @@ class DocType(AccountsController):
if date_diff <= 0: return
# Get List of Customer Account
acc_list = filter(lambda d: frappe.conn.get_value("Account", d.account,
acc_list = filter(lambda d: frappe.db.get_value("Account", d.account,
"master_type")=='Customer', getlist(self.doclist,'entries'))
for d in acc_list:
@ -202,11 +202,11 @@ class DocType(AccountsController):
def get_credit_days_for(self, ac):
if not self.credit_days_for.has_key(ac):
self.credit_days_for[ac] = cint(frappe.conn.get_value("Account", ac, "credit_days"))
self.credit_days_for[ac] = cint(frappe.db.get_value("Account", ac, "credit_days"))
if not self.credit_days_for[ac]:
if self.credit_days_global==-1:
self.credit_days_global = cint(frappe.conn.get_value("Company",
self.credit_days_global = cint(frappe.db.get_value("Company",
self.doc.company, "credit_days"))
return self.credit_days_global
@ -218,7 +218,7 @@ class DocType(AccountsController):
self.is_approving_authority = 0
# Fetch credit controller role
approving_authority = frappe.conn.get_value("Global Defaults", None,
approving_authority = frappe.db.get_value("Global Defaults", None,
"credit_controller")
# Check logged-in user is authorized
@ -229,12 +229,12 @@ class DocType(AccountsController):
def check_account_against_entries(self):
for d in self.doclist.get({"parentfield": "entries"}):
if d.against_invoice and frappe.conn.get_value("Sales Invoice",
if d.against_invoice and frappe.db.get_value("Sales Invoice",
d.against_invoice, "debit_to") != d.account:
frappe.throw(_("Row #") + cstr(d.idx) + ": " +
_("Account is not matching with Debit To account of Sales Invoice"))
if d.against_voucher and frappe.conn.get_value("Purchase Invoice",
if d.against_voucher and frappe.db.get_value("Purchase Invoice",
d.against_voucher, "credit_to") != d.account:
frappe.throw(_("Row #") + cstr(d.idx) + ": " +
_("Account is not matching with Credit To account of Purchase Invoice"))
@ -267,7 +267,7 @@ class DocType(AccountsController):
def check_credit_limit(self):
for d in self.doclist.get({"parentfield": "entries"}):
master_type, master_name = frappe.conn.get_value("Account", d.account,
master_type, master_name = frappe.db.get_value("Account", d.account,
["master_type", "master_name"])
if master_type == "Customer" and master_name:
super(DocType, self).check_credit_limit(d.account)
@ -328,18 +328,18 @@ class DocType(AccountsController):
cond = (flt(self.doc.write_off_amount) > 0) and \
' and outstanding_amount <= '+ self.doc.write_off_amount or ''
if self.doc.write_off_based_on == 'Accounts Receivable':
return frappe.conn.sql("""select name, debit_to, outstanding_amount
return frappe.db.sql("""select name, debit_to, outstanding_amount
from `tabSales Invoice` where docstatus = 1 and company = %s
and outstanding_amount > 0 %s""" % ('%s', cond), self.doc.company)
elif self.doc.write_off_based_on == 'Accounts Payable':
return frappe.conn.sql("""select name, credit_to, outstanding_amount
return frappe.db.sql("""select name, credit_to, outstanding_amount
from `tabPurchase Invoice` where docstatus = 1 and company = %s
and outstanding_amount > 0 %s""" % ('%s', cond), self.doc.company)
@frappe.whitelist()
def get_default_bank_cash_account(company, voucher_type):
from erpnext.accounts.utils import get_balance_on
account = frappe.conn.get_value("Company", company,
account = frappe.db.get_value("Company", company,
voucher_type=="Bank Voucher" and "default_bank_account" or "default_cash_account")
if account:
return {
@ -412,27 +412,27 @@ def get_payment_entry(doc):
def get_opening_accounts(company):
"""get all balance sheet accounts for opening entry"""
from erpnext.accounts.utils import get_balance_on
accounts = frappe.conn.sql_list("""select name from tabAccount
accounts = frappe.db.sql_list("""select name from tabAccount
where group_or_ledger='Ledger' and is_pl_account='No' and company=%s""", company)
return [{"account": a, "balance": get_balance_on(a)} for a in accounts]
def get_against_purchase_invoice(doctype, txt, searchfield, start, page_len, filters):
return frappe.conn.sql("""select name, credit_to, outstanding_amount, bill_no, bill_date
return frappe.db.sql("""select name, credit_to, outstanding_amount, bill_no, bill_date
from `tabPurchase Invoice` where credit_to = %s and docstatus = 1
and outstanding_amount > 0 and %s like %s order by name desc limit %s, %s""" %
("%s", searchfield, "%s", "%s", "%s"),
(filters["account"], "%%%s%%" % txt, start, page_len))
def get_against_sales_invoice(doctype, txt, searchfield, start, page_len, filters):
return frappe.conn.sql("""select name, debit_to, outstanding_amount
return frappe.db.sql("""select name, debit_to, outstanding_amount
from `tabSales Invoice` where debit_to = %s and docstatus = 1
and outstanding_amount > 0 and `%s` like %s order by name desc limit %s, %s""" %
("%s", searchfield, "%s", "%s", "%s"),
(filters["account"], "%%%s%%" % txt, start, page_len))
def get_against_jv(doctype, txt, searchfield, start, page_len, filters):
return frappe.conn.sql("""select jv.name, jv.posting_date, jv.user_remark
return frappe.db.sql("""select jv.name, jv.posting_date, jv.user_remark
from `tabJournal Voucher` jv, `tabJournal Voucher Detail` jv_detail
where jv_detail.parent = jv.name and jv_detail.account = %s and jv.docstatus = 1
and jv.%s like %s order by jv.name desc limit %s, %s""" %
@ -443,7 +443,7 @@ def get_against_jv(doctype, txt, searchfield, start, page_len, filters):
def get_outstanding(args):
args = eval(args)
if args.get("doctype") == "Journal Voucher" and args.get("account"):
against_jv_amount = frappe.conn.sql("""
against_jv_amount = frappe.db.sql("""
select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
from `tabJournal Voucher Detail` where parent=%s and account=%s
and ifnull(against_invoice, '')='' and ifnull(against_voucher, '')=''
@ -457,11 +457,11 @@ def get_outstanding(args):
elif args.get("doctype") == "Sales Invoice":
return {
"credit": flt(frappe.conn.get_value("Sales Invoice", args["docname"],
"credit": flt(frappe.db.get_value("Sales Invoice", args["docname"],
"outstanding_amount"))
}
elif args.get("doctype") == "Purchase Invoice":
return {
"debit": flt(frappe.conn.get_value("Purchase Invoice", args["docname"],
"debit": flt(frappe.db.get_value("Purchase Invoice", args["docname"],
"outstanding_amount"))
}

View File

@ -13,7 +13,7 @@ class TestJournalVoucher(unittest.TestCase):
jv_invoice.insert()
jv_invoice.submit()
self.assertTrue(not frappe.conn.sql("""select name from `tabJournal Voucher Detail`
self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_jv=%s""", jv_invoice.doc.name))
jv_payment = frappe.bean(copy=test_records[0])
@ -21,16 +21,16 @@ class TestJournalVoucher(unittest.TestCase):
jv_payment.insert()
jv_payment.submit()
self.assertTrue(frappe.conn.sql("""select name from `tabJournal Voucher Detail`
self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_jv=%s""", jv_invoice.doc.name))
self.assertTrue(frappe.conn.sql("""select name from `tabJournal Voucher Detail`
self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_jv=%s and credit=400""", jv_invoice.doc.name))
# cancel jv_invoice
jv_invoice.cancel()
self.assertTrue(not frappe.conn.sql("""select name from `tabJournal Voucher Detail`
self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_jv=%s""", jv_invoice.doc.name))
def test_jv_against_stock_account(self):
@ -47,7 +47,7 @@ class TestJournalVoucher(unittest.TestCase):
set_perpetual_inventory(0)
def test_monthly_budget_crossed_ignore(self):
frappe.conn.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
self.clear_account_balance()
jv = frappe.bean(copy=test_records[0])
@ -57,12 +57,12 @@ class TestJournalVoucher(unittest.TestCase):
jv.doclist[1].credit = 20000.0
jv.insert()
jv.submit()
self.assertTrue(frappe.conn.get_value("GL Entry",
self.assertTrue(frappe.db.get_value("GL Entry",
{"voucher_type": "Journal Voucher", "voucher_no": jv.doc.name}))
def test_monthly_budget_crossed_stop(self):
from erpnext.accounts.utils import BudgetError
frappe.conn.set_value("Company", "_Test Company", "monthly_bgt_flag", "Stop")
frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Stop")
self.clear_account_balance()
jv = frappe.bean(copy=test_records[0])
@ -74,14 +74,14 @@ class TestJournalVoucher(unittest.TestCase):
self.assertRaises(BudgetError, jv.submit)
frappe.conn.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
def test_yearly_budget_crossed_stop(self):
from erpnext.accounts.utils import BudgetError
self.clear_account_balance()
self.test_monthly_budget_crossed_ignore()
frappe.conn.set_value("Company", "_Test Company", "yearly_bgt_flag", "Stop")
frappe.db.set_value("Company", "_Test Company", "yearly_bgt_flag", "Stop")
jv = frappe.bean(copy=test_records[0])
jv.doc.posting_date = "2013-08-12"
@ -93,11 +93,11 @@ class TestJournalVoucher(unittest.TestCase):
self.assertRaises(BudgetError, jv.submit)
frappe.conn.set_value("Company", "_Test Company", "yearly_bgt_flag", "Ignore")
frappe.db.set_value("Company", "_Test Company", "yearly_bgt_flag", "Ignore")
def test_monthly_budget_on_cancellation(self):
from erpnext.accounts.utils import BudgetError
frappe.conn.set_value("Company", "_Test Company", "monthly_bgt_flag", "Stop")
frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Stop")
self.clear_account_balance()
jv = frappe.bean(copy=test_records[0])
@ -107,7 +107,7 @@ class TestJournalVoucher(unittest.TestCase):
jv.doclist[2].debit = 30000.0
jv.submit()
self.assertTrue(frappe.conn.get_value("GL Entry",
self.assertTrue(frappe.db.get_value("GL Entry",
{"voucher_type": "Journal Voucher", "voucher_no": jv.doc.name}))
jv1 = frappe.bean(copy=test_records[0])
@ -117,15 +117,15 @@ class TestJournalVoucher(unittest.TestCase):
jv1.doclist[1].credit = 40000.0
jv1.submit()
self.assertTrue(frappe.conn.get_value("GL Entry",
self.assertTrue(frappe.db.get_value("GL Entry",
{"voucher_type": "Journal Voucher", "voucher_no": jv1.doc.name}))
self.assertRaises(BudgetError, jv.cancel)
frappe.conn.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
def clear_account_balance(self):
frappe.conn.sql("""delete from `tabGL Entry`""")
frappe.db.sql("""delete from `tabGL Entry`""")
test_records = [

View File

@ -33,7 +33,7 @@ class DocType:
ret['company'] = get_companies()
#--- to get fiscal year and start_date of that fiscal year -----
res = frappe.conn.sql("select name, year_start_date from `tabFiscal Year`")
res = frappe.db.sql("select name, year_start_date from `tabFiscal Year`")
ret['fiscal_year'] = [r[0] for r in res]
ret['start_dates'] = {}
for r in res:
@ -41,7 +41,7 @@ class DocType:
#--- from month and to month (for MIS - Comparison Report) -------
month_list = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
fiscal_start_month = frappe.conn.sql("select MONTH(year_start_date) from `tabFiscal Year` where name = %s",(frappe.defaults.get_global_default("fiscal_year")))
fiscal_start_month = frappe.db.sql("select MONTH(year_start_date) from `tabFiscal Year` where name = %s",(frappe.defaults.get_global_default("fiscal_year")))
fiscal_start_month = fiscal_start_month and fiscal_start_month[0][0] or 1
mon = ['']
for i in range(fiscal_start_month,13): mon.append(month_list[i-1])
@ -76,7 +76,7 @@ class DocType:
return self.return_data
def get_children(self, parent_account, level, pl, company, fy):
cl = frappe.conn.sql("select distinct account_name, name, debit_or_credit, lft, rgt from `tabAccount` where ifnull(parent_account, '') = %s and ifnull(is_pl_account, 'No')=%s and company=%s and docstatus != 2 order by name asc", (parent_account, pl, company))
cl = frappe.db.sql("select distinct account_name, name, debit_or_credit, lft, rgt from `tabAccount` where ifnull(parent_account, '') = %s and ifnull(is_pl_account, 'No')=%s and company=%s and docstatus != 2 order by name asc", (parent_account, pl, company))
level0_diff = [0 for p in self.period_list]
if pl=='Yes' and level==0: # switch for income & expenses
cl = [c for c in cl]
@ -123,7 +123,7 @@ class DocType:
self.return_data.append([4, 'Total '+c[0]] + totals)
def define_periods(self, year, period):
ysd = frappe.conn.sql("select year_start_date from `tabFiscal Year` where name=%s", year)
ysd = frappe.db.sql("select year_start_date from `tabFiscal Year` where name=%s", year)
ysd = ysd and ysd[0][0] or ''
self.ysd = ysd

View File

@ -16,17 +16,17 @@ class DocType:
def set_account_type(self):
self.doc.account_type = self.doc.account and \
frappe.conn.get_value("Account", self.doc.account, "debit_or_credit").lower() or ""
frappe.db.get_value("Account", self.doc.account, "debit_or_credit").lower() or ""
def get_voucher_details(self):
total_amount = frappe.conn.sql("""select sum(%s) from `tabGL Entry`
total_amount = frappe.db.sql("""select sum(%s) from `tabGL Entry`
where voucher_type = %s and voucher_no = %s
and account = %s""" %
(self.doc.account_type, '%s', '%s', '%s'),
(self.doc.voucher_type, self.doc.voucher_no, self.doc.account))
total_amount = total_amount and flt(total_amount[0][0]) or 0
reconciled_payment = frappe.conn.sql("""
reconciled_payment = frappe.db.sql("""
select sum(ifnull(%s, 0)) - sum(ifnull(%s, 0)) from `tabGL Entry` where
against_voucher = %s and voucher_no != %s
and account = %s""" %
@ -63,7 +63,7 @@ class DocType:
cond += self.doc.amt_less_than and \
' and t2.' + dc+' <= ' + self.doc.amt_less_than or ''
gle = frappe.conn.sql("""
gle = frappe.db.sql("""
select t1.name as voucher_no, t1.posting_date, t1.total_debit as total_amt,
sum(ifnull(t2.credit, 0)) - sum(ifnull(t2.debit, 0)) as amt_due, t1.remark,
t2.against_account, t2.name as voucher_detail_no
@ -99,7 +99,7 @@ class DocType:
2. split into multiple rows if partially adjusted, assign against voucher
3. submit payment voucher
"""
if not self.doc.voucher_no or not frappe.conn.sql("""select name from `tab%s`
if not self.doc.voucher_no or not frappe.db.sql("""select name from `tab%s`
where name = %s""" % (self.doc.voucher_type, '%s'), self.doc.voucher_no):
msgprint("Please select valid Voucher No to proceed", raise_exception=1)
@ -130,7 +130,7 @@ class DocType:
def gl_entry_details(doctype, txt, searchfield, start, page_len, filters):
from erpnext.controllers.queries import get_match_cond
return frappe.conn.sql("""select gle.voucher_no, gle.posting_date,
return frappe.db.sql("""select gle.voucher_no, gle.posting_date,
gle.%(account_type)s from `tabGL Entry` gle
where gle.account = '%(acc)s'
and gle.voucher_type = '%(dt)s'

View File

@ -21,11 +21,11 @@ class DocType(AccountsController):
self.make_gl_entries()
def on_cancel(self):
frappe.conn.sql("""delete from `tabGL Entry`
frappe.db.sql("""delete from `tabGL Entry`
where voucher_type = 'Period Closing Voucher' and voucher_no=%s""", self.doc.name)
def validate_account_head(self):
debit_or_credit, is_pl_account = frappe.conn.get_value("Account",
debit_or_credit, is_pl_account = frappe.db.get_value("Account",
self.doc.closing_account_head, ["debit_or_credit", "is_pl_account"])
if debit_or_credit != 'Credit' or is_pl_account != 'No':
@ -36,7 +36,7 @@ class DocType(AccountsController):
from erpnext.accounts.utils import get_fiscal_year
self.year_start_date = get_fiscal_year(self.doc.posting_date, self.doc.fiscal_year)[1]
pce = frappe.conn.sql("""select name from `tabPeriod Closing Voucher`
pce = frappe.db.sql("""select name from `tabPeriod Closing Voucher`
where posting_date > %s and fiscal_year = %s and docstatus = 1""",
(self.doc.posting_date, self.doc.fiscal_year))
if pce and pce[0][0]:
@ -44,7 +44,7 @@ class DocType(AccountsController):
_("has been made after posting date") + ": " + self.doc.posting_date)
def validate_pl_balances(self):
income_bal = frappe.conn.sql("""
income_bal = frappe.db.sql("""
select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0))
from `tabGL Entry` t1, tabAccount t2
where t1.account = t2.name and t1.posting_date between %s and %s
@ -52,7 +52,7 @@ class DocType(AccountsController):
and t2.docstatus < 2 and t2.company = %s""",
(self.year_start_date, self.doc.posting_date, self.doc.company))
expense_bal = frappe.conn.sql("""
expense_bal = frappe.db.sql("""
select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0))
from `tabGL Entry` t1, tabAccount t2
where t1.account = t2.name and t1.posting_date between %s and %s
@ -68,7 +68,7 @@ class DocType(AccountsController):
def get_pl_balances(self):
"""Get balance for pl accounts"""
return frappe.conn.sql("""
return frappe.db.sql("""
select t1.account, sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) as balance
from `tabGL Entry` t1, `tabAccount` t2
where t1.account = t2.name and ifnull(t2.is_pl_account, 'No') = 'Yes'

View File

@ -9,7 +9,7 @@ import frappe
class TestPeriodClosingVoucher(unittest.TestCase):
def test_closing_entry(self):
# clear GL Entries
frappe.conn.sql("""delete from `tabGL Entry`""")
frappe.db.sql("""delete from `tabGL Entry`""")
from erpnext.accounts.doctype.journal_voucher.test_journal_voucher import test_records as jv_records
jv = frappe.bean(copy=jv_records[2])
@ -27,7 +27,7 @@ class TestPeriodClosingVoucher(unittest.TestCase):
pcv.insert()
pcv.submit()
gl_entries = frappe.conn.sql("""select account, debit, credit
gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Period Closing Voucher' and voucher_no=%s
order by account asc, debit asc""", pcv.doc.name, as_dict=1)

View File

@ -23,7 +23,7 @@ class DocType:
self.validate_all_link_fields()
def check_for_duplicate(self):
res = frappe.conn.sql("""select name, user from `tabPOS Setting`
res = frappe.db.sql("""select name, user from `tabPOS Setting`
where ifnull(user, '') = %s and name != %s and company = %s""",
(self.doc.user, self.doc.name, self.doc.company))
if res:
@ -46,14 +46,14 @@ class DocType:
for link_dt, dn_list in accounts.items():
for link_dn in dn_list:
if link_dn and not frappe.conn.exists({"doctype": link_dt,
if link_dn and not frappe.db.exists({"doctype": link_dt,
"company": self.doc.company, "name": link_dn}):
frappe.throw(link_dn +_(" does not belong to ") + self.doc.company)
def on_update(self):
frappe.defaults.clear_default("is_pos")
pos_view_users = frappe.conn.sql_list("""select user from `tabPOS Setting`""")
pos_view_users = frappe.db.sql_list("""select user from `tabPOS Setting`""")
for user in pos_view_users:
if user:
frappe.defaults.set_user_default("is_pos", 1, user)

View File

@ -73,7 +73,7 @@ class DocType(BuyingController):
def check_active_purchase_items(self):
for d in getlist(self.doclist, 'entries'):
if d.item_code: # extra condn coz item_code is not mandatory in PV
valid_item = frappe.conn.sql("select docstatus,is_purchase_item from tabItem where name = %s",d.item_code)
valid_item = frappe.db.sql("select docstatus,is_purchase_item from tabItem where name = %s",d.item_code)
if valid_item[0][0] == 2:
msgprint("Item : '%s' is Inactive, you can restore it from Trash" %(d.item_code))
raise Exception
@ -93,7 +93,7 @@ class DocType(BuyingController):
def validate_bill_no(self):
if self.doc.bill_no and self.doc.bill_no.lower().strip() \
not in ['na', 'not applicable', 'none']:
b_no = frappe.conn.sql("""select bill_no, name, ifnull(is_opening,'') from `tabPurchase Invoice`
b_no = frappe.db.sql("""select bill_no, name, ifnull(is_opening,'') from `tabPurchase Invoice`
where bill_no = %s and credit_to = %s and docstatus = 1 and name != %s""",
(self.doc.bill_no, self.doc.credit_to, self.doc.name))
if b_no and cstr(b_no[0][2]) == cstr(self.doc.is_opening):
@ -109,7 +109,7 @@ class DocType(BuyingController):
self.doc.remarks = "No Remarks"
def validate_credit_acc(self):
acc = frappe.conn.sql("select debit_or_credit, is_pl_account from tabAccount where name = %s",
acc = frappe.db.sql("select debit_or_credit, is_pl_account from tabAccount where name = %s",
self.doc.credit_to)
if not acc:
msgprint("Account: "+ self.doc.credit_to + "does not exist")
@ -125,7 +125,7 @@ class DocType(BuyingController):
# ------------------------------------------------------------
def check_for_acc_head_of_supplier(self):
if self.doc.supplier and self.doc.credit_to:
acc_head = frappe.conn.sql("select master_name from `tabAccount` where name = %s", self.doc.credit_to)
acc_head = frappe.db.sql("select master_name from `tabAccount` where name = %s", self.doc.credit_to)
if (acc_head and cstr(acc_head[0][0]) != cstr(self.doc.supplier)) or (not acc_head and (self.doc.credit_to != cstr(self.doc.supplier) + " - " + self.company_abbr)):
msgprint("Credit To: %s do not match with Supplier: %s for Company: %s.\n If both correctly entered, please select Master Type and Master Name in account master." %(self.doc.credit_to,self.doc.supplier,self.doc.company), raise_exception=1)
@ -137,7 +137,7 @@ class DocType(BuyingController):
for d in getlist(self.doclist,'entries'):
if d.purchase_order and not d.purchase_order in check_list and not d.purchase_receipt:
check_list.append(d.purhcase_order)
stopped = frappe.conn.sql("select name from `tabPurchase Order` where status = 'Stopped' and name = '%s'" % d.purchase_order)
stopped = frappe.db.sql("select name from `tabPurchase Order` where status = 'Stopped' and name = '%s'" % d.purchase_order)
if stopped:
msgprint("One cannot do any transaction against 'Purchase Order' : %s, it's status is 'Stopped'" % (d.purhcase_order))
raise Exception
@ -218,14 +218,14 @@ class DocType(BuyingController):
self.doc.against_expense_account = ",".join(against_accounts)
def po_required(self):
if frappe.conn.get_value("Buying Settings", None, "po_required") == 'Yes':
if frappe.db.get_value("Buying Settings", None, "po_required") == 'Yes':
for d in getlist(self.doclist,'entries'):
if not d.purchase_order:
msgprint("Purchse Order No. required against item %s"%d.item_code)
raise Exception
def pr_required(self):
if frappe.conn.get_value("Buying Settings", None, "pr_required") == 'Yes':
if frappe.db.get_value("Buying Settings", None, "pr_required") == 'Yes':
for d in getlist(self.doclist,'entries'):
if not d.purchase_receipt:
msgprint("Purchase Receipt No. required against item %s"%d.item_code)
@ -238,11 +238,11 @@ class DocType(BuyingController):
def check_prev_docstatus(self):
for d in getlist(self.doclist,'entries'):
if d.purchase_order:
submitted = frappe.conn.sql("select name from `tabPurchase Order` where docstatus = 1 and name = '%s'" % d.purchase_order)
submitted = frappe.db.sql("select name from `tabPurchase Order` where docstatus = 1 and name = '%s'" % d.purchase_order)
if not submitted:
frappe.throw("Purchase Order : "+ cstr(d.purchase_order) +" is not submitted")
if d.purchase_receipt:
submitted = frappe.conn.sql("select name from `tabPurchase Receipt` where docstatus = 1 and name = '%s'" % d.purchase_receipt)
submitted = frappe.db.sql("select name from `tabPurchase Receipt` where docstatus = 1 and name = '%s'" % d.purchase_receipt)
if not submitted:
frappe.throw("Purchase Receipt : "+ cstr(d.purchase_receipt) +" is not submitted")
@ -414,12 +414,12 @@ class DocType(BuyingController):
def update_raw_material_cost(self):
if self.sub_contracted_items:
for d in self.doclist.get({"parentfield": "entries"}):
rm_cost = frappe.conn.sql("""select raw_material_cost / quantity
rm_cost = frappe.db.sql("""select raw_material_cost / quantity
from `tabBOM` where item = %s and is_default = 1 and docstatus = 1
and is_active = 1 """, (d.item_code,))
rm_cost = rm_cost and flt(rm_cost[0][0]) or 0
d.conversion_factor = d.conversion_factor or flt(frappe.conn.get_value(
d.conversion_factor = d.conversion_factor or flt(frappe.db.get_value(
"UOM Conversion Detail", {"parent": d.item_code, "uom": d.uom},
"conversion_factor")) or 1
@ -432,7 +432,7 @@ def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
# expense account can be any Debit account,
# but can also be a Liability account with account_type='Expense Account' in special circumstances.
# Hence the first condition is an "OR"
return frappe.conn.sql("""select tabAccount.name from `tabAccount`
return frappe.db.sql("""select tabAccount.name from `tabAccount`
where (tabAccount.debit_or_credit="Debit"
or tabAccount.account_type = "Expense Account")
and tabAccount.group_or_ledger="Ledger"

View File

@ -36,7 +36,7 @@ class TestPurchaseInvoice(unittest.TestCase):
"_Test Account VAT - _TC": [156.25, 0],
"_Test Account Discount - _TC": [0, 168.03],
}
gl_entries = frappe.conn.sql("""select account, debit, credit from `tabGL Entry`
gl_entries = frappe.db.sql("""select account, debit, credit from `tabGL Entry`
where voucher_type = 'Purchase Invoice' and voucher_no = %s""", dl[0].name, as_dict=1)
for d in gl_entries:
self.assertEqual([d.debit, d.credit], expected_gl_entries.get(d.account))
@ -49,7 +49,7 @@ class TestPurchaseInvoice(unittest.TestCase):
pi.insert()
pi.submit()
gl_entries = frappe.conn.sql("""select account, debit, credit
gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Purchase Invoice' and voucher_no=%s
order by account asc""", pi.doc.name, as_dict=1)
self.assertTrue(gl_entries)
@ -81,7 +81,7 @@ class TestPurchaseInvoice(unittest.TestCase):
pi.insert()
pi.submit()
gl_entries = frappe.conn.sql("""select account, debit, credit
gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Purchase Invoice' and voucher_no=%s
order by account asc""", pi.doc.name, as_dict=1)
self.assertTrue(gl_entries)
@ -187,17 +187,17 @@ class TestPurchaseInvoice(unittest.TestCase):
pi.submit()
pi.load_from_db()
self.assertTrue(frappe.conn.sql("""select name from `tabJournal Voucher Detail`
self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_voucher=%s""", pi.doc.name))
self.assertTrue(frappe.conn.sql("""select name from `tabJournal Voucher Detail`
self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_voucher=%s and debit=300""", pi.doc.name))
self.assertEqual(pi.doc.outstanding_amount, 1212.30)
pi.cancel()
self.assertTrue(not frappe.conn.sql("""select name from `tabJournal Voucher Detail`
self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_voucher=%s""", pi.doc.name))
test_records = [

View File

@ -21,7 +21,7 @@ def get_items(price_list, sales_or_purchase, item=None, item_group=None):
condition += " and CONCAT(i.name, i.item_name) like %(name)s"
args["name"] = "%%%s%%" % item
return frappe.conn.sql("""select i.name, i.item_name, i.image,
return frappe.db.sql("""select i.name, i.item_name, i.image,
item_det.price_list_rate, item_det.currency
from `tabItem` i LEFT JOIN
(select item_code, price_list_rate, currency from
@ -34,12 +34,12 @@ def get_items(price_list, sales_or_purchase, item=None, item_group=None):
@frappe.whitelist()
def get_item_code(barcode_serial_no):
input_via = "serial_no"
item_code = frappe.conn.sql("""select name, item_code from `tabSerial No` where
item_code = frappe.db.sql("""select name, item_code from `tabSerial No` where
name=%s""", (barcode_serial_no), as_dict=1)
if not item_code:
input_via = "barcode"
item_code = frappe.conn.sql("""select name from `tabItem` where barcode=%s""",
item_code = frappe.db.sql("""select name from `tabItem` where barcode=%s""",
(barcode_serial_no), as_dict=1)
if item_code:
@ -49,4 +49,4 @@ def get_item_code(barcode_serial_no):
@frappe.whitelist()
def get_mode_of_payment():
return frappe.conn.sql("""select name from `tabMode of Payment`""", as_dict=1)
return frappe.db.sql("""select name from `tabMode of Payment`""", as_dict=1)

View File

@ -167,7 +167,7 @@ class DocType(SellingController):
def validate_time_logs_are_submitted(self):
for d in self.doclist.get({"doctype":"Sales Invoice Item"}):
if d.time_log_batch:
status = frappe.conn.get_value("Time Log Batch", d.time_log_batch, "status")
status = frappe.db.get_value("Time Log Batch", d.time_log_batch, "status")
if status!="Submitted":
frappe.msgprint(_("Time Log Batch status must be 'Submitted'") + ":" + d.time_log_batch,
raise_exception=True)
@ -202,7 +202,7 @@ class DocType(SellingController):
# fetch terms
if self.doc.tc_name and not self.doc.terms:
self.doc.terms = frappe.conn.get_value("Terms and Conditions", self.doc.tc_name, "terms")
self.doc.terms = frappe.db.get_value("Terms and Conditions", self.doc.tc_name, "terms")
# fetch charges
if self.doc.charge and not len(self.doclist.get({"parentfield": "other_charges"})):
@ -213,7 +213,7 @@ class DocType(SellingController):
"Sales Invoice Advance", "advance_adjustment_details", "credit")
def get_company_abbr(self):
return frappe.conn.sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0]
return frappe.db.sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0]
def update_against_document_in_jv(self):
"""
@ -246,7 +246,7 @@ class DocType(SellingController):
def validate_customer_account(self):
"""Validates Debit To Account and Customer Matches"""
if self.doc.customer and self.doc.debit_to and not cint(self.doc.is_pos):
acc_head = frappe.conn.sql("select master_name from `tabAccount` where name = %s and docstatus != 2", self.doc.debit_to)
acc_head = frappe.db.sql("select master_name from `tabAccount` where name = %s and docstatus != 2", self.doc.debit_to)
if (acc_head and cstr(acc_head[0][0]) != cstr(self.doc.customer)) or \
(not acc_head and (self.doc.debit_to != cstr(self.doc.customer) + " - " + self.get_company_abbr())):
@ -255,7 +255,7 @@ class DocType(SellingController):
def validate_debit_acc(self):
acc = frappe.conn.sql("select debit_or_credit, is_pl_account from tabAccount where name = '%s' and docstatus != 2" % self.doc.debit_to)
acc = frappe.db.sql("select debit_or_credit, is_pl_account from tabAccount where name = '%s' and docstatus != 2" % self.doc.debit_to)
if not acc:
msgprint("Account: "+ self.doc.debit_to + " does not exist")
raise Exception
@ -270,8 +270,8 @@ class DocType(SellingController):
def validate_fixed_asset_account(self):
"""Validate Fixed Asset Account and whether Income Account Entered Exists"""
for d in getlist(self.doclist,'entries'):
item = frappe.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 = frappe.conn.sql("select account_type from `tabAccount` where name = '%s' and docstatus != 2" % d.income_account)
item = frappe.db.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 = frappe.db.sql("select account_type from `tabAccount` where name = '%s' and docstatus != 2" % d.income_account)
if not acc:
msgprint("Account: "+d.income_account+" does not exist in the system", raise_exception=True)
elif item and item[0][1] == 'Yes' and not acc[0][0] == 'Fixed Asset Account':
@ -332,9 +332,9 @@ class DocType(SellingController):
"""check in manage account if sales order / delivery note required or not."""
dic = {'Sales Order':'so_required','Delivery Note':'dn_required'}
for i in dic:
if frappe.conn.get_value('Selling Settings', None, dic[i]) == 'Yes':
if frappe.db.get_value('Selling Settings', None, dic[i]) == 'Yes':
for d in getlist(self.doclist,'entries'):
if frappe.conn.get_value('Item', d.item_code, 'is_stock_item') == 'Yes' \
if frappe.db.get_value('Item', d.item_code, 'is_stock_item') == 'Yes' \
and not d.fields[i.lower().replace(' ','_')]:
msgprint("%s is mandatory for stock item which is not mentioed against item: %s"%(i,d.item_code), raise_exception=1)
@ -342,7 +342,7 @@ class DocType(SellingController):
def validate_proj_cust(self):
"""check for does customer belong to same project as entered.."""
if self.doc.project_name and self.doc.customer:
res = frappe.conn.sql("select name from `tabProject` where name = '%s' and (customer = '%s' or ifnull(customer,'')='')"%(self.doc.project_name, self.doc.customer))
res = frappe.db.sql("select name from `tabProject` where name = '%s' and (customer = '%s' or ifnull(customer,'')='')"%(self.doc.project_name, self.doc.customer))
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))
raise Exception
@ -377,28 +377,28 @@ class DocType(SellingController):
def validate_c_form(self):
""" 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:
frappe.conn.sql("""delete from `tabC-Form Invoice Detail` where invoice_no = %s
frappe.db.sql("""delete from `tabC-Form Invoice Detail` where invoice_no = %s
and parent = %s""", (self.doc.amended_from, self.doc.c_form_no))
frappe.conn.set(self.doc, 'c_form_no', '')
frappe.db.set(self.doc, 'c_form_no', '')
def update_current_stock(self):
for d in getlist(self.doclist, 'entries'):
if d.item_code and d.warehouse:
bin = frappe.conn.sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
bin = frappe.db.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
for d in getlist(self.doclist, 'packing_details'):
bin = frappe.conn.sql("select actual_qty, projected_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
bin = frappe.db.sql("select actual_qty, projected_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.projected_qty = bin and flt(bin[0]['projected_qty']) or 0
def get_warehouse(self):
w = frappe.conn.sql("select warehouse from `tabPOS Setting` where ifnull(user,'') = '%s' and company = '%s'" % (frappe.session['user'], self.doc.company))
w = frappe.db.sql("select warehouse from `tabPOS Setting` where ifnull(user,'') = '%s' and company = '%s'" % (frappe.session['user'], self.doc.company))
w = w and w[0][0] or ''
if not w:
ps = frappe.conn.sql("select name, warehouse from `tabPOS Setting` where ifnull(user,'') = '' and company = '%s'" % self.doc.company)
ps = frappe.db.sql("select name, warehouse from `tabPOS Setting` where ifnull(user,'') = '' and company = '%s'" % self.doc.company)
if not ps:
msgprint("To make POS entry, please create POS Setting from Accounts --> POS Setting page and refresh the system.", raise_exception=True)
elif not ps[0][1]:
@ -425,25 +425,25 @@ class DocType(SellingController):
if cint(self.doc.is_pos) == 1:
if flt(self.doc.paid_amount) == 0:
if self.doc.cash_bank_account:
frappe.conn.set(self.doc, 'paid_amount',
frappe.db.set(self.doc, 'paid_amount',
(flt(self.doc.grand_total) - flt(self.doc.write_off_amount)))
else:
# show message that the amount is not paid
frappe.conn.set(self.doc,'paid_amount',0)
frappe.db.set(self.doc,'paid_amount',0)
frappe.msgprint("Note: Payment Entry will not be created since 'Cash/Bank Account' was not specified.")
else:
frappe.conn.set(self.doc,'paid_amount',0)
frappe.db.set(self.doc,'paid_amount',0)
def check_prev_docstatus(self):
for d in getlist(self.doclist,'entries'):
if d.sales_order:
submitted = frappe.conn.sql("select name from `tabSales Order` where docstatus = 1 and name = '%s'" % d.sales_order)
submitted = frappe.db.sql("select name from `tabSales Order` where docstatus = 1 and name = '%s'" % d.sales_order)
if not submitted:
msgprint("Sales Order : "+ cstr(d.sales_order) +" is not submitted")
raise Exception , "Validation Error."
if d.delivery_note:
submitted = frappe.conn.sql("select name from `tabDelivery Note` where docstatus = 1 and name = '%s'" % d.delivery_note)
submitted = frappe.db.sql("select name from `tabDelivery Note` where docstatus = 1 and name = '%s'" % d.delivery_note)
if not submitted:
msgprint("Delivery Note : "+ cstr(d.delivery_note) +" is not submitted")
raise Exception , "Validation Error."
@ -451,11 +451,11 @@ class DocType(SellingController):
def update_stock_ledger(self):
sl_entries = []
for d in self.get_item_list():
if frappe.conn.get_value("Item", d.item_code, "is_stock_item") == "Yes" \
if frappe.db.get_value("Item", d.item_code, "is_stock_item") == "Yes" \
and d.warehouse:
sl_entries.append(self.get_sl_entries(d, {
"actual_qty": -1*flt(d.qty),
"stock_uom": frappe.conn.get_value("Item", d.item_code, "stock_uom")
"stock_uom": frappe.db.get_value("Item", d.item_code, "stock_uom")
}))
self.make_sl_entries(sl_entries)
@ -584,7 +584,7 @@ class DocType(SellingController):
def update_c_form(self):
"""Update amended id in C-form"""
if self.doc.c_form_no and self.doc.amended_from:
frappe.conn.sql("""update `tabC-Form Invoice Detail` set invoice_no = %s,
frappe.db.sql("""update `tabC-Form Invoice Detail` set invoice_no = %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))
@ -613,13 +613,13 @@ class DocType(SellingController):
def convert_to_recurring(self):
if self.doc.convert_into_recurring_invoice:
if not self.doc.recurring_id:
frappe.conn.set(self.doc, "recurring_id",
frappe.db.set(self.doc, "recurring_id",
make_autoname("RECINV/.#####"))
self.set_next_date()
elif self.doc.recurring_id:
frappe.conn.sql("""update `tabSales Invoice`
frappe.db.sql("""update `tabSales Invoice`
set convert_into_recurring_invoice = 0
where recurring_id = %s""", (self.doc.recurring_id,))
@ -649,7 +649,7 @@ class DocType(SellingController):
next_date = get_next_date(self.doc.posting_date,
month_map[self.doc.recurring_type], cint(self.doc.repeat_on_day_of_month))
frappe.conn.set(self.doc, 'next_date', next_date)
frappe.db.set(self.doc, 'next_date', next_date)
def get_next_date(dt, mcount, day=None):
dt = getdate(dt)
@ -665,14 +665,14 @@ def manage_recurring_invoices(next_date=None, commit=True):
and notify the concerned people
"""
next_date = next_date or nowdate()
recurring_invoices = frappe.conn.sql("""select name, recurring_id
recurring_invoices = frappe.db.sql("""select name, recurring_id
from `tabSales Invoice` where ifnull(convert_into_recurring_invoice, 0)=1
and docstatus=1 and next_date=%s
and next_date <= ifnull(end_date, '2199-12-31')""", next_date)
exception_list = []
for ref_invoice, recurring_id in recurring_invoices:
if not frappe.conn.sql("""select name from `tabSales Invoice`
if not frappe.db.sql("""select name from `tabSales Invoice`
where posting_date=%s and recurring_id=%s and docstatus=1""",
(next_date, recurring_id)):
try:
@ -680,21 +680,21 @@ def manage_recurring_invoices(next_date=None, commit=True):
new_invoice_wrapper = make_new_invoice(ref_wrapper, next_date)
send_notification(new_invoice_wrapper)
if commit:
frappe.conn.commit()
frappe.db.commit()
except:
if commit:
frappe.conn.rollback()
frappe.db.rollback()
frappe.conn.begin()
frappe.conn.sql("update `tabSales Invoice` set \
frappe.db.begin()
frappe.db.sql("update `tabSales Invoice` set \
convert_into_recurring_invoice = 0 where name = %s", ref_invoice)
notify_errors(ref_invoice, ref_wrapper.doc.customer, ref_wrapper.doc.owner)
frappe.conn.commit()
frappe.db.commit()
exception_list.append(frappe.get_traceback())
finally:
if commit:
frappe.conn.begin()
frappe.db.begin()
if exception_list:
exception_message = "\n\n".join([cstr(d) for d in exception_list])
@ -746,7 +746,7 @@ def send_notification(new_rv):
def notify_errors(inv, customer, owner):
from frappe.profile import get_system_managers
frappe.sendmail(recipients=get_system_managers() + [frappe.conn.get_value("Profile", owner, "email")],
frappe.sendmail(recipients=get_system_managers() + [frappe.db.get_value("Profile", owner, "email")],
subject="[Urgent] Error while creating recurring invoice for %s" % inv,
message = frappe.get_template("template/emails/recurring_invoice_failed.html").render({
"name": inv,
@ -769,7 +769,7 @@ def assign_task_to_owner(inv, msg, users):
@frappe.whitelist()
def get_bank_cash_account(mode_of_payment):
val = frappe.conn.get_value("Mode of Payment", mode_of_payment, "default_account")
val = frappe.db.get_value("Mode of Payment", mode_of_payment, "default_account")
if not val:
frappe.msgprint("Default Bank / Cash Account not set in Mode of Payment: %s. Please add a Default Account in Mode of Payment master." % mode_of_payment)
return {
@ -783,7 +783,7 @@ def get_income_account(doctype, txt, searchfield, start, page_len, filters):
# income account can be any Credit account,
# but can also be a Asset account with account_type='Income Account' in special circumstances.
# Hence the first condition is an "OR"
return frappe.conn.sql("""select tabAccount.name from `tabAccount`
return frappe.db.sql("""select tabAccount.name from `tabAccount`
where (tabAccount.debit_or_credit="Credit"
or tabAccount.account_type = "Income Account")
and tabAccount.group_or_ledger="Ledger"

View File

@ -210,7 +210,7 @@ class TestSalesInvoice(unittest.TestCase):
si.insert()
si.submit()
gl_entries = frappe.conn.sql("""select account, debit, credit
gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
order by account asc""", si.doc.name, as_dict=1)
@ -238,7 +238,7 @@ class TestSalesInvoice(unittest.TestCase):
# cancel
si.cancel()
gle = frappe.conn.sql("""select * from `tabGL Entry`
gle = frappe.db.sql("""select * from `tabGL Entry`
where voucher_type='Sales Invoice' and voucher_no=%s""", si.doc.name)
self.assertFalse(gle)
@ -363,7 +363,7 @@ class TestSalesInvoice(unittest.TestCase):
self.assertEquals(w.doc.outstanding_amount, w.doc.grand_total)
def test_payment(self):
frappe.conn.sql("""delete from `tabGL Entry`""")
frappe.db.sql("""delete from `tabGL Entry`""")
w = self.make()
from erpnext.accounts.doctype.journal_voucher.test_journal_voucher \
@ -374,11 +374,11 @@ class TestSalesInvoice(unittest.TestCase):
jv.insert()
jv.submit()
self.assertEquals(frappe.conn.get_value("Sales Invoice", w.doc.name, "outstanding_amount"),
self.assertEquals(frappe.db.get_value("Sales Invoice", w.doc.name, "outstanding_amount"),
161.8)
jv.cancel()
self.assertEquals(frappe.conn.get_value("Sales Invoice", w.doc.name, "outstanding_amount"),
self.assertEquals(frappe.db.get_value("Sales Invoice", w.doc.name, "outstanding_amount"),
561.8)
def test_time_log_batch(self):
@ -390,18 +390,18 @@ class TestSalesInvoice(unittest.TestCase):
si.insert()
si.submit()
self.assertEquals(frappe.conn.get_value("Time Log Batch", "_T-Time Log Batch-00001",
self.assertEquals(frappe.db.get_value("Time Log Batch", "_T-Time Log Batch-00001",
"status"), "Billed")
self.assertEquals(frappe.conn.get_value("Time Log", "_T-Time Log-00001", "status"),
self.assertEquals(frappe.db.get_value("Time Log", "_T-Time Log-00001", "status"),
"Billed")
si.cancel()
self.assertEquals(frappe.conn.get_value("Time Log Batch", "_T-Time Log Batch-00001",
self.assertEquals(frappe.db.get_value("Time Log Batch", "_T-Time Log Batch-00001",
"status"), "Submitted")
self.assertEquals(frappe.conn.get_value("Time Log", "_T-Time Log-00001", "status"),
self.assertEquals(frappe.db.get_value("Time Log", "_T-Time Log-00001", "status"),
"Batched for Billing")
def test_sales_invoice_gl_entry_without_aii(self):
@ -411,7 +411,7 @@ class TestSalesInvoice(unittest.TestCase):
si.insert()
si.submit()
gl_entries = frappe.conn.sql("""select account, debit, credit
gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
order by account asc""", si.doc.name, as_dict=1)
@ -432,7 +432,7 @@ class TestSalesInvoice(unittest.TestCase):
# cancel
si.cancel()
gle = frappe.conn.sql("""select * from `tabGL Entry`
gle = frappe.db.sql("""select * from `tabGL Entry`
where voucher_type='Sales Invoice' and voucher_no=%s""", si.doc.name)
self.assertFalse(gle)
@ -456,7 +456,7 @@ class TestSalesInvoice(unittest.TestCase):
si.submit()
# check stock ledger entries
sle = frappe.conn.sql("""select * from `tabStock Ledger Entry`
sle = frappe.db.sql("""select * from `tabStock Ledger Entry`
where voucher_type = 'Sales Invoice' and voucher_no = %s""",
si.doc.name, as_dict=1)[0]
self.assertTrue(sle)
@ -464,12 +464,12 @@ class TestSalesInvoice(unittest.TestCase):
["_Test Item", "_Test Warehouse - _TC", -1.0])
# check gl entries
gl_entries = frappe.conn.sql("""select account, debit, credit
gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
order by account asc, debit asc""", si.doc.name, as_dict=1)
self.assertTrue(gl_entries)
stock_in_hand = frappe.conn.get_value("Account", {"master_name": "_Test Warehouse - _TC"})
stock_in_hand = frappe.db.get_value("Account", {"master_name": "_Test Warehouse - _TC"})
expected_gl_entries = sorted([
[si.doc.debit_to, 630.0, 0.0],
@ -487,7 +487,7 @@ class TestSalesInvoice(unittest.TestCase):
self.assertEquals(expected_gl_entries[i][2], gle.credit)
si.cancel()
gle = frappe.conn.sql("""select * from `tabGL Entry`
gle = frappe.db.sql("""select * from `tabGL Entry`
where voucher_type='Sales Invoice' and voucher_no=%s""", si.doc.name)
self.assertFalse(gle)
@ -520,7 +520,7 @@ class TestSalesInvoice(unittest.TestCase):
si.submit()
# check stock ledger entries
sle = frappe.conn.sql("""select * from `tabStock Ledger Entry`
sle = frappe.db.sql("""select * from `tabStock Ledger Entry`
where voucher_type = 'Sales Invoice' and voucher_no = %s""",
si.doc.name, as_dict=1)[0]
self.assertTrue(sle)
@ -528,7 +528,7 @@ class TestSalesInvoice(unittest.TestCase):
["_Test Item", "_Test Warehouse No Account - _TC", -1.0])
# check gl entries
gl_entries = frappe.conn.sql("""select account, debit, credit
gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
order by account asc, debit asc""", si.doc.name, as_dict=1)
self.assertTrue(gl_entries)
@ -545,7 +545,7 @@ class TestSalesInvoice(unittest.TestCase):
self.assertEquals(expected_gl_entries[i][2], gle.credit)
si.cancel()
gle = frappe.conn.sql("""select * from `tabGL Entry`
gle = frappe.db.sql("""select * from `tabGL Entry`
where voucher_type='Sales Invoice' and voucher_no=%s""", si.doc.name)
self.assertFalse(gle)
@ -561,7 +561,7 @@ class TestSalesInvoice(unittest.TestCase):
si.insert()
si.submit()
gl_entries = frappe.conn.sql("""select account, debit, credit
gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
order by account asc""", si.doc.name, as_dict=1)
self.assertTrue(gl_entries)
@ -588,7 +588,7 @@ class TestSalesInvoice(unittest.TestCase):
si.insert()
si.submit()
gl_entries = frappe.conn.sql("""select account, debit, credit
gl_entries = frappe.db.sql("""select account, debit, credit
from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
order by account asc""", si.doc.name, as_dict=1)
self.assertTrue(gl_entries)
@ -626,7 +626,7 @@ class TestSalesInvoice(unittest.TestCase):
def _insert_pos_settings(self):
from erpnext.accounts.doctype.pos_setting.test_pos_setting \
import test_records as pos_setting_test_records
frappe.conn.sql("""delete from `tabPOS Setting`""")
frappe.db.sql("""delete from `tabPOS Setting`""")
ps = frappe.bean(copy=pos_setting_test_records[0])
ps.insert()
@ -653,17 +653,17 @@ class TestSalesInvoice(unittest.TestCase):
si.submit()
si.load_from_db()
self.assertTrue(frappe.conn.sql("""select name from `tabJournal Voucher Detail`
self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_invoice=%s""", si.doc.name))
self.assertTrue(frappe.conn.sql("""select name from `tabJournal Voucher Detail`
self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_invoice=%s and credit=300""", si.doc.name))
self.assertEqual(si.doc.outstanding_amount, 261.8)
si.cancel()
self.assertTrue(not frappe.conn.sql("""select name from `tabJournal Voucher Detail`
self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail`
where against_invoice=%s""", si.doc.name))
def test_recurring_invoice(self):
@ -762,7 +762,7 @@ class TestSalesInvoice(unittest.TestCase):
no_of_months = ({"Monthly": 1, "Quarterly": 3, "Yearly": 12})[base_si.doc.recurring_type]
def _test(i):
self.assertEquals(i+1, frappe.conn.sql("""select count(*) from `tabSales Invoice`
self.assertEquals(i+1, frappe.db.sql("""select count(*) from `tabSales Invoice`
where recurring_id=%s and docstatus=1""", base_si.doc.recurring_id)[0][0])
next_date = get_next_date(base_si.doc.posting_date, no_of_months,
@ -770,7 +770,7 @@ class TestSalesInvoice(unittest.TestCase):
manage_recurring_invoices(next_date=next_date, commit=False)
recurred_invoices = frappe.conn.sql("""select name from `tabSales Invoice`
recurred_invoices = frappe.db.sql("""select name from `tabSales Invoice`
where recurring_id=%s and docstatus=1 order by name desc""",
base_si.doc.recurring_id)
@ -805,9 +805,9 @@ class TestSalesInvoice(unittest.TestCase):
base_si = _test(i)
def clear_stock_account_balance(self):
frappe.conn.sql("delete from `tabStock Ledger Entry`")
frappe.conn.sql("delete from tabBin")
frappe.conn.sql("delete from `tabGL Entry`")
frappe.db.sql("delete from `tabStock Ledger Entry`")
frappe.db.sql("delete from tabBin")
frappe.db.sql("delete from `tabGL Entry`")
def test_serialized(self):
from erpnext.stock.doctype.stock_entry.test_stock_entry import make_serialized_item
@ -824,9 +824,9 @@ class TestSalesInvoice(unittest.TestCase):
si.insert()
si.submit()
self.assertEquals(frappe.conn.get_value("Serial No", serial_nos[0], "status"), "Delivered")
self.assertFalse(frappe.conn.get_value("Serial No", serial_nos[0], "warehouse"))
self.assertEquals(frappe.conn.get_value("Serial No", serial_nos[0],
self.assertEquals(frappe.db.get_value("Serial No", serial_nos[0], "status"), "Delivered")
self.assertFalse(frappe.db.get_value("Serial No", serial_nos[0], "warehouse"))
self.assertEquals(frappe.db.get_value("Serial No", serial_nos[0],
"delivery_document_no"), si.doc.name)
return si
@ -838,9 +838,9 @@ class TestSalesInvoice(unittest.TestCase):
serial_nos = get_serial_nos(si.doclist[1].serial_no)
self.assertEquals(frappe.conn.get_value("Serial No", serial_nos[0], "status"), "Available")
self.assertEquals(frappe.conn.get_value("Serial No", serial_nos[0], "warehouse"), "_Test Warehouse - _TC")
self.assertFalse(frappe.conn.get_value("Serial No", serial_nos[0],
self.assertEquals(frappe.db.get_value("Serial No", serial_nos[0], "status"), "Available")
self.assertEquals(frappe.db.get_value("Serial No", serial_nos[0], "warehouse"), "_Test Warehouse - _TC")
self.assertFalse(frappe.db.get_value("Serial No", serial_nos[0],
"delivery_document_no"))
def test_serialize_status(self):

View File

@ -9,7 +9,7 @@ from frappe.model.controller import DocListController
class DocType(DocListController):
def validate(self):
if self.doc.is_default == 1:
frappe.conn.sql("""update `tabSales Taxes and Charges Master` set is_default = 0
frappe.db.sql("""update `tabSales Taxes and Charges Master` set is_default = 0
where ifnull(is_default,0) = 1 and name != %s and company = %s""",
(self.doc.name, self.doc.company))

View File

@ -90,7 +90,7 @@ def validate_total_debit_credit(total_debit, total_credit):
def validate_account_for_auto_accounting_for_stock(gl_map):
if gl_map[0].voucher_type=="Journal Voucher":
aii_accounts = [d[0] for d in frappe.conn.sql("""select name from tabAccount
aii_accounts = [d[0] for d in frappe.db.sql("""select name from tabAccount
where account_type = 'Warehouse' and ifnull(master_name, '')!=''""")]
for entry in gl_map:
@ -107,12 +107,12 @@ def delete_gl_entries(gl_entries=None, voucher_type=None, voucher_no=None,
check_freezing_date, update_outstanding_amt, validate_frozen_account
if not gl_entries:
gl_entries = frappe.conn.sql("""select * from `tabGL Entry`
gl_entries = frappe.db.sql("""select * from `tabGL Entry`
where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no), as_dict=True)
if gl_entries:
check_freezing_date(gl_entries[0]["posting_date"], adv_adj)
frappe.conn.sql("""delete from `tabGL Entry` where voucher_type=%s and voucher_no=%s""",
frappe.db.sql("""delete from `tabGL Entry` where voucher_type=%s and voucher_no=%s""",
(voucher_type or gl_entries[0]["voucher_type"], voucher_no or gl_entries[0]["voucher_no"]))
for entry in gl_entries:

View File

@ -20,7 +20,7 @@ def get_children():
# root
if args['parent'] in ("Accounts", "Cost Centers"):
acc = frappe.conn.sql(""" select
acc = frappe.db.sql(""" select
name as value, if(group_or_ledger='Group', 1, 0) as expandable
from `tab%s`
where ifnull(parent_%s,'') = ''
@ -29,7 +29,7 @@ def get_children():
company, as_dict=1)
else:
# other
acc = frappe.conn.sql("""select
acc = frappe.db.sql("""select
name as value, if(group_or_ledger='Group', 1, 0) as expandable
from `tab%s`
where ifnull(parent_%s,'') = %s
@ -38,7 +38,7 @@ def get_children():
args['parent'], as_dict=1)
if ctype == 'Account':
currency = frappe.conn.sql("select default_currency from `tabCompany` where name = %s", company)[0][0]
currency = frappe.db.sql("select default_currency from `tabCompany` where name = %s", company)[0][0]
for each in acc:
bal = get_balance_on(each.get("value"))
each["currency"] = currency

View File

@ -48,7 +48,7 @@ def _get_party_details(party=None, account=None, party_type="Customer", company=
def set_address_details(out, party, party_type):
billing_address_field = "customer_address" if party_type == "Lead" \
else party_type.lower() + "_address"
out[billing_address_field] = frappe.conn.get_value("Address",
out[billing_address_field] = frappe.db.get_value("Address",
{party_type.lower(): party.name, "is_primary_address":1}, "name")
# address display
@ -56,12 +56,12 @@ def set_address_details(out, party, party_type):
# shipping address
if party_type in ["Customer", "Lead"]:
out.shipping_address_name = frappe.conn.get_value("Address",
out.shipping_address_name = frappe.db.get_value("Address",
{party_type.lower(): party.name, "is_shipping_address":1}, "name")
out.shipping_address = get_address_display(out["shipping_address_name"])
def set_contact_details(out, party, party_type):
out.contact_person = frappe.conn.get_value("Contact",
out.contact_person = frappe.db.get_value("Contact",
{party_type.lower(): party.name, "is_primary_contact":1}, "name")
out.update(get_contact_details(out.contact_person))
@ -91,14 +91,14 @@ def set_price_list(out, party, given_price_list):
price_list = party.default_price_list
if not price_list and party.party_type=="Customer":
price_list = frappe.conn.get_value("Customer Group",
price_list = frappe.db.get_value("Customer Group",
party.customer_group, "default_price_list")
if not price_list:
price_list = given_price_list
if price_list:
out.price_list_currency = frappe.conn.get_value("Price List", price_list, "currency")
out.price_list_currency = frappe.db.get_value("Price List", price_list, "currency")
out["selling_price_list" if party.doctype=="Customer" else "buying_price_list"] = price_list
@ -113,7 +113,7 @@ def set_account_and_due_date(party, account, party_type, company, posting_date):
if party:
account = get_party_account(company, party, party_type)
elif account:
party = frappe.conn.get_value('Account', account, 'master_name')
party = frappe.db.get_value('Account', account, 'master_name')
account_fieldname = "debit_to" if party_type=="Customer" else "credit_to"
@ -129,7 +129,7 @@ def get_party_account(company, party, party_type):
frappe.throw(_("Please select company first."))
if party:
acc_head = frappe.conn.get_value("Account", {"master_name":party,
acc_head = frappe.db.get_value("Account", {"master_name":party,
"master_type": party_type, "company": company})
if not acc_head:
@ -143,11 +143,11 @@ def get_due_date(posting_date, party, party_type, account, company):
if posting_date:
credit_days = 0
if account:
credit_days = frappe.conn.get_value("Account", account, "credit_days")
credit_days = frappe.db.get_value("Account", account, "credit_days")
if party and not credit_days:
credit_days = frappe.conn.get_value(party_type, party, "credit_days")
credit_days = frappe.db.get_value(party_type, party, "credit_days")
if company and not credit_days:
credit_days = frappe.conn.get_value("Company", company, "credit_days")
credit_days = frappe.db.get_value("Company", company, "credit_days")
due_date = add_days(posting_date, credit_days) if credit_days else posting_date
@ -157,9 +157,9 @@ def create_party_account(party, party_type, company):
if not company:
frappe.throw(_("Company is required"))
company_details = frappe.conn.get_value("Company", company,
company_details = frappe.db.get_value("Company", company,
["abbr", "receivables_group", "payables_group"], as_dict=True)
if not frappe.conn.exists("Account", (party + " - " + company_details.abbr)):
if not frappe.db.exists("Account", (party + " - " + company_details.abbr)):
parent_account = company_details.receivables_group \
if party_type=="Customer" else company_details.payables_group

View File

@ -9,10 +9,10 @@ from erpnext.accounts.report.accounts_receivable.accounts_receivable import get_
def execute(filters=None):
if not filters: filters = {}
supplier_naming_by = frappe.conn.get_value("Buying Settings", None, "supp_master_name")
supplier_naming_by = frappe.db.get_value("Buying Settings", None, "supp_master_name")
columns = get_columns(supplier_naming_by)
entries = get_gl_entries(filters)
account_map = dict(((r.name, r) for r in frappe.conn.sql("""select acc.name,
account_map = dict(((r.name, r) for r in frappe.db.sql("""select acc.name,
supp.supplier_name, supp.name as supplier
from `tabAccount` acc, `tabSupplier` supp
where acc.master_type="Supplier" and supp.name=acc.master_name""", as_dict=1)))
@ -85,7 +85,7 @@ def get_columns(supplier_naming_by):
def get_gl_entries(filters, before_report_date=True):
conditions, supplier_accounts = get_conditions(filters, before_report_date)
gl_entries = []
gl_entries = frappe.conn.sql("""select * from `tabGL Entry`
gl_entries = frappe.db.sql("""select * from `tabGL Entry`
where docstatus < 2 %s order by posting_date, account""" %
(conditions), tuple(supplier_accounts), as_dict=1)
return gl_entries
@ -99,7 +99,7 @@ def get_conditions(filters, before_report_date=True):
if filters.get("account"):
supplier_accounts = [filters["account"]]
else:
supplier_accounts = frappe.conn.sql_list("""select name from `tabAccount`
supplier_accounts = frappe.db.sql_list("""select name from `tabAccount`
where ifnull(master_type, '') = 'Supplier' and docstatus < 2 %s""" %
conditions, filters)
@ -118,7 +118,7 @@ def get_conditions(filters, before_report_date=True):
def get_account_supplier_type_map():
account_supplier_type_map = {}
for each in frappe.conn.sql("""select acc.name, supp.supplier_type from `tabSupplier` supp,
for each in frappe.db.sql("""select acc.name, supp.supplier_type from `tabSupplier` supp,
`tabAccount` acc where supp.name = acc.master_name group by acc.name"""):
account_supplier_type_map[each[0]] = each[1]
@ -128,14 +128,14 @@ def get_voucher_details():
voucher_details = {}
for dt in ["Purchase Invoice", "Journal Voucher"]:
voucher_details.setdefault(dt, frappe._dict())
for t in frappe.conn.sql("""select name, due_date, bill_no, bill_date
for t in frappe.db.sql("""select name, due_date, bill_no, bill_date
from `tab%s`""" % dt, as_dict=1):
voucher_details[dt].setdefault(t.name, t)
return voucher_details
def get_outstanding_amount(gle, report_date):
payment_amount = frappe.conn.sql("""
payment_amount = frappe.db.sql("""
select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
from `tabGL Entry`
where account = %s and posting_date <= %s and against_voucher_type = %s

View File

@ -15,7 +15,7 @@ class AccountsReceivableReport(object):
else self.filters.report_date
def run(self):
customer_naming_by = frappe.conn.get_value("Selling Settings", None, "cust_master_name")
customer_naming_by = frappe.db.get_value("Selling Settings", None, "cust_master_name")
return self.get_columns(customer_naming_by), self.get_data(customer_naming_by)
def get_columns(self, customer_naming_by):
@ -111,7 +111,7 @@ class AccountsReceivableReport(object):
def get_account_map(self):
if not hasattr(self, "account_map"):
self.account_map = dict(((r.name, r) for r in frappe.conn.sql("""select
self.account_map = dict(((r.name, r) for r in frappe.db.sql("""select
acc.name, cust.name as customer, cust.customer_name, cust.territory
from `tabAccount` acc left join `tabCustomer` cust
on cust.name=acc.master_name where acc.master_type="Customer" """, as_dict=True)))
@ -121,7 +121,7 @@ class AccountsReceivableReport(object):
def get_due_date(self, gle):
if not hasattr(self, "invoice_due_date_map"):
# TODO can be restricted to posting date
self.invoice_due_date_map = dict(frappe.conn.sql("""select name, due_date
self.invoice_due_date_map = dict(frappe.db.sql("""select name, due_date
from `tabSales Invoice` where docstatus=1"""))
return gle.voucher_type == "Sales Invoice" \
@ -130,7 +130,7 @@ class AccountsReceivableReport(object):
def get_gl_entries(self):
if not hasattr(self, "gl_entries"):
conditions, values = self.prepare_conditions()
self.gl_entries = frappe.conn.sql("""select * from `tabGL Entry`
self.gl_entries = frappe.db.sql("""select * from `tabGL Entry`
where docstatus < 2 {0} order by posting_date, account""".format(conditions),
values, as_dict=True)
return self.gl_entries

View File

@ -33,7 +33,7 @@ def get_conditions(filters):
def get_entries(filters):
conditions = get_conditions(filters)
entries = frappe.conn.sql("""select jv.name, jvd.account, jv.posting_date,
entries = frappe.db.sql("""select jv.name, jvd.account, jv.posting_date,
jv.clearance_date, jvd.against_account, jvd.debit, jvd.credit
from `tabJournal Voucher Detail` jvd, `tabJournal Voucher` jv
where jvd.parent = jv.name and jv.docstatus=1 %s

View File

@ -8,7 +8,7 @@ from frappe.utils import flt
def execute(filters=None):
if not filters: filters = {}
debit_or_credit = frappe.conn.get_value("Account", filters["account"], "debit_or_credit")
debit_or_credit = frappe.db.get_value("Account", filters["account"], "debit_or_credit")
columns = get_columns()
data = get_entries(filters)
@ -41,7 +41,7 @@ def get_columns():
]
def get_entries(filters):
entries = frappe.conn.sql("""select
entries = frappe.db.sql("""select
jv.name, jv.posting_date, jv.clearance_date, jvd.against_account, jvd.debit, jvd.credit
from
`tabJournal Voucher Detail` jvd, `tabJournal Voucher` jv

View File

@ -62,7 +62,7 @@ def get_columns(filters):
#Get cost center & target details
def get_costcenter_target_details(filters):
return frappe.conn.sql("""select cc.name, cc.distribution_id,
return frappe.db.sql("""select cc.name, cc.distribution_id,
cc.parent_cost_center, bd.account, bd.budget_allocated
from `tabCost Center` cc, `tabBudget Detail` bd
where bd.parent=cc.name and bd.fiscal_year=%s and
@ -73,7 +73,7 @@ def get_costcenter_target_details(filters):
def get_target_distribution_details(filters):
target_details = {}
for d in frappe.conn.sql("""select bd.name, bdd.month, bdd.percentage_allocation
for d in frappe.db.sql("""select bd.name, bdd.month, bdd.percentage_allocation
from `tabBudget Distribution Detail` bdd, `tabBudget Distribution` bd
where bdd.parent=bd.name and bd.fiscal_year=%s""", (filters["fiscal_year"]), as_dict=1):
target_details.setdefault(d.name, {}).setdefault(d.month, flt(d.percentage_allocation))
@ -82,7 +82,7 @@ def get_target_distribution_details(filters):
#Get actual details from gl entry
def get_actual_details(filters):
ac_details = frappe.conn.sql("""select gl.account, gl.debit, gl.credit,
ac_details = frappe.db.sql("""select gl.account, gl.debit, gl.credit,
gl.cost_center, MONTHNAME(gl.posting_date) as month_name
from `tabGL Entry` gl, `tabBudget Detail` bd
where gl.fiscal_year=%s and company=%s

View File

@ -8,7 +8,7 @@ def execute(filters=None):
account_map = get_account_map()
columns = get_columns(account_map)
data = []
customers = frappe.conn.sql("select name from tabCustomer where docstatus < 2")
customers = frappe.db.sql("select name from tabCustomer where docstatus < 2")
for cust in customers:
row = [cust[0]]
for company in sorted(account_map):
@ -18,7 +18,7 @@ def execute(filters=None):
return columns, data
def get_account_map():
accounts = frappe.conn.sql("""select name, company, master_name
accounts = frappe.db.sql("""select name, company, master_name
from `tabAccount` where master_type = 'Customer'
and ifnull(master_name, '') != '' and docstatus < 2""", as_dict=1)

View File

@ -8,7 +8,7 @@ from frappe import _
def execute(filters=None):
account_details = {}
for acc in frappe.conn.sql("""select name, debit_or_credit, group_or_ledger
for acc in frappe.db.sql("""select name, debit_or_credit, group_or_ledger
from tabAccount""", as_dict=1):
account_details.setdefault(acc.name, acc)
@ -49,7 +49,7 @@ def get_gl_entries(filters):
group_by_condition = "group by voucher_type, voucher_no, account" \
if filters.get("group_by_voucher") else "group by name"
gl_entries = frappe.conn.sql("""select posting_date, account,
gl_entries = frappe.db.sql("""select posting_date, account,
sum(ifnull(debit, 0)) as debit, sum(ifnull(credit, 0)) as credit,
voucher_type, voucher_no, cost_center, remarks, is_opening, against
from `tabGL Entry`
@ -64,7 +64,7 @@ def get_gl_entries(filters):
def get_conditions(filters):
conditions = []
if filters.get("account"):
lft, rgt = frappe.conn.get_value("Account", filters["account"], ["lft", "rgt"])
lft, rgt = frappe.db.get_value("Account", filters["account"], ["lft", "rgt"])
conditions.append("""account in (select name from tabAccount
where lft>=%s and rgt<=%s and docstatus<2)""" % (lft, rgt))
else:

View File

@ -59,7 +59,7 @@ def get_stock_ledger_entries(filters):
query += " order by item_code desc, warehouse desc, posting_date desc, posting_time desc, name desc"
res = frappe.conn.sql(query, filters, as_dict=True)
res = frappe.db.sql(query, filters, as_dict=True)
out = {}
for r in res:
@ -73,7 +73,7 @@ def get_stock_ledger_entries(filters):
def get_item_sales_bom():
item_sales_bom = {}
for d in frappe.conn.sql("""select parenttype, parent, parent_item,
for d in frappe.db.sql("""select parenttype, parent, parent_item,
item_code, warehouse, -1*qty as total_qty, parent_detail_docname
from `tabPacked Item` where docstatus=1""", as_dict=True):
item_sales_bom.setdefault(d.parenttype, frappe._dict()).setdefault(d.parent,
@ -90,7 +90,7 @@ def get_source_data(filters):
if filters.get("to_date"):
conditions += " and posting_date<=%(to_date)s"
delivery_note_items = frappe.conn.sql("""select item.parenttype, dn.name,
delivery_note_items = frappe.db.sql("""select item.parenttype, dn.name,
dn.posting_date, dn.posting_time, dn.project_name,
item.item_code, item.item_name, item.description, item.warehouse,
item.qty, item.base_rate, item.base_amount, item.name as "item_row",
@ -99,7 +99,7 @@ def get_source_data(filters):
where item.parent = dn.name and dn.docstatus = 1 %s
order by dn.posting_date desc, dn.posting_time desc""" % (conditions,), filters, as_dict=1)
sales_invoice_items = frappe.conn.sql("""select item.parenttype, si.name,
sales_invoice_items = frappe.db.sql("""select item.parenttype, si.name,
si.posting_date, si.posting_time, si.project_name,
item.item_code, item.item_name, item.description, item.warehouse,
item.qty, item.base_rate, item.base_amount, item.name as "item_row",

View File

@ -57,7 +57,7 @@ def get_items(filters):
conditions = get_conditions(filters)
match_conditions = frappe.build_match_conditions("Purchase Invoice")
return frappe.conn.sql("""select pi_item.parent, pi.posting_date, pi.credit_to, pi.company,
return frappe.db.sql("""select pi_item.parent, pi.posting_date, pi.credit_to, pi.company,
pi.supplier, pi.remarks, pi_item.item_code, pi_item.item_name, pi_item.item_group,
pi_item.project_name, pi_item.purchase_order, pi_item.purchase_receipt,
pi_item.expense_account, pi_item.qty, pi_item.base_rate, pi_item.base_amount, pi.supplier_name
@ -66,14 +66,14 @@ def get_items(filters):
order by pi.posting_date desc, pi_item.item_code desc""" % (conditions, match_conditions), filters, as_dict=1)
def get_aii_accounts():
return dict(frappe.conn.sql("select name, stock_received_but_not_billed from tabCompany"))
return dict(frappe.db.sql("select name, stock_received_but_not_billed from tabCompany"))
def get_tax_accounts(item_list, columns):
import json
item_tax = {}
tax_accounts = []
tax_details = frappe.conn.sql("""select parent, account_head, item_wise_tax_detail
tax_details = frappe.db.sql("""select parent, account_head, item_wise_tax_detail
from `tabPurchase Taxes and Charges` where parenttype = 'Purchase Invoice'
and docstatus = 1 and ifnull(account_head, '') != '' and category in ('Total', 'Valuation and Total')
and parent in (%s)""" % ', '.join(['%s']*len(item_list)), tuple([item.parent for item in item_list]))

View File

@ -55,7 +55,7 @@ def get_conditions(filters):
def get_items(filters):
conditions = get_conditions(filters)
return frappe.conn.sql("""select si_item.parent, si.posting_date, si.debit_to, si.project_name,
return frappe.db.sql("""select si_item.parent, si.posting_date, si.debit_to, si.project_name,
si.customer, si.remarks, si.territory, si.company, si_item.item_code, si_item.item_name,
si_item.item_group, si_item.sales_order, si_item.delivery_note, si_item.income_account,
si_item.qty, si_item.base_rate, si_item.base_amount, si.customer_name
@ -68,7 +68,7 @@ def get_tax_accounts(item_list, columns):
item_tax = {}
tax_accounts = []
tax_details = frappe.conn.sql("""select parent, account_head, item_wise_tax_detail
tax_details = frappe.db.sql("""select parent, account_head, item_wise_tax_detail
from `tabSales Taxes and Charges` where parenttype = 'Sales Invoice'
and docstatus = 1 and ifnull(account_head, '') != ''
and parent in (%s)""" % ', '.join(['%s']*len(item_list)),

View File

@ -58,7 +58,7 @@ def get_conditions(filters):
else:
cond += " and master_type = 'Supplier'"
party_accounts = frappe.conn.sql_list("""select name from `tabAccount`
party_accounts = frappe.db.sql_list("""select name from `tabAccount`
where ifnull(master_name, '')!='' and docstatus < 2 %s""" % cond)
if party_accounts:
@ -74,7 +74,7 @@ def get_conditions(filters):
def get_entries(filters):
conditions, party_accounts = get_conditions(filters)
entries = frappe.conn.sql("""select jv.name, jvd.account, jv.posting_date,
entries = frappe.db.sql("""select jv.name, jvd.account, jv.posting_date,
jvd.against_voucher, jvd.against_invoice, jvd.debit, jvd.credit,
jv.cheque_no, jv.cheque_date, jv.remark
from `tabJournal Voucher Detail` jvd, `tabJournal Voucher` jv
@ -86,10 +86,10 @@ def get_entries(filters):
def get_invoice_posting_date_map(filters):
invoice_posting_date_map = {}
if filters.get("payment_type") == "Incoming":
for t in frappe.conn.sql("""select name, posting_date from `tabSales Invoice`"""):
for t in frappe.db.sql("""select name, posting_date from `tabSales Invoice`"""):
invoice_posting_date_map[t[0]] = t[1]
else:
for t in frappe.conn.sql("""select name, posting_date from `tabPurchase Invoice`"""):
for t in frappe.db.sql("""select name, posting_date from `tabPurchase Invoice`"""):
invoice_posting_date_map[t[0]] = t[1]
return invoice_posting_date_map

View File

@ -72,12 +72,12 @@ def get_columns(invoice_list):
expense_accounts = tax_accounts = expense_columns = tax_columns = []
if invoice_list:
expense_accounts = frappe.conn.sql_list("""select distinct expense_account
expense_accounts = frappe.db.sql_list("""select distinct expense_account
from `tabPurchase Invoice Item` where docstatus = 1 and ifnull(expense_account, '') != ''
and parent in (%s) order by expense_account""" %
', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]))
tax_accounts = frappe.conn.sql_list("""select distinct account_head
tax_accounts = frappe.db.sql_list("""select distinct account_head
from `tabPurchase Taxes and Charges` where parenttype = 'Purchase Invoice'
and docstatus = 1 and ifnull(account_head, '') != '' and category in ('Total', 'Valuation and Total')
and parent in (%s) order by account_head""" %
@ -109,14 +109,14 @@ def get_conditions(filters):
def get_invoices(filters):
conditions = get_conditions(filters)
return frappe.conn.sql("""select name, posting_date, credit_to, supplier, supplier_name,
return frappe.db.sql("""select name, posting_date, credit_to, supplier, supplier_name,
bill_no, bill_date, remarks, net_total, grand_total, outstanding_amount
from `tabPurchase Invoice` where docstatus = 1 %s
order by posting_date desc, name desc""" % conditions, filters, as_dict=1)
def get_invoice_expense_map(invoice_list):
expense_details = frappe.conn.sql("""select parent, expense_account, sum(base_amount) as amount
expense_details = frappe.db.sql("""select parent, expense_account, sum(base_amount) as amount
from `tabPurchase Invoice Item` where parent in (%s) group by parent, expense_account""" %
', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1)
@ -128,7 +128,7 @@ def get_invoice_expense_map(invoice_list):
return invoice_expense_map
def get_invoice_tax_map(invoice_list, invoice_expense_map, expense_accounts):
tax_details = frappe.conn.sql("""select parent, account_head, sum(tax_amount) as tax_amount
tax_details = frappe.db.sql("""select parent, account_head, sum(tax_amount) as tax_amount
from `tabPurchase Taxes and Charges` where parent in (%s) group by parent, account_head""" %
', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1)
@ -146,7 +146,7 @@ def get_invoice_tax_map(invoice_list, invoice_expense_map, expense_accounts):
return invoice_expense_map, invoice_tax_map
def get_invoice_po_pr_map(invoice_list):
pi_items = frappe.conn.sql("""select parent, purchase_order, purchase_receipt,
pi_items = frappe.db.sql("""select parent, purchase_order, purchase_receipt,
project_name from `tabPurchase Invoice Item` where parent in (%s)
and (ifnull(purchase_order, '') != '' or ifnull(purchase_receipt, '') != '')""" %
', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1)
@ -168,7 +168,7 @@ def get_invoice_po_pr_map(invoice_list):
def get_account_details(invoice_list):
account_map = {}
accounts = list(set([inv.credit_to for inv in invoice_list]))
for acc in frappe.conn.sql("""select name, parent_account from tabAccount
for acc in frappe.db.sql("""select name, parent_account from tabAccount
where name in (%s)""" % ", ".join(["%s"]*len(accounts)), tuple(accounts), as_dict=1):
account_map[acc.name] = acc.parent_account

View File

@ -72,12 +72,12 @@ def get_columns(invoice_list):
income_accounts = tax_accounts = income_columns = tax_columns = []
if invoice_list:
income_accounts = frappe.conn.sql_list("""select distinct income_account
income_accounts = frappe.db.sql_list("""select distinct income_account
from `tabSales Invoice Item` where docstatus = 1 and parent in (%s)
order by income_account""" %
', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]))
tax_accounts = frappe.conn.sql_list("""select distinct account_head
tax_accounts = frappe.db.sql_list("""select distinct account_head
from `tabSales Taxes and Charges` where parenttype = 'Sales Invoice'
and docstatus = 1 and ifnull(tax_amount_after_discount_amount, 0) != 0
and parent in (%s) order by account_head""" %
@ -107,14 +107,14 @@ def get_conditions(filters):
def get_invoices(filters):
conditions = get_conditions(filters)
return frappe.conn.sql("""select name, posting_date, debit_to, project_name, customer,
return frappe.db.sql("""select name, posting_date, debit_to, project_name, customer,
customer_name, remarks, net_total, grand_total, rounded_total, outstanding_amount
from `tabSales Invoice`
where docstatus = 1 %s order by posting_date desc, name desc""" %
conditions, filters, as_dict=1)
def get_invoice_income_map(invoice_list):
income_details = frappe.conn.sql("""select parent, income_account, sum(base_amount) as amount
income_details = frappe.db.sql("""select parent, income_account, sum(base_amount) as amount
from `tabSales Invoice Item` where parent in (%s) group by parent, income_account""" %
', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1)
@ -126,7 +126,7 @@ def get_invoice_income_map(invoice_list):
return invoice_income_map
def get_invoice_tax_map(invoice_list, invoice_income_map, income_accounts):
tax_details = frappe.conn.sql("""select parent, account_head,
tax_details = frappe.db.sql("""select parent, account_head,
sum(tax_amount_after_discount_amount) as tax_amount
from `tabSales Taxes and Charges` where parent in (%s) group by parent, account_head""" %
', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1)
@ -145,7 +145,7 @@ def get_invoice_tax_map(invoice_list, invoice_income_map, income_accounts):
return invoice_income_map, invoice_tax_map
def get_invoice_so_dn_map(invoice_list):
si_items = frappe.conn.sql("""select parent, sales_order, delivery_note
si_items = frappe.db.sql("""select parent, sales_order, delivery_note
from `tabSales Invoice Item` where parent in (%s)
and (ifnull(sales_order, '') != '' or ifnull(delivery_note, '') != '')""" %
', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1)
@ -164,7 +164,7 @@ def get_invoice_so_dn_map(invoice_list):
def get_customer_deatils(invoice_list):
customer_map = {}
customers = list(set([inv.customer for inv in invoice_list]))
for cust in frappe.conn.sql("""select name, territory from `tabCustomer`
for cust in frappe.db.sql("""select name, territory from `tabCustomer`
where name in (%s)""" % ", ".join(["%s"]*len(customers)), tuple(customers), as_dict=1):
customer_map[cust.name] = cust.territory
@ -173,7 +173,7 @@ def get_customer_deatils(invoice_list):
def get_account_details(invoice_list):
account_map = {}
accounts = list(set([inv.debit_to for inv in invoice_list]))
for acc in frappe.conn.sql("""select name, parent_account from tabAccount
for acc in frappe.db.sql("""select name, parent_account from tabAccount
where name in (%s)""" % ", ".join(["%s"]*len(accounts)), tuple(accounts), as_dict=1):
account_map[acc.name] = acc.parent_account

View File

@ -8,7 +8,7 @@ def execute(filters=None):
account_map = get_account_map()
columns = get_columns(account_map)
data = []
suppliers = frappe.conn.sql("select name from tabSupplier where docstatus < 2")
suppliers = frappe.db.sql("select name from tabSupplier where docstatus < 2")
for supplier in suppliers:
row = [supplier[0]]
for company in sorted(account_map):
@ -18,7 +18,7 @@ def execute(filters=None):
return columns, data
def get_account_map():
accounts = frappe.conn.sql("""select name, company, master_name
accounts = frappe.db.sql("""select name, company, master_name
from `tabAccount` where master_type = 'Supplier'
and ifnull(master_name, '') != '' and docstatus < 2""", as_dict=1)

View File

@ -26,7 +26,7 @@ def get_fiscal_years(date=None, fiscal_year=None, label="Date", verbose=1):
else:
cond = "'%s' >= year_start_date and '%s' <= year_end_date" % \
(date, date)
fy = frappe.conn.sql("""select name, year_start_date, year_end_date
fy = frappe.db.sql("""select name, year_start_date, year_end_date
from `tabFiscal Year` where %s order by year_start_date desc""" % cond)
if not fy:
@ -73,7 +73,7 @@ def get_balance_on(account=None, date=None):
# hence, assuming balance as 0.0
return 0.0
acc = frappe.conn.get_value('Account', account, \
acc = frappe.db.get_value('Account', account, \
['lft', 'rgt', 'debit_or_credit', 'is_pl_account', 'group_or_ledger'], as_dict=1)
# for pl accounts, get balance within a fiscal year
@ -90,7 +90,7 @@ def get_balance_on(account=None, date=None):
else:
cond.append("""gle.account = "%s" """ % (account, ))
bal = frappe.conn.sql("""
bal = frappe.db.sql("""
SELECT sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
FROM `tabGL Entry` gle
WHERE %s""" % " and ".join(cond))[0][0]
@ -160,7 +160,7 @@ def check_if_jv_modified(args):
check if amount is same
check if jv is submitted
"""
ret = frappe.conn.sql("""
ret = frappe.db.sql("""
select t2.%(dr_or_cr)s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2
where t1.name = t2.parent and t2.account = '%(account)s'
and ifnull(t2.against_voucher, '')=''
@ -176,14 +176,14 @@ def update_against_doc(d, jv_obj):
Updates against document, if partial amount splits into rows
"""
frappe.conn.sql("""
frappe.db.sql("""
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()
where t1.name = '%(voucher_detail_no)s' and t1.parent = t2.name""" % d)
if d['allocated_amt'] < d['unadjusted_amt']:
jvd = frappe.conn.sql("""select cost_center, balance, against_account, is_advance
jvd = frappe.db.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
ch = addchild(jv_obj.doc, 'entries', 'Journal Voucher Detail')
@ -203,7 +203,7 @@ def get_account_list(doctype, txt, searchfield, start, page_len, filters):
conditions, filter_values = build_filter_conditions(filters)
return frappe.conn.sql("""select name, parent_account from `tabAccount`
return frappe.db.sql("""select name, parent_account from `tabAccount`
where docstatus < 2 %s and %s like %s order by name limit %s, %s""" %
(conditions, searchfield, "%s", "%s", "%s"),
tuple(filter_values + ["%%%s%%" % txt, start, page_len]))
@ -214,22 +214,22 @@ def get_cost_center_list(doctype, txt, searchfield, start, page_len, filters):
conditions, filter_values = build_filter_conditions(filters)
return frappe.conn.sql("""select name, parent_cost_center from `tabCost Center`
return frappe.db.sql("""select name, parent_cost_center from `tabCost Center`
where docstatus < 2 %s and %s like %s order by name limit %s, %s""" %
(conditions, searchfield, "%s", "%s", "%s"),
tuple(filter_values + ["%%%s%%" % txt, start, page_len]))
def remove_against_link_from_jv(ref_type, ref_no, against_field):
linked_jv = frappe.conn.sql_list("""select parent from `tabJournal Voucher Detail`
linked_jv = frappe.db.sql_list("""select parent from `tabJournal Voucher Detail`
where `%s`=%s and docstatus < 2""" % (against_field, "%s"), (ref_no))
if linked_jv:
frappe.conn.sql("""update `tabJournal Voucher Detail` set `%s`=null,
frappe.db.sql("""update `tabJournal Voucher Detail` set `%s`=null,
modified=%s, modified_by=%s
where `%s`=%s and docstatus < 2""" % (against_field, "%s", "%s", against_field, "%s"),
(now(), frappe.session.user, ref_no))
frappe.conn.sql("""update `tabGL Entry`
frappe.db.sql("""update `tabGL Entry`
set against_voucher_type=null, against_voucher=null,
modified=%s, modified_by=%s
where against_voucher_type=%s and against_voucher=%s
@ -243,7 +243,7 @@ def remove_against_link_from_jv(ref_type, ref_no, against_field):
@frappe.whitelist()
def get_company_default(company, fieldname):
value = frappe.conn.get_value("Company", company, fieldname)
value = frappe.db.get_value("Company", company, fieldname)
if not value:
throw(_("Please mention default value for '") +
@ -253,7 +253,7 @@ def get_company_default(company, fieldname):
return value
def fix_total_debit_credit():
vouchers = frappe.conn.sql("""select voucher_type, voucher_no,
vouchers = frappe.db.sql("""select voucher_type, voucher_no,
sum(debit) - sum(credit) as diff
from `tabGL Entry`
group by voucher_type, voucher_no
@ -263,7 +263,7 @@ def fix_total_debit_credit():
if abs(d.diff) > 0:
dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
frappe.conn.sql("""update `tabGL Entry` set %s = %s + %s
frappe.db.sql("""update `tabGL Entry` set %s = %s + %s
where voucher_type = %s and voucher_no = %s and %s > 0 limit 1""" %
(dr_or_cr, dr_or_cr, '%s', '%s', '%s', dr_or_cr),
(d.diff, d.voucher_type, d.voucher_no))
@ -275,7 +275,7 @@ def get_stock_and_account_difference(account_list=None, posting_date=None):
difference = {}
account_warehouse = dict(frappe.conn.sql("""select name, master_name from tabAccount
account_warehouse = dict(frappe.db.sql("""select name, master_name from tabAccount
where account_type = 'Warehouse' and ifnull(master_name, '') != ''
and name in (%s)""" % ', '.join(['%s']*len(account_list)), account_list))
@ -289,16 +289,16 @@ def get_stock_and_account_difference(account_list=None, posting_date=None):
def validate_expense_against_budget(args):
args = frappe._dict(args)
if frappe.conn.get_value("Account", {"name": args.account, "is_pl_account": "Yes",
if frappe.db.get_value("Account", {"name": args.account, "is_pl_account": "Yes",
"debit_or_credit": "Debit"}):
budget = frappe.conn.sql("""
budget = frappe.db.sql("""
select bd.budget_allocated, cc.distribution_id
from `tabCost Center` cc, `tabBudget Detail` bd
where cc.name=bd.parent and cc.name=%s and account=%s and bd.fiscal_year=%s
""", (args.cost_center, args.account, args.fiscal_year), as_dict=True)
if budget and budget[0].budget_allocated:
yearly_action, monthly_action = frappe.conn.get_value("Company", args.company,
yearly_action, monthly_action = frappe.db.get_value("Company", args.company,
["yearly_bgt_flag", "monthly_bgt_flag"])
action_for = action = ""
@ -306,7 +306,7 @@ def validate_expense_against_budget(args):
budget_amount = get_allocated_budget(budget[0].distribution_id,
args.posting_date, args.fiscal_year, budget[0].budget_allocated)
args["month_end_date"] = frappe.conn.sql("select LAST_DAY(%s)",
args["month_end_date"] = frappe.db.sql("select LAST_DAY(%s)",
args.posting_date)[0][0]
action_for, action = "Monthly", monthly_action
@ -326,12 +326,12 @@ def validate_expense_against_budget(args):
def get_allocated_budget(distribution_id, posting_date, fiscal_year, yearly_budget):
if distribution_id:
distribution = {}
for d in frappe.conn.sql("""select bdd.month, bdd.percentage_allocation
for d in frappe.db.sql("""select bdd.month, bdd.percentage_allocation
from `tabBudget Distribution Detail` bdd, `tabBudget Distribution` bd
where bdd.parent=bd.name and bd.fiscal_year=%s""", fiscal_year, as_dict=1):
distribution.setdefault(d.month, d.percentage_allocation)
dt = frappe.conn.get_value("Fiscal Year", fiscal_year, "year_start_date")
dt = frappe.db.get_value("Fiscal Year", fiscal_year, "year_start_date")
budget_percentage = 0.0
while(dt <= getdate(posting_date)):
@ -348,7 +348,7 @@ def get_actual_expense(args):
args["condition"] = " and posting_date<='%s'" % args.month_end_date \
if args.get("month_end_date") else ""
return frappe.conn.sql("""
return frappe.db.sql("""
select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
from `tabGL Entry`
where account='%(account)s' and cost_center='%(cost_center)s'
@ -367,7 +367,7 @@ def rename_account_for(dt, olddn, newdn, merge, company):
new_account = frappe.rename_doc("Account", old_account,
existing_new_account or newdn, merge=True if existing_new_account else False)
frappe.conn.set_value("Account", new_account or old_account, "master_name", newdn)
frappe.db.set_value("Account", new_account or old_account, "master_name", newdn)
def add_abbr_if_missing(dn, company):
from erpnext.setup.doctype.company.company import get_name_with_abbr
@ -379,14 +379,14 @@ def get_account_for(account_for_doctype, account_for):
elif account_for_doctype == "Warehouse":
account_for_field = "account_type"
return frappe.conn.get_value("Account", {account_for_field: account_for_doctype,
return frappe.db.get_value("Account", {account_for_field: account_for_doctype,
"master_name": account_for})
def get_currency_precision(currency=None):
if not currency:
currency = frappe.conn.get_value("Company",
frappe.conn.get_default("company"), "default_currency")
currency_format = frappe.conn.get_value("Currency", currency, "number_format")
currency = frappe.db.get_value("Company",
frappe.db.get_default("company"), "default_currency")
currency_format = frappe.db.get_value("Currency", currency, "number_format")
from frappe.utils import get_number_format_info
return get_number_format_info(currency_format)[2]

View File

@ -12,7 +12,7 @@ class DocType:
def validate(self):
for key in ["supplier_type", "supp_master_name", "maintain_same_rate", "buying_price_list"]:
frappe.conn.set_default(key, self.doc.fields.get(key, ""))
frappe.db.set_default(key, self.doc.fields.get(key, ""))
from erpnext.setup.doctype.naming_series.naming_series import set_by_naming_series
set_by_naming_series("Supplier", "supplier_name",

View File

@ -42,7 +42,7 @@ class DocType(BuyingController):
# update last purchsae rate
if last_purchase_rate:
frappe.conn.sql("""update `tabItem` set last_purchase_rate = %s where name = %s""",
frappe.db.sql("""update `tabItem` set last_purchase_rate = %s where name = %s""",
(flt(last_purchase_rate), d.item_code))
def get_last_purchase_rate(self, obj):
@ -64,7 +64,7 @@ class DocType(BuyingController):
# if no last purchase found, reset all values to 0
d.base_price_list_rate = d.base_rate = d.price_list_rate = d.rate = d.discount_percentage = 0
item_last_purchase_rate = frappe.conn.get_value("Item",
item_last_purchase_rate = frappe.db.get_value("Item",
d.item_code, "last_purchase_rate")
if item_last_purchase_rate:
d.base_price_list_rate = d.base_rate = d.price_list_rate \
@ -78,7 +78,7 @@ class DocType(BuyingController):
frappe.throw("Please enter valid qty for item %s" % cstr(d.item_code))
# udpate with latest quantities
bin = frappe.conn.sql("""select projected_qty from `tabBin` where
bin = frappe.db.sql("""select projected_qty from `tabBin` where
item_code = %s and warehouse = %s""", (d.item_code, d.warehouse), as_dict=1)
f_lst ={'projected_qty': bin and flt(bin[0]['projected_qty']) or 0, 'ordered_qty': 0, 'received_qty' : 0}
@ -88,7 +88,7 @@ class DocType(BuyingController):
if d.fields.has_key(x):
d.fields[x] = f_lst[x]
item = frappe.conn.sql("""select is_stock_item, is_purchase_item,
item = frappe.db.sql("""select is_stock_item, is_purchase_item,
is_sub_contracted_item, end_of_life from `tabItem` where name=%s""", d.item_code)
if not item:
frappe.throw("Item %s does not exist in Item Master." % cstr(d.item_code))
@ -113,7 +113,7 @@ class DocType(BuyingController):
# if is not stock item
f = [d.schedule_date, d.item_code, d.description]
ch = frappe.conn.sql("""select is_stock_item from `tabItem` where name = %s""", d.item_code)
ch = frappe.db.sql("""select is_stock_item from `tabItem` where name = %s""", d.item_code)
if ch and ch[0][0] == 'Yes':
# check for same items
@ -139,21 +139,21 @@ class DocType(BuyingController):
# but if in Material Request uom KG it can change in PO
get_qty = (transaction == 'Material Request - Purchase Order') and 'qty * conversion_factor' or 'qty'
qty = frappe.conn.sql("""select sum(%s) from `tab%s` where %s = %s and
qty = frappe.db.sql("""select sum(%s) from `tab%s` where %s = %s and
docstatus = 1 and parent != %s""" % (get_qty, curr_doctype, ref_tab_fname, '%s', '%s'),
(ref_tab_dn, curr_parent_name))
qty = qty and flt(qty[0][0]) or 0
# get total qty of ref doctype
#--------------------
max_qty = frappe.conn.sql("""select qty from `tab%s` where name = %s
max_qty = frappe.db.sql("""select qty from `tab%s` where name = %s
and docstatus = 1""" % (ref_doc_tname, '%s'), ref_tab_dn)
max_qty = max_qty and flt(max_qty[0][0]) or 0
return cstr(qty)+'~~~'+cstr(max_qty)
def check_for_stopped_status(self, doctype, docname):
stopped = frappe.conn.sql("""select name from `tab%s` where name = %s and
stopped = frappe.db.sql("""select name from `tab%s` where name = %s and
status = 'Stopped'""" % (doctype, '%s'), docname)
if stopped:
frappe.throw("One cannot do any transaction against %s : %s, it's status is 'Stopped'" %
@ -161,7 +161,7 @@ class DocType(BuyingController):
def check_docstatus(self, check, doctype, docname, detail_doctype = ''):
if check == 'Next':
submitted = frappe.conn.sql("""select t1.name from `tab%s` t1,`tab%s` t2
submitted = frappe.db.sql("""select t1.name from `tab%s` t1,`tab%s` t2
where t1.name = t2.parent and t2.prevdoc_docname = %s and t1.docstatus = 1"""
% (doctype, detail_doctype, '%s'), docname)
if submitted:
@ -169,7 +169,7 @@ class DocType(BuyingController):
+ _("has already been submitted."))
if check == 'Previous':
submitted = frappe.conn.sql("""select name from `tab%s`
submitted = frappe.db.sql("""select name from `tab%s`
where docstatus = 1 and name = %s""" % (doctype, '%s'), docname)
if not submitted:
frappe.throw(cstr(doctype) + ": " + cstr(submitted[0][0]) + _("not submitted"))

View File

@ -67,7 +67,7 @@ class DocType(BuyingController):
def get_schedule_dates(self):
for d in getlist(self.doclist, 'po_details'):
if d.prevdoc_detail_docname and not d.schedule_date:
d.schedule_date = frappe.conn.get_value("Material Request Item",
d.schedule_date = frappe.db.get_value("Material Request Item",
d.prevdoc_detail_docname, "schedule_date")
def get_last_purchase_rate(self):
@ -87,7 +87,7 @@ class DocType(BuyingController):
pc_obj = get_obj('Purchase Common')
for d in getlist(self.doclist, 'po_details'):
#1. Check if is_stock_item == 'Yes'
if frappe.conn.get_value("Item", d.item_code, "is_stock_item") == "Yes":
if frappe.db.get_value("Item", d.item_code, "is_stock_item") == "Yes":
# this happens when item is changed from non-stock to stock item
if not d.warehouse:
continue
@ -127,8 +127,8 @@ class DocType(BuyingController):
update_bin(args)
def check_modified_date(self):
mod_db = frappe.conn.sql("select modified from `tabPurchase Order` where name = '%s'" % self.doc.name)
date_diff = frappe.conn.sql("select TIMEDIFF('%s', '%s')" % ( mod_db[0][0],cstr(self.doc.modified)))
mod_db = frappe.db.sql("select modified from `tabPurchase Order` where name = '%s'" % self.doc.name)
date_diff = frappe.db.sql("select TIMEDIFF('%s', '%s')" % ( mod_db[0][0],cstr(self.doc.modified)))
if date_diff and date_diff[0][0]:
msgprint(cstr(self.doc.doctype) +" => "+ cstr(self.doc.name) +" has been modified. Please Refresh. ")
@ -137,7 +137,7 @@ class DocType(BuyingController):
def update_status(self, status):
self.check_modified_date()
# step 1:=> Set Status
frappe.conn.set(self.doc,'status',cstr(status))
frappe.db.set(self.doc,'status',cstr(status))
# step 2:=> Update Bin
self.update_bin(is_submit = (status == 'Submitted') and 1 or 0, is_stopped = 1)
@ -156,7 +156,7 @@ class DocType(BuyingController):
purchase_controller.update_last_purchase_rate(self, is_submit = 1)
frappe.conn.set(self.doc,'status','Submitted')
frappe.db.set(self.doc,'status','Submitted')
def on_cancel(self):
pc_obj = get_obj(dt = 'Purchase Common')
@ -166,12 +166,12 @@ class DocType(BuyingController):
pc_obj.check_docstatus(check = 'Next', doctype = 'Purchase Receipt', docname = self.doc.name, detail_doctype = 'Purchase Receipt Item')
# Check if Purchase Invoice has been submitted against current Purchase Order
submitted = frappe.conn.sql("select t1.name from `tabPurchase Invoice` t1,`tabPurchase Invoice Item` t2 where t1.name = t2.parent and t2.purchase_order = '%s' and t1.docstatus = 1" % self.doc.name)
submitted = frappe.db.sql("select t1.name from `tabPurchase Invoice` t1,`tabPurchase Invoice Item` t2 where t1.name = t2.parent and t2.purchase_order = '%s' and t1.docstatus = 1" % self.doc.name)
if submitted:
msgprint("Purchase Invoice : " + cstr(submitted[0][0]) + " has already been submitted !")
raise Exception
frappe.conn.set(self.doc,'status','Cancelled')
frappe.db.set(self.doc,'status','Cancelled')
self.update_prevdoc_status()
self.update_bin( is_submit = 0, is_stopped = 0)
pc_obj.update_last_purchase_rate(self, is_submit = 0)

View File

@ -30,7 +30,7 @@ class TestPurchaseOrder(unittest.TestCase):
pr_bean.insert()
def test_ordered_qty(self):
frappe.conn.sql("delete from tabBin")
frappe.db.sql("delete from tabBin")
from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt
@ -44,7 +44,7 @@ class TestPurchaseOrder(unittest.TestCase):
po.doclist[1].item_code = "_Test Item"
po.submit()
self.assertEquals(frappe.conn.get_value("Bin", {"item_code": "_Test Item",
self.assertEquals(frappe.db.get_value("Bin", {"item_code": "_Test Item",
"warehouse": "_Test Warehouse - _TC"}, "ordered_qty"), 10)
pr = make_purchase_receipt(po.doc.name)
@ -58,10 +58,10 @@ class TestPurchaseOrder(unittest.TestCase):
pr_bean.insert()
pr_bean.submit()
self.assertEquals(flt(frappe.conn.get_value("Bin", {"item_code": "_Test Item",
self.assertEquals(flt(frappe.db.get_value("Bin", {"item_code": "_Test Item",
"warehouse": "_Test Warehouse - _TC"}, "ordered_qty")), 6.0)
frappe.conn.set_value('Item', '_Test Item', 'tolerance', 50)
frappe.db.set_value('Item', '_Test Item', 'tolerance', 50)
pr1 = make_purchase_receipt(po.doc.name)
pr1[0].naming_series = "_T-Purchase Receipt-"
@ -71,7 +71,7 @@ class TestPurchaseOrder(unittest.TestCase):
pr1_bean.insert()
pr1_bean.submit()
self.assertEquals(flt(frappe.conn.get_value("Bin", {"item_code": "_Test Item",
self.assertEquals(flt(frappe.db.get_value("Bin", {"item_code": "_Test Item",
"warehouse": "_Test Warehouse - _TC"}, "ordered_qty")), 0.0)
def test_make_purchase_invoice(self):

View File

@ -13,7 +13,7 @@ class DocType:
def get_item_specification_details(self):
self.doclist = self.doc.clear_table(self.doclist, 'qa_specification_details')
specification = frappe.conn.sql("select specification, value from `tabItem Quality Inspection Parameter` \
specification = frappe.db.sql("select specification, value from `tabItem Quality Inspection Parameter` \
where parent = '%s' order by idx" % (self.doc.item_code))
for d in specification:
child = addchild(self.doc, 'qa_specification_details', 'Quality Inspection Reading', self.doclist)
@ -23,14 +23,14 @@ class DocType:
def on_submit(self):
if self.doc.purchase_receipt_no:
frappe.conn.sql("update `tabPurchase Receipt Item` t1, `tabPurchase Receipt` t2 set t1.qa_no = '%s', t2.modified = '%s' \
frappe.db.sql("update `tabPurchase Receipt Item` t1, `tabPurchase Receipt` t2 set t1.qa_no = '%s', t2.modified = '%s' \
where t1.parent = '%s' and t1.item_code = '%s' and t1.parent = t2.name" \
% (self.doc.name, self.doc.modified, self.doc.purchase_receipt_no, self.doc.item_code))
def on_cancel(self):
if self.doc.purchase_receipt_no:
frappe.conn.sql("update `tabPurchase Receipt Item` t1, `tabPurchase Receipt` t2 set t1.qa_no = '', t2.modified = '%s' \
frappe.db.sql("update `tabPurchase Receipt Item` t1, `tabPurchase Receipt` t2 set t1.qa_no = '', t2.modified = '%s' \
where t1.parent = '%s' and t1.item_code = '%s' and t1.parent = t2.name" \
% (self.doc.modified, self.doc.purchase_receipt_no, self.doc.item_code))
@ -44,6 +44,6 @@ def item_query(doctype, txt, searchfield, start, page_len, filters):
"start": start,
"page_len": page_len
})
return frappe.conn.sql("""select item_code from `tab%(from)s`
return frappe.db.sql("""select item_code from `tab%(from)s`
where parent='%(parent)s' and docstatus < 2 and item_code like '%%%(txt)s%%' %(mcond)s
order by item_code limit %(start)s, %(page_len)s""" % filters)

View File

@ -21,22 +21,22 @@ class DocType(TransactionBase):
supp_master_name = frappe.defaults.get_global_default('supp_master_name')
if supp_master_name == 'Supplier Name':
if frappe.conn.exists("Customer", self.doc.supplier_name):
if frappe.db.exists("Customer", self.doc.supplier_name):
frappe.msgprint(_("A Customer exists with same name"), raise_exception=1)
self.doc.name = self.doc.supplier_name
else:
self.doc.name = make_autoname(self.doc.naming_series + '.#####')
def update_address(self):
frappe.conn.sql("""update `tabAddress` set supplier_name=%s, modified=NOW()
frappe.db.sql("""update `tabAddress` set supplier_name=%s, modified=NOW()
where supplier=%s""", (self.doc.supplier_name, self.doc.name))
def update_contact(self):
frappe.conn.sql("""update `tabContact` set supplier_name=%s, modified=NOW()
frappe.db.sql("""update `tabContact` set supplier_name=%s, modified=NOW()
where supplier=%s""", (self.doc.supplier_name, self.doc.name))
def update_credit_days_limit(self):
frappe.conn.sql("""update tabAccount set credit_days = %s where name = %s""",
frappe.db.sql("""update tabAccount set credit_days = %s where name = %s""",
(cint(self.doc.credit_days), self.doc.name + " - " + self.get_company_abbr()))
def on_update(self):
@ -53,7 +53,7 @@ class DocType(TransactionBase):
self.update_credit_days_limit()
def get_company_abbr(self):
return frappe.conn.sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0]
return frappe.db.sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0]
def validate(self):
#validation for Naming Series mandatory field...
@ -63,24 +63,24 @@ class DocType(TransactionBase):
def get_contacts(self,nm):
if nm:
contact_details =frappe.conn.convert_to_lists(frappe.conn.sql("select name, CONCAT(IFNULL(first_name,''),' ',IFNULL(last_name,'')),contact_no,email_id from `tabContact` where supplier = '%s'"%nm))
contact_details =frappe.db.convert_to_lists(frappe.db.sql("select name, CONCAT(IFNULL(first_name,''),' ',IFNULL(last_name,'')),contact_no,email_id from `tabContact` where supplier = '%s'"%nm))
return contact_details
else:
return ''
def delete_supplier_address(self):
for rec in frappe.conn.sql("select * from `tabAddress` where supplier=%s", (self.doc.name,), as_dict=1):
frappe.conn.sql("delete from `tabAddress` where name=%s",(rec['name']))
for rec in frappe.db.sql("select * from `tabAddress` where supplier=%s", (self.doc.name,), as_dict=1):
frappe.db.sql("delete from `tabAddress` where name=%s",(rec['name']))
def delete_supplier_contact(self):
for contact in frappe.conn.sql_list("""select name from `tabContact`
for contact in frappe.db.sql_list("""select name from `tabContact`
where supplier=%s""", self.doc.name):
frappe.delete_doc("Contact", contact)
def delete_supplier_account(self):
"""delete supplier's ledger if exist and check balance before deletion"""
acc = frappe.conn.sql("select name from `tabAccount` where master_type = 'Supplier' \
acc = frappe.db.sql("select name from `tabAccount` where master_type = 'Supplier' \
and master_name = %s and docstatus < 2", self.doc.name)
if acc:
frappe.delete_doc('Account', acc[0][0])
@ -97,13 +97,13 @@ class DocType(TransactionBase):
def after_rename(self, olddn, newdn, merge=False):
set_field = ''
if frappe.defaults.get_global_default('supp_master_name') == 'Supplier Name':
frappe.conn.set(self.doc, "supplier_name", newdn)
frappe.db.set(self.doc, "supplier_name", newdn)
self.update_contact()
set_field = ", supplier_name=%(newdn)s"
self.update_supplier_address(newdn, set_field)
def update_supplier_address(self, newdn, set_field):
frappe.conn.sql("""update `tabAddress` set address_title=%(newdn)s
frappe.db.sql("""update `tabAddress` set address_title=%(newdn)s
{set_field} where supplier=%(newdn)s"""\
.format(set_field=set_field), ({"newdn": newdn}))
@ -114,14 +114,14 @@ def get_dashboard_info(supplier):
out = {}
for doctype in ["Supplier Quotation", "Purchase Order", "Purchase Receipt", "Purchase Invoice"]:
out[doctype] = frappe.conn.get_value(doctype,
out[doctype] = frappe.db.get_value(doctype,
{"supplier": supplier, "docstatus": ["!=", 2] }, "count(*)")
billing = frappe.conn.sql("""select sum(grand_total), sum(outstanding_amount)
billing = frappe.db.sql("""select sum(grand_total), sum(outstanding_amount)
from `tabPurchase Invoice`
where supplier=%s
and docstatus = 1
and fiscal_year = %s""", (supplier, frappe.conn.get_default("fiscal_year")))
and fiscal_year = %s""", (supplier, frappe.db.get_default("fiscal_year")))
out["total_billing"] = billing[0][0]
out["total_unpaid"] = billing[0][1]

View File

@ -26,10 +26,10 @@ class DocType(BuyingController):
self.validate_uom_is_integer("uom", "qty")
def on_submit(self):
frappe.conn.set(self.doc, "status", "Submitted")
frappe.db.set(self.doc, "status", "Submitted")
def on_cancel(self):
frappe.conn.set(self.doc, "status", "Cancelled")
frappe.db.set(self.doc, "status", "Cancelled")
def on_trash(self):
pass

View File

@ -44,7 +44,7 @@ class AccountsController(TransactionBase):
def validate_for_freezed_account(self):
for fieldname in ["customer", "supplier"]:
if self.meta.get_field(fieldname) and self.doc.fields.get(fieldname):
accounts = frappe.conn.get_values("Account",
accounts = frappe.db.get_values("Account",
{"master_type": fieldname.title(), "master_name": self.doc.fields[fieldname],
"company": self.doc.company}, "name")
if accounts:
@ -60,7 +60,7 @@ class AccountsController(TransactionBase):
fieldname = "selling_price_list" if buying_or_selling.lower() == "selling" \
else "buying_price_list"
if self.meta.get_field(fieldname) and self.doc.fields.get(fieldname):
self.doc.price_list_currency = frappe.conn.get_value("Price List",
self.doc.price_list_currency = frappe.db.get_value("Price List",
self.doc.fields.get(fieldname), "currency")
if self.doc.price_list_currency == company_currency:
@ -82,7 +82,7 @@ class AccountsController(TransactionBase):
def get_exchange_rate(self, from_currency, to_currency):
exchange = "%s-%s" % (from_currency, to_currency)
return flt(frappe.conn.get_value("Currency Exchange", exchange, "exchange_rate"))
return flt(frappe.db.get_value("Currency Exchange", exchange, "exchange_rate"))
def set_missing_item_details(self):
"""set missing item values"""
@ -106,7 +106,7 @@ class AccountsController(TransactionBase):
if not self.doc.fields.get(tax_master_field):
# get the default tax master
self.doc.fields[tax_master_field] = \
frappe.conn.get_value(tax_master_doctype, {"is_default": 1})
frappe.db.get_value(tax_master_doctype, {"is_default": 1})
self.append_taxes_from_master(tax_parentfield, tax_master_field, tax_master_doctype)
@ -393,11 +393,11 @@ class AccountsController(TransactionBase):
def clear_unallocated_advances(self, childtype, parentfield):
self.doclist.remove_items({"parentfield": parentfield, "allocated_amount": ["in", [0, None, ""]]})
frappe.conn.sql("""delete from `tab%s` where parentfield=%s and parent = %s
frappe.db.sql("""delete from `tab%s` where parentfield=%s and parent = %s
and ifnull(allocated_amount, 0) = 0""" % (childtype, '%s', '%s'), (parentfield, self.doc.name))
def get_advances(self, account_head, child_doctype, parentfield, dr_or_cr):
res = frappe.conn.sql("""select t1.name as jv_no, t1.remark,
res = frappe.db.sql("""select t1.name as jv_no, t1.remark,
t2.%s as amount, t2.name as jv_detail_no
from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2
where t1.name = t2.parent and t2.account = %s and t2.is_advance = 'Yes'
@ -426,13 +426,13 @@ class AccountsController(TransactionBase):
for item in self.doclist.get({"parentfield": "entries"}):
if item.fields.get(item_ref_dn):
ref_amt = flt(frappe.conn.get_value(ref_dt + " Item",
ref_amt = flt(frappe.db.get_value(ref_dt + " Item",
item.fields[item_ref_dn], based_on), self.precision(based_on, item))
if not ref_amt:
frappe.msgprint(_("As amount for item") + ": " + item.item_code + _(" in ") +
ref_dt + _(" is zero, system will not check for over-billed"))
else:
already_billed = frappe.conn.sql("""select sum(%s) from `tab%s`
already_billed = frappe.db.sql("""select sum(%s) from `tab%s`
where %s=%s and docstatus=1 and parent != %s""" %
(based_on, self.tname, item_ref_dn, '%s', '%s'),
(item.fields[item_ref_dn], self.doc.name))[0][0]
@ -468,7 +468,7 @@ class AccountsController(TransactionBase):
item_codes = list(set(item.item_code for item in
self.doclist.get({"parentfield": self.fname})))
if item_codes:
stock_items = [r[0] for r in frappe.conn.sql("""select name
stock_items = [r[0] for r in frappe.db.sql("""select name
from `tabItem` where name in (%s) and is_stock_item='Yes'""" % \
(", ".join((["%s"]*len(item_codes))),), item_codes)]
@ -477,12 +477,12 @@ class AccountsController(TransactionBase):
@property
def company_abbr(self):
if not hasattr(self, "_abbr"):
self._abbr = frappe.conn.get_value("Company", self.doc.company, "abbr")
self._abbr = frappe.db.get_value("Company", self.doc.company, "abbr")
return self._abbr
def check_credit_limit(self, account):
total_outstanding = frappe.conn.sql("""
total_outstanding = frappe.db.sql("""
select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
from `tabGL Entry` where account = %s""", account)
@ -493,4 +493,4 @@ class AccountsController(TransactionBase):
@frappe.whitelist()
def get_tax_rate(account_head):
return frappe.conn.get_value("Account", account_head, "tax_rate")
return frappe.db.get_value("Account", account_head, "tax_rate")

View File

@ -18,7 +18,7 @@ class BuyingController(StockController):
def validate(self):
super(BuyingController, self).validate()
if self.doc.supplier and not self.doc.supplier_name:
self.doc.supplier_name = frappe.conn.get_value("Supplier",
self.doc.supplier_name = frappe.db.get_value("Supplier",
self.doc.supplier, "supplier_name")
self.is_item_table_empty()
self.validate_stock_or_nonstock_items()
@ -41,7 +41,7 @@ class BuyingController(StockController):
def set_supplier_from_item_default(self):
if self.meta.get_field("supplier") and not self.doc.supplier:
for d in self.doclist.get({"doctype": self.tname}):
supplier = frappe.conn.get_value("Item", d.item_code, "default_supplier")
supplier = frappe.db.get_value("Item", d.item_code, "default_supplier")
if supplier:
self.doc.supplier = supplier
break
@ -198,7 +198,7 @@ class BuyingController(StockController):
self.round_floats_in(item)
item.conversion_factor = item.conversion_factor or flt(frappe.conn.get_value(
item.conversion_factor = item.conversion_factor or flt(frappe.db.get_value(
"UOM Conversion Detail", {"parent": item.item_code, "uom": item.uom},
"conversion_factor")) or 1
qty_in_stock_uom = flt(item.qty * item.conversion_factor)
@ -256,7 +256,7 @@ class BuyingController(StockController):
d.rm_supp_cost = raw_materials_cost
def get_items_from_default_bom(self, item_code):
bom_items = frappe.conn.sql("""select t2.item_code, t2.qty_consumed_per_unit,
bom_items = frappe.db.sql("""select t2.item_code, t2.qty_consumed_per_unit,
t2.rate, t2.stock_uom, t2.name, t2.description
from `tabBOM` t1, `tabBOM Item` t2
where t2.parent = t1.name and t1.item = %s and t1.is_default = 1
@ -273,7 +273,7 @@ class BuyingController(StockController):
item_codes = list(set(item.item_code for item in
self.doclist.get({"parentfield": self.fname})))
if item_codes:
self._sub_contracted_items = [r[0] for r in frappe.conn.sql("""select name
self._sub_contracted_items = [r[0] for r in frappe.db.sql("""select name
from `tabItem` where name in (%s) and is_sub_contracted_item='Yes'""" % \
(", ".join((["%s"]*len(item_codes))),), item_codes)]
@ -286,7 +286,7 @@ class BuyingController(StockController):
item_codes = list(set(item.item_code for item in
self.doclist.get({"parentfield": self.fname})))
if item_codes:
self._purchase_items = [r[0] for r in frappe.conn.sql("""select name
self._purchase_items = [r[0] for r in frappe.db.sql("""select name
from `tabItem` where name in (%s) and is_purchase_item='Yes'""" % \
(", ".join((["%s"]*len(item_codes))),), item_codes)]

View File

@ -25,7 +25,7 @@ def get_filters_cond(doctype, filters, conditions):
# searches for active employees
def employee_query(doctype, txt, searchfield, start, page_len, filters):
return frappe.conn.sql("""select name, employee_name from `tabEmployee`
return frappe.db.sql("""select name, employee_name from `tabEmployee`
where status = 'Active'
and docstatus < 2
and (%(key)s like "%(txt)s"
@ -40,7 +40,7 @@ def employee_query(doctype, txt, searchfield, start, page_len, filters):
# searches for leads which are not converted
def lead_query(doctype, txt, searchfield, start, page_len, filters):
return frappe.conn.sql("""select name, lead_name, company_name from `tabLead`
return frappe.db.sql("""select name, lead_name, company_name from `tabLead`
where docstatus < 2
and ifnull(status, '') != 'Converted'
and (%(key)s like "%(txt)s"
@ -66,7 +66,7 @@ def customer_query(doctype, txt, searchfield, start, page_len, filters):
fields = ", ".join(fields)
return frappe.conn.sql("""select %(field)s from `tabCustomer`
return frappe.db.sql("""select %(field)s from `tabCustomer`
where docstatus < 2
and (%(key)s like "%(txt)s"
or customer_name like "%(txt)s")
@ -88,7 +88,7 @@ def supplier_query(doctype, txt, searchfield, start, page_len, filters):
fields = ["name", "supplier_name", "supplier_type"]
fields = ", ".join(fields)
return frappe.conn.sql("""select %(field)s from `tabSupplier`
return frappe.db.sql("""select %(field)s from `tabSupplier`
where docstatus < 2
and (%(key)s like "%(txt)s"
or supplier_name like "%(txt)s")
@ -102,7 +102,7 @@ def supplier_query(doctype, txt, searchfield, start, page_len, filters):
'page_len': page_len})
def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
return frappe.conn.sql("""select name, parent_account, debit_or_credit
return frappe.db.sql("""select name, parent_account, debit_or_credit
from tabAccount
where tabAccount.docstatus!=2
and (account_type in (%s) or
@ -121,7 +121,7 @@ def item_query(doctype, txt, searchfield, start, page_len, filters):
conditions = []
return frappe.conn.sql("""select tabItem.name,
return frappe.db.sql("""select tabItem.name,
if(length(tabItem.item_name) > 40,
concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name,
if(length(tabItem.description) > 40, \
@ -145,7 +145,7 @@ def item_query(doctype, txt, searchfield, start, page_len, filters):
def bom(doctype, txt, searchfield, start, page_len, filters):
conditions = []
return frappe.conn.sql("""select tabBOM.name, tabBOM.item
return frappe.db.sql("""select tabBOM.name, tabBOM.item
from tabBOM
where tabBOM.docstatus=1
and tabBOM.is_active=1
@ -160,7 +160,7 @@ def get_project_name(doctype, txt, searchfield, start, page_len, filters):
if filters['customer']:
cond = '(`tabProject`.customer = "' + filters['customer'] + '" or ifnull(`tabProject`.customer,"")="") and'
return frappe.conn.sql("""select `tabProject`.name from `tabProject`
return frappe.db.sql("""select `tabProject`.name from `tabProject`
where `tabProject`.status not in ("Completed", "Cancelled")
and %(cond)s `tabProject`.name like "%(txt)s" %(mcond)s
order by `tabProject`.name asc
@ -168,7 +168,7 @@ def get_project_name(doctype, txt, searchfield, start, page_len, filters):
'mcond':get_match_cond(doctype, searchfield),'start': start, 'page_len': page_len})
def get_delivery_notes_to_be_billed(doctype, txt, searchfield, start, page_len, filters):
return frappe.conn.sql("""select `tabDelivery Note`.name, `tabDelivery Note`.customer_name
return frappe.db.sql("""select `tabDelivery Note`.name, `tabDelivery Note`.customer_name
from `tabDelivery Note`
where `tabDelivery Note`.`%(key)s` like %(txt)s and
`tabDelivery Note`.docstatus = 1 %(fcond)s and
@ -189,7 +189,7 @@ def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
from erpnext.controllers.queries import get_match_cond
if filters.has_key('warehouse'):
return frappe.conn.sql("""select batch_no from `tabStock Ledger Entry` sle
return frappe.db.sql("""select batch_no from `tabStock Ledger Entry` sle
where item_code = '%(item_code)s'
and warehouse = '%(warehouse)s'
and batch_no like '%(txt)s'
@ -205,7 +205,7 @@ def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
'txt': "%%%s%%" % txt, 'mcond':get_match_cond(doctype, searchfield),
'start': start, 'page_len': page_len})
else:
return frappe.conn.sql("""select name from tabBatch
return frappe.db.sql("""select name from tabBatch
where docstatus != 2
and item = '%(item_code)s'
and (ifnull(expiry_date, '')='' or expiry_date >= '%(posting_date)s')

View File

@ -20,7 +20,7 @@ class SellingController(StockController):
check_active_sales_items(self)
def get_sender(self, comm):
return frappe.conn.get_value('Sales Email Settings', None, 'email_id')
return frappe.db.get_value('Sales Email Settings', None, 'email_id')
def set_missing_values(self, for_validate=False):
super(SellingController, self).set_missing_values(for_validate)
@ -73,7 +73,7 @@ class SellingController(StockController):
from frappe.utils import money_in_words
company_currency = get_company_currency(self.doc.company)
disable_rounded_total = cint(frappe.conn.get_value("Global Defaults", None,
disable_rounded_total = cint(frappe.db.get_value("Global Defaults", None,
"disable_rounded_total"))
if self.meta.get_field("in_words"):
@ -266,10 +266,10 @@ class SellingController(StockController):
_("must be one of") + ": " + comma_or(valid_types), raise_exception=True)
def check_credit(self, grand_total):
customer_account = frappe.conn.get_value("Account", {"company": self.doc.company,
customer_account = frappe.db.get_value("Account", {"company": self.doc.company,
"master_name": self.doc.customer}, "name")
if customer_account:
total_outstanding = frappe.conn.sql("""select
total_outstanding = frappe.db.sql("""select
sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
from `tabGL Entry` where account = %s""", customer_account)
total_outstanding = total_outstanding[0][0] if total_outstanding else 0
@ -280,7 +280,7 @@ class SellingController(StockController):
def validate_max_discount(self):
for d in self.doclist.get({"parentfield": self.fname}):
discount = flt(frappe.conn.get_value("Item", d.item_code, "max_discount"))
discount = flt(frappe.db.get_value("Item", d.item_code, "max_discount"))
if discount and flt(d.discount_percentage) > discount:
frappe.throw(_("You cannot give more than ") + cstr(discount) + "% " +
@ -293,7 +293,7 @@ class SellingController(StockController):
reserved_qty_for_main_item = 0
if self.doc.doctype == "Sales Order":
if (frappe.conn.get_value("Item", d.item_code, "is_stock_item") == 'Yes' or
if (frappe.db.get_value("Item", d.item_code, "is_stock_item") == 'Yes' or
self.has_sales_bom(d.item_code)) and not d.warehouse:
frappe.throw(_("Please enter Reserved Warehouse for item ") +
d.item_code + _(" as it is stock Item or packing item"))
@ -344,18 +344,18 @@ class SellingController(StockController):
return il
def has_sales_bom(self, item_code):
return frappe.conn.sql("""select name from `tabSales BOM`
return frappe.db.sql("""select name from `tabSales BOM`
where new_item_code=%s and docstatus != 2""", item_code)
def get_already_delivered_qty(self, dn, so, so_detail):
qty = frappe.conn.sql("""select sum(qty) from `tabDelivery Note Item`
qty = frappe.db.sql("""select sum(qty) from `tabDelivery Note Item`
where prevdoc_detail_docname = %s and docstatus = 1
and against_sales_order = %s
and parent != %s""", (so_detail, so, dn))
return qty and flt(qty[0][0]) or 0.0
def get_so_qty_and_warehouse(self, so_detail):
so_item = frappe.conn.sql("""select qty, warehouse from `tabSales Order Item`
so_item = frappe.db.sql("""select qty, warehouse from `tabSales Order Item`
where name = %s and docstatus = 1""", so_detail, as_dict=1)
so_qty = so_item and flt(so_item[0]["qty"]) or 0.0
so_warehouse = so_item and so_item[0]["warehouse"] or ""
@ -364,7 +364,7 @@ class SellingController(StockController):
def check_stop_sales_order(self, ref_fieldname):
for d in self.doclist.get({"parentfield": self.fname}):
if d.fields.get(ref_fieldname):
status = frappe.conn.get_value("Sales Order", d.fields[ref_fieldname], "status")
status = frappe.db.get_value("Sales Order", d.fields[ref_fieldname], "status")
if status == "Stopped":
frappe.throw(self.doc.doctype +
_(" can not be created/modified against stopped Sales Order ") +
@ -373,11 +373,11 @@ class SellingController(StockController):
def check_active_sales_items(obj):
for d in obj.doclist.get({"parentfield": obj.fname}):
if d.item_code:
item = frappe.conn.sql("""select docstatus, is_sales_item,
item = frappe.db.sql("""select docstatus, is_sales_item,
is_service_item, income_account from tabItem where name = %s""",
d.item_code, as_dict=True)[0]
if item.is_sales_item == 'No' and item.is_service_item == 'No':
frappe.throw(_("Item is neither Sales nor Service Item") + ": " + d.item_code)
if d.income_account and not item.income_account:
frappe.conn.set_value("Item", d.item_code, "income_account",
frappe.db.set_value("Item", d.item_code, "income_account",
d.income_account)

View File

@ -85,7 +85,7 @@ class StatusUpdater(DocListController):
break
if update:
frappe.conn.set_value(self.doc.doctype, self.doc.name, "status", self.doc.status)
frappe.db.set_value(self.doc.doctype, self.doc.name, "status", self.doc.status)
def on_communication(self):
self.communication_set = True
@ -118,7 +118,7 @@ class StatusUpdater(DocListController):
args['name'] = d.fields[args['join_field']]
# get all qty where qty > target_field
item = frappe.conn.sql("""select item_code, `%(target_ref_field)s`,
item = frappe.db.sql("""select item_code, `%(target_ref_field)s`,
`%(target_field)s`, parenttype, parent from `tab%(target_dt)s`
where `%(target_ref_field)s` < `%(target_field)s`
and name="%(name)s" and docstatus=1""" % args, as_dict=1)
@ -204,7 +204,7 @@ class StatusUpdater(DocListController):
and (docstatus=1))""" % args
if args['detail_id']:
frappe.conn.sql("""update `tab%(target_dt)s`
frappe.db.sql("""update `tab%(target_dt)s`
set %(target_field)s = (select sum(%(source_field)s)
from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s"
and (docstatus=1 %(cond)s)) %(second_source_condition)s
@ -217,7 +217,7 @@ class StatusUpdater(DocListController):
args['name'] = name
# update percent complete in the parent table
frappe.conn.sql("""update `tab%(target_parent_dt)s`
frappe.db.sql("""update `tab%(target_parent_dt)s`
set %(target_parent_field)s = (select sum(if(%(target_ref_field)s >
ifnull(%(target_field)s, 0), %(target_field)s,
%(target_ref_field)s))/sum(%(target_ref_field)s)*100
@ -226,7 +226,7 @@ class StatusUpdater(DocListController):
# update field
if args.get('status_field'):
frappe.conn.sql("""update `tab%(target_parent_dt)s`
frappe.db.sql("""update `tab%(target_parent_dt)s`
set %(status_field)s = if(ifnull(%(target_parent_field)s,0)<0.001,
'Not %(keyword)s', if(%(target_parent_field)s>=99.99,
'Fully %(keyword)s', 'Partly %(keyword)s'))
@ -236,7 +236,7 @@ class StatusUpdater(DocListController):
def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
ref_fieldname = ref_dt.lower().replace(" ", "_")
zero_amount_refdoc = []
all_zero_amount_refdoc = frappe.conn.sql_list("""select name from `tab%s`
all_zero_amount_refdoc = frappe.db.sql_list("""select name from `tab%s`
where docstatus=1 and net_total = 0""" % ref_dt)
for item in self.doclist.get({"parentfield": "entries"}):
@ -250,16 +250,16 @@ class StatusUpdater(DocListController):
def update_biling_status(self, zero_amount_refdoc, ref_dt, ref_fieldname):
for ref_dn in zero_amount_refdoc:
ref_doc_qty = flt(frappe.conn.sql("""select sum(ifnull(qty, 0)) from `tab%s Item`
ref_doc_qty = flt(frappe.db.sql("""select sum(ifnull(qty, 0)) from `tab%s Item`
where parent=%s""" % (ref_dt, '%s'), (ref_dn))[0][0])
billed_qty = flt(frappe.conn.sql("""select sum(ifnull(qty, 0))
billed_qty = flt(frappe.db.sql("""select sum(ifnull(qty, 0))
from `tab%s Item` where %s=%s and docstatus=1""" %
(self.doc.doctype, ref_fieldname, '%s'), (ref_dn))[0][0])
per_billed = ((ref_doc_qty if billed_qty > ref_doc_qty else billed_qty)\
/ ref_doc_qty)*100
frappe.conn.set_value(ref_dt, ref_dn, "per_billed", per_billed)
frappe.db.set_value(ref_dt, ref_dn, "per_billed", per_billed)
from frappe.model.meta import has_field
if has_field(ref_dt, "billing_status"):
@ -267,7 +267,7 @@ class StatusUpdater(DocListController):
elif per_billed >= 99.99: billing_status = "Fully Billed"
else: billing_status = "Partly Billed"
frappe.conn.set_value(ref_dt, ref_dn, "billing_status", billing_status)
frappe.db.set_value(ref_dt, ref_dn, "billing_status", billing_status)
def get_tolerance_for(item_code, item_tolerance={}, global_tolerance=None):
"""
@ -276,11 +276,11 @@ def get_tolerance_for(item_code, item_tolerance={}, global_tolerance=None):
if item_tolerance.get(item_code):
return item_tolerance[item_code], item_tolerance, global_tolerance
tolerance = flt(frappe.conn.get_value('Item',item_code,'tolerance') or 0)
tolerance = flt(frappe.db.get_value('Item',item_code,'tolerance') or 0)
if not tolerance:
if global_tolerance == None:
global_tolerance = flt(frappe.conn.get_value('Global Defaults', None,
global_tolerance = flt(frappe.db.get_value('Global Defaults', None,
'tolerance'))
tolerance = global_tolerance

View File

@ -84,14 +84,14 @@ class StockController(AccountsController):
def get_stock_ledger_details(self):
stock_ledger = {}
for sle in frappe.conn.sql("""select warehouse, stock_value_difference, voucher_detail_no
for sle in frappe.db.sql("""select warehouse, stock_value_difference, voucher_detail_no
from `tabStock Ledger Entry` where voucher_type=%s and voucher_no=%s""",
(self.doc.doctype, self.doc.name), as_dict=True):
stock_ledger.setdefault(sle.voucher_detail_no, []).append(sle)
return stock_ledger
def get_warehouse_account(self):
warehouse_account = dict(frappe.conn.sql("""select master_name, name from tabAccount
warehouse_account = dict(frappe.db.sql("""select master_name, name from tabAccount
where account_type = 'Warehouse' and ifnull(master_name, '') != ''"""))
return warehouse_account
@ -134,7 +134,7 @@ class StockController(AccountsController):
else:
condition = ""
for d in frappe.conn.sql("""select distinct sle.voucher_type, sle.voucher_no
for d in frappe.db.sql("""select distinct sle.voucher_type, sle.voucher_no
from `tabStock Ledger Entry` sle
where timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s) %s
order by timestamp(sle.posting_date, sle.posting_time) asc, name asc""" %
@ -147,7 +147,7 @@ class StockController(AccountsController):
def get_voucherwise_gl_entries(self, future_stock_vouchers):
gl_entries = {}
if future_stock_vouchers:
for d in frappe.conn.sql("""select * from `tabGL Entry`
for d in frappe.db.sql("""select * from `tabGL Entry`
where posting_date >= %s and voucher_no in (%s)""" %
('%s', ', '.join(['%s']*len(future_stock_vouchers))),
tuple([self.doc.posting_date] + [d[1] for d in future_stock_vouchers]), as_dict=1):
@ -156,7 +156,7 @@ class StockController(AccountsController):
return gl_entries
def delete_gl_entries(self, voucher_type, voucher_no):
frappe.conn.sql("""delete from `tabGL Entry`
frappe.db.sql("""delete from `tabGL Entry`
where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
def make_adjustment_entry(self, expected_gle, voucher_obj):
@ -236,7 +236,7 @@ class StockController(AccountsController):
item_list, warehouse_list = self.get_distinct_item_warehouse()
if item_list and warehouse_list:
res = frappe.conn.sql("""select item_code, voucher_type, voucher_no,
res = frappe.db.sql("""select item_code, voucher_type, voucher_no,
voucher_detail_no, posting_date, posting_time, stock_value,
warehouse, actual_qty as qty from `tabStock Ledger Entry`
where company = %s and item_code in (%s) and warehouse in (%s)
@ -264,6 +264,6 @@ class StockController(AccountsController):
return list(set(item_list)), list(set(warehouse_list))
def make_cancel_gl_entries(self):
if frappe.conn.sql("""select name from `tabGL Entry` where voucher_type=%s
if frappe.db.sql("""select name from `tabGL Entry` where voucher_type=%s
and voucher_no=%s""", (self.doc.doctype, self.doc.name)):
self.make_gl_entries()

View File

@ -58,7 +58,7 @@ def get_data(filters, conditions):
inc = 2
else :
inc = 1
data1 = frappe.conn.sql(""" select %s from `tab%s` t1, `tab%s Item` t2 %s
data1 = frappe.db.sql(""" select %s from `tab%s` t1, `tab%s Item` t2 %s
where t2.parent = t1.name and t1.company = %s and t1.fiscal_year = %s and
t1.docstatus = 1 %s
group by %s
@ -73,7 +73,7 @@ def get_data(filters, conditions):
data.append(dt)
#to get distinct value of col specified by group_by in filter
row = frappe.conn.sql("""select DISTINCT(%s) from `tab%s` t1, `tab%s Item` t2 %s
row = frappe.db.sql("""select DISTINCT(%s) from `tab%s` t1, `tab%s Item` t2 %s
where t2.parent = t1.name and t1.company = %s and t1.fiscal_year = %s
and t1.docstatus = 1 and %s = %s
""" %
@ -85,7 +85,7 @@ def get_data(filters, conditions):
des = ['' for q in range(len(conditions["columns"]))]
#get data for group_by filter
row1 = frappe.conn.sql(""" select %s , %s from `tab%s` t1, `tab%s Item` t2 %s
row1 = frappe.db.sql(""" select %s , %s from `tab%s` t1, `tab%s Item` t2 %s
where t2.parent = t1.name and t1.company = %s and t1.fiscal_year = %s
and t1.docstatus = 1 and %s = %s and %s = %s
""" %
@ -101,7 +101,7 @@ def get_data(filters, conditions):
data.append(des)
else:
data = frappe.conn.sql(""" select %s from `tab%s` t1, `tab%s Item` t2 %s
data = frappe.db.sql(""" select %s from `tab%s` t1, `tab%s Item` t2 %s
where t2.parent = t1.name and t1.company = %s and t1.fiscal_year = %s and
t1.docstatus = 1 %s
group by %s
@ -156,7 +156,7 @@ def get_period_date_ranges(period, fiscal_year=None, year_start_date=None):
from dateutil.relativedelta import relativedelta
if not year_start_date:
year_start_date, year_end_date = frappe.conn.get_value("Fiscal Year",
year_start_date, year_end_date = frappe.db.get_value("Fiscal Year",
fiscal_year, ["year_start_date", "year_end_date"])
increment = {

View File

@ -64,11 +64,11 @@ def make_feed(feedtype, doctype, name, owner, subject, color):
if feedtype in ('Login', 'Comment', 'Assignment'):
# delete old login, comment feed
frappe.conn.sql("""delete from tabFeed where
frappe.db.sql("""delete from tabFeed where
datediff(curdate(), creation) > 7 and doc_type in ('Comment', 'Login', 'Assignment')""")
else:
# one feed per item
frappe.conn.sql("""delete from tabFeed
frappe.db.sql("""delete from tabFeed
where doc_type=%s and doc_name=%s
and ifnull(feed_type,'') != 'Comment'""", (doctype, name))

View File

@ -15,8 +15,8 @@ class DocType:
self.doc, self.doclist = d, dl
def on_doctype_update():
if not frappe.conn.sql("""show index from `tabFeed`
if not frappe.db.sql("""show index from `tabFeed`
where Key_name="feed_doctype_docname_index" """):
frappe.conn.commit()
frappe.conn.sql("""alter table `tabFeed`
frappe.db.commit()
frappe.db.sql("""alter table `tabFeed`
add index feed_doctype_docname_index(doc_type, doc_name)""")

View File

@ -7,7 +7,7 @@ import frappe
@frappe.whitelist()
def get_feed(arg=None):
"""get feed"""
return frappe.conn.sql("""select
return frappe.db.sql("""select
distinct t1.name, t1.feed_type, t1.doc_type, t1.doc_name, t1.subject, t1.owner,
t1.modified
from tabFeed t1, tabDocPerm t2

View File

@ -22,7 +22,7 @@ class DocType:
self.calculate_total()
def get_employee_name(self):
emp_nm = frappe.conn.sql("select employee_name from `tabEmployee` where name=%s", self.doc.employee)
emp_nm = frappe.db.sql("select employee_name from `tabEmployee` where name=%s", self.doc.employee)
emp_nm= emp_nm and emp_nm[0][0] or ''
self.doc.employee_name = emp_nm
return emp_nm
@ -33,7 +33,7 @@ class DocType:
raise Exception
def validate_existing_appraisal(self):
chk = frappe.conn.sql("""select name from `tabAppraisal` where employee=%s
chk = frappe.db.sql("""select name from `tabAppraisal` where employee=%s
and (status='Submitted' or status='Completed')
and ((start_date>=%s and start_date<=%s)
or (end_date>=%s and end_date<=%s))""",(self.doc.employee,self.doc.start_date,self.doc.end_date,self.doc.start_date,self.doc.end_date))
@ -55,17 +55,17 @@ class DocType:
msgprint("Total weightage assigned should be 100%. It is :" + str(total_w) + "%",
raise_exception=1)
if frappe.conn.get_value("Employee", self.doc.employee, "user_id") != \
if frappe.db.get_value("Employee", self.doc.employee, "user_id") != \
frappe.session.user and total == 0:
msgprint("Total can't be zero. You must atleast give some points!", raise_exception=1)
self.doc.total_score = total
def on_submit(self):
frappe.conn.set(self.doc, 'status', 'Submitted')
frappe.db.set(self.doc, 'status', 'Submitted')
def on_cancel(self):
frappe.conn.set(self.doc, 'status', 'Cancelled')
frappe.db.set(self.doc, 'status', 'Cancelled')
@frappe.whitelist()
def fetch_appraisal_template(source_name, target_doclist=None):

View File

@ -14,7 +14,7 @@ class DocType:
self.doclist = doclist
def validate_duplicate_record(self):
res = frappe.conn.sql("""select name from `tabAttendance` where employee = %s and att_date = %s
res = frappe.db.sql("""select name from `tabAttendance` where employee = %s and att_date = %s
and name != %s and docstatus = 1""",
(self.doc.employee, self.doc.att_date, self.doc.name))
if res:
@ -23,7 +23,7 @@ class DocType:
def check_leave_record(self):
if self.doc.status == 'Present':
leave = frappe.conn.sql("""select name from `tabLeave Application`
leave = frappe.db.sql("""select name from `tabLeave Application`
where employee = %s and %s between from_date and to_date and status = 'Approved'
and docstatus = 1""", (self.doc.employee, self.doc.att_date))
@ -41,7 +41,7 @@ class DocType:
msgprint(_("Attendance can not be marked for future dates"), raise_exception=1)
def validate_employee(self):
emp = frappe.conn.sql("select name from `tabEmployee` where name = %s and status = 'Active'",
emp = frappe.db.sql("select name from `tabEmployee` where name = %s and status = 'Active'",
self.doc.employee)
if not emp:
msgprint(_("Employee: ") + self.doc.employee +
@ -58,5 +58,5 @@ class DocType:
def on_update(self):
# this is done because sometimes user entered wrong employee name
# while uploading employee attendance
employee_name = frappe.conn.get_value("Employee", self.doc.employee, "employee_name")
frappe.conn.set(self.doc, 'employee_name', employee_name)
employee_name = frappe.db.get_value("Employee", self.doc.employee, "employee_name")
frappe.db.set(self.doc, 'employee_name', employee_name)

View File

@ -13,7 +13,7 @@ from frappe.model.controller import DocListController
class DocType(DocListController):
def autoname(self):
naming_method = frappe.conn.get_value("HR Settings", None, "emp_created_by")
naming_method = frappe.db.get_value("HR Settings", None, "emp_created_by")
if not naming_method:
throw(_("Please setup Employee Naming System in Human Resource > HR Settings"))
else:
@ -52,14 +52,14 @@ class DocType(DocListController):
self.add_restriction_if_required("Employee", self.doc.user_id)
def update_user_default(self):
frappe.conn.set_default("employee_name", self.doc.employee_name, self.doc.user_id)
frappe.conn.set_default("company", self.doc.company, self.doc.user_id)
frappe.db.set_default("employee_name", self.doc.employee_name, self.doc.user_id)
frappe.db.set_default("company", self.doc.company, self.doc.user_id)
def restrict_leave_approver(self):
"""restrict to this employee for leave approver"""
employee_leave_approvers = [d.leave_approver for d in self.doclist.get({"parentfield": "employee_leave_approvers"})]
if self.doc.reports_to and self.doc.reports_to not in employee_leave_approvers:
employee_leave_approvers.append(frappe.conn.get_value("Employee", self.doc.reports_to, "user_id"))
employee_leave_approvers.append(frappe.db.get_value("Employee", self.doc.reports_to, "user_id"))
for user in employee_leave_approvers:
self.add_restriction_if_required("Employee", user)
@ -73,7 +73,7 @@ class DocType(DocListController):
def update_profile(self):
# add employee role if missing
if not "Employee" in frappe.conn.sql_list("""select role from tabUserRole
if not "Employee" in frappe.db.sql_list("""select role from tabUserRole
where parent=%s""", self.doc.user_id):
from frappe.profile import add_role
add_role(self.doc.user_id, "Employee")
@ -143,7 +143,7 @@ class DocType(DocListController):
throw(_("Please enter relieving date."))
def validate_for_enabled_user_id(self):
enabled = frappe.conn.sql("""select name from `tabProfile` where
enabled = frappe.db.sql("""select name from `tabProfile` where
name=%s and enabled=1""", self.doc.user_id)
if not enabled:
throw("{id}: {user_id} {msg}".format(**{
@ -153,7 +153,7 @@ class DocType(DocListController):
}))
def validate_duplicate_user_id(self):
employee = frappe.conn.sql_list("""select name from `tabEmployee` where
employee = frappe.db.sql_list("""select name from `tabEmployee` where
user_id=%s and status='Active' and name!=%s""", (self.doc.user_id, self.doc.name))
if employee:
throw("{id}: {user_id} {msg}: {employee}".format(**{
@ -174,8 +174,8 @@ class DocType(DocListController):
def update_dob_event(self):
if self.doc.status == "Active" and self.doc.date_of_birth \
and not cint(frappe.conn.get_value("HR Settings", None, "stop_birthday_reminders")):
birthday_event = frappe.conn.sql("""select name from `tabEvent` where repeat_on='Every Year'
and not cint(frappe.db.get_value("HR Settings", None, "stop_birthday_reminders")):
birthday_event = frappe.db.sql("""select name from `tabEvent` where repeat_on='Every Year'
and ref_type='Employee' and ref_name=%s""", self.doc.name)
starts_on = self.doc.date_of_birth + " 00:00:00"
@ -202,7 +202,7 @@ class DocType(DocListController):
"ref_name": self.doc.name
}).insert()
else:
frappe.conn.sql("""delete from `tabEvent` where repeat_on='Every Year' and
frappe.db.sql("""delete from `tabEvent` where repeat_on='Every Year' and
ref_type='Employee' and ref_name=%s""", self.doc.name)
@frappe.whitelist()

View File

@ -41,7 +41,7 @@ class DocType:
throw(_("Please select weekly off day"))
def get_fy_start_end_dates(self):
return frappe.conn.sql("""select year_start_date, year_end_date
return frappe.db.sql("""select year_start_date, year_end_date
from `tabFiscal Year` where name=%s""", (self.doc.fiscal_year,))[0]
def get_weekly_off_date_list(self, year_start_date, year_end_date):
@ -66,5 +66,5 @@ class DocType:
self.doclist = self.doc.clear_table(self.doclist, 'holiday_list_details')
def update_default_holiday_list(self):
frappe.conn.sql("""update `tabHoliday List` set is_default = 0
frappe.db.sql("""update `tabHoliday List` set is_default = 0
where ifnull(is_default, 0) = 1 and fiscal_year = %s""", (self.doc.fiscal_year,))

View File

@ -20,15 +20,15 @@ class DocType:
self.doc.get("emp_created_by")=="Naming Series", hide_name_field=True)
def update_birthday_reminders(self):
original_stop_birthday_reminders = cint(frappe.conn.get_value("HR Settings",
original_stop_birthday_reminders = cint(frappe.db.get_value("HR Settings",
None, "stop_birthday_reminders"))
# reset birthday reminders
if cint(self.doc.stop_birthday_reminders) != original_stop_birthday_reminders:
frappe.conn.sql("""delete from `tabEvent` where repeat_on='Every Year' and ref_type='Employee'""")
frappe.db.sql("""delete from `tabEvent` where repeat_on='Every Year' and ref_type='Employee'""")
if not self.doc.stop_birthday_reminders:
for employee in frappe.conn.sql_list("""select name from `tabEmployee` where status='Active' and
for employee in frappe.db.sql_list("""select name from `tabEmployee` where status='Active' and
ifnull(date_of_birth, '')!=''"""):
frappe.get_obj("Employee", employee).update_dob_event()

View File

@ -15,7 +15,7 @@ class JobsMailbox(POP3Mailbox):
if mail.from_email == self.settings.email_id:
return
name = frappe.conn.get_value("Job Applicant", {"email_id": mail.from_email},
name = frappe.db.get_value("Job Applicant", {"email_id": mail.from_email},
"name")
if name:
applicant = frappe.bean("Job Applicant", name)
@ -40,5 +40,5 @@ class JobsMailbox(POP3Mailbox):
doctype="Job Applicant", name=applicant.doc.name, sent_or_received="Received")
def get_job_applications():
if cint(frappe.conn.get_value('Jobs Email Settings', None, 'extract_emails')):
if cint(frappe.db.get_value('Jobs Email Settings', None, 'extract_emails')):
JobsMailbox()

View File

@ -13,7 +13,7 @@ class DocType(TransactionBase):
self.doc, self.doclist = d, dl
def get_sender(self, comm):
return frappe.conn.get_value('Jobs Email Settings',None,'email_id')
return frappe.db.get_value('Jobs Email Settings',None,'email_id')
def validate(self):
self.set_status()

View File

@ -36,7 +36,7 @@ class DocType:
def check_existing_leave_allocation(self):
"""check whether leave for same type is already allocated or not"""
leave_allocation = frappe.conn.sql("""select name from `tabLeave Allocation`
leave_allocation = frappe.db.sql("""select name from `tabLeave Allocation`
where employee=%s and leave_type=%s and fiscal_year=%s and docstatus=1""",
(self.doc.employee, self.doc.leave_type, self.doc.fiscal_year))
if leave_allocation:
@ -63,14 +63,14 @@ class DocType:
return self.get_leaves_allocated(prev_fyear) - self.get_leaves_applied(prev_fyear)
def get_leaves_applied(self, fiscal_year):
leaves_applied = frappe.conn.sql("""select SUM(ifnull(total_leave_days, 0))
leaves_applied = frappe.db.sql("""select SUM(ifnull(total_leave_days, 0))
from `tabLeave Application` where employee=%s and leave_type=%s
and fiscal_year=%s and docstatus=1""",
(self.doc.employee, self.doc.leave_type, fiscal_year))
return leaves_applied and flt(leaves_applied[0][0]) or 0
def get_leaves_allocated(self, fiscal_year):
leaves_allocated = frappe.conn.sql("""select SUM(ifnull(total_leaves_allocated, 0))
leaves_allocated = frappe.db.sql("""select SUM(ifnull(total_leaves_allocated, 0))
from `tabLeave Allocation` where employee=%s and leave_type=%s
and fiscal_year=%s and docstatus=1 and name!=%s""",
(self.doc.employee, self.doc.leave_type, fiscal_year, self.doc.name))
@ -78,18 +78,18 @@ class DocType:
def allow_carry_forward(self):
"""check whether carry forward is allowed or not for this leave type"""
cf = frappe.conn.sql("""select is_carry_forward from `tabLeave Type` where name = %s""",
cf = frappe.db.sql("""select is_carry_forward from `tabLeave Type` where name = %s""",
self.doc.leave_type)
cf = cf and cint(cf[0][0]) or 0
if not cf:
frappe.conn.set(self.doc,'carry_forward',0)
frappe.db.set(self.doc,'carry_forward',0)
msgprint("Sorry! You cannot carry forward %s" % (self.doc.leave_type),
raise_exception=1)
def get_carry_forwarded_leaves(self):
if self.doc.carry_forward:
self.allow_carry_forward()
prev_fiscal_year = frappe.conn.sql("""select name from `tabFiscal Year`
prev_fiscal_year = frappe.db.sql("""select name from `tabFiscal Year`
where year_start_date = (select date_add(year_start_date, interval -1 year)
from `tabFiscal Year` where name=%s)
order by name desc limit 1""", self.doc.fiscal_year)
@ -105,11 +105,11 @@ class DocType:
def get_total_allocated_leaves(self):
leave_det = self.get_carry_forwarded_leaves()
frappe.conn.set(self.doc,'carry_forwarded_leaves',flt(leave_det['carry_forwarded_leaves']))
frappe.conn.set(self.doc,'total_leaves_allocated',flt(leave_det['total_leaves_allocated']))
frappe.db.set(self.doc,'carry_forwarded_leaves',flt(leave_det['carry_forwarded_leaves']))
frappe.db.set(self.doc,'total_leaves_allocated',flt(leave_det['total_leaves_allocated']))
def check_for_leave_application(self):
exists = frappe.conn.sql("""select name from `tabLeave Application`
exists = frappe.db.sql("""select name from `tabLeave Application`
where employee=%s and leave_type=%s and fiscal_year=%s and docstatus=1""",
(self.doc.employee, self.doc.leave_type, self.doc.fiscal_year))
if exists:

View File

@ -17,7 +17,7 @@ class LeaveApproverIdentityError(frappe.ValidationError): pass
from frappe.model.controller import DocListController
class DocType(DocListController):
def setup(self):
if frappe.conn.exists(self.doc.doctype, self.doc.name):
if frappe.db.exists(self.doc.doctype, self.doc.name):
self.previous_doc = frappe.doc(self.doc.doctype, self.doc.name)
else:
self.previous_doc = None
@ -76,11 +76,11 @@ class DocType(DocListController):
raise LeaveDayBlockedError
def get_holidays(self):
tot_hol = frappe.conn.sql("""select count(*) from `tabHoliday` h1, `tabHoliday List` h2, `tabEmployee` e1
tot_hol = frappe.db.sql("""select count(*) from `tabHoliday` h1, `tabHoliday List` h2, `tabEmployee` e1
where e1.name = %s and h1.parent = h2.name and e1.holiday_list = h2.name
and h1.holiday_date between %s and %s""", (self.doc.employee, self.doc.from_date, self.doc.to_date))
if not tot_hol:
tot_hol = frappe.conn.sql("""select count(*) from `tabHoliday` h1, `tabHoliday List` h2
tot_hol = frappe.db.sql("""select count(*) from `tabHoliday` h1, `tabHoliday List` h2
where h1.parent = h2.name and h1.holiday_date between %s and %s
and ifnull(h2.is_default,0) = 1 and h2.fiscal_year = %s""",
(self.doc.from_date, self.doc.to_date, self.doc.fiscal_year))
@ -120,13 +120,13 @@ class DocType(DocListController):
#check if this leave type allow the remaining balance to be in negative. If yes then warn the user and continue to save else warn the user and don't save.
msgprint("There is not enough leave balance for Leave Type: %s" % \
(self.doc.leave_type,),
raise_exception=not(frappe.conn.get_value("Leave Type", self.doc.leave_type,"allow_negative") or None))
raise_exception=not(frappe.db.get_value("Leave Type", self.doc.leave_type,"allow_negative") or None))
def validate_leave_overlap(self):
if not self.doc.name:
self.doc.name = "New Leave Application"
for d in frappe.conn.sql("""select name, leave_type, posting_date,
for d in frappe.db.sql("""select name, leave_type, posting_date,
from_date, to_date
from `tabLeave Application`
where
@ -141,7 +141,7 @@ class DocType(DocListController):
msgprint("Employee : %s has already applied for %s between %s and %s on %s. Please refer Leave Application : <a href=\"#Form/Leave Application/%s\">%s</a>" % (self.doc.employee, cstr(d['leave_type']), formatdate(d['from_date']), formatdate(d['to_date']), formatdate(d['posting_date']), d['name'], d['name']), raise_exception = OverlapError)
def validate_max_days(self):
max_days = frappe.conn.sql("select max_days_allowed from `tabLeave Type` where name = '%s'" %(self.doc.leave_type))
max_days = frappe.db.sql("select max_days_allowed from `tabLeave Type` where name = '%s'" %(self.doc.leave_type))
max_days = max_days and flt(max_days[0][0]) or 0
if max_days and self.doc.total_leave_days > max_days:
msgprint("Sorry ! You cannot apply for %s for more than %s days" % (self.doc.leave_type, max_days))
@ -157,7 +157,7 @@ class DocType(DocListController):
+ _("Leave Approver can be one of") + ": "
+ comma_or(leave_approvers)), raise_exception=InvalidLeaveApproverError)
elif self.doc.leave_approver and not frappe.conn.sql("""select name from `tabUserRole`
elif self.doc.leave_approver and not frappe.db.sql("""select name from `tabUserRole`
where parent=%s and role='Leave Approver'""", self.doc.leave_approver):
msgprint(get_fullname(self.doc.leave_approver) + ": " \
+ _("does not have role 'Leave Approver'"), raise_exception=InvalidLeaveApproverError)
@ -215,14 +215,14 @@ class DocType(DocListController):
@frappe.whitelist()
def get_leave_balance(employee, leave_type, fiscal_year):
leave_all = frappe.conn.sql("""select total_leaves_allocated
leave_all = frappe.db.sql("""select total_leaves_allocated
from `tabLeave Allocation` where employee = %s and leave_type = %s
and fiscal_year = %s and docstatus = 1""", (employee,
leave_type, fiscal_year))
leave_all = leave_all and flt(leave_all[0][0]) or 0
leave_app = frappe.conn.sql("""select SUM(total_leave_days)
leave_app = frappe.db.sql("""select SUM(total_leave_days)
from `tabLeave Application`
where employee = %s and leave_type = %s and fiscal_year = %s
and status="Approved" and docstatus = 1""", (employee, leave_type, fiscal_year))
@ -232,14 +232,14 @@ def get_leave_balance(employee, leave_type, fiscal_year):
return ret
def is_lwp(leave_type):
lwp = frappe.conn.sql("select is_lwp from `tabLeave Type` where name = %s", leave_type)
lwp = frappe.db.sql("select is_lwp from `tabLeave Type` where name = %s", leave_type)
return lwp and cint(lwp[0][0]) or 0
@frappe.whitelist()
def get_events(start, end):
events = []
employee = frappe.conn.get_default("employee", frappe.session.user)
company = frappe.conn.get_default("company", frappe.session.user)
employee = frappe.db.get_default("employee", frappe.session.user)
company = frappe.db.get_default("company", frappe.session.user)
from frappe.widgets.reportview import build_match_conditions
match_conditions = build_match_conditions("Leave Application")
@ -256,13 +256,13 @@ def get_events(start, end):
return events
def add_department_leaves(events, start, end, employee, company):
department = frappe.conn.get_value("Employee", employee, "department")
department = frappe.db.get_value("Employee", employee, "department")
if not department:
return
# department leaves
department_employees = frappe.conn.sql_list("""select name from tabEmployee where department=%s
department_employees = frappe.db.sql_list("""select name from tabEmployee where department=%s
and company=%s""", (department, company))
match_conditions = "employee in (\"%s\")" % '", "'.join(department_employees)
@ -278,7 +278,7 @@ def add_leaves(events, start, end, employee, company, match_conditions=None):
if match_conditions:
query += " and " + match_conditions
for d in frappe.conn.sql(query, (start, end, start, end), as_dict=True):
for d in frappe.db.sql(query, (start, end, start, end), as_dict=True):
e = {
"name": d.name,
"doctype": "Leave Application",
@ -309,11 +309,11 @@ def add_block_dates(events, start, end, employee, company):
cnt+=1
def add_holidays(events, start, end, employee, company):
applicable_holiday_list = frappe.conn.get_value("Employee", employee, "holiday_list")
applicable_holiday_list = frappe.db.get_value("Employee", employee, "holiday_list")
if not applicable_holiday_list:
return
for holiday in frappe.conn.sql("""select name, holiday_date, description
for holiday in frappe.db.sql("""select name, holiday_date, description
from `tabHoliday` where parent=%s and holiday_date between %s and %s""",
(applicable_holiday_list, start, end), as_dict=True):
events.append({
@ -338,7 +338,7 @@ def query_for_permitted_employees(doctype, txt, searchfield, start, page_len, fi
condition = build_match_conditions("Employee")
condition = ("and " + condition) if condition else ""
return frappe.conn.sql("""select name, employee_name from `tabEmployee`
return frappe.db.sql("""select name, employee_name from `tabEmployee`
where status = 'Active' and docstatus < 2 and
(`%s` like %s or employee_name like %s) %s
order by

View File

@ -11,14 +11,14 @@ class TestLeaveApplication(unittest.TestCase):
frappe.set_user("Administrator")
# so that this test doesn't affect other tests
frappe.conn.sql("""delete from `tabEmployee Leave Approver`""")
frappe.db.sql("""delete from `tabEmployee Leave Approver`""")
def _clear_roles(self):
frappe.conn.sql("""delete from `tabUserRole` where parent in
frappe.db.sql("""delete from `tabUserRole` where parent in
("test@example.com", "test1@example.com", "test2@example.com")""")
def _clear_applications(self):
frappe.conn.sql("""delete from `tabLeave Application`""")
frappe.db.sql("""delete from `tabLeave Application`""")
def _add_employee_leave_approver(self, employee, leave_approver):
temp_session_user = frappe.session.user
@ -44,7 +44,7 @@ class TestLeaveApplication(unittest.TestCase):
from frappe.profile import add_role
add_role("test1@example.com", "HR User")
frappe.conn.set_value("Department", "_Test Department",
frappe.db.set_value("Department", "_Test Department",
"leave_block_list", "_Test Leave Block List")
application = self.get_application(test_records[1])
@ -55,7 +55,7 @@ class TestLeaveApplication(unittest.TestCase):
frappe.set_user("test1@example.com")
# clear other applications
frappe.conn.sql("delete from `tabLeave Application`")
frappe.db.sql("delete from `tabLeave Application`")
application = self.get_application(test_records[1])
self.assertTrue(application.insert())
@ -87,9 +87,9 @@ class TestLeaveApplication(unittest.TestCase):
application = self.get_application(test_records[3])
application.doc.leave_approver = "test@example.com"
frappe.conn.set_value("Leave Block List", "_Test Leave Block List",
frappe.db.set_value("Leave Block List", "_Test Leave Block List",
"applies_to_all_departments", 1)
frappe.conn.set_value("Employee", "_T-Employee-0002", "department",
frappe.db.set_value("Employee", "_T-Employee-0002", "department",
"_Test Department")
frappe.set_user("test1@example.com")
@ -99,7 +99,7 @@ class TestLeaveApplication(unittest.TestCase):
application.doc.status = "Approved"
self.assertRaises(LeaveDayBlockedError, application.submit)
frappe.conn.set_value("Leave Block List", "_Test Leave Block List",
frappe.db.set_value("Leave Block List", "_Test Leave Block List",
"applies_to_all_departments", 0)
def test_leave_approval(self):
@ -128,7 +128,7 @@ class TestLeaveApplication(unittest.TestCase):
frappe.set_user("test1@example.com")
application.doc.status = "Approved"
application.submit()
self.assertEqual(frappe.conn.get_value("Leave Application", application.doc.name,
self.assertEqual(frappe.db.get_value("Leave Application", application.doc.name,
"docstatus"), 1)
def _test_leave_approval_invalid_leave_approver_insert(self):
@ -147,7 +147,7 @@ class TestLeaveApplication(unittest.TestCase):
application.doc.leave_approver = "test1@example.com"
self.assertRaises(InvalidLeaveApproverError, application.insert)
frappe.conn.sql("""delete from `tabEmployee Leave Approver` where parent=%s""",
frappe.db.sql("""delete from `tabEmployee Leave Approver` where parent=%s""",
"_T-Employee-0001")
def _test_leave_approval_invalid_leave_approver_submit(self):
@ -166,15 +166,15 @@ class TestLeaveApplication(unittest.TestCase):
from erpnext.hr.doctype.leave_application.leave_application import LeaveApproverIdentityError
self.assertRaises(LeaveApproverIdentityError, application.submit)
frappe.conn.sql("""delete from `tabEmployee Leave Approver` where parent=%s""",
frappe.db.sql("""delete from `tabEmployee Leave Approver` where parent=%s""",
"_T-Employee-0001")
def _test_leave_approval_valid_leave_approver_insert(self):
self._clear_applications()
self._add_employee_leave_approver("_T-Employee-0001", "test2@example.com")
original_department = frappe.conn.get_value("Employee", "_T-Employee-0001", "department")
frappe.conn.set_value("Employee", "_T-Employee-0001", "department", None)
original_department = frappe.db.get_value("Employee", "_T-Employee-0001", "department")
frappe.db.set_value("Employee", "_T-Employee-0001", "department", None)
frappe.set_user("test@example.com")
application = self.get_application(test_records[1])
@ -185,13 +185,13 @@ class TestLeaveApplication(unittest.TestCase):
frappe.set_user("test2@example.com")
application.doc.status = "Approved"
application.submit()
self.assertEqual(frappe.conn.get_value("Leave Application", application.doc.name,
self.assertEqual(frappe.db.get_value("Leave Application", application.doc.name,
"docstatus"), 1)
frappe.conn.sql("""delete from `tabEmployee Leave Approver` where parent=%s""",
frappe.db.sql("""delete from `tabEmployee Leave Approver` where parent=%s""",
"_T-Employee-0001")
frappe.conn.set_value("Employee", "_T-Employee-0001", "department", original_department)
frappe.db.set_value("Employee", "_T-Employee-0001", "department", original_department)
test_dependencies = ["Leave Block List"]

View File

@ -28,7 +28,7 @@ def get_applicable_block_dates(from_date, to_date, employee=None,
company=None, all_lists=False):
block_dates = []
for block_list in get_applicable_block_lists(employee, company, all_lists):
block_dates.extend(frappe.conn.sql("""select block_date, reason
block_dates.extend(frappe.db.sql("""select block_date, reason
from `tabLeave Block List Date` where parent=%s
and block_date between %s and %s""", (block_list, from_date, to_date),
as_dict=1))
@ -39,12 +39,12 @@ def get_applicable_block_lists(employee=None, company=None, all_lists=False):
block_lists = []
if not employee:
employee = frappe.conn.get_value("Employee", {"user_id":frappe.session.user})
employee = frappe.db.get_value("Employee", {"user_id":frappe.session.user})
if not employee:
return []
if not company:
company = frappe.conn.get_value("Employee", employee, "company")
company = frappe.db.get_value("Employee", employee, "company")
def add_block_list(block_list):
if block_list:
@ -52,18 +52,18 @@ def get_applicable_block_lists(employee=None, company=None, all_lists=False):
block_lists.append(block_list)
# per department
department = frappe.conn.get_value("Employee",employee, "department")
department = frappe.db.get_value("Employee",employee, "department")
if department:
block_list = frappe.conn.get_value("Department", department, "leave_block_list")
block_list = frappe.db.get_value("Department", department, "leave_block_list")
add_block_list(block_list)
# global
for block_list in frappe.conn.sql_list("""select name from `tabLeave Block List`
for block_list in frappe.db.sql_list("""select name from `tabLeave Block List`
where ifnull(applies_to_all_departments,0)=1 and company=%s""", company):
add_block_list(block_list)
return list(set(block_lists))
def is_user_in_allow_list(block_list):
return frappe.session.user in frappe.conn.sql_list("""select allow_user
return frappe.session.user in frappe.db.sql_list("""select allow_user
from `tabLeave Block List Allow` where parent=%s""", block_list)

View File

@ -12,20 +12,20 @@ class TestLeaveBlockList(unittest.TestCase):
def test_get_applicable_block_dates(self):
frappe.set_user("test@example.com")
frappe.conn.set_value("Department", "_Test Department", "leave_block_list",
frappe.db.set_value("Department", "_Test Department", "leave_block_list",
"_Test Leave Block List")
self.assertTrue("2013-01-02" in
[d.block_date for d in get_applicable_block_dates("2013-01-01", "2013-01-03")])
def test_get_applicable_block_dates_for_allowed_user(self):
frappe.set_user("test1@example.com")
frappe.conn.set_value("Department", "_Test Department 1", "leave_block_list",
frappe.db.set_value("Department", "_Test Department 1", "leave_block_list",
"_Test Leave Block List")
self.assertEquals([], [d.block_date for d in get_applicable_block_dates("2013-01-01", "2013-01-03")])
def test_get_applicable_block_dates_all_lists(self):
frappe.set_user("test1@example.com")
frappe.conn.set_value("Department", "_Test Department 1", "leave_block_list",
frappe.db.set_value("Department", "_Test Department 1", "leave_block_list",
"_Test Leave Block List")
self.assertTrue("2013-01-02" in
[d.block_date for d in get_applicable_block_dates("2013-01-01", "2013-01-03", all_lists=True)])

View File

@ -33,7 +33,7 @@ class DocType:
emp_query = "select name from `tabEmployee` "
if flag == 1:
emp_query += condition
e = frappe.conn.sql(emp_query)
e = frappe.db.sql(emp_query)
return e
# ----------------
@ -54,7 +54,7 @@ class DocType:
for d in self.get_employees():
la = Document('Leave Allocation')
la.employee = cstr(d[0])
la.employee_name = frappe.conn.get_value('Employee',cstr(d[0]),'employee_name')
la.employee_name = frappe.db.get_value('Employee',cstr(d[0]),'employee_name')
la.leave_type = self.doc.leave_type
la.fiscal_year = self.doc.fiscal_year
la.posting_date = nowdate()

View File

@ -21,7 +21,7 @@ class DocType:
cond = self.get_filter_condition()
cond += self.get_joining_releiving_condition()
emp_list = frappe.conn.sql("""
emp_list = frappe.db.sql("""
select t1.name
from `tabEmployee` t1, `tabSalary Structure` t2
where t1.docstatus!=2 and t2.docstatus != 2
@ -58,7 +58,7 @@ class DocType:
def get_month_details(self, year, month):
ysd = frappe.conn.sql("select year_start_date from `tabFiscal Year` where name ='%s'"%year)[0][0]
ysd = frappe.db.sql("select year_start_date from `tabFiscal Year` where name ='%s'"%year)[0][0]
if ysd:
from dateutil.relativedelta import relativedelta
import calendar, datetime
@ -84,7 +84,7 @@ class DocType:
emp_list = self.get_emp_list()
ss_list = []
for emp in emp_list:
if not frappe.conn.sql("""select name from `tabSalary Slip`
if not frappe.db.sql("""select name from `tabSalary Slip`
where docstatus!= 2 and employee = %s and month = %s and fiscal_year = %s and company = %s
""", (emp[0], self.doc.month, self.doc.fiscal_year, self.doc.company)):
ss = frappe.bean({
@ -115,7 +115,7 @@ class DocType:
which are not submitted
"""
cond = self.get_filter_condition()
ss_list = frappe.conn.sql("""
ss_list = frappe.db.sql("""
select t1.name from `tabSalary Slip` t1
where t1.docstatus = 0 and month = '%s' and fiscal_year = '%s' %s
""" % (self.doc.month, self.doc.fiscal_year, cond))
@ -131,11 +131,11 @@ class DocType:
for ss in ss_list:
ss_obj = get_obj("Salary Slip",ss[0],with_children=1)
try:
frappe.conn.set(ss_obj.doc, 'email_check', cint(self.doc.send_mail))
frappe.db.set(ss_obj.doc, 'email_check', cint(self.doc.send_mail))
if cint(self.doc.send_email) == 1:
ss_obj.send_mail_funct()
frappe.conn.set(ss_obj.doc, 'docstatus', 1)
frappe.db.set(ss_obj.doc, 'docstatus', 1)
except Exception,e:
not_submitted_ss.append(ss[0])
msgprint(e)
@ -177,7 +177,7 @@ class DocType:
Get total salary amount from submitted salary slip based on selected criteria
"""
cond = self.get_filter_condition()
tot = frappe.conn.sql("""
tot = frappe.db.sql("""
select sum(rounded_total) from `tabSalary Slip` t1
where t1.docstatus = 1 and month = '%s' and fiscal_year = '%s' %s
""" % (self.doc.month, self.doc.fiscal_year, cond))
@ -190,7 +190,7 @@ class DocType:
get default bank account,default salary acount from company
"""
amt = self.get_total_salary()
default_bank_account = frappe.conn.get_value("Company", self.doc.company,
default_bank_account = frappe.db.get_value("Company", self.doc.company,
"default_bank_account")
if not default_bank_account:
msgprint("You can set Default Bank Account in Company master.")

View File

@ -9,26 +9,26 @@ test_records = []
# from frappe.model.doc import Document
# from frappe.model.code import get_obj
# frappe.conn.sql = frappe.conn.sql
# frappe.db.sql = frappe.db.sql
#
# class TestSalaryManager(unittest.TestCase):
# def setUp(self):
# frappe.conn.begin()
# frappe.db.begin()
# for rec in [des1, dep1, branch1, grade1, comp1, emp1, emp2]:
# rec.save(1)
#
# ss1[0].employee = emp1.name
# for s in ss1: s.save(1)
# for s in ss1[1:]:
# frappe.conn.sql("update `tabSalary Structure Earning` set parent = '%s' where name = '%s'" % (ss1[0].name, s.name))
# frappe.conn.sql("update `tabSalary Structure Deduction` set parent = '%s' where name = '%s'" % (ss1[0].name, s.name))
# frappe.db.sql("update `tabSalary Structure Earning` set parent = '%s' where name = '%s'" % (ss1[0].name, s.name))
# frappe.db.sql("update `tabSalary Structure Deduction` set parent = '%s' where name = '%s'" % (ss1[0].name, s.name))
#
#
# ss2[0].employee = emp2.name
# for s in ss2: s.save(1)
# for s in ss2[1:]:
# frappe.conn.sql("update `tabSalary Structure Earning` set parent = '%s' where name = '%s'" % (ss2[0].name, s.name))
# frappe.conn.sql("update `tabSalary Structure Deduction` set parent = '%s' where name = '%s'" % (ss2[0].name, s.name))
# frappe.db.sql("update `tabSalary Structure Earning` set parent = '%s' where name = '%s'" % (ss2[0].name, s.name))
# frappe.db.sql("update `tabSalary Structure Deduction` set parent = '%s' where name = '%s'" % (ss2[0].name, s.name))
#
# sman.save()
# self.sm = get_obj('Salary Manager')
@ -36,7 +36,7 @@ test_records = []
# self.sm.create_sal_slip()
#
# def test_creation(self):
# ssid = frappe.conn.sql("""
# ssid = frappe.db.sql("""
# select name, department
# from `tabSalary Slip`
# where month = '08' and fiscal_year='2011-2012'""")
@ -46,7 +46,7 @@ test_records = []
#
#
# def test_lwp_calc(self):
# ss = frappe.conn.sql("""
# ss = frappe.db.sql("""
# select payment_days
# from `tabSalary Slip`
# where month = '08' and fiscal_year='2011-2012' and employee = '%s'
@ -55,7 +55,7 @@ test_records = []
# self.assertTrue(ss[0][0]==27)
#
# def test_net_pay(self):
# ss = frappe.conn.sql("""
# ss = frappe.db.sql("""
# select rounded_total
# from `tabSalary Slip`
# where month = '08'
@ -64,7 +64,7 @@ test_records = []
#
# def test_submit(self):
# self.sm.submit_salary_slip()
# ss = frappe.conn.sql("""
# ss = frappe.db.sql("""
# select docstatus
# from `tabSalary Slip`
# where month = '08'
@ -72,7 +72,7 @@ test_records = []
# self.assertTrue(ss[0][0]==1)
#
# def tearDown(self):
# frappe.conn.rollback()
# frappe.db.rollback()
#
# #--------------------------------------------
# # test data

View File

@ -30,7 +30,7 @@ class DocType(TransactionBase):
self.pull_sal_struct(struct)
def check_sal_struct(self):
struct = frappe.conn.sql("""select name from `tabSalary Structure`
struct = frappe.db.sql("""select name from `tabSalary Structure`
where employee=%s and is_active = 'Yes'""", self.doc.employee)
if not struct:
msgprint("Please create Salary Structure for employee '%s'" % self.doc.employee)
@ -42,7 +42,7 @@ class DocType(TransactionBase):
self.doclist = get_mapped_doclist(struct, self.doclist)
def pull_emp_details(self):
emp = frappe.conn.get_value("Employee", self.doc.employee,
emp = frappe.db.get_value("Employee", self.doc.employee,
["bank_name", "bank_ac_no", "esic_card_no", "pf_number"], as_dict=1)
if emp:
self.doc.bank_name = emp.bank_name
@ -59,7 +59,7 @@ class DocType(TransactionBase):
m = get_obj('Salary Manager').get_month_details(self.doc.fiscal_year, self.doc.month)
holidays = self.get_holidays_for_employee(m)
if not cint(frappe.conn.get_value("HR Settings", "HR Settings",
if not cint(frappe.db.get_value("HR Settings", "HR Settings",
"include_holidays_in_total_working_days")):
m["month_days"] -= len(holidays)
if m["month_days"] < 0:
@ -76,7 +76,7 @@ class DocType(TransactionBase):
def get_payment_days(self, m):
payment_days = m['month_days']
emp = frappe.conn.sql("select date_of_joining, relieving_date from `tabEmployee` \
emp = frappe.db.sql("select date_of_joining, relieving_date from `tabEmployee` \
where name = %s", self.doc.employee, as_dict=1)[0]
if emp['relieving_date']:
@ -98,13 +98,13 @@ class DocType(TransactionBase):
return payment_days
def get_holidays_for_employee(self, m):
holidays = frappe.conn.sql("""select t1.holiday_date
holidays = frappe.db.sql("""select t1.holiday_date
from `tabHoliday` t1, tabEmployee t2
where t1.parent = t2.holiday_list and t2.name = %s
and t1.holiday_date between %s and %s""",
(self.doc.employee, m['month_start_date'], m['month_end_date']))
if not holidays:
holidays = frappe.conn.sql("""select t1.holiday_date
holidays = frappe.db.sql("""select t1.holiday_date
from `tabHoliday` t1, `tabHoliday List` t2
where t1.parent = t2.name and ifnull(t2.is_default, 0) = 1
and t2.fiscal_year = %s
@ -118,7 +118,7 @@ class DocType(TransactionBase):
for d in range(m['month_days']):
dt = add_days(cstr(m['month_start_date']), d)
if dt not in holidays:
leave = frappe.conn.sql("""
leave = frappe.db.sql("""
select t1.name, t1.half_day
from `tabLeave Application` t1, `tabLeave Type` t2
where t2.name = t1.leave_type
@ -132,7 +132,7 @@ class DocType(TransactionBase):
return lwp
def check_existing(self):
ret_exist = frappe.conn.sql("""select name from `tabSalary Slip`
ret_exist = frappe.db.sql("""select name from `tabSalary Slip`
where month = %s and fiscal_year = %s and docstatus != 2
and employee = %s and name != %s""",
(self.doc.month, self.doc.fiscal_year, self.doc.employee, self.doc.name))
@ -196,12 +196,12 @@ class DocType(TransactionBase):
def send_mail_funct(self):
from frappe.utils.email_lib import sendmail
receiver = frappe.conn.get_value("Employee", self.doc.employee, "company_email")
receiver = frappe.db.get_value("Employee", self.doc.employee, "company_email")
if receiver:
subj = 'Salary Slip - ' + cstr(self.doc.month) +'/'+cstr(self.doc.fiscal_year)
earn_ret=frappe.conn.sql("""select e_type, e_modified_amount from `tabSalary Slip Earning`
earn_ret=frappe.db.sql("""select e_type, e_modified_amount from `tabSalary Slip Earning`
where parent = %s""", self.doc.name)
ded_ret=frappe.conn.sql("""select d_type, d_modified_amount from `tabSalary Slip Deduction`
ded_ret=frappe.db.sql("""select d_type, d_modified_amount from `tabSalary Slip Deduction`
where parent = %s""", self.doc.name)
earn_table = ''
@ -229,7 +229,7 @@ class DocType(TransactionBase):
% (cstr(d[0]), cstr(d[1]))
ded_table += '</table>'
letter_head = frappe.conn.get_value("Letter Head", {"is_default": 1, "disabled": 0},
letter_head = frappe.db.get_value("Letter Head", {"is_default": 1, "disabled": 0},
"content")
msg = '''<div> %s <br>

View File

@ -6,8 +6,8 @@ import unittest
class TestSalarySlip(unittest.TestCase):
def setUp(self):
frappe.conn.sql("""delete from `tabLeave Application`""")
frappe.conn.sql("""delete from `tabSalary Slip`""")
frappe.db.sql("""delete from `tabLeave Application`""")
frappe.db.sql("""delete from `tabSalary Slip`""")
from erpnext.hr.doctype.leave_application.test_leave_application import test_records as leave_applications
la = frappe.bean(copy=leave_applications[4])
la.insert()
@ -15,10 +15,10 @@ class TestSalarySlip(unittest.TestCase):
la.submit()
def tearDown(self):
frappe.conn.set_value("HR Settings", "HR Settings", "include_holidays_in_total_working_days", 0)
frappe.db.set_value("HR Settings", "HR Settings", "include_holidays_in_total_working_days", 0)
def test_salary_slip_with_holidays_included(self):
frappe.conn.set_value("HR Settings", "HR Settings", "include_holidays_in_total_working_days", 1)
frappe.db.set_value("HR Settings", "HR Settings", "include_holidays_in_total_working_days", 1)
ss = frappe.bean(copy=test_records[0])
ss.insert()
self.assertEquals(ss.doc.total_days_in_month, 31)

View File

@ -19,7 +19,7 @@ class DocType:
def get_employee_details(self):
ret = {}
det = frappe.conn.sql("""select employee_name, branch, designation, department, grade
det = frappe.db.sql("""select employee_name, branch, designation, department, grade
from `tabEmployee` where name = %s""", self.doc.employee)
if det:
ret = {
@ -33,7 +33,7 @@ class DocType:
return ret
def get_ss_values(self,employee):
basic_info = frappe.conn.sql("""select bank_name, bank_ac_no, esic_card_no, pf_number
basic_info = frappe.db.sql("""select bank_name, bank_ac_no, esic_card_no, pf_number
from `tabEmployee` where name =%s""", employee)
ret = {'bank_name': basic_info and basic_info[0][0] or '',
'bank_ac_no': basic_info and basic_info[0][1] or '',
@ -42,7 +42,7 @@ class DocType:
return ret
def make_table(self, doct_name, tab_fname, tab_name):
list1 = frappe.conn.sql("select name from `tab%s` where docstatus != 2" % doct_name)
list1 = frappe.db.sql("select name from `tab%s` where docstatus != 2" % doct_name)
for li in list1:
child = addchild(self.doc, tab_fname, tab_name, self.doclist)
if(tab_fname == 'earning_details'):
@ -57,7 +57,7 @@ class DocType:
self.make_table('Deduction Type','deduction_details', 'Salary Structure Deduction')
def check_existing(self):
ret = frappe.conn.sql("""select name from `tabSalary Structure` where is_active = 'Yes'
ret = frappe.db.sql("""select name from `tabSalary Structure` where is_active = 'Yes'
and employee = %s and name!=%s""", (self.doc.employee,self.doc.name))
if ret and self.doc.is_active=='Yes':
msgprint(_("""Another Salary Structure '%s' is active for employee '%s'. Please make its status 'Inactive' to proceed.""") %

View File

@ -79,12 +79,12 @@ def get_dates(args):
return dates
def get_active_employees():
employees = frappe.conn.sql("""select name, employee_name, company
employees = frappe.db.sql("""select name, employee_name, company
from tabEmployee where docstatus < 2 and status = 'Active'""", as_dict=1)
return employees
def get_existing_attendance_records(args):
attendance = frappe.conn.sql("""select name, att_date, employee, status, naming_series
attendance = frappe.db.sql("""select name, att_date, employee, status, naming_series
from `tabAttendance` where att_date between %s and %s and docstatus < 2""",
(args["from_date"], args["to_date"]), as_dict=1)
@ -129,7 +129,7 @@ def upload():
d = frappe._dict(zip(columns, row))
d["doctype"] = "Attendance"
if d.name:
d["docstatus"] = frappe.conn.get_value("Attendance", d.name, "docstatus")
d["docstatus"] = frappe.db.get_value("Attendance", d.name, "docstatus")
try:
check_record(d, doctype_dl=doctype_dl)
@ -141,7 +141,7 @@ def upload():
frappe.errprint(frappe.get_traceback())
if error:
frappe.conn.rollback()
frappe.db.rollback()
else:
frappe.conn.commit()
frappe.db.commit()
return {"messages": ret, "error": error}

View File

@ -22,7 +22,7 @@ def get_columns():
def get_employees(filters):
conditions = get_conditions(filters)
return frappe.conn.sql("""select name, date_of_birth, branch, department, designation,
return frappe.db.sql("""select name, date_of_birth, branch, department, designation,
gender, company from tabEmployee where status = 'Active' %s""" % conditions, as_list=1)
def get_conditions(filters):

View File

@ -12,19 +12,19 @@ def execute(filters=None):
[["Employee", "company", "=", filters.get("company")]] or None
employees = runreport(doctype="Employee", fields=["name", "employee_name", "department"],
filters=employee_filters)
leave_types = frappe.conn.sql_list("select name from `tabLeave Type`")
leave_types = frappe.db.sql_list("select name from `tabLeave Type`")
if filters.get("fiscal_year"):
fiscal_years = [filters["fiscal_year"]]
else:
fiscal_years = frappe.conn.sql_list("select name from `tabFiscal Year` order by name desc")
fiscal_years = frappe.db.sql_list("select name from `tabFiscal Year` order by name desc")
employee_in = '", "'.join([e.name for e in employees])
allocations = frappe.conn.sql("""select employee, fiscal_year, leave_type, total_leaves_allocated
allocations = frappe.db.sql("""select employee, fiscal_year, leave_type, total_leaves_allocated
from `tabLeave Allocation`
where docstatus=1 and employee in ("%s")""" % employee_in, as_dict=True)
applications = frappe.conn.sql("""select employee, fiscal_year, leave_type, SUM(total_leave_days) as leaves
applications = frappe.db.sql("""select employee, fiscal_year, leave_type, SUM(total_leave_days) as leaves
from `tabLeave Application`
where status="Approved" and docstatus = 1 and employee in ("%s")
group by employee, fiscal_year, leave_type""" % employee_in, as_dict=True)

View File

@ -54,7 +54,7 @@ def get_columns(filters):
return columns
def get_attendance_list(conditions, filters):
attendance_list = frappe.conn.sql("""select employee, day(att_date) as day_of_month,
attendance_list = frappe.db.sql("""select employee, day(att_date) as day_of_month,
status from tabAttendance where docstatus = 1 %s order by employee, att_date""" %
conditions, filters, as_dict=1)
@ -84,7 +84,7 @@ def get_conditions(filters):
return conditions, filters
def get_employee_details():
employee = frappe.conn.sql("""select name, employee_name, designation, department,
employee = frappe.db.sql("""select name, employee_name, designation, department,
branch, company from tabEmployee where docstatus < 2 and status = 'Active'""", as_dict=1)
emp_map = {}

View File

@ -42,11 +42,11 @@ def get_columns(salary_slips):
"Payment Days:Float:120"
]
earning_types = frappe.conn.sql_list("""select distinct e_type from `tabSalary Slip Earning`
earning_types = frappe.db.sql_list("""select distinct e_type from `tabSalary Slip Earning`
where ifnull(e_modified_amount, 0) != 0 and parent in (%s)""" %
(', '.join(['%s']*len(salary_slips))), tuple([d.name for d in salary_slips]))
ded_types = frappe.conn.sql_list("""select distinct d_type from `tabSalary Slip Deduction`
ded_types = frappe.db.sql_list("""select distinct d_type from `tabSalary Slip Deduction`
where ifnull(d_modified_amount, 0) != 0 and parent in (%s)""" %
(', '.join(['%s']*len(salary_slips))), tuple([d.name for d in salary_slips]))
@ -59,7 +59,7 @@ def get_columns(salary_slips):
def get_salary_slips(filters):
conditions, filters = get_conditions(filters)
salary_slips = frappe.conn.sql("""select * from `tabSalary Slip` where docstatus = 1 %s
salary_slips = frappe.db.sql("""select * from `tabSalary Slip` where docstatus = 1 %s
order by employee, month""" % conditions, filters, as_dict=1)
if not salary_slips:
@ -83,7 +83,7 @@ def get_conditions(filters):
return conditions, filters
def get_ss_earning_map(salary_slips):
ss_earnings = frappe.conn.sql("""select parent, e_type, e_modified_amount
ss_earnings = frappe.db.sql("""select parent, e_type, e_modified_amount
from `tabSalary Slip Earning` where parent in (%s)""" %
(', '.join(['%s']*len(salary_slips))), tuple([d.name for d in salary_slips]), as_dict=1)
@ -95,7 +95,7 @@ def get_ss_earning_map(salary_slips):
return ss_earning_map
def get_ss_ded_map(salary_slips):
ss_deductions = frappe.conn.sql("""select parent, d_type, d_modified_amount
ss_deductions = frappe.db.sql("""select parent, d_type, d_modified_amount
from `tabSalary Slip Deduction` where parent in (%s)""" %
(', '.join(['%s']*len(salary_slips))), tuple([d.name for d in salary_slips]), as_dict=1)

View File

@ -7,7 +7,7 @@ from frappe import _
@frappe.whitelist()
def get_leave_approver_list():
roles = [r[0] for r in frappe.conn.sql("""select distinct parent from `tabUserRole`
roles = [r[0] for r in frappe.db.sql("""select distinct parent from `tabUserRole`
where role='Leave Approver'""")]
if not roles:
frappe.msgprint(_("No Leave Approvers. Please assign 'Leave Approver' Role to atleast one user."))
@ -17,7 +17,7 @@ def get_leave_approver_list():
@frappe.whitelist()
def get_expense_approver_list():
roles = [r[0] for r in frappe.conn.sql("""select distinct parent from `tabUserRole`
roles = [r[0] for r in frappe.db.sql("""select distinct parent from `tabUserRole`
where role='Expense Approver'""")]
if not roles:
frappe.msgprint("No Expense Approvers. Please assign 'Expense Approver' \

View File

@ -17,7 +17,7 @@ class DocType:
self.doclist = doclist
def autoname(self):
last_name = frappe.conn.sql("""select max(name) from `tabBOM`
last_name = frappe.db.sql("""select max(name) from `tabBOM`
where name like "BOM/%s/%%" """ % cstr(self.doc.item).replace('"', '\\"'))
if last_name:
idx = cint(cstr(last_name[0][0]).split('/')[-1].split('-')[0]) + 1
@ -47,8 +47,8 @@ class DocType:
self.manage_default_bom()
def on_cancel(self):
frappe.conn.set(self.doc, "is_active", 0)
frappe.conn.set(self.doc, "is_default", 0)
frappe.db.set(self.doc, "is_active", 0)
frappe.db.set(self.doc, "is_default", 0)
# check if used in any other bom
self.validate_bom_links()
@ -59,7 +59,7 @@ class DocType:
self.manage_default_bom()
def get_item_det(self, item_code):
item = frappe.conn.sql("""select name, is_asset_item, is_purchase_item,
item = frappe.db.sql("""select name, is_asset_item, is_purchase_item,
docstatus, description, is_sub_contracted_item, stock_uom, default_bom,
last_purchase_rate, standard_rate, is_manufactured_item
from `tabItem` where name=%s""", item_code, as_dict = 1)
@ -120,7 +120,7 @@ class DocType:
elif self.doc.rm_cost_as_per == "Price List":
if not self.doc.buying_price_list:
frappe.throw(_("Please select Price List"))
rate = frappe.conn.get_value("Item Price", {"price_list": self.doc.buying_price_list,
rate = frappe.db.get_value("Item Price", {"price_list": self.doc.buying_price_list,
"item_code": arg["item_code"]}, "price_list_rate") or 0
elif self.doc.rm_cost_as_per == 'Standard Rate':
rate = arg['standard_rate']
@ -143,7 +143,7 @@ class DocType:
frappe.bean(self.doclist).update_after_submit()
def get_bom_unitcost(self, bom_no):
bom = frappe.conn.sql("""select name, total_cost/quantity as unit_cost from `tabBOM`
bom = frappe.db.sql("""select name, total_cost/quantity as unit_cost from `tabBOM`
where is_active = 1 and name = %s""", bom_no, as_dict=1)
return bom and bom[0]['unit_cost'] or 0
@ -155,7 +155,7 @@ class DocType:
from erpnext.stock.utils import get_incoming_rate
dt = self.doc.costing_date or nowdate()
time = self.doc.costing_date == nowdate() and now().split()[1] or '23:59'
warehouse = frappe.conn.sql("select warehouse from `tabBin` where item_code = %s", args['item_code'])
warehouse = frappe.db.sql("select warehouse from `tabBin` where item_code = %s", args['item_code'])
rate = []
for wh in warehouse:
r = get_incoming_rate({
@ -177,13 +177,13 @@ class DocType:
if self.doc.is_default and self.doc.is_active:
from frappe.model.utils import set_default
set_default(self.doc, "item")
frappe.conn.set_value("Item", self.doc.item, "default_bom", self.doc.name)
frappe.db.set_value("Item", self.doc.item, "default_bom", self.doc.name)
else:
if not self.doc.is_active:
frappe.conn.set(self.doc, "is_default", 0)
frappe.db.set(self.doc, "is_default", 0)
frappe.conn.sql("update `tabItem` set default_bom = null where name = %s and default_bom = %s",
frappe.db.sql("update `tabItem` set default_bom = null where name = %s and default_bom = %s",
(self.doc.item, self.doc.name))
def clear_operations(self):
@ -203,7 +203,7 @@ class DocType:
msgprint("""As Item: %s is not a manufactured / sub-contracted item, \
you can not make BOM for it""" % self.doc.item, raise_exception = 1)
else:
ret = frappe.conn.get_value("Item", self.doc.item, ["description", "stock_uom"])
ret = frappe.db.get_value("Item", self.doc.item, ["description", "stock_uom"])
self.doc.description = ret[0]
self.doc.uom = ret[1]
@ -249,7 +249,7 @@ class DocType:
def validate_bom_no(self, item, bom_no, idx):
"""Validate BOM No of sub-contracted items"""
bom = frappe.conn.sql("""select name from `tabBOM` where name = %s and item = %s
bom = frappe.db.sql("""select name from `tabBOM` where name = %s and item = %s
and is_active=1 and docstatus=1""",
(bom_no, item), as_dict =1)
if not bom:
@ -271,7 +271,7 @@ class DocType:
for d in check_list:
bom_list, count = [self.doc.name], 0
while (len(bom_list) > count ):
boms = frappe.conn.sql(" select %s from `tabBOM Item` where %s = '%s' " %
boms = frappe.db.sql(" select %s from `tabBOM Item` where %s = '%s' " %
(d[0], d[1], cstr(bom_list[count])))
count = count + 1
for b in boms:
@ -291,7 +291,7 @@ class DocType:
def traverse_tree(self, bom_list=[]):
def _get_children(bom_no):
return [cstr(d[0]) for d in frappe.conn.sql("""select bom_no from `tabBOM Item`
return [cstr(d[0]) for d in frappe.db.sql("""select bom_no from `tabBOM Item`
where parent = %s and ifnull(bom_no, '') != ''""", bom_no)]
count = 0
@ -317,7 +317,7 @@ class DocType:
total_op_cost = 0
for d in getlist(self.doclist, 'bom_operations'):
if d.workstation and not d.hour_rate:
d.hour_rate = frappe.conn.get_value("Workstation", d.workstation, "hour_rate")
d.hour_rate = frappe.db.get_value("Workstation", d.workstation, "hour_rate")
if d.hour_rate and d.time_in_mins:
d.operating_cost = flt(d.hour_rate) * flt(d.time_in_mins) / 60.0
total_op_cost += flt(d.operating_cost)
@ -364,7 +364,7 @@ class DocType:
def get_child_exploded_items(self, bom_no, qty):
""" Add all items from Flat BOM of child BOM"""
child_fb_items = frappe.conn.sql("""select item_code, description, stock_uom, qty, rate,
child_fb_items = frappe.db.sql("""select item_code, description, stock_uom, qty, rate,
qty_consumed_per_unit from `tabBOM Explosion Item`
where parent = %s and docstatus = 1""", bom_no, as_dict = 1)
@ -390,12 +390,12 @@ class DocType:
ch.save(1)
def get_parent_bom_list(self, bom_no):
p_bom = frappe.conn.sql("select parent from `tabBOM Item` where bom_no = '%s'" % bom_no)
p_bom = frappe.db.sql("select parent from `tabBOM Item` where bom_no = '%s'" % bom_no)
return p_bom and [i[0] for i in p_bom] or []
def validate_bom_links(self):
if not self.doc.is_active:
act_pbom = frappe.conn.sql("""select distinct bom_item.parent from `tabBOM Item` bom_item
act_pbom = frappe.db.sql("""select distinct bom_item.parent from `tabBOM Item` bom_item
where bom_item.bom_no = %s and bom_item.docstatus = 1
and exists (select * from `tabBOM` where name = bom_item.parent
and docstatus = 1 and is_active = 1)""", self.doc.name)
@ -427,7 +427,7 @@ def get_bom_items_as_dict(bom, qty=1, fetch_exploded=1):
group by item_code, stock_uom"""
if fetch_exploded:
items = frappe.conn.sql(query % {
items = frappe.db.sql(query % {
"qty": qty,
"table": "BOM Explosion Item",
"bom": bom,
@ -435,7 +435,7 @@ def get_bom_items_as_dict(bom, qty=1, fetch_exploded=1):
and ifnull(item.is_sub_contracted_item, 'No') = 'No' """
}, as_dict=True)
else:
items = frappe.conn.sql(query % {
items = frappe.db.sql(query % {
"qty": qty,
"table": "BOM Item",
"bom": bom,

View File

@ -28,14 +28,14 @@ class DocType:
msgprint("Current BOM and New BOM can not be same", raise_exception=1)
def update_new_bom(self):
current_bom_unitcost = frappe.conn.sql("""select total_cost/quantity
current_bom_unitcost = frappe.db.sql("""select total_cost/quantity
from `tabBOM` where name = %s""", self.doc.current_bom)
current_bom_unitcost = current_bom_unitcost and flt(current_bom_unitcost[0][0]) or 0
frappe.conn.sql("""update `tabBOM Item` set bom_no=%s,
frappe.db.sql("""update `tabBOM Item` set bom_no=%s,
rate=%s, amount=qty*%s where bom_no = %s and docstatus < 2""",
(self.doc.new_bom, current_bom_unitcost, current_bom_unitcost, self.doc.current_bom))
def get_parent_boms(self):
return [d[0] for d in frappe.conn.sql("""select distinct parent
return [d[0] for d in frappe.db.sql("""select distinct parent
from `tabBOM Item` where ifnull(bom_no, '') = %s and docstatus < 2""",
self.doc.new_bom)]

View File

@ -32,7 +32,7 @@ class DocType:
def validate_bom_no(self):
if self.doc.bom_no:
bom = frappe.conn.sql("""select name from `tabBOM` where name=%s and docstatus=1
bom = frappe.db.sql("""select name from `tabBOM` where name=%s and docstatus=1
and is_active=1 and item=%s"""
, (self.doc.bom_no, self.doc.production_item), as_dict =1)
if not bom:
@ -42,7 +42,7 @@ class DocType:
def validate_sales_order(self):
if self.doc.sales_order:
so = frappe.conn.sql("""select name, delivery_date from `tabSales Order`
so = frappe.db.sql("""select name, delivery_date from `tabSales Order`
where name=%s and docstatus = 1""", self.doc.sales_order, as_dict=1)[0]
if not so.name:
@ -61,18 +61,18 @@ class DocType:
def validate_production_order_against_so(self):
# already ordered qty
ordered_qty_against_so = frappe.conn.sql("""select sum(qty) from `tabProduction Order`
ordered_qty_against_so = frappe.db.sql("""select sum(qty) from `tabProduction Order`
where production_item = %s and sales_order = %s and docstatus < 2 and name != %s""",
(self.doc.production_item, self.doc.sales_order, self.doc.name))[0][0]
total_qty = flt(ordered_qty_against_so) + flt(self.doc.qty)
# get qty from Sales Order Item table
so_item_qty = frappe.conn.sql("""select sum(qty) from `tabSales Order Item`
so_item_qty = frappe.db.sql("""select sum(qty) from `tabSales Order Item`
where parent = %s and item_code = %s""",
(self.doc.sales_order, self.doc.production_item))[0][0]
# get qty from Packing Item table
dnpi_qty = frappe.conn.sql("""select sum(qty) from `tabPacked Item`
dnpi_qty = frappe.db.sql("""select sum(qty) from `tabPacked Item`
where parent = %s and parenttype = 'Sales Order' and item_code = %s""",
(self.doc.sales_order, self.doc.production_item))[0][0]
# total qty in SO
@ -95,32 +95,32 @@ class DocType:
def update_status(self, status):
if status == 'Stopped':
frappe.conn.set(self.doc, 'status', cstr(status))
frappe.db.set(self.doc, 'status', cstr(status))
else:
if flt(self.doc.qty) == flt(self.doc.produced_qty):
frappe.conn.set(self.doc, 'status', 'Completed')
frappe.db.set(self.doc, 'status', 'Completed')
if flt(self.doc.qty) > flt(self.doc.produced_qty):
frappe.conn.set(self.doc, 'status', 'In Process')
frappe.db.set(self.doc, 'status', 'In Process')
if flt(self.doc.produced_qty) == 0:
frappe.conn.set(self.doc, 'status', 'Submitted')
frappe.db.set(self.doc, 'status', 'Submitted')
def on_submit(self):
if not self.doc.wip_warehouse:
frappe.throw(_("WIP Warehouse required before Submit"))
frappe.conn.set(self.doc,'status', 'Submitted')
frappe.db.set(self.doc,'status', 'Submitted')
self.update_planned_qty(self.doc.qty)
def on_cancel(self):
# Check whether any stock entry exists against this Production Order
stock_entry = frappe.conn.sql("""select name from `tabStock Entry`
stock_entry = frappe.db.sql("""select name from `tabStock Entry`
where production_order = %s and docstatus = 1""", self.doc.name)
if stock_entry:
frappe.throw("""Submitted Stock Entry %s exists against this production order.
Hence can not be cancelled.""" % stock_entry[0][0])
frappe.conn.set(self.doc,'status', 'Cancelled')
frappe.db.set(self.doc,'status', 'Cancelled')
self.update_planned_qty(-self.doc.qty)
def update_planned_qty(self, qty):
@ -136,7 +136,7 @@ class DocType:
@frappe.whitelist()
def get_item_details(item):
res = frappe.conn.sql("""select stock_uom, description
res = frappe.db.sql("""select stock_uom, description
from `tabItem` where (ifnull(end_of_life, "")="" or end_of_life > now())
and name=%s""", item, as_dict=1)
@ -144,7 +144,7 @@ def get_item_details(item):
return {}
res = res[0]
bom = frappe.conn.sql("""select name from `tabBOM` where item=%s
bom = frappe.db.sql("""select name from `tabBOM` where item=%s
and ifnull(is_default, 0)=1""", item)
if bom:
res.bom_no = bom[0][0]

View File

@ -13,9 +13,9 @@ from erpnext.manufacturing.doctype.production_order.production_order import make
class TestProductionOrder(unittest.TestCase):
def test_planned_qty(self):
set_perpetual_inventory(0)
frappe.conn.sql("delete from `tabStock Ledger Entry`")
frappe.conn.sql("""delete from `tabBin`""")
frappe.conn.sql("""delete from `tabGL Entry`""")
frappe.db.sql("delete from `tabStock Ledger Entry`")
frappe.db.sql("""delete from `tabBin`""")
frappe.db.sql("""delete from `tabGL Entry`""")
pro_bean = frappe.bean(copy = test_records[0])
pro_bean.insert()
@ -40,9 +40,9 @@ class TestProductionOrder(unittest.TestCase):
stock_entry.run_method("get_items")
stock_entry.submit()
self.assertEqual(frappe.conn.get_value("Production Order", pro_bean.doc.name,
self.assertEqual(frappe.db.get_value("Production Order", pro_bean.doc.name,
"produced_qty"), 4)
self.assertEqual(frappe.conn.get_value("Bin", {"item_code": "_Test FG Item",
self.assertEqual(frappe.db.get_value("Bin", {"item_code": "_Test FG Item",
"warehouse": "_Test Warehouse 1 - _TC"}, "planned_qty"), 6)
return pro_bean.doc.name

View File

@ -17,7 +17,7 @@ class DocType:
def get_so_details(self, so):
"""Pull other details from so"""
so = frappe.conn.sql("""select transaction_date, customer, grand_total
so = frappe.db.sql("""select transaction_date, customer, grand_total
from `tabSales Order` where name = %s""", so, as_dict = 1)
ret = {
'sales_order_date': so and so[0]['transaction_date'] or '',
@ -29,7 +29,7 @@ class DocType:
def get_item_details(self, item_code):
""" Pull other item details from item master"""
item = frappe.conn.sql("""select description, stock_uom, default_bom
item = frappe.db.sql("""select description, stock_uom, default_bom
from `tabItem` where name = %s""", item_code, as_dict =1)
ret = {
'description' : item and item[0]['description'],
@ -61,7 +61,7 @@ class DocType:
if self.doc.fg_item:
item_filter += ' and item.name = "' + self.doc.fg_item + '"'
open_so = frappe.conn.sql("""
open_so = frappe.db.sql("""
select distinct so.name, so.transaction_date, so.customer, so.grand_total
from `tabSales Order` so, `tabSales Order Item` so_item
where so_item.parent = so.name
@ -108,7 +108,7 @@ class DocType:
msgprint(_("Please enter sales order in the above table"))
return []
items = frappe.conn.sql("""select distinct parent, item_code, warehouse,
items = frappe.db.sql("""select distinct parent, item_code, warehouse,
(qty - ifnull(delivered_qty, 0)) as pending_qty
from `tabSales Order Item` so_item
where parent in (%s) and docstatus = 1 and ifnull(qty, 0) > ifnull(delivered_qty, 0)
@ -117,7 +117,7 @@ class DocType:
or ifnull(item.is_sub_contracted_item, 'No') = 'Yes'))""" % \
(", ".join(["%s"] * len(so_list))), tuple(so_list), as_dict=1)
packed_items = frappe.conn.sql("""select distinct pi.parent, pi.item_code, pi.warehouse as reserved_warhouse,
packed_items = frappe.db.sql("""select distinct pi.parent, pi.item_code, pi.warehouse as reserved_warhouse,
(((so_item.qty - ifnull(so_item.delivered_qty, 0)) * pi.qty) / so_item.qty)
as pending_qty
from `tabSales Order Item` so_item, `tabPacked Item` pi
@ -136,7 +136,7 @@ class DocType:
self.clear_item_table()
for p in items:
item_details = frappe.conn.sql("""select description, stock_uom, default_bom
item_details = frappe.db.sql("""select description, stock_uom, default_bom
from tabItem where name=%s""", p['item_code'])
pi = addchild(self.doc, 'pp_details', 'Production Plan Item', self.doclist)
pi.sales_order = p['parent']
@ -162,7 +162,7 @@ class DocType:
frappe.throw("Please enter bom no for item: %s at row no: %s" %
(d.item_code, d.idx))
else:
bom = frappe.conn.sql("""select name from `tabBOM` where name = %s and item = %s
bom = frappe.db.sql("""select name from `tabBOM` where name = %s and item = %s
and docstatus = 1 and is_active = 1""",
(d.bom_no, d.item_code), as_dict = 1)
if not bom:
@ -249,7 +249,7 @@ class DocType:
bom_wise_item_details = {}
if self.doc.use_multi_level_bom:
# get all raw materials with sub assembly childs
for d in frappe.conn.sql("""select fb.item_code,
for d in frappe.db.sql("""select fb.item_code,
ifnull(sum(fb.qty_consumed_per_unit), 0) as qty,
fb.description, fb.stock_uom, it.min_order_qty
from `tabBOM Explosion Item` fb,`tabItem` it
@ -261,7 +261,7 @@ class DocType:
else:
# Get all raw materials considering SA items as raw materials,
# so no childs of SA items
for d in frappe.conn.sql("""select bom_item.item_code,
for d in frappe.db.sql("""select bom_item.item_code,
ifnull(sum(bom_item.qty_consumed_per_unit), 0) as qty,
bom_item.description, bom_item.stock_uom, item.min_order_qty
from `tabBOM Item` bom_item, tabItem item
@ -288,7 +288,7 @@ class DocType:
total_qty = sum([flt(d[0]) for d in self.item_dict[item]])
for item_details in self.item_dict[item]:
item_list.append([item, item_details[1], item_details[2], item_details[0]])
item_qty = frappe.conn.sql("""select warehouse, indented_qty, ordered_qty, actual_qty
item_qty = frappe.db.sql("""select warehouse, indented_qty, ordered_qty, actual_qty
from `tabBin` where item_code = %s""", item, as_dict=1)
i_qty, o_qty, a_qty = 0, 0, 0
for w in item_qty:
@ -353,7 +353,7 @@ class DocType:
def get_projected_qty(self):
items = self.item_dict.keys()
item_projected_qty = frappe.conn.sql("""select item_code, sum(projected_qty)
item_projected_qty = frappe.db.sql("""select item_code, sum(projected_qty)
from `tabBin` where item_code in (%s) group by item_code""" %
(", ".join(["%s"]*len(items)),), tuple(items))

View File

@ -17,11 +17,11 @@ class DocType:
self.doclist = doclist
def update_bom_operation(self):
bom_list = frappe.conn.sql(" select DISTINCT parent from `tabBOM Operation` where workstation = '%s'" % self.doc.name)
bom_list = frappe.db.sql(" select DISTINCT parent from `tabBOM Operation` where workstation = '%s'" % self.doc.name)
for bom_no in bom_list:
frappe.conn.sql("update `tabBOM Operation` set hour_rate = '%s' where parent = '%s' and workstation = '%s'"%( self.doc.hour_rate, bom_no[0], self.doc.name))
frappe.db.sql("update `tabBOM Operation` set hour_rate = '%s' where parent = '%s' and workstation = '%s'"%( self.doc.hour_rate, bom_no[0], self.doc.name))
def on_update(self):
frappe.conn.set(self.doc, 'overhead', flt(self.doc.hour_rate_electricity) + flt(self.doc.hour_rate_consumable) + flt(self.doc.hour_rate_rent))
frappe.conn.set(self.doc, 'hour_rate', flt(self.doc.hour_rate_labour) + flt(self.doc.overhead))
frappe.db.set(self.doc, 'overhead', flt(self.doc.hour_rate_electricity) + flt(self.doc.hour_rate_consumable) + flt(self.doc.hour_rate_rent))
frappe.db.set(self.doc, 'hour_rate', flt(self.doc.hour_rate_labour) + flt(self.doc.overhead))
self.update_bom_operation()

View File

@ -18,6 +18,6 @@ execute:frappe.reload_doc('buying', 'doctype', 'supplier') # 2014-01-29
erpnext.patches.4_0.map_charge_to_taxes_and_charges
execute:frappe.reload_doc('support', 'doctype', 'newsletter') # 2014-01-31
execute:frappe.reload_doc('hr', 'doctype', 'employee') # 2014-02-03
execute:frappe.conn.sql("update tabPage set module='Core' where name='Setup'")
execute:frappe.db.sql("update tabPage set module='Core' where name='Setup'")
erpnext.patches.4_0.fields_to_be_renamed
erpnext.patches.4_0.rename_sitemap_to_route

View File

@ -112,7 +112,7 @@ def reload_docs(docs):
frappe.reload_doc(get_module(dn), "doctype", dn.lower().replace(" ", "_"))
# reload all standard print formats
for pf in frappe.conn.sql("""select name, module from `tabPrint Format`
for pf in frappe.db.sql("""select name, module from `tabPrint Format`
where ifnull(standard, 'No') = 'Yes'""", as_dict=1):
try:
frappe.reload_doc(pf.module, "Print Format", pf.name)
@ -121,10 +121,10 @@ def reload_docs(docs):
pass
# reload all standard reports
for r in frappe.conn.sql("""select name, ref_doctype from `tabReport`
for r in frappe.db.sql("""select name, ref_doctype from `tabReport`
where ifnull(is_standard, 'No') = 'Yes'
and report_type in ('Report Builder', 'Query Report')""", as_dict=1):
frappe.reload_doc(get_module(r.ref_doctype), "Report", r.name)
def get_module(dn):
return frappe.conn.get_value("DocType", dn, "module").lower().replace(" ", "_")
return frappe.db.get_value("DocType", dn, "module").lower().replace(" ", "_")

View File

@ -7,10 +7,10 @@ import frappe
def execute():
# udpate sales cycle
for d in ['Sales Invoice', 'Sales Order', 'Quotation', 'Delivery Note']:
frappe.conn.sql("""update `tab%s` set taxes_and_charges=charge""" % d)
frappe.db.sql("""update `tab%s` set taxes_and_charges=charge""" % d)
# udpate purchase cycle
for d in ['Purchase Invoice', 'Purchase Order', 'Supplier Quotation', 'Purchase Receipt']:
frappe.conn.sql("""update `tab%s` set taxes_and_charges=purchase_other_charges""" % d)
frappe.db.sql("""update `tab%s` set taxes_and_charges=purchase_other_charges""" % d)
frappe.conn.sql("""update `tabPurchase Taxes and Charges` set parentfield='other_charges'""")
frappe.db.sql("""update `tabPurchase Taxes and Charges` set parentfield='other_charges'""")

View File

@ -6,7 +6,7 @@ import frappe
def execute():
from frappe.core.page.user_properties import user_properties
for warehouse, profile in frappe.conn.sql("""select parent, user from `tabWarehouse User`"""):
for warehouse, profile in frappe.db.sql("""select parent, user from `tabWarehouse User`"""):
user_properties.add(profile, "Warehouse", warehouse)
frappe.delete_doc("DocType", "Warehouse User")

View File

@ -11,14 +11,14 @@ def execute():
reset("Report")
# patch to move print, email into DocPerm
for doctype, hide_print, hide_email in frappe.conn.sql("""select name, ifnull(allow_print, 0), ifnull(allow_email, 0)
for doctype, hide_print, hide_email in frappe.db.sql("""select name, ifnull(allow_print, 0), ifnull(allow_email, 0)
from `tabDocType` where ifnull(issingle, 0)=0 and ifnull(istable, 0)=0 and
(ifnull(allow_print, 0)=0 or ifnull(allow_email, 0)=0)"""):
if not hide_print:
frappe.conn.sql("""update `tabDocPerm` set `print`=1
frappe.db.sql("""update `tabDocPerm` set `print`=1
where permlevel=0 and `read`=1 and parent=%s""", doctype)
if not hide_email:
frappe.conn.sql("""update `tabDocPerm` set `email`=1
frappe.db.sql("""update `tabDocPerm` set `email`=1
where permlevel=0 and `read`=1 and parent=%s""", doctype)

View File

@ -8,5 +8,5 @@ def execute():
frappe.reload_doc("support", "doctype", "maintenance_schedule_detail")
frappe.reload_doc("support", "doctype", "maintenance_schedule_item")
frappe.conn.sql("""update `tabMaintenance Schedule Detail` set sales_person=incharge_name""")
frappe.conn.sql("""update `tabMaintenance Schedule Item` set sales_person=incharge_name""")
frappe.db.sql("""update `tabMaintenance Schedule Detail` set sales_person=incharge_name""")
frappe.db.sql("""update `tabMaintenance Schedule Item` set sales_person=incharge_name""")

View File

@ -20,13 +20,13 @@ def execute():
def update_user_properties():
frappe.reload_doc("core", "doctype", "docfield")
for d in frappe.conn.sql("""select parent, defkey, defvalue from tabDefaultValue
for d in frappe.db.sql("""select parent, defkey, defvalue from tabDefaultValue
where parent not in ('__global', 'Control Panel')""", as_dict=True):
df = frappe.conn.sql("""select options from tabDocField
df = frappe.db.sql("""select options from tabDocField
where fieldname=%s and fieldtype='Link'""", d.defkey, as_dict=True)
if df:
frappe.conn.sql("""update tabDefaultValue
frappe.db.sql("""update tabDefaultValue
set defkey=%s, parenttype='Restriction'
where defkey=%s and
parent not in ('__global', 'Control Panel')""", (df[0].options, d.defkey))
@ -34,7 +34,7 @@ def update_user_properties():
def update_user_match():
import frappe.defaults
doctype_matches = {}
for doctype, match in frappe.conn.sql("""select parent, `match` from `tabDocPerm`
for doctype, match in frappe.db.sql("""select parent, `match` from `tabDocPerm`
where `match` like %s and ifnull(`match`, '')!="leave_approver:user" """, "%:user"):
doctype_matches.setdefault(doctype, []).append(match)
@ -42,7 +42,7 @@ def update_user_match():
meta = frappe.get_doctype(doctype)
# for each user with roles of this doctype, check if match condition applies
for profile in frappe.conn.sql_list("""select name from `tabProfile`
for profile in frappe.db.sql_list("""select name from `tabProfile`
where enabled=1 and user_type='System User'"""):
user_roles = frappe.get_roles(profile)
@ -68,7 +68,7 @@ def update_user_match():
# if match condition applies, restrict that user
# add that doc's restriction to that user
for match in user_matches:
for name in frappe.conn.sql_list("""select name from `tab{doctype}`
for name in frappe.db.sql_list("""select name from `tab{doctype}`
where `{field}`=%s""".format(doctype=doctype, field=match.split(":")[0]), profile):
frappe.defaults.add_default(doctype, name, profile, "Restriction")
@ -77,12 +77,12 @@ def add_employee_restrictions_to_leave_approver():
from frappe.core.page.user_properties import user_properties
# add restrict rights to HR User and HR Manager
frappe.conn.sql("""update `tabDocPerm` set `restrict`=1 where parent in ('Employee', 'Leave Application')
frappe.db.sql("""update `tabDocPerm` set `restrict`=1 where parent in ('Employee', 'Leave Application')
and role in ('HR User', 'HR Manager') and permlevel=0 and `read`=1""")
frappe.model.doctype.clear_cache()
# add Employee restrictions (in on_update method)
for employee in frappe.conn.sql_list("""select name from `tabEmployee`
for employee in frappe.db.sql_list("""select name from `tabEmployee`
where exists(select leave_approver from `tabEmployee Leave Approver`
where `tabEmployee Leave Approver`.parent=`tabEmployee`.name)
or ifnull(`reports_to`, '')!=''"""):
@ -91,16 +91,16 @@ def add_employee_restrictions_to_leave_approver():
def update_permissions():
# clear match conditions other than owner
frappe.conn.sql("""update tabDocPerm set `match`=''
frappe.db.sql("""update tabDocPerm set `match`=''
where ifnull(`match`,'') not in ('', 'owner')""")
def remove_duplicate_restrictions():
# remove duplicate restrictions (if they exist)
for d in frappe.conn.sql("""select parent, defkey, defvalue,
for d in frappe.db.sql("""select parent, defkey, defvalue,
count(*) as cnt from tabDefaultValue
where parent not in ('__global', 'Control Panel')
group by parent, defkey, defvalue""", as_dict=1):
if d.cnt > 1:
# order by parenttype so that restriction does not get removed!
frappe.conn.sql("""delete from tabDefaultValue where parent=%s, defkey=%s,
frappe.db.sql("""delete from tabDefaultValue where parent=%s, defkey=%s,
defvalue=%s order by parenttype limit %s""", (d.parent, d.defkey, d.defvalue, d.cnt-1))

View File

@ -32,12 +32,12 @@ class DocType:
self.add_calendar_event()
def update_percent_complete(self):
total = frappe.conn.sql("""select count(*) from tabTask where project=%s""",
total = frappe.db.sql("""select count(*) from tabTask where project=%s""",
self.doc.name)[0][0]
if total:
completed = frappe.conn.sql("""select count(*) from tabTask where
completed = frappe.db.sql("""select count(*) from tabTask where
project=%s and status in ('Closed', 'Cancelled')""", self.doc.name)[0][0]
frappe.conn.set_value("Project", self.doc.name, "percent_complete",
frappe.db.set_value("Project", self.doc.name, "percent_complete",
int(float(completed) / total * 100))
def add_calendar_event(self):

View File

@ -21,7 +21,7 @@ class DocType:
}
def get_customer_details(self):
cust = frappe.conn.sql("select customer_name from `tabCustomer` where name=%s", self.doc.customer)
cust = frappe.db.sql("select customer_name from `tabCustomer` where name=%s", self.doc.customer)
if cust:
ret = {'customer_name': cust and cust[0][0] or ''}
return ret
@ -38,7 +38,7 @@ class DocType:
self.update_status()
def update_status(self):
status = frappe.conn.get_value("Task", self.doc.name, "status")
status = frappe.db.get_value("Task", self.doc.name, "status")
if self.doc.status=="Working" and status !="Working" and not self.doc.act_start_date:
self.doc.act_start_date = today()
@ -66,7 +66,7 @@ def get_events(start, end, filters=None):
if filters[key]:
conditions += " and " + key + ' = "' + filters[key].replace('"', '\"') + '"'
data = frappe.conn.sql("""select name, exp_start_date, exp_end_date,
data = frappe.db.sql("""select name, exp_start_date, exp_end_date,
subject, status, project from `tabTask`
where ((exp_start_date between '%(start)s' and '%(end)s') \
or (exp_end_date between '%(start)s' and '%(end)s'))
@ -80,7 +80,7 @@ def get_events(start, end, filters=None):
def get_project(doctype, txt, searchfield, start, page_len, filters):
from erpnext.controllers.queries import get_match_cond
return frappe.conn.sql(""" select name from `tabProject`
return frappe.db.sql(""" select name from `tabProject`
where %(key)s like "%(txt)s"
%(mcond)s
order by name

View File

@ -38,7 +38,7 @@ class DocType:
self.doc.status="Billed"
def validate_overlap(self):
existing = frappe.conn.sql_list("""select name from `tabTime Log` where owner=%s and
existing = frappe.db.sql_list("""select name from `tabTime Log` where owner=%s and
(
(from_time between %s and %s) or
(to_time between %s and %s) or
@ -67,7 +67,7 @@ def get_events(start, end):
frappe.msgprint(_("No Permission"), raise_exception=1)
match = build_match_conditions("Time Log")
data = frappe.conn.sql("""select name, from_time, to_time,
data = frappe.db.sql("""select name, from_time, to_time,
activity_type, task, project from `tabTime Log`
where from_time between '%(start)s' and '%(end)s' or to_time between '%(start)s' and '%(end)s'
%(match)s""" % {

View File

@ -15,15 +15,15 @@ class TimeLogBatchTest(unittest.TestCase):
time_log.insert()
time_log.submit()
self.assertEquals(frappe.conn.get_value("Time Log", time_log.doc.name, "status"), "Submitted")
self.assertEquals(frappe.db.get_value("Time Log", time_log.doc.name, "status"), "Submitted")
tlb = frappe.bean(copy=test_records[0])
tlb.doclist[1].time_log = time_log.doc.name
tlb.insert()
tlb.submit()
self.assertEquals(frappe.conn.get_value("Time Log", time_log.doc.name, "status"), "Batched for Billing")
self.assertEquals(frappe.db.get_value("Time Log", time_log.doc.name, "status"), "Batched for Billing")
tlb.cancel()
self.assertEquals(frappe.conn.get_value("Time Log", time_log.doc.name, "status"), "Submitted")
self.assertEquals(frappe.db.get_value("Time Log", time_log.doc.name, "status"), "Submitted")
test_records = [[
{

View File

@ -19,7 +19,7 @@ def execute(filters=None):
task_map = get_task_map()
conditions = build_conditions(filters)
time_logs = frappe.conn.sql("""select * from `tabTime Log`
time_logs = frappe.db.sql("""select * from `tabTime Log`
where docstatus < 2 %s order by owner asc""" % (conditions, ), filters, as_dict=1)
if time_logs:
@ -49,7 +49,7 @@ def execute(filters=None):
return columns, data
def get_profile_map():
profiles = frappe.conn.sql("""select name,
profiles = frappe.db.sql("""select name,
concat(first_name, if(last_name, (' ' + last_name), '')) as fullname
from tabProfile""", as_dict=1)
profile_map = {}
@ -59,7 +59,7 @@ def get_profile_map():
return profile_map
def get_task_map():
tasks = frappe.conn.sql("""select name, subject from tabTask""", as_dict=1)
tasks = frappe.db.sql("""select name, subject from tabTask""", as_dict=1)
task_map = {}
for t in tasks:
task_map.setdefault(t.name, []).append(t.subject)

View File

@ -28,11 +28,11 @@ def get_columns():
"Project Start Date:Date:120", "Completion Date:Date:120"]
def get_project_details():
return frappe.conn.sql(""" select name, project_name, status, company, customer, project_value,
return frappe.db.sql(""" select name, project_name, status, company, customer, project_value,
project_start_date, completion_date from tabProject where docstatus < 2""", as_dict=1)
def get_purchased_items_cost():
pr_items = frappe.conn.sql("""select project_name, sum(base_amount) as amount
pr_items = frappe.db.sql("""select project_name, sum(base_amount) as amount
from `tabPurchase Receipt Item` where ifnull(project_name, '') != ''
and docstatus = 1 group by project_name""", as_dict=1)
@ -43,7 +43,7 @@ def get_purchased_items_cost():
return pr_item_map
def get_issued_items_cost():
se_items = frappe.conn.sql("""select se.project_name, sum(se_item.amount) as amount
se_items = frappe.db.sql("""select se.project_name, sum(se_item.amount) as amount
from `tabStock Entry` se, `tabStock Entry Detail` se_item
where se.name = se_item.parent and se.docstatus = 1 and ifnull(se_item.t_warehouse, '') = ''
and ifnull(se.project_name, '') != '' group by se.project_name""", as_dict=1)
@ -55,12 +55,12 @@ def get_issued_items_cost():
return se_item_map
def get_delivered_items_cost():
dn_items = frappe.conn.sql("""select dn.project_name, sum(dn_item.base_amount) as amount
dn_items = frappe.db.sql("""select dn.project_name, sum(dn_item.base_amount) as amount
from `tabDelivery Note` dn, `tabDelivery Note Item` dn_item
where dn.name = dn_item.parent and dn.docstatus = 1 and ifnull(dn.project_name, '') != ''
group by dn.project_name""", as_dict=1)
si_items = frappe.conn.sql("""select si.project_name, sum(si_item.base_amount) as amount
si_items = frappe.db.sql("""select si.project_name, sum(si_item.base_amount) as amount
from `tabSales Invoice` si, `tabSales Invoice Item` si_item
where si.name = si_item.parent and si.docstatus = 1 and ifnull(si.update_stock, 0) = 1
and ifnull(si.is_pos, 0) = 1 and ifnull(si.project_name, '') != ''

View File

@ -8,7 +8,7 @@ import frappe
@frappe.whitelist()
def get_time_log_list(doctype, txt, searchfield, start, page_len, filters):
return frappe.conn.get_values("Time Log", filters, ["name", "activity_type", "owner"])
return frappe.db.get_values("Time Log", filters, ["name", "activity_type", "owner"])
@frappe.whitelist()
def query_task(doctype, txt, searchfield, start, page_len, filters):
@ -19,7 +19,7 @@ def query_task(doctype, txt, searchfield, start, page_len, filters):
match_conditions = build_match_conditions("Task")
match_conditions = ("and" + match_conditions) if match_conditions else ""
return frappe.conn.sql("""select name, subject from `tabTask`
return frappe.db.sql("""select name, subject from `tabTask`
where (`%s` like %s or `subject` like %s) %s
order by
case when `subject` like %s then 0 else 1 end,

Some files were not shown because too many files have changed in this diff Show More