def execute():
	frappe.reload_doc('custom', 'doctype', 'custom_field', force=True)

	try:
		frappe.db.sql('update `tabCustom Field` set in_standard_filter = in_filter_dash')
	except Exception, e:
		if e.args[0]!=1054: raise e
Esempio n. 2
0
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 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():
	frappe.reload_doc("education", "doctype", "student_attendance")
	frappe.db.sql('''
		update `tabStudent Attendance` set
			docstatus=0
		where
			docstatus=1''')
def execute():
	'''

	Fields to move from the item to item defaults child table
	[ default_warehouse, buying_cost_center, expense_account, selling_cost_center, income_account ]

	'''
	if not frappe.db.has_column('Item', 'default_warehouse'):
		return

	frappe.reload_doc('stock', 'doctype', 'item_default')
	frappe.reload_doc('stock', 'doctype', 'item')

	if frappe.db.a_row_exists('Item Default'): return

	companies = frappe.get_all("Company")
	if len(companies) == 1:
		try:
			frappe.db.sql('''
					INSERT INTO `tabItem Default`
						(name, parent, parenttype, parentfield, idx, company, default_warehouse,
						buying_cost_center, selling_cost_center, expense_account, income_account, default_supplier)
					SELECT
						SUBSTRING(SHA2(name,224), 1, 10) as name, name as parent, 'Item' as parenttype,
						'item_defaults' as parentfield, 1 as idx, %s as company, default_warehouse,
						buying_cost_center, selling_cost_center, expense_account, income_account, default_supplier
					FROM `tabItem`;
			''', companies[0].name)
		except:
			pass
	else:
		item_details = frappe.get_all("Item", fields=["name", "default_warehouse", "buying_cost_center",
									"expense_account", "selling_cost_center", "income_account"], limit=100)

		for item in item_details:
			item_defaults = []

			def insert_into_item_defaults(doc_field_name, doc_field_value, company):
				for d in item_defaults:
					if d.get("company") == company:
						d[doc_field_name] = doc_field_value
						return
				item_defaults.append({
					"company": company,
					doc_field_name: doc_field_value
				})

			for d in [
						["default_warehouse", "Warehouse"], ["expense_account", "Account"], ["income_account", "Account"],
						["buying_cost_center", "Cost Center"], ["selling_cost_center", "Cost Center"]
					]:
				if item.get(d[0]):
					company = frappe.get_value(d[1], item.get(d[0]), "company", cache=True)
					insert_into_item_defaults(d[0], item.get(d[0]), company)

			doc = frappe.get_doc("Item", item.name)
			doc.extend("item_defaults", item_defaults)

			for child_doc in doc.item_defaults:
				child_doc.db_insert()
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_doc("email", "doctype", "email_template")

	if not frappe.db.exists("Email Template", _('Leave Approval Notification')):
		base_path = frappe.get_app_path("erpnext", "hr", "doctype")
		response = frappe.read_file(os.path.join(base_path, "leave_application/leave_application_email_template.html"))
		frappe.get_doc({
			'doctype': 'Email Template',
			'name': _("Leave Approval Notification"),
			'response': response,
			'subject': _("Leave Approval Notification"),
			'owner': frappe.session.user,
		}).insert(ignore_permissions=True)


	if not frappe.db.exists("Email Template", _('Leave Status Notification')):
		base_path = frappe.get_app_path("erpnext", "hr", "doctype")
		response = frappe.read_file(os.path.join(base_path, "leave_application/leave_application_email_template.html"))
		frappe.get_doc({
			'doctype': 'Email Template',
			'name': _("Leave Status Notification"),
			'response': response,
			'subject': _("Leave Status Notification"),
			'owner': frappe.session.user,
		}).insert(ignore_permissions=True)
def execute():
	frappe.reload_doc('website', 'doctype', 'style_settings')
	style_settings = frappe.get_doc("Style Settings", "Style Settings")
	if not style_settings.apply_style:
		style_settings.update(default_properties)
		style_settings.apply_style = 1
		style_settings.save()
def execute():
	frappe.reload_doc("erpnext_integrations", "doctype","woocommerce_settings")
	doc = frappe.get_doc("Woocommerce Settings")

	if cint(doc.enable_sync):
		doc.creation_user = doc.modified_by
		doc.save(ignore_permissions=True)
def execute():
	"""
	Patch Reference:
		1. check whether warehouse is associated to company or not
		2. if warehouse is associated with company
			a. create warehouse group for company
			b. set warehouse group as parent to other warehouses and set is_group as 0
		3. if warehouses is not associated with company
			a. get distinct companies from stock ledger entries
			b. if sle have only company,
				i. set default company to all warehouse
				ii. repeat 2.a and 2.b
			c. if have multiple companies,
				i. create group warehouse without company
				ii. repeat 2.b
	"""
	
	frappe.reload_doc("stock", "doctype", "warehouse")

	if check_is_warehouse_associated_with_company():
		for company in frappe.get_all("Company", fields=["name", "abbr"]):
			make_warehouse_nestedset(company)
	else:
		sle_against_companies = frappe.db.sql_list("""select distinct company from `tabStock Ledger Entry`""")

		if len(sle_against_companies) == 1:
			company = frappe.get_cached_value('Company',  sle_against_companies[0],  
				fieldname=["name", "abbr"], as_dict=1)
			set_company_to_warehouse(company.name)
			make_warehouse_nestedset(company)

		elif len(sle_against_companies) > 1:
			make_warehouse_nestedset()
def execute():
	# 'Schools' module changed to the 'Education'
	# frappe.reload_doc('schools', 'doctype', 'Student Admission Program')
	# frappe.reload_doc('schools', 'doctype', 'student_admission')
	frappe.reload_doc('education', 'doctype', 'Student Admission Program')
	frappe.reload_doc('education', 'doctype', 'student_admission')

	if "program" not in frappe.db.get_table_columns("Student Admission"):
		return

	student_admissions = frappe.get_all("Student Admission", fields=["name", "application_fee", \
		"naming_series_for_student_applicant", "program", "introduction", "eligibility"])
	for student_admission in student_admissions:
		doc = frappe.get_doc("Student Admission", student_admission.name)
		doc.append("program_details", {
			"program": student_admission.get("program"),
			"application_fee": student_admission.get("application_fee"),
			"applicant_naming_series": student_admission.get("naming_series_for_student_applicant"),
		})
		if student_admission.eligibility and student_admission.introduction:
			doc.introduction = student_admission.introduction + "<br><div>" + \
				student_admission.eligibility + "</div>"
		doc.flags.ignore_validate = True
		doc.flags.ignore_mandatory = True
		doc.save()
def execute():
	frappe.reload_doc('projects', 'doctype', 'timesheet')
	if not frappe.db.table_exists("Time Log"):
		return

	for data in frappe.db.sql("select * from `tabTime Log` where docstatus < 2", as_dict=1):
		if data.task:
			company = frappe.db.get_value("Task", data.task, "company")
		elif data.production_order:
			company = frappe.db.get_value("Prodction Order", data.production_order, "company")
		else:
			company = frappe.db.get_single_value('Global Defaults', 'default_company')
		
		time_sheet = make_timesheet(data.production_order)
		args = get_timelog_data(data)
		add_timesheet_detail(time_sheet, args)
		time_sheet.employee = data.employee
		time_sheet.note = data.note
		time_sheet.company = company

		time_sheet.set_status()
		time_sheet.set_dates()
		time_sheet.update_cost()
		time_sheet.calculate_total_amounts()
		time_sheet.flags.ignore_validate = True
		time_sheet.save(ignore_permissions=True)

		# To ignore validate_mandatory_fields function
		if data.docstatus == 1:
			time_sheet.db_set("docstatus", 1)
			for d in time_sheet.get("time_logs"):
				d.db_set("docstatus", 1)
			time_sheet.update_production_order(time_sheet.name)
			time_sheet.update_task_and_project()
def execute():
	""" Set the Serial Numbers in Sales Invoice Item from Delivery Note Item """

	frappe.reload_doc("stock", "doctype", "serial_no")

	frappe.db.sql(""" update `tabSales Invoice Item` sii inner join 
		`tabDelivery Note Item` dni on sii.dn_detail=dni.name and  sii.qty=dni.qty
		set sii.serial_no=dni.serial_no where sii.parent IN (select si.name 
			from `tabSales Invoice` si where si.update_stock=0 and si.docstatus=1)""")

	items = frappe.db.sql(""" select  sii.parent, sii.serial_no from  `tabSales Invoice Item` sii
		left join `tabSales Invoice` si on sii.parent=si.name
		where si.docstatus=1 and si.update_stock=0""", as_dict=True)

	for item in items:
		sales_invoice = item.get("parent", None)
		serial_nos = item.get("serial_no", "")

		if not sales_invoice or not serial_nos:
			continue

		serial_nos = ["'%s'"%frappe.db.escape(no) for no in serial_nos.split("\n")]

		frappe.db.sql("""
			UPDATE 
				`tabSerial No`
			SET 
				sales_invoice='{sales_invoice}'
			WHERE
				name in ({serial_nos})
			""".format(
				sales_invoice=frappe.db.escape(sales_invoice),
				serial_nos=",".join(serial_nos)
			)
		)
def execute():
	frappe.reload_doc("accounts", "doctype", "account")
	
	frappe.db.sql(""" update tabAccount set account_type = "Stock"
		where account_type = "Warehouse" """)
	
	frappe.db.commit()
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'""")
def execute():
	frappe.reload_doc("accounts", "doctype", "account")

	account_table_columns = frappe.db.get_table_columns("Account")
	if "debit_or_credit" in account_table_columns and "is_pl_account" in account_table_columns:
		frappe.db.sql("""UPDATE tabAccount
			SET root_type = CASE
				WHEN (debit_or_credit='Debit' and is_pl_account = 'No') THEN 'Asset'
				WHEN (debit_or_credit='Credit' and is_pl_account = 'No') THEN 'Liability'
				WHEN (debit_or_credit='Debit' and is_pl_account = 'Yes') THEN 'Expense'
				WHEN (debit_or_credit='Credit' and is_pl_account = 'Yes') THEN 'Income'
				END
			WHERE ifnull(parent_account, '') = ''
		""")

	else:
		for key, root_type in (("asset", "Asset"), ("liabilities", "Liability"), ("expense", "Expense"),
			("income", "Income")):
			frappe.db.sql("""update tabAccount set root_type=%s where name like %s
				and ifnull(parent_account, '')=''""", (root_type, "%" + key + "%"))

	for root in frappe.db.sql("""SELECT name, lft, rgt, root_type FROM `tabAccount`
		WHERE ifnull(parent_account, '')=''""",	as_dict=True):
			if root.root_type:
				frappe.db.sql("""UPDATE tabAccount SET root_type=%s WHERE lft>%s and rgt<%s""",
					(root.root_type, root.lft, root.rgt))
			else:
				print b"Root type not found for {0}".format(root.name.encode("utf-8"))
def execute():
	frappe.reload_doc('setup', 'doctype', 'party_type')
	party_types = {'Customer': 'Receivable', 'Supplier': 'Payable',
		'Employee': 'Payable', 'Member': 'Receivable', 'Shareholder': 'Payable', 'Student': 'Receivable'}

	for party_type, account_type in party_types.items():
		frappe.db.set_value('Party Type', party_type, 'account_type', account_type)
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 execute():
	frappe.reload_doc("accounts", "doctype", "pricing_rule")
	frappe.db.sql("""update `tabPricing Rule` set selling=1 where ifnull(applicable_for, '') in
		('', 'Customer', 'Customer Group', 'Territory', 'Sales Partner', 'Campaign')""")

	frappe.db.sql("""update `tabPricing Rule` set buying=1 where ifnull(applicable_for, '') in
		('', 'Supplier', 'Supplier Type')""")
Esempio n. 20
0
def execute():
	frappe.reload_doc("accounts", "doctype", "tax_rule")

	customers = frappe.db.sql("""select name, default_taxes_and_charges from tabCustomer where
		ifnull(default_taxes_and_charges, '') != '' """, as_dict=1)

	for d in customers:
		if not frappe.db.sql("select name from `tabTax Rule` where customer=%s", d.name):
			tr = frappe.new_doc("Tax Rule")
			tr.tax_type = "Sales"
			tr.customer = d.name
			tr.sales_tax_template = d.default_taxes_and_charges
			tr.save()


	suppliers = frappe.db.sql("""select name, default_taxes_and_charges from tabSupplier where
		ifnull(default_taxes_and_charges, '') != '' """, as_dict=1)

	for d in suppliers:
		if not frappe.db.sql("select name from `tabTax Rule` where supplier=%s", d.name):
			tr = frappe.new_doc("Tax Rule")
			tr.tax_type = "Purchase"
			tr.supplier = d.name
			tr.purchase_tax_template = d.default_taxes_and_charges
			tr.save()
def execute():
    frappe.reload_doc("accounts", "doctype", "journal_entry")

    frappe.db.sql(
        """ update `tabJournal Entry` set total_amount_currency = %s
		where ifnull(multi_currency, 0) = 0
		and (pay_to_recd_from is not null or pay_to_recd_from != "") """,
        get_default_currency(),
    )

    for je in frappe.db.sql(
        """ select name from `tabJournal Entry` where multi_currency = 1
		and (pay_to_recd_from is not null or pay_to_recd_from != "")""",
        as_dict=1,
    ):

        doc = frappe.get_doc("Journal Entry", je.name)
        for d in doc.get("accounts"):
            if d.party_type and d.party:
                total_amount_currency = d.account_currency

            elif frappe.db.get_value("Account", d.account, "account_type") in ["Bank", "Cash"]:
                total_amount_currency = d.account_currency

        frappe.db.set_value(
            "Journal Entry", je.name, "total_amount_currency", total_amount_currency, update_modified=False
        )
Esempio n. 22
0
def execute():
	frappe.reload_doc("Core", "DocType", "User")
	
	for user in frappe.db.get_all('User'):
		user = frappe.get_doc('User', user.name)
		user.set_full_name()
		user.db_set('full_name', user.full_name, update_modified = False)
def execute():
	frappe.reload_doc('desk', 'doctype', 'auto_repeat')

	doctypes_to_rename = {
		'accounts': ['Journal Entry', 'Payment Entry', 'Purchase Invoice', 'Sales Invoice'],
		'buying': ['Purchase Order', 'Supplier Quotation'],
		'selling': ['Quotation', 'Sales Order'],
		'stock': ['Delivery Note', 'Purchase Receipt']
	}

	for module, doctypes in doctypes_to_rename.items():
		for doctype in doctypes:
			frappe.reload_doc(module, 'doctype', frappe.scrub(doctype))

			if frappe.db.has_column(doctype, 'subscription'):
				rename_field(doctype, 'subscription', 'auto_repeat')

	subscriptions = frappe.db.sql('select * from `tabSubscription`', as_dict=1)

	for doc in subscriptions:
		doc['doctype'] = 'Auto Repeat'
		auto_repeat = frappe.get_doc(doc)
		auto_repeat.db_insert()

	frappe.db.sql('delete from `tabSubscription`')
	frappe.db.commit()
	drop_columns_from_subscription()
def execute():
	#Rename Grading Structure to Grading Scale
	frappe.rename_doc("DocType", "Grading Structure", "Grading Scale", force=True)
	frappe.rename_doc("DocType", "Grade Interval", "Grading Scale Interval", force=True)

	frappe.reload_doc("schools", "doctype", "grading_scale_interval")
	rename_field("Grading Scale Interval", "to_score", "threshold")

	frappe.rename_doc("DocType", "Assessment", "Assessment Plan", force=True)

	#Rename Assessment Results
	frappe.reload_doc("schools", "doctype", "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")


	for assessment in frappe.get_all("Assessment Plan", fields=["name", "grading_scale"], filters = [["docstatus", "!=", 2 ]]):
		print assessment
		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""")
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
def execute():
	frappe.reload_doc('accounts', 'doctype', 'sales_invoice')
	frappe.reload_doc('accounts', 'doctype', 'purchase_invoice')

	frappe.db.sql(""" 
		update 
			`tabPurchase Invoice` 
		set 
			status = (Case When outstanding_amount = 0 and docstatus = 1 and is_return = 0 then 'Paid'
			when due_date < CURDATE() and outstanding_amount > 0 and docstatus =1 then 'Overdue'
			when due_date >= CURDATE() and outstanding_amount > 0 and docstatus =1 then 'Unpaid'
			when outstanding_amount < 0 and docstatus =1 then 'Debit Note Issued'
			when is_return = 1 and docstatus =1 then 'Return'
			when docstatus = 2 then 'Cancelled'
			else 'Draft'
		End)""")

	frappe.db.sql(""" 
		update 
			`tabSales Invoice` 
		set status = (Case When outstanding_amount = 0 and docstatus = 1 and is_return = 0 then 'Paid'
			when due_date < CURDATE() and outstanding_amount > 0 and docstatus =1 then 'Overdue'
			when due_date >= CURDATE() and outstanding_amount > 0 and docstatus =1 then 'Unpaid'
			when outstanding_amount < 0 and docstatus =1 then 'Credit Note Issued'
			when is_return = 1 and docstatus =1 then 'Return'
			when docstatus = 2 then 'Cancelled'
			else 'Draft'
		End)""")
Esempio n. 27
0
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')
Esempio n. 28
0
def execute():
    frappe.reload_doc("email", "doctype", "email_group_member")
    if "newsletter_list" in frappe.db.get_table_columns("Email Group Member"):
        frappe.db.sql(
            """update `tabEmail Group Member` set email_group = newsletter_list 
			where email_group is null or email_group = ''"""
        )
def execute():
	'''
	Enable translatable in these fields
	- Customer Name
	- Supplier Name
	- Contact Name
	- Item Name/ Description
	- Address
	'''

	frappe.reload_doc('core', 'doctype', 'docfield')
	frappe.reload_doc('custom', 'doctype', 'custom_field')

	enable_for_fields = [
		['Customer', 'customer_name'],
		['Supplier', 'supplier_name'],
		['Contact', 'first_name'],
		['Contact', 'last_name'],
		['Item', 'item_name'],
		['Item', 'description'],
		['Address', 'address_line1'],
		['Address', 'address_line2'],
	]


	for f in enable_for_fields:
		frappe.get_doc({
			'doctype': 'Property Setter',
			'doc_type': f[0],
			'doctype_or_field': 'DocField',
			'field_name': f[1],
			'property': 'translatable',
			'propery_type': 'Check',
			'value': 1
		}).db_insert()
def execute():
	if frappe.db.table_exists("POS Profile User"):
		frappe.reload_doc('accounts', 'doctype', 'pos_profile_user')

		frappe.db.sql(""" update `tabPOS Profile User`,
			(select `tabPOS Profile User`.name from `tabPOS Profile User`, `tabPOS Profile`
				where `tabPOS Profile`.name = `tabPOS Profile User`.parent
				group by `tabPOS Profile User`.user, `tabPOS Profile`.company) as pfu
			set
				`tabPOS Profile User`.default = 1
			where `tabPOS Profile User`.name = pfu.name""")
	else:
		doctype = 'POS Profile'
		frappe.reload_doc('accounts', 'doctype', doctype)
		frappe.reload_doc('accounts', 'doctype', 'pos_profile_user')
		frappe.reload_doc('accounts', 'doctype', 'pos_item_group')
		frappe.reload_doc('accounts', 'doctype', 'pos_customer_group')

		for doc in frappe.get_all(doctype):
			_doc = frappe.get_doc(doctype, doc.name)
			user = frappe.db.get_value(doctype, doc.name, 'user')

			if not user: continue

			_doc.append('applicable_for_users', {
				'user': user,
				'default': 1
			})
			_doc.pos_profile_name = user + ' - ' + _doc.company
			_doc.flags.ignore_validate  = True
			_doc.flags.ignore_mandatory = True
			_doc.save()
Esempio n. 31
0
def execute():
	frappe.reload_doc('crm', 'doctype', 'sales_stage')

	frappe.local.lang = frappe.db.get_default("lang") or 'en'

	add_sale_stages()
Esempio n. 32
0
def execute():
	frappe.reload_doc('accounts', 'Print Format', 'POS Invoice')
Esempio n. 33
0
def execute():

	# Create a penalty account for loan types

	frappe.reload_doc('loan_management', 'doctype', 'loan_type')
	frappe.reload_doc('loan_management', 'doctype', 'loan')
	frappe.reload_doc('loan_management', 'doctype', 'repayment_schedule')
	frappe.reload_doc('loan_management', 'doctype', 'process_loan_interest_accrual')
	frappe.reload_doc('loan_management', 'doctype', 'loan_repayment')
	frappe.reload_doc('loan_management', 'doctype', 'loan_repayment_detail')
	frappe.reload_doc('loan_management', 'doctype', 'loan_interest_accrual')
	frappe.reload_doc('accounts', 'doctype', 'gl_entry')
	frappe.reload_doc('accounts', 'doctype', 'journal_entry_account')

	updated_loan_types = []
	loans_to_close = []

	# Update old loan status as closed
	if frappe.db.has_column('Repayment Schedule', 'paid'):
		loans_list = frappe.db.sql("""SELECT distinct parent from `tabRepayment Schedule`
			where paid = 0 and docstatus = 1""", as_dict=1)

		loans_to_close = [d.parent for d in loans_list]

	if loans_to_close:
		frappe.db.sql("UPDATE `tabLoan` set status = 'Closed' where name not in (%s)" % (', '.join(['%s'] * len(loans_to_close))), tuple(loans_to_close))

	loans = frappe.get_all('Loan', fields=['name', 'loan_type', 'company', 'status', 'mode_of_payment',
		'applicant_type', 'applicant', 'loan_account', 'payment_account', 'interest_income_account'],
		filters={'docstatus': 1, 'status': ('!=', 'Closed')})

	for loan in loans:
		# Update details in Loan Types and Loan
		loan_type_company = frappe.db.get_value('Loan Type', loan.loan_type, 'company')
		loan_type = loan.loan_type

		group_income_account = frappe.get_value('Account', {'company': loan.company,
			'is_group': 1, 'root_type': 'Income', 'account_name': _('Indirect Income')})

		if not group_income_account:
			group_income_account = frappe.get_value('Account', {'company': loan.company,
				'is_group': 1, 'root_type': 'Income'})

		penalty_account = create_account(company=loan.company, account_type='Income Account',
			account_name='Penalty Account', parent_account=group_income_account)

		# Same loan type used for multiple companies
		if loan_type_company and loan_type_company != loan.company:
			# get loan type for appropriate company
			loan_type_name = frappe.get_value('Loan Type', {'company': loan.company,
				'mode_of_payment': loan.mode_of_payment, 'loan_account': loan.loan_account,
				'payment_account': loan.payment_account, 'interest_income_account': loan.interest_income_account,
				'penalty_income_account': loan.penalty_income_account}, 'name')

			if not loan_type_name:
				loan_type_name = create_loan_type(loan, loan_type_name, penalty_account)

			# update loan type in loan
			frappe.db.sql("UPDATE `tabLoan` set loan_type = %s where name = %s", (loan_type_name,
				loan.name))

			loan_type = loan_type_name
			if loan_type_name not in updated_loan_types:
				updated_loan_types.append(loan_type_name)

		elif not loan_type_company:
			loan_type_doc = frappe.get_doc('Loan Type', loan.loan_type)
			loan_type_doc.is_term_loan = 1
			loan_type_doc.company = loan.company
			loan_type_doc.mode_of_payment = loan.mode_of_payment
			loan_type_doc.payment_account = loan.payment_account
			loan_type_doc.loan_account = loan.loan_account
			loan_type_doc.interest_income_account = loan.interest_income_account
			loan_type_doc.penalty_income_account = penalty_account
			loan_type_doc.submit()
			updated_loan_types.append(loan.loan_type)
			loan_type = loan.loan_type

		if loan_type in updated_loan_types:
			if loan.status == 'Fully Disbursed':
				status = 'Disbursed'
			elif loan.status == 'Repaid/Closed':
				status = 'Closed'
			else:
				status = loan.status

			frappe.db.set_value('Loan', loan.name, {
				'is_term_loan': 1,
				'penalty_income_account': penalty_account,
				'status': status
			})

			process_loan_interest_accrual_for_term_loans(posting_date=nowdate(), loan_type=loan_type,
				loan=loan.name)


			if frappe.db.has_column('Repayment Schedule', 'paid'):
				total_principal, total_interest = frappe.db.get_value('Repayment Schedule', {'paid': 1, 'parent': loan.name},
					['sum(principal_amount) as total_principal', 'sum(interest_amount) as total_interest'])

				accrued_entries = get_accrued_interest_entries(loan.name)
				for entry in accrued_entries:
					interest_paid = 0
					principal_paid = 0

					if flt(total_interest) > flt(entry.interest_amount):
						interest_paid = flt(entry.interest_amount)
					else:
						interest_paid = flt(total_interest)

					if flt(total_principal) > flt(entry.payable_principal_amount):
						principal_paid = flt(entry.payable_principal_amount)
					else:
						principal_paid = flt(total_principal)

					frappe.db.sql(""" UPDATE `tabLoan Interest Accrual`
						SET paid_principal_amount = `paid_principal_amount` + %s,
							paid_interest_amount = `paid_interest_amount` + %s
						WHERE name = %s""",
						(principal_paid, interest_paid, entry.name))

					total_principal = flt(total_principal) - principal_paid
					total_interest = flt(total_interest) - interest_paid
Esempio n. 34
0
def execute():
    frappe.reload_doc('accounts', 'doctype', 'sales_invoice')
    frappe.db.sql(
        """update `tabSales Invoice` set from_date = invoice_period_from_date,
		to_date = invoice_period_to_date, is_recurring = convert_into_recurring_invoice"""
    )
Esempio n. 35
0
def execute():
	frappe.reload_doc('assets', 'doctype', 'asset_finance_book')
	frappe.reload_doc('assets', 'doctype', 'depreciation_schedule')
	frappe.reload_doc('assets', 'doctype', 'asset_category')
	frappe.reload_doc('assets', 'doctype', 'asset')
	frappe.reload_doc('assets', 'doctype', 'asset_movement')
	frappe.reload_doc('assets', 'doctype', 'asset_category_account')

	if frappe.db.has_column("Asset", "warehouse"):
		frappe.db.sql(""" update `tabAsset` ast, `tabWarehouse` wh
			set ast.location = wh.warehouse_name where ast.warehouse = wh.name""")

		for d in frappe.get_all('Asset'):
			doc = frappe.get_doc('Asset', d.name)
			if doc.calculate_depreciation:
				fb = doc.append('finance_books', {
					'depreciation_method': doc.depreciation_method,
					'total_number_of_depreciations': doc.total_number_of_depreciations,
					'frequency_of_depreciation': doc.frequency_of_depreciation,
					'depreciation_start_date': doc.next_depreciation_date,
					'expected_value_after_useful_life': doc.expected_value_after_useful_life,
					'value_after_depreciation': doc.value_after_depreciation
				})

				fb.db_update()

		frappe.db.sql(""" update `tabDepreciation Schedule` ds, `tabAsset` ast
			set ds.depreciation_method = ast.depreciation_method, ds.finance_book_id = 1 where ds.parent = ast.name """)

		for category in frappe.get_all('Asset Category'):
			asset_category_doc = frappe.get_doc("Asset Category", category)
			row = asset_category_doc.append('finance_books', {
				'depreciation_method': asset_category_doc.depreciation_method,
				'total_number_of_depreciations': asset_category_doc.total_number_of_depreciations,
				'frequency_of_depreciation': asset_category_doc.frequency_of_depreciation
			})

			row.db_update()
def execute():
    contact_details = frappe.db.sql("""
		SELECT
			`name`, `email_id`, `phone`, `mobile_no`, `modified_by`, `creation`, `modified`
		FROM `tabContact`
	""",
                                    as_dict=True)
    frappe.reload_doc("contacts", "doctype", "contact_email")
    frappe.reload_doc("contacts", "doctype", "contact_phone")
    frappe.reload_doc("contacts", "doctype", "contact")

    email_values = []
    phone_values = []
    for count, contact_detail in enumerate(contact_details):
        phone_counter = 1
        is_primary = 1

        if contact_detail.email_id:
            email_values.append(
                (1, frappe.generate_hash(contact_detail.email_id, 10),
                 contact_detail.email_id, 'email_ids', 'Contact',
                 contact_detail.name, 1, contact_detail.creation,
                 contact_detail.modified, contact_detail.modified_by))

        if contact_detail.phone:
            is_primary_phone = 1 if phone_counter == 1 else 0
            phone_values.append(
                (phone_counter,
                 frappe.generate_hash(contact_detail.email_id,
                                      10), contact_detail.phone, 'phone_nos',
                 'Contact', contact_detail.name, is_primary_phone, 0,
                 contact_detail.creation, contact_detail.modified,
                 contact_detail.modified_by))
            phone_counter += 1
            is_primary += 1

        if contact_detail.mobile_no:
            is_primary_mobile_no = 1 if phone_counter == 1 else 0
            phone_values.append(
                (phone_counter,
                 frappe.generate_hash(contact_detail.email_id,
                                      10), contact_detail.mobile_no,
                 'phone_nos', 'Contact', contact_detail.name, 0,
                 is_primary_mobile_no, contact_detail.creation,
                 contact_detail.modified, contact_detail.modified_by))

        if email_values and (count % 10000 == 0
                             or count == len(contact_details) - 1):
            frappe.db.sql(
                """
				INSERT INTO `tabContact Email`
					(`idx`, `name`, `email_id`, `parentfield`, `parenttype`, `parent`, `is_primary`, `creation`,
					`modified`, `modified_by`)
				VALUES {}
			""".format(", ".join(['%s'] * len(email_values))), tuple(email_values))

            email_values = []

        if phone_values and (count % 10000 == 0
                             or count == len(contact_details) - 1):
            frappe.db.sql(
                """
				INSERT INTO `tabContact Phone`
					(`idx`, `name`, `phone`, `parentfield`, `parenttype`, `parent`, `is_primary_phone`, `is_primary_mobile_no`, `creation`,
					`modified`, `modified_by`)
				VALUES {}
			""".format(", ".join(['%s'] * len(phone_values))), tuple(phone_values))

            phone_values = []

    frappe.db.add_index("Contact Phone", ["phone"])
    frappe.db.add_index("Contact Email", ["email_id"])
Esempio n. 37
0
def add_print_formats():
    frappe.reload_doc("regional", "print_format", "gst_tax_invoice")
def execute():
    frappe.reload_doc('selling', 'doctype', 'quotation')
    frappe.reload_doc('selling', 'doctype', 'quotation_item')
    frappe.reload_doc('selling', 'doctype', 'sales_order')
    frappe.reload_doc('selling', 'doctype', 'sales_order_item')
    frappe.reload_doc('stock', 'doctype', 'delivery_note')
    frappe.reload_doc('stock', 'doctype', 'delivery_note_item')
    frappe.reload_doc('accounts', 'doctype', 'sales_invoice')
    frappe.reload_doc('accounts', 'doctype', 'sales_invoice_item')
    frappe.reload_doc('buying', 'doctype', 'supplier_quotation')
    frappe.reload_doc('buying', 'doctype', 'supplier_quotation_item')
    frappe.reload_doc('buying', 'doctype', 'purchase_order')
    frappe.reload_doc('buying', 'doctype', 'purchase_order_item')
    frappe.reload_doc('stock', 'doctype', 'purchase_receipt')
    frappe.reload_doc('stock', 'doctype', 'purchase_receipt_item')
    frappe.reload_doc('accounts', 'doctype', 'purchase_invoice')
    frappe.reload_doc('accounts', 'doctype', 'purchase_invoice_item')
    frappe.reload_doc('accounts', 'doctype', 'sales_taxes_and_charges')
    frappe.reload_doc('accounts', 'doctype', 'purchase_taxes_and_charges')

    doctypes = [
        'Sales Order', 'Delivery Note', 'Sales Invoice', 'Purchase Order',
        'Purchase Receipt', 'Purchase Invoice', 'Quotation',
        'Supplier Quotation'
    ]

    new_transaction_fields = [
        'total_before_discount',
        'tax_exclusive_total_before_discount',
        'total_discount',
        'tax_exclusive_total_discount',
        'taxable_total',
        'net_total',
        'total_after_taxes',
        'total_discount_after_taxes',
    ]
    new_transaction_fields += ['base_' + f for f in new_transaction_fields]
    new_transaction_fields = set(new_transaction_fields)

    new_item_fields = [
        'tax_exclusive_price_list_rate',
        'tax_exclusive_rate',
        'tax_exclusive_amount',
        'tax_exclusive_discount_amount',
        'tax_exclusive_rate_with_margin',
        'amount_before_discount',
        'tax_exclusive_amount_before_discount',
        'total_discount',
        'tax_exclusive_total_discount',
        'taxable_rate',
        'taxable_amount',
        'net_rate',
        'net_amount',
        'item_taxes_and_charges',
        'tax_inclusive_amount',
        'tax_inclusive_rate',
    ]
    new_item_fields += ['base_' + f for f in new_item_fields]
    new_item_fields = set(new_item_fields)

    # Calculate and update database
    for dt in doctypes:
        docnames = frappe.get_all(dt)
        for dn in docnames:
            dn = dn.name
            doc = frappe.get_doc(dt, dn)
            calculate_taxes_and_totals(doc)

            values_to_update = [doc.get(f) for f in new_transaction_fields]
            update_dict = dict(zip(new_transaction_fields, values_to_update))
            frappe.db.set_value(dt,
                                doc.name,
                                update_dict,
                                None,
                                update_modified=False)

            for item in doc.items:
                item_fields = set([f.fieldname for f in item.meta.fields])
                fields_to_update = list(
                    new_item_fields.intersection(item_fields))
                values_to_update = [item.get(f) for f in fields_to_update]
                update_dict = dict(zip(fields_to_update, values_to_update))
                frappe.db.set_value(dt + " Item",
                                    item.name,
                                    update_dict,
                                    None,
                                    update_modified=False)

            for tax in doc.taxes:
                frappe.db.set_value(tax.doctype,
                                    tax.name,
                                    "displayed_total",
                                    tax.displayed_total,
                                    update_modified=False)
def execute():
    frappe.reload_doc("Healthcare", "doctype", "Inpatient Record")
    if frappe.db.has_column("Inpatient Record", "discharge_date"):
        rename_field("Inpatient Record", "discharge_date",
                     "discharge_datetime")
Esempio n. 40
0
def execute():
    # Update the title of all BOM.
    frappe.reload_doc('manufacturing', 'doctype', 'bom')
    frappe.db.sql("""UPDATE `tabBOM` set title=item_name""")
Esempio n. 41
0
def sync_jobs(hooks: Dict = None):
	frappe.reload_doc("core", "doctype", "scheduled_job_type")
	scheduler_events = hooks or frappe.get_hooks("scheduler_events")
	all_events = insert_events(scheduler_events)
	clear_events(all_events)
def execute():
    frappe.reload_doc('printing', 'doctype', 'print_style')
    frappe.reload_doc('printing', 'doctype', 'print_settings')
    create_print_zero_amount_taxes_custom_field()
Esempio n. 43
0
def before_install():
    frappe.reload_doc("core", "doctype", "docfield")
    frappe.reload_doc("core", "doctype", "docperm")
    frappe.reload_doc("core", "doctype", "doctype")
def execute():
    company = frappe.get_all('Company', filters={'country': 'India'})
    if not company:
        return

    frappe.reload_doc("custom", "doctype", "custom_field")
    frappe.reload_doc("regional", "doctype", "e_invoice_settings")
    custom_fields = {
        'Sales Invoice': [
            dict(
                fieldname='irn',
                label='IRN',
                fieldtype='Data',
                read_only=1,
                insert_after='customer',
                no_copy=1,
                print_hide=1,
                depends_on=
                'eval:in_list(["Registered Regular", "SEZ", "Overseas", "Deemed Export"], doc.gst_category) && doc.irn_cancelled === 0'
            ),
            dict(fieldname='ack_no',
                 label='Ack. No.',
                 fieldtype='Data',
                 read_only=1,
                 hidden=1,
                 insert_after='irn',
                 no_copy=1,
                 print_hide=1),
            dict(fieldname='ack_date',
                 label='Ack. Date',
                 fieldtype='Data',
                 read_only=1,
                 hidden=1,
                 insert_after='ack_no',
                 no_copy=1,
                 print_hide=1),
            dict(fieldname='irn_cancelled',
                 label='IRN Cancelled',
                 fieldtype='Check',
                 no_copy=1,
                 print_hide=1,
                 depends_on='eval:(doc.irn_cancelled === 1)',
                 read_only=1,
                 allow_on_submit=1,
                 insert_after='customer'),
            dict(fieldname='eway_bill_cancelled',
                 label='E-Way Bill Cancelled',
                 fieldtype='Check',
                 no_copy=1,
                 print_hide=1,
                 depends_on='eval:(doc.eway_bill_cancelled === 1)',
                 read_only=1,
                 allow_on_submit=1,
                 insert_after='customer'),
            dict(fieldname='signed_einvoice',
                 fieldtype='Code',
                 options='JSON',
                 hidden=1,
                 no_copy=1,
                 print_hide=1,
                 read_only=1),
            dict(fieldname='signed_qr_code',
                 fieldtype='Code',
                 options='JSON',
                 hidden=1,
                 no_copy=1,
                 print_hide=1,
                 read_only=1),
            dict(fieldname='qrcode_image',
                 label='QRCode',
                 fieldtype='Attach Image',
                 hidden=1,
                 no_copy=1,
                 print_hide=1,
                 read_only=1)
        ]
    }
    create_custom_fields(custom_fields, update=True)
    add_permissions()
    add_print_formats()

    einvoice_cond = 'in_list(["Registered Regular", "SEZ", "Overseas", "Deemed Export"], doc.gst_category)'
    t = {
        'mode_of_transport': [{
            'default': None
        }],
        'distance': [{
            'mandatory_depends_on':
            f'eval:{einvoice_cond} && doc.transporter'
        }],
        'gst_vehicle_type': [{
            'mandatory_depends_on':
            f'eval:{einvoice_cond} && doc.mode_of_transport == "Road"'
        }],
        'lr_date': [{
            'mandatory_depends_on':
            f'eval:{einvoice_cond} && in_list(["Air", "Ship", "Rail"], doc.mode_of_transport)'
        }],
        'lr_no': [{
            'mandatory_depends_on':
            f'eval:{einvoice_cond} && in_list(["Air", "Ship", "Rail"], doc.mode_of_transport)'
        }],
        'vehicle_no': [{
            'mandatory_depends_on':
            f'eval:{einvoice_cond} && doc.mode_of_transport == "Road"'
        }],
        'ewaybill': [{
            'read_only_depends_on': 'eval:doc.irn && doc.ewaybill'
        }, {
            'depends_on':
            'eval:((doc.docstatus === 1 || doc.ewaybill) && doc.eway_bill_cancelled === 0)'
        }]
    }

    for field, conditions in t.items():
        for c in conditions:
            [(prop, value)] = c.items()
            frappe.db.set_value('Custom Field', {'fieldname': field}, prop,
                                value)
Esempio n. 45
0
def add_print_formats():
    frappe.reload_doc("regional", "print_format", "gst_tax_invoice")
    frappe.reload_doc("accounts", "print_format", "gst_pos_invoice")

    frappe.db.sql(""" update `tabPrint Format` set disabled = 0 where
		name in('GST POS Invoice', 'GST Tax Invoice') """)
Esempio n. 46
0
def execute():
    frappe.reload_doc("buying", "doctype", "supplier_quotation")
    frappe.db.sql("""UPDATE `tabSupplier Quotation`
		SET valid_till = DATE_ADD(transaction_date , INTERVAL 1 MONTH)
		WHERE docstatus < 2""")
Esempio n. 47
0
def add_print_formats():
    frappe.reload_doc("regional", "print_format", "irs_1099_form")
    frappe.db.sql(""" update `tabPrint Format` set disabled = 0 where
		name in('IRS 1099 Form') """)
def execute():
    if frappe.db.exists('DocType', 'Issue'):
        frappe.reload_doc("support", "doctype", "issue")
        rename_status()
def execute():
    if not frappe.db.has_column('Work Order', 'has_batch_no'):
        return

    frappe.reload_doc('manufacturing', 'doctype', 'manufacturing_settings')
    if cint(
            frappe.db.get_single_value(
                'Manufacturing Settings',
                'make_serial_no_batch_from_work_order')):
        return

    frappe.reload_doc('manufacturing', 'doctype', 'work_order')
    filters = {
        'docstatus': 1,
        'produced_qty': ('>', 0),
        'creation': ('>=', '2021-06-29 00:00:00'),
        'has_batch_no': 1
    }

    fields = ['name', 'production_item']

    work_orders = [
        d.name
        for d in frappe.get_all('Work Order', filters=filters, fields=fields)
    ]

    if not work_orders:
        return

    repost_stock_entries = []

    stock_entries = frappe.db.sql_list(
        '''
		SELECT
			se.name
		FROM
			`tabStock Entry` se
		WHERE
			se.purpose = 'Manufacture' and se.docstatus < 2 and se.work_order in %s
			and not exists(
				select name from `tabStock Entry Detail` sed where sed.parent = se.name and sed.is_finished_item = 1
			)
		ORDER BY
			se.posting_date, se.posting_time
	''', (work_orders, ))

    if stock_entries:
        print('Length of stock entries', len(stock_entries))

    for stock_entry in stock_entries:
        doc = frappe.get_doc('Stock Entry', stock_entry)
        doc.set_work_order_details()
        doc.load_items_from_bom()
        doc.calculate_rate_and_amount()
        set_expense_account(doc)
        doc.make_batches('t_warehouse')

        if doc.docstatus == 0:
            doc.save()
        else:
            repost_stock_entry(doc)
            repost_stock_entries.append(doc)

    for repost_doc in repost_stock_entries:
        repost_future_sle_and_gle(repost_doc)
Esempio n. 50
0
def execute():

    frappe.reload_doc('stock', 'doctype', 'delivery_note_item', force=True)
    frappe.reload_doc('stock', 'doctype', 'purchase_receipt_item', force=True)

    def map_rows(doc_row, return_doc_row, detail_field, doctype):
        """Map rows after identifying similar ones."""

        frappe.db.sql(""" UPDATE `tab{doctype} Item` set {detail_field} = '{doc_row_name}'
				where name = '{return_doc_row_name}'""" \
         .format(doctype=doctype,
           detail_field=detail_field,
           doc_row_name=doc_row.get('name'),
           return_doc_row_name=return_doc_row.get('name'))) #nosec

    def row_is_mappable(doc_row, return_doc_row, detail_field):
        """Checks if two rows are similar enough to be mapped."""

        if doc_row.item_code == return_doc_row.item_code and not return_doc_row.get(
                detail_field):
            if doc_row.get('batch_no') and return_doc_row.get(
                    'batch_no'
            ) and doc_row.batch_no == return_doc_row.batch_no:
                return True

            elif doc_row.get('serial_no') and return_doc_row.get('serial_no'):
                doc_sn = doc_row.serial_no.split('\n')
                return_doc_sn = return_doc_row.serial_no.split('\n')

                if set(doc_sn) & set(return_doc_sn):
                    # if two rows have serial nos in common, map them
                    return True

            elif doc_row.rate == return_doc_row.rate:
                return True
        else:
            return False

    def make_return_document_map(doctype, return_document_map):
        """Returns a map of documents and it's return documents.
		Format => { 'document' : ['return_document_1','return_document_2'] }"""

        return_against_documents = frappe.db.sql("""
			SELECT
				return_against as document, name as return_document
			FROM `tab{doctype}`
			WHERE
				is_return = 1 and docstatus = 1""".format(doctype=doctype),
                                                 as_dict=1)  #nosec

        for entry in return_against_documents:
            return_document_map[entry.document].append(entry.return_document)

        return return_document_map

    def set_document_detail_in_return_document(doctype):
        """Map each row of the original document in the return document."""
        mapped = []
        return_document_map = defaultdict(list)
        detail_field = "purchase_receipt_item" if doctype == "Purchase Receipt" else "dn_detail"

        child_doc = frappe.scrub("{0} Item".format(doctype))
        frappe.reload_doc("stock", "doctype", child_doc)

        return_document_map = make_return_document_map(doctype,
                                                       return_document_map)

        count = 0

        #iterate through original documents and its return documents
        for docname in return_document_map:
            doc_items = frappe.get_cached_doc(doctype, docname).get("items")
            for return_doc in return_document_map[docname]:
                return_doc_items = frappe.get_cached_doc(
                    doctype, return_doc).get("items")

                #iterate through return document items and original document items for mapping
                for return_item in return_doc_items:
                    for doc_item in doc_items:
                        if row_is_mappable(doc_item, return_item,
                                           detail_field) and doc_item.get(
                                               'name') not in mapped:
                            map_rows(doc_item, return_item, detail_field,
                                     doctype)
                            mapped.append(doc_item.get('name'))
                            break
                        else:
                            continue

            # commit after every 100 sql updates
            count += 1
            if count % 100 == 0:
                frappe.db.commit()

    set_document_detail_in_return_document("Purchase Receipt")
    set_document_detail_in_return_document("Delivery Note")
    frappe.db.commit()
def execute():
	frappe.reload_doc("accounts", "doctype", frappe.scrub("Cash Flow Mapping"))
	frappe.reload_doc("accounts", "doctype", frappe.scrub("Cash Flow Mapper"))
	frappe.reload_doc("accounts", "doctype", frappe.scrub("Cash Flow Mapping Template Details"))

	create_default_cash_flow_mapper_templates()
Esempio n. 52
0
def add_print_formats():
    frappe.reload_doc("regional", "print_format", "detailed_tax_invoice")
    frappe.reload_doc("regional", "print_format", "simplified_tax_invoice")

    frappe.db.sql(""" update `tabPrint Format` set disabled = 0 where
		name in('Simplified Tax Invoice', 'Detailed Tax Invoice') """)
Esempio n. 53
0
def execute():
    frappe.reload_doc('crm', 'doctype', 'lead')
    frappe.reload_doc('crm', 'doctype', 'opportunity')

    add_crm_to_user_desktop_items()
Esempio n. 54
0
def execute():
    for dt in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
        frappe.reload_doc(get_doctype_module(dt), "doctype", scrub(dt))
        frappe.db.sql(
            """update `tab{0}` set base_discount_amount=discount_amount,
			discount_amount=discount_amount/conversion_rate""".format(dt))
def execute():
    if frappe.db.exists('DocType', 'Issue'):
        issues = frappe.db.get_all('Issue',
                                   fields=[
                                       'name', 'response_by_variance',
                                       'resolution_by_variance',
                                       'mins_to_first_response'
                                   ],
                                   order_by='creation desc')
        frappe.reload_doc('support', 'doctype', 'issue')

        # rename fields
        rename_map = {
            'agreement_fulfilled': 'agreement_status',
            'mins_to_first_response': 'first_response_time'
        }
        for old, new in rename_map.items():
            rename_field('Issue', old, new)

        # change fieldtype to duration
        count = 0
        for entry in issues:
            response_by_variance = convert_to_seconds(
                entry.response_by_variance, 'Hours')
            resolution_by_variance = convert_to_seconds(
                entry.resolution_by_variance, 'Hours')
            mins_to_first_response = convert_to_seconds(
                entry.mins_to_first_response, 'Minutes')
            frappe.db.set_value(
                'Issue', entry.name, {
                    'response_by_variance': response_by_variance,
                    'resolution_by_variance': resolution_by_variance,
                    'first_response_time': mins_to_first_response
                })
            # commit after every 100 updates
            count += 1
            if count % 100 == 0:
                frappe.db.commit()

    if frappe.db.exists('DocType', 'Opportunity'):
        opportunities = frappe.db.get_all(
            'Opportunity',
            fields=['name', 'mins_to_first_response'],
            order_by='creation desc')
        frappe.reload_doc('crm', 'doctype', 'opportunity')
        rename_field('Opportunity', 'mins_to_first_response',
                     'first_response_time')

        # change fieldtype to duration
        count = 0
        for entry in opportunities:
            mins_to_first_response = convert_to_seconds(
                entry.mins_to_first_response, 'Minutes')
            frappe.db.set_value('Opportunity', entry.name,
                                'first_response_time', mins_to_first_response)
            # commit after every 100 updates
            count += 1
            if count % 100 == 0:
                frappe.db.commit()

    # renamed reports from "Minutes to First Response for Issues" to "First Response Time for Issues". Same for Opportunity
    for report in [
            'Minutes to First Response for Issues',
            'Minutes to First Response for Opportunity'
    ]:
        if frappe.db.exists('Report', report):
            frappe.delete_doc('Report', report)
def execute():
	frappe.reload_doc("assets", "doctype", "Location")
	for dt in ("Account", "Cost Center", "File", "Employee", "Location", "Task", "Customer Group", "Sales Person", "Territory"):
		frappe.reload_doctype(dt)
		frappe.get_doc("DocType", dt).run_module_method("on_doctype_update")
Esempio n. 57
0
def add_print_formats():
    frappe.reload_doc("regional", "print_format", "irs_1099_form")
    frappe.db.set_value("Print Format", "IRS 1099 Form", "disabled", 0)
def execute():
    for dn in field_rename_map:
        if frappe.db.exists('DocType', dn):
            if dn == 'Healthcare Settings':
                frappe.reload_doctype('Healthcare Settings')
            else:
                frappe.reload_doc(get_doctype_module(dn), "doctype", scrub(dn))

    for dt, field_list in field_rename_map.items():
        if frappe.db.exists('DocType', dt):
            for field in field_list:
                if dt == 'Healthcare Settings':
                    rename_field(dt, field[0], field[1])
                elif frappe.db.has_column(dt, field[0]):
                    rename_field(dt, field[0], field[1])

    # first name mandatory in Patient
    if frappe.db.exists('DocType', 'Patient'):
        patients = frappe.db.sql("select name, patient_name from `tabPatient`",
                                 as_dict=1)
        frappe.reload_doc('healthcare', 'doctype', 'patient')
        for entry in patients:
            name = entry.patient_name.split(' ')
            frappe.db.set_value('Patient', entry.name, 'first_name', name[0])

    # mark Healthcare Practitioner status as Disabled
    if frappe.db.exists('DocType', 'Healthcare Practitioner'):
        practitioners = frappe.db.sql(
            "select name from `tabHealthcare Practitioner` where 'active'= 0",
            as_dict=1)
        practitioners_lst = [p.name for p in practitioners]
        frappe.reload_doc('healthcare', 'doctype', 'healthcare_practitioner')
        if practitioners_lst:
            frappe.db.sql(
                "update `tabHealthcare Practitioner` set status = 'Disabled' where name IN %(practitioners)s"
                "", {"practitioners": practitioners_lst})

    # set Clinical Procedure status
    if frappe.db.exists('DocType', 'Clinical Procedure'):
        frappe.reload_doc('healthcare', 'doctype', 'clinical_procedure')
        frappe.db.sql("""
			UPDATE
				`tabClinical Procedure`
			SET
				docstatus = (CASE WHEN status = 'Cancelled' THEN 2
								WHEN status = 'Draft' THEN 0
								ELSE 1
							END)
		""")

    # set complaints and diagnosis in table multiselect in Patient Encounter
    if frappe.db.exists('DocType', 'Patient Encounter'):
        field_list = [['visit_department', 'medical_department'],
                      ['type', 'appointment_type']]
        encounter_details = frappe.db.sql(
            """select symptoms, diagnosis, name from `tabPatient Encounter`""",
            as_dict=True)
        frappe.reload_doc('healthcare', 'doctype', 'patient_encounter')
        frappe.reload_doc('healthcare', 'doctype', 'patient_encounter_symptom')
        frappe.reload_doc('healthcare', 'doctype',
                          'patient_encounter_diagnosis')

        for field in field_list:
            if frappe.db.has_column(dt, field[0]):
                rename_field(dt, field[0], field[1])

        for entry in encounter_details:
            doc = frappe.get_doc('Patient Encounter', entry.name)
            symptoms = entry.symptoms.split('\n') if entry.symptoms else []
            for symptom in symptoms:
                if not frappe.db.exists('Complaint', symptom):
                    frappe.get_doc({
                        'doctype': 'Complaint',
                        'complaints': symptom
                    }).insert()
                row = doc.append('symptoms', {'complaint': symptom})
                row.db_update()

            diagnosis = entry.diagnosis.split('\n') if entry.diagnosis else []
            for d in diagnosis:
                if not frappe.db.exists('Diagnosis', d):
                    frappe.get_doc({
                        'doctype': 'Diagnosis',
                        'diagnosis': d
                    }).insert()
                row = doc.append('diagnosis', {'diagnosis': d})
                row.db_update()
            doc.db_update()

    if frappe.db.exists('DocType', 'Fee Validity'):
        # update fee validity status
        frappe.db.sql("""
			UPDATE
				`tabFee Validity`
			SET
				status = (CASE WHEN visited >= max_visits THEN 'Completed'
								ELSE 'Pending'
							END)
		""")
def execute():
    company = frappe.get_all('Company',
                             filters={'country': 'India'},
                             fields=['name'])
    if not company:
        return

    frappe.reload_doc("regional", "doctype", "gst_settings")
    frappe.reload_doc("accounts", "doctype", "gst_account")

    journal_entry_types = frappe.get_meta("Journal Entry").get_options(
        "voucher_type").split("\n") + ['Reversal Of ITC']
    make_property_setter('Journal Entry', 'voucher_type', 'options',
                         '\n'.join(journal_entry_types), '')

    custom_fields = {
        'Journal Entry': [
            dict(
                fieldname='reversal_type',
                label='Reversal Type',
                fieldtype='Select',
                insert_after='voucher_type',
                print_hide=1,
                options="As per rules 42 & 43 of CGST Rules\nOthers",
                depends_on="eval:doc.voucher_type=='Reversal Of ITC'",
                mandatory_depends_on="eval:doc.voucher_type=='Reversal Of ITC'"
            ),
            dict(
                fieldname='company_address',
                label='Company Address',
                fieldtype='Link',
                options='Address',
                insert_after='reversal_type',
                print_hide=1,
                depends_on="eval:doc.voucher_type=='Reversal Of ITC'",
                mandatory_depends_on="eval:doc.voucher_type=='Reversal Of ITC'"
            ),
            dict(
                fieldname='company_gstin',
                label='Company GSTIN',
                fieldtype='Data',
                read_only=1,
                insert_after='company_address',
                print_hide=1,
                fetch_from='company_address.gstin',
                depends_on="eval:doc.voucher_type=='Reversal Of ITC'",
                mandatory_depends_on="eval:doc.voucher_type=='Reversal Of ITC'"
            )
        ],
        'Purchase Invoice': [
            dict(
                fieldname='eligibility_for_itc',
                label='Eligibility For ITC',
                fieldtype='Select',
                insert_after='reason_for_issuing_document',
                print_hide=1,
                options=
                'Input Service Distributor\nImport Of Service\nImport Of Capital Goods\nITC on Reverse Charge\nIneligible As Per Section 17(5)\nIneligible Others\nAll Other ITC',
                default="All Other ITC")
        ],
        'Purchase Invoice Item': [
            dict(fieldname='taxable_value',
                 label='Taxable Value',
                 fieldtype='Currency',
                 insert_after='base_net_amount',
                 hidden=1,
                 options="Company:company:default_currency",
                 print_hide=1)
        ]
    }

    create_custom_fields(custom_fields, update=True)

    # Patch ITC Availed fields from Data to Currency
    # Patch Availed ITC for current fiscal_year

    gst_accounts = get_gst_accounts(only_non_reverse_charge=1)

    frappe.db.sql("""
		UPDATE `tabCustom Field` SET fieldtype='Currency', options='Company:company:default_currency'
		WHERE dt = 'Purchase Invoice' and fieldname in ('itc_integrated_tax', 'itc_state_tax', 'itc_central_tax',
			'itc_cess_amount')
	""")

    frappe.db.sql("""UPDATE `tabPurchase Invoice` set itc_integrated_tax = '0'
		WHERE trim(coalesce(itc_integrated_tax, '')) = '' """)

    frappe.db.sql("""UPDATE `tabPurchase Invoice` set itc_state_tax = '0'
		WHERE trim(coalesce(itc_state_tax, '')) = '' """)

    frappe.db.sql("""UPDATE `tabPurchase Invoice` set itc_central_tax = '0'
		WHERE trim(coalesce(itc_central_tax, '')) = '' """)

    frappe.db.sql("""UPDATE `tabPurchase Invoice` set itc_cess_amount = '0'
		WHERE trim(coalesce(itc_cess_amount, '')) = '' """)

    # Get purchase invoices
    invoices = frappe.get_all(
        'Purchase Invoice', {
            'posting_date': ('>=', '2021-04-01'),
            'eligibility_for_itc': ('!=', 'Ineligible')
        }, ['name'])

    amount_map = {}

    if invoices:
        invoice_list = set([d.name for d in invoices])

        # Get GST applied
        amounts = frappe.db.sql("""
			SELECT parent, account_head, sum(base_tax_amount_after_discount_amount) as amount
			FROM `tabPurchase Taxes and Charges`
			where parent in %s
			GROUP BY parent, account_head
		""", (invoice_list),
                                as_dict=1)

        for d in amounts:
            amount_map.setdefault(
                d.parent, {
                    'itc_integrated_tax': 0,
                    'itc_state_tax': 0,
                    'itc_central_tax': 0,
                    'itc_cess_amount': 0
                })

            if d.account_head in gst_accounts.get('igst_account'):
                amount_map[d.parent]['itc_integrated_tax'] += d.amount
            if d.account_head in gst_accounts.get('cgst_account'):
                amount_map[d.parent]['itc_central_tax'] += d.amount
            if d.account_head in gst_accounts.get('sgst_account'):
                amount_map[d.parent]['itc_state_tax'] += d.amount
            if d.account_head in gst_accounts.get('cess_account'):
                amount_map[d.parent]['itc_cess_amount'] += d.amount

        for invoice, values in amount_map.items():
            frappe.db.set_value(
                'Purchase Invoice', invoice, {
                    'itc_integrated_tax': values.get('itc_integrated_tax'),
                    'itc_central_tax': values.get('itc_central_tax'),
                    'itc_state_tax': values['itc_state_tax'],
                    'itc_cess_amount': values['itc_cess_amount'],
                })
Esempio n. 60
0
def execute():
    frappe.reload_doc("core", "doctype", "success_action")
    create_default_success_action()