Ejemplo n.º 1
0
def execute():
	# rename doctypes
	tables = frappe.db.sql_list("show tables")
	for old_dt, new_dt in [["Journal Voucher Detail", "Journal Entry Account"],
		["Journal Voucher", "Journal Entry"],
		["Budget Distribution Detail", "Monthly Distribution Percentage"],
		["Budget Distribution", "Monthly Distribution"]]:
			if "tab"+new_dt not in tables:
				frappe.rename_doc("DocType", old_dt, new_dt, force=True)

	# reload new child doctypes
	frappe.reload_doc("manufacturing", "doctype", "work_order_operation")
	frappe.reload_doc("manufacturing", "doctype", "workstation_working_hour")
	frappe.reload_doc("stock", "doctype", "item_variant")
	frappe.reload_doc("hr", "doctype", "salary_detail")
	frappe.reload_doc("accounts", "doctype", "party_account")
	frappe.reload_doc("accounts", "doctype", "fiscal_year_company")

	#rename table fieldnames
	for dn in rename_map:
		if not frappe.db.exists("DocType", dn):
			continue
		frappe.reload_doc(get_doctype_module(dn), "doctype", scrub(dn))

	for dt, field_list in rename_map.items():
		if not frappe.db.exists("DocType", dt):
			continue
		for field in field_list:
			rename_field(dt, field[0], field[1])

	# update voucher type
	for old, new in [["Bank Voucher", "Bank Entry"], ["Cash Voucher", "Cash Entry"],
		["Credit Card Voucher", "Credit Card Entry"], ["Contra Voucher", "Contra Entry"],
		["Write Off Voucher", "Write Off Entry"], ["Excise Voucher", "Excise Entry"]]:
			frappe.db.sql("update `tabJournal Entry` set voucher_type=%s where voucher_type=%s", (new, old))
Ejemplo n.º 2
0
def execute():
	if not frappe.db.exists('DocType', 'Has Role'):
		frappe.rename_doc('DocType', 'Page Role', 'Has Role')
	reload_doc()
	set_ref_doctype_roles_to_report()
	copy_user_roles_to_has_roles()
	remove_doctypes()
Ejemplo n.º 3
0
def setup_folder_path(filename, new_parent):
	file = frappe.get_doc("File", filename)
	file.folder = new_parent
	file.save()

	if file.is_folder:
		frappe.rename_doc("File", file.name, file.get_name_based_on_parent_folder(), ignore_permissions=True)
def execute():
	# rename the School module as Education

	# rename the school module
	if frappe.db.exists('Module Def', 'Schools') and not frappe.db.exists('Module Def', 'Education'):
		frappe.rename_doc("Module Def", "Schools", "Education")

	# delete the school module
	if frappe.db.exists('Module Def', 'Schools') and frappe.db.exists('Module Def', 'Education'):
		frappe.db.sql("""delete from `tabModule Def` where module_name = 'Schools'""")


	# rename "School Settings" to the "Education Settings
	if frappe.db.exists('DocType', 'School Settings'):
		frappe.rename_doc("DocType", "School Settings", "Education Settings", force=True)
		frappe.reload_doc("education", "doctype", "education_settings")

	# delete the discussion web form if exists
	if frappe.db.exists('Web Form', 'Discussion'):
		frappe.db.sql("""delete from `tabWeb Form` where name = 'discussion'""")

	# rename the select option field from "School Bus" to "Institute's Bus"
	frappe.reload_doc("education", "doctype", "Program Enrollment")
	if "mode_of_transportation" in frappe.db.get_table_columns("Program Enrollment"):
		frappe.db.sql("""update `tabProgram Enrollment` set mode_of_transportation = "Institute's Bus"
			where mode_of_transportation = "School Bus" """)
def execute():
	language = frappe.get_single("System Settings").language

	if language and language.startswith('en'): return

	frappe.local.lang = language

	all_domains = frappe.get_hooks("domains")

	for domain in all_domains:
		translated_domain = _(domain, lang=language)
		if frappe.db.exists("Domain", translated_domain):
			#if domain already exists merged translated_domain and domain
			merge = False
			if frappe.db.exists("Domain", domain):
				merge=True

			frappe.rename_doc("Domain", translated_domain, domain, ignore_permissions=True, merge=merge)

	domain_settings = frappe.get_single("Domain Settings")
	active_domains = [d.domain for d in domain_settings.active_domains]
	
	try:
		for domain in active_domains:
			domain = frappe.get_doc("Domain", domain)
			domain.setup_domain()

			if int(frappe.db.get_single_value('System Settings', 'setup_complete')):
				domain.setup_sidebar_items()
				domain.setup_desktop_icons()
				domain.set_default_portal_role()
	except frappe.LinkValidationError:
		pass
def execute():
	"""
		rename feedback request documents,
		update the feedback request and save the rating and communication
		reference in Feedback Request document
	"""

	frappe.reload_doc("core", "doctype", "feedback_request")
	feedback_requests = frappe.get_all("Feedback Request")
	for request in feedback_requests:
		communication, rating = frappe.db.get_value("Communication", { "feedback_request": request.get("name") },
			["name", "rating"]) or [None, 0]

		if communication:
			frappe.db.sql("""update `tabFeedback Request` set reference_communication='{communication}',
				rating={rating} where name='{feedback_request}'""".format(
					communication=communication,
					rating=rating or 0,
					feedback_request=request.get("name")
			))

		if "Feedback" not in request.get("name"):
			# rename the feedback request doc
			reference_name, creation = frappe.db.get_value("Feedback Request", request.get("name"), ["name", "creation"])
			oldname = request.get("name")
			newname = "Feedback for {doctype} {docname} on {datetime}".format(
				doctype="Feedback Request",
				docname=reference_name,
				datetime=creation
			)
			frappe.rename_doc("Feedback Request", oldname, newname, ignore_permissions=True)
			if communication: frappe.db.set_value("Communication", communication, "feedback_request", newname)
def execute():
	rename_doc('DocType', 'Production Order', 'Work Order', force=True)
	frappe.reload_doc('manufacturing', 'doctype', 'work_order')

	rename_doc('DocType', 'Production Order Item', 'Work Order Item', force=True)
	frappe.reload_doc('manufacturing', 'doctype', 'work_order_item')

	rename_doc('DocType', 'Production Order Operation', 'Work Order Operation', force=True)
	frappe.reload_doc('manufacturing', 'doctype', 'work_order_operation')

	frappe.reload_doc('projects', 'doctype', 'timesheet')
	frappe.reload_doc('stock', 'doctype', 'stock_entry')
	rename_field("Timesheet", "production_order", "work_order")
	rename_field("Stock Entry", "production_order", "work_order")

	frappe.rename_doc("Report", "Production Orders in Progress", "Work Orders in Progress", force=True)
	frappe.rename_doc("Report", "Completed Production Orders", "Completed Work Orders", force=True)
	frappe.rename_doc("Report", "Open Production Orders", "Open Work Orders", force=True)
	frappe.rename_doc("Report", "Issued Items Against Production Order", "Issued Items Against Work Order", force=True)
	frappe.rename_doc("Report", "Production Order Stock Report", "Work Order Stock Report", force=True)

	frappe.db.sql("""update `tabDesktop Icon` \
		set label='Work Order', module_name='Work Order' \
		where label='Production Order'""")
	frappe.db.sql("""update `tabDesktop Icon` \
		set link='List/Work Order' \
		where link='List/Production Order'""")
Ejemplo n.º 8
0
def update_number_field(doctype_name, name, field_name, number_value, company):
	'''
		doctype_name = Name of the DocType
		name = Docname being referred
		field_name = Name of the field thats holding the 'number' attribute
		number_value = Numeric value entered in field_name

		Stores the number entered in the dialog to the DocType's field.

		Renames the document by adding the number as a prefix to the current name and updates
		all transaction where it was present.
	'''
	doc_title = frappe.db.get_value(doctype_name, name, frappe.scrub(doctype_name)+"_name")

	validate_field_number(doctype_name, name, number_value, company, field_name)

	frappe.db.set_value(doctype_name, name, field_name, number_value)

	if doc_title[0].isdigit():
		separator = " - " if " - " in doc_title else " "
		doc_title = doc_title.split(separator, 1)[1]

	frappe.db.set_value(doctype_name, name, frappe.scrub(doctype_name)+"_name", doc_title)

	new_name = get_autoname_with_number(number_value, doc_title, name, company)

	if name != new_name:
		frappe.rename_doc(doctype_name, name, new_name)
		return new_name
Ejemplo n.º 9
0
	def test_rename(self):
		frappe.rename_doc("Customer", "_Test Customer 1", "_Test Customer 1 Renamed")

		self.assertTrue(frappe.db.exists("Customer", "_Test Customer 1 Renamed"))
		self.assertFalse(frappe.db.exists("Customer", "_Test Customer 1"))
		
		frappe.rename_doc("Customer", "_Test Customer 1 Renamed", "_Test Customer 1")
def execute():
	if frappe.db.table_exists("Offer Letter") and not frappe.db.table_exists("Job Offer"):
		frappe.rename_doc("DocType", "Offer Letter", "Job Offer", force=True)
		frappe.rename_doc("DocType", "Offer Letter Term", "Job Offer Term", force=True)
		frappe.reload_doc("hr", "doctype", "job_offer")
		frappe.reload_doc("hr", "doctype", "job_offer_term")
		frappe.delete_doc("Print Format", "Offer Letter")
Ejemplo n.º 11
0
	def test_rename_account(self):
		if not frappe.db.exists("Account", "1210 - Debtors - _TC"):
			acc = frappe.new_doc("Account")
			acc.account_name = "Debtors"
			acc.parent_account = "Accounts Receivable - _TC"
			acc.account_number = "1210"
			acc.company = "_Test Company"
			acc.insert()

		account_number, account_name = frappe.db.get_value("Account", "1210 - Debtors - _TC",
			["account_number", "account_name"])
		self.assertEqual(account_number, "1210")
		self.assertEqual(account_name, "Debtors")

		frappe.rename_doc("Account", "1210 - Debtors - _TC", "1211 - Debtors 1 - _TC")

		new_acc = frappe.db.get_value("Account", "1211 - Debtors 1 - _TC",
			["account_name", "account_number"], as_dict=1)
		self.assertEqual(new_acc.account_name, "Debtors 1")
		self.assertEqual(new_acc.account_number, "1211")

		frappe.rename_doc("Account", "1211 - Debtors 1 - _TC", "Debtors 2")

		new_acc = frappe.db.get_value("Account", "1211 - Debtors 2 - _TC",
			["account_name", "account_number"], as_dict=1)
		self.assertEqual(new_acc.account_name, "Debtors 2")
		self.assertEqual(new_acc.account_number, "1211")

		frappe.delete_doc("Account", "1211 - Debtors 2 - _TC")
Ejemplo n.º 12
0
	def test_rename(self):
		# delete communication linked to these 2 customers
		for name in ("_Test Customer 1", "_Test Customer 1 Renamed"):
			frappe.db.sql("""delete from `tabCommunication`
				where communication_type='Comment' and reference_doctype=%s and reference_name=%s""",
				("Customer", name))

		# add comments
		comment = frappe.get_doc("Customer", "_Test Customer 1").add_comment("Comment", "Test Comment for Rename")

		# rename
		frappe.rename_doc("Customer", "_Test Customer 1", "_Test Customer 1 Renamed")

		# check if customer renamed
		self.assertTrue(frappe.db.exists("Customer", "_Test Customer 1 Renamed"))
		self.assertFalse(frappe.db.exists("Customer", "_Test Customer 1"))

		# test that comment gets linked to renamed doc
		self.assertEquals(frappe.db.get_value("Communication", {
			"communication_type": "Comment",
			"reference_doctype": "Customer",
			"reference_name": "_Test Customer 1 Renamed"
		}), comment.name)

		# rename back to original
		frappe.rename_doc("Customer", "_Test Customer 1 Renamed", "_Test Customer 1")
Ejemplo n.º 13
0
def execute():
	from frappe.core.doctype.file.file import make_home_folder

	if not frappe.db.exists("DocType", "File"):
		frappe.rename_doc("DocType", "File Data", "File")
		frappe.reload_doctype("File")

	if not frappe.db.exists("File", {"is_home_folder": 1}):
		make_home_folder()

	# make missing folders and set parent folder
	for file in frappe.get_all("File", filters={"is_folder": 0}):
		file = frappe.get_doc("File", file.name)
		file.flags.ignore_folder_validate = True
		file.flags.ignore_file_validate = True
		file.flags.ignore_duplicate_entry_error = True
		file.flags.ignore_links = True
		file.set_folder_name()
		try:
			file.save()
		except:
			print frappe.get_traceback()
			raise

	from frappe.utils.nestedset import rebuild_tree
	rebuild_tree("File", "folder")

	# reset file size
	for folder in frappe.db.sql("""select name from tabFile f1 where is_folder = 1 and
		(select count(*) from tabFile f2 where f2.folder = f1.name and f2.is_folder = 1) = 0"""):
		folder = frappe.get_doc("File", folder[0])
		folder.save()
def execute():
	frappe.rename_doc('Language', 'zh-cn', 'zh', force=True,
		merge=True if frappe.db.exists('Language', 'zh') else False)
	if frappe.db.get_value('Language', 'zh-tw') == 'zh-tw':
		frappe.rename_doc('Language', 'zh-tw', 'zh-TW', force=True)

	frappe.db.set_value('Language', 'zh', 'language_code', 'zh')
	frappe.db.set_value('Language', 'zh-TW', 'language_code', 'zh-TW')
def execute():
	if frappe.db.exists("DocType", "Examination"):
		frappe.rename_doc("DocType", "Examination", "Assessment")
		frappe.reload_doctype("Assessment")
		rename_field("Assessment", "exam_name", "assessment_name")
		rename_field("Assessment", "exam_code", "assessment_code")
	
		frappe.db.sql("delete from `tabPortal Menu Item` where route = '/examination'")
def execute():
	hr = frappe.db.get_value("Module Def", "HR")
	if hr == "Hr":
		frappe.rename_doc("Module Def", "Hr", "HR")
		frappe.db.set_value("Module Def", "HR", "module_name", "HR")

	frappe.clear_cache()
	frappe.setup_module_map()
Ejemplo n.º 17
0
def rename_and_reload_doctypes():
	if "tabVariant Attribute" in frappe.db.get_tables():
		frappe.rename_doc("DocType", "Variant Attribute", "Item Variant Attribute")

	frappe.reload_doctype("Item")
	frappe.reload_doc("Stock", "DocType", "Item Variant Attribute")
	frappe.reload_doc("Stock", "DocType", "Item Attribute Value")
	frappe.reload_doc("Stock", "DocType", "Item Attribute")
def execute():
	if not 'tabError Log' in frappe.db.get_tables():
		frappe.rename_doc('DocType', 'Scheduler Log', 'Error Log')
		frappe.db.sql("""delete from `tabError Log` where datediff(curdate(), creation) > 30""")
		frappe.db.commit()
		frappe.db.sql('alter table `tabError Log` change column name name varchar(140)')
		frappe.db.sql('alter table `tabError Log` change column parent parent varchar(140)')
		frappe.db.sql('alter table `tabError Log` engine=MyISAM')
Ejemplo n.º 19
0
    def test_merge_leaves(self):
        frappe.rename_doc("Item Group", "_Test Item Group B - 2", "_Test Item Group B - 1", merge=True)
        records_to_test = test_records[2:]
        del records_to_test[3]
        self.test_basic_tree(records=records_to_test)

        # insert Group B - 2back
        frappe.copy_doc(test_records[5]).insert()
        self.test_basic_tree()
Ejemplo n.º 20
0
def execute():
	tables = frappe.db.sql_list("show tables")
	if "tabUser" not in tables:
		frappe.rename_doc("DocType", "Profile", "User", force=True)

	frappe.reload_doc("website", "doctype", "blogger")

	if "profile" in get_table_columns("Blogger"):
		rename_field("Blogger", "profile", "user")
Ejemplo n.º 21
0
def change_item_code(item, item_code, doc_name):
	item_exist = frappe.db.exists({
		"doctype": "Item",
		"item_code": item_code})
	if(item_exist):
		frappe.throw(_("Code {0} already exist").format(item_code))
	else:
		frappe.rename_doc("Item", item, item_code, ignore_permissions = True)
		frappe.db.set_value("Healthcare Service Unit Type", doc_name, "item_code", item_code)
def execute():
	if frappe.db.table_exists("Sales Taxes and Charges Master"):
		frappe.rename_doc("DocType", "Sales Taxes and Charges Master",
			"Sales Taxes and Charges Template")
		frappe.delete_doc("DocType", "Sales Taxes and Charges Master")

	if frappe.db.table_exists("Purchase Taxes and Charges Master"):
		frappe.rename_doc("DocType", "Purchase Taxes and Charges Master",
			"Purchase Taxes and Charges Template")
		frappe.delete_doc("DocType", "Purchase Taxes and Charges Master")
Ejemplo n.º 23
0
def link_customer_and_address(raw_billing_data,customer_status):

	if customer_status == 0:
		# create
		customer = frappe.new_doc("Customer")
		address = frappe.new_doc("Address")

	if customer_status == 1:
		# Edit
		customer_woo_com_email = raw_billing_data.get("email")
		customer = frappe.get_doc("Customer",{"woocommerce_email": customer_woo_com_email})
		old_name = customer.customer_name

	full_name = str(raw_billing_data.get("first_name"))+ " "+str(raw_billing_data.get("last_name"))
	customer.customer_name = full_name
	customer.woocommerce_email = str(raw_billing_data.get("email"))
	customer.save()
	frappe.db.commit()

	if customer_status == 1:
		frappe.rename_doc("Customer", old_name, full_name)
		address = frappe.get_doc("Address",{"woocommerce_email":customer_woo_com_email})
		customer = frappe.get_doc("Customer",{"woocommerce_email": customer_woo_com_email})

	address.address_line1 = raw_billing_data.get("address_1", "Not Provided")
	address.address_line2 = raw_billing_data.get("address_2", "Not Provided")
	address.city = raw_billing_data.get("city", "Not Provided")
	address.woocommerce_email = str(raw_billing_data.get("email"))
	address.address_type = "Shipping"
	address.country = frappe.get_value("Country", filters={"code":raw_billing_data.get("country", "IN").lower()})
	address.state =  raw_billing_data.get("state")
	address.pincode =  str(raw_billing_data.get("postcode"))
	address.phone = str(raw_billing_data.get("phone"))
	address.email_id = str(raw_billing_data.get("email"))

	address.append("links", {
		"link_doctype": "Customer",
		"link_name": customer.customer_name
	})

	address.save()
	frappe.db.commit()

	if customer_status == 1:

		address = frappe.get_doc("Address",{"woocommerce_email":customer_woo_com_email})
		old_address_title = address.name
		new_address_title = customer.customer_name+"-billing"
		address.address_title = customer.customer_name
		address.save()

		frappe.rename_doc("Address",old_address_title,new_address_title)

	frappe.db.commit()
Ejemplo n.º 24
0
def execute():
	if frappe.db.table_exists("Time Sheet") and not frappe.db.table_exists("Timesheet"):
		frappe.rename_doc("DocType", "Time Sheet", "Timesheet")
		frappe.rename_doc("DocType", "Time Sheet Detail", "Timesheet Detail")
		
		for doctype in ['Time Sheet', 'Time Sheet Detail']:
			frappe.delete_doc('DocType', doctype)
		
		report = "Daily Time Sheet Summary"
		if frappe.db.exists("Report", report):
			frappe.delete_doc('Report', report)
def execute():
	frappe.reload_doc("non_profit", "doctype", "member")
	old_named_members = frappe.get_all("Member", filters = {"name": ("not like", "MEM-%")})
	correctly_named_members = frappe.get_all("Member", filters = {"name": ("like", "MEM-%")})
	current_index = len(correctly_named_members)

	for member in old_named_members:
		current_index += 1
		frappe.rename_doc("Member", member["name"], "MEM-" + str(current_index).zfill(5))

	frappe.db.sql("""update `tabMember` set naming_series = 'MEM-'""")
def change_item_code_from_template(item_code, doc):
	args = json.loads(doc)
	doc = frappe._dict(args)

	if(frappe.db.exists({
		"doctype": "Item",
		"item_code": item_code})):
		frappe.throw(_("Code {0} already exist").format(item_code))
	else:
		frappe.rename_doc("Item", doc.item_code, item_code, ignore_permissions = True)
		frappe.db.set_value("Clinical Procedure Template", doc.name, "item_code", item_code)
	return
Ejemplo n.º 27
0
def update_account_number(name, account_name, account_number=None):

	account = frappe.db.get_value("Account", name, ["company"], as_dict=True)
	validate_account_number(name, account_number, account.company)
	if account_number:
		frappe.db.set_value("Account", name, "account_number", account_number.strip())
	frappe.db.set_value("Account", name, "account_name", account_name.strip())

	new_name = get_account_autoname(account_number, account_name, account.company)
	if name != new_name:
		frappe.rename_doc("Account", name, new_name, ignore_permissions=1)
		return new_name
Ejemplo n.º 28
0
def rename_account_for(dt, olddn, newdn, merge, company):
    old_account = get_account_for(dt, olddn)
    if old_account:
        new_account = None
        if not merge:
            if old_account == add_abbr_if_missing(olddn, company):
                new_account = frappe.rename_doc("Account", old_account, newdn)
        else:
            existing_new_account = get_account_for(dt, newdn)
            new_account = frappe.rename_doc(
                "Account", old_account, existing_new_account or newdn, merge=True if existing_new_account else False
            )

        frappe.db.set_value("Account", new_account or old_account, "master_name", newdn)
Ejemplo n.º 29
0
	def rename_account_for(self, olddn, newdn, merge):
		old_account = self.get_account(olddn)

		if old_account:
			new_account = None
			if not merge:
				if old_account == self.add_abbr_if_missing(olddn):
					new_account = frappe.rename_doc("Account", old_account, newdn)
			else:
				existing_new_account = self.get_account(newdn)
				new_account = frappe.rename_doc("Account", old_account,
					existing_new_account or newdn, merge=True if existing_new_account else False)

			frappe.db.set_value("Account", new_account or old_account, "warehouse", newdn)
Ejemplo n.º 30
0
def change_test_code_from_template(lab_test_code, doc):
	args = json.loads(doc)
	doc = frappe._dict(args)

	item_exist = frappe.db.exists({
		"doctype": "Item",
		"item_code": lab_test_code})
	if(item_exist):
		frappe.throw(_("Code {0} already exist").format(lab_test_code))
	else:
		frappe.rename_doc("Item", doc.name, lab_test_code, ignore_permissions = True)
		frappe.db.set_value("Lab Test Template",doc.name,"lab_test_code",lab_test_code)
		frappe.rename_doc("Lab Test Template", doc.name, lab_test_code, ignore_permissions = True)
	return lab_test_code
Ejemplo n.º 31
0
def execute():
    if frappe.db.table_exists("Bank Reconciliation"):
        frappe.rename_doc('DocType',
                          'Bank Reconciliation',
                          'Bank Clearance',
                          force=True)
        frappe.reload_doc('Accounts', 'doctype', 'Bank Clearance')

        frappe.rename_doc('DocType',
                          'Bank Reconciliation Detail',
                          'Bank Clearance Detail',
                          force=True)
        frappe.reload_doc('Accounts', 'doctype', 'Bank Clearance Detail')

    _rename_single_field(doctype="Bank Clearance",
                         old_name="bank_account",
                         new_name="account")
    _rename_single_field(doctype="Bank Clearance",
                         old_name="bank_account_no",
                         new_name="bank_account")
Ejemplo n.º 32
0
def execute():
    if frappe.db.table_exists("Supplier Group"):
        frappe.reload_doc('setup', 'doctype', 'supplier_group')
    elif frappe.db.table_exists("Supplier Type"):
        frappe.rename_doc("DocType",
                          "Supplier Type",
                          "Supplier Group",
                          force=True)
        frappe.reload_doc('setup', 'doctype', 'supplier_group')
        frappe.reload_doc("accounts", "doctype", "pricing_rule")
        frappe.reload_doc("accounts", "doctype", "tax_rule")
        frappe.reload_doc("buying", "doctype", "buying_settings")
        frappe.reload_doc("buying", "doctype", "supplier")
        rename_field("Supplier Group", "supplier_type", "supplier_group_name")
        rename_field("Supplier", "supplier_type", "supplier_group")
        rename_field("Buying Settings", "supplier_type", "supplier_group")
        rename_field("Pricing Rule", "supplier_type", "supplier_group")
        rename_field("Tax Rule", "supplier_type", "supplier_group")

    build_tree()
Ejemplo n.º 33
0
def update_account_number(name, account_number):
    account = frappe.db.get_value("Account",
                                  name, ["account_name", "company"],
                                  as_dict=True)

    validate_account_number(name, account_number, account.company)

    frappe.db.set_value("Account", name, "account_number", account_number)

    account_name = account.account_name
    if account_name[0].isdigit():
        separator = " - " if " - " in account_name else " "
        account_name = account_name.split(separator, 1)[1]
    frappe.db.set_value("Account", name, "account_name", account_name)

    new_name = get_account_autoname(account_number, account_name,
                                    account.company)
    if name != new_name:
        frappe.rename_doc("Account", name, new_name)
        return new_name
Ejemplo n.º 34
0
def execute():
    # rename doctypes
    tables = frappe.db.sql_list("show tables")
    for old_dt, new_dt in [["Journal Voucher Detail", "Journal Entry Account"],
                           ["Journal Voucher", "Journal Entry"],
                           [
                               "Budget Distribution Detail",
                               "Monthly Distribution Percentage"
                           ], ["Budget Distribution", "Monthly Distribution"]]:
        if "tab" + new_dt not in tables:
            frappe.rename_doc("DocType", old_dt, new_dt, force=True)

    # reload new child doctypes
    frappe.reload_doc("manufacturing", "doctype", "production_order_operation")
    frappe.reload_doc("manufacturing", "doctype", "workstation_working_hour")
    frappe.reload_doc("stock", "doctype", "item_variant")
    frappe.reload_doc("accounts", "doctype", "party_account")
    frappe.reload_doc("accounts", "doctype", "fiscal_year_company")

    #rename table fieldnames
    for dn in rename_map:
        if not frappe.db.exists("DocType", dn):
            continue
        frappe.reload_doc(get_doctype_module(dn), "doctype", scrub(dn))

    for dt, field_list in rename_map.items():
        if not frappe.db.exists("DocType", dt):
            continue
        for field in field_list:
            rename_field(dt, field[0], field[1])

    # update voucher type
    for old, new in [["Bank Voucher", "Bank Entry"],
                     ["Cash Voucher", "Cash Entry"],
                     ["Credit Card Voucher", "Credit Card Entry"],
                     ["Contra Voucher", "Contra Entry"],
                     ["Write Off Voucher", "Write Off Entry"],
                     ["Excise Voucher", "Excise Entry"]]:
        frappe.db.sql(
            "update `tabJournal Entry` set voucher_type=%s where voucher_type=%s",
            (new, old))
Ejemplo n.º 35
0
	def _anonymize_data(self, email=None, anon=None, set_data=True, commit=False):
		email = email or self.email
		anon = anon or self.name

		if set_data:
			self.__set_anonymization_data(email, anon)

		self.add_deletion_steps()

		self.full_match_doctypes = (
			x
			for x in self.full_match_privacy_docs
			if filter(
				lambda x: x.document_type == x and x.status == "Pending", self.deletion_steps
			)
		)

		self.partial_match_doctypes = (
			x
			for x in self.partial_privacy_docs
			if filter(
				lambda x: x.document_type == x and x.status == "Pending", self.deletion_steps
			)
		)

		for doctype in self.full_match_doctypes:
			self.redact_full_match_data(doctype, email)
			self.set_step_status(doctype["doctype"])
			if commit:
				frappe.db.commit()

		for doctype in self.partial_match_doctypes:
			self.redact_partial_match_data(doctype)
			self.set_step_status(doctype["doctype"])
			if commit:
				frappe.db.commit()

		frappe.rename_doc("User", email, anon, force=True, show_alert=False)
		self.db_set("status", "Deleted")
		if commit:
			frappe.db.commit()
Ejemplo n.º 36
0
def execute():
    rename_doc('DocType', 'Production Order', 'Work Order', force=True)
    frappe.reload_doc('manufacturing', 'doctype', 'work_order')

    rename_doc('DocType',
               'Production Order Item',
               'Work Order Item',
               force=True)
    frappe.reload_doc('manufacturing', 'doctype', 'work_order_item')

    rename_doc('DocType',
               'Production Order Operation',
               'Work Order Operation',
               force=True)
    frappe.reload_doc('manufacturing', 'doctype', 'work_order_operation')

    frappe.reload_doc('projects', 'doctype', 'timesheet')
    frappe.reload_doc('stock', 'doctype', 'stock_entry')
    rename_field("Timesheet", "production_order", "work_order")
    rename_field("Stock Entry", "production_order", "work_order")

    frappe.rename_doc("Report",
                      "Production Orders in Progress",
                      "Work Orders in Progress",
                      force=True)
    frappe.rename_doc("Report",
                      "Completed Production Orders",
                      "Completed Work Orders",
                      force=True)
    frappe.rename_doc("Report",
                      "Open Production Orders",
                      "Open Work Orders",
                      force=True)
    frappe.rename_doc("Report",
                      "Issued Items Against Production Order",
                      "Issued Items Against Work Order",
                      force=True)
    frappe.rename_doc("Report",
                      "Production Order Stock Report",
                      "Work Order Stock Report",
                      force=True)
Ejemplo n.º 37
0
    def test_impact_on_merging_items(self):
        "Check if merging items is blocked if old and new items both have website items"
        first_item = make_item("Test First Item")
        second_item = make_item("Test Second Item")

        first_web_item = make_website_item(first_item, save=False)
        first_web_item.save()
        second_web_item = make_website_item(second_item, save=False)
        second_web_item.save()

        with self.assertRaises(DataValidationError):
            frappe.rename_doc("Item",
                              "Test First Item",
                              "Test Second Item",
                              merge=True)

        # tear down
        second_web_item.delete()
        first_web_item.delete()
        second_item.delete()
        first_item.delete()
Ejemplo n.º 38
0
	def test_merge_groups(self):
		frappe.rename_doc("Item Group", "_Test Item Group B", "_Test Item Group C", merge=True)
		records_to_test = test_records[2:]
		del records_to_test[1]
		self.test_basic_tree(records=records_to_test)

		# insert Group B back
		frappe.copy_doc(test_records[3]).insert()
		self.test_basic_tree()

		# move its children back
		for name in frappe.db.sql_list(
			"""select name from `tabItem Group`
			where parent_item_group='_Test Item Group C'"""
		):

			doc = frappe.get_doc("Item Group", name)
			doc.parent_item_group = "_Test Item Group B"
			doc.save()

		self.test_basic_tree()
Ejemplo n.º 39
0
	def after_rename(self, old_name, new_name, merge=False):
		tables = frappe.db.get_tables()
		for tab in tables:
			desc = frappe.db.get_table_columns_description(tab)
			has_fields = []
			for d in desc:
				if d.get('name') in ['owner', 'modified_by']:
					has_fields.append(d.get('name'))
			for field in has_fields:
				frappe.db.sql("""UPDATE `%s`
					SET `%s` = %s
					WHERE `%s` = %s""" %
					(tab, field, '%s', field, '%s'), (new_name, old_name))

		if frappe.db.exists("Chat Profile", old_name):
			frappe.rename_doc("Chat Profile", old_name, new_name, force=True)

		# set email
		frappe.db.sql("""UPDATE `tabUser`
			SET email = %s
			WHERE name = %s""", (new_name, new_name))
Ejemplo n.º 40
0
	def after_rename(self, old_name, new_name, merge=False):
		tables = frappe.db.sql("show tables")
		for tab in tables:
			desc = frappe.db.sql("desc `%s`" % tab[0], as_dict=1)
			has_fields = []
			for d in desc:
				if d.get('Field') in ['owner', 'modified_by']:
					has_fields.append(d.get('Field'))
			for field in has_fields:
				frappe.db.sql("""\
					update `%s` set `%s`=%s
					where `%s`=%s""" % \
					(tab[0], field, '%s', field, '%s'), (new_name, old_name))

		if frappe.db.exists("Chat Profile", old_name):
			frappe.rename_doc("Chat Profile", old_name, new_name, force=True)

		# set email
		frappe.db.sql("""\
			update `tabUser` set email=%s
			where name=%s""", (new_name, new_name))
Ejemplo n.º 41
0
	def test_rename(self):
		for name in ("_Test Customer 1", "_Test Customer 1 Renamed"):
			frappe.db.sql("""delete from `tabCommunication`
				where communication_type='Comment' and reference_doctype=%s and reference_name=%s""",
				("Customer", name))

		comment = frappe.get_doc("Customer", "_Test Customer 1").add_comment("Comment", "Test Comment for Rename")

		frappe.rename_doc("Customer", "_Test Customer 1", "_Test Customer 1 Renamed")

		self.assertTrue(frappe.db.exists("Customer", "_Test Customer 1 Renamed"))
		self.assertFalse(frappe.db.exists("Customer", "_Test Customer 1"))

		# test that comment gets renamed
		self.assertEquals(frappe.db.get_value("Communication", {
			"communication_type": "Comment",
			"reference_doctype": "Customer",
			"reference_name": "_Test Customer 1 Renamed"
		}), comment.name)

		frappe.rename_doc("Customer", "_Test Customer 1 Renamed", "_Test Customer 1")
Ejemplo n.º 42
0
def execute():
    doctype = 'POS Profile'
    frappe.reload_doctype(doctype)

    for pos in frappe.get_all(doctype, filters={'disabled': 0}):
        doc = frappe.get_doc(doctype, pos.name)

        if not doc.user and doc.pos_profile_name: continue

        try:
            doc.pos_profile_name = doc.user + ' - ' + doc.company
            doc.flags.ignore_validate = True
            doc.flags.ignore_mandatory = True
            doc.save()

            frappe.rename_doc(doctype,
                              doc.name,
                              doc.pos_profile_name,
                              force=True)
        except frappe.LinkValidationError:
            frappe.db.set_value("POS Profile", doc.name, 'disabled', 1)
Ejemplo n.º 43
0
 def test_rename_doc(self):
     """Rename an existing document via frappe.rename_doc"""
     old_name = choice(self.available_documents)
     new_name = old_name + ".new"
     self.assertEqual(
         new_name,
         frappe.rename_doc(self.test_doctype,
                           old_name,
                           new_name,
                           force=True))
     self.available_documents.remove(old_name)
     self.available_documents.append(new_name)
Ejemplo n.º 44
0
def execute():
    if frappe.db.exists("DocType", "Membership Settings"):
        frappe.rename_doc("DocType", "Membership Settings",
                          "Non Profit Settings")
        frappe.reload_doctype("Non Profit Settings", force=True)

    if frappe.db.exists("DocType", "Non Profit Settings"):
        rename_fields_map = {
            "enable_invoicing": "allow_invoicing",
            "create_for_web_forms": "automate_membership_invoicing",
            "make_payment_entry": "automate_membership_payment_entries",
            "enable_razorpay": "enable_razorpay_for_memberships",
            "debit_account": "membership_debit_account",
            "payment_account": "membership_payment_account",
            "webhook_secret": "membership_webhook_secret",
        }

        for old_name, new_name in rename_fields_map.items():
            rename_field("Non Profit Settings", old_name, new_name)

        frappe.delete_doc_if_exists("DocType", "Membership Settings")
Ejemplo n.º 45
0
def execute():
    frappe.reload_doc('stock', 'doctype', 'item')
    language = frappe.get_single("System Settings").language

    if language and language.startswith('en'): return

    frappe.local.lang = language

    all_domains = frappe.get_hooks("domains")

    for domain in all_domains:
        translated_domain = _(domain, lang=language)
        if frappe.db.exists("Domain", translated_domain):
            #if domain already exists merged translated_domain and domain
            merge = False
            if frappe.db.exists("Domain", domain):
                merge = True

            frappe.rename_doc("Domain",
                              translated_domain,
                              domain,
                              ignore_permissions=True,
                              merge=merge)

    domain_settings = frappe.get_single("Domain Settings")
    active_domains = [d.domain for d in domain_settings.active_domains]

    try:
        for domain in active_domains:
            domain = frappe.get_doc("Domain", domain)
            domain.setup_domain()

            if int(
                    frappe.db.get_single_value('System Settings',
                                               'setup_complete')):
                domain.setup_sidebar_items()
                domain.setup_desktop_icons()
                domain.set_default_portal_role()
    except frappe.LinkValidationError:
        pass
Ejemplo n.º 46
0
def execute():
    #Rename Grading Structure to Grading Scale
    if not frappe.db.exists("DocType", "Grading Scale"):
        frappe.rename_doc("DocType",
                          "Grading Structure",
                          "Grading Scale",
                          force=True)
    if not frappe.db.exists("DocType", "Grading Scale Interval"):
        frappe.rename_doc("DocType",
                          "Grade Interval",
                          "Grading Scale Interval",
                          force=True)

    # frappe.reload_doc("schools", "doctype", "grading_scale_interval")
    frappe.reload_doc("education", "doctype", "grading_scale_interval")
    if "to_score" in frappe.db.get_table_columns("Grading Scale Interval"):
        rename_field("Grading Scale Interval", "to_score", "threshold")

    if not frappe.db.exists("DocType", "Assessment Plan"):
        frappe.rename_doc("DocType",
                          "Assessment",
                          "Assessment Plan",
                          force=True)

    # 'Schools' module changed to the 'Education'
    # frappe.reload_doc("schools", "doctype", "assessment_plan")

    #Rename Assessment Results
    frappe.reload_doc("education", "doctype", "assessment_plan")
    if "grading_structure" in frappe.db.get_table_columns("Assessment Plan"):
        rename_field("Assessment Plan", "grading_structure", "grading_scale")

    # frappe.reload_doc("schools", "doctype", "assessment_result")
    # frappe.reload_doc("schools", "doctype", "assessment_result_detail")
    # frappe.reload_doc("schools", "doctype", "assessment_criteria")
    frappe.reload_doc("education", "doctype", "assessment_result")
    frappe.reload_doc("education", "doctype", "assessment_result_detail")
    frappe.reload_doc("education", "doctype", "assessment_criteria")

    for assessment in frappe.get_all("Assessment Plan",
                                     fields=["name", "grading_scale"],
                                     filters=[["docstatus", "!=", 2]]):
        for stud_result in frappe.db.sql(
                "select * from `tabAssessment Result` where parent= %s",
                assessment.name,
                as_dict=True):
            if stud_result.result:
                assessment_result = frappe.new_doc("Assessment Result")
                assessment_result.student = stud_result.student
                assessment_result.student_name = stud_result.student_name
                assessment_result.assessment_plan = assessment.name
                assessment_result.grading_scale = assessment.grading_scale
                assessment_result.total_score = stud_result.result
                assessment_result.flags.ignore_validate = True
                assessment_result.flags.ignore_mandatory = True
                assessment_result.save()

    frappe.db.sql(
        """delete from `tabAssessment Result` where parent != '' or parent is not null"""
    )
Ejemplo n.º 47
0
def execute():
    tables = frappe.db.sql_list("show tables")
    if "tabWebsite Route" not in tables:
        frappe.rename_doc("DocType",
                          "Website Sitemap",
                          "Website Route",
                          force=True)

    if "tabWebsite Template" not in tables:
        frappe.rename_doc("DocType",
                          "Website Sitemap Config",
                          "Website Template",
                          force=True)

    try:
        if "tabWebsite Route Permission" not in tables:
            frappe.rename_doc("DocType",
                              "Website Sitemap Permission",
                              "Website Route Permission",
                              force=True)

        for d in ("Blog Category", "Blog Post", "Web Page", "Website Route",
                  "Website Group"):
            rename_field(d, "parent_website_sitemap", "parent_website_route")

        rename_field("Website Route", "website_sitemap_config",
                     "website_template")
        rename_field("Website Route Permission", "website_sitemap",
                     "website_route")
    except Exception, e:
        if e.args[0] != 1054:
            raise
def execute():
	# 'Schools' module changed to the 'Education'


	frappe.rename_doc("DocType", "Evaluation Criteria", "Assessment Criteria", force=True)
	# frappe.reload_doc("schools", "doctype", "assessment_criteria")
	frappe.reload_doc("education", "doctype", "assessment_criteria")
	if 'evaluation_criteria' in frappe.db.get_table_columns('Assessment Criteria'):
		rename_field("Assessment Criteria", "evaluation_criteria", "assessment_criteria")

	frappe.rename_doc("DocType", "Assessment Evaluation Criteria", "Assessment Plan Criteria", force=True)
	# frappe.reload_doc("schools", "doctype", "assessment_plan_criteria")
	frappe.reload_doc("education", "doctype", "assessment_plan_criteria")
	if 'evaluation_criteria' in frappe.db.get_table_columns('Assessment Plan'):
		rename_field("Assessment Plan Criteria", "evaluation_criteria", "assessment_criteria")

	# frappe.reload_doc("schools", "doctype", "assessment_plan")
	frappe.reload_doc("education", "doctype", "assessment_plan")
	rename_field("Assessment Plan", "evaluation_criterias", "assessment_criteria")

	# frappe.reload_doc("schools", "doctype", "assessment_result_detail")
	frappe.reload_doc("education", "doctype", "assessment_result_detail")
	if 'evaluation_criteria' in frappe.db.get_table_columns('Assessment Result Detail'):
		rename_field("Assessment Result Detail", "evaluation_criteria", "assessment_criteria")

	frappe.rename_doc("DocType", "Course Evaluation Criteria", "Course Assessment Criteria", force=True)
	# frappe.reload_doc("schools", "doctype", "course_assessment_criteria")
	frappe.reload_doc("education", "doctype", "course_assessment_criteria")
	if 'evaluation_criteria' in frappe.db.get_table_columns('Course Assessment Criteria'):
		rename_field("Course Assessment Criteria", "evaluation_criteria", "assessment_criteria")

	# frappe.reload_doc("schools", "doctype", "course")
	frappe.reload_doc("education", "doctype", "course")
	if 'evaluation_criteria' in frappe.db.get_table_columns('Course'):
		rename_field("Course", "evaluation_criterias", "assessment_criteria")
Ejemplo n.º 49
0
def execute():
	if not frappe.db.exists("Role", "Stock User"):
		frappe.rename_doc("Role", "Material User", "Stock User")
	if not frappe.db.exists("Role", "Stock Manager"):
		frappe.rename_doc("Role", "Material Manager", "Stock Manager")
	if not frappe.db.exists("Role", "Stock Manager"):
		frappe.rename_doc("Role", "Material Master Manager", "Item Manager")
Ejemplo n.º 50
0
	def test_rename_doc(self):
		from random import choice, sample

		available_documents = []
		doctype = "ToDo"

		# data generation: 4 todo documents
		for num in range(1, 5):
			doc = frappe.get_doc({
				"doctype": doctype,
				"date": add_to_date(now(), days=num),
				"description": "this is todo #{}".format(num)
			}).insert()
			available_documents.append(doc.name)

		# test 1: document renaming
		old_name = choice(available_documents)
		new_name = old_name + '.new'
		self.assertEqual(new_name, frappe.rename_doc(doctype, old_name, new_name, force=True))
		available_documents.remove(old_name)
		available_documents.append(new_name)

		# test 2: merge documents
		first_todo, second_todo = sample(available_documents, 2)

		second_todo_doc = frappe.get_doc(doctype, second_todo)
		second_todo_doc.priority = "High"
		second_todo_doc.save()

		merged_todo = frappe.rename_doc(doctype, first_todo, second_todo, merge=True, force=True)
		merged_todo_doc = frappe.get_doc(doctype, merged_todo)
		available_documents.remove(first_todo)

		with self.assertRaises(frappe.DoesNotExistError):
			frappe.get_doc(doctype, first_todo)

		self.assertEqual(merged_todo_doc.priority, second_todo_doc.priority)

		for docname in available_documents:
			frappe.delete_doc(doctype, docname)
Ejemplo n.º 51
0
def execute():
    if frappe.db.table_exists("POS Closing Voucher"):
        if not frappe.db.exists("DocType", "POS Closing Entry"):
            frappe.rename_doc("DocType",
                              "POS Closing Voucher",
                              "POS Closing Entry",
                              force=True)

        if not frappe.db.exists("DocType", "POS Closing Entry Taxes"):
            frappe.rename_doc("DocType",
                              "POS Closing Voucher Taxes",
                              "POS Closing Entry Taxes",
                              force=True)

        if not frappe.db.exists("DocType", "POS Closing Voucher Details"):
            frappe.rename_doc("DocType",
                              "POS Closing Voucher Details",
                              "POS Closing Entry Detail",
                              force=True)

        frappe.reload_doc("Accounts", "doctype", "POS Closing Entry")
        frappe.reload_doc("Accounts", "doctype", "POS Closing Entry Taxes")
        frappe.reload_doc("Accounts", "doctype", "POS Closing Entry Detail")

    if frappe.db.exists("DocType", "POS Closing Voucher"):
        frappe.delete_doc("DocType", "POS Closing Voucher")
        frappe.delete_doc("DocType", "POS Closing Voucher Taxes")
        frappe.delete_doc("DocType", "POS Closing Voucher Details")
        frappe.delete_doc("DocType", "POS Closing Voucher Invoices")
def execute():
    if frappe.db.table_exists("POS Closing Voucher"):
        if not frappe.db.exists("DocType", "POS Closing Entry"):
            frappe.rename_doc('DocType',
                              'POS Closing Voucher',
                              'POS Closing Entry',
                              force=True)

        if not frappe.db.exists('DocType', 'POS Closing Entry Taxes'):
            frappe.rename_doc('DocType',
                              'POS Closing Voucher Taxes',
                              'POS Closing Entry Taxes',
                              force=True)

        if not frappe.db.exists('DocType', 'POS Closing Voucher Details'):
            frappe.rename_doc('DocType',
                              'POS Closing Voucher Details',
                              'POS Closing Entry Detail',
                              force=True)

        frappe.reload_doc('Accounts', 'doctype', 'POS Closing Entry')
        frappe.reload_doc('Accounts', 'doctype', 'POS Closing Entry Taxes')
        frappe.reload_doc('Accounts', 'doctype', 'POS Closing Entry Detail')

    if frappe.db.exists("DocType", "POS Closing Voucher"):
        frappe.delete_doc("DocType", "POS Closing Voucher")
        frappe.delete_doc("DocType", "POS Closing Voucher Taxes")
        frappe.delete_doc("DocType", "POS Closing Voucher Details")
        frappe.delete_doc("DocType", "POS Closing Voucher Invoices")
Ejemplo n.º 53
0
    def rename_account_for(self, olddn, newdn, merge):
        if self.is_group:
            old_account = self.get_account()
        else:
            old_account = self.get_account(olddn)

        if old_account:
            new_account = None
            if not merge:
                if old_account == self.add_abbr_if_missing(olddn):
                    new_account = frappe.rename_doc("Account", old_account,
                                                    newdn)
            else:
                existing_new_account = self.get_account(newdn)
                new_account = frappe.rename_doc(
                    "Account",
                    old_account,
                    existing_new_account or newdn,
                    merge=True if existing_new_account else False)

            frappe.db.set_value("Account", new_account or old_account,
                                "warehouse", newdn)
Ejemplo n.º 54
0
	def redact_doc(self, doc, ref):
		filter_by = ref["filter_by"]
		meta = frappe.get_meta(ref["doctype"])
		filter_by_meta = meta.get_field(filter_by)

		if filter_by_meta and filter_by_meta.fieldtype != "Link":

			if self.email in doc[filter_by]:
				value = re.sub(
					self.full_name_regex, self.anonymization_value_map["Data"], doc[filter_by]
				)
				value = re.sub(self.email_regex, self.anon, value)
				self.anonymize_fields_dict[filter_by] = value

		frappe.db.set_value(
			ref["doctype"], doc["name"], self.anonymize_fields_dict, modified_by="Administrator",
		)

		if ref.get("rename") and doc["name"] != self.anon:
			frappe.rename_doc(
				ref["doctype"], doc["name"], self.anon, force=True, show_alert=False
			)
Ejemplo n.º 55
0
    def test_rename(self):
        # delete communication linked to these 2 customers

        new_name = "_Test Customer 1 Renamed"
        for name in ("_Test Customer 1", new_name):
            frappe.db.sql(
                """delete from `tabComment`
				where reference_doctype=%s and reference_name=%s""",
                ("Customer", name),
            )

        # add comments
        comment = frappe.get_doc("Customer", "_Test Customer 1").add_comment(
            "Comment", "Test Comment for Rename")

        # rename
        frappe.rename_doc("Customer", "_Test Customer 1", new_name)

        # check if customer renamed
        self.assertTrue(frappe.db.exists("Customer", new_name))
        self.assertFalse(frappe.db.exists("Customer", "_Test Customer 1"))

        # test that comment gets linked to renamed doc
        self.assertEqual(
            frappe.db.get_value(
                "Comment",
                {
                    "reference_doctype": "Customer",
                    "reference_name": new_name,
                    "content": "Test Comment for Rename",
                },
            ),
            comment.name,
        )

        # rename back to original
        frappe.rename_doc("Customer", new_name, "_Test Customer 1")

        frappe.db.rollback()
Ejemplo n.º 56
0
def set_identifier_device_data(device_components=None,
                               string_components=None,
                               detail_components=None,
                               device_id=None):
    if device_components is not None:
        import json
        from ceti.api import encrypt

        request_components = json.loads(device_components)
        detail_components = json.loads(detail_components)
        components = {}

        base = ""
        for item in request_components:
            components[item["key"]] = item["value"]
            base = f'{base}%({item["key"]})s|'

        HA1_str = base % components
        device_id = encrypt(HA1_str, "md5")

    cookie_device_id = Device.identifier()
    if cookie_device_id is None:
        Device.set_identifier(device_id, string_components, detail_components)
    else:
        if frappe.get_value("Device", cookie_device_id) is None:
            Device.set_identifier(device_id, string_components,
                                  detail_components)
        else:
            if cookie_device_id != device_id:
                if frappe.get_value("Device", device_id) is None:
                    frappe.rename_doc('Device', cookie_device_id, device_id)
                    frappe.db.set_value("Device", device_id, "identifier",
                                        device_id)
                else:
                    pass
                    # TODO: Disconnect

    return device_id
Ejemplo n.º 57
0
	def test_rename(self):
		for name in ("_Test Customer 1", "_Test Customer 1 Renamed"):
			frappe.db.sql("""delete from `tabComment` where comment_doctype=%s and comment_docname=%s""",
				("Customer", name))

		comment = frappe.new_doc("Comment")
		comment.update({
			"comment": "Test Comment for Rename",
			"comment_doctype": "Customer",
			"comment_docname": "_Test Customer 1"
		})
		comment.insert()

		frappe.rename_doc("Customer", "_Test Customer 1", "_Test Customer 1 Renamed")

		self.assertTrue(frappe.db.exists("Customer", "_Test Customer 1 Renamed"))
		self.assertFalse(frappe.db.exists("Customer", "_Test Customer 1"))

		# test that comment gets renamed
		self.assertEquals(frappe.db.get_value("Comment",
			{"comment_doctype": "Customer", "comment_docname": "_Test Customer 1 Renamed"}), comment.name)

		frappe.rename_doc("Customer", "_Test Customer 1 Renamed", "_Test Customer 1")
Ejemplo n.º 58
0
def _rename_doc(doctype, name, naming_series):
    if frappe.get_meta(doctype).get_field("amended_from"):
        amended_from = frappe.db.get_value(doctype, name, "amended_from")
    else:
        amended_from = None

    if amended_from:
        am_id = 1
        am_prefix = amended_from
        if frappe.db.get_value(doctype, amended_from, "amended_from"):
            am_id = cint(amended_from.split('-')[-1]) + 1
            am_prefix = '-'.join(
                amended_from.split('-')[:-1])  # except the last hyphen

        fixed_name = am_prefix + '-' + str(am_id)
    else:
        fixed_name = make_autoname(naming_series + '.#####')

    frappe.db.set_value(doctype, name, "naming_series", naming_series)
    frappe.rename_doc(doctype, name, fixed_name, force=True)
    add_comment(doctype, name, fixed_name)

    return fixed_name
Ejemplo n.º 59
0
def merge_account(old, new, is_group, root_type, company):
    # Validate properties before merging
    if not frappe.db.exists("Account", new):
        throw(_("Account {0} does not exist").format(new))

    val = list(
        frappe.db.get_value("Account", new,
                            ["is_group", "root_type", "company"]))

    if val != [cint(is_group), root_type, company]:
        throw(
            _("""Merging is only possible if following properties are same in both records. Is Group, Root Type, Company"""
              ))

    if is_group and frappe.db.get_value("Account", new,
                                        "parent_account") == old:
        frappe.db.set_value(
            "Account", new, "parent_account",
            frappe.db.get_value("Account", old, "parent_account"))

    frappe.rename_doc("Account", old, new, merge=1, ignore_permissions=1)

    return new
Ejemplo n.º 60
0
def actualiza_expedientes():
    expedientes = frappe.get_all('Expediente')

    for expediente in expedientes:
        #exp = frappe.get_doc("Expediente", expediente.get("name"))
        name = expediente.get("name")
        print("{0}".format(name))
        partes = name.split("-")
        ntdoc = cint(partes[0])
        ntdoc = formatea_serie(ntdoc, 3)
        nexp = cint(partes[1])
        nexp = formatea_serie(nexp, 3)

        new_name = "{0}-{1}".format(ntdoc, nexp)
        print(new_name)

        print("------")

        frappe.rename_doc('Expediente', name, new_name, force=True)

        frappe.db.set_value('Expediente', new_name, 'expediente_name',
                            new_name)
        frappe.db.commit()