Exemplo n.º 1
1
def before_tests():
	frappe.clear_cache()
	# complete setup if missing
	from frappe.desk.page.setup_wizard.setup_wizard import setup_complete
	if not frappe.get_list("Company"):
		setup_complete({
			"currency"			:"USD",
			"first_name"		:"Test",
			"last_name"			:"User",
			"company_name"		:"Wind Power LLC",
			"timezone"			:"America/New_York",
			"company_abbr"		:"WP",
			"industry"			:"Manufacturing",
			"country"			:"United States",
			"fy_start_date"		:"2014-01-01",
			"fy_end_date"		:"2014-12-31",
			"language"			:"english",
			"company_tagline"	:"Testing",
			"email"				:"*****@*****.**",
			"password"			:"test",
			"chart_of_accounts" : "Standard"
		})

	frappe.db.sql("delete from `tabLeave Allocation`")
	frappe.db.sql("delete from `tabLeave Application`")
	frappe.db.sql("delete from `tabSalary Slip`")
	frappe.db.sql("delete from `tabItem Price`")

	frappe.db.set_value("Stock Settings", None, "auto_insert_price_list_rate_if_missing", 0)

	frappe.db.commit()
Exemplo n.º 2
0
def update_global_settings(args):
	if args.language and args.language != "english":
		set_default_language(get_language_code(args.lang))
	frappe.clear_cache()

	update_system_settings(args)
	update_user_name(args)
Exemplo n.º 3
0
def setup_complete(args=None):
	if frappe.db.sql("select name from tabCompany"):
		frappe.throw(_("Setup Already Complete!!"))

	install_fixtures.install(args.get("country"))

	update_user_name(args)
	create_fiscal_year_and_company(args)
	create_users(args)
	set_defaults(args)
	create_territories()
	create_price_lists(args)
	create_feed_and_todo()
	create_email_digest()
	create_letter_head(args)
	create_taxes(args)
	create_items(args)
	create_customers(args)
	create_suppliers(args)
	frappe.local.message_log = []

	website_maker(args.company_name.strip(), args.company_tagline, args.name)
	create_logo(args)

	frappe.db.commit()
	login_as_first_user(args)
	frappe.db.commit()
	frappe.clear_cache()

	if args.get("add_sample_data"):
		try:
			make_sample_data()
			frappe.clear_cache()
		except FiscalYearError:
			pass
Exemplo n.º 4
0
	def on_update(self):
		"""update defaults"""
		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
			from `tabFiscal Year` where name=%s""", self.current_fiscal_year)
		if year_start_end_date:
			ysd = year_start_end_date[0][0] or ''
			yed = year_start_end_date[0][1] or ''

			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)

		self.toggle_rounded_total()
		self.toggle_in_words()

		# clear cache
		frappe.clear_cache()
Exemplo n.º 5
0
    def test_save_customization_idx(self):
        d = self.get_customize_form("User")
        original_sequence = [df.fieldname for df in d.get("fields")]

        # move field to last
        location_field = d.get("fields", {"fieldname": "location"})[0]
        d.get("fields").remove(location_field)
        d.append("fields", location_field)
        d.run_method("save_customization")
        frappe.clear_cache(doctype=d.doc_type)

        property_setter_name, _idx = frappe.db.get_value(
            "Property Setter", {"doc_type": d.doc_type, "property": "_idx"}, ("name", "value")
        )
        self.assertTrue(_idx)

        _idx = json.loads(_idx)
        for i, df in enumerate(frappe.get_meta(d.doc_type).get("fields")):
            self.assertEquals(_idx[i], df.fieldname)

        frappe.delete_doc("Property Setter", property_setter_name)
        frappe.clear_cache(doctype=d.doc_type)

        for i, df in enumerate(frappe.get_meta(d.doc_type).get("fields")):
            self.assertEquals(original_sequence[i], df.fieldname)
Exemplo n.º 6
0
def clear_cache():
	import frappe.sessions
	from frappe.core.doctype.notification_count.notification_count import clear_notifications
	frappe.connect()
	frappe.clear_cache()
	clear_notifications()
	frappe.destroy()
Exemplo n.º 7
0
	def on_update(self):
		# owner is always name
		frappe.db.set(self, 'owner', self.name)

		# clear new password
		new_password = self.new_password
		self.db_set("new_password", "")

		clear_notifications(user=self.name)
		frappe.clear_cache(user=self.name)

		try:
			if self.in_insert:
				if self.name not in STANDARD_USERS:
					if new_password:
						# new password given, no email required
						_update_password(self.name, new_password)
					if not getattr(self, "no_welcome_mail", False):
						self.send_welcome_mail()
						msgprint(_("Welcome email sent"))
						return
			else:
				self.email_new_password(new_password)

		except frappe.OutgoingEmailError:
			pass # email server not set, don't send email
Exemplo n.º 8
0
def before_tests():
	if len(frappe.get_installed_apps()) > 1:
		# don't run before tests if any other app is installed
		return

	frappe.db.sql("delete from `tabCustom Field`")
	frappe.db.sql("delete from `tabEvent`")
	frappe.db.commit()
	frappe.clear_cache()

	# complete setup if missing
	from frappe.desk.page.setup_wizard.setup_wizard import setup_complete
	if not int(frappe.db.get_single_value('System Settings', 'setup_complete') or 0):
		setup_complete({
			"language"			:"english",
			"email"				:"*****@*****.**",
			"full_name"			:"Test User",
			"password"			:"test",
			"country"			:"United States",
			"timezone"			:"America/New_York",
			"currency"			:"USD"
		})

	frappe.db.commit()
	frappe.clear_cache()
Exemplo n.º 9
0
	def on_trash(self):
		frappe.clear_cache(user=self.name)
		if self.name in STANDARD_USERS:
			throw(_("User {0} cannot be deleted").format(self.name))

		self.a_system_manager_should_exist()

		# disable the user and log him/her out
		self.enabled = 0
		if getattr(frappe.local, "login_manager", None):
			frappe.local.login_manager.logout(user=self.name)

		# delete their password
		frappe.db.sql("""delete from __Auth where user=%s""", (self.name,))

		# delete todos
		frappe.db.sql("""delete from `tabToDo` where owner=%s""", (self.name,))
		frappe.db.sql("""update tabToDo set assigned_by=null where assigned_by=%s""",
			(self.name,))

		# delete events
		frappe.db.sql("""delete from `tabEvent` where owner=%s
			and event_type='Private'""", (self.name,))

		# delete messages
		frappe.db.sql("""delete from `tabComment` where comment_doctype='Message'
			and (comment_docname=%s or owner=%s)""", (self.name, self.name))
Exemplo n.º 10
0
	def on_update(self):
		if hasattr(self, 'old_doc_type') and self.old_doc_type:
			frappe.clear_cache(doctype=self.old_doc_type)
		if self.doc_type:
			frappe.clear_cache(doctype=self.doc_type)

		self.export_doc()
Exemplo n.º 11
0
def load_messages(language):
	frappe.clear_cache()
	set_default_language(language)
	m = get_dict("page", "setup-wizard")
	m.update(get_dict("boot"))
	send_translations(m)
	return frappe.local.lang
Exemplo n.º 12
0
def setup_domain(domain):
	if not domain in domains:
		return

	from frappe.desk.doctype.desktop_icon.desktop_icon import set_desktop_icons
	data = frappe._dict(domains[domain])

	if data.remove_roles:
		for role in data.remove_roles:
			frappe.db.sql('delete from tabUserRole where role=%s', role)

	if data.desktop_icons:
		set_desktop_icons(data.desktop_icons)

	if data.properties:
		for args in data.properties:
			frappe.make_property_setter(args)

	if data.set_value:
		for args in data.set_value:
			doc = frappe.get_doc(args[0], args[1] or args[0])
			doc.set(args[2], args[3])
			doc.save()

	frappe.clear_cache()
Exemplo n.º 13
0
	def reset_to_defaults(self):
		if not self.doc_type:
			return

		frappe.db.sql("""delete from `tabProperty Setter` where doc_type=%s""", self.doc_type)
		frappe.clear_cache(doctype=self.doc_type)
		self.fetch_to_customize()
Exemplo n.º 14
0
	def on_trash(self):
		frappe.clear_cache(user=self.name)
		if self.name in STANDARD_USERS:
			throw(_("User {0} cannot be deleted").format(self.name))

		self.a_system_manager_should_exist()

		# disable the user and log him/her out
		self.enabled = 0
		if getattr(frappe.local, "login_manager", None):
			frappe.local.login_manager.logout(user=self.name)

		# delete todos
		frappe.db.sql("""delete from `tabToDo` where owner=%s""", (self.name,))
		frappe.db.sql("""update tabToDo set assigned_by=null where assigned_by=%s""",
			(self.name,))

		# delete events
		frappe.db.sql("""delete from `tabEvent` where owner=%s
			and event_type='Private'""", (self.name,))

		# delete shares
		frappe.db.sql("""delete from `tabDocShare` where user=%s""", self.name)

		# delete messages
		frappe.db.sql("""delete from `tabCommunication`
			where communication_type in ('Chat', 'Notification')
			and reference_doctype='User'
			and (reference_name=%s or owner=%s)""", (self.name, self.name))
Exemplo n.º 15
0
def post_install(rebuild_website=False):
	if rebuild_website:
		render.clear_cache()

	init_singles()
	frappe.db.commit()
	frappe.clear_cache()
Exemplo n.º 16
0
def reset_perms():
	frappe.connect()
	for d in frappe.db.sql_list("""select name from `tabDocType`
		where ifnull(istable, 0)=0 and ifnull(custom, 0)=0"""):
			frappe.clear_cache(doctype=d)
			frappe.reset_perms(d)
	frappe.destroy()
Exemplo n.º 17
0
def clear_doctype_cache(doctype):
	frappe.clear_cache(doctype=doctype)
	delete_notification_count_for(doctype)
	for user in frappe.db.sql_list("""select distinct tabUserRole.parent from tabUserRole, tabDocPerm
		where tabDocPerm.parent = %s
		and tabDocPerm.role = tabUserRole.role""", doctype):
		frappe.clear_cache(user=user)
Exemplo n.º 18
0
	def tearDown(self):
		frappe.db.sql('delete from `tabProperty Setter` where doc_type="Event"')
		frappe.clear_cache(doctype='Event')
		frappe.db.sql('delete from `tabEvent`')
		frappe.db.sql('delete from __global_search')
		make_test_objects('Event')
		frappe.db.commit()
Exemplo n.º 19
0
	def on_update(self):
		if not frappe.db.sql("""select name from tabAccount
				where company=%s and docstatus<2 limit 1""", self.name):
			if not frappe.local.flags.ignore_chart_of_accounts:
				self.create_default_accounts()
				self.create_default_warehouses()

				self.install_country_fixtures()

		if not frappe.db.get_value("Cost Center", {"is_group": 0, "company": self.name}):
			self.create_default_cost_center()

		if not frappe.local.flags.ignore_chart_of_accounts:
			self.set_default_accounts()
			if self.default_cash_account:
				self.set_mode_of_payment_account()

		if self.default_currency:
			frappe.db.set_value("Currency", self.default_currency, "enabled", 1)

		if hasattr(frappe.local, 'enable_perpetual_inventory') and \
			self.name in frappe.local.enable_perpetual_inventory:
			frappe.local.enable_perpetual_inventory[self.name] = self.enable_perpetual_inventory

		frappe.clear_cache()
Exemplo n.º 20
0
def setup(domain):
	complete_setup(domain)
	setup_demo_page()
	setup_fiscal_year()
	setup_holiday_list()
	setup_user()
	setup_employee()
	setup_salary_structure()
	setup_salary_structure_for_timesheet()
	setup_leave_allocation()
	setup_user_roles()
	setup_customer()
	setup_supplier()
	setup_warehouse()
	import_json('Address')
	import_json('Contact')
	import_json('Lead')
	setup_currency_exchange()
	setup_mode_of_payment()
	setup_account_to_expense_type()
	setup_budget()
	setup_pos_profile()
	
	frappe.db.commit()
	frappe.clear_cache()
Exemplo n.º 21
0
def setup(domain):
	complete_setup(domain)
	setup_demo_page()
	setup_fiscal_year()
	setup_holiday_list()
	setup_user()
	setup_employee()
	setup_user_roles()

	employees = frappe.get_all('Employee',  fields=['name', 'date_of_joining'])

	# monthly salary
	setup_salary_structure(employees[:5], 0)

	# based on timesheet
	setup_salary_structure(employees[5:], 1)

	setup_leave_allocation()
	setup_customer()
	setup_supplier()
	setup_warehouse()
	import_json('Address')
	import_json('Contact')
	import_json('Lead')
	setup_currency_exchange()
	#setup_mode_of_payment()
	setup_account_to_expense_type()
	setup_budget()
	setup_pos_profile()

	frappe.db.commit()
	frappe.clear_cache()
Exemplo n.º 22
0
	def validate_currency(self):
		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 :
					frappe.throw(_("Cannot change company's default currency, because there are existing transactions. Transactions must be cancelled to change the default currency."))

		if frappe.flags.country_change:
			install_country_fixtures(self.name)

		#if not frappe.db.get_value("Cost Center", {"is_group": 0, "company": self.name}):
			#self.create_default_cost_center()

		#if not frappe.local.flags.ignore_chart_of_accounts:
			#self.set_default_accounts()
			#if self.default_cash_account:
				#self.set_mode_of_payment_account()

		if self.default_currency:
			frappe.db.set_value("Currency", self.default_currency, "enabled", 1)

		#if hasattr(frappe.local, 'enable_perpetual_inventory') and \
			#self.name in frappe.local.enable_perpetual_inventory:
			#frappe.local.enable_perpetual_inventory[self.name] = self.enable_perpetual_inventory

		frappe.clear_cache()
Exemplo n.º 23
0
def setup_complete(args):
	"""Calls hooks for `setup_wizard_complete`, sets home page as `desktop`
	and clears cache. If wizard breaks, calls `setup_wizard_exception` hook"""
	args = process_args(args)

	try:
		if args.language and args.language != "english":
			set_default_language(args.language)

		frappe.clear_cache()

		# update system settings
		update_system_settings(args)

		for method in frappe.get_hooks("setup_wizard_complete"):
			frappe.get_attr(method)(args)

		# frappe.db.set_default('desktop:home_page', 'desktop')
		frappe.db.set_default('desktop:home_page', 'dashboard')
		frappe.db.commit()
		frappe.clear_cache()
	except:
		if args:
			traceback = frappe.get_traceback()
			for hook in frappe.get_hooks("setup_wizard_exception"):
				frappe.get_attr(hook)(traceback, args)

		raise

	else:
		for hook in frappe.get_hooks("setup_wizard_success"):
			frappe.get_attr(hook)(args)
Exemplo n.º 24
0
	def on_update(self):
		"""update defaults"""
		for key in education_keydict:
			frappe.db.set_default(key, self.get(education_keydict[key], ''))

		# clear cache
		frappe.clear_cache()
Exemplo n.º 25
0
	def validate(self):
		if self.disabled:
			if self.name in ("Guest", "Administrator", "System Manager", "All"):
				frappe.throw(frappe._("Standard roles cannot be disabled"))
			else:
				frappe.db.sql("delete from `tabUserRole` where role = %s", self.name)
				frappe.clear_cache()
Exemplo n.º 26
0
	def on_update(self):
		NestedSet.on_update(self)
		if not frappe.db.sql("""select name from tabAccount
				where company=%s and docstatus<2 limit 1""", self.name):
			if not frappe.local.flags.ignore_chart_of_accounts:
				frappe.flags.country_change = True
				self.create_default_accounts()
				self.create_default_warehouses()

		if frappe.flags.country_change:
			install_country_fixtures(self.name)
			self.create_default_tax_template()



		if not frappe.db.get_value("Department", {"company": self.name}):
			from erpnext.setup.setup_wizard.operations.install_fixtures import install_post_company_fixtures
			install_post_company_fixtures(frappe._dict({'company_name': self.name}))

		if not frappe.db.get_value("Cost Center", {"is_group": 0, "company": self.name}):
			self.create_default_cost_center()

		if not frappe.local.flags.ignore_chart_of_accounts:
			self.set_default_accounts()
			if self.default_cash_account:
				self.set_mode_of_payment_account()

		if self.default_currency:
			frappe.db.set_value("Currency", self.default_currency, "enabled", 1)

		if hasattr(frappe.local, 'enable_perpetual_inventory') and \
			self.name in frappe.local.enable_perpetual_inventory:
			frappe.local.enable_perpetual_inventory[self.name] = self.enable_perpetual_inventory

		frappe.clear_cache()
Exemplo n.º 27
0
	def on_update(self):
		"""Update database schema, make controller templates if `custom` is not set and clear cache."""
		from frappe.model.db_schema import updatedb
		updatedb(self.name, self)

		self.change_modified_of_parent()
		make_module_and_roles(self)

		self.update_fields_to_fetch()

		from frappe import conf
		if not self.custom and not (frappe.flags.in_import or frappe.flags.in_test) and conf.get('developer_mode'):
			self.export_doc()
			self.make_controller_template()

			if self.has_web_view:
				self.set_base_class_for_controller()

		# update index
		if not self.custom:
			self.run_module_method("on_doctype_update")
			if self.flags.in_insert:
				self.run_module_method("after_doctype_insert")

		delete_notification_count_for(doctype=self.name)
		frappe.clear_cache(doctype=self.name)

		if not frappe.flags.in_install and hasattr(self, 'before_update'):
			self.sync_global_search()

		# clear from local cache
		if self.name in frappe.local.meta_cache:
			del frappe.local.meta_cache[self.name]
Exemplo n.º 28
0
	def on_update(self):
		# clear new password
		self.validate_user_limit()
		self.share_with_self()
		clear_notifications(user=self.name)
		frappe.clear_cache(user=self.name)
		self.send_password_notification(self.__new_password)
Exemplo n.º 29
0
def test_fetch_if_empty(self):
		frappe.db.sql('delete from tabToDo')

		# Allow user changes
		todo_meta = frappe.get_doc('DocType', 'ToDo')
		field = todo_meta.get('fields', dict(fieldname='assigned_by_full_name'))[0]
		field.fetch_from = 'assigned_by.full_name'
		field.fetch_if_empty = 1
		todo_meta.save()

		frappe.clear_cache(doctype='ToDo')

		todo = frappe.get_doc(dict(doctype='ToDo', description='test todo',
			assigned_by='Administrator', assigned_by_full_name='Admin')).insert()

		self.assertEqual(todo.assigned_by_full_name, 'Admin')

		# Overwrite user changes
		todo_meta = frappe.get_doc('DocType', 'ToDo')
		todo_meta.get('fields', dict(fieldname='assigned_by_full_name'))[0].fetch_if_empty = 0
		todo_meta.save()

		todo.reload()
		todo.save()

		self.assertEqual(todo.assigned_by_full_name,
			frappe.db.get_value('User', todo.assigned_by, 'full_name'))
Exemplo n.º 30
0
def main(app=None, module=None, doctype=None, verbose=False, tests=(), force=False):
	frappe.flags.print_messages = verbose
	frappe.flags.in_test = True

	if not frappe.db:
		frappe.connect()

	# if not frappe.conf.get("db_name").startswith("test_"):
	# 	raise Exception, 'db_name must start with "test_"'

	# workaround! since there is no separate test db
	frappe.clear_cache()
	frappe.utils.scheduler.disable_scheduler()
	set_test_email_config()

	if verbose:
		print 'Running "before_tests" hooks'
	for fn in frappe.get_hooks("before_tests", app_name=app):
		frappe.get_attr(fn)()

	if doctype:
		ret = run_tests_for_doctype(doctype, verbose=verbose, tests=tests, force=force)
	elif module:
		ret = run_tests_for_module(module, verbose=verbose, tests=tests)
	else:
		ret = run_all_tests(app, verbose)

	frappe.db.commit()

	# workaround! since there is no separate test db
	frappe.clear_cache()

	return ret
Exemplo n.º 31
0
    def setUp(self):
        frappe.clear_cache(doctype="Blog Post")

        if not frappe.flags.permission_user_setup_done:
            user = frappe.get_doc("User", "*****@*****.**")
            user.add_roles("Website Manager")
            user.add_roles("System Manager")

            user = frappe.get_doc("User", "*****@*****.**")
            user.add_roles("Blogger")

            user = frappe.get_doc("User", "*****@*****.**")
            user.add_roles("Sales User")
            frappe.flags.permission_user_setup_done = True

        reset('Blogger')
        reset('Blog Post')

        frappe.db.sql('delete from `tabUser Permission`')

        frappe.set_user("*****@*****.**")
Exemplo n.º 32
0
def toggle_disabling(doc):
    doc = json.loads(doc)

    if doc.get('disabled'):
        df = {"read_only": 1}
    else:
        df = {"read_only": 0}

    doclist = get_doctypes_with_dimensions()

    for doctype in doclist:
        field = frappe.db.get_value("Custom Field", {
            "dt": doctype,
            "fieldname": doc.get('fieldname')
        })
        if field:
            custom_field = frappe.get_doc("Custom Field", field)
            custom_field.update(df)
            custom_field.save()

        frappe.clear_cache(doctype=doctype)
Exemplo n.º 33
0
def main(app=None,
         module=None,
         doctype=None,
         verbose=False,
         tests=(),
         force=False):
    frappe.flags.print_messages = verbose
    frappe.flags.in_test = True

    if not frappe.db:
        frappe.connect()

    # if not frappe.conf.get("db_name").startswith("test_"):
    # 	raise Exception, 'db_name must start with "test_"'

    # workaround! since there is no separate test db
    frappe.clear_cache()
    set_test_email_config()

    if verbose:
        print 'Running "before_tests" hooks'
    for fn in frappe.get_hooks("before_tests", app_name=app):
        frappe.get_attr(fn)()

    if doctype:
        ret = run_tests_for_doctype(doctype,
                                    verbose=verbose,
                                    tests=tests,
                                    force=force)
    elif module:
        ret = run_tests_for_module(module, verbose=verbose, tests=tests)
    else:
        ret = run_all_tests(app, verbose)

    frappe.db.commit()

    # workaround! since there is no separate test db
    frappe.clear_cache()

    return ret
Exemplo n.º 34
0
    def set_series_for(self, doctype, ol):
        options = self.scrub_options_list(ol)

        # validate names
        for i in options:
            self.validate_series_name(i)

        if self.user_must_always_select:
            options = [''] + options
            default = ''
        else:
            default = options[0]

        # update in property setter
        prop_dict = {'options': "\n".join(options), 'default': default}
        for prop in prop_dict:
            ps_exists = frappe.db.sql(
                """SELECT name FROM `tabProperty Setter`
					WHERE doc_type = %s AND field_name = 'naming_series'
					AND property = %s""", (doctype, prop))
            if ps_exists:
                ps = frappe.get_doc('Property Setter', ps_exists[0][0])
                ps.value = prop_dict[prop]
                ps.save()
            else:
                ps = frappe.get_doc({
                    'doctype': 'Property Setter',
                    'doctype_or_field': 'DocField',
                    'doc_type': doctype,
                    'field_name': 'naming_series',
                    'property': prop,
                    'value': prop_dict[prop],
                    'property_type': 'Text',
                    '__islocal': 1
                })
                ps.save()

        self.set_options = "\n".join(options)

        frappe.clear_cache(doctype=doctype)
Exemplo n.º 35
0
	def set_series_for(self, doctype, ol):
		options = list(self.scrub_options_list(ol))

		# validate names                                                                                            #
		for i in options: self.validate_series_name(i)

		if options and self.user_must_always_select:
			options = [''] + options

	    ##default = options[0] if options else ''

		default = (options[0]) 
		
		# update in property setter
		prop_dict = {'options': "\n".join(options), 'default': default}

		for prop in prop_dict:
			ps_exists = frappe.db.get_value("Property Setter",
				{"field_name": 'naming_series', 'doc_type': doctype, 'property': prop})

			if ps_exists:
				ps = frappe.get_doc('Property Setter', ps_exists)
				ps.value = prop_dict[prop]
				ps.save()
			else:
				ps = frappe.get_doc({
					'doctype': 'Property Setter',
					'doctype_or_field': 'DocField',
					'doc_type': doctype,
					'field_name': 'naming_series',
					'property': prop,
					'value': prop_dict[prop],
					'property_type': 'Text',
					'__islocal': 1
				})
				ps.save()

		self.set_options = "\n".join(options)

		frappe.clear_cache(doctype=doctype)
Exemplo n.º 36
0
	def on_trash(self):
		frappe.clear_cache(user=self.name)
		if self.name in STANDARD_USERS:
			throw(_("User {0} cannot be deleted").format(self.name))

		self.a_system_manager_should_exist()

		# disable the user and log him/her out
		self.enabled = 0
		if getattr(frappe.local, "login_manager", None):
			frappe.local.login_manager.logout(user=self.name)

		# delete todos
		frappe.db.delete("ToDo", {"owner": self.name})
		frappe.db.sql("""UPDATE `tabToDo` SET `assigned_by`=NULL WHERE `assigned_by`=%s""",
			(self.name,))

		# delete events
		frappe.db.delete("Event", {"owner": self.name, "event_type": "Private"})

		# delete shares
		frappe.db.delete("DocShare", {"user": self.name})
		# delete messages
		frappe.db.sql("""delete from `tabCommunication`
			where communication_type in ('Chat', 'Notification')
			and reference_doctype='User'
			and (reference_name=%s or owner=%s)""", (self.name, self.name))

		# unlink contact
		frappe.db.sql("""update `tabContact`
			set `user`=null
			where `user`=%s""", (self.name))

		# delete notification settings
		frappe.delete_doc("Notification Settings", self.name, ignore_permissions=True)

		if self.get('allow_in_mentions'):
			frappe.cache().delete_key('users_for_mentions')

		frappe.cache().delete_key('enabled_users')
Exemplo n.º 37
0
    def on_update(self):
        NestedSet.on_update(self)
        if not frappe.db.sql(
                """select name from tabAccount
				where company=%s and docstatus<2 limit 1""", self.name):
            if not frappe.local.flags.ignore_chart_of_accounts:
                frappe.flags.country_change = True
                self.create_default_accounts()
                self.create_default_warehouses()

        if frappe.flags.country_change:
            install_country_fixtures(self.name)
            self.create_default_tax_template()

        if not frappe.db.get_value("Department", {"company": self.name}):
            from erpnext.setup.setup_wizard.operations.install_fixtures import install_post_company_fixtures
            install_post_company_fixtures(
                frappe._dict({'company_name': self.name}))

        if not frappe.db.get_value("Cost Center", {
                "is_group": 0,
                "company": self.name
        }):
            self.create_default_cost_center()

        if not frappe.local.flags.ignore_chart_of_accounts:
            self.set_default_accounts()
            if self.default_cash_account:
                self.set_mode_of_payment_account()

        if self.default_currency:
            frappe.db.set_value("Currency", self.default_currency, "enabled",
                                1)

        if hasattr(frappe.local, 'enable_perpetual_inventory') and \
         self.name in frappe.local.enable_perpetual_inventory:
            frappe.local.enable_perpetual_inventory[
                self.name] = self.enable_perpetual_inventory

        frappe.clear_cache()
Exemplo n.º 38
0
def setup_complete(args=None):
    if frappe.db.sql("select name from tabCompany"):
        frappe.throw(_("Setup Already Complete!!"))

    install_fixtures.install(args.get("country"))

    update_setup_wizard_access()
    create_fiscal_year_and_company(args)
    create_users(args)
    set_defaults(args)
    create_territories()
    create_price_lists(args)
    create_feed_and_todo()
    create_email_digest()
    create_letter_head(args)
    create_taxes(args)
    create_items(args)
    create_customers(args)
    create_suppliers(args)
    frappe.local.message_log = []
    setup_domain(args.get('domain'))

    website_maker(args)
    create_logo(args)

    frappe.db.commit()
    login_as_first_user(args)
    frappe.db.commit()
    frappe.clear_cache()

    if args.get("add_sample_data"):
        try:
            make_sample_data()
            frappe.clear_cache()
        except:
            # clear message
            if frappe.message_log:
                frappe.message_log.pop()

            pass
Exemplo n.º 39
0
	def on_update(self):
		"""Update database schema, make controller templates if `custom` is not set and clear cache."""
		self.delete_duplicate_custom_fields()
		try:
			frappe.db.updatedb(self.name, self)
		except Exception as e:
			print("\n\nThere was an issue while migrating the DocType: {}\n".format(self.name))
			raise e

		self.change_modified_of_parent()
		make_module_and_roles(self)

		self.update_fields_to_fetch()

		from frappe import conf
		allow_doctype_export = frappe.flags.allow_doctype_export or (not frappe.flags.in_test and conf.get('developer_mode'))
		if not self.custom and not frappe.flags.in_import and allow_doctype_export:
			self.export_doc()
			self.make_controller_template()

			if self.has_web_view:
				self.set_base_class_for_controller()

		# update index
		if not self.custom:
			self.run_module_method("on_doctype_update")
			if self.flags.in_insert:
				self.run_module_method("after_doctype_insert")

		delete_notification_count_for(doctype=self.name)
		frappe.clear_cache(doctype=self.name)

		if not frappe.flags.in_install and hasattr(self, 'before_update'):
			self.sync_global_search()

		# clear from local cache
		if self.name in frappe.local.meta_cache:
			del frappe.local.meta_cache[self.name]

		clear_linked_doctype_cache()
Exemplo n.º 40
0
def complete_setup():
	print "Complete Setup..."
	from frappe.desk.page.setup_wizard.setup_wizard import setup_complete
	setup_complete({
		"first_name": "Test",
		"last_name": "User",
		"email": "*****@*****.**",
		"company_tagline": "Wind Mills for a Better Tomorrow",
		"password": "******",
		"fy_start_date": "2015-01-01",
		"fy_end_date": "2015-12-31",
		"industry": "Manufacturing",
		"company_name": settings.company,
		"chart_of_accounts": "Standard",
		"company_abbr": settings.company_abbr,
		"currency": settings.currency,
		"timezone": settings.time_zone,
		"country": settings.country,
		"language": "english"
	})

	# home page should always be "start"
	website_settings = frappe.get_doc("Website Settings", "Website Settings")
	website_settings.home_page = "start"
	website_settings.save()

	for year in xrange(2014, frappe.utils.now_datetime().year + 1, 1):
		try:
			frappe.get_doc({
				"doctype": "Fiscal Year",
				"year": frappe.utils.cstr(year),
				"year_start_date": "{0}-01-01".format(year),
				"year_end_date": "{0}-12-31".format(year)
			}).insert()
		except frappe.DuplicateEntryError:
			pass

	import_data("Holiday List")

	frappe.clear_cache()
Exemplo n.º 41
0
def execute():
    frappe.reload_doc('core', 'doctype', 'DocField')

    if frappe.db.has_column('DocField', 'show_days'):
        frappe.db.sql("""
			UPDATE
				tabDocField
			SET
				hide_days = 1 WHERE show_days = 0
		""")
        frappe.db.sql_ddl('alter table tabDocField drop column show_days')

    if frappe.db.has_column('DocField', 'show_seconds'):
        frappe.db.sql("""
			UPDATE
				tabDocField
			SET
				hide_seconds = 1 WHERE show_seconds = 0
		""")
        frappe.db.sql_ddl('alter table tabDocField drop column show_seconds')

    frappe.clear_cache(doctype='DocField')
Exemplo n.º 42
0
def update_hr_permissions():
    # add set user permissions rights to HR Manager
    frappe.db.sql(
        """update `tabDocPerm` set `set_user_permissions`=1 where parent in ('Employee', 'Leave Application')
		and role='HR Manager' and permlevel=0 and `read`=1""")

    # apply user permissions on Employee and Leave Application
    frappe.db.sql(
        """update `tabDocPerm` set `apply_user_permissions`=1 where parent in ('Employee', 'Leave Application')
		and role in ('Employee', 'Leave Approver') and permlevel=0 and `read`=1""")

    frappe.clear_cache()

    # save employees to run on_update events
    for employee in frappe.db.sql_list(
            """select name from `tabEmployee` where docstatus < 2"""):
        try:
            emp = frappe.get_doc("Employee", employee)
            emp.flags.ignore_mandatory = True
            emp.save()
        except EmployeeUserDisabledError:
            pass
Exemplo n.º 43
0
    def on_update(self):
        from frappe.model.db_schema import updatedb
        updatedb(self.name)

        self.change_modified_of_parent()
        make_module_and_roles(self)

        from frappe import conf
        if not (frappe.flags.in_import
                or frappe.flags.in_test) and conf.get('developer_mode') or 0:
            self.export_doc()
            self.make_controller_template()

        # update index
        if not getattr(self, "custom", False):
            from frappe.modules import load_doctype_module
            module = load_doctype_module(self.name, self.module)
            if hasattr(module, "on_doctype_update"):
                module.on_doctype_update()

        delete_notification_count_for(doctype=self.name)
        frappe.clear_cache(doctype=self.name)
Exemplo n.º 44
0
	def test_default_values(self):
		doc = frappe.new_doc("Blog Post")
		self.assertFalse(doc.get("blog_category"))

		# Fetch default based on single user permission
		add_user_permission("Blog Category", "-test-blog-category-1", "*****@*****.**")

		frappe.set_user("*****@*****.**")
		doc = frappe.new_doc("Blog Post")
		self.assertEqual(doc.get("blog_category"), "-test-blog-category-1")

		# Don't fetch default if user permissions is more than 1
		add_user_permission("Blog Category", "-test-blog-category", "*****@*****.**", ignore_permissions=True)
		frappe.clear_cache()
		doc = frappe.new_doc("Blog Post")
		self.assertFalse(doc.get("blog_category"))

		# Fetch user permission set as default from multiple user permission
		add_user_permission("Blog Category", "-test-blog-category-2", "*****@*****.**", ignore_permissions=True, is_default=1)
		frappe.clear_cache()
		doc = frappe.new_doc("Blog Post")
		self.assertEqual(doc.get("blog_category"), "-test-blog-category-2")
Exemplo n.º 45
0
	def save_customization(self):
		if not self.doc_type:
			return

		self.flags.update_db = False
		self.flags.rebuild_doctype_for_global_search = False
		self.set_property_setters()
		self.update_custom_fields()
		self.set_name_translation()
		validate_fields_for_doctype(self.doc_type)

		if self.flags.update_db:
			frappe.db.updatedb(self.doc_type)

		if not hasattr(self, 'hide_success') or not self.hide_success:
			frappe.msgprint(_("{0} updated").format(_(self.doc_type)), alert=True)
		frappe.clear_cache(doctype=self.doc_type)
		self.fetch_to_customize()

		if self.flags.rebuild_doctype_for_global_search:
			frappe.enqueue('frappe.utils.global_search.rebuild_for_doctype',
				now=True, doctype=self.doc_type)
Exemplo n.º 46
0
	def on_update(self):
		# clear new password
		self.share_with_self()
		clear_notifications(user=self.name)
		frappe.clear_cache(user=self.name)
		now = frappe.flags.in_test or frappe.flags.in_install
		self.send_password_notification(self.__new_password)
		frappe.enqueue(
			"frappe.core.doctype.user.user.create_contact", user=self, ignore_mandatory=True, now=now
		)
		if self.name not in ("Administrator", "Guest") and not self.user_image:
			frappe.enqueue("frappe.core.doctype.user.user.update_gravatar", name=self.name, now=now)

		# Set user selected timezone
		if self.time_zone:
			frappe.defaults.set_default("time_zone", self.time_zone, self.name)

		if self.has_value_changed("allow_in_mentions") or self.has_value_changed("user_type"):
			frappe.cache().delete_key("users_for_mentions")

		if self.has_value_changed("enabled"):
			frappe.cache().delete_key("enabled_users")
Exemplo n.º 47
0
    def on_trash(self):
        """Delete module name from modules.txt"""

        if frappe.flags.in_uninstall:
            return

        modules = None
        if frappe.local.module_app.get(frappe.scrub(self.name)):
            with open(frappe.get_app_path(self.app_name, "modules.txt"),
                      "r") as f:
                content = f.read()
                if self.name in content.splitlines():
                    modules = list(filter(None, content.splitlines()))
                    modules.remove(self.name)

            if modules:
                with open(frappe.get_app_path(self.app_name, "modules.txt"),
                          "w") as f:
                    f.write("\n".join(modules))

                frappe.clear_cache()
                frappe.setup_module_map()
Exemplo n.º 48
0
def _reinstall(site, admin_password=None, mariadb_root_username=None, mariadb_root_password=None, yes=False, verbose=False):
	from frappe.installer import _new_site

	if not yes:
		click.confirm('This will wipe your database. Are you sure you want to reinstall?', abort=True)
	try:
		frappe.init(site=site)
		frappe.connect()
		frappe.clear_cache()
		installed = frappe.get_installed_apps()
		frappe.clear_cache()
	except Exception:
		installed = []
	finally:
		if frappe.db:
			frappe.db.close()
		frappe.destroy()

	frappe.init(site=site)
	_new_site(frappe.conf.db_name, site, verbose=verbose, force=True, reinstall=True, install_apps=installed,
		mariadb_root_username=mariadb_root_username, mariadb_root_password=mariadb_root_password,
		admin_password=admin_password)
Exemplo n.º 49
0
def create_custom_fields(custom_fields, ignore_validate=False, update=True):
    """Add / update multiple custom fields

	:param custom_fields: example `{'Sales Invoice': [dict(fieldname='test')]}`"""

    if not ignore_validate and frappe.flags.in_setup_wizard:
        ignore_validate = True

    for doctypes, fields in custom_fields.items():
        if isinstance(fields, dict):
            # only one field
            fields = [fields]

        if isinstance(doctypes, str):
            # only one doctype
            doctypes = (doctypes, )

        for doctype in doctypes:
            for df in fields:
                field = frappe.db.get_value("Custom Field", {
                    "dt": doctype,
                    "fieldname": df["fieldname"]
                })
                if not field:
                    try:
                        df["owner"] = "Administrator"
                        create_custom_field(doctype,
                                            df,
                                            ignore_validate=ignore_validate)
                    except frappe.exceptions.DuplicateEntryError:
                        pass
                elif update:
                    custom_field = frappe.get_doc("Custom Field", field)
                    custom_field.flags.ignore_validate = ignore_validate
                    custom_field.update(df)
                    custom_field.save()

        frappe.clear_cache(doctype=doctype)
        frappe.db.updatedb(doctype)
Exemplo n.º 50
0
    def on_trash(self):
        frappe.clear_cache(user=self.name)
        if self.name in STANDARD_USERS:
            throw(_("User {0} cannot be deleted").format(self.name))

        self.a_system_manager_should_exist()

        # disable the user and log him/her out
        self.enabled = 0
        if getattr(frappe.local, "login_manager", None):
            frappe.local.login_manager.logout(user=self.name)

        # delete todos
        frappe.db.sql("""delete from `tabToDo` where owner=%s""",
                      (self.name, ))
        frappe.db.sql(
            """update tabToDo set assigned_by=null where assigned_by=%s""",
            (self.name, ))

        # delete events
        frappe.db.sql(
            """delete from `tabEvent` where owner=%s
			and event_type='Private'""", (self.name, ))

        # delete shares
        frappe.db.sql("""delete from `tabDocShare` where user=%s""", self.name)

        # delete messages
        frappe.db.sql(
            """delete from `tabCommunication`
			where communication_type in ('Chat', 'Notification')
			and reference_doctype='User'
			and (reference_name=%s or owner=%s)""", (self.name, self.name))

        # unlink contact
        frappe.db.sql(
            """update `tabContact`
			set user=null
			where user=%s""", (self.name))
Exemplo n.º 51
0
def clear_cache(path=None):
    '''Clear website caches

	:param path: (optional) for the given path'''
    for key in ('website_generator_routes', 'website_pages',
                'website_full_index'):
        frappe.cache().delete_value(key)

    frappe.cache().delete_value("website_404")
    if path:
        frappe.cache().hdel('website_redirects', path)
        delete_page_cache(path)
    else:
        clear_sitemap()
        frappe.clear_cache("Guest")
        for key in ('portal_menu_items', 'home_page', 'website_route_rules',
                    'doctypes_with_web_view', 'website_redirects',
                    'page_context', 'website_page'):
            frappe.cache().delete_value(key)

    for method in frappe.get_hooks("website_clear_cache"):
        frappe.get_attr(method)(path)
Exemplo n.º 52
0
    def on_update(self):
        """Update database schema, make controller templates if `custom` is not set and clear cache."""
        from frappe.model.db_schema import updatedb
        updatedb(self.name)

        self.change_modified_of_parent()
        make_module_and_roles(self)

        from frappe import conf
        if not self.custom and not (
                frappe.flags.in_import
                or frappe.flags.in_test) and conf.get('developer_mode'):
            self.export_doc()
            self.make_controller_template()

        # update index
        self.run_module_method("on_doctype_update")
        if self.flags.in_insert:
            self.run_module_method("after_doctype_insert")

        delete_notification_count_for(doctype=self.name)
        frappe.clear_cache(doctype=self.name)
Exemplo n.º 53
0
def setup_complete(args):
	"""Calls hooks for `setup_wizard_complete`, sets home page as `desktop`
	and clears cache. If wizard breaks, calls `setup_wizard_exception` hook"""

	if cint(frappe.db.get_single_value('System Settings', 'setup_complete')):
		frappe.throw(_('Setup already complete'))

	args = process_args(args)

	try:
		if args.language and args.language != "english":
			set_default_language(get_language_code(args.lang))

		frappe.clear_cache()

		# update system settings
		update_system_settings(args)
		update_user_name(args)

		for method in frappe.get_hooks("setup_wizard_complete"):
			frappe.get_attr(method)(args)

		disable_future_access()

		frappe.db.commit()
		frappe.clear_cache()
	except:
		frappe.db.rollback()
		if args:
			traceback = frappe.get_traceback()
			for hook in frappe.get_hooks("setup_wizard_exception"):
				frappe.get_attr(hook)(traceback, args)

		raise

	else:
		for hook in frappe.get_hooks("setup_wizard_success"):
			frappe.get_attr(hook)(args)
Exemplo n.º 54
0
    def on_trash(self):
        frappe.clear_cache(user=self.doc.name)
        if self.doc.name in ["Administrator", "Guest"]:
            throw(
                "{msg}: {name}".format(**{
                    "msg": _("Hey! You cannot delete user"),
                    "name": self.doc.name
                }))

        self.a_system_manager_should_exist()

        # disable the user and log him/her out
        self.doc.enabled = 0
        if getattr(frappe.local, "login_manager", None):
            frappe.local.login_manager.logout(user=self.doc.name)

        # delete their password
        frappe.db.sql("""delete from __Auth where user=%s""",
                      (self.doc.name, ))

        # delete todos
        frappe.db.sql("""delete from `tabToDo` where owner=%s""",
                      (self.doc.name, ))
        frappe.db.sql(
            """update tabToDo set assigned_by=null where assigned_by=%s""",
            (self.doc.name, ))

        # delete events
        frappe.db.sql(
            """delete from `tabEvent` where owner=%s
			and event_type='Private'""", (self.doc.name, ))
        frappe.db.sql("""delete from `tabEvent User` where person=%s""",
                      (self.doc.name, ))

        # delete messages
        frappe.db.sql(
            """delete from `tabComment` where comment_doctype='Message'
			and (comment_docname=%s or owner=%s)""", (self.doc.name, self.doc.name))
Exemplo n.º 55
0
def install_app(name, verbose=False, set_as_patched=True):
    frappe.flags.in_install_app = name
    frappe.clear_cache()

    app_hooks = frappe.get_hooks(app_name=name)
    installed_apps = frappe.get_installed_apps()

    if name not in frappe.get_all_apps(with_frappe=True):
        raise Exception("App not in apps.txt")

    if name in installed_apps:
        print "App Already Installed"
        frappe.msgprint("App {0} already installed".format(name))
        return

    if name != "frappe":
        frappe.only_for("System Manager")

    for before_install in app_hooks.before_install or []:
        frappe.get_attr(before_install)()

    if name != "frappe":
        add_module_defs(name)

    sync_for(name, force=True, sync_everything=True, verbose=verbose)

    add_to_installed_apps(name)

    if set_as_patched:
        set_all_patches_as_completed(name)

    for after_install in app_hooks.after_install or []:
        frappe.get_attr(after_install)()

    print "Installing Fixtures..."
    sync_fixtures(name)

    frappe.flags.in_install_app = False
def execute():
    accounting_dimensions = frappe.db.get_all(
        "Accounting Dimension",
        fields=["fieldname", "label", "document_type", "disabled"])

    if not accounting_dimensions:
        return

    count = 1
    for d in accounting_dimensions:

        if count % 2 == 0:
            insert_after_field = "dimension_col_break"
        else:
            insert_after_field = "accounting_dimensions_section"

        for doctype in ["Purchase Order", "Purchase Receipt", "Sales Order"]:

            field = frappe.db.get_value("Custom Field", {
                "dt": doctype,
                "fieldname": d.fieldname
            })

            if field:
                continue

            df = {
                "fieldname": d.fieldname,
                "label": d.label,
                "fieldtype": "Link",
                "options": d.document_type,
                "insert_after": insert_after_field,
            }

            create_custom_field(doctype, df, ignore_validate=True)
            frappe.clear_cache(doctype=doctype)

        count += 1
Exemplo n.º 57
0
def reinstall(context, admin_password=None, yes=False):
	"Reinstall site ie. wipe all data and start over"

	if not yes:
		click.confirm('This will wipe your database. Are you sure you want to reinstall?', abort=True)

	site = get_site(context)
	try:
		frappe.init(site=site)
		frappe.connect()
		frappe.clear_cache()
		installed = frappe.get_installed_apps()
		frappe.clear_cache()
	except Exception:
		installed = []
	finally:
		if frappe.db:
			frappe.db.close()
		frappe.destroy()

	frappe.init(site=site)
	_new_site(frappe.conf.db_name, site, verbose=context.verbose, force=True, reinstall=True,
		install_apps=installed, admin_password=admin_password)
Exemplo n.º 58
0
def reinstall(context):
    "Reinstall site ie. wipe all data and start over"
    site = get_single_site(context)
    try:
        frappe.init(site=site)
        frappe.connect()
        frappe.clear_cache()
        installed = frappe.get_installed_apps()
        frappe.clear_cache()
    except Exception:
        installed = []
    finally:
        if frappe.db:
            frappe.db.close()
        frappe.destroy()

    frappe.init(site=site)
    _new_site(frappe.conf.db_name,
              site,
              verbose=context.verbose,
              force=True,
              reinstall=True,
              install_apps=installed)
Exemplo n.º 59
0
def setup_complete(args):
    """Calls hooks for `setup_wizard_complete`, sets home page as `desktop`
	and clears cache. If wizard breaks, calls `setup_wizard_exception` hook"""
    args = process_args(args)

    try:
        for method in frappe.get_hooks("setup_wizard_complete"):
            frappe.get_attr(method)(args)

        frappe.db.set_default('desktop:home_page', 'desktop')
        frappe.db.commit()
        frappe.clear_cache()
    except:
        if args:
            traceback = frappe.get_traceback()
            for hook in frappe.get_hooks("setup_wizard_exception"):
                frappe.get_attr(hook)(traceback, args)

        raise

    else:
        for hook in frappe.get_hooks("setup_wizard_success"):
            frappe.get_attr(hook)(args)
Exemplo n.º 60
0
def delete_currency_from_gl_entry(currency):
    doclist = [
        scrub(currency), "debit_in_" + scrub(currency),
        "credit_in_" + scrub(currency)
    ]

    frappe.db.sql(
        """
		DELETE FROM `tabCustom Field`
		WHERE fieldname IN (%s)
		AND dt = 'GL Entry'""" %  #nosec
        (', '.join(['%s'] * len(doclist))),
        tuple(doclist))

    frappe.db.sql(
        """
		DELETE FROM `tabProperty Setter`
		WHERE field_name IN (%s)
		AND doc_type = 'GL Entry'""" %  #nosec
        (', '.join(['%s'] * len(doclist))),
        tuple(doclist))

    frappe.clear_cache(doctype="GL Entry")