Example #1
0
def add_sales_communication(subject, content, sender, real_name, mail=None, 
	status="Open", date=None):
	lead_name = webnotes.conn.get_value("Lead", {"email_id": sender})
	contact_name = webnotes.conn.get_value("Contact", {"email_id": sender})

	if not (lead_name or contact_name):
		# none, create a new Lead
		lead = webnotes.bean({
			"doctype":"Lead",
			"lead_name": real_name or sender,
			"email_id": sender,
			"status": status,
			"source": "Email"
		})
		lead.ignore_permissions = True
		lead.insert()
		lead_name = lead.doc.name

	parent_doctype = "Contact" if contact_name else "Lead"
	parent_name = contact_name or lead_name

	message = make(content=content, sender=sender, subject=subject,
		doctype = parent_doctype, name = parent_name, date=date, sent_or_received="Received")
	
	if mail:
		# save attachments to parent if from mail
		bean = webnotes.bean(parent_doctype, parent_name)
		mail.save_attachments_in_doc(bean.doc)
	def test_sales_invoice_with_advance(self):
		from accounts.doctype.journal_voucher.test_journal_voucher \
			import test_records as jv_test_records
			
		jv = webnotes.bean(copy=jv_test_records[0])
		jv.insert()
		jv.submit()
		
		si = webnotes.bean(copy=test_records[0])
		si.doclist.append({
			"doctype": "Sales Invoice Advance",
			"parentfield": "advance_adjustment_details",
			"journal_voucher": jv.doc.name,
			"jv_detail_no": jv.doclist[1].name,
			"advance_amount": 400,
			"allocated_amount": 300,
			"remarks": jv.doc.remark
		})
		si.insert()
		si.submit()
		si.load_from_db()
		
		self.assertTrue(webnotes.conn.sql("""select name from `tabJournal Voucher Detail`
			where against_invoice=%s""", si.doc.name))
		
		self.assertTrue(webnotes.conn.sql("""select name from `tabJournal Voucher Detail`
			where against_invoice=%s and credit=300""", si.doc.name))
			
		self.assertEqual(si.doc.outstanding_amount, 261.8)
		
		si.cancel()
		
		self.assertTrue(not webnotes.conn.sql("""select name from `tabJournal Voucher Detail`
			where against_invoice=%s""", si.doc.name))
Example #3
0
def execute():
	webnotes.reload_doc("utilities", "doctype", "note")
	webnotes.reload_doc("utilities", "doctype", "note_user")
	
	for question in webnotes.conn.sql("""select * from tabQuestion""", as_dict=True):
		if question.question:
			try:
				name = question.question[:180]
				if webnotes.conn.exists("Note", name):
					webnotes.delete_doc("Note", name)

				similar_questions = webnotes.conn.sql_list("""select name from `tabQuestion`
					where question like %s""", "%s%%" % name)
				answers = [markdown2.markdown(c) for c in webnotes.conn.sql_list("""
						select answer from tabAnswer where question in (%s)""" % \
						", ".join(["%s"]*len(similar_questions)), similar_questions)]

				webnotes.bean({
					"doctype":"Note",
					"title": name,
					"content": "<hr>".join(answers),
					"owner": question.owner,
					"creation": question.creation,
					"public": 1
				}).insert()
			
			except NameError:
				pass
			except Exception, e:
				if e.args[0] != 1062:
					raise
Example #4
0
def add_support_communication(subject, content, sender, docname=None, mail=None):
	if docname:
		ticket = webnotes.bean("Support Ticket", docname)
		ticket.doc.status = 'Open'
		ticket.ignore_permissions = True
		ticket.doc.save()
	else:
		ticket = webnotes.bean([decode_dict({
			"doctype":"Support Ticket",
			"description": content,
			"subject": subject,
			"raised_by": sender,
			"content_type": mail.content_type if mail else None,
			"status": "Open",
		})])
		ticket.ignore_permissions = True
		ticket.insert()
	
	make(content=content, sender=sender, subject = subject,
		doctype="Support Ticket", name=ticket.doc.name,
		date=mail.date if mail else today(), sent_or_received="Received")

	if mail:
		mail.save_attachments_in_doc(ticket.doc)
		
	return ticket
Example #5
0
	def get_warehouse_account(self):
		for d in webnotes.conn.sql("select name from tabWarehouse"):
			webnotes.bean("Warehouse", d[0]).save()

		warehouse_account = dict(webnotes.conn.sql("""select master_name, name from tabAccount 
			where account_type = 'Warehouse' and ifnull(master_name, '') != ''"""))
		return warehouse_account
Example #6
0
    def create_custom_field_for_workflow_state(self):
        webnotes.clear_cache(doctype=self.doc.document_type)
        doctypeobj = webnotes.get_doctype(self.doc.document_type)
        if not len(doctypeobj.get({"doctype": "DocField", "fieldname": self.doc.workflow_state_field})):

            # create custom field
            webnotes.bean(
                [
                    {
                        "doctype": "Custom Field",
                        "dt": self.doc.document_type,
                        "__islocal": 1,
                        "fieldname": self.doc.workflow_state_field,
                        "label": self.doc.workflow_state_field.replace("_", " ").title(),
                        "hidden": 1,
                        "fieldtype": "Link",
                        "options": "Workflow State",
                        # "insert_after": doctypeobj.get({"doctype":"DocField"})[-1].fieldname
                    }
                ]
            ).save()

            webnotes.msgprint(
                "Created Custom Field '%s' in '%s'" % (self.doc.workflow_state_field, self.doc.document_type)
            )
Example #7
0
	def test_material_transfer_gl_entry(self):
		self._clear_stock()
		webnotes.defaults.set_global_default("auto_inventory_accounting", 1)

		mr = webnotes.bean(copy=test_records[0])
		mr.insert()
		mr.submit()

		mtn = webnotes.bean(copy=test_records[2])
		mtn.insert()
		mtn.submit()

		self.check_stock_ledger_entries("Stock Entry", mtn.doc.name, 
			[["_Test Item", "_Test Warehouse", -45.0], ["_Test Item", "_Test Warehouse 1", 45.0]])

		# no gl entry
		gl_entries = webnotes.conn.sql("""select * from `tabGL Entry` 
			where voucher_type = 'Stock Entry' and voucher_no=%s""", mtn.doc.name)
		self.assertFalse(gl_entries)
		
		mtn.cancel()
		self.check_stock_ledger_entries("Stock Entry", mtn.doc.name, 
			sorted([["_Test Item", "_Test Warehouse", 45.0], 
				["_Test Item", "_Test Warehouse 1", -45.0],
				["_Test Item", "_Test Warehouse", -45.0], 
				["_Test Item", "_Test Warehouse 1", 45.0]]))

		# no gl entry
		gl_entries = webnotes.conn.sql("""select * from `tabGL Entry` 
			where voucher_type = 'Stock Entry' and voucher_no=%s""", mtn.doc.name)
		self.assertFalse(gl_entries)
		
		webnotes.defaults.set_global_default("auto_inventory_accounting", 0)
		webnotes.conn.set_default("company", self.old_default_company)
def create_chart_of_accounts_if_not_exists():
	for company in webnotes.conn.sql("select name from `tabCompany`"):
		if not webnotes.conn.sql("select * from `tabAccount` where company = %s", company[0]):
			webnotes.conn.sql("""update `tabCompany` set receivables_group = '', 
				payables_group = '' where name = %s""", company[0])
			webnotes.bean("Company", company[0]).save()
				
	def test_purchase_invoice_with_advance(self):
		from accounts.doctype.journal_voucher.test_journal_voucher \
			import test_records as jv_test_records
			
		jv = webnotes.bean(copy=jv_test_records[1])
		jv.insert()
		jv.submit()
		
		pi = webnotes.bean(copy=test_records[0])
		pi.doclist.append({
			"doctype": "Purchase Invoice Advance",
			"parentfield": "advance_allocation_details",
			"journal_voucher": jv.doc.name,
			"jv_detail_no": jv.doclist[1].name,
			"advance_amount": 400,
			"allocated_amount": 300,
			"remarks": jv.doc.remark
		})
		pi.run_method("calculate_taxes_and_totals")
		pi.insert()
		pi.submit()
		pi.load_from_db()
		
		self.assertTrue(webnotes.conn.sql("""select name from `tabJournal Voucher Detail`
			where against_voucher=%s""", pi.doc.name))
		
		self.assertTrue(webnotes.conn.sql("""select name from `tabJournal Voucher Detail`
			where against_voucher=%s and debit=300""", pi.doc.name))
			
		self.assertEqual(pi.doc.outstanding_amount, 1212.30)
		
		pi.cancel()
		
		self.assertTrue(not webnotes.conn.sql("""select name from `tabJournal Voucher Detail`
			where against_voucher=%s""", pi.doc.name))
Example #10
0
	def create_default_warehouses(self):
		for whname in ("Stores", "Work In Progress", "Finished Goods"):
			webnotes.bean({
				"doctype":"Warehouse",
				"warehouse_name": whname,
				"company": self.doc.name
			}).insert()
Example #11
0
def execute():
	webnotes.reload_doc("utilities", "doctype", "note")
	webnotes.reload_doc("utilities", "doctype", "note_user")
	
	for question in webnotes.conn.sql("""select * from tabQuestion""", as_dict=True):
		if question.question:
			try:
				name = question.question[:180]
				if webnotes.conn.exists("Note", name):
					webnotes.delete_doc("Note", name)
				note = webnotes.bean({
					"doctype":"Note",
					"title": name,
					"content": "<hr>".join([markdown2.markdown(c) for c in webnotes.conn.sql_list("""
						select answer from tabAnswer where question=%s""", question.name)]),
					"owner": question.owner,
					"creation": question.creation,
					"public": 1
				}).insert()
			except NameError:
				pass

	webnotes.delete_doc("DocType", "Question")
	webnotes.delete_doc("DocType", "Answer")
	webnotes.bean("Style Settings").save()
	
	# update comment delete
	webnotes.conn.sql("""update tabDocPerm \
		set cancel=1 where parent='Comment' and role='System Manager'""")
Example #12
0
	def create_default_web_page(self):
		if not webnotes.conn.get_value("Website Settings", None, "home_page"):
			import os
			with open(os.path.join(os.path.dirname(__file__), "sample_home_page.html"), "r") as webfile:
				webpage = webnotes.bean({
					"doctype": "Web Page",
					"title": self.doc.name + " Home",
					"published": 1,
					"description": "Standard Home Page for " + self.doc.company,
					"main_section": webfile.read() % self.doc.fields
				}).insert()
			
				# update in home page in settings
				website_settings = webnotes.bean("Website Settings", "Website Settings")
				website_settings.doc.home_page = webpage.doc.name
				website_settings.doc.banner_html = """<h3 style='margin-bottom: 20px;'>""" + self.doc.name + "</h3>"
				website_settings.doc.copyright = self.doc.name
				website_settings.doclist.append({
					"doctype": "Top Bar Item",
					"parentfield": "top_bar_items",
					"label":"Contact",
					"url": "contact"
				})
				website_settings.doclist.append({
					"doctype": "Top Bar Item",
					"parentfield": "top_bar_items",
					"label":"Blog",
					"url": "blog"
				})
				website_settings.save()
				style_settings = webnotes.bean("Style Settings", "Style Settings")
				style_settings.doc.top_bar_background = "F2F2F2"
				style_settings.doc.font_size = "15px"
				style_settings.save()
Example #13
0
    def test_auto_material_request(self):
        webnotes.conn.sql("""delete from `tabMaterial Request Item`""")
        webnotes.conn.sql("""delete from `tabMaterial Request`""")
        self._clear_stock_account_balance()

        webnotes.conn.set_value("Stock Settings", None, "auto_indent", True)

        st1 = webnotes.bean(copy=test_records[0])
        st1.insert()
        st1.submit()

        st2 = webnotes.bean(copy=test_records[1])
        st2.insert()
        st2.submit()

        from stock.utils import reorder_item

        reorder_item()

        mr_name = webnotes.conn.sql(
            """select parent from `tabMaterial Request Item`
			where item_code='_Test Item'"""
        )

        self.assertTrue(mr_name)

        webnotes.conn.set_default("company", self.old_default_company)
	def test_closing_entry(self):
		# clear GL Entries
		webnotes.conn.sql("""delete from `tabGL Entry`""")
		
		from accounts.doctype.journal_voucher.test_journal_voucher import test_records as jv_records
		jv = webnotes.bean(copy=jv_records[2])
		jv.insert()
		jv.submit()
		
		jv1 = webnotes.bean(copy=jv_records[0])
		jv1.doclist[2].account = "_Test Account Cost for Goods Sold - _TC"
		jv1.doclist[2].debit = 600.0
		jv1.doclist[1].credit = 600.0
		jv1.insert()
		jv1.submit()
		
		pcv = webnotes.bean(copy=test_record)
		pcv.insert()
		pcv.submit()
		
		gl_entries = webnotes.conn.sql("""select account, debit, credit
			from `tabGL Entry` where voucher_type='Period Closing Voucher' and voucher_no=%s
			order by account asc, debit asc""", pcv.doc.name, as_dict=1)

		self.assertTrue(gl_entries)
		
		expected_gl_entries = sorted([
			["_Test Account Reserves and Surplus - _TC", 200.0, 0.0],
			["_Test Account Cost for Goods Sold - _TC", 0.0, 600.0],
			["Sales - _TC", 400.0, 0.0]
		])
		for i, gle in enumerate(gl_entries):
			self.assertEquals(expected_gl_entries[i][0], gle.account)
			self.assertEquals(expected_gl_entries[i][1], gle.debit)
			self.assertEquals(expected_gl_entries[i][2], gle.credit)
Example #15
0
def update_party(fullname, company_name=None, mobile_no=None, phone=None):
	party = get_lead_or_customer()

	if party.doctype == "Lead":
		party.company_name = company_name
		party.lead_name = fullname
		party.mobile_no = mobile_no
		party.phone = phone
	else:
		party.customer_name = company_name or fullname
		party.customer_type == "Company" if company_name else "Individual"
		
		contact_name = webnotes.conn.get_value("Contact", {"email_id": webnotes.session.user,
			"customer": party.name})
		contact = webnotes.bean("Contact", contact_name)
		contact.doc.first_name = fullname
		contact.doc.last_name = None
		contact.doc.customer_name = party.customer_name
		contact.doc.mobile_no = mobile_no
		contact.doc.phone = phone
		contact.ignore_permissions = True
		contact.save()
	
	party_bean = webnotes.bean(party.fields)
	party_bean.ignore_permissions = True
	party_bean.save()
	
	qbean = _get_cart_quotation(party)
	if not qbean.doc.fields.get("__islocal"):
		qbean.doc.customer_name = company_name or fullname
		qbean.run_method("set_contact_fields")
		qbean.ignore_permissions = True
		qbean.save()
Example #16
0
	def process_message(self, mail):
		if mail.from_email == self.email_settings.fields.get('support_email'):
			return
		thread_id = mail.get_thread_id()
		ticket = None
		new_ticket = False

		if thread_id and webnotes.conn.exists("Support Ticket", thread_id):
			ticket = webnotes.bean("Support Ticket", thread_id)
			ticket.doc.status = 'Open'
			ticket.doc.save()
				
		else:
			ticket = webnotes.bean([{
				"doctype":"Support Ticket",
				"description": mail.content,
				"subject": mail.mail["Subject"],
				"raised_by": mail.from_email,
				"content_type": mail.content_type,
				"status": "Open"
			}])
			ticket.insert()
			new_ticket = True

		mail.save_attachments_in_doc(ticket.doc)
				
		make(content=mail.content, sender=mail.from_email, subject = ticket.doc.subject,
			doctype="Support Ticket", name=ticket.doc.name, 
			lead = ticket.doc.lead, contact=ticket.doc.contact, date=mail.date)
			
		if new_ticket and cint(self.email_settings.send_autoreply) and \
			"mailer-daemon" not in mail.from_email.lower():
				self.send_auto_reply(ticket.doc)
Example #17
0
	def process_message(self, mail):
		if mail.from_email == self.settings.email_id:
			return
			
		name = webnotes.conn.get_value("Job Applicant", {"email_id": mail.from_email}, 
			"name")
		if name:
			applicant = webnotes.bean("Job Applicant", name)
			if applicant.doc.status!="Rejected":
				applicant.doc.status = "Open"
			applicant.doc.save()
		else:
			name = (mail.from_real_name and (mail.from_real_name + " - ") or "") \
				+ mail.from_email
			applicant = webnotes.bean({
				"creation": mail.date,
				"doctype":"Job Applicant",
				"applicant_name": name,
				"email_id": mail.from_email,
				"status": "Open"
			})
			applicant.insert()
		
		mail.save_attachments_in_doc(applicant.doc)
				
		make(content=mail.content, sender=mail.from_email, 
			doctype="Job Applicant", name=applicant.doc.name)
def execute():
	webnotes.reload_doc("selling", "doctype", "shopping_cart_price_list")
	webnotes.reload_doc("stock", "doctype", "item_price")
	
	for t in [
			("Supplier Quotation", "price_list_name", "buying_price_list"),
			("Purchase Order", "price_list_name", "buying_price_list"),
			("Purchase Invoice", "price_list_name", "buying_price_list"),
			("Purchase Receipt", "price_list_name", "buying_price_list"),
			("Quotation", "price_list_name", "selling_price_list"),
			("Sales Order", "price_list_name", "selling_price_list"),
			("Delivery Note", "price_list_name", "selling_price_list"),
			("Sales Invoice", "price_list_name", "selling_price_list"),
			("POS Setting", "price_list_name", "selling_price_list"),
			("Shopping Cart Price List", "price_list", "selling_price_list"),
			("Item Price", "price_list_name", "price_list"),
			("BOM", "price_list", "buying_price_list"),
		]:
		table_columns = webnotes.conn.get_table_columns(t[0])
		if t[2] in table_columns and t[1] in table_columns:
			# already reloaded, so copy into new column and drop old column
			webnotes.conn.sql("""update `tab%s` set `%s`=`%s`""" % (t[0], t[2], t[1]))
			webnotes.conn.sql_ddl("""alter table `tab%s` drop column `%s`""" % (t[0], t[1]))
		elif t[1] in table_columns:
			webnotes.conn.sql_ddl("alter table `tab%s` change `%s` `%s` varchar(180)" % t)

		webnotes.reload_doc(webnotes.conn.get_value("DocType", t[0], "module"), "DocType", t[0])
		
	webnotes.conn.sql("""update tabSingles set field='selling_price_list'
		where field='price_list_name' and doctype='Selling Settings'""")
	
	webnotes.reload_doc("Selling", "DocType", "Selling Settings")
	webnotes.bean("Selling Settings").save()
Example #19
0
	def test_planned_qty(self):
		set_perpetual_inventory(0)
		webnotes.conn.sql("delete from `tabStock Ledger Entry`")
		webnotes.conn.sql("""delete from `tabBin`""")
		webnotes.conn.sql("""delete from `tabGL Entry`""")
		
		pro_bean = webnotes.bean(copy = test_records[0])
		pro_bean.insert()
		pro_bean.submit()
		
		from stock.doctype.stock_entry.test_stock_entry import test_records as se_test_records
		mr1 = webnotes.bean(copy = se_test_records[0])
		mr1.insert()
		mr1.submit()
		
		mr2 = webnotes.bean(copy = se_test_records[0])
		mr2.doclist[1].item_code = "_Test Item Home Desktop 100"
		mr2.insert()
		mr2.submit()
		
		stock_entry = make_stock_entry(pro_bean.doc.name, "Manufacture/Repack")
		stock_entry = webnotes.bean(stock_entry)
		
		stock_entry.doc.fg_completed_qty = 4
		stock_entry.doc.posting_date = "2013-05-12"
		stock_entry.doc.fiscal_year = "_Test Fiscal Year 2013"
		stock_entry.run_method("get_items")
		stock_entry.submit()
		
		self.assertEqual(webnotes.conn.get_value("Production Order", pro_bean.doc.name, 
			"produced_qty"), 4)
		self.assertEqual(webnotes.conn.get_value("Bin", {"item_code": "_Test FG Item", 
			"warehouse": "_Test Warehouse 1 - _TC"}, "planned_qty"), 6)
			
		return pro_bean.doc.name
Example #20
0
	def test_monthly_budget_on_cancellation(self):
		from accounts.utils import BudgetError
		webnotes.conn.set_value("Company", "_Test Company", "monthly_bgt_flag", "Stop")
		self.clear_account_balance()
		
		jv = webnotes.bean(copy=test_records[0])
		jv.doclist[1].account = "_Test Account Cost for Goods Sold - _TC"
		jv.doclist[1].cost_center = "_Test Cost Center - _TC"
		jv.doclist[1].credit = 30000.0
		jv.doclist[2].debit = 30000.0
		jv.submit()
		
		self.assertTrue(webnotes.conn.get_value("GL Entry", 
			{"voucher_type": "Journal Voucher", "voucher_no": jv.doc.name}))
		
		jv1 = webnotes.bean(copy=test_records[0])
		jv1.doclist[2].account = "_Test Account Cost for Goods Sold - _TC"
		jv1.doclist[2].cost_center = "_Test Cost Center - _TC"
		jv1.doclist[2].debit = 40000.0
		jv1.doclist[1].credit = 40000.0
		jv1.submit()
		
		self.assertTrue(webnotes.conn.get_value("GL Entry", 
			{"voucher_type": "Journal Voucher", "voucher_no": jv1.doc.name}))
		
		self.assertRaises(BudgetError, jv.cancel)
		
		webnotes.conn.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
Example #21
0
	def test_incorrect_mapping_of_stock_entry(self):
		# submit material request of type Purchase
		mr = webnotes.bean(copy=test_records[0])
		mr.doc.material_request_type = "Transfer"
		mr.insert()
		mr.submit()

		# map a stock entry
		from stock.doctype.material_request.material_request import make_stock_entry
		
		se_doclist = make_stock_entry(mr.doc.name)
		se_doclist[0].update({
			"posting_date": "2013-03-01",
			"posting_time": "00:00",
			"fiscal_year": "_Test Fiscal Year 2013",
		})
		se_doclist[1].update({
			"qty": 60.0,
			"transfer_qty": 60.0,
			"s_warehouse": "_Test Warehouse - _TC",
			"t_warehouse": "_Test Warehouse 1 - _TC",
			"incoming_rate": 1.0
		})
		se_doclist[2].update({
			"qty": 3.0,
			"transfer_qty": 3.0,
			"s_warehouse": "_Test Warehouse 1 - _TC",
			"incoming_rate": 1.0
		})
		
		# check for stopped status of Material Request
		se = webnotes.bean(copy=se_doclist)
		self.assertRaises(webnotes.MappingMismatchError, se.insert)
Example #22
0
def after_install():
	# reset installed apps for re-install
	webnotes.conn.set_global("installed_apps", '["webnotes"]')
	
	# core users / roles
	install_docs = [
		{'doctype':'Profile', 'name':'Administrator', 'first_name':'Administrator', 
			'email':'admin@localhost', 'enabled':1},
		{'doctype':'Profile', 'name':'Guest', 'first_name':'Guest',
			'email':'guest@localhost', 'enabled':1},
		{'doctype':'UserRole', 'parent': 'Administrator', 'role': 'Administrator', 
			'parenttype':'Profile', 'parentfield':'user_roles'},
		{'doctype':'UserRole', 'parent': 'Guest', 'role': 'Guest', 
			'parenttype':'Profile', 'parentfield':'user_roles'},
		{'doctype': "Role", "role_name": "Report Manager"}
	]
	
	for d in install_docs:
		try:
			webnotes.bean(d).insert()
		except NameError:
			pass

	# all roles to admin
	webnotes.bean("Profile", "Administrator").get_controller().add_roles(*webnotes.conn.sql_list("""
		select name from tabRole"""))

	# update admin password
	from webnotes.auth import _update_password
	_update_password("Administrator", webnotes.conf.get("admin_password"))

	webnotes.conn.commit()
Example #23
0
def update_profile_name(args):
	if args.get("email"):
		args['name'] = args.get("email")
		webnotes.flags.mute_emails = True
		webnotes.bean({
			"doctype":"Profile",
			"email": args.get("email"),
			"first_name": args.get("first_name"),
			"last_name": args.get("last_name"),
			"profile_type":"Employee"
		}).insert()
		webnotes.flags.mute_emails = False
		from webnotes.auth import _update_password
		_update_password(args.get("email"), args.get("password"))

	else:
		args['name'] = webnotes.session.user

		# Update Profile
		if not args.get('last_name') or args.get('last_name')=='None': 
				args['last_name'] = None
		webnotes.conn.sql("""update `tabProfile` SET first_name=%(first_name)s,
			last_name=%(last_name)s WHERE name=%(name)s""", args)
		
	if args.get("attach_profile"):
		filename, filetype, content = args.get("attach_profile").split(",")
		fileurl = save_file(filename, content, "Profile", args.get("name"), decode=True).file_name
		webnotes.conn.set_value("Profile", args.get("name"), "user_image", fileurl)
		
	add_all_roles_to(args.get("name"))
Example #24
0
def _get_cart_quotation(party=None):
	if not party:
		party = get_lead_or_customer()
		
	quotation = webnotes.conn.get_value("Quotation", 
		{party.doctype.lower(): party.name, "order_type": "Shopping Cart", "docstatus": 0})
	
	if quotation:
		qbean = webnotes.bean("Quotation", quotation)
	else:
		qbean = webnotes.bean({
			"doctype": "Quotation",
			"naming_series": webnotes.defaults.get_user_default("shopping_cart_quotation_series") or "QTN-CART-",
			"quotation_to": party.doctype,
			"company": webnotes.defaults.get_user_default("company"),
			"order_type": "Shopping Cart",
			"status": "Draft",
			"docstatus": 0,
			"__islocal": 1,
			(party.doctype.lower()): party.name
		})
		
		if party.doctype == "Customer":
			qbean.doc.contact_person = webnotes.conn.get_value("Contact", {"email_id": webnotes.session.user,
				"customer": party.name})
			qbean.run_method("set_contact_fields")
		
		qbean.run_method("onload_post_render")
		apply_cart_settings(party, qbean)
	
	return qbean
def update_for_doc(doctype, doc):
	for filedata in doc.file_list.split("\n"):
		if not filedata:
			continue
			
		filedata = filedata.split(",")
		if len(filedata)==2:
			filename, fileid = filedata[0], filedata[1] 
		else:
			continue
		
		exists = True
		if not (filename.startswith("http://") or filename.startswith("https://")):
			if not os.path.exists(webnotes.utils.get_path("public", "files", filename)):
				exists = False

		if exists:
			if webnotes.conn.exists("File Data", fileid):
				try:
					fd = webnotes.bean("File Data", fileid)
					if not (fd.doc.attached_to_doctype and fd.doc.attached_to_name):
						fd.doc.attached_to_doctype = doctype
						fd.doc.attached_to_name = doc.name
						fd.save()
					else:
						fd = webnotes.bean("File Data", copy=fd.doclist)
						fd.doc.attached_to_doctype = doctype
						fd.doc.attached_to_name = doc.name
						fd.doc.name = None
						fd.insert()
				except webnotes.DuplicateEntryError:
					pass
		else:
			webnotes.conn.sql("""delete from `tabFile Data` where name=%s""",
				fileid)
Example #26
0
	def _test_delivery_note_return_against_sales_order(self, item_code, delivered_qty, returned_qty):
		self._insert_material_receipt()

		from selling.doctype.sales_order.test_sales_order \
			import test_records as sales_order_test_records

		actual_qty_0 = self._get_actual_qty()
		
		so = webnotes.bean(copy=sales_order_test_records[0])
		so.doclist[1].item_code = item_code
		so.doclist[1].qty = 5.0
		so.insert()
		so.submit()
		
		dn_doclist = webnotes.map_doclist([
			["Sales Order", "Delivery Note"],
			["Sales Order Item", "Delivery Note Item"],
			["Sales Taxes and Charges", "Sales Taxes and Charges"],
			["Sales Team", "Sales Team"]], so.doc.name)

		dn = webnotes.bean(dn_doclist)
		dn.doc.status = "Draft"
		dn.doc.posting_date = so.doc.delivery_date
		dn.insert()
		dn.submit()
		
		actual_qty_1 = self._get_actual_qty()

		self.assertEquals(actual_qty_0 - delivered_qty, actual_qty_1)

		si_doclist = webnotes.map_doclist([
			["Sales Order", "Sales Invoice"],
			["Sales Order Item", "Sales Invoice Item"],
			["Sales Taxes and Charges", "Sales Taxes and Charges"],
			["Sales Team", "Sales Team"]], so.doc.name)

		si = webnotes.bean(si_doclist)
		si.doc.posting_date = dn.doc.posting_date
		si.doc.debit_to = "_Test Customer - _TC"
		for d in si.doclist.get({"parentfield": "entries"}):
			d.income_account = "Sales - _TC"
			d.cost_center = "_Test Cost Center - _TC"
		si.insert()
		si.submit()

		# insert and submit stock entry for sales return
		se = webnotes.bean(copy=test_records[0])
		se.doc.purpose = "Sales Return"
		se.doc.delivery_note_no = dn.doc.name
		se.doc.posting_date = "2013-03-10"
		se.doc.fiscal_year = "_Test Fiscal Year 2013"
		se.doclist[1].qty = se.doclist[1].transfer_qty = returned_qty

		se.insert()
		se.submit()

		actual_qty_2 = self._get_actual_qty()
		self.assertEquals(actual_qty_1 + returned_qty, actual_qty_2)

		return se
Example #27
0
def import_doc(d, doctype, overwrite, row_idx, submit=False, ignore_links=False):
	"""import main (non child) document"""
	if d.get("name") and webnotes.conn.exists(doctype, d['name']):
		if overwrite:
			bean = webnotes.bean(doctype, d['name'])
			bean.ignore_links = ignore_links
			bean.doc.fields.update(d)
			if d.get("docstatus") == 1:
				bean.update_after_submit()
			else:
				bean.save()
			return 'Updated row (#%d) %s' % (row_idx + 1, getlink(doctype, d['name']))
		else:
			return 'Ignored row (#%d) %s (exists)' % (row_idx + 1, 
				getlink(doctype, d['name']))
	else:
		bean = webnotes.bean([d])
		bean.ignore_links = ignore_links
		bean.insert()
		
		if submit:
			bean.submit()
		
		return 'Inserted row (#%d) %s' % (row_idx + 1, getlink(doctype,
			bean.doc.fields['name']))
Example #28
0
	def test_incorrect_mapping_of_stock_entry(self):
		# submit material request of type Purchase
		mr = webnotes.bean(copy=test_records[0])
		mr.doc.material_request_type = "Transfer"
		mr.insert()
		mr.submit()

		# map a stock entry
		se_doclist = webnotes.map_doclist([["Material Request", "Stock Entry"], 
			["Material Request Item", "Stock Entry Detail"]], mr.doc.name)
		se_doclist[0].fields.update({
			"posting_date": "2013-03-01",
			"posting_time": "00:00"
		})
		se_doclist[1].fields.update({
			"qty": 60.0,
			"transfer_qty": 60.0,
			"s_warehouse": "_Test Warehouse",
			"t_warehouse": "_Test Warehouse 1",
			"incoming_rate": 1.0
		})
		se_doclist[2].fields.update({
			"qty": 3.0,
			"transfer_qty": 3.0,
			"s_warehouse": "_Test Warehouse 1",
			"incoming_rate": 1.0
		})
		
		# check for stopped status of Material Request
		se = webnotes.bean(copy=se_doclist)
		self.assertRaises(webnotes.MappingMismatchError, se.insert)
Example #29
0
	def update_dob_event(self):
		if self.doc.status == "Active" and self.doc.date_of_birth \
			and not cint(webnotes.conn.get_value("HR Settings", None, "stop_birthday_reminders")):
			birthday_event = webnotes.conn.sql("""select name from `tabEvent` where repeat_on='Every Year' 
				and ref_type='Employee' and ref_name=%s""", self.doc.name)
			
			starts_on = self.doc.date_of_birth + " 00:00:00"
			ends_on = self.doc.date_of_birth + " 00:15:00"

			if birthday_event:
				event = webnotes.bean("Event", birthday_event[0][0])
				event.doc.starts_on = starts_on
				event.doc.ends_on = ends_on
				event.save()
			else:
				webnotes.bean({
					"doctype": "Event",
					"subject": _("Birthday") + ": " + self.doc.employee_name,
					"description": _("Happy Birthday!") + " " + self.doc.employee_name,
					"starts_on": starts_on,
					"ends_on": ends_on,
					"event_type": "Public",
					"all_day": 1,
					"send_reminder": 1,
					"repeat_this_event": 1,
					"repeat_on": "Every Year",
					"ref_type": "Employee",
					"ref_name": self.doc.name
				}).insert()
		else:
			webnotes.conn.sql("""delete from `tabEvent` where repeat_on='Every Year' and
				ref_type='Employee' and ref_name=%s""", self.doc.name)
Example #30
0
	def test_journal_voucher_with_against_jv(self):
		self.clear_account_balance()
		jv_invoice = webnotes.bean(copy=test_records[2])
		jv_invoice.insert()
		jv_invoice.submit()
		
		self.assertTrue(not webnotes.conn.sql("""select name from `tabJournal Voucher Detail`
			where against_jv=%s""", jv_invoice.doc.name))
		
		jv_payment = webnotes.bean(copy=test_records[0])
		jv_payment.doclist[1].against_jv = jv_invoice.doc.name
		jv_payment.insert()
		jv_payment.submit()
		
		self.assertTrue(webnotes.conn.sql("""select name from `tabJournal Voucher Detail`
			where against_jv=%s""", jv_invoice.doc.name))
			
		self.assertTrue(webnotes.conn.sql("""select name from `tabJournal Voucher Detail`
			where against_jv=%s and credit=400""", jv_invoice.doc.name))
		
		# cancel jv_invoice
		jv_invoice.cancel()
		
		self.assertTrue(not webnotes.conn.sql("""select name from `tabJournal Voucher Detail`
			where against_jv=%s""", jv_invoice.doc.name))
Example #31
0
def make_return_jv(stock_entry):
    se = webnotes.bean("Stock Entry", stock_entry)
    if not se.doc.purpose in ["Sales Return", "Purchase Return"]:
        return

    ref = get_return_doclist_and_details(se.doc.fields)

    if ref.doclist[0].doctype == "Delivery Note":
        result = make_return_jv_from_delivery_note(se, ref)
    elif ref.doclist[0].doctype == "Sales Invoice":
        result = make_return_jv_from_sales_invoice(se, ref)
    elif ref.doclist[0].doctype == "Purchase Receipt":
        result = make_return_jv_from_purchase_receipt(se, ref)

    # create jv doclist and fetch balance for each unique row item
    jv_list = [{
        "__islocal":
        1,
        "doctype":
        "Journal Voucher",
        "posting_date":
        se.doc.posting_date,
        "voucher_type":
        se.doc.purpose == "Sales Return" and "Credit Note" or "Debit Note",
        "fiscal_year":
        se.doc.fiscal_year,
        "company":
        se.doc.company
    }]

    from accounts.utils import get_balance_on
    for r in result:
        jv_list.append({
            "__islocal":
            1,
            "doctype":
            "Journal Voucher Detail",
            "parentfield":
            "entries",
            "account":
            r.get("account"),
            "against_invoice":
            r.get("against_invoice"),
            "against_voucher":
            r.get("against_voucher"),
            "balance":
            get_balance_on(r.get("account"), se.doc.posting_date)
        })

    return jv_list
Example #32
0
def get_website_args():
    customer = webnotes.conn.get_value("Contact",
                                       {"email_id": webnotes.session.user},
                                       "customer")
    bean = webnotes.bean("Sales Order", webnotes.form_dict.name)
    if bean.doc.customer != customer:
        return {"doc": {"name": "Not Allowed"}}
    else:
        return {
            "doc": bean.doc,
            "doclist": bean.doclist,
            "webnotes": webnotes,
            "utils": webnotes.utils
        }
Example #33
0
        def _test(i):
            self.assertEquals(
                i + 1,
                webnotes.conn.sql(
                    """select count(*) from `tabSales Invoice`
				where recurring_id=%s and docstatus=1""", base_si.doc.recurring_id)[0][0])

            next_date = add_months(base_si.doc.posting_date, no_of_months)

            manage_recurring_invoices(next_date=next_date, commit=False)

            recurred_invoices = webnotes.conn.sql(
                """select name from `tabSales Invoice`
				where recurring_id=%s and docstatus=1 order by name desc""",
                base_si.doc.recurring_id)

            self.assertEquals(i + 2, len(recurred_invoices))

            new_si = webnotes.bean("Sales Invoice", recurred_invoices[0][0])

            for fieldname in [
                    "convert_into_recurring_invoice", "recurring_type",
                    "repeat_on_day_of_month", "notification_email_address"
            ]:
                self.assertEquals(base_si.doc.fields.get(fieldname),
                                  new_si.doc.fields.get(fieldname))

            self.assertEquals(new_si.doc.posting_date, unicode(next_date))

            self.assertEquals(
                new_si.doc.invoice_period_from_date,
                unicode(
                    add_months(base_si.doc.invoice_period_from_date,
                               no_of_months)))

            if first_and_last_day:
                self.assertEquals(
                    new_si.doc.invoice_period_to_date,
                    unicode(
                        get_last_day(
                            add_months(base_si.doc.invoice_period_to_date,
                                       no_of_months))))
            else:
                self.assertEquals(
                    new_si.doc.invoice_period_to_date,
                    unicode(
                        add_months(base_si.doc.invoice_period_to_date,
                                   no_of_months)))

            return new_si
    def _add_calendar_event(self, opts):
        opts = webnotes._dict(opts)

        if self.doc.contact_date:
            event_doclist = [{
                "doctype": "Event",
                "owner": opts.owner or self.doc.owner,
                "subject": opts.subject,
                "description": opts.description,
                "starts_on": self.doc.contact_date + " 10:00:00",
                "event_type": "Private",
                "ref_type": self.doc.doctype,
                "ref_name": self.doc.name
            }]

            if webnotes.conn.exists("Profile", self.doc.contact_by):
                event_doclist.append({
                    "doctype": "Event User",
                    "parentfield": "event_individuals",
                    "person": self.doc.contact_by
                })

            webnotes.bean(event_doclist).insert()
Example #35
0
def save_address(fields, address_fieldname=None):
	party = get_lead_or_customer()
	fields = webnotes.load_json(fields)
	
	if fields.get("name"):
		bean = webnotes.bean("Address", fields.get("name"))
	else:
		bean = webnotes.bean({"doctype": "Address", "__islocal": 1})
	
	bean.doc.fields.update(fields)
	
	party_fieldname = party.doctype.lower()
	bean.doc.fields.update({
		party_fieldname: party.name,
		(party_fieldname + "_name"): party.fields[party_fieldname + "_name"]
	})
	bean.ignore_permissions = True
	bean.save()
	
	if address_fieldname:
		update_cart_address(address_fieldname, bean.doc.name)
	
	return bean.doc.name
Example #36
0
	def test_aii_gl_entries_for_serial_no_delivered(self):
		webnotes.defaults.set_global_default("auto_inventory_accounting", 1)
		
		sr = webnotes.bean(copy=test_records[0])
		sr.doc.serial_no = "_Test Serial No 2"
		sr.doc.status = "Delivered"
		sr.insert()
		
		gl_entries = webnotes.conn.sql("""select account, debit, credit
			from `tabGL Entry` where voucher_type='Serial No' and voucher_no=%s
			order by account desc""", sr.doc.name, as_dict=1)
		self.assertFalse(gl_entries)
		
		webnotes.defaults.set_global_default("auto_inventory_accounting", 0)
Example #37
0
	def validate_leave_approver(self):
		employee = webnotes.bean("Employee", self.doc.employee)
		leave_approvers = [l.leave_approver for l in 
			employee.doclist.get({"parentfield": "employee_leave_approvers"})]

		if len(leave_approvers) and self.doc.leave_approver not in leave_approvers:
			msgprint(("[" + _("For Employee") + ' "' + self.doc.employee + '"] ' 
				+ _("Leave Approver can be one of") + ": "
				+ comma_or(leave_approvers)), raise_exception=InvalidLeaveApproverError)
		
		elif self.doc.leave_approver and not webnotes.conn.sql("""select name from `tabUserRole` 
			where parent=%s and role='Leave Approver'""", self.doc.leave_approver):
				msgprint(get_fullname(self.doc.leave_approver) + ": " \
					+ _("does not have role 'Leave Approver'"), raise_exception=InvalidLeaveApproverError)
Example #38
0
def export_json(doctype, name, path):
    from webnotes.handler import json_handler
    if not name or name == "-":
        name = doctype
    with open(path, "w") as outfile:
        doclist = [d.fields for d in webnotes.bean(doctype, name).doclist]
        for d in doclist:
            if d.get("parent"):
                del d["parent"]
                del d["name"]
            d["__islocal"] = 1
        outfile.write(
            json.dumps(doclist, default=json_handler, indent=1,
                       sort_keys=True))
Example #39
0
def save_url(file_url, dt, dn):
	if not (file_url.startswith("http://") or file_url.startswith("https://")):
		webnotes.msgprint("URL must start with 'http://' or 'https://'")
		return None, None
		
	f = webnotes.bean({
		"doctype": "File Data",
		"file_url": file_url,
		"attached_to_doctype": dt,
		"attached_to_name": dn
	})
	f.ignore_permissions = True
	f.insert();
	return f.doc
Example #40
0
def reset_password(user):
    user = webnotes.form_dict.get('user', '')
    if user in ["*****@*****.**", "Administrator"]:
        return "Not allowed"

    if webnotes.conn.sql("""select name from tabProfile where name=%s""",
                         user):
        # Hack!
        webnotes.session["user"] = "******"
        profile = webnotes.bean("Profile", user)
        profile.get_controller().reset_password()
        return "Password reset details sent to your email."
    else:
        return "No such user (%s)" % user
	def test_serial_no_transfer_in(self):
		se = webnotes.bean(copy=test_records[0])
		se.doclist[1].item_code = "_Test Serialized Item"
		se.doclist[1].qty = 2
		se.doclist[1].serial_no = "ABCD\nEFGH"
		se.doclist[1].transfer_qty = 2
		se.insert()
		se.submit()
		
		self.assertTrue(webnotes.conn.exists("Serial No", "ABCD"))
		self.assertTrue(webnotes.conn.exists("Serial No", "EFGH"))
		
		se.cancel()
		self.assertFalse(webnotes.conn.get_value("Serial No", "ABCD", "warehouse"))
Example #42
0
def import_doc(d, doctype, overwrite, row_idx, submit=False):
	"""import main (non child) document"""
	if webnotes.conn.exists(doctype, d['name']):
		if overwrite:
			bean = webnotes.bean(doctype, d['name'])
			bean.doc.fields.update(d)
			if d.get("docstatus") == 1:
				bean.update_after_submit()
			else:
				bean.save()
			return 'Updated row (#%d) %s' % (row_idx, getlink(doctype, d['name']))
		else:
			return 'Ignored row (#%d) %s (exists)' % (row_idx, 
				getlink(doctype, d['name']))
	else:
		bean = webnotes.bean([d])
		bean.insert()
		
		if submit:
			bean.submit()
		
		return 'Inserted row (#%d) %s' % (row_idx, getlink(doctype,
			bean.doc.fields['name']))
Example #43
0
def insert(doclist):
    if not isinstance(doclist, list):
        doclist = [doclist]

    for d in doclist:
        if isinstance(d, dict):
            d["__islocal"] = 1
        else:
            d.fields["__islocal"] = 1

    wrapper = webnotes.bean(doclist)
    wrapper.save()

    return wrapper
Example #44
0
def create_suppliers(args):
    for i in xrange(1, 6):
        supplier = args.get("supplier_" + str(i))
        if supplier:
            webnotes.bean({
                "doctype": "Supplier",
                "supplier_name": supplier,
                "supplier_type": "Local",
                "company": args.get("company_name")
            }).insert()

            if args.get("supplier_contact_" + str(i)):
                contact = args.get("supplier_contact_" + str(i)).split(" ")
                webnotes.bean({
                    "doctype":
                    "Contact",
                    "supplier":
                    supplier,
                    "first_name":
                    contact[0],
                    "last_name":
                    len(contact) > 1 and contact[1] or ""
                }).insert()
    def test_serial_warehouse_error(self):
        self._clear_stock_account_balance()
        make_serialized_item()

        se = webnotes.bean(copy=test_records[0])
        se.doc.purpose = "Material Transfer"
        se.doclist[1].item_code = "_Test Serialized Item With Series"
        se.doclist[1].qty = 1
        se.doclist[1].transfer_qty = 1
        se.doclist[1].serial_no = "ABCD00001"
        se.doclist[1].s_warehouse = "_Test Warehouse 1 - _TC"
        se.doclist[1].t_warehouse = "_Test Warehouse - _TC"
        se.insert()
        self.assertRaises(SerialNoWarehouseError, se.submit)
Example #46
0
    def test_make_sales_order(self):
        from selling.doctype.quotation.quotation import make_sales_order

        quotation = webnotes.bean(copy=test_records[0])
        quotation.insert()

        self.assertRaises(webnotes.ValidationError, make_sales_order,
                          quotation.doc.name)

        quotation.submit()

        sales_order = make_sales_order(quotation.doc.name)

        self.assertEquals(sales_order[0]["doctype"], "Sales Order")
        self.assertEquals(len(sales_order), 2)
        self.assertEquals(sales_order[1]["doctype"], "Sales Order Item")
        self.assertEquals(sales_order[1]["prevdoc_docname"],
                          quotation.doc.name)
        self.assertEquals(sales_order[0]["customer"], "_Test Customer")

        sales_order[0]["delivery_date"] = "2014-01-01"
        sales_order[0]["naming_series"] = "_T-Quotation-"
        webnotes.bean(sales_order).insert()
Example #47
0
def make_return_jv_from_delivery_note(se, ref):
	invoices_against_delivery = get_invoice_list("Sales Invoice Item", "delivery_note",
		ref.doclist[0].name)
	
	if not invoices_against_delivery:
		sales_orders_against_delivery = [d.against_sales_order for d in ref.doclist if d.against_sales_order]
		
		if sales_orders_against_delivery:
			invoices_against_delivery = get_invoice_list("Sales Invoice Item", "sales_order",
				sales_orders_against_delivery)
			
	if not invoices_against_delivery:
		return []
		
	packing_item_parent_map = dict([[d.item_code, d.parent_item] for d in ref.doclist.get(
		{"parentfield": ref.parentfields[1]})])
	
	parent = {}
	children = []
	
	for se_item in se.doclist.get({"parentfield": "mtn_details"}):
		for sales_invoice in invoices_against_delivery:
			si = webnotes.bean("Sales Invoice", sales_invoice)
			
			if se_item.item_code in packing_item_parent_map:
				ref_item = si.doclist.get({"item_code": packing_item_parent_map[se_item.item_code]})
			else:
				ref_item = si.doclist.get({"item_code": se_item.item_code})
			
			if not ref_item:
				continue
				
			ref_item = ref_item[0]
			
			account = get_sales_account_from_item(si.doclist, ref_item)
			
			if account not in children:
				children.append(account)
			
			if not parent:
				parent = {"account": si.doc.debit_to}

			break
			
	if len(invoices_against_delivery) == 1:
		parent["against_invoice"] = invoices_against_delivery[0]
	
	result = [parent] + [{"account": account} for account in children]
	
	return result
Example #48
0
 def test_overlapping_conditions(self):
     for range_a, range_b in [
         ((50, 150), (0, 100)),
         ((50, 150), (100, 200)),
         ((50, 150), (75, 125)),
         ((50, 150), (25, 175)),
         ((50, 150), (50, 150)),
     ]:
         shipping_rule = webnotes.bean(copy=test_records[0])
         shipping_rule.doclist[1].from_value = range_a[0]
         shipping_rule.doclist[1].to_value = range_a[1]
         shipping_rule.doclist[2].from_value = range_b[0]
         shipping_rule.doclist[2].to_value = range_b[1]
         self.assertRaises(OverlappingConditionError, shipping_rule.insert)
Example #49
0
	def on_submit(self):
		if not getlist(self.doclist, 'maintenance_schedule_detail'):
			msgprint("Please click on 'Generate Schedule' to get schedule")
			raise Exception
		self.check_serial_no_added()
		self.validate_serial_no_warranty()
		self.validate_schedule()

		email_map ={}
		for d in getlist(self.doclist, 'item_maintenance_detail'):
			if d.serial_no:
				self.update_amc_date(d.serial_no, d.end_date)

			if d.incharge_name not in email_map:
				email_map[d.incharge_name] = webnotes.bean("Sales Person", 
					d.incharge_name).run_method("get_email_id")

			scheduled_date =webnotes.conn.sql("select scheduled_date from `tabMaintenance Schedule Detail` \
				where incharge_name='%s' and item_code='%s' and parent='%s' " %(d.incharge_name, \
				d.item_code, self.doc.name), as_dict=1)

			for key in scheduled_date:
				if email_map[d.incharge_name]:
					description = "Reference: %s, Item Code: %s and Customer: %s" % \
						(self.doc.name, d.item_code, self.doc.customer)
					webnotes.bean({
						"doctype": "Event",
						"owner": email_map[d.incharge_name] or self.doc.owner,
						"subject": description,
						"description": description,
						"starts_on": key["scheduled_date"] + " 10:00:00",
						"event_type": "Private",
						"ref_type": self.doc.doctype,
						"ref_name": self.doc.name
					}).insert()

		webnotes.conn.set(self.doc, 'status', 'Submitted')		
Example #50
0
def execute():
    webnotes.reload_doc("selling", "doctype", "shopping_cart_price_list")
    webnotes.reload_doc("setup", "doctype", "item_price")

    for t in [
        ("Supplier Quotation", "price_list_name", "buying_price_list"),
        ("Purchase Order", "price_list_name", "buying_price_list"),
        ("Purchase Invoice", "price_list_name", "buying_price_list"),
        ("Purchase Receipt", "price_list_name", "buying_price_list"),
        ("Quotation", "price_list_name", "selling_price_list"),
        ("Sales Order", "price_list_name", "selling_price_list"),
        ("Delivery Note", "price_list_name", "selling_price_list"),
        ("Sales Invoice", "price_list_name", "selling_price_list"),
        ("POS Setting", "price_list_name", "selling_price_list"),
        ("Shopping Cart Price List", "price_list", "selling_price_list"),
        ("Item Price", "price_list_name", "price_list"),
        ("BOM", "price_list", "buying_price_list"),
    ]:
        table_columns = webnotes.conn.get_table_columns(t[0])
        if t[2] in table_columns and t[1] in table_columns:
            # already reloaded, so copy into new column and drop old column
            webnotes.conn.sql("""update `tab%s` set `%s`=`%s`""" %
                              (t[0], t[2], t[1]))
            webnotes.conn.sql_ddl("""alter table `tab%s` drop column `%s`""" %
                                  (t[0], t[1]))
        elif t[1] in table_columns:
            webnotes.conn.sql_ddl(
                "alter table `tab%s` change `%s` `%s` varchar(180)" % t)

        webnotes.reload_doc(webnotes.conn.get_value("DocType", t[0], "module"),
                            "DocType", t[0])

    webnotes.conn.sql("""update tabSingles set field='selling_price_list'
		where field='price_list_name' and doctype='Selling Settings'""")

    webnotes.reload_doc("Selling", "DocType", "Selling Settings")
    webnotes.bean("Selling Settings").save()
Example #51
0
	def test_sales_invoice_calculation_export_currency(self):
		si = webnotes.bean(copy=test_records[2])
		si.doc.currency = "USD"
		si.doc.conversion_rate = 50
		si.doclist[1].export_rate = 1
		si.doclist[1].ref_rate = 1
		si.doclist[2].export_rate = 3
		si.doclist[2].ref_rate = 3
		si.insert()
		
		expected_values = {
			"keys": ["ref_rate", "adj_rate", "export_rate", "export_amount", 
				"base_ref_rate", "basic_rate", "amount"],
			"_Test Item Home Desktop 100": [1, 0, 1, 10, 50, 50, 500],
			"_Test Item Home Desktop 200": [3, 0, 3, 15, 150, 150, 750],
		}
		
		# check if children are saved
		self.assertEquals(len(si.doclist.get({"parentfield": "entries"})),
			len(expected_values)-1)
		
		# check if item values are calculated
		for d in si.doclist.get({"parentfield": "entries"}):
			for i, k in enumerate(expected_values["keys"]):
				self.assertEquals(d.fields.get(k), expected_values[d.item_code][i])
		
		# check net total
		self.assertEquals(si.doc.net_total, 1250)
		self.assertEquals(si.doc.net_total_export, 25)
		
		# check tax calculation
		expected_values = {
			"keys": ["tax_amount", "total"],
			"_Test Account Shipping Charges - _TC": [100, 1350],
			"_Test Account Customs Duty - _TC": [125, 1475],
			"_Test Account Excise Duty - _TC": [140, 1615],
			"_Test Account Education Cess - _TC": [2.8, 1617.8],
			"_Test Account S&H Education Cess - _TC": [1.4, 1619.2],
			"_Test Account CST - _TC": [32.38, 1651.58],
			"_Test Account VAT - _TC": [156.25, 1807.83],
			"_Test Account Discount - _TC": [-180.78, 1627.05]
		}
		
		for d in si.doclist.get({"parentfield": "other_charges"}):
			for i, k in enumerate(expected_values["keys"]):
				self.assertEquals(d.fields.get(k), expected_values[d.account_head][i])
				
		self.assertEquals(si.doc.grand_total, 1627.05)
		self.assertEquals(si.doc.grand_total_export, 32.54)
    def test_material_issue_gl_entry(self):
        self._clear_stock_account_balance()
        set_perpetual_inventory()

        self._insert_material_receipt()

        mi = webnotes.bean(copy=test_records[1])
        mi.insert()
        mi.submit()

        self.check_stock_ledger_entries(
            "Stock Entry", mi.doc.name,
            [["_Test Item", "_Test Warehouse - _TC", -40.0]])

        stock_in_hand_account = webnotes.conn.get_value(
            "Account", {
                "account_type": "Warehouse",
                "master_name": mi.doclist[1].s_warehouse
            })

        self.check_gl_entries(
            "Stock Entry", mi.doc.name,
            sorted([[stock_in_hand_account, 0.0, 4000.0],
                    ["Stock Adjustment - _TC", 4000.0, 0.0]]))

        mi.cancel()
        self.assertFalse(
            webnotes.conn.sql(
                """select * from `tabStock Ledger Entry` 
			where voucher_type='Stock Entry' and voucher_no=%s""", mi.doc.name))

        self.assertFalse(
            webnotes.conn.sql(
                """select * from `tabGL Entry` 
			where voucher_type='Stock Entry' and voucher_no=%s""", mi.doc.name))

        self.assertEquals(
            webnotes.conn.get_value(
                "Bin", {
                    "warehouse": mi.doclist[1].s_warehouse,
                    "item_code": mi.doclist[1].item_code
                }, "actual_qty"), 50)

        self.assertEquals(
            webnotes.conn.get_value(
                "Bin", {
                    "warehouse": mi.doclist[1].s_warehouse,
                    "item_code": mi.doclist[1].item_code
                }, "stock_value"), 5000)
Example #53
0
def add_comment(args=None):
	"""
		args = {
			'comment': '',
			'comment_by': '',
			'comment_by_fullname': '',
			'comment_doctype': '',
			'comment_docname': '',
			'page_name': '',
		}
	"""
	
	if not args: 
		args = webnotes.local.form_dict
	args['doctype'] = "Comment"

	page_name = args.get("page_name")
	if "page_name" in args:
		del args["page_name"]
	if "cmd" in args:
		del args["cmd"]

	comment = webnotes.bean(args)
	comment.ignore_permissions = True
	comment.insert()
	
	# since comments are embedded in the page, clear the web cache
	webnotes.webutils.clear_cache(page_name)

	# notify commentors 
	commentors = [d[0] for d in webnotes.conn.sql("""select comment_by from tabComment where
		comment_doctype=%s and comment_docname=%s and
		ifnull(unsubscribed, 0)=0""", (comment.doc.comment_doctype, comment.doc.comment_docname))]
	
	owner = webnotes.conn.get_value(comment.doc.comment_doctype, comment.doc.comment_docname, "owner")
	
	from webnotes.utils.email_lib.bulk import send
	send(recipients=list(set(commentors + [owner])), 
		doctype='Comment', 
		email_field='comment_by', 
		subject='New Comment on %s: %s' % (comment.doc.comment_doctype, 
			comment.doc.title or comment.doc.comment_docname), 
		message='%(comment)s<p>By %(comment_by_fullname)s</p>' % args,
		ref_doctype=comment.doc.comment_doctype, ref_docname=comment.doc.comment_docname)
	
	template = webnotes.get_template("lib/website/templates/includes/comment.html")
	
	return template.render({"comment": comment.doc.fields})
	
Example #54
0
def make_return_jv_from_purchase_receipt(se, ref):
    invoice_against_receipt = get_invoice_list("Purchase Invoice Item",
                                               "purchase_receipt",
                                               ref.doclist[0].name)

    if not invoice_against_receipt:
        purchase_orders_against_receipt = [
            d.prevdoc_docname
            for d in ref.doclist.get({"prevdoc_doctype": "Purchase Order"})
            if d.prevdoc_docname
        ]

        if purchase_orders_against_receipt:
            invoice_against_receipt = get_invoice_list(
                "Purchase Invoice Item", "purchase_order",
                purchase_orders_against_receipt)

    if not invoice_against_receipt:
        return []

    parent = {}
    children = []

    for se_item in se.doclist.get({"parentfield": "mtn_details"}):
        for purchase_invoice in invoice_against_receipt:
            pi = webnotes.bean("Purchase Invoice", purchase_invoice)
            ref_item = pi.doclist.get({"item_code": se_item.item_code})

            if not ref_item:
                continue

            ref_item = ref_item[0]

            account = ref_item.expense_head

            if account not in children:
                children.append(account)

            if not parent:
                parent = {"account": pi.doc.credit_to}

            break

    if len(invoice_against_receipt) == 1:
        parent["against_voucher"] = invoice_against_receipt[0]

    result = [parent] + [{"account": account} for account in children]

    return result
Example #55
0
    def test_make_sales_invoice(self):
        from selling.doctype.sales_order.sales_order import make_sales_invoice

        so = webnotes.bean(copy=test_records[0]).insert()

        self.assertRaises(webnotes.ValidationError, make_sales_invoice,
                          so.doc.name)

        sales_order = webnotes.bean("Sales Order", so.doc.name)
        sales_order.submit()
        si = make_sales_invoice(so.doc.name)

        self.assertEquals(si[0]["doctype"], "Sales Invoice")
        self.assertEquals(len(si), len(sales_order.doclist))
        self.assertEquals(
            len([d for d in si if d["doctype"] == "Sales Invoice Item"]), 1)

        si = webnotes.bean(si)
        si.insert()
        si.submit()

        si1 = make_sales_invoice(so.doc.name)
        self.assertEquals(
            len([d for d in si1 if d["doctype"] == "Sales Invoice Item"]), 0)
Example #56
0
    def create_dn_against_so(self, so, delivered_qty=0):
        from stock.doctype.delivery_note.test_delivery_note import test_records as dn_test_records
        from stock.doctype.delivery_note.test_delivery_note import _insert_purchase_receipt

        _insert_purchase_receipt(so.doclist[1].item_code)

        dn = webnotes.bean(webnotes.copy_doclist(dn_test_records[0]))
        dn.doclist[1].item_code = so.doclist[1].item_code
        dn.doclist[1].against_sales_order = so.doc.name
        dn.doclist[1].prevdoc_detail_docname = so.doclist[1].name
        if delivered_qty:
            dn.doclist[1].qty = delivered_qty
        dn.insert()
        dn.submit()
        return dn
    def test_closing_entry(self):
        # clear GL Entries
        webnotes.conn.sql("""delete from `tabGL Entry`""")

        from accounts.doctype.journal_voucher.test_journal_voucher import test_records as jv_records
        jv = webnotes.bean(copy=jv_records[2])
        jv.insert()
        jv.submit()

        jv1 = webnotes.bean(copy=jv_records[0])
        jv1.doclist[2].account = "_Test Account Cost for Goods Sold - _TC"
        jv1.doclist[2].debit = 600.0
        jv1.doclist[1].credit = 600.0
        jv1.insert()
        jv1.submit()

        pcv = webnotes.bean(copy=test_record)
        pcv.insert()
        pcv.submit()

        gl_entries = webnotes.conn.sql("""select account, debit, credit
			from `tabGL Entry` where voucher_type='Period Closing Voucher' and voucher_no=%s
			order by account asc, debit asc""",
                                       pcv.doc.name,
                                       as_dict=1)

        self.assertTrue(gl_entries)

        expected_gl_entries = sorted(
            [["_Test Account Reserves and Surplus - _TC", 200.0, 0.0],
             ["_Test Account Cost for Goods Sold - _TC", 0.0, 600.0],
             ["Sales - _TC", 400.0, 0.0]])
        for i, gle in enumerate(gl_entries):
            self.assertEquals(expected_gl_entries[i][0], gle.account)
            self.assertEquals(expected_gl_entries[i][1], gle.debit)
            self.assertEquals(expected_gl_entries[i][2], gle.credit)
Example #58
0
def add_support_communication(subject,
                              content,
                              sender,
                              docname=None,
                              mail=None):
    if docname:
        ticket = webnotes.bean("Support Ticket", docname)
        ticket.doc.status = 'Open'
        ticket.ignore_permissions = True
        ticket.doc.save()
    else:
        ticket = webnotes.bean([
            decode_dict({
                "doctype": "Support Ticket",
                "description": content,
                "subject": subject,
                "raised_by": sender,
                "content_type": mail.content_type if mail else None,
                "status": "Open",
            })
        ])
        ticket.ignore_permissions = True
        ticket.insert()

    make(content=content,
         sender=sender,
         subject=subject,
         doctype="Support Ticket",
         name=ticket.doc.name,
         date=mail.date if mail else today(),
         sent_or_received="Received")

    if mail:
        mail.save_attachments_in_doc(ticket.doc)

    return ticket
Example #59
0
def get_transaction_context(doctype, name):
    customer = webnotes.conn.get_value("Contact",
                                       {"email_id": webnotes.session.user},
                                       "customer")

    bean = webnotes.bean(doctype, name)
    if bean.doc.customer != customer:
        return {"doc": {"name": "Not Allowed"}}
    else:
        return {
            "doc": bean.doc,
            "doclist": bean.doclist,
            "webnotes": webnotes,
            "utils": webnotes.utils
        }
Example #60
0
 def update_parent_account(self):
     if not self.doc.__islocal and (
             self.doc.create_account_under != webnotes.conn.get_value(
                 "Warehouse", self.doc.name, "create_account_under")):
         warehouse_account = webnotes.conn.get_value(
             "Account", {
                 "account_type": "Warehouse",
                 "company": self.doc.company,
                 "master_name": self.doc.name
             }, ["name", "parent_account"])
         if warehouse_account and warehouse_account[
                 1] != self.doc.create_account_under:
             acc_bean = webnotes.bean("Account", warehouse_account[0])
             acc_bean.doc.parent_account = self.doc.create_account_under
             acc_bean.save()