update translation strings #1403

This commit is contained in:
Rushabh Mehta
2014-04-14 19:20:45 +05:30
parent 7da01d6007
commit 9f0d625300
70 changed files with 1325 additions and 1639 deletions

View File

@@ -4,12 +4,11 @@
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr, flt, has_common, make_esc
from frappe.utils import cstr, flt, has_common, make_esc, comma_or
from frappe import session, _
from frappe import session, msgprint
from erpnext.setup.utils import get_company_currency
from erpnext.utilities.transaction_base import TransactionBase
class AuthorizationControl(TransactionBase):
@@ -24,27 +23,18 @@ class AuthorizationControl(TransactionBase):
for x in det:
amt_list.append(flt(x[0]))
max_amount = max(amt_list)
app_dtl = frappe.db.sql("select approving_user, approving_role from `tabAuthorization Rule` where transaction = %s and (value = %s or value > %s) and docstatus != 2 and based_on = %s and company = %s %s" % ('%s', '%s', '%s', '%s', '%s', condition), (doctype_name, flt(max_amount), total, based_on, company))
if not app_dtl:
app_dtl = frappe.db.sql("select approving_user, approving_role from `tabAuthorization Rule` where transaction = %s and (value = %s or value > %s) and docstatus != 2 and based_on = %s and ifnull(company,'') = '' %s" % ('%s', '%s', '%s', '%s', condition), (doctype_name, flt(max_amount), total, based_on))
app_dtl = frappe.db.sql("select approving_user, approving_role from `tabAuthorization Rule` where transaction = %s and (value = %s or value > %s) and docstatus != 2 and based_on = %s and ifnull(company,'') = '' %s" % ('%s', '%s', '%s', '%s', condition), (doctype_name, flt(max_amount), total, based_on))
for d in app_dtl:
if(d[0]): appr_users.append(d[0])
if(d[1]): appr_roles.append(d[1])
if not has_common(appr_roles, frappe.user.get_roles()) and not has_common(appr_users, [session['user']]):
msg, add_msg = '',''
if max_amount:
dcc = get_company_currency(self.company)
if based_on == 'Grand Total': msg = "since Grand Total exceeds %s. %s" % (dcc, flt(max_amount))
elif based_on == 'Itemwise Discount': msg = "since Discount exceeds %s for Item Code : %s" % (cstr(max_amount)+'%', item)
elif based_on == 'Average Discount' or based_on == 'Customerwise Discount': msg = "since Discount exceeds %s" % (cstr(max_amount)+'%')
if appr_users: add_msg = "Users : "+cstr(appr_users)
if appr_roles: add_msg = "Roles : "+cstr(appr_roles)
if appr_users and appr_roles: add_msg = "Users : "+cstr(appr_users)+" or "+"Roles : "+cstr(appr_roles)
msgprint("You are not authorize to submit this %s %s. Please send for approval to %s" % (doctype_name, msg, add_msg))
frappe.msgprint(_("Not authroized since {0} exceeds limits").format(_(based_on)))
frappe.throw(_("Can be approved by {0}").format(comma_or(appr_roles + appr_users)))
raise Exception
@@ -64,12 +54,12 @@ class AuthorizationControl(TransactionBase):
if chk == 1:
if based_on == 'Itemwise Discount': add_cond2 += " and ifnull(master_name,'') = ''"
appr = frappe.db.sql("select value from `tabAuthorization Rule` where transaction = %s and value <= %s and based_on = %s and company = %s and docstatus != 2 %s %s" % ('%s', '%s', '%s', '%s', cond, add_cond2), (doctype_name, total, based_on, company))
if not appr:
appr = frappe.db.sql("select value from `tabAuthorization Rule` where transaction = %s and value <= %s and based_on = %s and ifnull(company,'') = '' and docstatus != 2 %s %s"% ('%s', '%s', '%s', cond, add_cond2), (doctype_name, total, based_on))
self.get_appr_user_role(appr, doctype_name, total, based_on, cond+add_cond2, item, company)
# Bifurcate Authorization based on type
# --------------------------------------
def bifurcate_based_on_type(self, doctype_name, total, av_dis, based_on, doc_obj, val, company):
@@ -108,39 +98,39 @@ class AuthorizationControl(TransactionBase):
# Individual User
# ================
# Check for authorization set for individual user
based_on = [x[0] for x in frappe.db.sql("select distinct based_on from `tabAuthorization Rule` where transaction = %s and system_user = %s and (company = %s or ifnull(company,'')='') and docstatus != 2", (doctype_name, session['user'], company))]
for d in based_on:
self.bifurcate_based_on_type(doctype_name, total, av_dis, d, doc_obj, 1, company)
# Remove user specific rules from global authorization rules
for r in based_on:
if r in final_based_on and r != 'Itemwise Discount': final_based_on.remove(r)
# Specific Role
# ===============
# Check for authorization set on particular roles
based_on = [x[0] for x in frappe.db.sql("""select based_on
from `tabAuthorization Rule`
where transaction = %s and system_role IN (%s) and based_on IN (%s)
and (company = %s or ifnull(company,'')='')
based_on = [x[0] for x in frappe.db.sql("""select based_on
from `tabAuthorization Rule`
where transaction = %s and system_role IN (%s) and based_on IN (%s)
and (company = %s or ifnull(company,'')='')
and docstatus != 2
""" % ('%s', "'"+"','".join(frappe.user.get_roles())+"'", "'"+"','".join(final_based_on)+"'", '%s'), (doctype_name, company))]
for d in based_on:
self.bifurcate_based_on_type(doctype_name, total, av_dis, d, doc_obj, 2, company)
# Remove role specific rules from global authorization rules
for r in based_on:
if r in final_based_on and r != 'Itemwise Discount': final_based_on.remove(r)
# Global Rule
# =============
# Check for global authorization
for g in final_based_on:
self.bifurcate_based_on_type(doctype_name, total, av_dis, g, doc_obj, 0, company)
#========================================================================================================================
# payroll related check
def get_value_based_rule(self,doctype_name,employee,total_claimed_amount,company):
@@ -153,29 +143,29 @@ class AuthorizationControl(TransactionBase):
val_lst = [y[0] for y in val]
else:
val_lst.append(0)
max_val = max(val_lst)
rule = frappe.db.sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and company = %s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(value,0)= %s and docstatus!=2",(doctype_name,company,employee,employee,flt(max_val)), as_dict=1)
if not rule:
rule = frappe.db.sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and ifnull(company,'') = '' and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(value,0)= %s and docstatus!=2",(doctype_name,employee,employee,flt(max_val)), as_dict=1)
return rule
#---------------------------------------------------------------------------------------------------------------------
# related to payroll module only
def get_approver_name(self, doctype_name, total, doc_obj=''):
app_user=[]
app_specific_user =[]
rule ={}
if doc_obj:
if doctype_name == 'Expense Claim':
rule = self.get_value_based_rule(doctype_name,doc_obj.employee,doc_obj.total_claimed_amount, doc_obj.company)
elif doctype_name == 'Appraisal':
rule = frappe.db.sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and company = %s and docstatus!=2",(doctype_name,doc_obj.employee, doc_obj.employee, doc_obj.company),as_dict=1)
rule = frappe.db.sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and company = %s and docstatus!=2",(doctype_name,doc_obj.employee, doc_obj.employee, doc_obj.company),as_dict=1)
if not rule:
rule = frappe.db.sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(company,'') = '' and docstatus!=2",(doctype_name,doc_obj.employee, doc_obj.employee),as_dict=1)
rule = frappe.db.sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(company,'') = '' and docstatus!=2",(doctype_name,doc_obj.employee, doc_obj.employee),as_dict=1)
if rule:
for m in rule:
if m['to_emp'] or m['to_designation']:
@@ -186,7 +176,7 @@ class AuthorizationControl(TransactionBase):
for x in user_lst:
if not x in app_user:
app_user.append(x)
if len(app_specific_user) >0:
return app_specific_user
else:

View File

@@ -4,8 +4,8 @@
from __future__ import unicode_literals
import frappe
from frappe.utils import cint, cstr, flt, has_common
from frappe import msgprint
from frappe.utils import cstr, flt
from frappe import _, msgprint
from frappe.model.document import Document
@@ -13,75 +13,41 @@ class AuthorizationRule(Document):
def check_duplicate_entry(self):
exists = frappe.db.sql("""select name, docstatus from `tabAuthorization Rule`
where transaction = %s and based_on = %s and system_user = %s
and system_role = %s and approving_user = %s and approving_role = %s
and to_emp =%s and to_designation=%s and name != %s""",
(self.transaction, self.based_on, cstr(self.system_user),
cstr(self.system_role), cstr(self.approving_user),
cstr(self.approving_role), cstr(self.to_emp),
exists = frappe.db.sql("""select name, docstatus from `tabAuthorization Rule`
where transaction = %s and based_on = %s and system_user = %s
and system_role = %s and approving_user = %s and approving_role = %s
and to_emp =%s and to_designation=%s and name != %s""",
(self.transaction, self.based_on, cstr(self.system_user),
cstr(self.system_role), cstr(self.approving_user),
cstr(self.approving_role), cstr(self.to_emp),
cstr(self.to_designation), self.name))
auth_exists = exists and exists[0][0] or ''
if auth_exists:
if cint(exists[0][1]) == 2:
msgprint("""Duplicate Entry. Please untrash Authorization Rule : %s \
from Recycle Bin""" % (auth_exists), raise_exception=1)
else:
msgprint("Duplicate Entry. Please check Authorization Rule : %s" %
(auth_exists), raise_exception=1)
def validate_master_name(self):
if self.based_on == 'Customerwise Discount' and \
not frappe.db.sql("""select name from tabCustomer
where name = %s and docstatus != 2""", (self.master_name)):
msgprint("Please select valid Customer Name for Customerwise Discount",
raise_exception=1)
elif self.based_on == 'Itemwise Discount' and \
not frappe.db.sql("select name from tabItem where name = %s and docstatus != 2",
(self.master_name)):
msgprint("Please select valid Item Name for Itemwise Discount", raise_exception=1)
elif (self.based_on == 'Grand Total' or \
self.based_on == 'Average Discount') and self.master_name:
msgprint("Please remove Customer/Item Name for %s." %
self.based_on, raise_exception=1)
frappe.throw(_("Duplicate Entry. Please check Authorization Rule {0}").format(auth_exists))
def validate_rule(self):
if self.transaction != 'Appraisal':
if not self.approving_role and not self.approving_user:
msgprint("Please enter Approving Role or Approving User", raise_exception=1)
frappe.throw(_("Please enter Approving Role or Approving User"))
elif self.system_user and self.system_user == self.approving_user:
msgprint("Approving User cannot be same as user the rule is Applicable To (User)",
raise_exception=1)
frappe.throw(_("Approving User cannot be same as user the rule is Applicable To"))
elif self.system_role and self.system_role == self.approving_role:
msgprint("Approving Role cannot be same as user the rule is \
Applicable To (Role).", raise_exception=1)
elif self.system_user and self.approving_role and \
has_common([self.approving_role], [x[0] for x in \
frappe.db.sql("select role from `tabUserRole` where parent = %s", \
(self.system_user))]):
msgprint("System User : %s is assigned role : %s. So rule does not make sense" %
(self.system_user,self.approving_role), raise_exception=1)
frappe.throw(_("Approving Role cannot be same as role the rule is Applicable To"))
elif self.transaction in ['Purchase Order', 'Purchase Receipt', \
'Purchase Invoice', 'Stock Entry'] and self.based_on \
in ['Average Discount', 'Customerwise Discount', 'Itemwise Discount']:
msgprint("You cannot set authorization on basis of Discount for %s" %
self.transaction, raise_exception=1)
frappe.throw(_("Cannot set authorization on basis of Discount for {0}").format(self.transaction))
elif self.based_on == 'Average Discount' and flt(self.value) > 100.00:
msgprint("Discount cannot given for more than 100%", raise_exception=1)
frappe.throw(_("Discount must be less than 100"))
elif self.based_on == 'Customerwise Discount' and not self.master_name:
msgprint("Please enter Customer Name for 'Customerwise Discount'",
raise_exception=1)
frappe.throw(_("Customer required for 'Customerwise Discount'"))
else:
if self.transaction == 'Appraisal' and self.based_on != 'Not Applicable':
msgprint("Based on should be 'Not Applicable' while setting authorization rule\
for 'Appraisal'", raise_exception=1)
if self.transaction == 'Appraisal':
self.based_on = "Not Applicable"
def validate(self):
self.check_duplicate_entry()
self.validate_rule()
self.validate_master_name()
if not self.value: self.value = 0.0
if not self.value: self.value = 0.0

View File

@@ -20,7 +20,7 @@ import mimetypes
import frappe
import oauth2client.client
from frappe.utils import cstr
from frappe import _, msgprint
from frappe import _
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
@@ -71,17 +71,17 @@ def backup_to_gdrive():
backup = new_backup()
path = os.path.join(frappe.local.site_path, "public", "backups")
filename = os.path.join(path, os.path.basename(backup.backup_path_db))
# upload files to database folder
upload_files(filename, 'application/x-gzip', drive_service,
upload_files(filename, 'application/x-gzip', drive_service,
frappe.db.get_value("Backup Manager", None, "database_folder_id"))
# upload files to files folder
did_not_upload = []
error_log = []
files_folder_id = frappe.db.get_value("Backup Manager", None, "files_folder_id")
frappe.db.close()
path = os.path.join(frappe.local.site_path, "public", "files")
for filename in os.listdir(path):
@@ -94,7 +94,7 @@ def backup_to_gdrive():
mimetype = 'application/x-gzip'
else:
mimetype = mimetypes.types_map.get("." + ext) or "application/octet-stream"
#Compare Local File with Server File
children = drive_service.children().list(folderId=files_folder_id).execute()
for child in children.get('items', []):
@@ -108,29 +108,28 @@ def backup_to_gdrive():
except Exception, e:
did_not_upload.append(filename)
error_log.append(cstr(e))
frappe.connect()
return did_not_upload, list(set(error_log))
def get_gdrive_flow():
from oauth2client.client import OAuth2WebServerFlow
from frappe import conf
if not "gdrive_client_id" in conf:
frappe.msgprint(_("Please set Google Drive access keys in") + " conf.py",
raise_exception=True)
flow = OAuth2WebServerFlow(conf.gdrive_client_id, conf.gdrive_client_secret,
if not "gdrive_client_id" in conf:
frappe.throw(_("Please set Google Drive access keys in {0}"),format("site_config.json"))
flow = OAuth2WebServerFlow(conf.gdrive_client_id, conf.gdrive_client_secret,
"https://www.googleapis.com/auth/drive", 'urn:ietf:wg:oauth:2.0:oob')
return flow
@frappe.whitelist()
def gdrive_callback(verification_code = None):
flow = get_gdrive_flow()
if verification_code:
credentials = flow.step2_exchange(verification_code)
allowed = 1
# make folders to save id
http = httplib2.Http()
http = credentials.authorize(http)
@@ -145,7 +144,7 @@ def gdrive_callback(verification_code = None):
final_credentials = credentials.to_json()
frappe.db.set_value("Backup Manager", "Backup Manager", "gdrive_credentials", final_credentials)
frappe.msgprint("Updated")
frappe.msgprint(_("Updated"))
def create_erpnext_folder(service):
if not frappe.db:

View File

@@ -3,9 +3,9 @@
from __future__ import unicode_literals
import frappe
from frappe import _, msgprint
from frappe import _
from frappe.utils import cstr, cint
from frappe.utils import cint
import frappe.defaults
@@ -13,10 +13,10 @@ from frappe.model.document import Document
class Company(Document):
def onload(self):
self.set("__transactions_exist", self.check_if_transactions_exist())
def check_if_transactions_exist(self):
exists = False
for doctype in ["Sales Invoice", "Delivery Note", "Sales Order", "Quotation",
@@ -25,31 +25,30 @@ class Company(Document):
limit 1""" % (doctype, "%s"), self.name):
exists = True
break
return exists
def validate(self):
if self.get('__islocal') and len(self.abbr) > 5:
frappe.msgprint("Abbreviation cannot have more than 5 characters",
raise_exception=1)
frappe.throw(_("Abbreviation cannot have more than 5 characters"))
self.previous_default_currency = frappe.db.get_value("Company", self.name, "default_currency")
if self.default_currency and self.previous_default_currency and \
self.default_currency != self.previous_default_currency and \
self.check_if_transactions_exist():
msgprint(_("Sorry! You cannot change company's default currency, because there are existing transactions against it. You will need to cancel those transactions if you want to change the default currency."), raise_exception=True)
frappe.throw(_("Cannot change company's default currency, because there are existing transactions. Transactions must be cancelled to change the default currency."))
def on_update(self):
if not frappe.db.sql("""select name from tabAccount
if not frappe.db.sql("""select name from tabAccount
where company=%s and docstatus<2 limit 1""", self.name):
self.create_default_accounts()
self.create_default_warehouses()
self.create_default_web_page()
if not frappe.db.get_value("Cost Center", {"group_or_ledger": "Ledger",
if not frappe.db.get_value("Cost Center", {"group_or_ledger": "Ledger",
"company": self.name}):
self.create_default_cost_center()
self.set_default_accounts()
if self.default_currency:
@@ -58,7 +57,7 @@ class Company(Document):
def create_default_warehouses(self):
for whname in ("Stores", "Work In Progress", "Finished Goods"):
if not frappe.db.exists("Warehouse", whname + " - " + self.abbr):
stock_group = frappe.db.get_value("Account", {"account_type": "Stock",
stock_group = frappe.db.get_value("Account", {"account_type": "Stock",
"group_or_ledger": "Group"})
if stock_group:
frappe.get_doc({
@@ -67,7 +66,7 @@ class Company(Document):
"company": self.name,
"create_account_under": stock_group
}).insert()
def create_default_web_page(self):
if not frappe.db.get_value("Website Settings", None, "home_page") and \
not frappe.db.sql("select name from tabCompany where name!=%s", self.name):
@@ -80,7 +79,7 @@ class Company(Document):
"description": "Standard Home Page for " + self.name,
"main_section": webfile.read() % self.as_dict()
}).insert()
# update in home page in settings
website_settings = frappe.get_doc("Website Settings", "Website Settings")
website_settings.home_page = webpage.name
@@ -109,7 +108,7 @@ class Company(Document):
self.create_standard_accounts()
frappe.db.set(self, "receivables_group", "Accounts Receivable - " + self.abbr)
frappe.db.set(self, "payables_group", "Accounts Payable - " + self.abbr)
def import_chart_of_account(self):
chart = frappe.get_doc("Chart of Accounts", self.chart_of_accounts)
chart.create_accounts(self.name)
@@ -120,7 +119,7 @@ class Company(Document):
"freeze_account": "No",
"master_type": "",
})
for d in self.fld_dict.keys():
account.set(d, (d == 'parent_account' and lst[self.fld_dict[d]]) and lst[self.fld_dict[d]] +' - '+ self.abbr or lst[self.fld_dict[d]])
account.insert()
@@ -128,17 +127,17 @@ class Company(Document):
def set_default_accounts(self):
def _set_default_accounts(accounts):
for field, account_type in accounts.items():
account = frappe.db.get_value("Account", {"account_type": account_type,
account = frappe.db.get_value("Account", {"account_type": account_type,
"group_or_ledger": "Ledger", "company": self.name})
if account and not self.get(field):
frappe.db.set(self, field, account)
_set_default_accounts({
"default_cash_account": "Cash",
"default_bank_account": "Bank"
})
if cint(frappe.db.get_value("Accounts Settings", None, "auto_accounting_for_stock")):
_set_default_accounts({
"stock_received_but_not_billed": "Stock Received But Not Billed",
@@ -153,9 +152,9 @@ class Company(Document):
'company':self.name,
'group_or_ledger':'Group',
'parent_cost_center':''
},
},
{
'cost_center_name':'Main',
'cost_center_name':'Main',
'company':self.name,
'group_or_ledger':'Ledger',
'parent_cost_center':self.name + ' - ' + self.abbr
@@ -165,11 +164,11 @@ class Company(Document):
cc.update({"doctype": "Cost Center"})
cc_doc = frappe.get_doc(cc)
cc_doc.ignore_permissions = True
if cc.get("cost_center_name") == self.name:
cc_doc.ignore_mandatory = True
cc_doc.insert()
frappe.db.set(self, "cost_center", "Main - " + self.abbr)
def on_trash(self):
@@ -180,33 +179,33 @@ class Company(Document):
if not rec:
#delete tabAccount
frappe.db.sql("delete from `tabAccount` where company = %s order by lft desc, rgt desc", self.name)
#delete cost center child table - budget detail
frappe.db.sql("delete bd.* from `tabBudget Detail` bd, `tabCost Center` cc where bd.parent = cc.name and cc.company = %s", self.name)
#delete cost center
frappe.db.sql("delete from `tabCost Center` WHERE company = %s order by lft desc, rgt desc", self.name)
if not frappe.db.get_value("Stock Ledger Entry", {"company": self.name}):
frappe.db.sql("""delete from `tabWarehouse` where company=%s""", self.name)
frappe.defaults.clear_default("company", value=self.name)
frappe.db.sql("""update `tabSingles` set value=""
where doctype='Global Defaults' and field='default_company'
where doctype='Global Defaults' and field='default_company'
and value=%s""", self.name)
def before_rename(self, olddn, newdn, merge=False):
if merge:
frappe.throw(_("Sorry, companies cannot be merged"))
def after_rename(self, olddn, newdn, merge=False):
frappe.db.set(self, "company_name", newdn)
frappe.db.sql("""update `tabDefaultValue` set defvalue=%s
frappe.db.sql("""update `tabDefaultValue` set defvalue=%s
where defkey='Company' and defvalue=%s""", (newdn, olddn))
frappe.defaults.clear_cache()
def create_standard_accounts(self):
self.fld_dict = {
'account_name': 0,
@@ -217,7 +216,7 @@ class Company(Document):
'company': 5,
'tax_rate': 6
}
acc_list_common = [
['Application of Funds (Assets)','','Group','','Balance Sheet',self.name,''],
['Current Assets','Application of Funds (Assets)','Group','','Balance Sheet',self.name,''],
@@ -282,7 +281,7 @@ class Company(Document):
['Current Liabilities','Source of Funds (Liabilities)','Group','','Balance Sheet',self.name,''],
['Accounts Payable','Current Liabilities','Group','','Balance Sheet',self.name,''],
['Stock Liabilities','Current Liabilities','Group','','Balance Sheet',self.name,''],
['Stock Received But Not Billed', 'Stock Liabilities', 'Ledger', 'Stock Received But Not Billed', 'Balance Sheet', self.name, ''],
['Stock Received But Not Billed', 'Stock Liabilities', 'Ledger', 'Stock Received But Not Billed', 'Balance Sheet', self.name, ''],
['Duties and Taxes','Current Liabilities','Group','','Balance Sheet',self.name,''],
['Loans (Liabilities)','Current Liabilities','Group','','Balance Sheet',self.name,''],
['Secured Loans','Loans (Liabilities)','Group','','Balance Sheet',self.name,''],
@@ -291,7 +290,7 @@ class Company(Document):
['Temporary Accounts (Liabilities)','Source of Funds (Liabilities)','Group','','Balance Sheet',self.name,''],
['Temporary Account (Liabilities)','Temporary Accounts (Liabilities)','Ledger','','Balance Sheet',self.name,'']
]
acc_list_india = [
['CENVAT Capital Goods','Tax Assets','Ledger','Chargeable','Balance Sheet',self.name,''],
['CENVAT','Tax Assets','Ledger','Chargeable','Balance Sheet',self.name,''],
@@ -342,23 +341,23 @@ class Company(Document):
@frappe.whitelist()
def replace_abbr(company, old, new):
frappe.db.set_value("Company", company, "abbr", new)
def _rename_record(dt):
for d in frappe.db.sql("select name from `tab%s` where company=%s" % (dt, '%s'), company):
parts = d[0].split(" - ")
if parts[-1].lower() == old.lower():
name_without_abbr = " - ".join(parts[:-1])
frappe.rename_doc(dt, d[0], name_without_abbr + " - " + new)
for dt in ["Account", "Cost Center", "Warehouse"]:
_rename_record(dt)
frappe.db.commit()
def get_name_with_abbr(name, company):
company_abbr = frappe.db.get_value("Company", company, "abbr")
company_abbr = frappe.db.get_value("Company", company, "abbr")
parts = name.split(" - ")
if parts[-1].lower() != company_abbr.lower():
parts.append(company_abbr)
return " - ".join(parts)

View File

@@ -5,16 +5,16 @@
from __future__ import unicode_literals
import frappe
from frappe import _, msgprint
from frappe import _
from frappe.model.controller import DocListController
class CurrencyExchange(DocListController):
def autoname(self):
self.name = self.from_currency + "-" + self.to_currency
def validate(self):
self.validate_value("exchange_rate", ">", 0)
if self.from_currency == self.to_currency:
msgprint(_("From Currency and To Currency cannot be same"), raise_exception=True)
frappe.throw(_("From Currency and To Currency cannot be same"))

View File

@@ -3,45 +3,20 @@
from __future__ import unicode_literals
import frappe
from frappe import msgprint
from frappe import _
from frappe.utils.nestedset import NestedSet
class CustomerGroup(NestedSet):
nsm_parent_field = 'parent_customer_group';
def validate(self):
if frappe.db.sql("select name from `tabCustomer Group` where name = %s and docstatus = 2",
(self.customer_group_name)):
msgprint("""Another %s record is trashed.
To untrash please go to Setup -> Recycle Bin.""" %
(self.customer_group_name), raise_exception = 1)
def on_update(self):
self.validate_name_with_customer()
super(CustomerGroup, self).on_update()
self.validate_one_root()
def validate_name_with_customer(self):
if frappe.db.exists("Customer", self.name):
frappe.msgprint("An Customer exists with same name (%s), \
please change the Customer Group name or rename the Customer" %
frappe.msgprint(_("An Customer exists with same name (%s), \
please change the Customer Group name or rename the Customer") %
self.name, raise_exception=1)
def on_trash(self):
cust = frappe.db.sql("select name from `tabCustomer` where ifnull(customer_group, '') = %s",
self.name)
cust = [d[0] for d in cust]
if cust:
msgprint("""Customer Group: %s can not be trashed/deleted \
because it is used in customer: %s.
To trash/delete this, remove/change customer group in customer master""" %
(self.name, cust or ''), raise_exception=1)
if frappe.db.sql("select name from `tabCustomer Group` where parent_customer_group = %s \
and docstatus != 2", self.name):
msgprint("Child customer group exists for this customer group. \
You can not trash/cancel/delete this customer group.", raise_exception=1)
# rebuild tree
super(CustomerGroup, self).on_trash()

View File

@@ -4,6 +4,7 @@
from __future__ import unicode_literals
"""Global Defaults"""
import frappe
from frappe import _
import frappe.defaults
from frappe.utils import cint
@@ -25,17 +26,17 @@ keydict = {
from frappe.model.document import Document
class GlobalDefaults(Document):
def on_update(self):
"""update defaults"""
self.validate_session_expiry()
self.set_country_and_timezone()
for key in keydict:
frappe.db.set_default(key, self.get(keydict[key], ''))
# update year start date and year end date from fiscal_year
year_start_end_date = frappe.db.sql("""select year_start_date, year_end_date
year_start_end_date = frappe.db.sql("""select year_start_date, year_end_date
from `tabFiscal Year` where name=%s""", self.current_fiscal_year)
ysd = year_start_end_date[0][0] or ''
@@ -44,20 +45,19 @@ class GlobalDefaults(Document):
if ysd and yed:
frappe.db.set_default('year_start_date', ysd.strftime('%Y-%m-%d'))
frappe.db.set_default('year_end_date', yed.strftime('%Y-%m-%d'))
# enable default currency
if self.default_currency:
frappe.db.set_value("Currency", self.default_currency, "enabled", 1)
# clear cache
frappe.clear_cache()
def validate_session_expiry(self):
if self.session_expiry:
parts = self.session_expiry.split(":")
if len(parts)!=2 or not (cint(parts[0]) or cint(parts[1])):
frappe.msgprint("""Session Expiry must be in format hh:mm""",
raise_exception=1)
frappe.throw(_("Session Expiry must be in format {0}").format("hh:mm"))
def set_country_and_timezone(self):
frappe.db.set_default("country", self.country)

View File

@@ -34,5 +34,4 @@ class ItemGroup(NestedSet, WebsiteGenerator):
def validate_name_with_item(self):
if frappe.db.exists("Item", self.name):
frappe.msgprint("An item exists with same name (%s), please change the \
item group name or rename the item" % self.name, raise_exception=1)
frappe.throw(frappe._("An item exists with same name ({0}), please change the item group name or rename the item").format(self.name))

View File

@@ -11,10 +11,9 @@ from frappe.utils import cint
from frappe.model.document import Document
class JobsEmailSettings(Document):
def validate(self):
if cint(self.extract_emails) and not (self.email_id and self.host and \
self.username and self.password):
frappe.msgprint(_("""Host, Email and Password required if emails are to be pulled"""),
raise_exception=True)
frappe.throw(_("""Host, Email and Password required if emails are to be pulled"""))

View File

@@ -4,8 +4,7 @@
from __future__ import unicode_literals
import frappe
from frappe import msgprint
from frappe import _
from frappe.model.document import Document
@@ -18,5 +17,5 @@ class NotificationControl(Document):
def set_message(self, arg = ''):
fn = self.select_transaction.lower().replace(' ', '_') + '_message'
frappe.db.set(self, fn, self.custom_message)
msgprint("Custom Message for %s updated!" % self.select_transaction)
frappe.msgprint(_("Message updated"))

View File

@@ -6,17 +6,17 @@ import frappe
from frappe.utils import flt
from frappe import _
from frappe.utils.nestedset import NestedSet
class Territory(NestedSet):
nsm_parent_field = 'parent_territory'
def validate(self):
def validate(self):
for d in self.get('target_details'):
if not flt(d.target_qty) and not flt(d.target_amount):
msgprint("Either target qty or target amount is mandatory.")
raise Exception
frappe.throw(_("Either target qty or target amount is mandatory"))
def on_update(self):
super(Territory, self).on_update()