Merge remote-tracking branch 'upstream/develop' into remove-india

This commit is contained in:
Sagar Vora
2022-06-19 22:57:22 +05:30
2017 changed files with 248759 additions and 94060 deletions

View File

@@ -8,12 +8,16 @@ from frappe.model.utils.rename_field import rename_field
def execute():
frappe.reload_doc("setup", "doctype", "company")
if frappe.db.has_column('Company', 'default_terms'):
rename_field('Company', "default_terms", "default_selling_terms")
if frappe.db.has_column("Company", "default_terms"):
rename_field("Company", "default_terms", "default_selling_terms")
for company in frappe.get_all("Company", ["name", "default_selling_terms", "default_buying_terms"]):
for company in frappe.get_all(
"Company", ["name", "default_selling_terms", "default_buying_terms"]
):
if company.default_selling_terms and not company.default_buying_terms:
frappe.db.set_value("Company", company.name, "default_buying_terms", company.default_selling_terms)
frappe.db.set_value(
"Company", company.name, "default_buying_terms", company.default_selling_terms
)
frappe.reload_doc("setup", "doctype", "terms_and_conditions")
frappe.db.sql("update `tabTerms and Conditions` set selling=1, buying=1, hr=1")

View File

@@ -3,15 +3,19 @@ from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
def execute():
company = frappe.get_all('Company', filters = {'country': 'Italy'})
company = frappe.get_all("Company", filters={"country": "Italy"})
if not company:
return
custom_fields = {
'Sales Invoice': [
dict(fieldname='type_of_document', label='Type of Document',
fieldtype='Select', insert_after='customer_fiscal_code',
options='\nTD01\nTD02\nTD03\nTD04\nTD05\nTD06\nTD16\nTD17\nTD18\nTD19\nTD20\nTD21\nTD22\nTD23\nTD24\nTD25\nTD26\nTD27'),
"Sales Invoice": [
dict(
fieldname="type_of_document",
label="Type of Document",
fieldtype="Select",
insert_after="customer_fiscal_code",
options="\nTD01\nTD02\nTD03\nTD04\nTD05\nTD06\nTD16\nTD17\nTD18\nTD19\nTD20\nTD21\nTD22\nTD23\nTD24\nTD25\nTD26\nTD27",
),
]
}

View File

@@ -4,11 +4,13 @@ import frappe
def execute():
frappe.reload_doc("manufacturing", "doctype", "work_order")
frappe.db.sql("""
frappe.db.sql(
"""
UPDATE
`tabWork Order` wo
JOIN `tabItem` item ON wo.production_item = item.item_code
SET
wo.item_name = item.item_name
""")
"""
)
frappe.db.commit()

View File

@@ -3,12 +3,12 @@ from frappe.permissions import add_permission, update_permission_property
def execute():
company = frappe.get_all('Company', filters = {'country': 'India'})
company = frappe.get_all("Company", filters={"country": "India"})
if not company:
return
frappe.reload_doc('regional', 'doctype', 'Lower Deduction Certificate')
frappe.reload_doc("regional", "doctype", "Lower Deduction Certificate")
add_permission('Lower Deduction Certificate', 'Accounts Manager', 0)
update_permission_property('Lower Deduction Certificate', 'Accounts Manager', 0, 'write', 1)
update_permission_property('Lower Deduction Certificate', 'Accounts Manager', 0, 'create', 1)
add_permission("Lower Deduction Certificate", "Accounts Manager", 0)
update_permission_property("Lower Deduction Certificate", "Accounts Manager", 0, "write", 1)
update_permission_property("Lower Deduction Certificate", "Accounts Manager", 0, "create", 1)

View File

@@ -5,15 +5,15 @@ from erpnext.regional.india import states
def execute():
company = frappe.get_all('Company', filters = {'country': 'India'})
company = frappe.get_all("Company", filters={"country": "India"})
if not company:
return
custom_fields = ['Address-gst_state', 'Tax Category-gst_state']
custom_fields = ["Address-gst_state", "Tax Category-gst_state"]
# Update options in gst_state custom fields
for field in custom_fields:
if frappe.db.exists('Custom Field', field):
gst_state_field = frappe.get_doc('Custom Field', field)
gst_state_field.options = '\n'.join(states)
if frappe.db.exists("Custom Field", field):
gst_state_field = frappe.get_doc("Custom Field", field)
gst_state_field.options = "\n".join(states)
gst_state_field.save()

View File

@@ -4,7 +4,7 @@ from erpnext.regional.united_states.setup import make_custom_fields
def execute():
company = frappe.get_all('Company', filters={'country': 'United States'})
company = frappe.get_all("Company", filters={"country": "United States"})
if not company:
return

View File

@@ -2,9 +2,11 @@ import frappe
def execute():
frappe.reload_doc('stock', 'doctype', 'item_variant_attribute')
frappe.db.sql('''
frappe.reload_doc("stock", "doctype", "item_variant_attribute")
frappe.db.sql(
"""
UPDATE `tabItem Variant Attribute` t1
INNER JOIN `tabItem` t2 ON t2.name = t1.parent
SET t1.variant_of = t2.variant_of
''')
"""
)

View File

@@ -4,10 +4,13 @@ from frappe.custom.doctype.custom_field.custom_field import create_custom_field
def execute():
frappe.reload_doc('accounts', 'doctype', 'accounting_dimension')
frappe.reload_doc("accounts", "doctype", "accounting_dimension")
accounting_dimensions = frappe.db.sql("""select fieldname, label, document_type, disabled from
`tabAccounting Dimension`""", as_dict=1)
accounting_dimensions = frappe.db.sql(
"""select fieldname, label, document_type, disabled from
`tabAccounting Dimension`""",
as_dict=1,
)
if not accounting_dimensions:
return
@@ -15,13 +18,19 @@ def execute():
count = 1
for d in accounting_dimensions:
if count%2 == 0:
insert_after_field = 'dimension_col_break'
if count % 2 == 0:
insert_after_field = "dimension_col_break"
else:
insert_after_field = 'accounting_dimensions_section'
insert_after_field = "accounting_dimensions_section"
for doctype in ["Subscription Plan", "Subscription", "Opening Invoice Creation Tool", "Opening Invoice Creation Tool Item",
"Expense Claim Detail", "Expense Taxes and Charges"]:
for doctype in [
"Subscription Plan",
"Subscription",
"Opening Invoice Creation Tool",
"Opening Invoice Creation Tool Item",
"Expense Claim Detail",
"Expense Taxes and Charges",
]:
field = frappe.db.get_value("Custom Field", {"dt": doctype, "fieldname": d.fieldname})
@@ -33,7 +42,7 @@ def execute():
"label": d.label,
"fieldtype": "Link",
"options": d.document_type,
"insert_after": insert_after_field
"insert_after": insert_after_field,
}
create_custom_field(doctype, df)

View File

@@ -4,5 +4,5 @@ from erpnext.setup.install import create_default_energy_point_rules
def execute():
frappe.reload_doc('social', 'doctype', 'energy_point_rule')
frappe.reload_doc("social", "doctype", "energy_point_rule")
create_default_energy_point_rules()

View File

@@ -5,12 +5,12 @@ from erpnext.regional.united_states.setup import make_custom_fields
def execute():
frappe.reload_doc('accounts', 'doctype', 'allowed_to_transact_with', force=True)
frappe.reload_doc('accounts', 'doctype', 'pricing_rule_detail', force=True)
frappe.reload_doc('crm', 'doctype', 'lost_reason_detail', force=True)
frappe.reload_doc('setup', 'doctype', 'quotation_lost_reason_detail', force=True)
frappe.reload_doc("accounts", "doctype", "allowed_to_transact_with", force=True)
frappe.reload_doc("accounts", "doctype", "pricing_rule_detail", force=True)
frappe.reload_doc("crm", "doctype", "lost_reason_detail", force=True)
frappe.reload_doc("setup", "doctype", "quotation_lost_reason_detail", force=True)
company = frappe.get_all('Company', filters = {'country': 'United States'})
company = frappe.get_all("Company", filters={"country": "United States"})
if not company:
return

View File

@@ -6,44 +6,76 @@ from erpnext.regional.india.utils import get_gst_accounts
def execute():
company = frappe.get_all('Company', filters = {'country': 'India'}, fields=['name'])
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), '')
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,
"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',
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'")
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": [
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,
)
],
'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)
@@ -53,28 +85,40 @@ def execute():
gst_accounts = get_gst_accounts(only_non_reverse_charge=1)
frappe.db.sql("""
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_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_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_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, '')) = '' """)
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'])
invoices = frappe.get_all(
"Purchase Invoice",
{"posting_date": (">=", "2021-04-01"), "eligibility_for_itc": ("!=", "Ineligible")},
["name"],
)
amount_map = {}
@@ -82,37 +126,42 @@ def execute():
invoice_list = set([d.name for d in invoices])
# Get GST applied
amounts = frappe.db.sql("""
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)
""",
(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
})
amount_map.setdefault(
d.parent,
{"itc_integrated_tax": 0, "itc_state_tax": 0, "itc_central_tax": 0, "itc_cess_amount": 0},
)
if not gst_accounts:
continue
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
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'],
})
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"],
},
)

View File

@@ -3,15 +3,21 @@ from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
def execute():
company = frappe.get_all('Company', filters = {'country': 'India'})
company = frappe.get_all("Company", filters={"country": "India"})
if not company:
return
custom_fields = {
'Sales 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)
"Sales 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,
)
]
}

View File

@@ -2,9 +2,11 @@ import frappe
def execute():
frappe.db.sql("""
frappe.db.sql(
"""
DELETE FROM `tabProperty Setter`
WHERE `tabProperty Setter`.doc_type='Issue'
AND `tabProperty Setter`.field_name='priority'
AND `tabProperty Setter`.property='options'
""")
"""
)

View File

@@ -4,10 +4,13 @@ from frappe.utils import flt
def execute():
for project in frappe.get_all("Project", fields=["name", "percent_complete_method"]):
total = frappe.db.count('Task', dict(project=project.name))
total = frappe.db.count("Task", dict(project=project.name))
if project.percent_complete_method == "Task Completion" and total > 0:
completed = frappe.db.sql("""select count(name) from tabTask where
project=%s and status in ('Cancelled', 'Completed')""", project.name)[0][0]
completed = frappe.db.sql(
"""select count(name) from tabTask where
project=%s and status in ('Cancelled', 'Completed')""",
project.name,
)[0][0]
percent_complete = flt(flt(completed) / total * 100, 2)
if project.percent_complete != percent_complete:
frappe.db.set_value("Project", project.name, "percent_complete", percent_complete)

View File

@@ -13,12 +13,13 @@ def execute():
so_item.docstatus = 1 and so.docstatus = 1
and so_item.parent = so.name
and so_item.prevdoc_docname = qo.name
and qo.valid_till < so.transaction_date""" # check if SO was created after quotation expired
and qo.valid_till < so.transaction_date""" # check if SO was created after quotation expired
frappe.db.sql(
"""UPDATE `tabQuotation` qo SET qo.status = 'Expired' WHERE {cond} and exists({invalid_so_against_quo})"""
.format(cond=cond, invalid_so_against_quo=invalid_so_against_quo)
"""UPDATE `tabQuotation` qo SET qo.status = 'Expired' WHERE {cond} and exists({invalid_so_against_quo})""".format(
cond=cond, invalid_so_against_quo=invalid_so_against_quo
)
)
valid_so_against_quo = """
SELECT
@@ -27,9 +28,10 @@ def execute():
so_item.docstatus = 1 and so.docstatus = 1
and so_item.parent = so.name
and so_item.prevdoc_docname = qo.name
and qo.valid_till >= so.transaction_date""" # check if SO was created before quotation expired
and qo.valid_till >= so.transaction_date""" # check if SO was created before quotation expired
frappe.db.sql(
"""UPDATE `tabQuotation` qo SET qo.status = 'Closed' WHERE {cond} and exists({valid_so_against_quo})"""
.format(cond=cond, valid_so_against_quo=valid_so_against_quo)
"""UPDATE `tabQuotation` qo SET qo.status = 'Closed' WHERE {cond} and exists({valid_so_against_quo})""".format(
cond=cond, valid_so_against_quo=valid_so_against_quo
)
)

View File

@@ -7,8 +7,8 @@ from frappe.utils import getdate, today
def execute():
""" Generates leave ledger entries for leave allocation/application/encashment
for last allocation """
"""Generates leave ledger entries for leave allocation/application/encashment
for last allocation"""
frappe.reload_doc("HR", "doctype", "Leave Ledger Entry")
frappe.reload_doc("HR", "doctype", "Leave Encashment")
frappe.reload_doc("HR", "doctype", "Leave Type")
@@ -22,55 +22,79 @@ def execute():
generate_encashment_leave_ledger_entries()
generate_expiry_allocation_ledger_entries()
def update_leave_allocation_fieldname():
''' maps data from old field to the new field '''
frappe.db.sql("""
"""maps data from old field to the new field"""
frappe.db.sql(
"""
UPDATE `tabLeave Allocation`
SET `unused_leaves` = `carry_forwarded_leaves`
""")
"""
)
def generate_allocation_ledger_entries():
''' fix ledger entries for missing leave allocation transaction '''
"""fix ledger entries for missing leave allocation transaction"""
allocation_list = get_allocation_records()
for allocation in allocation_list:
if not frappe.db.exists("Leave Ledger Entry", {'transaction_type': 'Leave Allocation', 'transaction_name': allocation.name}):
if not frappe.db.exists(
"Leave Ledger Entry",
{"transaction_type": "Leave Allocation", "transaction_name": allocation.name},
):
allocation_obj = frappe.get_doc("Leave Allocation", allocation)
allocation_obj.create_leave_ledger_entry()
def generate_application_leave_ledger_entries():
''' fix ledger entries for missing leave application transaction '''
"""fix ledger entries for missing leave application transaction"""
leave_applications = get_leaves_application_records()
for application in leave_applications:
if not frappe.db.exists("Leave Ledger Entry", {'transaction_type': 'Leave Application', 'transaction_name': application.name}):
if not frappe.db.exists(
"Leave Ledger Entry",
{"transaction_type": "Leave Application", "transaction_name": application.name},
):
frappe.get_doc("Leave Application", application.name).create_leave_ledger_entry()
def generate_encashment_leave_ledger_entries():
''' fix ledger entries for missing leave encashment transaction '''
"""fix ledger entries for missing leave encashment transaction"""
leave_encashments = get_leave_encashment_records()
for encashment in leave_encashments:
if not frappe.db.exists("Leave Ledger Entry", {'transaction_type': 'Leave Encashment', 'transaction_name': encashment.name}):
if not frappe.db.exists(
"Leave Ledger Entry",
{"transaction_type": "Leave Encashment", "transaction_name": encashment.name},
):
frappe.get_doc("Leave Encashment", encashment).create_leave_ledger_entry()
def generate_expiry_allocation_ledger_entries():
''' fix ledger entries for missing leave allocation transaction '''
"""fix ledger entries for missing leave allocation transaction"""
from erpnext.hr.doctype.leave_ledger_entry.leave_ledger_entry import expire_allocation
allocation_list = get_allocation_records()
for allocation in allocation_list:
if not frappe.db.exists("Leave Ledger Entry", {'transaction_type': 'Leave Allocation', 'transaction_name': allocation.name, 'is_expired': 1}):
if not frappe.db.exists(
"Leave Ledger Entry",
{"transaction_type": "Leave Allocation", "transaction_name": allocation.name, "is_expired": 1},
):
allocation_obj = frappe.get_doc("Leave Allocation", allocation)
if allocation_obj.to_date <= getdate(today()):
expire_allocation(allocation_obj)
def get_allocation_records():
return frappe.get_all("Leave Allocation", filters={"docstatus": 1},
fields=['name'], order_by='to_date ASC')
return frappe.get_all(
"Leave Allocation", filters={"docstatus": 1}, fields=["name"], order_by="to_date ASC"
)
def get_leaves_application_records():
return frappe.get_all("Leave Application", filters={"docstatus": 1}, fields=['name'])
return frappe.get_all("Leave Application", filters={"docstatus": 1}, fields=["name"])
def get_leave_encashment_records():
return frappe.get_all("Leave Encashment", filters={"docstatus": 1}, fields=['name'])
return frappe.get_all("Leave Encashment", filters={"docstatus": 1}, fields=["name"])

View File

@@ -9,20 +9,29 @@ def execute():
frappe.reload_doc("stock", "doctype", "item_manufacturer")
item_manufacturer = []
for d in frappe.db.sql(""" SELECT name, manufacturer, manufacturer_part_no, creation, owner
FROM `tabItem` WHERE manufacturer is not null and manufacturer != ''""", as_dict=1):
item_manufacturer.append((
frappe.generate_hash("", 10),
d.name,
d.manufacturer,
d.manufacturer_part_no,
d.creation,
d.owner
))
for d in frappe.db.sql(
""" SELECT name, manufacturer, manufacturer_part_no, creation, owner
FROM `tabItem` WHERE manufacturer is not null and manufacturer != ''""",
as_dict=1,
):
item_manufacturer.append(
(
frappe.generate_hash("", 10),
d.name,
d.manufacturer,
d.manufacturer_part_no,
d.creation,
d.owner,
)
)
if item_manufacturer:
frappe.db.sql('''
frappe.db.sql(
"""
INSERT INTO `tabItem Manufacturer`
(`name`, `item_code`, `manufacturer`, `manufacturer_part_no`, `creation`, `owner`)
VALUES {}'''.format(', '.join(['%s'] * len(item_manufacturer))), tuple(item_manufacturer)
VALUES {}""".format(
", ".join(["%s"] * len(item_manufacturer))
),
tuple(item_manufacturer),
)

View File

@@ -2,13 +2,22 @@ import frappe
def execute():
frappe.reload_doc('accounts', 'doctype', 'bank', force=1)
frappe.reload_doc("accounts", "doctype", "bank", force=1)
if frappe.db.table_exists('Bank') and frappe.db.table_exists('Bank Account') and frappe.db.has_column('Bank Account', 'swift_number'):
frappe.db.sql("""
UPDATE `tabBank` b, `tabBank Account` ba
SET b.swift_number = ba.swift_number WHERE b.name = ba.bank
""")
if (
frappe.db.table_exists("Bank")
and frappe.db.table_exists("Bank Account")
and frappe.db.has_column("Bank Account", "swift_number")
):
try:
frappe.db.sql(
"""
UPDATE `tabBank` b, `tabBank Account` ba
SET b.swift_number = ba.swift_number WHERE b.name = ba.bank
"""
)
except Exception as e:
frappe.log_error("Bank to Bank Account patch migration failed")
frappe.reload_doc('accounts', 'doctype', 'bank_account')
frappe.reload_doc('accounts', 'doctype', 'payment_request')
frappe.reload_doc("accounts", "doctype", "bank_account")
frappe.reload_doc("accounts", "doctype", "payment_request")

View File

@@ -6,7 +6,7 @@ import frappe
def execute():
''' Move credit limit and bypass credit limit to the child table of customer credit limit '''
"""Move credit limit and bypass credit limit to the child table of customer credit limit"""
frappe.reload_doc("Selling", "doctype", "Customer Credit Limit")
frappe.reload_doc("Selling", "doctype", "Customer")
frappe.reload_doc("Setup", "doctype", "Customer Group")
@@ -16,28 +16,32 @@ def execute():
move_credit_limit_to_child_table()
def move_credit_limit_to_child_table():
''' maps data from old field to the new field in the child table '''
companies = frappe.get_all("Company", 'name')
def move_credit_limit_to_child_table():
"""maps data from old field to the new field in the child table"""
companies = frappe.get_all("Company", "name")
for doctype in ("Customer", "Customer Group"):
fields = ""
if doctype == "Customer" \
and frappe.db.has_column('Customer', 'bypass_credit_limit_check_at_sales_order'):
if doctype == "Customer" and frappe.db.has_column(
"Customer", "bypass_credit_limit_check_at_sales_order"
):
fields = ", bypass_credit_limit_check_at_sales_order"
credit_limit_records = frappe.db.sql('''
credit_limit_records = frappe.db.sql(
"""
SELECT name, credit_limit {0}
FROM `tab{1}` where credit_limit > 0
'''.format(fields, doctype), as_dict=1) #nosec
""".format(
fields, doctype
),
as_dict=1,
) # nosec
for record in credit_limit_records:
doc = frappe.get_doc(doctype, record.name)
for company in companies:
row = frappe._dict({
'credit_limit': record.credit_limit,
'company': company.name
})
row = frappe._dict({"credit_limit": record.credit_limit, "company": company.name})
if doctype == "Customer":
row.bypass_credit_limit_check = record.bypass_credit_limit_check_at_sales_order

View File

@@ -6,7 +6,7 @@ import frappe
def execute():
''' Move from due_advance_amount to pending_amount '''
"""Move from due_advance_amount to pending_amount"""
if frappe.db.has_column("Employee Advance", "due_advance_amount"):
frappe.db.sql(''' UPDATE `tabEmployee Advance` SET pending_amount=due_advance_amount ''')
if frappe.db.has_column("Employee Advance", "due_advance_amount"):
frappe.db.sql(""" UPDATE `tabEmployee Advance` SET pending_amount=due_advance_amount """)

View File

@@ -12,17 +12,22 @@ def execute():
frappe.reload_doc("accounts", "doctype", "item_tax_template_detail", force=1)
frappe.reload_doc("accounts", "doctype", "item_tax_template", force=1)
existing_templates = frappe.db.sql("""select template.name, details.tax_type, details.tax_rate
existing_templates = frappe.db.sql(
"""select template.name, details.tax_type, details.tax_rate
from `tabItem Tax Template` template, `tabItem Tax Template Detail` details
where details.parent=template.name
""", as_dict=1)
""",
as_dict=1,
)
if len(existing_templates):
for d in existing_templates:
item_tax_templates.setdefault(d.name, {})
item_tax_templates[d.name][d.tax_type] = d.tax_rate
for d in frappe.db.sql("""select parent as item_code, tax_type, tax_rate from `tabItem Tax`""", as_dict=1):
for d in frappe.db.sql(
"""select parent as item_code, tax_type, tax_rate from `tabItem Tax`""", as_dict=1
):
old_item_taxes.setdefault(d.item_code, [])
old_item_taxes[d.item_code].append(d)
@@ -49,7 +54,9 @@ def execute():
item_tax_map[d.tax_type] = d.tax_rate
tax_types = []
item_tax_template_name = get_item_tax_template(item_tax_templates, item_tax_map, item_code, tax_types=tax_types)
item_tax_template_name = get_item_tax_template(
item_tax_templates, item_tax_map, item_code, tax_types=tax_types
)
# update the item tax table
frappe.db.sql("delete from `tabItem Tax` where parent=%s and parenttype='Item'", item_code)
@@ -61,17 +68,29 @@ def execute():
d.db_insert()
doctypes = [
'Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice',
'Supplier Quotation', 'Purchase Order', 'Purchase Receipt', 'Purchase Invoice'
"Quotation",
"Sales Order",
"Delivery Note",
"Sales Invoice",
"Supplier Quotation",
"Purchase Order",
"Purchase Receipt",
"Purchase Invoice",
]
for dt in doctypes:
for d in frappe.db.sql("""select name, parenttype, parent, item_code, item_tax_rate from `tab{0} Item`
for d in frappe.db.sql(
"""select name, parenttype, parent, item_code, item_tax_rate from `tab{0} Item`
where ifnull(item_tax_rate, '') not in ('', '{{}}')
and item_tax_template is NULL""".format(dt), as_dict=1):
and item_tax_template is NULL""".format(
dt
),
as_dict=1,
):
item_tax_map = json.loads(d.item_tax_rate)
item_tax_template_name = get_item_tax_template(item_tax_templates,
item_tax_map, d.item_code, d.parenttype, d.parent, tax_types=tax_types)
item_tax_template_name = get_item_tax_template(
item_tax_templates, item_tax_map, d.item_code, d.parenttype, d.parent, tax_types=tax_types
)
frappe.db.set_value(dt + " Item", d.name, "item_tax_template", item_tax_template_name)
frappe.db.auto_commit_on_many_writes = False
@@ -81,7 +100,10 @@ def execute():
settings.determine_address_tax_category_from = "Billing Address"
settings.save()
def get_item_tax_template(item_tax_templates, item_tax_map, item_code, parenttype=None, parent=None, tax_types=None):
def get_item_tax_template(
item_tax_templates, item_tax_map, item_code, parenttype=None, parent=None, tax_types=None
):
# search for previously created item tax template by comparing tax maps
for template, item_tax_template_map in item_tax_templates.items():
if item_tax_map == item_tax_template_map:
@@ -90,13 +112,26 @@ def get_item_tax_template(item_tax_templates, item_tax_map, item_code, parenttyp
# if no item tax template found, create one
item_tax_template = frappe.new_doc("Item Tax Template")
item_tax_template.title = make_autoname("Item Tax Template-.####")
item_tax_template_name = item_tax_template.title
for tax_type, tax_rate in item_tax_map.items():
account_details = frappe.db.get_value("Account", tax_type, ['name', 'account_type', 'company'], as_dict=1)
account_details = frappe.db.get_value(
"Account", tax_type, ["name", "account_type", "company"], as_dict=1
)
if account_details:
item_tax_template.company = account_details.company
if account_details.account_type not in ('Tax', 'Chargeable', 'Income Account', 'Expense Account', 'Expenses Included In Valuation'):
frappe.db.set_value('Account', account_details.name, 'account_type', 'Chargeable')
if not item_tax_template_name:
# set name once company is set as name is generated from company & title
# setting name is required to update `item_tax_templates` dict
item_tax_template_name = item_tax_template.set_new_name()
if account_details.account_type not in (
"Tax",
"Chargeable",
"Income Account",
"Expense Account",
"Expenses Included In Valuation",
):
frappe.db.set_value("Account", account_details.name, "account_type", "Chargeable")
else:
parts = tax_type.strip().split(" - ")
account_name = " - ".join(parts[:-1])
@@ -104,18 +139,25 @@ def get_item_tax_template(item_tax_templates, item_tax_map, item_code, parenttyp
tax_type = None
else:
company = get_company(parts[-1], parenttype, parent)
parent_account = frappe.get_value("Account", {"account_name": account_name, "company": company}, "parent_account")
parent_account = frappe.get_value(
"Account", {"account_name": account_name, "company": company}, "parent_account"
)
if not parent_account:
parent_account = frappe.db.get_value("Account",
filters={"account_type": "Tax", "root_type": "Liability", "is_group": 0, "company": company}, fieldname="parent_account")
parent_account = frappe.db.get_value(
"Account",
filters={"account_type": "Tax", "root_type": "Liability", "is_group": 0, "company": company},
fieldname="parent_account",
)
if not parent_account:
parent_account = frappe.db.get_value("Account",
filters={"account_type": "Tax", "root_type": "Liability", "is_group": 1, "company": company})
parent_account = frappe.db.get_value(
"Account",
filters={"account_type": "Tax", "root_type": "Liability", "is_group": 1, "company": company},
)
filters = {
"account_name": account_name,
"company": company,
"account_type": "Tax",
"parent_account": parent_account
"parent_account": parent_account,
}
tax_type = frappe.db.get_value("Account", filters)
if not tax_type:
@@ -125,28 +167,38 @@ def get_item_tax_template(item_tax_templates, item_tax_map, item_code, parenttyp
account.insert()
tax_type = account.name
except frappe.DuplicateEntryError:
tax_type = frappe.db.get_value("Account", {"account_name": account_name, "company": company}, "name")
tax_type = frappe.db.get_value(
"Account", {"account_name": account_name, "company": company}, "name"
)
account_type = frappe.get_cached_value("Account", tax_type, "account_type")
if tax_type and account_type in ('Tax', 'Chargeable', 'Income Account', 'Expense Account', 'Expenses Included In Valuation'):
if tax_type and account_type in (
"Tax",
"Chargeable",
"Income Account",
"Expense Account",
"Expenses Included In Valuation",
):
if tax_type not in tax_types:
item_tax_template.append("taxes", {"tax_type": tax_type, "tax_rate": tax_rate})
tax_types.append(tax_type)
item_tax_templates.setdefault(item_tax_template.title, {})
item_tax_templates[item_tax_template.title][tax_type] = tax_rate
item_tax_templates.setdefault(item_tax_template_name, {})
item_tax_templates[item_tax_template_name][tax_type] = tax_rate
if item_tax_template.get("taxes"):
item_tax_template.save()
return item_tax_template.name
def get_company(company_abbr, parenttype=None, parent=None):
if parenttype and parent:
company = frappe.get_cached_value(parenttype, parent, 'company')
company = frappe.get_cached_value(parenttype, parent, "company")
else:
company = frappe.db.get_value("Company", filters={"abbr": company_abbr})
if not company:
companies = frappe.get_all('Company')
companies = frappe.get_all("Company")
if len(companies) == 1:
company = companies[0].name

View File

@@ -12,10 +12,12 @@ def execute():
if not (frappe.conf.plaid_client_id and frappe.conf.plaid_env and frappe.conf.plaid_secret):
plaid_settings.enabled = 0
else:
plaid_settings.update({
"plaid_client_id": frappe.conf.plaid_client_id,
"plaid_env": frappe.conf.plaid_env,
"plaid_secret": frappe.conf.plaid_secret
})
plaid_settings.update(
{
"plaid_client_id": frappe.conf.plaid_client_id,
"plaid_env": frappe.conf.plaid_env,
"plaid_secret": frappe.conf.plaid_secret,
}
)
plaid_settings.flags.ignore_mandatory = True
plaid_settings.save()

View File

@@ -6,19 +6,23 @@ import frappe
def execute():
frappe.reload_doc("setup", "doctype", "target_detail")
frappe.reload_doc("core", "doctype", "prepared_report")
frappe.reload_doc("setup", "doctype", "target_detail")
frappe.reload_doc("core", "doctype", "prepared_report")
for d in ['Sales Person', 'Sales Partner', 'Territory']:
frappe.db.sql("""
for d in ["Sales Person", "Sales Partner", "Territory"]:
frappe.db.sql(
"""
UPDATE `tab{child_doc}`, `tab{parent_doc}`
SET
`tab{child_doc}`.distribution_id = `tab{parent_doc}`.distribution_id
WHERE
`tab{child_doc}`.parent = `tab{parent_doc}`.name
and `tab{parent_doc}`.distribution_id is not null and `tab{parent_doc}`.distribution_id != ''
""".format(parent_doc = d, child_doc = "Target Detail"))
""".format(
parent_doc=d, child_doc="Target Detail"
)
)
frappe.delete_doc("Report", "Sales Partner-wise Transaction Summary")
frappe.delete_doc("Report", "Sales Person Target Variance Item Group-Wise")
frappe.delete_doc("Report", "Territory Target Variance Item Group-Wise")
frappe.delete_doc("Report", "Sales Partner-wise Transaction Summary")
frappe.delete_doc("Report", "Sales Person Target Variance Item Group-Wise")
frappe.delete_doc("Report", "Territory Target Variance Item Group-Wise")

View File

@@ -7,6 +7,7 @@ import frappe
logger = frappe.logger("patch", allow_site=True, file_count=50)
def execute():
affected_purchase_receipts = frappe.db.sql(
"""select name from `tabPurchase Receipt`
@@ -16,13 +17,13 @@ def execute():
if not affected_purchase_receipts:
return
logger.info("purchase_receipt_status: begin patch, PR count: {}"
.format(len(affected_purchase_receipts)))
logger.info(
"purchase_receipt_status: begin patch, PR count: {}".format(len(affected_purchase_receipts))
)
frappe.reload_doc("stock", "doctype", "Purchase Receipt")
frappe.reload_doc("stock", "doctype", "Purchase Receipt Item")
for pr in affected_purchase_receipts:
pr_name = pr[0]
logger.info("purchase_receipt_status: patching PR - {}".format(pr_name))

View File

@@ -4,13 +4,18 @@ from erpnext.stock.stock_balance import get_indented_qty, update_bin_qty
def execute():
bin_details = frappe.db.sql("""
bin_details = frappe.db.sql(
"""
SELECT item_code, warehouse
FROM `tabBin`""",as_dict=1)
FROM `tabBin`""",
as_dict=1,
)
for entry in bin_details:
if not (entry.item_code and entry.warehouse):
continue
update_bin_qty(entry.get("item_code"), entry.get("warehouse"), {
"indented_qty": get_indented_qty(entry.get("item_code"), entry.get("warehouse"))
})
update_bin_qty(
entry.get("item_code"),
entry.get("warehouse"),
{"indented_qty": get_indented_qty(entry.get("item_code"), entry.get("warehouse"))},
)

View File

@@ -4,10 +4,15 @@ import frappe
def execute():
frappe.reload_doc("accounts", "doctype", "tax_category")
frappe.reload_doc("stock", "doctype", "item_manufacturer")
company = frappe.get_all('Company', filters = {'country': 'India'})
company = frappe.get_all("Company", filters={"country": "India"})
if not company:
return
if frappe.db.exists("Custom Field", "Company-bank_remittance_section"):
deprecated_fields = ['bank_remittance_section', 'client_code', 'remittance_column_break', 'product_code']
deprecated_fields = [
"bank_remittance_section",
"client_code",
"remittance_column_break",
"product_code",
]
for i in range(len(deprecated_fields)):
frappe.delete_doc("Custom Field", 'Company-'+deprecated_fields[i])
frappe.delete_doc("Custom Field", "Company-" + deprecated_fields[i])

View File

@@ -6,8 +6,8 @@ import frappe
def execute():
''' Delete leave ledger entry created
via leave applications with status != Approved '''
"""Delete leave ledger entry created
via leave applications with status != Approved"""
if not frappe.db.a_row_exists("Leave Ledger Entry"):
return
@@ -15,14 +15,21 @@ def execute():
if leave_application_list:
delete_denied_leaves_from_leave_ledger_entry(leave_application_list)
def get_denied_leave_application_list():
return frappe.db.sql_list(''' Select name from `tabLeave Application` where status <> 'Approved' ''')
return frappe.db.sql_list(
""" Select name from `tabLeave Application` where status <> 'Approved' """
)
def delete_denied_leaves_from_leave_ledger_entry(leave_application_list):
if leave_application_list:
frappe.db.sql(''' Delete
frappe.db.sql(
""" Delete
FROM `tabLeave Ledger Entry`
WHERE
transaction_type = 'Leave Application'
AND transaction_name in (%s) ''' % (', '.join(['%s'] * len(leave_application_list))), #nosec
tuple(leave_application_list))
AND transaction_name in (%s) """
% (", ".join(["%s"] * len(leave_application_list))), # nosec
tuple(leave_application_list),
)

View File

@@ -7,16 +7,18 @@ import frappe
def execute():
"""Delete duplicate leave ledger entries of type allocation created."""
frappe.reload_doc('hr', 'doctype', 'leave_ledger_entry')
frappe.reload_doc("hr", "doctype", "leave_ledger_entry")
if not frappe.db.a_row_exists("Leave Ledger Entry"):
return
duplicate_records_list = get_duplicate_records()
delete_duplicate_ledger_entries(duplicate_records_list)
def get_duplicate_records():
"""Fetch all but one duplicate records from the list of expired leave allocation."""
return frappe.db.sql("""
return frappe.db.sql(
"""
SELECT name, employee, transaction_name, leave_type, is_carry_forward, from_date, to_date
FROM `tabLeave Ledger Entry`
WHERE
@@ -29,13 +31,17 @@ def get_duplicate_records():
count(name) > 1
ORDER BY
creation
""")
"""
)
def delete_duplicate_ledger_entries(duplicate_records_list):
"""Delete duplicate leave ledger entries."""
if not duplicate_records_list: return
if not duplicate_records_list:
return
for d in duplicate_records_list:
frappe.db.sql('''
frappe.db.sql(
"""
DELETE FROM `tabLeave Ledger Entry`
WHERE name != %s
AND employee = %s
@@ -44,4 +50,6 @@ def delete_duplicate_ledger_entries(duplicate_records_list):
AND is_carry_forward = %s
AND from_date = %s
AND to_date = %s
''', tuple(d))
""",
tuple(d),
)

View File

@@ -2,6 +2,6 @@ import frappe
def execute():
frappe.rename_doc('DocType', 'Account Type', 'Bank Account Type', force=True)
frappe.rename_doc('DocType', 'Account Subtype', 'Bank Account Subtype', force=True)
frappe.reload_doc('accounts', 'doctype', 'bank_account')
frappe.rename_doc("DocType", "Account Type", "Bank Account Type", force=True)
frappe.rename_doc("DocType", "Account Subtype", "Bank Account Subtype", force=True)
frappe.reload_doc("accounts", "doctype", "bank_account")

View File

@@ -7,12 +7,13 @@ from frappe.model.utils.rename_field import rename_field
def execute():
''' Change the fieldname from bank_account_no to bank_account '''
"""Change the fieldname from bank_account_no to bank_account"""
if not frappe.get_meta("Journal Entry Account").has_field("bank_account"):
frappe.reload_doc("Accounts", "doctype", "Journal Entry Account")
update_journal_entry_account_fieldname()
def update_journal_entry_account_fieldname():
''' maps data from old field to the new field '''
if frappe.db.has_column('Journal Entry Account', 'bank_account_no'):
"""maps data from old field to the new field"""
if frappe.db.has_column("Journal Entry Account", "bank_account_no"):
rename_field("Journal Entry Account", "bank_account_no", "bank_account")

View File

@@ -7,8 +7,8 @@ import frappe
def execute():
if frappe.db.table_exists("Bank Reconciliation"):
frappe.rename_doc('DocType', 'Bank Reconciliation', 'Bank Clearance', force=True)
frappe.reload_doc('Accounts', 'doctype', 'Bank Clearance')
frappe.rename_doc("DocType", "Bank Reconciliation", "Bank Clearance", force=True)
frappe.reload_doc("Accounts", "doctype", "Bank Clearance")
frappe.rename_doc('DocType', 'Bank Reconciliation Detail', 'Bank Clearance Detail', force=True)
frappe.reload_doc('Accounts', 'doctype', 'Bank Clearance Detail')
frappe.rename_doc("DocType", "Bank Reconciliation Detail", "Bank Clearance Detail", force=True)
frappe.reload_doc("Accounts", "doctype", "Bank Clearance Detail")

View File

@@ -5,11 +5,24 @@ import frappe
def _rename_single_field(**kwargs):
count = frappe.db.sql("SELECT COUNT(*) FROM tabSingles WHERE doctype='{doctype}' AND field='{new_name}';".format(**kwargs))[0][0] #nosec
count = frappe.db.sql(
"SELECT COUNT(*) FROM tabSingles WHERE doctype='{doctype}' AND field='{new_name}';".format(
**kwargs
)
)[0][
0
] # nosec
if count == 0:
frappe.db.sql("UPDATE tabSingles SET field='{new_name}' WHERE doctype='{doctype}' AND field='{old_name}';".format(**kwargs)) #nosec
frappe.db.sql(
"UPDATE tabSingles SET field='{new_name}' WHERE doctype='{doctype}' AND field='{old_name}';".format(
**kwargs
)
) # nosec
def execute():
_rename_single_field(doctype = "Bank Clearance", old_name = "bank_account" , new_name = "account")
_rename_single_field(doctype = "Bank Clearance", old_name = "bank_account_no", new_name = "bank_account")
_rename_single_field(doctype="Bank Clearance", old_name="bank_account", new_name="account")
_rename_single_field(
doctype="Bank Clearance", old_name="bank_account_no", new_name="bank_account"
)
frappe.reload_doc("Accounts", "doctype", "Bank Clearance")

View File

@@ -2,17 +2,23 @@ import frappe
def execute():
if frappe.db.exists("DocType", "Lost Reason Detail"):
frappe.reload_doc("crm", "doctype", "opportunity_lost_reason")
frappe.reload_doc("crm", "doctype", "opportunity_lost_reason_detail")
frappe.reload_doc("setup", "doctype", "quotation_lost_reason_detail")
if frappe.db.exists("DocType", "Lost Reason Detail"):
frappe.reload_doc("crm", "doctype", "opportunity_lost_reason")
frappe.reload_doc("crm", "doctype", "opportunity_lost_reason_detail")
frappe.reload_doc("setup", "doctype", "quotation_lost_reason_detail")
frappe.db.sql("""INSERT INTO `tabOpportunity Lost Reason Detail` SELECT * FROM `tabLost Reason Detail` WHERE `parenttype` = 'Opportunity'""")
frappe.db.sql(
"""INSERT INTO `tabOpportunity Lost Reason Detail` SELECT * FROM `tabLost Reason Detail` WHERE `parenttype` = 'Opportunity'"""
)
frappe.db.sql("""INSERT INTO `tabQuotation Lost Reason Detail` SELECT * FROM `tabLost Reason Detail` WHERE `parenttype` = 'Quotation'""")
frappe.db.sql(
"""INSERT INTO `tabQuotation Lost Reason Detail` SELECT * FROM `tabLost Reason Detail` WHERE `parenttype` = 'Quotation'"""
)
frappe.db.sql("""INSERT INTO `tabQuotation Lost Reason` (`name`, `creation`, `modified`, `modified_by`, `owner`, `docstatus`, `parent`, `parentfield`, `parenttype`, `idx`, `_comments`, `_assign`, `_user_tags`, `_liked_by`, `order_lost_reason`)
frappe.db.sql(
"""INSERT INTO `tabQuotation Lost Reason` (`name`, `creation`, `modified`, `modified_by`, `owner`, `docstatus`, `parent`, `parentfield`, `parenttype`, `idx`, `_comments`, `_assign`, `_user_tags`, `_liked_by`, `order_lost_reason`)
SELECT o.`name`, o.`creation`, o.`modified`, o.`modified_by`, o.`owner`, o.`docstatus`, o.`parent`, o.`parentfield`, o.`parenttype`, o.`idx`, o.`_comments`, o.`_assign`, o.`_user_tags`, o.`_liked_by`, o.`lost_reason`
FROM `tabOpportunity Lost Reason` o LEFT JOIN `tabQuotation Lost Reason` q ON q.name = o.name WHERE q.name IS NULL""")
FROM `tabOpportunity Lost Reason` o LEFT JOIN `tabQuotation Lost Reason` q ON q.name = o.name WHERE q.name IS NULL"""
)
frappe.delete_doc("DocType", "Lost Reason Detail")
frappe.delete_doc("DocType", "Lost Reason Detail")

View File

@@ -7,17 +7,19 @@ import frappe
def execute():
if frappe.db.table_exists("POS Closing Voucher"):
if not frappe.db.exists("DocType", "POS Closing Entry"):
frappe.rename_doc('DocType', 'POS Closing Voucher', 'POS Closing Entry', force=True)
frappe.rename_doc("DocType", "POS Closing Voucher", "POS Closing Entry", force=True)
if not frappe.db.exists('DocType', 'POS Closing Entry Taxes'):
frappe.rename_doc('DocType', 'POS Closing Voucher Taxes', 'POS Closing Entry Taxes', force=True)
if not frappe.db.exists("DocType", "POS Closing Entry Taxes"):
frappe.rename_doc("DocType", "POS Closing Voucher Taxes", "POS Closing Entry Taxes", force=True)
if not frappe.db.exists('DocType', 'POS Closing Voucher Details'):
frappe.rename_doc('DocType', 'POS Closing Voucher Details', 'POS Closing Entry Detail', force=True)
if not frappe.db.exists("DocType", "POS Closing Voucher Details"):
frappe.rename_doc(
"DocType", "POS Closing Voucher Details", "POS Closing Entry Detail", force=True
)
frappe.reload_doc('Accounts', 'doctype', 'POS Closing Entry')
frappe.reload_doc('Accounts', 'doctype', 'POS Closing Entry Taxes')
frappe.reload_doc('Accounts', 'doctype', 'POS Closing Entry Detail')
frappe.reload_doc("Accounts", "doctype", "POS Closing Entry")
frappe.reload_doc("Accounts", "doctype", "POS Closing Entry Taxes")
frappe.reload_doc("Accounts", "doctype", "POS Closing Entry Detail")
if frappe.db.exists("DocType", "POS Closing Voucher"):
frappe.delete_doc("DocType", "POS Closing Voucher")

View File

@@ -5,16 +5,17 @@
import frappe
doctypes = {
'Price Discount Slab': 'Promotional Scheme Price Discount',
'Product Discount Slab': 'Promotional Scheme Product Discount',
'Apply Rule On Item Code': 'Pricing Rule Item Code',
'Apply Rule On Item Group': 'Pricing Rule Item Group',
'Apply Rule On Brand': 'Pricing Rule Brand'
"Price Discount Slab": "Promotional Scheme Price Discount",
"Product Discount Slab": "Promotional Scheme Product Discount",
"Apply Rule On Item Code": "Pricing Rule Item Code",
"Apply Rule On Item Group": "Pricing Rule Item Group",
"Apply Rule On Brand": "Pricing Rule Brand",
}
def execute():
for old_doc, new_doc in doctypes.items():
if not frappe.db.table_exists(new_doc) and frappe.db.table_exists(old_doc):
frappe.rename_doc('DocType', old_doc, new_doc)
frappe.reload_doc("accounts", "doctype", frappe.scrub(new_doc))
frappe.delete_doc("DocType", old_doc)
for old_doc, new_doc in doctypes.items():
if not frappe.db.table_exists(new_doc) and frappe.db.table_exists(old_doc):
frappe.rename_doc("DocType", old_doc, new_doc)
frappe.reload_doc("accounts", "doctype", frappe.scrub(new_doc))
frappe.delete_doc("DocType", old_doc)

View File

@@ -7,8 +7,8 @@ def execute():
frappe.reload_doc("stock", "doctype", "stock_settings")
frappe.reload_doc("accounts", "doctype", "accounts_settings")
rename_field('Stock Settings', "tolerance", "over_delivery_receipt_allowance")
rename_field('Item', "tolerance", "over_delivery_receipt_allowance")
rename_field("Stock Settings", "tolerance", "over_delivery_receipt_allowance")
rename_field("Item", "tolerance", "over_delivery_receipt_allowance")
qty_allowance = frappe.db.get_single_value("Stock Settings", "over_delivery_receipt_allowance")
frappe.db.set_value("Accounts Settings", None, "over_delivery_receipt_allowance", qty_allowance)

View File

@@ -2,5 +2,7 @@ import frappe
def execute():
frappe.db.sql("""UPDATE `tabUser` SET `home_settings` = REPLACE(`home_settings`, 'Accounting', 'Accounts')""")
frappe.cache().delete_key('home_settings')
frappe.db.sql(
"""UPDATE `tabUser` SET `home_settings` = REPLACE(`home_settings`, 'Accounting', 'Accounts')"""
)
frappe.cache().delete_key("home_settings")

View File

@@ -6,51 +6,79 @@ import frappe
def execute():
warehouse_perm = frappe.get_all("User Permission",
fields=["count(*) as p_count", "is_default", "user"], filters={"allow": "Warehouse"}, group_by="user")
warehouse_perm = frappe.get_all(
"User Permission",
fields=["count(*) as p_count", "is_default", "user"],
filters={"allow": "Warehouse"},
group_by="user",
)
if not warehouse_perm:
return
execute_patch = False
for perm_data in warehouse_perm:
if perm_data.p_count == 1 or (perm_data.p_count > 1 and frappe.get_all("User Permission",
filters = {"user": perm_data.user, "allow": "warehouse", "is_default": 1}, limit=1)):
if perm_data.p_count == 1 or (
perm_data.p_count > 1
and frappe.get_all(
"User Permission",
filters={"user": perm_data.user, "allow": "warehouse", "is_default": 1},
limit=1,
)
):
execute_patch = True
break
if not execute_patch: return
if not execute_patch:
return
for doctype in ["Sales Invoice", "Delivery Note"]:
if not frappe.get_meta(doctype + ' Item').get_field("target_warehouse").hidden: continue
if not frappe.get_meta(doctype + " Item").get_field("target_warehouse").hidden:
continue
cond = ""
if doctype == "Sales Invoice":
cond = " AND parent_doc.update_stock = 1"
data = frappe.db.sql(""" SELECT parent_doc.name as name, child_doc.name as child_name
data = frappe.db.sql(
""" SELECT parent_doc.name as name, child_doc.name as child_name
FROM
`tab{doctype}` parent_doc, `tab{doctype} Item` child_doc
WHERE
parent_doc.name = child_doc.parent AND parent_doc.docstatus < 2
AND child_doc.target_warehouse is not null AND child_doc.target_warehouse != ''
AND child_doc.creation > '2020-04-16' {cond}
""".format(doctype=doctype, cond=cond), as_dict=1)
""".format(
doctype=doctype, cond=cond
),
as_dict=1,
)
if data:
names = [d.child_name for d in data]
frappe.db.sql(""" UPDATE `tab{0} Item` set target_warehouse = null
WHERE name in ({1}) """.format(doctype, ','.join(["%s"] * len(names) )), tuple(names))
frappe.db.sql(
""" UPDATE `tab{0} Item` set target_warehouse = null
WHERE name in ({1}) """.format(
doctype, ",".join(["%s"] * len(names))
),
tuple(names),
)
frappe.db.sql(""" UPDATE `tabPacked Item` set target_warehouse = null
frappe.db.sql(
""" UPDATE `tabPacked Item` set target_warehouse = null
WHERE parenttype = '{0}' and parent_detail_docname in ({1})
""".format(doctype, ','.join(["%s"] * len(names) )), tuple(names))
""".format(
doctype, ",".join(["%s"] * len(names))
),
tuple(names),
)
parent_names = list(set([d.name for d in data]))
for d in parent_names:
doc = frappe.get_doc(doctype, d)
if doc.docstatus != 1: continue
if doc.docstatus != 1:
continue
doc.docstatus = 2
doc.update_stock_ledger()
@@ -61,9 +89,13 @@ def execute():
doc.update_stock_ledger()
doc.make_gl_entries()
if frappe.get_meta('Sales Order Item').get_field("target_warehouse").hidden:
frappe.db.sql(""" UPDATE `tabSales Order Item` set target_warehouse = null
WHERE creation > '2020-04-16' and docstatus < 2 """)
if frappe.get_meta("Sales Order Item").get_field("target_warehouse").hidden:
frappe.db.sql(
""" UPDATE `tabSales Order Item` set target_warehouse = null
WHERE creation > '2020-04-16' and docstatus < 2 """
)
frappe.db.sql(""" UPDATE `tabPacked Item` set target_warehouse = null
WHERE creation > '2020-04-16' and docstatus < 2 and parenttype = 'Sales Order' """)
frappe.db.sql(
""" UPDATE `tabPacked Item` set target_warehouse = null
WHERE creation > '2020-04-16' and docstatus < 2 and parenttype = 'Sales Order' """
)

View File

@@ -3,12 +3,16 @@ import frappe
def execute():
frappe.reload_doc('selling', 'doctype', 'sales_order_item', force=True)
frappe.reload_doc('buying', 'doctype', 'purchase_order_item', force=True)
frappe.reload_doc("selling", "doctype", "sales_order_item", force=True)
frappe.reload_doc("buying", "doctype", "purchase_order_item", force=True)
for doctype in ('Sales Order Item', 'Purchase Order Item'):
frappe.db.sql("""
for doctype in ("Sales Order Item", "Purchase Order Item"):
frappe.db.sql(
"""
UPDATE `tab{0}`
SET against_blanket_order = 1
WHERE ifnull(blanket_order, '') != ''
""".format(doctype))
""".format(
doctype
)
)

View File

@@ -4,4 +4,6 @@ import frappe
def execute():
frappe.reload_doc("accounts", "doctype", "accounts_settings")
frappe.db.set_value("Accounts Settings", None, "automatically_process_deferred_accounting_entry", 1)
frappe.db.set_value(
"Accounts Settings", None, "automatically_process_deferred_accounting_entry", 1
)

View File

@@ -2,9 +2,11 @@ import frappe
def execute():
frappe.reload_doc('hr', 'doctype', 'expense_claim_detail')
frappe.db.sql("""
frappe.reload_doc("hr", "doctype", "expense_claim_detail")
frappe.db.sql(
"""
UPDATE `tabExpense Claim Detail` child, `tabExpense Claim` par
SET child.cost_center = par.cost_center
WHERE child.parent = par.name
""")
"""
)

View File

@@ -3,8 +3,8 @@ from frappe.utils import cint
def execute():
'''Get 'Disable CWIP Accounting value' from Asset Settings, set it in 'Enable Capital Work in Progress Accounting' field
in Company, delete Asset Settings '''
"""Get 'Disable CWIP Accounting value' from Asset Settings, set it in 'Enable Capital Work in Progress Accounting' field
in Company, delete Asset Settings"""
if frappe.db.exists("DocType", "Asset Settings"):
frappe.reload_doctype("Asset Category")

View File

@@ -2,18 +2,22 @@ import frappe
def execute():
frappe.reload_doc("manufacturing", "doctype", "bom_operation")
frappe.reload_doc("manufacturing", "doctype", "work_order_operation")
frappe.reload_doc("manufacturing", "doctype", "bom_operation")
frappe.reload_doc("manufacturing", "doctype", "work_order_operation")
frappe.db.sql("""
frappe.db.sql(
"""
UPDATE
`tabBOM Operation` bo
SET
bo.batch_size = 1
""")
frappe.db.sql("""
"""
)
frappe.db.sql(
"""
UPDATE
`tabWork Order Operation` wop
SET
wop.batch_size = 1
""")
"""
)

View File

@@ -2,4 +2,4 @@ import frappe
def execute():
frappe.db.set_value('Homepage', 'Homepage', 'hero_section_based_on', 'Default')
frappe.db.set_value("Homepage", "Homepage", "hero_section_based_on", "Default")

View File

@@ -2,9 +2,11 @@ import frappe
def execute():
employees = frappe.get_all("Employee",
employees = frappe.get_all(
"Employee",
filters={"prefered_email": ""},
fields=["name", "prefered_contact_email", "company_email", "personal_email", "user_id"])
fields=["name", "prefered_contact_email", "company_email", "personal_email", "user_id"],
)
for employee in employees:
if not employee.prefered_contact_email:
@@ -13,4 +15,6 @@ def execute():
preferred_email_field = frappe.scrub(employee.prefered_contact_email)
preferred_email = employee.get(preferred_email_field)
frappe.db.set_value("Employee", employee.name, "prefered_email", preferred_email, update_modified=False)
frappe.db.set_value(
"Employee", employee.name, "prefered_email", preferred_email, update_modified=False
)

View File

@@ -2,14 +2,19 @@ import frappe
def execute():
frappe.reload_doctype('Landed Cost Taxes and Charges')
frappe.reload_doctype("Landed Cost Taxes and Charges")
company_account_map = frappe._dict(frappe.db.sql("""
company_account_map = frappe._dict(
frappe.db.sql(
"""
SELECT name, expenses_included_in_valuation from `tabCompany`
"""))
"""
)
)
for company, account in company_account_map.items():
frappe.db.sql("""
frappe.db.sql(
"""
UPDATE
`tabLanded Cost Taxes and Charges` t, `tabLanded Cost Voucher` l
SET
@@ -18,9 +23,12 @@ def execute():
l.docstatus = 1
AND l.company = %s
AND t.parent = l.name
""", (account, company))
""",
(account, company),
)
frappe.db.sql("""
frappe.db.sql(
"""
UPDATE
`tabLanded Cost Taxes and Charges` t, `tabStock Entry` s
SET
@@ -29,4 +37,6 @@ def execute():
s.docstatus = 1
AND s.company = %s
AND t.parent = s.name
""", (account, company))
""",
(account, company),
)

View File

@@ -4,9 +4,11 @@ import frappe
def execute():
frappe.reload_doc("hr", "doctype", "job_offer")
frappe.db.sql("""
frappe.db.sql(
"""
UPDATE
`tabJob Offer` AS offer
SET
applicant_email = (SELECT email_id FROM `tabJob Applicant` WHERE name = offer.job_applicant)
""")
"""
)

View File

@@ -3,9 +3,11 @@ import frappe
def execute():
frappe.reload_doc("crm", "doctype", "lead")
frappe.db.sql("""
frappe.db.sql(
"""
UPDATE
`tabLead`
SET
title = IF(organization_lead = 1, company_name, lead_name)
""")
"""
)

View File

@@ -6,10 +6,12 @@ import frappe
def execute():
frappe.reload_doc('buying', 'doctype', 'request_for_quotation_item')
frappe.reload_doc("buying", "doctype", "request_for_quotation_item")
frappe.db.sql("""UPDATE `tabRequest for Quotation Item`
frappe.db.sql(
"""UPDATE `tabRequest for Quotation Item`
SET
stock_uom = uom,
conversion_factor = 1,
stock_qty = qty""")
stock_qty = qty"""
)

View File

@@ -3,8 +3,10 @@ import frappe
def execute():
frappe.reload_doctype("Payment Entry")
frappe.db.sql("""update `tabPayment Entry` set status = CASE
frappe.db.sql(
"""update `tabPayment Entry` set status = CASE
WHEN docstatus = 1 THEN 'Submitted'
WHEN docstatus = 2 THEN 'Cancelled'
ELSE 'Draft'
END;""")
END;"""
)

View File

@@ -5,7 +5,7 @@ from erpnext.regional.italy.setup import make_custom_fields
def execute():
company = frappe.get_all('Company', filters = {'country': 'Italy'})
company = frappe.get_all("Company", filters={"country": "Italy"})
if not company:
return
@@ -14,6 +14,6 @@ def execute():
frappe.reload_doc("regional", "doctype", "import_supplier_invoice")
add_permission('Import Supplier Invoice', 'Accounts Manager', 0)
update_permission_property('Import Supplier Invoice', 'Accounts Manager', 0, 'write', 1)
update_permission_property('Import Supplier Invoice', 'Accounts Manager', 0, 'create', 1)
add_permission("Import Supplier Invoice", "Accounts Manager", 0)
update_permission_property("Import Supplier Invoice", "Accounts Manager", 0, "write", 1)
update_permission_property("Import Supplier Invoice", "Accounts Manager", 0, "create", 1)

View File

@@ -4,21 +4,20 @@ import frappe
def execute():
frappe.reload_doc("support", "doctype", "issue_priority")
frappe.reload_doc("support", "doctype", "service_level_priority")
frappe.reload_doc('support', 'doctype', 'issue')
frappe.reload_doc("support", "doctype", "issue")
set_issue_priority()
set_priority_for_issue()
set_priorities_service_level()
set_priorities_service_level_agreement()
def set_issue_priority():
# Adds priority from issue to Issue Priority DocType as Priority is a new DocType.
for priority in frappe.get_meta("Issue").get_field("priority").options.split("\n"):
if priority and not frappe.db.exists("Issue Priority", priority):
frappe.get_doc({
"doctype": "Issue Priority",
"name": priority
}).insert(ignore_permissions=True)
frappe.get_doc({"doctype": "Issue Priority", "name": priority}).insert(ignore_permissions=True)
def set_priority_for_issue():
# Sets priority for Issues as Select field is changed to Link field.
@@ -28,38 +27,63 @@ def set_priority_for_issue():
for issue in issue_priority:
frappe.db.set_value("Issue", issue.name, "priority", issue.priority)
def set_priorities_service_level():
# Migrates "priority", "response_time", "response_time_period", "resolution_time", "resolution_time_period" to Child Table
# as a Service Level can have multiple priorities
try:
service_level_priorities = frappe.get_list("Service Level", fields=["name", "priority", "response_time", "response_time_period", "resolution_time", "resolution_time_period"])
service_level_priorities = frappe.get_list(
"Service Level",
fields=[
"name",
"priority",
"response_time",
"response_time_period",
"resolution_time",
"resolution_time_period",
],
)
frappe.reload_doc("support", "doctype", "service_level")
frappe.reload_doc("support", "doctype", "support_settings")
frappe.db.set_value('Support Settings', None, 'track_service_level_agreement', 1)
frappe.db.set_value("Support Settings", None, "track_service_level_agreement", 1)
for service_level in service_level_priorities:
if service_level:
doc = frappe.get_doc("Service Level", service_level.name)
if not doc.priorities:
doc.append("priorities", {
"priority": service_level.priority,
"default_priority": 1,
"response_time": service_level.response_time,
"response_time_period": service_level.response_time_period,
"resolution_time": service_level.resolution_time,
"resolution_time_period": service_level.resolution_time_period
})
doc.append(
"priorities",
{
"priority": service_level.priority,
"default_priority": 1,
"response_time": service_level.response_time,
"response_time_period": service_level.response_time_period,
"resolution_time": service_level.resolution_time,
"resolution_time_period": service_level.resolution_time_period,
},
)
doc.flags.ignore_validate = True
doc.save(ignore_permissions=True)
except frappe.db.TableMissingError:
frappe.reload_doc("support", "doctype", "service_level")
def set_priorities_service_level_agreement():
# Migrates "priority", "response_time", "response_time_period", "resolution_time", "resolution_time_period" to Child Table
# as a Service Level Agreement can have multiple priorities
try:
service_level_agreement_priorities = frappe.get_list("Service Level Agreement", fields=["name", "priority", "response_time", "response_time_period", "resolution_time", "resolution_time_period"])
service_level_agreement_priorities = frappe.get_list(
"Service Level Agreement",
fields=[
"name",
"priority",
"response_time",
"response_time_period",
"resolution_time",
"resolution_time_period",
],
)
frappe.reload_doc("support", "doctype", "service_level_agreement")
@@ -71,14 +95,17 @@ def set_priorities_service_level_agreement():
doc.entity_type = "Customer"
doc.entity = doc.customer
doc.append("priorities", {
"priority": service_level_agreement.priority,
"default_priority": 1,
"response_time": service_level_agreement.response_time,
"response_time_period": service_level_agreement.response_time_period,
"resolution_time": service_level_agreement.resolution_time,
"resolution_time_period": service_level_agreement.resolution_time_period
})
doc.append(
"priorities",
{
"priority": service_level_agreement.priority,
"default_priority": 1,
"response_time": service_level_agreement.response_time,
"response_time_period": service_level_agreement.response_time_period,
"resolution_time": service_level_agreement.resolution_time,
"resolution_time_period": service_level_agreement.resolution_time_period,
},
)
doc.flags.ignore_validate = True
doc.save(ignore_permissions=True)
except frappe.db.TableMissingError:

View File

@@ -4,12 +4,14 @@ from erpnext.selling.doctype.sales_order.sales_order import update_produced_qty_
def execute():
frappe.reload_doctype('Sales Order Item')
frappe.reload_doctype('Sales Order')
frappe.reload_doctype("Sales Order Item")
frappe.reload_doctype("Sales Order")
for d in frappe.get_all('Work Order',
fields = ['sales_order', 'sales_order_item'],
filters={'sales_order': ('!=', ''), 'sales_order_item': ('!=', '')}):
for d in frappe.get_all(
"Work Order",
fields=["sales_order", "sales_order_item"],
filters={"sales_order": ("!=", ""), "sales_order_item": ("!=", "")},
):
# update produced qty in sales order
update_produced_qty_in_so_item(d.sales_order, d.sales_order_item)

View File

@@ -2,7 +2,9 @@ import frappe
def execute():
frappe.reload_doc("manufacturing", "doctype", "workstation")
frappe.reload_doc("manufacturing", "doctype", "workstation")
frappe.db.sql(""" UPDATE `tabWorkstation`
SET production_capacity = 1 """)
frappe.db.sql(
""" UPDATE `tabWorkstation`
SET production_capacity = 1 """
)

View File

@@ -5,29 +5,36 @@ import frappe
def execute():
frappe.reload_doc('stock', 'doctype', 'delivery_note_item', force=True)
frappe.reload_doc('stock', 'doctype', 'purchase_receipt_item', force=True)
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
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:
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')
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
@@ -42,12 +49,17 @@ def execute():
"""Returns a map of documents and it's return documents.
Format => { 'document' : ['return_document_1','return_document_2'] }"""
return_against_documents = frappe.db.sql("""
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
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)
@@ -58,7 +70,7 @@ def execute():
"""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"
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)
@@ -67,25 +79,27 @@ def execute():
count = 0
#iterate through original documents and its return documents
# 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
# 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:
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'))
mapped.append(doc_item.get("name"))
break
else:
continue
# commit after every 100 sql updates
count += 1
if count%100 == 0:
if count % 100 == 0:
frappe.db.commit()
set_document_detail_in_return_document("Purchase Receipt")

View File

@@ -3,5 +3,7 @@ import frappe
def execute():
frappe.db.sql(""" UPDATE `tabQuotation` set status = 'Open'
where docstatus = 1 and status = 'Submitted' """)
frappe.db.sql(
""" UPDATE `tabQuotation` set status = 'Open'
where docstatus = 1 and status = 'Submitted' """
)

View File

@@ -2,13 +2,16 @@ import frappe
def execute():
purchase_receipts = frappe.db.sql("""
purchase_receipts = frappe.db.sql(
"""
SELECT
parent from `tabPurchase Receipt Item`
WHERE
material_request is not null
AND docstatus=1
""",as_dict=1)
""",
as_dict=1,
)
purchase_receipts = set([d.parent for d in purchase_receipts])
@@ -16,15 +19,15 @@ def execute():
doc = frappe.get_doc("Purchase Receipt", pr)
doc.status_updater = [
{
'source_dt': 'Purchase Receipt Item',
'target_dt': 'Material Request Item',
'join_field': 'material_request_item',
'target_field': 'received_qty',
'target_parent_dt': 'Material Request',
'target_parent_field': 'per_received',
'target_ref_field': 'stock_qty',
'source_field': 'stock_qty',
'percent_join_field': 'material_request'
"source_dt": "Purchase Receipt Item",
"target_dt": "Material Request Item",
"join_field": "material_request_item",
"target_field": "received_qty",
"target_parent_dt": "Material Request",
"target_parent_field": "per_received",
"target_ref_field": "stock_qty",
"source_field": "stock_qty",
"percent_join_field": "material_request",
}
]
doc.update_qty()

View File

@@ -3,17 +3,22 @@ from frappe.utils import getdate, nowdate
def execute():
frappe.reload_doc('stock', 'doctype', 'serial_no')
frappe.reload_doc("stock", "doctype", "serial_no")
serial_no_list = frappe.db.sql("""select name, delivery_document_type, warranty_expiry_date, warehouse from `tabSerial No`
where (status is NULL OR status='')""", as_dict = 1)
serial_no_list = frappe.db.sql(
"""select name, delivery_document_type, warranty_expiry_date, warehouse from `tabSerial No`
where (status is NULL OR status='')""",
as_dict=1,
)
if len(serial_no_list) > 20000:
frappe.db.auto_commit_on_many_writes = True
for serial_no in serial_no_list:
if serial_no.get("delivery_document_type"):
status = "Delivered"
elif serial_no.get("warranty_expiry_date") and getdate(serial_no.get("warranty_expiry_date")) <= getdate(nowdate()):
elif serial_no.get("warranty_expiry_date") and getdate(
serial_no.get("warranty_expiry_date")
) <= getdate(nowdate()):
status = "Expired"
elif not serial_no.get("warehouse"):
status = "Inactive"

View File

@@ -2,14 +2,16 @@ import frappe
def execute():
frappe.reload_doctype('Task')
frappe.reload_doctype("Task")
# add "Completed" if customized
property_setter_name = frappe.db.exists('Property Setter', dict(doc_type='Task', field_name = 'status', property = 'options'))
property_setter_name = frappe.db.exists(
"Property Setter", dict(doc_type="Task", field_name="status", property="options")
)
if property_setter_name:
property_setter = frappe.get_doc('Property Setter', property_setter_name)
property_setter = frappe.get_doc("Property Setter", property_setter_name)
if not "Completed" in property_setter.value:
property_setter.value = property_setter.value + '\nCompleted'
property_setter.value = property_setter.value + "\nCompleted"
property_setter.save()
# renamed default status to Completed as status "Closed" is ambiguous

View File

@@ -5,7 +5,12 @@ def execute():
frappe.reload_doc("stock", "doctype", "batch")
for batch in frappe.get_all("Batch", fields=["name", "batch_id"]):
batch_qty = frappe.db.get_value("Stock Ledger Entry",
{"docstatus": 1, "batch_no": batch.batch_id, "is_cancelled": 0},
"sum(actual_qty)") or 0.0
batch_qty = (
frappe.db.get_value(
"Stock Ledger Entry",
{"docstatus": 1, "batch_no": batch.batch_id, "is_cancelled": 0},
"sum(actual_qty)",
)
or 0.0
)
frappe.db.set_value("Batch", batch.name, "batch_qty", batch_qty, update_modified=False)

View File

@@ -6,6 +6,8 @@ import frappe
def execute():
frappe.reload_doc("stock", "doctype", "pick_list")
frappe.db.sql("""UPDATE `tabPick List` set purpose = 'Delivery'
WHERE docstatus = 1 and purpose = 'Delivery against Sales Order' """)
frappe.reload_doc("stock", "doctype", "pick_list")
frappe.db.sql(
"""UPDATE `tabPick List` set purpose = 'Delivery'
WHERE docstatus = 1 and purpose = 'Delivery against Sales Order' """
)

View File

@@ -3,6 +3,8 @@ import frappe
def execute():
frappe.reload_doc("buying", "doctype", "supplier_quotation")
frappe.db.sql("""UPDATE `tabSupplier Quotation`
frappe.db.sql(
"""UPDATE `tabSupplier Quotation`
SET valid_till = DATE_ADD(transaction_date , INTERVAL 1 MONTH)
WHERE docstatus < 2""")
WHERE docstatus < 2"""
)

View File

@@ -2,7 +2,6 @@
# License: GNU General Public License v3. See license.txt
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
@@ -10,44 +9,61 @@ from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
def execute():
create_stock_entry_types()
company = frappe.db.get_value("Company", {'country': 'India'}, 'name')
company = frappe.db.get_value("Company", {"country": "India"}, "name")
if company:
add_gst_hsn_code_field()
def create_stock_entry_types():
frappe.reload_doc('stock', 'doctype', 'stock_entry_type')
frappe.reload_doc('stock', 'doctype', 'stock_entry')
frappe.reload_doc("stock", "doctype", "stock_entry_type")
frappe.reload_doc("stock", "doctype", "stock_entry")
for purpose in ["Material Issue", "Material Receipt", "Material Transfer",
"Material Transfer for Manufacture", "Material Consumption for Manufacture", "Manufacture",
"Repack", "Send to Subcontractor"]:
for purpose in [
"Material Issue",
"Material Receipt",
"Material Transfer",
"Material Transfer for Manufacture",
"Material Consumption for Manufacture",
"Manufacture",
"Repack",
"Send to Subcontractor",
]:
ste_type = frappe.get_doc({
'doctype': 'Stock Entry Type',
'name': purpose,
'purpose': purpose
})
ste_type = frappe.get_doc({"doctype": "Stock Entry Type", "name": purpose, "purpose": purpose})
try:
ste_type.insert()
except frappe.DuplicateEntryError:
pass
frappe.db.sql(" UPDATE `tabStock Entry` set purpose = 'Send to Subcontractor' where purpose = 'Subcontract'")
frappe.db.sql(
" UPDATE `tabStock Entry` set purpose = 'Send to Subcontractor' where purpose = 'Subcontract'"
)
frappe.db.sql(" UPDATE `tabStock Entry` set stock_entry_type = purpose ")
def add_gst_hsn_code_field():
custom_fields = {
'Stock Entry Detail': [dict(fieldname='gst_hsn_code', label='HSN/SAC',
fieldtype='Data', fetch_from='item_code.gst_hsn_code',
insert_after='description', allow_on_submit=1, print_hide=0)]
"Stock Entry Detail": [
dict(
fieldname="gst_hsn_code",
label="HSN/SAC",
fieldtype="Data",
fetch_from="item_code.gst_hsn_code",
insert_after="description",
allow_on_submit=1,
print_hide=0,
)
]
}
create_custom_fields(custom_fields, ignore_validate = frappe.flags.in_patch, update=True)
create_custom_fields(custom_fields, ignore_validate=frappe.flags.in_patch, update=True)
frappe.db.sql(""" update `tabStock Entry Detail`, `tabItem`
frappe.db.sql(
""" update `tabStock Entry Detail`, `tabItem`
SET
`tabStock Entry Detail`.gst_hsn_code = `tabItem`.gst_hsn_code
Where
`tabItem`.name = `tabStock Entry Detail`.item_code and `tabItem`.gst_hsn_code is not null
""")
"""
)

View File

@@ -6,9 +6,11 @@ import frappe
def execute():
frappe.db.sql("""
frappe.db.sql(
"""
DELETE FROM `tabProperty Setter`
WHERE doc_type in ('Sales Invoice', 'Purchase Invoice', 'Payment Entry')
AND field_name = 'cost_center'
AND property = 'hidden'
""")
"""
)

View File

@@ -2,27 +2,29 @@ import frappe
def execute():
"""
set proper customer and supplier details for item price
based on selling and buying values
"""
"""
set proper customer and supplier details for item price
based on selling and buying values
"""
# update for selling
frappe.db.sql(
"""UPDATE `tabItem Price` ip, `tabPrice List` pl
# update for selling
frappe.db.sql(
"""UPDATE `tabItem Price` ip, `tabPrice List` pl
SET ip.`reference` = ip.`customer`, ip.`supplier` = NULL
WHERE ip.`selling` = 1
AND ip.`buying` = 0
AND (ip.`supplier` IS NOT NULL OR ip.`supplier` = '')
AND ip.`price_list` = pl.`name`
AND pl.`enabled` = 1""")
AND pl.`enabled` = 1"""
)
# update for buying
frappe.db.sql(
"""UPDATE `tabItem Price` ip, `tabPrice List` pl
# update for buying
frappe.db.sql(
"""UPDATE `tabItem Price` ip, `tabPrice List` pl
SET ip.`reference` = ip.`supplier`, ip.`customer` = NULL
WHERE ip.`selling` = 0
AND ip.`buying` = 1
AND (ip.`customer` IS NOT NULL OR ip.`customer` = '')
AND ip.`price_list` = pl.`name`
AND pl.`enabled` = 1""")
AND pl.`enabled` = 1"""
)

View File

@@ -10,11 +10,15 @@ def execute():
if doctype == "Material Request":
condition = " and doc.per_ordered < 100 and doc.material_request_type = 'Manufacture'"
frappe.db.sql(""" UPDATE `tab{doc}` as doc, `tab{doc} Item` as child_doc, tabItem as item
frappe.db.sql(
""" UPDATE `tab{doc}` as doc, `tab{doc} Item` as child_doc, tabItem as item
SET
child_doc.bom_no = item.default_bom
WHERE
child_doc.item_code = item.name and child_doc.docstatus < 2
and child_doc.parent = doc.name
and item.default_bom is not null and item.default_bom != '' {cond}
""".format(doc = doctype, cond = condition))
""".format(
doc=doctype, cond=condition
)
)

View File

@@ -2,16 +2,19 @@ import frappe
def execute():
frappe.reload_doc("accounts", "doctype", "gl_entry")
frappe.reload_doc("accounts", "doctype", "gl_entry")
for doctype in ["Sales Invoice", "Purchase Invoice", "Journal Entry"]:
frappe.reload_doc("accounts", "doctype", frappe.scrub(doctype))
for doctype in ["Sales Invoice", "Purchase Invoice", "Journal Entry"]:
frappe.reload_doc("accounts", "doctype", frappe.scrub(doctype))
frappe.db.sql(""" UPDATE `tabGL Entry`, `tab{doctype}`
frappe.db.sql(
""" UPDATE `tabGL Entry`, `tab{doctype}`
SET
`tabGL Entry`.due_date = `tab{doctype}`.due_date
WHERE
`tabGL Entry`.voucher_no = `tab{doctype}`.name and `tabGL Entry`.party is not null
and `tabGL Entry`.voucher_type in ('Sales Invoice', 'Purchase Invoice', 'Journal Entry')
and `tabGL Entry`.account in (select name from `tabAccount` where account_type in ('Receivable', 'Payable'))""" #nosec
.format(doctype=doctype))
and `tabGL Entry`.account in (select name from `tabAccount` where account_type in ('Receivable', 'Payable'))""".format( # nosec
doctype=doctype
)
)

View File

@@ -3,22 +3,22 @@ from frappe.utils import add_days, getdate, today
def execute():
if frappe.db.exists('DocType', 'Email Campaign'):
email_campaign = frappe.get_all('Email Campaign')
for campaign in email_campaign:
doc = frappe.get_doc("Email Campaign",campaign["name"])
send_after_days = []
if frappe.db.exists("DocType", "Email Campaign"):
email_campaign = frappe.get_all("Email Campaign")
for campaign in email_campaign:
doc = frappe.get_doc("Email Campaign", campaign["name"])
send_after_days = []
camp = frappe.get_doc("Campaign", doc.campaign_name)
for entry in camp.get("campaign_schedules"):
send_after_days.append(entry.send_after_days)
if send_after_days:
end_date = add_days(getdate(doc.start_date), max(send_after_days))
doc.db_set("end_date", end_date)
today_date = getdate(today())
if doc.start_date > today_date:
doc.db_set("status", "Scheduled")
elif end_date >= today_date:
doc.db_set("status", "In Progress")
elif end_date < today_date:
doc.db_set("status", "Completed")
camp = frappe.get_doc("Campaign", doc.campaign_name)
for entry in camp.get("campaign_schedules"):
send_after_days.append(entry.send_after_days)
if send_after_days:
end_date = add_days(getdate(doc.start_date), max(send_after_days))
doc.db_set("end_date", end_date)
today_date = getdate(today())
if doc.start_date > today_date:
doc.db_set("status", "Scheduled")
elif end_date >= today_date:
doc.db_set("status", "In Progress")
elif end_date < today_date:
doc.db_set("status", "Completed")

View File

@@ -1,136 +0,0 @@
import frappe
from frappe.model.utils.rename_field import rename_field
from frappe.modules import get_doctype_module, scrub
field_rename_map = {
'Healthcare Settings': [
['patient_master_name', 'patient_name_by'],
['max_visit', 'max_visits'],
['reg_sms', 'send_registration_msg'],
['reg_msg', 'registration_msg'],
['app_con', 'send_appointment_confirmation'],
['app_con_msg', 'appointment_confirmation_msg'],
['no_con', 'avoid_confirmation'],
['app_rem', 'send_appointment_reminder'],
['app_rem_msg', 'appointment_reminder_msg'],
['rem_before', 'remind_before'],
['manage_customer', 'link_customer_to_patient'],
['create_test_on_si_submit', 'create_lab_test_on_si_submit'],
['require_sample_collection', 'create_sample_collection_for_lab_test'],
['require_test_result_approval', 'lab_test_approval_required'],
['manage_appointment_invoice_automatically', 'automate_appointment_invoicing']
],
'Drug Prescription':[
['use_interval', 'usage_interval'],
['in_every', 'interval_uom']
],
'Lab Test Template':[
['sample_quantity', 'sample_qty'],
['sample_collection_details', 'sample_details']
],
'Sample Collection':[
['sample_quantity', 'sample_qty'],
['sample_collection_details', 'sample_details']
],
'Fee Validity': [
['max_visit', 'max_visits']
]
}
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)
""")

View File

@@ -2,28 +2,35 @@ import frappe
def execute():
#handle type casting for is_cancelled field
# handle type casting for is_cancelled field
module_doctypes = (
('stock', 'Stock Ledger Entry'),
('stock', 'Serial No'),
('accounts', 'GL Entry')
("stock", "Stock Ledger Entry"),
("stock", "Serial No"),
("accounts", "GL Entry"),
)
for module, doctype in module_doctypes:
if (not frappe.db.has_column(doctype, "is_cancelled")
if (
not frappe.db.has_column(doctype, "is_cancelled")
or frappe.db.get_column_type(doctype, "is_cancelled").lower() == "int(1)"
):
continue
frappe.db.sql("""
frappe.db.sql(
"""
UPDATE `tab{doctype}`
SET is_cancelled = 0
where is_cancelled in ('', NULL, 'No')"""
.format(doctype=doctype))
frappe.db.sql("""
where is_cancelled in ('', 'No') or is_cancelled is NULL""".format(
doctype=doctype
)
)
frappe.db.sql(
"""
UPDATE `tab{doctype}`
SET is_cancelled = 1
where is_cancelled = 'Yes'"""
.format(doctype=doctype))
where is_cancelled = 'Yes'""".format(
doctype=doctype
)
)
frappe.reload_doc(module, "doctype", frappe.scrub(doctype))

View File

@@ -2,12 +2,12 @@ import frappe
def execute():
frappe.reload_doc('accounts', 'doctype', 'item_tax_template')
frappe.reload_doc("accounts", "doctype", "item_tax_template")
item_tax_template_list = frappe.get_list('Item Tax Template')
for template in item_tax_template_list:
doc = frappe.get_doc('Item Tax Template', template.name)
for tax in doc.taxes:
doc.company = frappe.get_value('Account', tax.tax_type, 'company')
break
doc.save()
item_tax_template_list = frappe.get_list("Item Tax Template")
for template in item_tax_template_list:
doc = frappe.get_doc("Item Tax Template", template.name)
for tax in doc.taxes:
doc.company = frappe.get_value("Account", tax.tax_type, "company")
break
doc.save()

View File

@@ -6,15 +6,21 @@ from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
def execute():
accounting_dimensions = frappe.db.sql("""select fieldname from
`tabAccounting Dimension`""", as_dict=1)
accounting_dimensions = frappe.db.sql(
"""select fieldname from
`tabAccounting Dimension`""",
as_dict=1,
)
doclist = get_doctypes_with_dimensions()
for dimension in accounting_dimensions:
frappe.db.sql("""
frappe.db.sql(
"""
UPDATE `tabCustom Field`
SET owner = 'Administrator'
WHERE fieldname = %s
AND dt IN (%s)""" % #nosec
('%s', ', '.join(['%s']* len(doclist))), tuple([dimension.fieldname] + doclist))
AND dt IN (%s)"""
% ("%s", ", ".join(["%s"] * len(doclist))), # nosec
tuple([dimension.fieldname] + doclist),
)

View File

@@ -8,16 +8,19 @@ def execute():
frappe.reload_doc("manufacturing", "doctype", "bom")
frappe.reload_doc("manufacturing", "doctype", "bom_item")
frappe.db.sql(""" UPDATE `tabBOM`, `tabPrice List`
frappe.db.sql(
""" UPDATE `tabBOM`, `tabPrice List`
SET
`tabBOM`.price_list_currency = `tabPrice List`.currency,
`tabBOM`.plc_conversion_rate = 1.0
WHERE
`tabBOM`.buying_price_list = `tabPrice List`.name AND `tabBOM`.docstatus < 2
AND `tabBOM`.rm_cost_as_per = 'Price List'
""")
"""
)
for d in frappe.db.sql("""
for d in frappe.db.sql(
"""
SELECT
bom.creation, bom.name, bom.price_list_currency as currency,
company.default_currency as company_currency
@@ -25,8 +28,11 @@ def execute():
`tabBOM` as bom, `tabCompany` as company
WHERE
bom.company = company.name AND bom.rm_cost_as_per = 'Price List' AND
bom.price_list_currency != company.default_currency AND bom.docstatus < 2""", as_dict=1):
plc_conversion_rate = get_exchange_rate(d.currency,
d.company_currency, getdate(d.creation), "for_buying")
bom.price_list_currency != company.default_currency AND bom.docstatus < 2""",
as_dict=1,
):
plc_conversion_rate = get_exchange_rate(
d.currency, d.company_currency, getdate(d.creation), "for_buying"
)
frappe.db.set_value("BOM", d.name, "plc_conversion_rate", plc_conversion_rate)
frappe.db.set_value("BOM", d.name, "plc_conversion_rate", plc_conversion_rate)

View File

@@ -4,5 +4,7 @@ import frappe
def execute():
frappe.reload_doc("accounts", "doctype", "pricing_rule")
frappe.db.sql(""" UPDATE `tabPricing Rule` SET price_or_product_discount = 'Price'
WHERE ifnull(price_or_product_discount,'') = '' """)
frappe.db.sql(
""" UPDATE `tabPricing Rule` SET price_or_product_discount = 'Price'
WHERE ifnull(price_or_product_discount,'') = '' """
)

View File

@@ -4,68 +4,120 @@
import frappe
parentfield = {
'item_code': 'items',
'item_group': 'item_groups',
'brand': 'brands'
}
parentfield = {"item_code": "items", "item_group": "item_groups", "brand": "brands"}
def execute():
if not frappe.get_all('Pricing Rule', limit=1):
if not frappe.get_all("Pricing Rule", limit=1):
return
frappe.reload_doc('accounts', 'doctype', 'pricing_rule_detail')
doctypes = {'Supplier Quotation': 'buying', 'Purchase Order': 'buying', 'Purchase Invoice': 'accounts',
'Purchase Receipt': 'stock', 'Quotation': 'selling', 'Sales Order': 'selling',
'Sales Invoice': 'accounts', 'Delivery Note': 'stock'}
frappe.reload_doc("accounts", "doctype", "pricing_rule_detail")
doctypes = {
"Supplier Quotation": "buying",
"Purchase Order": "buying",
"Purchase Invoice": "accounts",
"Purchase Receipt": "stock",
"Quotation": "selling",
"Sales Order": "selling",
"Sales Invoice": "accounts",
"Delivery Note": "stock",
}
for doctype, module in doctypes.items():
frappe.reload_doc(module, 'doctype', frappe.scrub(doctype))
frappe.reload_doc(module, "doctype", frappe.scrub(doctype))
child_doc = frappe.scrub(doctype) + '_item'
frappe.reload_doc(module, 'doctype', child_doc, force=True)
child_doc = frappe.scrub(doctype) + "_item"
frappe.reload_doc(module, "doctype", child_doc, force=True)
child_doctype = doctype + ' Item'
child_doctype = doctype + " Item"
frappe.db.sql(""" UPDATE `tab{child_doctype}` SET pricing_rules = pricing_rule
frappe.db.sql(
""" UPDATE `tab{child_doctype}` SET pricing_rules = pricing_rule
WHERE docstatus < 2 and pricing_rule is not null and pricing_rule != ''
""".format(child_doctype= child_doctype))
""".format(
child_doctype=child_doctype
)
)
data = frappe.db.sql(""" SELECT pricing_rule, name, parent,
data = frappe.db.sql(
""" SELECT pricing_rule, name, parent,
parenttype, creation, modified, docstatus, modified_by, owner, name
FROM `tab{child_doc}` where docstatus < 2 and pricing_rule is not null
and pricing_rule != ''""".format(child_doc=child_doctype), as_dict=1)
and pricing_rule != ''""".format(
child_doc=child_doctype
),
as_dict=1,
)
values = []
for d in data:
values.append((d.pricing_rule, d.name, d.parent, 'pricing_rules', d.parenttype,
d.creation, d.modified, d.docstatus, d.modified_by, d.owner, frappe.generate_hash("", 10)))
values.append(
(
d.pricing_rule,
d.name,
d.parent,
"pricing_rules",
d.parenttype,
d.creation,
d.modified,
d.docstatus,
d.modified_by,
d.owner,
frappe.generate_hash("", 10),
)
)
if values:
frappe.db.sql(""" INSERT INTO
frappe.db.sql(
""" INSERT INTO
`tabPricing Rule Detail` (`pricing_rule`, `child_docname`, `parent`, `parentfield`, `parenttype`,
`creation`, `modified`, `docstatus`, `modified_by`, `owner`, `name`)
VALUES {values} """.format(values=', '.join(['%s'] * len(values))), tuple(values))
VALUES {values} """.format(
values=", ".join(["%s"] * len(values))
),
tuple(values),
)
frappe.reload_doc('accounts', 'doctype', 'pricing_rule')
frappe.reload_doc("accounts", "doctype", "pricing_rule")
for doctype, apply_on in {'Pricing Rule Item Code': 'Item Code',
'Pricing Rule Item Group': 'Item Group', 'Pricing Rule Brand': 'Brand'}.items():
frappe.reload_doc('accounts', 'doctype', frappe.scrub(doctype))
for doctype, apply_on in {
"Pricing Rule Item Code": "Item Code",
"Pricing Rule Item Group": "Item Group",
"Pricing Rule Brand": "Brand",
}.items():
frappe.reload_doc("accounts", "doctype", frappe.scrub(doctype))
field = frappe.scrub(apply_on)
data = frappe.get_all('Pricing Rule', fields=[field, "name", "creation", "modified",
"owner", "modified_by"], filters= {'apply_on': apply_on})
data = frappe.get_all(
"Pricing Rule",
fields=[field, "name", "creation", "modified", "owner", "modified_by"],
filters={"apply_on": apply_on},
)
values = []
for d in data:
values.append((d.get(field), d.name, parentfield.get(field), 'Pricing Rule',
d.creation, d.modified, d.owner, d.modified_by, frappe.generate_hash("", 10)))
values.append(
(
d.get(field),
d.name,
parentfield.get(field),
"Pricing Rule",
d.creation,
d.modified,
d.owner,
d.modified_by,
frappe.generate_hash("", 10),
)
)
if values:
frappe.db.sql(""" INSERT INTO
frappe.db.sql(
""" INSERT INTO
`tab{doctype}` ({field}, parent, parentfield, parenttype, creation, modified,
owner, modified_by, name)
VALUES {values} """.format(doctype=doctype,
field=field, values=', '.join(['%s'] * len(values))), tuple(values))
VALUES {values} """.format(
doctype=doctype, field=field, values=", ".join(["%s"] * len(values))
),
tuple(values),
)

View File

@@ -6,7 +6,8 @@ import frappe
def execute():
frappe.reload_doc("manufacturing", "doctype", "production_plan")
frappe.db.sql("""
frappe.db.sql(
"""
UPDATE `tabProduction Plan` ppl
SET status = "Completed"
WHERE ppl.name IN (
@@ -28,4 +29,5 @@ def execute():
HAVING should_set = 1
) ss
)
""")
"""
)

View File

@@ -5,20 +5,22 @@ from erpnext.regional.india import states
def execute():
company = frappe.get_all('Company', filters = {'country': 'India'})
company = frappe.get_all("Company", filters={"country": "India"})
if not company:
return
# Update options in gst_state custom field
gst_state = frappe.get_doc('Custom Field', 'Address-gst_state')
gst_state.options = '\n'.join(states)
gst_state = frappe.get_doc("Custom Field", "Address-gst_state")
gst_state.options = "\n".join(states)
gst_state.save()
# Update gst_state and state code in existing address
frappe.db.sql("""
frappe.db.sql(
"""
UPDATE `tabAddress`
SET
gst_state = 'Dadra and Nagar Haveli and Daman and Diu',
gst_state_number = 26
WHERE gst_state = 'Daman and Diu'
""")
"""
)