コード例 #1
0
def check_budget(gl_map, cancel):
    for gle in gl_map:
        if gle.get("cost_center"):
            # check budget only if account is expense account
            acc_details = webnotes.conn.get_value("Account", gle["account"], ["is_pl_account", "debit_or_credit"])
            if acc_details[0] == "Yes" and acc_details[1] == "Debit":
                webnotes.get_obj("Budget Control").check_budget(gle, cancel)
コード例 #2
0
def _update_requested_qty(controller, mr_obj, mr_items):
    """update requested qty (before ordered_qty is updated)"""
    for mr_item_name in mr_items:
        mr_item = mr_obj.doclist.getone({"parentfield": "indent_details", "name": mr_item_name})
        se_detail = controller.doclist.getone(
            {"parentfield": "mtn_details", "material_request": mr_obj.doc.name, "material_request_item": mr_item_name}
        )

        mr_item.ordered_qty = flt(mr_item.ordered_qty)
        mr_item.qty = flt(mr_item.qty)
        se_detail.transfer_qty = flt(se_detail.transfer_qty)

        if (
            se_detail.docstatus == 2
            and mr_item.ordered_qty > mr_item.qty
            and se_detail.transfer_qty == mr_item.ordered_qty
        ):
            add_indented_qty = mr_item.qty
        elif se_detail.docstatus == 1 and mr_item.ordered_qty + se_detail.transfer_qty > mr_item.qty:
            add_indented_qty = mr_item.qty - mr_item.ordered_qty
        else:
            add_indented_qty = se_detail.transfer_qty

        webnotes.get_obj("Warehouse", se_detail.t_warehouse).update_bin(
            {
                "item_code": se_detail.item_code,
                "indented_qty": (se_detail.docstatus == 2 and 1 or -1) * add_indented_qty,
                "posting_date": controller.doc.posting_date,
            }
        )
コード例 #3
0
def execute():
    import webnotes
    for si in webnotes.conn.sql(
            """select name from `tabSales Invoice` where docstatus = 1"""):
        webnotes.get_obj("Sales Invoice", si[0],
                         with_children=1).update_qty(change_modified=False)
        webnotes.conn.commit()
コード例 #4
0
def execute():
    webnotes.reload_doc("stock", "doctype", "delivery_note_item")
    webnotes.reload_doc("accounts", "doctype", "sales_invoice_item")

    webnotes.conn.auto_commit_on_many_writes = True
    for company in webnotes.conn.sql("select name from `tabCompany`"):
        stock_ledger_entries = webnotes.conn.sql(
            """select item_code, voucher_type, voucher_no,
			voucher_detail_no, posting_date, posting_time, stock_value, 
			warehouse, actual_qty as qty from `tabStock Ledger Entry` 
			where ifnull(`is_cancelled`, "No") = "No" and company = %s
			order by item_code desc, warehouse desc, 
			posting_date desc, posting_time desc, name desc""",
            company[0],
            as_dict=True)

        dn_list = webnotes.conn.sql(
            """select name from `tabDelivery Note` 
			where docstatus < 2 and company = %s""", company[0])

        for dn in dn_list:
            dn = webnotes.get_obj("Delivery Note", dn[0], with_children=1)
            dn.set_buying_amount(stock_ledger_entries)

        si_list = webnotes.conn.sql(
            """select name from `tabSales Invoice` 
			where docstatus < 2	and company = %s""", company[0])
        for si in si_list:
            si = webnotes.get_obj("Sales Invoice", si[0], with_children=1)
            si.set_buying_amount(stock_ledger_entries)

    webnotes.conn.auto_commit_on_many_writes = False
コード例 #5
0
def execute():
	webnotes.reload_doc("stock", "doctype", "delivery_note_item")
	webnotes.reload_doc("accounts", "doctype", "sales_invoice_item")

	webnotes.conn.auto_commit_on_many_writes = True
	for company in webnotes.conn.sql("select name from `tabCompany`"):
		stock_ledger_entries = webnotes.conn.sql("""select item_code, voucher_type, voucher_no,
			voucher_detail_no, posting_date, posting_time, stock_value, 
			warehouse, actual_qty as qty from `tabStock Ledger Entry` 
			where ifnull(`is_cancelled`, "No") = "No" and company = %s
			order by item_code desc, warehouse desc, 
			posting_date desc, posting_time desc, name desc""", company[0], as_dict=True)
		
		dn_list = webnotes.conn.sql("""select name from `tabDelivery Note` 
			where docstatus < 2 and company = %s""", company[0])
		
		for dn in dn_list:
			dn = webnotes.get_obj("Delivery Note", dn[0], with_children = 1)
			dn.set_buying_amount(stock_ledger_entries)
		
		si_list = webnotes.conn.sql("""select name from `tabSales Invoice` 
			where docstatus < 2	and company = %s""", company[0])
		for si in si_list:
			si = webnotes.get_obj("Sales Invoice", si[0], with_children = 1)
			si.set_buying_amount(stock_ledger_entries)
		
	webnotes.conn.auto_commit_on_many_writes = False
コード例 #6
0
def execute():
	import webnotes
	webnotes.reload_doc("buying", "doctype", "purchase_order_item")
	webnotes.reload_doc("stock", "doctype", "purchase_receipt_item")
	for pi in webnotes.conn.sql("""select name from `tabPurchase Invoice` where docstatus = 1"""):
		webnotes.get_obj("Purchase Invoice", pi[0], 
			with_children=1).update_qty(change_modified=False)
コード例 #7
0
ファイル: utils.py プロジェクト: rohitw1991/erpnext
def reconcile_against_document(args):
	"""
		Cancel JV, Update aginst document, split if required and resubmit jv
	"""
	for d in args:
		check_if_jv_modified(d)

		against_fld = {
			'Journal Voucher' : 'against_jv',
			'Sales Invoice' : 'against_invoice',
			'Purchase Invoice' : 'against_voucher'
		}
		
		d['against_fld'] = against_fld[d['against_voucher_type']]

		# cancel JV
		jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children=1)
		jv_obj.make_gl_entries(cancel=1, adv_adj=1)
		
		# update ref in JV Detail
		update_against_doc(d, jv_obj)

		# re-submit JV
		jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children =1)
		jv_obj.make_gl_entries(cancel = 0, adv_adj =1)
コード例 #8
0
	def insert_entries(self, opts, row):
		"""Insert Stock Ledger Entries"""		
		args = webnotes._dict({
			"doctype": "Stock Ledger Entry",
			"item_code": row.item_code,
			"warehouse": row.warehouse,
			"posting_date": self.doc.posting_date,
			"posting_time": self.doc.posting_time,
			"voucher_type": self.doc.doctype,
			"voucher_no": self.doc.name,
			"company": self.doc.company,
			"is_cancelled": "No",
			"voucher_detail_no": row.voucher_detail_no,
			"fiscal_year": self.doc.fiscal_year,
		})
		args.update(opts)
		# create stock ledger entry
		sle_wrapper = webnotes.bean([args])
		sle_wrapper.ignore_permissions = 1
		sle_wrapper.insert()
		
		# update bin
		webnotes.get_obj('Warehouse', row.warehouse).update_bin(args)
		
		# append to entries
		self.entries.append(args)
コード例 #9
0
ファイル: utils.py プロジェクト: robertbecht/erpnext
def reconcile_against_document(args):
	"""
		Cancel JV, Update aginst document, split if required and resubmit jv
	"""
	for d in args:
		check_if_jv_modified(d)

		against_fld = {
			'Journal Voucher' : 'against_jv',
			'Sales Invoice' : 'against_invoice',
			'Purchase Invoice' : 'against_voucher'
		}
		
		d['against_fld'] = against_fld[d['against_voucher_type']]

		# cancel JV
		jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children=1)
		jv_obj.make_gl_entries(cancel=1, adv_adj=1)
		
		# update ref in JV Detail
		update_against_doc(d, jv_obj)

		# re-submit JV
		jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children =1)
		jv_obj.make_gl_entries(cancel = 0, adv_adj =1)
コード例 #10
0
def execute():
	import webnotes
	webnotes.reload_doc('stock', 'doctype', 'packed_item')
	for si in webnotes.conn.sql("""select name from `tabSales Invoice` where docstatus = 1"""):
		webnotes.get_obj("Sales Invoice", si[0], 
			with_children=1).update_qty(change_modified=False)
		webnotes.conn.commit()
コード例 #11
0
	def insert_entries(self, opts, row):
		"""Insert Stock Ledger Entries"""		
		args = webnotes._dict({
			"doctype": "Stock Ledger Entry",
			"item_code": row.item_code,
			"warehouse": row.warehouse,
			"posting_date": self.doc.posting_date,
			"posting_time": self.doc.posting_time,
			"voucher_type": self.doc.doctype,
			"voucher_no": self.doc.name,
			"company": self.doc.company,
			"is_cancelled": "No",
			"voucher_detail_no": row.voucher_detail_no
		})
		args.update(opts)
		# create stock ledger entry
		sle_wrapper = webnotes.bean([args])
		sle_wrapper.ignore_permissions = 1
		sle_wrapper.insert()
		
		# update bin
		webnotes.get_obj('Warehouse', row.warehouse).update_bin(args)
		
		# append to entries
		self.entries.append(args)
コード例 #12
0
ファイル: utils.py プロジェクト: nivawebs/erpnext
def reconcile_against_document(args):
    """
		Cancel JV, Update aginst document, split if required and resubmit jv
	"""
    for d in args:
        check_if_jv_modified(d)

        against_fld = {
            "Journal Voucher": "against_jv",
            "Sales Invoice": "against_invoice",
            "Purchase Invoice": "against_voucher",
        }

        d["against_fld"] = against_fld[d["against_voucher_type"]]

        # cancel JV
        jv_obj = webnotes.get_obj("Journal Voucher", d["voucher_no"], with_children=1)
        jv_obj.make_gl_entries(cancel=1, adv_adj=1)

        # update ref in JV Detail
        update_against_doc(d, jv_obj)

        # re-submit JV
        jv_obj = webnotes.get_obj("Journal Voucher", d["voucher_no"], with_children=1)
        jv_obj.make_gl_entries(cancel=0, adv_adj=1)
コード例 #13
0
def _update_requested_qty(controller, mr_obj, mr_items):
	"""update requested qty (before ordered_qty is updated)"""
	for mr_item_name in mr_items:
		mr_item = mr_obj.doclist.getone({"parentfield": "indent_details", "name": mr_item_name})
		se_detail = controller.doclist.getone({"parentfield": "mtn_details",
			"material_request": mr_obj.doc.name, "material_request_item": mr_item_name})
	
		mr_item.ordered_qty = flt(mr_item.ordered_qty)
		mr_item.qty = flt(mr_item.qty)
		se_detail.transfer_qty = flt(se_detail.transfer_qty)
	
		if se_detail.docstatus == 2 and mr_item.ordered_qty > mr_item.qty \
				and se_detail.transfer_qty == mr_item.ordered_qty:
			add_indented_qty = mr_item.qty
		elif se_detail.docstatus == 1 and \
				mr_item.ordered_qty + se_detail.transfer_qty > mr_item.qty:
			add_indented_qty = mr_item.qty - mr_item.ordered_qty
		else:
			add_indented_qty = se_detail.transfer_qty
	
		webnotes.get_obj("Warehouse", se_detail.t_warehouse).update_bin({
			"item_code": se_detail.item_code,
			"indented_qty": (se_detail.docstatus==2 and 1 or -1) * add_indented_qty,
			"posting_date": controller.doc.posting_date,
		})
コード例 #14
0
def execute():
    si_no_gle = webnotes.conn.sql("""select si.name from `tabSales Invoice` si 
		where docstatus=1 and not exists(select name from `tabGL Entry` 
			where voucher_type='Sales Invoice' and voucher_no=si.name) 
		and modified >= '2013-08-01'""")

    for si in si_no_gle:
        webnotes.get_obj("Sales Invoice", si[0]).make_gl_entries()
コード例 #15
0
def check_budget(gl_map, cancel):
	for gle in gl_map:
		if gle.get('cost_center'):
			#check budget only if account is expense account
			acc_details = webnotes.conn.get_value("Account", gle['account'], 
				['is_pl_account', 'debit_or_credit'])
			if acc_details[0]=="Yes" and acc_details[1]=="Debit":
				webnotes.get_obj('Budget Control').check_budget(gle, cancel)
コード例 #16
0
def execute():
	si_no_gle = webnotes.conn.sql("""select si.name from `tabSales Invoice` si 
		where docstatus=1 and not exists(select name from `tabGL Entry` 
			where voucher_type='Sales Invoice' and voucher_no=si.name) 
		and modified >= '2013-08-01'""")

	for si in si_no_gle:
		webnotes.get_obj("Sales Invoice", si[0]).make_gl_entries()
コード例 #17
0
def execute():
    import webnotes
    webnotes.reload_doc('stock', 'doctype', 'packed_item')
    for si in webnotes.conn.sql(
            """select name from `tabSales Invoice` where docstatus = 1"""):
        webnotes.get_obj("Sales Invoice", si[0],
                         with_children=1).update_qty(change_modified=False)
        webnotes.conn.commit()
コード例 #18
0
ファイル: general_ledger.py プロジェクト: hfeeki/erpnext
def check_budget(gl_map, cancel):
	for gle in gl_map:
		if gle.get('cost_center'):
			#check budget only if account is expense account
			acc_details = webnotes.conn.get_value("Account", gle['account'], 
				['is_pl_account', 'debit_or_credit'])
			if acc_details[0]=="Yes" and acc_details[1]=="Debit":
				webnotes.get_obj('Budget Control').check_budget(gle, cancel)
コード例 #19
0
def run_on_trash(doctype, name, doclist):
    # call on_trash if required
    if doclist:
        obj = webnotes.get_obj(doclist=doclist)
    else:
        obj = webnotes.get_obj(doctype, name)

    if hasattr(obj, 'on_trash'):
        obj.on_trash()
コード例 #20
0
ファイル: fiscal_year.py プロジェクト: BillTheBest/erpnext
	def set_as_default(self):
		webnotes.conn.set_value("Global Defaults", None, "current_fiscal_year", self.doc.name)
		webnotes.get_obj("Global Defaults").on_update()
		
		# clear cache
		webnotes.clear_cache()
		
		msgprint(self.doc.name + _(""" is now the default Fiscal Year. \
			Please refresh your browser for the change to take effect."""))
コード例 #21
0
ファイル: utils.py プロジェクト: alvz/wnframework
def run_on_trash(doctype, name, doclist):
	# call on_trash if required
	if doclist:
		obj = webnotes.get_obj(doclist=doclist)
	else:
		obj = webnotes.get_obj(doctype, name)

	if hasattr(obj,'on_trash'):
		obj.on_trash()
コード例 #22
0
ファイル: employee.py プロジェクト: robertbecht/erpnext
	def update_user_default(self):
		if self.doc.user_id:
			webnotes.conn.set_default("employee", self.doc.name, self.doc.user_id)
			webnotes.conn.set_default("employee_name", self.doc.employee_name, self.doc.user_id)
			webnotes.conn.set_default("company", self.doc.company, self.doc.user_id)
			
			# add employee role if missing
			if not "Employee" in webnotes.conn.sql_list("""select role from tabUserRole
				where parent=%s""", self.doc.user_id):
				webnotes.get_obj("Profile", self.doc.user_id).add_role("Employee")
コード例 #23
0
ファイル: fiscal_year.py プロジェクト: rohitw1991/erpnext
    def set_as_default(self):
        webnotes.conn.set_value("Global Defaults", None, "current_fiscal_year",
                                self.doc.name)
        webnotes.get_obj("Global Defaults").on_update()

        # clear cache
        webnotes.clear_cache()

        msgprint(self.doc.name + _(""" is now the default Fiscal Year. \
			Please refresh your browser for the change to take effect."""))
コード例 #24
0
ファイル: hr_settings.py プロジェクト: mxmo-co/erpnext
	def on_update(self):
		# reset birthday reminders
		if cint(self.doc.stop_birthday_reminders) != self.original_stop_birthday_reminders:
			webnotes.conn.sql("""delete from `tabEvent` where repeat_on='Every Year' and ref_type='Employee'""")
		
			if not self.doc.stop_birthday_reminders:
				for employee in webnotes.conn.sql_list("""select name from `tabEmployee` where status='Active' and 
					ifnull(date_of_birth, '')!=''"""):
					webnotes.get_obj("Employee", employee).update_dob_event()
					
			webnotes.msgprint(webnotes._("Updated Birthday Reminders"))
コード例 #25
0
	def test_block_list(self):
		import webnotes
		webnotes.conn.set_value("Employee", "_T-Employee-0001", "department", 
			"_Test Department with Block List")
		
		application = webnotes.model_wrapper(test_records[1])
		application.doc.from_date = "2013-01-01"
		application.doc.to_date = "2013-01-05"
		self.assertRaises(LeaveDayBlockedError, application.insert)
		
		webnotes.session.user = "******"
		webnotes.get_obj("Profile", "*****@*****.**").add_role("HR User")
		self.assertTrue(application.insert())
コード例 #26
0
ファイル: make_demo.py プロジェクト: antaryaami/erpnext
def complete_setup():
	print "Complete Setup..."
	webnotes.get_obj("Setup Control").setup_account({
		"first_name": "Test",
		"last_name": "User",
		"fy_start": "1st Jan",
		"industry": "Manufacturing",
		"company_name": "Wind Power LLC",
		"company_abbr": "WP",
		"currency": "INR",
		"timezone": "America/New York",
		"country": "United States"
	})
コード例 #27
0
def complete_setup():
    print "Complete Setup..."
    webnotes.get_obj("Setup Control").setup_account({
        "first_name": "Test",
        "last_name": "User",
        "fy_start": "1st Jan",
        "industry": "Manufacturing",
        "company_name": company,
        "company_abbr": company_abbr,
        "currency": currency,
        "timezone": time_zone,
        "country": country
    })

    import_data("Fiscal_Year")
コード例 #28
0
ファイル: make_demo.py プロジェクト: CarlosAnt/erpnext
def complete_setup():
	print "Complete Setup..."
	webnotes.get_obj("Setup Control").setup_account({
		"first_name": "Test",
		"last_name": "User",
		"fy_start": "1st Jan",
		"industry": "Manufacturing",
		"company_name": company,
		"company_abbr": company_abbr,
		"currency": currency,
		"timezone": time_zone,
		"country": country
	})

	import_data("Fiscal_Year")
コード例 #29
0
	def insert_existing_sle(self, valuation_method):
		webnotes.conn.set_value("Item", "_Test Item", "valuation_method", valuation_method)
		webnotes.conn.set_default("allow_negative_stock", 1)
		
		existing_ledgers = [
			{
				"doctype": "Stock Ledger Entry", "__islocal": 1,
				"voucher_type": "Stock Entry", "voucher_no": "TEST",
				"item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC",
				"posting_date": "2012-12-12", "posting_time": "01:00",
				"actual_qty": 20, "incoming_rate": 1000, "company": "_Test Company",
				"fiscal_year": "_Test Fiscal Year 2012",
			},
			{
				"doctype": "Stock Ledger Entry", "__islocal": 1,
				"voucher_type": "Stock Entry", "voucher_no": "TEST",
				"item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC",
				"posting_date": "2012-12-15", "posting_time": "02:00",
				"actual_qty": 10, "incoming_rate": 700, "company": "_Test Company",
				"fiscal_year": "_Test Fiscal Year 2012",
			},
			{
				"doctype": "Stock Ledger Entry", "__islocal": 1,
				"voucher_type": "Stock Entry", "voucher_no": "TEST",
				"item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC",
				"posting_date": "2012-12-25", "posting_time": "03:00",
				"actual_qty": -15, "company": "_Test Company",
				"fiscal_year": "_Test Fiscal Year 2012",
			},
			{
				"doctype": "Stock Ledger Entry", "__islocal": 1,
				"voucher_type": "Stock Entry", "voucher_no": "TEST",
				"item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC",
				"posting_date": "2012-12-31", "posting_time": "08:00",
				"actual_qty": -20, "company": "_Test Company",
				"fiscal_year": "_Test Fiscal Year 2012",
			},
			{
				"doctype": "Stock Ledger Entry", "__islocal": 1,
				"voucher_type": "Stock Entry", "voucher_no": "TEST",
				"item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC",
				"posting_date": "2013-01-05", "posting_time": "07:00",
				"actual_qty": 15, "incoming_rate": 1200, "company": "_Test Company",
				"fiscal_year": "_Test Fiscal Year 2013",
			},
		]
		
		webnotes.get_obj("Stock Ledger").update_stock(existing_ledgers)
コード例 #30
0
	def insert_existing_sle(self, valuation_method):
		webnotes.conn.set_value("Item", "_Test Item", "valuation_method", valuation_method)
		webnotes.conn.set_default("allow_negative_stock", 1)
		
		existing_ledgers = [
			{
				"doctype": "Stock Ledger Entry", "__islocal": 1,
				"voucher_type": "Stock Entry", "voucher_no": "TEST",
				"item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC",
				"posting_date": "2012-12-12", "posting_time": "01:00",
				"actual_qty": 20, "incoming_rate": 1000, "company": "_Test Company",
				"fiscal_year": "_Test Fiscal Year 2012",
			},
			{
				"doctype": "Stock Ledger Entry", "__islocal": 1,
				"voucher_type": "Stock Entry", "voucher_no": "TEST",
				"item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC",
				"posting_date": "2012-12-15", "posting_time": "02:00",
				"actual_qty": 10, "incoming_rate": 700, "company": "_Test Company",
				"fiscal_year": "_Test Fiscal Year 2012",
			},
			{
				"doctype": "Stock Ledger Entry", "__islocal": 1,
				"voucher_type": "Stock Entry", "voucher_no": "TEST",
				"item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC",
				"posting_date": "2012-12-25", "posting_time": "03:00",
				"actual_qty": -15, "company": "_Test Company",
				"fiscal_year": "_Test Fiscal Year 2012",
			},
			{
				"doctype": "Stock Ledger Entry", "__islocal": 1,
				"voucher_type": "Stock Entry", "voucher_no": "TEST",
				"item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC",
				"posting_date": "2012-12-31", "posting_time": "08:00",
				"actual_qty": -20, "company": "_Test Company",
				"fiscal_year": "_Test Fiscal Year 2012",
			},
			{
				"doctype": "Stock Ledger Entry", "__islocal": 1,
				"voucher_type": "Stock Entry", "voucher_no": "TEST",
				"item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC",
				"posting_date": "2013-01-05", "posting_time": "07:00",
				"actual_qty": 15, "incoming_rate": 1200, "company": "_Test Company",
				"fiscal_year": "_Test Fiscal Year 2013",
			},
		]
		
		webnotes.get_obj("Stock Ledger").update_stock(existing_ledgers)
コード例 #31
0
def execute():
	from stock.stock_ledger import update_entries_after
	item_warehouse = []
	# update valuation_rate in transaction
	doctypes = {"Purchase Receipt": "purchase_receipt_details", "Purchase Invoice": "entries"}
	
	for dt in doctypes:
		for d in webnotes.conn.sql("""select name from `tab%s` 
				where modified >= '2013-05-09' and docstatus=1""" % dt):
			rec = webnotes.get_obj(dt, d[0])
			rec.update_valuation_rate(doctypes[dt])
			
			for item in rec.doclist.get({"parentfield": doctypes[dt]}):
				webnotes.conn.sql("""update `tab%s Item` set valuation_rate = %s 
					where name = %s"""% (dt, '%s', '%s'), tuple([item.valuation_rate, item.name]))
					
				if dt == "Purchase Receipt":
					webnotes.conn.sql("""update `tabStock Ledger Entry` set incoming_rate = %s 
						where voucher_detail_no = %s""", (item.valuation_rate, item.name))
					if [item.item_code, item.warehouse] not in item_warehouse:
						item_warehouse.append([item.item_code, item.warehouse])
			
	for d in item_warehouse:
		try:
			update_entries_after({"item_code": d[0], "warehouse": d[1], 
				"posting_date": "2013-01-01", "posting_time": "00:05:00"})
			webnotes.conn.commit()
		except:
			pass
コード例 #32
0
	def update_gl_entries_after(self, warehouse_account=None):
		future_stock_vouchers = self.get_future_stock_vouchers()
		gle = self.get_voucherwise_gl_entries(future_stock_vouchers)
		if not warehouse_account:
			warehouse_account = self.get_warehouse_account()
		for voucher_type, voucher_no in future_stock_vouchers:
			existing_gle = gle.get((voucher_type, voucher_no), [])
			voucher_obj = webnotes.get_obj(voucher_type, voucher_no)
			expected_gle = voucher_obj.get_gl_entries(warehouse_account)
			if expected_gle:
				matched = True
				if existing_gle:
					for entry in expected_gle:
						for e in existing_gle:
							if entry.account==e.account \
								and entry.against_account==e.against_account\
								and entry.cost_center==e.cost_center:
									if entry.debit != e.debit or entry.credit != e.credit:
										matched = False
										break
				else:
					matched = False
									
				if not matched:
					self.delete_gl_entries(voucher_type, voucher_no)
					voucher_obj.make_gl_entries(update_gl_entries_after=False)
			else:
				self.delete_gl_entries(voucher_type, voucher_no)
コード例 #33
0
def update_completed_qty(controller, caller_method):
    if controller.doc.doctype == "Stock Entry":
        material_request_map = {}

        for d in controller.doclist.get({"parentfield": "mtn_details"}):
            if d.material_request:
                if d.material_request not in material_request_map:
                    material_request_map[d.material_request] = []
                material_request_map[d.material_request].append(d.material_request_item)

        for mr_name, mr_items in material_request_map.items():
            mr_obj = webnotes.get_obj("Material Request", mr_name, with_children=1)
            mr_doctype = webnotes.get_doctype("Material Request")

            if mr_obj.doc.status in ["Stopped", "Cancelled"]:
                msgprint(
                    _("Material Request")
                    + ": %s, " % mr_obj.doc.name
                    + _(mr_doctype.get_label("status"))
                    + " = %s. " % _(mr_obj.doc.status)
                    + _("Cannot continue."),
                    raise_exception=webnotes.InvalidStatusError,
                )

            _update_requested_qty(controller, mr_obj, mr_items)

            # update ordered percentage and qty
            mr_obj.update_completed_qty(mr_items)
コード例 #34
0
ファイル: holiday_list_patch.py プロジェクト: MiteshC/erpnext
def execute():
	for name in webnotes.conn.sql("""select name from `tabHoliday List`"""):
		holiday_list_wrapper = webnotes.model_wrapper("Holiday List", name[0])
		
		desc_count = _count([d.description for d in 
			holiday_list_wrapper.doclist.get({"doctype": "Holiday"})])
			
		holiday_list_obj = webnotes.get_obj(doc=holiday_list_wrapper.doc,
			doclist=holiday_list_wrapper.doclist)
			
		save = False
		
		for desc in desc_count.keys():
			if desc in ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
					"Friday", "Saturday"] and desc_count[desc] > 50:
				holiday_list_obj.doclist = holiday_list_obj.doclist.get(
					{"description": ["!=", desc]})
				
				webnotes.conn.sql("""delete from `tabHoliday`
					where parent=%s and parenttype='Holiday List' 
					and `description`=%s""", (holiday_list_obj.doc.name, desc))
				holiday_list_obj.doc.weekly_off = desc
				holiday_list_obj.get_weekly_off_dates()
				save = True
		
		if save:
			holiday_list_wrapper.set_doclist(holiday_list_obj.doclist)
			holiday_list_wrapper.save()
コード例 #35
0
    def on_submit(self):
        purchase_controller = webnotes.get_obj("Purchase Common")
        purchase_controller.is_item_table_empty(self)

        # Check for Approving Authority
        get_obj('Authorization Control').validate_approving_authority(
            self.doc.doctype, self.doc.company, self.doc.grand_total)

        # Set status as Submitted
        webnotes.conn.set(self.doc, 'status', 'Submitted')

        # Update Previous Doc i.e. update pending_qty and Status accordingly
        purchase_controller.update_prevdoc_detail(self, is_submit=1)

        # Update Serial Record
        get_obj('Stock Ledger').update_serial_record(
            self, 'purchase_receipt_details', is_submit=1, is_incoming=1)

        # Update Stock
        self.update_stock(is_submit=1)

        # Update last purchase rate
        purchase_controller.update_last_purchase_rate(self, 1)

        self.make_gl_entries()
コード例 #36
0
def execute():
	webnotes.reload_doc("core", "doctype", "event")
	webnotes.conn.sql("""delete from `tabEvent` where repeat_on='Every Year' and ref_type='Employee'""")
	for employee in webnotes.conn.sql_list("""select name from `tabEmployee` where status='Active' and 
		ifnull(date_of_birth, '')!=''"""):
			obj = webnotes.get_obj("Employee", employee)
			obj.update_dob_event()
コード例 #37
0
ファイル: general_ledger.py プロジェクト: robertbecht/erpnext
def save_entries(gl_map, cancel, adv_adj, update_outstanding):
	total_debit = total_credit = 0.0
	def _swap(gle):
		gle.debit, gle.credit = abs(flt(gle.credit)), abs(flt(gle.debit))
			
	for entry in gl_map:
		gle = Document('GL Entry', fielddata=entry)
		
		# toggle debit, credit if negative entry
		if flt(gle.debit) < 0 or flt(gle.credit) < 0:
			_swap(gle)

		# toggled debit/credit in two separate condition because 
		# both should be executed at the 
		# time of cancellation when there is negative amount (tax discount)
		if cancel:
			_swap(gle)

		gle_obj = webnotes.get_obj(doc=gle)
		# validate except on_cancel
		if not cancel:
			gle_obj.validate()

		# save
		gle.save(1)
		gle_obj.on_update(adv_adj, cancel, update_outstanding)

		# update total debit / credit
		total_debit += flt(gle.debit)
		total_credit += flt(gle.credit)
		
		# print gle.account, gle.debit, gle.credit, total_debit, total_credit
		
	if not cancel:
		validate_total_debit_credit(total_debit, total_credit)
コード例 #38
0
def execute():
	webnotes.reload_doc("core", "doctype", "event")
	webnotes.conn.sql("""delete from `tabEvent` where repeat_on='Every Year' and ref_type='Employee'""")
	for employee in webnotes.conn.sql_list("""select name from `tabEmployee` where status='Active' and 
		ifnull(date_of_birth, '')!=''"""):
			obj = webnotes.get_obj("Employee", employee)
			obj.update_dob_event()
コード例 #39
0
def rename_doc(doctype, old, new, force=False, merge=False):
    """
		Renames a doc(dt, old) to doc(dt, new) and 
		updates all linked fields of type "Link" or "Select" with "link:"
	"""
    if not webnotes.conn.exists(doctype, old):
        return

    # get doclist of given doctype
    doclist = webnotes.model.doctype.get(doctype)

    validate_rename(doctype, new, doclist, merge, force)

    # call on_rename
    obj = webnotes.get_obj(doctype, old)
    if hasattr(obj, 'on_rename'):
        new = obj.on_rename(new, old) or new

    if not merge:
        rename_parent_and_child(doctype, old, new, doclist)

    # update link fields' values
    link_fields = get_link_fields(doctype)
    update_link_field_values(link_fields, old, new)

    if doctype == 'DocType':
        rename_doctype(doctype, old, new, force)

    if merge:
        webnotes.delete_doc(doctype, old)

    return new
コード例 #40
0
def execute():
    for name in webnotes.conn.sql("""select name from `tabHoliday List`"""):
        holiday_list_wrapper = webnotes.bean("Holiday List", name[0])

        desc_count = _count([
            d.description
            for d in holiday_list_wrapper.doclist.get({"doctype": "Holiday"})
        ])

        holiday_list_obj = webnotes.get_obj(
            doc=holiday_list_wrapper.doc, doclist=holiday_list_wrapper.doclist)

        save = False

        for desc in desc_count.keys():
            if desc in [
                    "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
                    "Friday", "Saturday"
            ] and desc_count[desc] > 50:
                holiday_list_obj.doclist = holiday_list_obj.doclist.get(
                    {"description": ["!=", desc]})

                webnotes.conn.sql(
                    """delete from `tabHoliday`
					where parent=%s and parenttype='Holiday List' 
					and `description`=%s""", (holiday_list_obj.doc.name, desc))
                holiday_list_obj.doc.weekly_off = desc
                holiday_list_obj.get_weekly_off_dates()
                save = True

        if save:
            holiday_list_wrapper.set_doclist(holiday_list_obj.doclist)
            holiday_list_wrapper.save()
コード例 #41
0
def rename_doc(doctype, old, new, force=False, merge=False):
	"""
		Renames a doc(dt, old) to doc(dt, new) and 
		updates all linked fields of type "Link" or "Select" with "link:"
	"""
	if not webnotes.conn.exists(doctype, old):
		return
		
	# get doclist of given doctype
	doclist = webnotes.model.doctype.get(doctype)
	
	validate_rename(doctype, new, doclist, merge, force)

	# call on_rename
	obj = webnotes.get_obj(doctype, old)
	if hasattr(obj, 'on_rename'):
		new = obj.on_rename(new, old) or new
		
	if not merge:
		rename_parent_and_child(doctype, old, new, doclist)
			
	# update link fields' values
	link_fields = get_link_fields(doctype)
	update_link_field_values(link_fields, old, new)
	
	if doctype=='DocType':
		rename_doctype(doctype, old, new, force)
	
	if merge:
		webnotes.delete_doc(doctype, old)
		
	return new
コード例 #42
0
def update_completed_qty(controller, caller_method):
    if controller.doc.doctype == "Stock Entry":
        material_request_map = {}

        for d in controller.doclist.get({"parentfield": "mtn_details"}):
            if d.material_request:
                if d.material_request not in material_request_map:
                    material_request_map[d.material_request] = []
                material_request_map[d.material_request].append(
                    d.material_request_item)

        for mr_name, mr_items in material_request_map.items():
            mr_obj = webnotes.get_obj("Material Request",
                                      mr_name,
                                      with_children=1)
            mr_doctype = webnotes.get_doctype("Material Request")

            if mr_obj.doc.status in ["Stopped", "Cancelled"]:
                msgprint(_("Material Request") + ": %s, " % mr_obj.doc.name +
                         _(mr_doctype.get_label("status")) +
                         " = %s. " % _(mr_obj.doc.status) +
                         _("Cannot continue."),
                         raise_exception=webnotes.InvalidStatusError)

            _update_requested_qty(controller, mr_obj, mr_items)

            # update ordered percentage and qty
            mr_obj.update_completed_qty(mr_items)
コード例 #43
0
	def test_gl_entries(self):
		wrapper = webnotes.model_wrapper(self.get_test_doclist())
		
		# circumvent the disabled calculation call
		obj = webnotes.get_obj(doc=wrapper.doc, doclist=wrapper.doclist)
		obj.calculate_taxes_and_totals()
		wrapper.set_doclist(obj.doclist)
		
		wrapper.insert()
		wrapper.submit()
		wrapper.load_from_db()
		dl = wrapper.doclist
		
		expected_gl_entries = {
			"_Test Supplier - _TC": [0, 1512.30],
			"_Test Account Cost for Goods Sold - _TC": [1250, 0],
			"_Test Account Shipping Charges - _TC": [100, 0],
			"_Test Account Excise Duty - _TC": [140, 0],
			"_Test Account Education Cess - _TC": [2.8, 0],
			"_Test Account S&H Education Cess - _TC": [1.4, 0],
			"_Test Account CST - _TC": [29.88, 0],
			"_Test Account VAT - _TC": [156.25, 0],
			"_Test Account Discount - _TC": [0, 168.03],
		}
		gl_entries = webnotes.conn.sql("""select account, debit, credit from `tabGL Entry`
			where voucher_type = 'Purchase Invoice' and voucher_no = %s""", dl[0].name, as_dict=1)
		for d in gl_entries:
			self.assertEqual([d.debit, d.credit], expected_gl_entries.get(d.account))
コード例 #44
0
def update_gl_entries_after(posting_date,
                            posting_time,
                            warehouse_account=None,
                            for_items=None):
    def _delete_gl_entries(voucher_type, voucher_no):
        webnotes.conn.sql(
            """delete from `tabGL Entry` 
			where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))

    if not warehouse_account:
        warehouse_account = get_warehouse_account()
    future_stock_vouchers = get_future_stock_vouchers(posting_date,
                                                      posting_time,
                                                      warehouse_account,
                                                      for_items)
    gle = get_voucherwise_gl_entries(future_stock_vouchers, posting_date)

    for voucher_type, voucher_no in future_stock_vouchers:
        existing_gle = gle.get((voucher_type, voucher_no), [])
        voucher_obj = webnotes.get_obj(voucher_type, voucher_no)
        expected_gle = voucher_obj.get_gl_entries(warehouse_account)
        if expected_gle:
            if not existing_gle or not compare_existing_and_expected_gle(
                    existing_gle, expected_gle):
                _delete_gl_entries(voucher_type, voucher_no)
                voucher_obj.make_gl_entries(repost_future_gle=False)
        else:
            _delete_gl_entries(voucher_type, voucher_no)
コード例 #45
0
def make(doctype=None, name=None, content=None, subject=None, 
	sender=None, recipients=None, contact=None, lead=None, company=None, 
	communication_medium="Email", send_email=False, print_html=None,
	attachments='[]', send_me_a_copy=False, set_lead=True, date=None):
	# add to Communication
	sent_via = None
	
	d = webnotes.doc('Communication')
	d.subject = subject
	d.content = content
	d.sender = sender or webnotes.conn.get_value("Profile", webnotes.session.user, "email")
	d.recipients = recipients
	d.lead = lead
	d.contact = contact
	d.company = company
	if date:
		d.creation = date
	if doctype:
		sent_via = webnotes.get_obj(doctype, name)
		d.fields[doctype.replace(" ", "_").lower()] = name

	if set_lead:
		set_lead_and_contact(d)
	d.communication_medium = communication_medium
	if send_email:
		send_comm_email(d, name, sent_via, print_html, attachments, send_me_a_copy)
	d.save(1, ignore_fields=True)
コード例 #46
0
ファイル: doc.py プロジェクト: ricardomomm/wnframework
	def set_new_name(self, controller=None):
		if self._new_name_set:
			# already set by bean
			return

		self._new_name_set = True

		self.get_meta()
		autoname = self._meta.autoname
		
		self.localname = self.name


		# amendments
		if self.amended_from: 
			return self._get_amended_name()

		# by method
		else:
			# get my object
			if not controller:
				controller = webnotes.get_obj([self])
				
			if hasattr(controller, 'autoname'):
				return controller.autoname()
			
		# based on a field
		if autoname and autoname.startswith('field:'):
			n = self.fields[autoname[6:]]
			if not n:
				raise Exception, 'Name is required'
			self.name = n.strip()
			
		elif autoname and autoname.startswith("naming_series:"):
			self.set_naming_series()
			if not self.naming_series:
				webnotes.msgprint(webnotes._("Naming Series mandatory"), raise_exception=True)
			self.name = make_autoname(self.naming_series+'.#####')
			
		# based on expression
		elif autoname and autoname.startswith('eval:'):
			doc = self # for setting
			self.name = eval(autoname[5:])
		
		# call the method!
		elif autoname and autoname!='Prompt': 
			self.name = make_autoname(autoname, self.doctype)
				
		# given
		elif self.fields.get('__newname',''): 
			self.name = self.fields['__newname']

		# default name for table
		elif self._meta.istable: 
			self.name = make_autoname('#########', self.doctype)
			
		# unable to determine a name, use global series
		if not self.name:
			self.name = make_autoname('#########', self.doctype)
コード例 #47
0
    def set_new_name(self, controller=None):
        if self._new_name_set:
            # already set by bean
            return

        self._new_name_set = True

        self.get_meta()
        autoname = self._meta.autoname

        self.localname = self.name

        # amendments
        if self.amended_from:
            return self._get_amended_name()

        # by method
        else:
            # get my object
            if not controller:
                controller = webnotes.get_obj([self])

            if hasattr(controller, 'autoname'):
                return controller.autoname()

        # based on a field
        if autoname and autoname.startswith('field:'):
            n = self.fields[autoname[6:]]
            if not n:
                raise Exception, 'Name is required'
            self.name = n.strip()

        elif autoname and autoname.startswith("naming_series:"):
            self.set_naming_series()
            if not self.naming_series:
                webnotes.msgprint(webnotes._("Naming Series mandatory"),
                                  raise_exception=True)
            self.name = make_autoname(self.naming_series + '.#####')

        # based on expression
        elif autoname and autoname.startswith('eval:'):
            doc = self  # for setting
            self.name = eval(autoname[5:])

        # call the method!
        elif autoname and autoname != 'Prompt':
            self.name = make_autoname(autoname, self.doctype)

        # given
        elif self.fields.get('__newname', ''):
            self.name = self.fields['__newname']

        # default name for table
        elif self._meta.istable:
            self.name = make_autoname('#########', self.doctype)

        # unable to determine a name, use global series
        if not self.name:
            self.name = make_autoname('#########', self.doctype)
コード例 #48
0
ファイル: webutils.py プロジェクト: ricardomomm/wnframework
def build_page(page_name):
	if not webnotes.conn:
		webnotes.connect()

	sitemap = get_website_sitemap()
	page_options = sitemap.get(page_name)
	
	if not page_options:
		if page_name=="index":
			# page not found, try home page
			home_page = get_home_page()
			page_options = sitemap.get(home_page)
			if not page_options:
				raise PageNotFoundError
			page_options["page_name"] = home_page
		else:
			raise PageNotFoundError
	else:
		page_options["page_name"] = page_name
	
	basepath = webnotes.utils.get_base_path()
	module = None
	no_cache = False
	
	if page_options.get("controller"):
		module = webnotes.get_module(page_options["controller"])
		no_cache = getattr(module, "no_cache", False)

	# if generator, then load bean, pass arguments
	if page_options.get("is_generator"):
		if not module:
			raise Exception("Generator controller not defined")
		
		name = webnotes.conn.get_value(module.doctype, {
			page_options.get("page_name_field", "page_name"): page_options["page_name"]})
		obj = webnotes.get_obj(module.doctype, name, with_children=True)

		if hasattr(obj, 'get_context'):
			obj.get_context()

		context = webnotes._dict(obj.doc.fields)
		context["obj"] = obj
	else:
		# page
		context = webnotes._dict({ 'name': page_name })
		if module and hasattr(module, "get_context"):
			context.update(module.get_context())
	
	context.update(get_website_settings())

	jenv = webnotes.get_jenv()
	context["base_template"] = jenv.get_template(webnotes.get_config().get("base_template"))
	
	template_name = page_options['template']	
	html = jenv.get_template(template_name).render(context)
	
	if not no_cache:
		webnotes.cache().set_value("page:" + page_name, html)
	return html
コード例 #49
0
def get_args():
	obj = webnotes.get_obj("About Us Settings")
	for d in obj.doclist.get({"doctype":"About Us Team Member"}):
		if not "/" in d.image_link:
			d.image_link = "files/" + d.image_link
	return {
		"obj": obj
	}
コード例 #50
0
def execute():
	webnotes.reload_doc("support", "doctype", "support_ticket")
	webnotes.reload_doc("core", "doctype", "communication")
	for d in webnotes.conn.sql("""select name, raised_by from `tabSupport Ticket` 
			where docstatus < 2""", as_dict=True):
		tic = webnotes.get_obj("Support Ticket", d.name)
		tic.set_lead_contact(d.raised_by)
		webnotes.conn.sql("""update `tabSupport Ticket` set lead = %s, contact = %s, company = %s 
			where name = %s""", (tic.doc.lead, tic.doc.contact, tic.doc.company, d.name
コード例 #51
0
def make(doctype=None,
         name=None,
         content=None,
         subject=None,
         sent_or_received="Sent",
         sender=None,
         recipients=None,
         communication_medium="Email",
         send_email=False,
         print_html=None,
         attachments='[]',
         send_me_a_copy=False,
         set_lead=True,
         date=None):
    # add to Communication
    sent_via = None

    # since we are using fullname and email,
    # if the fullname has any incompatible characters,formataddr can deal with it
    try:
        import json
        sender = json.loads(sender)
    except ValueError:
        pass

    if isinstance(sender, (tuple, list)) and len(sender) == 2:
        from email.utils import formataddr
        sender = formataddr(sender)

    comm = webnotes.new_bean('Communication')
    d = comm.doc
    d.subject = subject
    d.content = content
    d.sent_or_received = sent_or_received
    d.sender = sender or webnotes.conn.get_value(
        "Profile", webnotes.session.user, "email")
    d.recipients = recipients

    # add as child
    sent_via = webnotes.get_obj(doctype, name)
    d.parent = name
    d.parenttype = doctype
    d.parentfield = "communications"

    if date:
        d.communication_date = date

    d.communication_medium = communication_medium

    comm.ignore_permissions = True
    comm.insert()

    if send_email:
        d = comm.doc
        send_comm_email(d, name, sent_via, print_html, attachments,
                        send_me_a_copy)
コード例 #52
0
ファイル: bean.py プロジェクト: miguelfontanes/wnframework
    def make_controller(self):
        if self.obj:
            # update doclist before running any method
            self.obj.doclist = self.doclist
            return self.obj

        self.obj = webnotes.get_obj(doc=self.doc, doclist=self.doclist)
        self.obj.bean = self
        self.controller = self.obj
        return self.obj
コード例 #53
0
ファイル: hr_settings.py プロジェクト: poses/erpnext
    def update_birthday_reminders(self):
        original_stop_birthday_reminders = cint(
            webnotes.conn.get_value("HR Settings", None,
                                    "stop_birthday_reminders"))

        # reset birthday reminders
        if cint(self.doc.stop_birthday_reminders
                ) != original_stop_birthday_reminders:
            webnotes.conn.sql(
                """delete from `tabEvent` where repeat_on='Every Year' and ref_type='Employee'"""
            )

            if not self.doc.stop_birthday_reminders:
                for employee in webnotes.conn.sql_list(
                        """select name from `tabEmployee` where status='Active' and 
					ifnull(date_of_birth, '')!=''"""):
                    webnotes.get_obj("Employee", employee).update_dob_event()

            webnotes.msgprint(webnotes._("Updated Birthday Reminders"))
コード例 #54
0
			def set_next(current, parent, breadcrumbs):
				web_page = webnotes.get_obj("Web Page", parent)
				toc_list = web_page.get_toc_list()
				for i, toc in enumerate(toc_list):
					if toc.name == current and ((i+1)<len(toc_list)):
						links["next"] = toc_list[i+1]
						break
						
				if not links.get("next") and breadcrumbs:
					set_next(parent, breadcrumbs[-1].name, breadcrumbs[:-1])
コード例 #55
0
def build_page(page_name):
    if not webnotes.conn:
        webnotes.connect()

    sitemap_options = webnotes.doc("Website Sitemap", page_name).fields

    page_options = webnotes.doc(
        "Website Sitemap Config",
        sitemap_options.get("website_sitemap_config")).fields.update({
            "page_name":
            sitemap_options.page_name,
            "docname":
            sitemap_options.docname
        })

    if not page_options:
        raise PageNotFoundError
    else:
        page_options["page_name"] = page_name

    basepath = webnotes.utils.get_base_path()
    no_cache = page_options.get("no_cache")

    # if generator, then load bean, pass arguments
    if page_options.get("page_or_generator") == "Generator":
        doctype = page_options.get("ref_doctype")
        obj = webnotes.get_obj(doctype,
                               page_options["docname"],
                               with_children=True)

        if hasattr(obj, 'get_context'):
            obj.get_context()

        context = webnotes._dict(obj.doc.fields)
        context["obj"] = obj
    else:
        # page
        context = webnotes._dict({'name': page_name})
        if page_options.get("controller"):
            module = webnotes.get_module(page_options.get("controller"))
            if module and hasattr(module, "get_context"):
                context.update(module.get_context())

    context.update(get_website_settings())

    jenv = webnotes.get_jenv()
    context["base_template"] = jenv.get_template(
        webnotes.get_config().get("base_template"))

    template_name = page_options['template_path']
    html = jenv.get_template(template_name).render(context)

    if not no_cache:
        webnotes.cache().set_value("page:" + page_name, html)
    return html
コード例 #56
0
def rename_doc(doctype, old, new, force=False, merge=False):
    """
		Renames a doc(dt, old) to doc(dt, new) and 
		updates all linked fields of type "Link" or "Select" with "link:"
	"""
    if not webnotes.conn.exists(doctype, old):
        return

    force = cint(force)
    merge = cint(merge)

    # get doclist of given doctype
    doclist = webnotes.model.doctype.get(doctype)

    # call before_rename
    old_obj = webnotes.get_obj(doctype, old)
    if hasattr(old_obj, 'before_rename'):
        new = old_obj.before_rename(old, new, merge) or new

    new = validate_rename(doctype, new, doclist, merge, force)

    if not merge:
        rename_parent_and_child(doctype, old, new, doclist)

    # update link fields' values
    link_fields = get_link_fields(doctype)
    update_link_field_values(link_fields, old, new)

    if doctype == 'DocType':
        rename_doctype(doctype, old, new, force)

    update_attachments(doctype, old, new)

    if merge:
        webnotes.delete_doc(doctype, old)

    # call after_rename
    new_obj = webnotes.get_obj(doctype, new)
    if hasattr(new_obj, 'after_rename'):
        new_obj.after_rename(old, new, merge)

    return new