def test_import_only_children(self): user_email = "*****@*****.**" if frappe.db.exists("User", user_email): frappe.delete_doc("User", user_email) frappe.get_doc({"doctype": "User", "email": user_email, "first_name": "Test Import UserRole"}).insert() exporter.get_template("UserRole", "User", all_doctypes="No", with_data="No") content = read_csv_content(frappe.response.result) content.append(["", "*****@*****.**", "Blogger"]) importer.upload(content) user = frappe.get_doc("User", user_email) self.assertEquals(len(user.get("user_roles")), 1) self.assertTrue(user.get("user_roles")[0].role, "Blogger") # overwrite exporter.get_template("UserRole", "User", all_doctypes="No", with_data="No") content = read_csv_content(frappe.response.result) content.append(["", "*****@*****.**", "Website Manager"]) importer.upload(content, overwrite=True) user = frappe.get_doc("User", user_email) self.assertEquals(len(user.get("user_roles")), 1) self.assertTrue(user.get("user_roles")[0].role, "Website Manager")
def sync_variants(self): variant_item_codes = self.get_variant_item_codes() # delete missing variants existing_variants = [d.name for d in frappe.get_all("Item", filters={"variant_of":self.name})] updated, deleted = [], [] for existing_variant in existing_variants: if existing_variant not in variant_item_codes: frappe.delete_doc("Item", existing_variant) deleted.append(existing_variant) else: self.update_variant(existing_variant) updated.append(existing_variant) inserted = [] for item_code in variant_item_codes: if item_code not in existing_variants: self.make_variant(item_code) inserted.append(item_code) if inserted: frappe.msgprint(_("Item Variants {0} created").format(", ".join(inserted))) if updated: frappe.msgprint(_("Item Variants {0} updated").format(", ".join(updated))) if deleted: frappe.msgprint(_("Item Variants {0} deleted").format(", ".join(deleted)))
def execute(): if frappe.db.exists('DocType', 'View log'): # for mac users direct renaming would not work since mysql for mac saves table name in lower case # so while renaming `tabView log` to `tabView Log` we get "Table 'tabView Log' already exists" error # more info https://stackoverflow.com/a/44753093/5955589 , # https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_lower_case_table_names # here we are creating a temp table to store view log data frappe.db.sql("CREATE TABLE `ViewLogTemp` AS SELECT * FROM `tabView log`") # deleting old View log table frappe.db.sql("DROP table `tabView log`") frappe.delete_doc('DocType', 'View log') # reloading view log doctype to create `tabView Log` table frappe.reload_doc('core', 'doctype', 'view_log') # Move the data to newly created `tabView Log` table frappe.db.sql("INSERT INTO `tabView Log` SELECT * FROM `ViewLogTemp`") frappe.db.commit() # Delete temporary table frappe.db.sql("DROP table `ViewLogTemp`") else: frappe.reload_doc('core', 'doctype', 'view_log')
def test_coa_based_on_existing_company(self): company = frappe.new_doc("Company") company.company_name = "COA from Existing Company" company.abbr = "CFEC" company.default_currency = "INR" company.create_chart_of_accounts_based_on = "Existing Company" company.existing_company = "_Test Company" company.save() expected_results = { "Debtors - CFEC": { "account_type": "Receivable", "is_group": 0, "root_type": "Asset", "parent_account": "Accounts Receivable - CFEC", }, "_Test Cash - CFEC": { "account_type": "Cash", "is_group": 0, "root_type": "Asset", "parent_account": "Cash In Hand - CFEC" } } for account, acc_property in expected_results.items(): acc = frappe.get_doc("Account", account) for prop, val in acc_property.items(): self.assertEqual(acc.get(prop), val) self.delete_mode_of_payment("COA from Existing Company") frappe.delete_doc("Company", "COA from Existing Company")
def execute(): frappe.reload_doc("accounts", "doctype", "pricing_rule") frappe.db.auto_commit_on_many_writes = True for d in frappe.db.sql("""select * from `tabCustomer Discount` where ifnull(parent, '') != '' and docstatus < 2""", as_dict=1): if not d.item_group: item_group = frappe.db.sql("""select name from `tabItem Group` where ifnull(parent_item_group, '') = ''""")[0][0] else: item_group = d.item_group frappe.get_doc({ "doctype": "Pricing Rule", "apply_on": "Item Group", "item_group": item_group, "applicable_for": "Customer", "customer": d.parent, "price_or_discount": "Discount", "discount_percentage": d.discount }).insert() frappe.db.auto_commit_on_many_writes = False frappe.delete_doc("DocType", "Customer Discount")
def remove_sal_slip(self): cond = '' for f in ['company', 'branch', 'department', 'division', 'designation', 'employee']: if self.get(f): cond += " and t1." + f + " = '" + self.get(f).replace("'", "\'") + "'" ss_list = frappe.db.sql_list(""" select t1.name from `tabSalary Slip` as t1 where t1.fiscal_year = '%s' and t1.month = '%s' and t1.docstatus = 0 %s """ % (self.fiscal_year, self.month, cond)) if ss_list: frappe.delete_doc("Salary Slip", frappe.db.sql_list(""" select t1.name from `tabSalary Slip` as t1 where t1.fiscal_year = '%s' and t1.month = '%s' and t1.docstatus = 0 %s """ % (self.fiscal_year, self.month, cond)), for_reload=True) frappe.msgprint(_("Un-submitted Salary Slip(s) for the Month:{0} and Year:{1} removed successfully.")\ .format(self.month, self.fiscal_year)) else: frappe.msgprint(_("No Un-submitted Salary Slip(s) Found."))
def test_auto_insert_price(self): from erpnext.stock.doctype.item.test_item import make_item make_item("_Test Item for Auto Price List", {"is_stock_item": 0}) frappe.db.set_value("Stock Settings", None, "auto_insert_price_list_rate_if_missing", 1) item_price = frappe.db.get_value("Item Price", {"price_list": "_Test Price List", "item_code": "_Test Item for Auto Price List"}) if item_price: frappe.delete_doc("Item Price", item_price) make_sales_order(item_code = "_Test Item for Auto Price List", selling_price_list="_Test Price List", rate=100) self.assertEquals(frappe.db.get_value("Item Price", {"price_list": "_Test Price List", "item_code": "_Test Item for Auto Price List"}, "price_list_rate"), 100) # do not update price list frappe.db.set_value("Stock Settings", None, "auto_insert_price_list_rate_if_missing", 0) item_price = frappe.db.get_value("Item Price", {"price_list": "_Test Price List", "item_code": "_Test Item for Auto Price List"}) if item_price: frappe.delete_doc("Item Price", item_price) make_sales_order(item_code = "_Test Item for Auto Price List", selling_price_list="_Test Price List", rate=100) self.assertEquals(frappe.db.get_value("Item Price", {"price_list": "_Test Price List", "item_code": "_Test Item for Auto Price List"}, "price_list_rate"), None) frappe.db.set_value("Stock Settings", None, "auto_insert_price_list_rate_if_missing", 1)
def unzip(self): """Unzip current file and replace it by its children""" if not ".zip" in self.file_name: frappe.msgprint(_("Not a zip file")) return zip_path = frappe.get_site_path(self.file_url.strip("/")) base_url = os.path.dirname(self.file_url) with zipfile.ZipFile(zip_path) as zf: zf.extractall(os.path.dirname(zip_path)) for info in zf.infolist(): if not info.filename.startswith("__MACOSX"): file_url = file_url = base_url + "/" + info.filename file_name = frappe.db.get_value("File", dict(file_url=file_url)) if file_name: file_doc = frappe.get_doc("File", file_name) else: file_doc = frappe.new_doc("File") file_doc.file_name = info.filename file_doc.file_size = info.file_size file_doc.folder = self.folder file_doc.is_private = self.is_private file_doc.file_url = file_url file_doc.attached_to_doctype = self.attached_to_doctype file_doc.attached_to_name = self.attached_to_name file_doc.save() frappe.delete_doc("File", self.name)
def setup_charts(delete_existing=True): frappe.local.flags.allow_unverified_charts = True # delete if delete_existing: for company in frappe.get_all("Company"): if company.name not in ("Wind Power LLC", "Test Company"): print "deleting {0}".format(company.name) frappe.delete_doc("Company", company.name) frappe.db.commit() print "-"*40 for country in frappe.get_all("Country", fields=["name", "code"]): charts = get_charts_for_country(country.name) for i, chart in enumerate(charts): if (chart != "Standard" or country.name == "United States"): if not frappe.db.exists("Company", chart): print chart.encode('utf-8') company = frappe.new_doc("Company") company.company_name = chart company.country = country.name company.chart_of_accounts = chart company.abbr = country.code + str(i+1) company.default_currency = "USD" company.insert() frappe.db.commit()
def sync_tasks(self): """sync tasks and remove table""" if self.flags.dont_sync_tasks: return task_names = [] for t in self.tasks: if t.task_id: task = frappe.get_doc("Task", t.task_id) else: task = frappe.new_doc("Task") task.project = self.name task.update({ "subject": t.title, "status": t.status, "exp_start_date": t.start_date, "exp_end_date": t.end_date, "description": t.description, "task_weight": t.task_weight }) task.flags.ignore_links = True task.flags.from_project = True task.flags.ignore_feed = True task.save(ignore_permissions = True) task_names.append(task.name) # delete for t in frappe.get_all("Task", ["name"], {"project": self.name, "name": ("not in", task_names)}): frappe.delete_doc("Task", t.name) self.update_percent_complete() self.update_costing()
def execute(): frappe.reload_doc("core", "doctype", "docperm") frappe.reload_doc("core", "doctype", "docshare") frappe.reload_doc('email', 'doctype', 'email_account') # default share to all writes frappe.db.sql("""update tabDocPerm set `share`=1 where ifnull(`write`,0)=1 and ifnull(`permlevel`,0)=0""") # every user must have access to his / her own detail users = frappe.get_all("User", filters={"user_type": "System User"}) usernames = [user.name for user in users] for user in usernames: frappe.share.add("User", user, user, share=1) # move event user to shared if frappe.db.exists("DocType", "Event User"): for event in frappe.get_all("Event User", fields=["parent", "person"]): if event.person in usernames: if not frappe.db.exists("Event", event.parent): frappe.db.sql("delete from `tabEvent User` where parent = %s",event.parent) else: frappe.share.add("Event", event.parent, event.person, write=1) frappe.delete_doc("DocType", "Event User") # move note user to shared if frappe.db.exists("DocType", "Note User"): for note in frappe.get_all("Note User", fields=["parent", "user", "permission"]): perm = {"read": 1} if note.permission=="Read" else {"write": 1} if note.user in usernames: frappe.share.add("Note", note.parent, note.user, **perm) frappe.delete_doc("DocType", "Note User")
def import_doc(docdict, force=False, data_import=False, pre_process=None): frappe.flags.in_import = True docdict["__islocal"] = 1 doc = frappe.get_doc(docdict) if pre_process: pre_process(doc) ignore = [] if frappe.db.exists(doc.doctype, doc.name): old_doc = frappe.get_doc(doc.doctype, doc.name) if doc.doctype in ignore_values and not force: # update ignore values for key in ignore_values.get(doc.doctype) or []: doc.set(key, old_doc.get(key)) # update ignored docs into new doc for df in doc.meta.get_table_fields(): if df.options in ignore_doctypes and not force: doc.set(df.fieldname, []) ignore.append(df.options) # delete old frappe.delete_doc(doc.doctype, doc.name, force=1, ignore_doctypes=ignore, for_reload=True) doc.flags.ignore_children_type = ignore doc.flags.ignore_links = True if not data_import: doc.flags.ignore_validate = True doc.flags.ignore_permissions = True doc.flags.ignore_mandatory = True doc.insert() frappe.flags.in_import = False
def test_time_log_batch(self): delete_time_log_and_batch() time_log = create_time_log() tlb = create_time_log_batch(time_log) tlb = frappe.get_doc("Time Log Batch", tlb.name) tlb.submit() si = frappe.get_doc(frappe.copy_doc(test_records[0])) si.get("entries")[0].time_log_batch = tlb.name si.insert() si.submit() self.assertEquals(frappe.db.get_value("Time Log Batch", tlb.name, "status"), "Billed") self.assertEquals(frappe.db.get_value("Time Log", time_log, "status"), "Billed") si.cancel() self.assertEquals(frappe.db.get_value("Time Log Batch", tlb.name, "status"), "Submitted") self.assertEquals(frappe.db.get_value("Time Log", time_log, "status"), "Batched for Billing") frappe.delete_doc("Sales Invoice", si.name) delete_time_log_and_batch()
def delete_supplier_contact(self): for contact in frappe.db.sql_list( """select name from `tabContact` where supplier=%s""", self.name, ): frappe.delete_doc("Contact", contact)
def on_trash(self): # remove template refernce from item and disable item if(self.item): try: frappe.delete_doc("Item",self.item, force=True) except Exception: frappe.throw(_("""Not permitted. Please disable the Test Template"""))
def delete_task(self): if not self.get('deleted_task_list'): return for d in self.get('deleted_task_list'): frappe.delete_doc("Task", d) self.deleted_task_list = []
def on_packing_slip_cancel(doc, method): # delete the packing slip details entry from delivery note delivery_note = doc.delivery_note dn = frappe.get_doc("Delivery Note", delivery_note) if dn.docstatus == 1: frappe.throw("Packing Slip is Linked with Submitted Delivery Note : %s"%dn.name) elif dn.docstatus == 0: if dn.dn_status not in ["Draft","Packing Slips Created","Partialy Packed"]: frappe.throw("Delivery Note is in Freezed state can not cancel the Packing Slip") else: to_remove = [] for ps in dn.packing_slip_details: if ps.packing_slip == doc.name: to_remove.append(ps) if to_remove: [dn.remove(ch) for ch in to_remove] if not dn.packing_slip_details: dn.dn_status = "Draft" dn.not_packed_items = json.dumps({}) else: dn.dn_status = "Partialy Packed" not_packed_items = json.loads(dn.not_packed_items) for item in doc.bin_items: qty = not_packed_items.get(item.item_code) + 1 if not_packed_items.get(item.item_code) else 1 not_packed_items.update({ item.item_code: qty }) dn.not_packed_items = json.dumps(not_packed_items) dn.save(ignore_permissions = True) frappe.delete_doc("Packing Slip",doc.name, ignore_permissions=True)
def remove_app(app_name, dry_run=False): """Delete app and all linked to the app's module with the app.""" if not dry_run: confirm = raw_input("All doctypes (including custom), modules related to this app will be deleted. Are you sure you want to continue (y/n) ? ") if confirm!="y": return from frappe.utils.backups import scheduled_backup print "Backing up..." scheduled_backup(ignore_files=True) # remove modules, doctypes, roles for module_name in frappe.get_module_list(app_name): for doctype in frappe.get_list("DocType", filters={"module": module_name}, fields=["name", "issingle"]): print "removing {0}...".format(doctype.name) # drop table if not dry_run: if not doctype.issingle: frappe.db.sql("drop table `tab{0}`".format(doctype.name)) frappe.delete_doc("DocType", doctype.name) print "removing Module {0}...".format(module_name) if not dry_run: frappe.delete_doc("Module Def", module_name) remove_from_installed_apps(app_name)
def setup_charts(): frappe.local.flags.allow_unverified_charts = True # delete for company in frappe.get_all("Company"): if company.name != "Wind Power LLC": print "deleting {0}".format(company.name) frappe.delete_doc("Company", company.name) frappe.db.commit() for country in frappe.get_all("Country", fields=["name", "code"]): if country.name in countries: print "creating for {0}".format(country.name) charts = get_charts_for_country(country.name) for i, chart in enumerate(charts): company = frappe.new_doc("Company") company.company_name = "{0} - {1}".format(country.name, chart) company.country = country.name company.chart_of_accounts = chart company.abbr = country.code + str(i) company.default_currency = "USD" company.insert() frappe.db.commit()
def test_asset_sale(self): frappe.get_doc("Asset", "Macbook Pro 1").submit() post_depreciation_entries(date="2021-01-01") si = make_sales_invoice(asset="Macbook Pro 1", item_code="Macbook Pro", company="_Test Company") si.customer = "_Test Customer" si.due_date = nowdate() si.get("items")[0].rate = 25000 si.insert() si.submit() self.assertEqual(frappe.db.get_value("Asset", "Macbook Pro 1", "status"), "Sold") expected_gle = ( ("_Test Accumulated Depreciations - _TC", 30000.0, 0.0), ("_Test Fixed Asset - _TC", 0.0, 100000.0), ("_Test Gain/Loss on Asset Disposal - _TC", 45000.0, 0.0), ("Debtors - _TC", 25000.0, 0.0) ) gle = frappe.db.sql("""select account, debit, credit from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no = %s order by account""", si.name) self.assertEqual(gle, expected_gle) si.cancel() frappe.delete_doc("Sales Invoice", si.name) self.assertEqual(frappe.db.get_value("Asset", "Macbook Pro 1", "status"), "Partially Depreciated")
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")
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")
def execute(): frappe.reload_doctype("Email Digest") frappe.db.sql("""update `tabEmail Digest` set expense_year_to_date = income_year_to_date""") if frappe.db.exists("Email Digest", "Scheduler Errors"): frappe.delete_doc("Email Digest", "Scheduler Errors")
def insert_web_page(self, route, fpath, page_name, priority, parent_website_route): page = frappe.get_doc({ "doctype":"Web Page", "idx": priority, "page_name": page_name, "published": 1, "parent_website_route": parent_website_route }) page.update(get_static_content(fpath, page_name, route)) try: page.insert() except frappe.NameError: # page exists, if deleted static, delete it and try again old_route = frappe.get_doc("Website Route", {"ref_doctype":"Web Page", "docname": page.name}) if old_route.static_file_timestamp and not os.path.exists(os.path.join(self.statics_path, old_route.name)): frappe.delete_doc("Web Page", page.name) page.insert() # retry # update timestamp route_doc = frappe.get_doc("Website Route", {"ref_doctype": "Web Page", "docname": page.name}) route_doc.static_file_timestamp = cint(os.path.getmtime(fpath)) route_doc.save() self.updated += 1 print route_doc.name + " inserted" self.synced.append(route)
def delete_existing_property_setter(self, property, fieldname=None): # first delete existing property setter existing_property_setter = frappe.db.get_value("Property Setter", {"doc_type": self.doc_type, "property": property, "field_name['']": fieldname or ''}) if existing_property_setter: frappe.delete_doc("Property Setter", existing_property_setter)
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)
def execute(): # convert milestones to tasks frappe.reload_doctype("Project") frappe.reload_doc("projects", "doctype", "project_task") frappe.reload_doctype("Task") frappe.reload_doc("projects", "doctype", "task_depends_on") for m in frappe.get_all("Project Milestone", "*"): if (m.milestone and m.milestone_date and frappe.db.exists("Project", m.parent)): task = frappe.get_doc({ "doctype": "Task", "subject": m.milestone, "expected_start_date": m.milestone_date, "status": "Open" if m.status=="Pending" else "Closed", "project": m.parent, }) task.flags.ignore_mandatory = True task.insert(ignore_permissions=True) # remove project milestone frappe.delete_doc("DocType", "Project Milestone") # remove calendar events for milestone for e in frappe.get_all("Event", ["name"], {"ref_type": "Project"}): frappe.delete_doc("Event", e.name)
def on_trash(self): # delete bin bins = frappe.db.sql("select * from `tabBin` where warehouse = %s", self.name, as_dict=1) for d in bins: if ( d["actual_qty"] or d["reserved_qty"] or d["ordered_qty"] or d["indented_qty"] or d["projected_qty"] or d["planned_qty"] ): throw( _("Warehouse {0} can not be deleted as quantity exists for Item {1}").format( self.name, d["item_code"] ) ) else: frappe.db.sql("delete from `tabBin` where name = %s", d["name"]) warehouse_account = self.get_account(self.name) if warehouse_account: frappe.delete_doc("Account", warehouse_account) if self.check_if_sle_exists(): throw(_("Warehouse can not be deleted as stock ledger entry exists for this warehouse.")) if self.check_if_child_exists(): throw(_("Child warehouse exists for this warehouse. You can not delete this warehouse.")) self.update_nsm_model()
def set_property_setter_for_idx(self): dt_meta = frappe.get_meta(self.dt) self.validate_insert_after(dt_meta) _idx = [] existing_property_setter = frappe.db.get_value("Property Setter", {"doc_type": self.dt, "property": "_idx"}, ["name", "value"], as_dict=1) # if no existsing property setter, build based on meta if not existing_property_setter: for df in sorted(dt_meta.get("fields"), key=lambda x: x.idx): if df.fieldname != self.fieldname: _idx.append(df.fieldname) else: _idx = json.loads(existing_property_setter.value) # Delete existing property setter if field is not there if self.fieldname not in _idx: frappe.delete_doc("Property Setter", existing_property_setter.name) existing_property_setter = None # Create new peroperty setter if order changed if _idx and not existing_property_setter: field_idx = (_idx.index(self.insert_after) + 1) if (self.insert_after in _idx) else len(_idx) _idx.insert(field_idx, self.fieldname) frappe.make_property_setter({ "doctype":self.dt, "doctype_or_field": "DocType", "property": "_idx", "value": json.dumps(_idx), "property_type": "Text" }, validate_fields_for_doctype=False)
def execute(): frappe.reload_doctype("Web Form") frappe.delete_doc("Web Form", "Issues") frappe.delete_doc("Web Form", "Addresses") from erpnext.setup.install import add_web_forms add_web_forms()
def execute(): frappe.db.sql("""update `tabPrint Format` set disabled=1 where name='fatura_6' and module ='Angola ERPNext' """) frappe.delete_doc("DocType", "TestGRID")
def delete_job_card(self): for d in frappe.get_all("Job Card", ["name"], {"work_order": self.name}): frappe.delete_doc("Job Card", d.name)
def delete_ip_medication_order(encounter): record = frappe.db.exists('Inpatient Medication Order', {'patient_encounter': encounter.name}) if record: frappe.delete_doc('Inpatient Medication Order', record, force=1)
def delete_invoice(invoice): frappe.delete_doc("Sales Invoice", invoice, force=1) return "Inovice {0} Deleted".format(invoice)
def delete_test_data(self): for f in frappe.db.sql('''select name, file_name from tabFile where is_home_folder = 0 and is_attachments_folder = 0 order by creation desc'''): frappe.delete_doc("File", f[0])
def create_delete_custom_fields(self): if self.enable_sync: # create create_custom_field_id_and_check_status = False create_custom_field_email_check = False names = ["Customer-woocommerce_id","Sales Order-woocommerce_id","Item-woocommerce_id","Address-woocommerce_id"] names_check_box = ["Customer-woocommerce_check","Sales Order-woocommerce_check","Item-woocommerce_check","Address-woocommerce_check"] email_names = ["Customer-woocommerce_email","Address-woocommerce_email"] for i in zip(names,names_check_box): if not frappe.get_value("Custom Field",{"name":i[0]}) or not frappe.get_value("Custom Field",{"name":i[1]}): create_custom_field_id_and_check_status = True break if create_custom_field_id_and_check_status: names = ["Customer","Sales Order","Item","Address"] for name in names: custom = frappe.new_doc("Custom Field") custom.dt = name custom.label = "woocommerce_id" custom.read_only = 1 custom.save() custom = frappe.new_doc("Custom Field") custom.dt = name custom.label = "woocommerce_check" custom.fieldtype = "Check" custom.read_only = 1 custom.save() for i in email_names: if not frappe.get_value("Custom Field",{"name":i}): create_custom_field_email_check = True break; if create_custom_field_email_check: names = ["Customer","Address"] for name in names: custom = frappe.new_doc("Custom Field") custom.dt = name custom.label = "woocommerce_email" custom.read_only = 1 custom.save() if not frappe.get_value("Item Group",{"name": "WooCommerce Products"}): item_group = frappe.new_doc("Item Group") item_group.item_group_name = "WooCommerce Products" item_group.parent_item_group = _("All Item Groups") item_group.save() elif not self.enable_sync: # delete names = ["Customer-woocommerce_id","Sales Order-woocommerce_id","Item-woocommerce_id","Address-woocommerce_id"] names_check_box = ["Customer-woocommerce_check","Sales Order-woocommerce_check","Item-woocommerce_check","Address-woocommerce_check"] email_names = ["Customer-woocommerce_email","Address-woocommerce_email"] for name in names: frappe.delete_doc("Custom Field",name) for name in names_check_box: frappe.delete_doc("Custom Field",name) for name in email_names: frappe.delete_doc("Custom Field",name) frappe.delete_doc("Item Group","WooCommerce Products") frappe.db.commit()
def tearDown(self): frappe.delete_doc("Custom Field", "User-test_custom_field") frappe.db.commit() frappe.clear_cache(doctype="User")
def delete_vital_signs_from_medical_record(doc): medical_record_id = frappe.db.sql("select name from `tabPatient Medical Record` where reference_name=%s",(doc.name)) if medical_record_id and medical_record_id[0][0]: frappe.delete_doc("Patient Medical Record", medical_record_id[0][0])
def tearDown(self): frappe.delete_doc('Cash Flow Mapping', 'Test Mapping')
def on_trash(self): for dev in self.devices: frappe.delete_doc("IOT Device Config", dev.device)
def clean_doc(doc_type, doc_id): for d in frappe.db.get_values("Wechat Send Doc", {"document_type": doc_type, "document_id": doc_id}, "name"): frappe.delete_doc("Wechat Send Doc", d[0])
def setUp(self): if frappe.db.exists("Cash Flow Mapping", "Test Mapping"): frappe.delete_doc('Cash Flow Mappping', 'Test Mapping')
def on_trash(self): if self.script_type == "Scheduler Event": for job in self.scheduled_jobs: frappe.delete_doc("Scheduled Job Type", job.name)
def clear_scheduled_events(self): """Deletes existing scheduled jobs by Server Script if self.event_frequency has changed""" if self.script_type == "Scheduler Event" and self.has_value_changed( "event_frequency"): for scheduled_job in self.scheduled_jobs: frappe.delete_doc("Scheduled Job Type", scheduled_job.name)
def test_db_keywords_as_fields(self): """Tests if DB keywords work as docfield names. If they're wrapped with grave accents.""" # Using random.choices, picked out a list of 40 keywords for testing all_keywords = { "mariadb": [ "CHARACTER", "DELAYED", "LINES", "EXISTS", "YEAR_MONTH", "LOCALTIME", "BOTH", "MEDIUMINT", "LEFT", "BINARY", "DEFAULT", "KILL", "WRITE", "SQL_SMALL_RESULT", "CURRENT_TIME", "CROSS", "INHERITS", "SELECT", "TABLE", "ALTER", "CURRENT_TIMESTAMP", "XOR", "CASE", "ALL", "WHERE", "INT", "TO", "SOME", "DAY_MINUTE", "ERRORS", "OPTIMIZE", "REPLACE", "HIGH_PRIORITY", "VARBINARY", "HELP", "IS", "CHAR", "DESCRIBE", "KEY", ], "postgres": [ "WORK", "LANCOMPILER", "REAL", "HAVING", "REPEATABLE", "DATA", "USING", "BIT", "DEALLOCATE", "SERIALIZABLE", "CURSOR", "INHERITS", "ARRAY", "TRUE", "IGNORE", "PARAMETER_MODE", "ROW", "CHECKPOINT", "SHOW", "BY", "SIZE", "SCALE", "UNENCRYPTED", "WITH", "AND", "CONVERT", "FIRST", "SCOPE", "WRITE", "INTERVAL", "CHARACTER_SET_SCHEMA", "ADD", "SCROLL", "NULL", "WHEN", "TRANSACTION_ACTIVE", "INT", "FORTRAN", "STABLE", ], } created_docs = [] # edit by rushabh: added [:1] # don't run every keyword! - if one works, they all do fields = all_keywords[frappe.conf.db_type][:1] test_doctype = "ToDo" def add_custom_field(field): create_custom_field( test_doctype, { "fieldname": field.lower(), "label": field.title(), "fieldtype": "Data", }, ) # Create custom fields for test_doctype for field in fields: add_custom_field(field) # Create documents under that doctype and query them via ORM for _ in range(10): docfields = {key.lower(): random_string(10) for key in fields} doc = frappe.get_doc({ "doctype": test_doctype, "description": random_string(20), **docfields }) doc.insert() created_docs.append(doc.name) random_field = choice(fields).lower() random_doc = choice(created_docs) random_value = random_string(20) # Testing read self.assertEqual( list(frappe.get_all("ToDo", fields=[random_field], limit=1)[0])[0], random_field) self.assertEqual( list( frappe.get_all("ToDo", fields=[f"`{random_field}` as total"], limit=1)[0])[0], "total") # Testing read for distinct and sql functions self.assertEqual( list( frappe.get_all( "ToDo", fields=[f"`{random_field}` as total"], distinct=True, limit=1, )[0])[0], "total", ) self.assertEqual( list( frappe.get_all( "ToDo", fields=[f"`{random_field}`"], distinct=True, limit=1, )[0])[0], random_field, ) self.assertEqual( list( frappe.get_all("ToDo", fields=[f"count(`{random_field}`)"], limit=1)[0])[0], "count" if frappe.conf.db_type == "postgres" else f"count(`{random_field}`)", ) # Testing update frappe.db.set_value(test_doctype, random_doc, random_field, random_value) self.assertEqual( frappe.db.get_value(test_doctype, random_doc, random_field), random_value) # Cleanup - delete records and remove custom fields for doc in created_docs: frappe.delete_doc(test_doctype, doc) clear_custom_fields(test_doctype)
def delete_timesheet(self): for timesheet in frappe.get_all("Timesheet", ["name"], {"production_order": self.name}): frappe.delete_doc("Timesheet", timesheet.name)
def delete_supplier_contact(self): for contact in frappe.db.sql_list("""select name from `tabContact` where supplier=%s""", self.name): frappe.delete_doc("Contact", contact)
def rename_doc(doctype, old, new, force=False, merge=False, ignore_permissions=False, ignore_if_exists=False): """ Renames a doc(dt, old) to doc(dt, new) and updates all linked fields of type "Link" """ if not frappe.db.exists(doctype, old): return if ignore_if_exists and frappe.db.exists(doctype, new): return if old == new: frappe.msgprint(_('Please select a new name to rename')) return force = cint(force) merge = cint(merge) meta = frappe.get_meta(doctype) # call before_rename old_doc = frappe.get_doc(doctype, old) out = old_doc.run_method("before_rename", old, new, merge) or {} new = (out.get("new") or new) if isinstance(out, dict) else (out or new) if doctype != "DocType": new = validate_rename(doctype, new, meta, merge, force, ignore_permissions) if not merge: rename_parent_and_child(doctype, old, new, meta) # update link fields' values link_fields = get_link_fields(doctype) update_link_field_values(link_fields, old, new, doctype) rename_dynamic_links(doctype, old, new) # save the user settings in the db update_user_settings(old, new, link_fields) if doctype == 'DocType': rename_doctype(doctype, old, new, force) update_attachments(doctype, old, new) rename_versions(doctype, old, new) # call after_rename new_doc = frappe.get_doc(doctype, new) # copy any flags if required new_doc._local = getattr(old_doc, "_local", None) new_doc.run_method("after_rename", old, new, merge) if not merge: rename_password(doctype, old, new) # update user_permissions frappe.db.sql( """update tabDefaultValue set defvalue=%s where parenttype='User Permission' and defkey=%s and defvalue=%s""", (new, doctype, old)) if merge: new_doc.add_comment( 'Edit', _("merged {0} into {1}").format(frappe.bold(old), frappe.bold(new))) else: new_doc.add_comment( 'Edit', _("renamed from {0} to {1}").format(frappe.bold(old), frappe.bold(new))) if merge: frappe.delete_doc(doctype, old) frappe.clear_cache() frappe.enqueue('frappe.utils.global_search.rebuild_for_doctype', doctype=doctype) return new
def delete_custom_role(field, docname): name = frappe.db.get_value('Custom Role', {field: docname}, "name") if name: frappe.delete_doc('Custom Role', name)
def handle(): """ Handler for `/api` methods ### Examples: `/api/method/{methodname}` will call a whitelisted method `/api/resource/{doctype}` will query a table examples: - `?fields=["name", "owner"]` - `?filters=[["Task", "name", "like", "%005"]]` - `?limit_start=0` - `?limit_page_length=20` `/api/resource/{doctype}/{name}` will point to a resource `GET` will return doclist `POST` will insert `PUT` will update `DELETE` will delete `/api/resource/{doctype}/{name}?run_method={method}` will run a whitelisted controller method """ validate_oauth() validate_auth_via_api_keys() parts = frappe.request.path[1:].split("/", 3) call = doctype = name = None if len(parts) > 1: call = parts[1] if len(parts) > 2: doctype = parts[2] if len(parts) > 3: name = parts[3] if call == "method": frappe.local.form_dict.cmd = doctype return frappe.handler.handle() elif call == "resource": if "run_method" in frappe.local.form_dict: method = frappe.local.form_dict.pop("run_method") doc = frappe.get_doc(doctype, name) doc.is_whitelisted(method) if frappe.local.request.method == "GET": if not doc.has_permission("read"): frappe.throw(_("Not permitted"), frappe.PermissionError) frappe.local.response.update( {"data": doc.run_method(method, **frappe.local.form_dict)}) if frappe.local.request.method == "POST": if not doc.has_permission("write"): frappe.throw(_("Not permitted"), frappe.PermissionError) frappe.local.response.update( {"data": doc.run_method(method, **frappe.local.form_dict)}) frappe.db.commit() else: if name: if frappe.local.request.method == "GET": doc = frappe.get_doc(doctype, name) if not doc.has_permission("read"): raise frappe.PermissionError frappe.local.response.update({"data": doc}) if frappe.local.request.method == "PUT": data = json.loads(frappe.local.form_dict.data) doc = frappe.get_doc(doctype, name) if "flags" in data: del data["flags"] # Not checking permissions here because it's checked in doc.save doc.update(data) frappe.local.response.update( {"data": doc.save().as_dict()}) frappe.db.commit() if frappe.local.request.method == "DELETE": # Not checking permissions here because it's checked in delete_doc frappe.delete_doc(doctype, name, ignore_missing=False) frappe.local.response.http_status_code = 202 frappe.local.response.message = "ok" frappe.db.commit() elif doctype: if frappe.local.request.method == "GET": if frappe.local.form_dict.get('fields'): frappe.local.form_dict['fields'] = json.loads( frappe.local.form_dict['fields']) frappe.local.form_dict.setdefault('limit_page_length', 20) frappe.local.response.update({ "data": frappe.call(frappe.client.get_list, doctype, **frappe.local.form_dict) }) if frappe.local.request.method == "POST": if frappe.local.form_dict.data is None: data = json.loads(frappe.local.request.get_data()) else: data = json.loads(frappe.local.form_dict.data) data.update({"doctype": doctype}) frappe.local.response.update( {"data": frappe.get_doc(data).insert().as_dict()}) frappe.db.commit() else: raise frappe.DoesNotExistError else: raise frappe.DoesNotExistError return build_response("json")
def pre_process(events): if events["status"] == "cancelled": if frappe.db.exists("Event", dict(gcalendar_sync_id=events["id"])): e = frappe.get_doc("Event", dict(gcalendar_sync_id=events["id"])) frappe.delete_doc("Event", e.name) return {} elif events["status"] == "confirmed": if 'date' in events["start"]: datevar = 'date' start_dt = parse(events["start"]['date']) end_dt = parse(events["end"]['date']) elif 'dateTime' in events["start"]: datevar = 'dateTime' start_dt = parse(events["start"]['dateTime']) end_dt = parse(events["end"]['dateTime']) if start_dt.tzinfo is None or start_dt.tzinfo.utcoffset( start_dt) is None: if "timeZone" in events["start"]: event_tz = events["start"]["timeZone"] else: event_tz = events["calendar_tz"] start_dt = timezone(event_tz).localize(start_dt) if end_dt.tzinfo is None or end_dt.tzinfo.utcoffset(end_dt) is None: if "timeZone" in events["end"]: event_tz = events["end"]["timeZone"] else: event_tz = events["calendar_tz"] end_dt = timezone(event_tz).localize(end_dt) default_tz = frappe.db.get_value("System Settings", None, "time_zone") event = { 'id': events["id"], 'summary': events["summary"], 'start_datetime': start_dt.astimezone( timezone(default_tz)).strftime('%Y-%m-%d %H:%M:%S'), 'end_datetime': end_dt.astimezone( timezone(default_tz)).strftime('%Y-%m-%d %H:%M:%S'), 'account': events['account'] } if "recurrence" in events: recurrence = get_recurrence_event_fields_value( events['recurrence'][0], events["start"][datevar]) event.update(recurrence) if 'description' in events: event.update({'description': events["description"]}) else: event.update({'description': ""}) if datevar == 'date': event.update({'all_day': 1}) return event
def execute(): if frappe.db.exists("Custom Field", "Stock Entry-qty"): frappe.delete_doc("Custom Field", "Stock Entry-qty", force=True) if 'qty' in frappe.db.get_table_columns("Stock Entry"): frappe.db.sql_ddl("alter table `tabStock Entry` drop column qty")
def on_trash(self): for d in frappe.get_all("Newsletter List Subscriber", "name", {"newsletter_list": self.name}): frappe.delete_doc("Newsletter List Subscriber", d.name)
def delete_variant(variant_code): frappe.delete_doc("Item", variant_code)
def on_cancel(self): frappe.delete_doc( "Salary Slip", frappe.db.sql_list( """select name from `tabSalary Slip` where payroll_entry=%s """, (self.name)))
def execute(): # Update Social Logins in User run_patch() # Create Social Login Key(s) from Social Login Keys frappe.reload_doc("integrations", "doctype", "social_login_key", force=True) if not frappe.db.exists('DocType', 'Social Login Keys'): return social_login_keys = frappe.get_doc("Social Login Keys", "Social Login Keys") if social_login_keys.get("facebook_client_id") or social_login_keys.get( "facebook_client_secret"): facebook_login_key = frappe.new_doc("Social Login Key") facebook_login_key.get_social_login_provider("Facebook", initialize=True) facebook_login_key.social_login_provider = "Facebook" facebook_login_key.client_id = social_login_keys.get( "facebook_client_id") facebook_login_key.client_secret = social_login_keys.get( "facebook_client_secret") if not (facebook_login_key.client_secret and facebook_login_key.client_id): facebook_login_key.enable_social_login = 0 facebook_login_key.save() if social_login_keys.get("frappe_server_url"): frappe_login_key = frappe.new_doc("Social Login Key") frappe_login_key.get_social_login_provider("Frappe", initialize=True) frappe_login_key.social_login_provider = "Frappe" frappe_login_key.base_url = social_login_keys.get("frappe_server_url") frappe_login_key.client_id = social_login_keys.get("frappe_client_id") frappe_login_key.client_secret = social_login_keys.get( "frappe_client_secret") if not (frappe_login_key.client_secret and frappe_login_key.client_id and frappe_login_key.base_url): frappe_login_key.enable_social_login = 0 frappe_login_key.save() if social_login_keys.get("github_client_id") or social_login_keys.get( "github_client_secret"): github_login_key = frappe.new_doc("Social Login Key") github_login_key.get_social_login_provider("GitHub", initialize=True) github_login_key.social_login_provider = "GitHub" github_login_key.client_id = social_login_keys.get("github_client_id") github_login_key.client_secret = social_login_keys.get( "github_client_secret") if not (github_login_key.client_secret and github_login_key.client_id): github_login_key.enable_social_login = 0 github_login_key.save() if social_login_keys.get("google_client_id") or social_login_keys.get( "google_client_secret"): google_login_key = frappe.new_doc("Social Login Key") google_login_key.get_social_login_provider("Google", initialize=True) google_login_key.social_login_provider = "Google" google_login_key.client_id = social_login_keys.get("google_client_id") google_login_key.client_secret = social_login_keys.get( "google_client_secret") if not (google_login_key.client_secret and google_login_key.client_id): google_login_key.enable_social_login = 0 google_login_key.save() frappe.delete_doc("DocType", "Social Login Keys")
def rename_doc(doctype, old, new, force=False, merge=False, ignore_permissions=False): """ Renames a doc(dt, old) to doc(dt, new) and updates all linked fields of type "Link" """ if not frappe.db.exists(doctype, old): return force = cint(force) merge = cint(merge) meta = frappe.get_meta(doctype) # call before_rename old_doc = frappe.get_doc(doctype, old) out = old_doc.run_method("before_rename", old, new, merge) or {} new = (out.get("new") or new) if isinstance(out, dict) else (out or new) if doctype != "DocType": new = validate_rename(doctype, new, meta, merge, force, ignore_permissions) if not merge: rename_parent_and_child(doctype, old, new, meta) # update link fields' values link_fields = get_link_fields(doctype) update_link_field_values(link_fields, old, new, doctype) rename_dynamic_links(doctype, old, new) if doctype == 'DocType': rename_doctype(doctype, old, new, force) update_comments(doctype, old, new, force) update_attachments(doctype, old, new) if merge: frappe.delete_doc(doctype, old) # call after_rename new_doc = frappe.get_doc(doctype, new) # copy any flags if required new_doc._local = getattr(old_doc, "_local", None) new_doc.run_method("after_rename", old, new, merge) rename_versions(doctype, old, new) # update user_permissions frappe.db.sql( """update tabDefaultValue set defvalue=%s where parenttype='User Permission' and defkey=%s and defvalue=%s""", (new, doctype, old)) frappe.clear_cache() return new
def setUp(self): frappe.delete_doc('Email Account', 'Test Email Account Password') frappe.delete_doc('Email Account', 'Test Email Account Password-new')
def remove(doctype, name, user, flags=None): share_name = frappe.db.get_value("DocShare", {"user": user, "share_name": name, "share_doctype": doctype}) if share_name: frappe.delete_doc("DocShare", share_name)
def delete_draft_work_order(self): for d in frappe.get_all('Work Order', fields = ["name"], filters = {'docstatus': 0, 'production_plan': ("=", self.name)}): frappe.delete_doc('Work Order', d.name)