more message fixing

This commit is contained in:
Rushabh Mehta 2014-04-15 16:30:55 +05:30
parent c5e057f676
commit 8a40c136ce
15 changed files with 130 additions and 201 deletions

View File

@ -42,7 +42,7 @@ class BankReconciliation(Document):
for d in self.get('entries'): for d in self.get('entries'):
if d.clearance_date: if d.clearance_date:
if d.cheque_date and getdate(d.clearance_date) < getdate(d.cheque_date): if d.cheque_date and getdate(d.clearance_date) < getdate(d.cheque_date):
frappe.throw("Clearance Date can not be before Cheque Date (Row #%s)" % d.idx) frappe.throw(_("Clearance date cannot be before check date in row {0}").format(d.idx))
frappe.db.set_value("Journal Voucher", d.voucher_id, "clearance_date", d.clearance_date) frappe.db.set_value("Journal Voucher", d.voucher_id, "clearance_date", d.clearance_date)
frappe.db.sql("""update `tabJournal Voucher` set clearance_date = %s, modified = %s frappe.db.sql("""update `tabJournal Voucher` set clearance_date = %s, modified = %s

View File

@ -4,9 +4,9 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import frappe import frappe
from frappe.utils import flt, fmt_money, getdate from frappe.utils import flt, fmt_money, getdate, formatdate
from frappe import _ from frappe import _
from frappe.model.document import Document from frappe.model.document import Document
class GLEntry(Document): class GLEntry(Document):
@ -27,28 +27,26 @@ class GLEntry(Document):
# Update outstanding amt on against voucher # Update outstanding amt on against voucher
if self.against_voucher and self.against_voucher_type != "POS" \ if self.against_voucher and self.against_voucher_type != "POS" \
and update_outstanding == 'Yes': and update_outstanding == 'Yes':
update_outstanding_amt(self.account, self.against_voucher_type, update_outstanding_amt(self.account, self.against_voucher_type,
self.against_voucher) self.against_voucher)
def check_mandatory(self): def check_mandatory(self):
mandatory = ['account','remarks','voucher_type','voucher_no','fiscal_year','company'] mandatory = ['account','remarks','voucher_type','voucher_no','fiscal_year','company']
for k in mandatory: for k in mandatory:
if not self.get(k): if not self.get(k):
frappe.throw(k + _(" is mandatory for GL Entry")) frappe.throw(_("{0} is required").format(k))
# Zero value transaction is not allowed # Zero value transaction is not allowed
if not (flt(self.debit) or flt(self.credit)): if not (flt(self.debit) or flt(self.credit)):
frappe.throw(_("GL Entry: Debit or Credit amount is mandatory for ") + frappe.throw(_("Either debit or credit amount is required for {0}").format(self.account))
self.account)
def pl_must_have_cost_center(self): def pl_must_have_cost_center(self):
if frappe.db.get_value("Account", self.account, "report_type") == "Profit and Loss": if frappe.db.get_value("Account", self.account, "report_type") == "Profit and Loss":
if not self.cost_center and self.voucher_type != 'Period Closing Voucher': if not self.cost_center and self.voucher_type != 'Period Closing Voucher':
frappe.throw(_("Cost Center must be specified for Profit and Loss type account: ") frappe.throw(_("Cost Center is required for 'Profit and Loss' account {0}").format(self.account))
+ self.account)
elif self.cost_center: elif self.cost_center:
self.cost_center = None self.cost_center = None
def validate_posting_date(self): def validate_posting_date(self):
from erpnext.accounts.utils import validate_fiscal_year from erpnext.accounts.utils import validate_fiscal_year
validate_fiscal_year(self.posting_date, self.fiscal_year, "Posting Date") validate_fiscal_year(self.posting_date, self.fiscal_year, "Posting Date")
@ -56,55 +54,51 @@ class GLEntry(Document):
def check_pl_account(self): def check_pl_account(self):
if self.is_opening=='Yes' and \ if self.is_opening=='Yes' and \
frappe.db.get_value("Account", self.account, "report_type")=="Profit and Loss": frappe.db.get_value("Account", self.account, "report_type")=="Profit and Loss":
frappe.throw(_("For opening balance entry, account can not be \ frappe.throw(_("'Profit and Loss' type account {0} not allowed in Opening Entry").format(self.account))
a Profit and Loss type account"))
def validate_account_details(self, adv_adj): def validate_account_details(self, adv_adj):
"""Account must be ledger, active and not freezed""" """Account must be ledger, active and not freezed"""
ret = frappe.db.sql("""select group_or_ledger, docstatus, company ret = frappe.db.sql("""select group_or_ledger, docstatus, company
from tabAccount where name=%s""", self.account, as_dict=1)[0] from tabAccount where name=%s""", self.account, as_dict=1)[0]
if ret.group_or_ledger=='Group': if ret.group_or_ledger=='Group':
frappe.throw(_("Account") + ": " + self.account + _(" is not a ledger")) frappe.throw(_("Account {0} cannot be a Group").format(self.account))
if ret.docstatus==2: if ret.docstatus==2:
frappe.throw(_("Account") + ": " + self.account + _(" is not active")) frappe.throw(_("Account {0} is inactive").format(self.account))
if ret.company != self.company: if ret.company != self.company:
frappe.throw(_("Account") + ": " + self.account + frappe.throw(_("Account {0} does not belong to Company {1}").format(self.account, self.company))
_(" does not belong to the company") + ": " + self.company)
def validate_cost_center(self): def validate_cost_center(self):
if not hasattr(self, "cost_center_company"): if not hasattr(self, "cost_center_company"):
self.cost_center_company = {} self.cost_center_company = {}
def _get_cost_center_company(): def _get_cost_center_company():
if not self.cost_center_company.get(self.cost_center): if not self.cost_center_company.get(self.cost_center):
self.cost_center_company[self.cost_center] = frappe.db.get_value( self.cost_center_company[self.cost_center] = frappe.db.get_value(
"Cost Center", self.cost_center, "company") "Cost Center", self.cost_center, "company")
return self.cost_center_company[self.cost_center] return self.cost_center_company[self.cost_center]
if self.cost_center and _get_cost_center_company() != self.company: if self.cost_center and _get_cost_center_company() != self.company:
frappe.throw(_("Cost Center") + ": " + self.cost_center + frappe.throw(_("Cost Center {0} does not belong to Company {1}").format(self.cost_center, self.company))
_(" does not belong to the company") + ": " + self.company)
def validate_balance_type(account, adv_adj=False): def validate_balance_type(account, adv_adj=False):
if not adv_adj and account: if not adv_adj and account:
balance_must_be = frappe.db.get_value("Account", account, "balance_must_be") balance_must_be = frappe.db.get_value("Account", account, "balance_must_be")
if balance_must_be: if balance_must_be:
balance = frappe.db.sql("""select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0)) balance = frappe.db.sql("""select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
from `tabGL Entry` where account = %s""", account)[0][0] from `tabGL Entry` where account = %s""", account)[0][0]
if (balance_must_be=="Debit" and flt(balance) < 0) or \ if (balance_must_be=="Debit" and flt(balance) < 0) or \
(balance_must_be=="Credit" and flt(balance) > 0): (balance_must_be=="Credit" and flt(balance) > 0):
frappe.throw("Credit" if balance_must_be=="Debit" else "Credit" frappe.throw(_("Balance for Account {0} must always be {1}").format(account, _(balance_must_be)))
+ _(" balance is not allowed for account ") + account)
def check_freezing_date(posting_date, adv_adj=False): def check_freezing_date(posting_date, adv_adj=False):
""" """
Nobody can do GL Entries where posting date is before freezing date Nobody can do GL Entries where posting date is before freezing date
except authorized person except authorized person
""" """
if not adv_adj: if not adv_adj:
@ -113,14 +107,13 @@ def check_freezing_date(posting_date, adv_adj=False):
bde_auth_role = frappe.db.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) \ if getdate(posting_date) <= getdate(acc_frozen_upto) \
and not bde_auth_role in frappe.user.get_roles(): and not bde_auth_role in frappe.user.get_roles():
frappe.throw(_("You are not authorized to do/modify back dated entries before ") frappe.throw(_("You are not authorized to add or update entries before {0}").format(formatdate(acc_frozen_upto)))
+ getdate(acc_frozen_upto).strftime('%d-%m-%Y'))
def update_outstanding_amt(account, against_voucher_type, against_voucher, on_cancel=False): def update_outstanding_amt(account, against_voucher_type, against_voucher, on_cancel=False):
# get final outstanding amt # get final outstanding amt
bal = flt(frappe.db.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` from `tabGL Entry`
where against_voucher_type=%s and against_voucher=%s and account = %s""", where against_voucher_type=%s and against_voucher=%s and account = %s""",
(against_voucher_type, against_voucher, account))[0][0] or 0.0) (against_voucher_type, against_voucher, account))[0][0] or 0.0)
if against_voucher_type == 'Purchase Invoice': if against_voucher_type == 'Purchase Invoice':
@ -129,31 +122,28 @@ def update_outstanding_amt(account, against_voucher_type, against_voucher, on_ca
against_voucher_amount = flt(frappe.db.sql(""" against_voucher_amount = flt(frappe.db.sql("""
select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0)) select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
from `tabGL Entry` where voucher_type = 'Journal Voucher' and voucher_no = %s from `tabGL Entry` where voucher_type = 'Journal Voucher' and voucher_no = %s
and account = %s and ifnull(against_voucher, '') = ''""", and account = %s and ifnull(against_voucher, '') = ''""",
(against_voucher, account))[0][0]) (against_voucher, account))[0][0])
bal = against_voucher_amount + bal bal = against_voucher_amount + bal
if against_voucher_amount < 0: if against_voucher_amount < 0:
bal = -bal bal = -bal
# Validation : Outstanding can not be negative # Validation : Outstanding can not be negative
if bal < 0 and not on_cancel: if bal < 0 and not on_cancel:
frappe.throw(_("Outstanding for Voucher ") + against_voucher + _(" will become ") + frappe.throw(_("Outstanding for {0} cannot be less than zero ({1})").format(against_voucher, fmt_money(bal)))
fmt_money(bal) + _(". Outstanding cannot be less than zero. \
Please match exact outstanding."))
# Update outstanding amt on against voucher # Update outstanding amt on against voucher
if against_voucher_type in ["Sales Invoice", "Purchase Invoice"]: if against_voucher_type in ["Sales Invoice", "Purchase Invoice"]:
frappe.db.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, '%s', '%s'), (bal, against_voucher)) (against_voucher_type, '%s', '%s'), (bal, against_voucher))
def validate_frozen_account(account, adv_adj=None): def validate_frozen_account(account, adv_adj=None):
frozen_account = frappe.db.get_value("Account", account, "freeze_account") frozen_account = frappe.db.get_value("Account", account, "freeze_account")
if frozen_account == 'Yes' and not adv_adj: if frozen_account == 'Yes' and not adv_adj:
frozen_accounts_modifier = frappe.db.get_value( 'Accounts Settings', None, frozen_accounts_modifier = frappe.db.get_value( 'Accounts Settings', None,
'frozen_accounts_modifier') 'frozen_accounts_modifier')
if not frozen_accounts_modifier: if not frozen_accounts_modifier:
frappe.throw(account + _(" is a frozen account. Either make the account active or assign role in Accounts Settings who can create / modify entries against this account")) frappe.throw(_("Account {0} is frozen").format(account))
elif frozen_accounts_modifier not in frappe.user.get_roles(): elif frozen_accounts_modifier not in frappe.user.get_roles():
frappe.throw(account + _(" is a frozen account. To create / edit transactions against this account, you need role") \ frappe.throw(_("Not authorized to edit frozen Account {0}").format(account))
+ ": " + frozen_accounts_modifier)

View File

@ -225,13 +225,11 @@ class JournalVoucher(AccountsController):
for d in self.get("entries"): for d in self.get("entries"):
if d.against_invoice and frappe.db.get_value("Sales Invoice", if d.against_invoice and frappe.db.get_value("Sales Invoice",
d.against_invoice, "debit_to") != d.account: d.against_invoice, "debit_to") != d.account:
frappe.throw(_("Row #") + cstr(d.idx) + ": " + frappe.throw(_("Account {0} must be sames as Debit To Account in Sales Invoice in row {0}").format(d.account, d.idx))
_("Account is not matching with Debit To account of Sales Invoice"))
if d.against_voucher and frappe.db.get_value("Purchase Invoice", if d.against_voucher and frappe.db.get_value("Purchase Invoice",
d.against_voucher, "credit_to") != d.account: d.against_voucher, "credit_to") != d.account:
frappe.throw(_("Row #") + cstr(d.idx) + ": " + frappe.throw(_("Account {0} must be sames as Credit To Account in Purchase Invoice in row {0}").format(d.account, d.idx))
_("Account is not matching with Credit To account of Purchase Invoice"))
def make_gl_entries(self, cancel=0, adv_adj=0): def make_gl_entries(self, cancel=0, adv_adj=0):
from erpnext.accounts.general_ledger import make_gl_entries from erpnext.accounts.general_ledger import make_gl_entries

View File

@ -43,7 +43,7 @@ class POSSetting(Document):
for link_dn in dn_list: for link_dn in dn_list:
if link_dn and not frappe.db.exists({"doctype": link_dt, if link_dn and not frappe.db.exists({"doctype": link_dt,
"company": self.company, "name": link_dn}): "company": self.company, "name": link_dn}):
frappe.throw(link_dn +_(" does not belong to ") + self.company) frappe.throw(_("{0} does not belong to Company {1}").format(link_dn, self.company))
def on_update(self): def on_update(self):
self.set_defaults() self.set_defaults()

View File

@ -9,28 +9,26 @@ from frappe import throw, _
from frappe.model.controller import DocListController from frappe.model.controller import DocListController
class PricingRule(DocListController): class PricingRule(DocListController):
def validate(self): def validate(self):
self.validate_mandatory() self.validate_mandatory()
self.cleanup_fields_value() self.cleanup_fields_value()
def validate_mandatory(self): def validate_mandatory(self):
for field in ["apply_on", "applicable_for", "price_or_discount"]: for field in ["apply_on", "applicable_for", "price_or_discount"]:
val = self.get("applicable_for") val = self.get("applicable_for")
if val and not self.get(frappe.scrub(val)): if val and not self.get(frappe.scrub(val)):
throw("{fname} {msg}".format(fname = _(val), msg = _(" is mandatory")), throw(_("{0} is required").format(val), frappe.MandatoryError)
frappe.MandatoryError)
def cleanup_fields_value(self): def cleanup_fields_value(self):
for logic_field in ["apply_on", "applicable_for", "price_or_discount"]: for logic_field in ["apply_on", "applicable_for", "price_or_discount"]:
fieldname = frappe.scrub(self.get(logic_field) or "") fieldname = frappe.scrub(self.get(logic_field) or "")
# reset all values except for the logic field # reset all values except for the logic field
options = (self.meta.get_options(logic_field) or "").split("\n") options = (self.meta.get_options(logic_field) or "").split("\n")
for f in options: for f in options:
if not f: continue if not f: continue
f = frappe.scrub(f) f = frappe.scrub(f)
if f!=fieldname: if f!=fieldname:
self.set(f, None) self.set(f, None)

View File

@ -221,11 +221,11 @@ class PurchaseInvoice(BuyingController):
if d.purchase_order: if d.purchase_order:
submitted = frappe.db.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: if not submitted:
frappe.throw("Purchase Order : "+ cstr(d.purchase_order) +" is not submitted") frappe.throw(_("Purchase Order {0} is not submitted").format(d.purchase_order))
if d.purchase_receipt: if d.purchase_receipt:
submitted = frappe.db.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: if not submitted:
frappe.throw("Purchase Receipt : "+ cstr(d.purchase_receipt) +" is not submitted") frappe.throw(_("Purchase Receipt {0} is not submitted").format(d.purchase_receipt))
def update_against_document_in_jv(self): def update_against_document_in_jv(self):
@ -305,9 +305,7 @@ class PurchaseInvoice(BuyingController):
# accumulate valuation tax # accumulate valuation tax
if tax.category in ("Valuation", "Valuation and Total") and flt(tax.tax_amount): if tax.category in ("Valuation", "Valuation and Total") and flt(tax.tax_amount):
if auto_accounting_for_stock and not tax.cost_center: if auto_accounting_for_stock and not tax.cost_center:
frappe.throw(_("Row %(row)s: Cost Center is mandatory \ frappe.throw(_("Cost Center is required in row {0} in Taxes table for type {1}").format(tax.idx, _(tax.category)))
if tax/charges category is Valuation or Valuation and Total" %
{"row": tax.idx}))
valuation_tax.setdefault(tax.cost_center, 0) valuation_tax.setdefault(tax.cost_center, 0)
valuation_tax[tax.cost_center] += \ valuation_tax[tax.cost_center] += \
(tax.add_deduct_tax == "Add" and 1 or -1) * flt(tax.tax_amount) (tax.add_deduct_tax == "Add" and 1 or -1) * flt(tax.tax_amount)

View File

@ -8,12 +8,12 @@ import frappe
def get_items(price_list, sales_or_purchase, item=None, item_group=None): def get_items(price_list, sales_or_purchase, item=None, item_group=None):
condition = "" condition = ""
args = {"price_list": price_list} args = {"price_list": price_list}
if sales_or_purchase == "Sales": if sales_or_purchase == "Sales":
condition = "i.is_sales_item='Yes'" condition = "i.is_sales_item='Yes'"
else: else:
condition = "i.is_purchase_item='Yes'" condition = "i.is_purchase_item='Yes'"
if item_group and item_group != "All Item Groups": if item_group and item_group != "All Item Groups":
condition += " and i.item_group='%s'" % item_group.replace("'", "\'") condition += " and i.item_group='%s'" % item_group.replace("'", "\'")
@ -21,10 +21,10 @@ def get_items(price_list, sales_or_purchase, item=None, item_group=None):
condition += " and CONCAT(i.name, i.item_name) like %(name)s" condition += " and CONCAT(i.name, i.item_name) like %(name)s"
args["name"] = "%%%s%%" % item args["name"] = "%%%s%%" % item
return frappe.db.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 item_det.price_list_rate, item_det.currency
from `tabItem` i LEFT JOIN from `tabItem` i LEFT JOIN
(select item_code, price_list_rate, currency from (select item_code, price_list_rate, currency from
`tabItem Price` where price_list=%s) item_det `tabItem Price` where price_list=%s) item_det
ON ON
item_det.item_code=i.name item_det.item_code=i.name
@ -34,7 +34,7 @@ def get_items(price_list, sales_or_purchase, item=None, item_group=None):
@frappe.whitelist() @frappe.whitelist()
def get_item_code(barcode_serial_no): def get_item_code(barcode_serial_no):
input_via = "serial_no" input_via = "serial_no"
item_code = frappe.db.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) name=%s""", (barcode_serial_no), as_dict=1)
if not item_code: if not item_code:
@ -45,7 +45,7 @@ def get_item_code(barcode_serial_no):
if item_code: if item_code:
return item_code, input_via return item_code, input_via
else: else:
frappe.throw("Invalid Barcode / Serial No") frappe.throw(frappe._("Invalid Barcode or Serial No"))
@frappe.whitelist() @frappe.whitelist()
def get_mode_of_payment(): def get_mode_of_payment():

View File

@ -23,7 +23,7 @@ def _get_party_details(party=None, account=None, party_type="Customer", company=
party = out[party_type.lower()] party = out[party_type.lower()]
if not ignore_permissions and not frappe.has_permission(party_type, "read", party): if not ignore_permissions and not frappe.has_permission(party_type, "read", party):
frappe.throw("Not Permitted", frappe.PermissionError) frappe.throw(_("Not permitted"), frappe.PermissionError)
party = frappe.get_doc(party_type, party) party = frappe.get_doc(party_type, party)

View File

@ -294,20 +294,19 @@ def validate_expense_against_budget(args):
args["month_end_date"] = frappe.db.sql("select LAST_DAY(%s)", args["month_end_date"] = frappe.db.sql("select LAST_DAY(%s)",
args.posting_date)[0][0] args.posting_date)[0][0]
action_for, action = "Monthly", monthly_action action_for, action = _("Monthly"), monthly_action
elif yearly_action in ["Stop", "Warn"]: elif yearly_action in ["Stop", "Warn"]:
budget_amount = budget[0].budget_allocated budget_amount = budget[0].budget_allocated
action_for, action = "Monthly", yearly_action action_for, action = _("Annual"), yearly_action
if action_for: if action_for:
actual_expense = get_actual_expense(args) actual_expense = get_actual_expense(args)
if actual_expense > budget_amount: if actual_expense > budget_amount:
throw(action_for + _(" budget ") + cstr(budget_amount) + frappe.msgprint(_("{0} budget for Account {1} against Cost Center {2} will exceed by {3}").format(
_(" for account ") + args.account + _(" against cost center ") + _(action_for), args.account, args.cost_center, cstr(actual_expense - budget_amount)))
args.cost_center + _(" will exceed by ") + if action=="Stop":
cstr(actual_expense - budget_amount) + _(" after this transaction.") raise BudgetError
, exc=BudgetError if action=="Stop" else False)
def get_allocated_budget(distribution_id, posting_date, fiscal_year, yearly_budget): def get_allocated_budget(distribution_id, posting_date, fiscal_year, yearly_budget):
if distribution_id: if distribution_id:

View File

@ -5,7 +5,7 @@ from __future__ import unicode_literals
import frappe import frappe
from frappe.utils import cstr, flt from frappe.utils import cstr, flt
from frappe import msgprint, _ from frappe import _
from erpnext.stock.doctype.item.item import get_last_purchase_details from erpnext.stock.doctype.item.item import get_last_purchase_details
from erpnext.controllers.buying_controller import BuyingController from erpnext.controllers.buying_controller import BuyingController
@ -33,8 +33,7 @@ class PurchaseCommon(BuyingController):
if flt(d.conversion_factor): if flt(d.conversion_factor):
last_purchase_rate = flt(d.base_rate) / flt(d.conversion_factor) last_purchase_rate = flt(d.base_rate) / flt(d.conversion_factor)
else: else:
frappe.throw(_("Row ") + cstr(d.idx) + ": " + frappe.throw(_("UOM Conversion factor is required in row {0}").format(d.idx))
_("UOM Conversion Factor is mandatory"))
# update last purchsae rate # update last purchsae rate
if last_purchase_rate: if last_purchase_rate:
@ -71,7 +70,7 @@ class PurchaseCommon(BuyingController):
for d in obj.get(obj.fname): for d in obj.get(obj.fname):
# validation for valid qty # validation for valid qty
if flt(d.qty) < 0 or (d.parenttype != 'Purchase Receipt' and not flt(d.qty)): if flt(d.qty) < 0 or (d.parenttype != 'Purchase Receipt' and not flt(d.qty)):
frappe.throw("Please enter valid qty for item %s" % cstr(d.item_code)) frappe.throw(_("Please enter quantity for Item {0}").format(d.item_code))
# udpate with latest quantities # udpate with latest quantities
bin = frappe.db.sql("""select projected_qty from `tabBin` where bin = frappe.db.sql("""select projected_qty from `tabBin` where
@ -86,19 +85,17 @@ class PurchaseCommon(BuyingController):
item = frappe.db.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) 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))
from erpnext.stock.doctype.item.item import validate_end_of_life from erpnext.stock.doctype.item.item import validate_end_of_life
validate_end_of_life(d.item_code, item[0][3]) validate_end_of_life(d.item_code, item[0][3])
# validate stock item # validate stock item
if item[0][0]=='Yes' and d.qty and not d.warehouse: if item[0][0]=='Yes' and d.qty and not d.warehouse:
frappe.throw("Warehouse is mandatory for %s, since it is a stock item" % d.item_code) frappe.throw(_("Warehouse is mandatory for stock Item {0} in row {1}").format(d.item_code, d.idx))
# validate purchase item # validate purchase item
if item[0][1] != 'Yes' and item[0][2] != 'Yes': if item[0][1] != 'Yes' and item[0][2] != 'Yes':
frappe.throw("Item %s is not a purchase item or sub-contracted item. Please check" % (d.item_code)) frappe.throw(_("{0} must be a Purchased or Sub-Contracted Item in row {1}").format(d.item_code, d.idx))
# list criteria that should not repeat if item is stock item # list criteria that should not repeat if item is stock item
e = [getattr(d, "schedule_date", None), d.item_code, d.description, d.warehouse, d.uom, e = [getattr(d, "schedule_date", None), d.item_code, d.description, d.warehouse, d.uom,
@ -114,16 +111,14 @@ class PurchaseCommon(BuyingController):
if ch and ch[0][0] == 'Yes': if ch and ch[0][0] == 'Yes':
# check for same items # check for same items
if e in check_list: if e in check_list:
frappe.throw("""Item %s has been entered more than once with same description, schedule date, warehouse and uom.\n frappe.throw(_("Item {0} has been entered multiple times with same description or date or warehouse").format(d.item_code))
Please change any of the field value to enter the item twice""" % d.item_code)
else: else:
check_list.append(e) check_list.append(e)
elif ch and ch[0][0] == 'No': elif ch and ch[0][0] == 'No':
# check for same items # check for same items
if f in chk_dupl_itm: if f in chk_dupl_itm:
frappe.throw("""Item %s has been entered more than once with same description, schedule date.\n frappe.throw(_("Item {0} has been entered multiple times with same description or date").format(d.item_code))
Please change any of the field value to enter the item twice.""" % d.item_code)
else: else:
chk_dupl_itm.append(f) chk_dupl_itm.append(f)
@ -152,8 +147,7 @@ class PurchaseCommon(BuyingController):
stopped = frappe.db.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) status = 'Stopped'""" % (doctype, '%s'), docname)
if stopped: if stopped:
frappe.throw("One cannot do any transaction against %s : %s, it's status is 'Stopped'" % frappe.throw("{0} {1} status is 'Stopped'".format(doctype, docname), frappe.InvalidStatusError)
(doctype, docname), exc=frappe.InvalidStatusError)
def check_docstatus(self, check, doctype, docname, detail_doctype = ''): def check_docstatus(self, check, doctype, docname, detail_doctype = ''):
if check == 'Next': if check == 'Next':
@ -161,11 +155,10 @@ class PurchaseCommon(BuyingController):
where t1.name = t2.parent and t2.prevdoc_docname = %s and t1.docstatus = 1""" where t1.name = t2.parent and t2.prevdoc_docname = %s and t1.docstatus = 1"""
% (doctype, detail_doctype, '%s'), docname) % (doctype, detail_doctype, '%s'), docname)
if submitted: if submitted:
frappe.throw(cstr(doctype) + ": " + cstr(submitted[0][0]) frappe.throw(_("{0} {1} has already been submitted").format(doctype, submitted[0][0]))
+ _("has already been submitted."))
if check == 'Previous': if check == 'Previous':
submitted = frappe.db.sql("""select name from `tab%s` submitted = frappe.db.sql("""select name from `tab%s`
where docstatus = 1 and name = %s""" % (doctype, '%s'), docname) where docstatus = 1 and name = %s""" % (doctype, '%s'), docname)
if not submitted: if not submitted:
frappe.throw(cstr(doctype) + ": " + cstr(submitted[0][0]) + _("not submitted")) frappe.throw(_("{0} {1} is not submitted").format(doctype, submitted[0][0]))

View File

@ -4,7 +4,7 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import frappe import frappe
from frappe import _, throw from frappe import _, throw
from frappe.utils import flt, cint, today, cstr from frappe.utils import flt, cint, today
from erpnext.setup.utils import get_company_currency from erpnext.setup.utils import get_company_currency
from erpnext.accounts.utils import get_fiscal_year, validate_fiscal_year from erpnext.accounts.utils import get_fiscal_year, validate_fiscal_year
from erpnext.utilities.transaction_base import TransactionBase from erpnext.utilities.transaction_base import TransactionBase
@ -191,38 +191,17 @@ class AccountsController(TransactionBase):
""" """
if tax.charge_type in ["On Previous Row Amount", "On Previous Row Total"] and \ if tax.charge_type in ["On Previous Row Amount", "On Previous Row Total"] and \
(not tax.row_id or cint(tax.row_id) >= tax.idx): (not tax.row_id or cint(tax.row_id) >= tax.idx):
throw((_("Row") + " # %(idx)s [%(taxes_doctype)s]: " + \ throw(_("Please specify a valid Row ID for {0} in row {1}").format(_(tax.doctype), tax.idx))
_("Please specify a valid") + " %(row_id_label)s") % {
"idx": tax.idx,
"taxes_doctype": tax.doctype,
"row_id_label": self.meta.get_label("row_id",
parentfield=self.other_fname)
})
def validate_inclusive_tax(self, tax): def validate_inclusive_tax(self, tax):
def _on_previous_row_error(row_range): def _on_previous_row_error(row_range):
throw((_("Row") + " # %(idx)s [%(doctype)s]: " + throw(_("To include tax in row {0} in Item rate, taxes in rows {1} must also be included").format(tax.idx,
_("to be included in Item's rate, it is required that: ") + row_range))
" [" + _("Row") + " # %(row_range)s] " + _("also be included in Item's rate")) % {
"idx": tax.idx,
"doctype": tax.doctype,
"inclusive_label": frappe.get_meta(tax.doctype).get_label("included_in_print_rate"),
"charge_type_label": frappe.get_meta(tax.doctype).get_label("charge_type"),
"charge_type": tax.charge_type,
"row_range": row_range
})
if cint(getattr(tax, "included_in_print_rate", None)): if cint(getattr(tax, "included_in_print_rate", None)):
if tax.charge_type == "Actual": if tax.charge_type == "Actual":
# inclusive tax cannot be of type Actual # inclusive tax cannot be of type Actual
throw((_("Row") throw(_("Charge of type 'Actual' in row {0} cannot be included in Item Rate").format(tax.idx))
+ " # %(idx)s [%(doctype)s]: %(charge_type_label)s = \"%(charge_type)s\" "
+ "cannot be included in Item's rate") % {
"idx": tax.idx,
"doctype": tax.doctype,
"charge_type_label": frappe.get_meta(tax.doctype).get_label("charge_type"),
"charge_type": tax.charge_type,
})
elif tax.charge_type == "On Previous Row Amount" and \ elif tax.charge_type == "On Previous Row Amount" and \
not cint(self.tax_doclist[cint(tax.row_id) - 1].included_in_print_rate): not cint(self.tax_doclist[cint(tax.row_id) - 1].included_in_print_rate):
# referred row should also be inclusive # referred row should also be inclusive
@ -434,17 +413,7 @@ class AccountsController(TransactionBase):
if total_billed_amt - max_allowed_amt > 0.01: if total_billed_amt - max_allowed_amt > 0.01:
reduce_by = total_billed_amt - max_allowed_amt reduce_by = total_billed_amt - max_allowed_amt
frappe.throw(_("Cannot overbill for Item {0} in row {0} more than {1}. To allow overbilling, please set in 'Setup' > 'Global Defaults'").format(item.item_code, item.row, max_allowed_amt))
frappe.throw(_("Row #") + cstr(item.idx) + ": " +
_(" Max amount allowed for Item ") + cstr(item.item_code) +
_(" against ") + ref_dt + " " +
cstr(item.get(ref_dt.lower().replace(" ", "_"))) + _(" is ") +
cstr(max_allowed_amt) + ". \n" +
_("""If you want to increase your overflow tolerance, please increase \
tolerance % in Global Defaults or Item master.
Or, you must reduce the amount by """) + cstr(reduce_by) + "\n" +
_("""Also, please check if the order item has already been billed \
in the Sales Order"""))
def get_company_default(self, fieldname): def get_company_default(self, fieldname):
from erpnext.accounts.utils import get_company_default from erpnext.accounts.utils import get_company_default

View File

@ -361,9 +361,7 @@ class SellingController(StockController):
if d.get(ref_fieldname): if d.get(ref_fieldname):
status = frappe.db.get_value("Sales Order", d.get(ref_fieldname), "status") status = frappe.db.get_value("Sales Order", d.get(ref_fieldname), "status")
if status == "Stopped": if status == "Stopped":
frappe.throw(self.doctype + frappe.throw(_("Sales Order {0} is stopped").format(d.get(ref_fieldname)))
_(" can not be created/modified against stopped Sales Order ") +
d.get(ref_fieldname))
def check_active_sales_items(obj): def check_active_sales_items(obj):
for d in obj.get(obj.fname): for d in obj.get(obj.fname):

View File

@ -4,9 +4,9 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import frappe import frappe
from frappe.utils import cstr, flt, getdate from frappe.utils import flt, getdate
from frappe import msgprint, _ from frappe import _
from frappe.model.mapper import get_mapped_doc from frappe.model.mapper import get_mapped_doc
from frappe.model.document import Document from frappe.model.document import Document
@ -34,9 +34,7 @@ class Appraisal(Document):
or (end_date>=%s and end_date<=%s))""", or (end_date>=%s and end_date<=%s))""",
(self.employee,self.start_date,self.end_date,self.start_date,self.end_date)) (self.employee,self.start_date,self.end_date,self.start_date,self.end_date))
if chk: if chk:
frappe.throw("You have already created Appraisal "\ frappe.throw(_("Appraisal {0} created for Employee {1} in the given date range").format(chk[0][0], self.employee_name))
+cstr(chk[0][0])+" in the current date range for employee "\
+cstr(self.employee_name))
def calculate_total(self): def calculate_total(self):
total, total_w = 0, 0 total, total_w = 0, 0

View File

@ -4,9 +4,9 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import frappe import frappe
from frappe.utils import getdate, validate_email_add, cstr, cint from frappe.utils import getdate, validate_email_add, cint
from frappe.model.naming import make_autoname from frappe.model.naming import make_autoname
from frappe import msgprint, throw, _ from frappe import throw, _
import frappe.permissions import frappe.permissions
from frappe.defaults import get_restrictions from frappe.defaults import get_restrictions
from frappe.model.controller import DocListController from frappe.model.controller import DocListController
@ -37,16 +37,16 @@ class Employee(DocListController):
if self.user_id: if self.user_id:
self.validate_for_enabled_user_id() self.validate_for_enabled_user_id()
self.validate_duplicate_user_id() self.validate_duplicate_user_id()
def on_update(self): def on_update(self):
if self.user_id and frappe.db.get_value("User", self.user_id, 'docstatus') == 0: if self.user_id and frappe.db.get_value("User", self.user_id, 'docstatus') == 0:
self.restrict_user() self.restrict_user()
self.update_user_default() self.update_user_default()
self.update_user() self.update_user()
self.update_dob_event() self.update_dob_event()
self.restrict_leave_approver() self.restrict_leave_approver()
def restrict_user(self): def restrict_user(self):
"""restrict to this employee for user""" """restrict to this employee for user"""
self.add_restriction_if_required("Employee", self.user_id) self.add_restriction_if_required("Employee", self.user_id)
@ -54,32 +54,32 @@ class Employee(DocListController):
def update_user_default(self): def update_user_default(self):
frappe.db.set_default("employee_name", self.employee_name, self.user_id) frappe.db.set_default("employee_name", self.employee_name, self.user_id)
frappe.db.set_default("company", self.company, self.user_id) frappe.db.set_default("company", self.company, self.user_id)
def restrict_leave_approver(self): def restrict_leave_approver(self):
"""restrict to this employee for leave approver""" """restrict to this employee for leave approver"""
employee_leave_approvers = [d.leave_approver for d in self.get("employee_leave_approvers")] employee_leave_approvers = [d.leave_approver for d in self.get("employee_leave_approvers")]
if self.reports_to and self.reports_to not in employee_leave_approvers: if self.reports_to and self.reports_to not in employee_leave_approvers:
employee_leave_approvers.append(frappe.db.get_value("Employee", self.reports_to, "user_id")) employee_leave_approvers.append(frappe.db.get_value("Employee", self.reports_to, "user_id"))
for user in employee_leave_approvers: for user in employee_leave_approvers:
self.add_restriction_if_required("Employee", user) self.add_restriction_if_required("Employee", user)
self.add_restriction_if_required("Leave Application", user) self.add_restriction_if_required("Leave Application", user)
def add_restriction_if_required(self, doctype, user): def add_restriction_if_required(self, doctype, user):
if frappe.permissions.has_only_non_restrict_role(doctype, user) \ if frappe.permissions.has_only_non_restrict_role(doctype, user) \
and self.name not in get_restrictions(user).get("Employee", []): and self.name not in get_restrictions(user).get("Employee", []):
frappe.defaults.add_default("Employee", self.name, user, "Restriction") frappe.defaults.add_default("Employee", self.name, user, "Restriction")
def update_user(self): def update_user(self):
# add employee role if missing # add employee role if missing
if not "Employee" in frappe.db.sql_list("""select role from tabUserRole if not "Employee" in frappe.db.sql_list("""select role from tabUserRole
where parent=%s""", self.user_id): where parent=%s""", self.user_id):
from frappe.utils.user import add_role from frappe.utils.user import add_role
add_role(self.user_id, "Employee") add_role(self.user_id, "Employee")
user_wrapper = frappe.get_doc("User", self.user_id) user_wrapper = frappe.get_doc("User", self.user_id)
# copy details like Fullname, DOB and Image to User # copy details like Fullname, DOB and Image to User
if self.employee_name: if self.employee_name:
employee_name = self.employee_name.split(" ") employee_name = self.employee_name.split(" ")
@ -88,15 +88,15 @@ class Employee(DocListController):
user_wrapper.middle_name = employee_name[1] user_wrapper.middle_name = employee_name[1]
elif len(employee_name) == 2: elif len(employee_name) == 2:
user_wrapper.last_name = employee_name[1] user_wrapper.last_name = employee_name[1]
user_wrapper.first_name = employee_name[0] user_wrapper.first_name = employee_name[0]
if self.date_of_birth: if self.date_of_birth:
user_wrapper.birth_date = self.date_of_birth user_wrapper.birth_date = self.date_of_birth
if self.gender: if self.gender:
user_wrapper.gender = self.gender user_wrapper.gender = self.gender
if self.image: if self.image:
if not user_wrapper.user_image == self.image: if not user_wrapper.user_image == self.image:
user_wrapper.user_image = self.image user_wrapper.user_image = self.image
@ -112,72 +112,62 @@ class Employee(DocListController):
pass pass
user_wrapper.ignore_permissions = True user_wrapper.ignore_permissions = True
user_wrapper.save() user_wrapper.save()
def validate_date(self): def validate_date(self):
if self.date_of_birth and self.date_of_joining and getdate(self.date_of_birth) >= getdate(self.date_of_joining): if self.date_of_birth and self.date_of_joining and getdate(self.date_of_birth) >= getdate(self.date_of_joining):
throw(_("Date of Joining must be greater than Date of Birth")) throw(_("Date of Joining must be greater than Date of Birth"))
elif self.scheduled_confirmation_date and self.date_of_joining and (getdate(self.scheduled_confirmation_date) < getdate(self.date_of_joining)): elif self.scheduled_confirmation_date and self.date_of_joining and (getdate(self.scheduled_confirmation_date) < getdate(self.date_of_joining)):
throw(_("Scheduled Confirmation Date must be greater than Date of Joining")) throw(_("Scheduled Confirmation Date must be greater than Date of Joining"))
elif self.final_confirmation_date and self.date_of_joining and (getdate(self.final_confirmation_date) < getdate(self.date_of_joining)): elif self.final_confirmation_date and self.date_of_joining and (getdate(self.final_confirmation_date) < getdate(self.date_of_joining)):
throw(_("Final Confirmation Date must be greater than Date of Joining")) throw(_("Final Confirmation Date must be greater than Date of Joining"))
elif self.date_of_retirement and self.date_of_joining and (getdate(self.date_of_retirement) <= getdate(self.date_of_joining)): elif self.date_of_retirement and self.date_of_joining and (getdate(self.date_of_retirement) <= getdate(self.date_of_joining)):
throw(_("Date Of Retirement must be greater than Date of Joining")) throw(_("Date Of Retirement must be greater than Date of Joining"))
elif self.relieving_date and self.date_of_joining and (getdate(self.relieving_date) <= getdate(self.date_of_joining)): elif self.relieving_date and self.date_of_joining and (getdate(self.relieving_date) <= getdate(self.date_of_joining)):
throw(_("Relieving Date must be greater than Date of Joining")) throw(_("Relieving Date must be greater than Date of Joining"))
elif self.contract_end_date and self.date_of_joining and (getdate(self.contract_end_date)<=getdate(self.date_of_joining)): elif self.contract_end_date and self.date_of_joining and (getdate(self.contract_end_date)<=getdate(self.date_of_joining)):
throw(_("Contract End Date must be greater than Date of Joining")) throw(_("Contract End Date must be greater than Date of Joining"))
def validate_email(self): def validate_email(self):
if self.company_email and not validate_email_add(self.company_email): if self.company_email and not validate_email_add(self.company_email):
throw(_("Please enter valid Company Email")) throw(_("Please enter valid Company Email"))
if self.personal_email and not validate_email_add(self.personal_email): if self.personal_email and not validate_email_add(self.personal_email):
throw(_("Please enter valid Personal Email")) throw(_("Please enter valid Personal Email"))
def validate_status(self): def validate_status(self):
if self.status == 'Left' and not self.relieving_date: if self.status == 'Left' and not self.relieving_date:
throw(_("Please enter relieving date.")) throw(_("Please enter relieving date."))
def validate_for_enabled_user_id(self): def validate_for_enabled_user_id(self):
enabled = frappe.db.sql("""select name from `tabUser` where enabled = frappe.db.sql("""select name from `tabUser` where
name=%s and enabled=1""", self.user_id) name=%s and enabled=1""", self.user_id)
if not enabled: if not enabled:
throw("{id}: {user_id} {msg}".format(**{ throw(_("User {0} is disabled").format(self.user_id))
"id": _("User ID"),
"user_id": self.user_id,
"msg": _("is disabled.")
}))
def validate_duplicate_user_id(self): def validate_duplicate_user_id(self):
employee = frappe.db.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.user_id, self.name)) user_id=%s and status='Active' and name!=%s""", (self.user_id, self.name))
if employee: if employee:
throw("{id}: {user_id} {msg}: {employee}".format(**{ throw(_("User {0} is already assigned to Employee {1}").format(self.user_id, employee[0]))
"id": _("User ID"),
"user_id": self.user_id,
"msg": _("is already assigned to Employee"),
"employee": employee[0]
}))
def validate_employee_leave_approver(self): def validate_employee_leave_approver(self):
from frappe.utils.user import User from frappe.utils.user import User
from erpnext.hr.doctype.leave_application.leave_application import InvalidLeaveApproverError from erpnext.hr.doctype.leave_application.leave_application import InvalidLeaveApproverError
for l in self.get("employee_leave_approvers"): for l in self.get("employee_leave_approvers"):
if "Leave Approver" not in User(l.leave_approver).get_roles(): if "Leave Approver" not in User(l.leave_approver).get_roles():
throw(_("Invalid Leave Approver") + ": \"" + l.leave_approver + "\"", throw(_("{0} is not a valid Leave Approver").format(l.leave_approver), InvalidLeaveApproverError)
exc=InvalidLeaveApproverError)
def update_dob_event(self): def update_dob_event(self):
if self.status == "Active" and self.date_of_birth \ if self.status == "Active" and self.date_of_birth \
and not cint(frappe.db.get_value("HR Settings", None, "stop_birthday_reminders")): 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' birthday_event = frappe.db.sql("""select name from `tabEvent` where repeat_on='Every Year'
and ref_type='Employee' and ref_name=%s""", self.name) and ref_type='Employee' and ref_name=%s""", self.name)
starts_on = self.date_of_birth + " 00:00:00" starts_on = self.date_of_birth + " 00:00:00"
ends_on = self.date_of_birth + " 00:15:00" ends_on = self.date_of_birth + " 00:15:00"

View File

@ -6,12 +6,9 @@ frappe.provide('erpnext');
// add toolbar icon // add toolbar icon
$(document).bind('toolbar_setup', function() { $(document).bind('toolbar_setup', function() {
frappe.app.name = "ERPNext"; frappe.app.name = "ERPNext";
var brand = ($("<div></div>").append(frappe.boot.website_settings.brand_html).text() || 'erpnext'); $('.navbar-brand').html('<i class="icon-home"></i>')
$('.navbar-brand').html('<div style="display: inline-block;">\ .attr("title", "Home")
<object type="image/svg+xml" data="assets/erpnext/images/splash.svg" class="toolbar-splash"></object>\
</div>' + brand)
.attr("title", brand)
.addClass("navbar-icon-home") .addClass("navbar-icon-home")
.css({ .css({
"max-width": "200px", "max-width": "200px",
@ -24,19 +21,20 @@ frappe.provide('frappe.ui.misc');
frappe.ui.misc.about = function() { frappe.ui.misc.about = function() {
if(!frappe.ui.misc.about_dialog) { if(!frappe.ui.misc.about_dialog) {
var d = new frappe.ui.Dialog({title: __('About')}) var d = new frappe.ui.Dialog({title: __('About')})
$(d.body).html(repl("<div>\ $(d.body).html(repl("<div>\
<h2>ERPNext</h2> \ <h2>ERPNext</h2> \
<p>"+__("An open source ERP made for the web.</p>") + <h4 class='text-muted'>"+__("Built on") + " Frappe Framework"+"</h4> \
<p>"+__("Open source ERP built for the web") + "</p>" +
"<p>"+__("To report an issue, go to ")+"<a href='https://github.com/frappe/erpnext/issues'>GitHub Issues</a></p> \ "<p>"+__("To report an issue, go to ")+"<a href='https://github.com/frappe/erpnext/issues'>GitHub Issues</a></p> \
<p><a href='http://erpnext.org' target='_blank'>http://erpnext.org</a>.</p>\ <p><a href='http://erpnext.org' target='_blank'>http://erpnext.org</a>.</p>\
<p><a href='http://www.gnu.org/copyleft/gpl.html'>License: GNU General Public License Version 3</a></p>\ <p><a href='http://www.gnu.org/copyleft/gpl.html'>License: GNU General Public License Version 3</a></p>\
<hr>\ <hr>\
<p>&copy; 2014 Web Notes Technologies Pvt. Ltd and contributers </p> \ <p>&copy; 2014 Web Notes Technologies Pvt. Ltd and contributers </p> \
</div>", frappe.app)); </div>", frappe.app));
frappe.ui.misc.about_dialog = d; frappe.ui.misc.about_dialog = d;
} }
frappe.ui.misc.about_dialog.show(); frappe.ui.misc.about_dialog.show();
} }