Beispiel #1
0
def _get_cart_quotation(party=None):
	if not party:
		party = get_lead_or_customer()

	quotation = frappe.db.get_value("Quotation",
		{party.doctype.lower(): party.name, "order_type": "Shopping Cart", "docstatus": 0})

	if quotation:
		qdoc = frappe.get_doc("Quotation", quotation)
	else:
		qdoc = frappe.get_doc({
			"doctype": "Quotation",
			"naming_series": frappe.defaults.get_user_default("shopping_cart_quotation_series") or "QTN-CART-",
			"quotation_to": party.doctype,
			"company": frappe.db.get_value("Shopping Cart Settings", None, "company"),
			"order_type": "Shopping Cart",
			"status": "Draft",
			"docstatus": 0,
			"__islocal": 1,
			(party.doctype.lower()): party.name
		})

		if party.doctype == "Customer":
			qdoc.contact_person = frappe.db.get_value("Contact", {"email_id": frappe.session.user,
				"customer": party.name})

		qdoc.ignore_permissions = True
		qdoc.run_method("set_missing_values")
		apply_cart_settings(party, qdoc)

	return qdoc
	def test_material_request_type_manufacture(self):
		mr = frappe.copy_doc(test_records[1]).insert()
		mr = frappe.get_doc("Material Request", mr.name)
		mr.submit()
		completed_qty = mr.items[0].ordered_qty
		requested_qty = frappe.db.sql("""select indented_qty from `tabBin` where \
			item_code= %s and warehouse= %s """, (mr.items[0].item_code, mr.items[0].warehouse))[0][0]

		prod_order = raise_production_orders(mr.name)
		po = frappe.get_doc("Production Order", prod_order[0])
		po.wip_warehouse = "_Test Warehouse 1 - _TC"
		po.submit()
		
		mr = frappe.get_doc("Material Request", mr.name)
		self.assertEquals(completed_qty + po.qty, mr.items[0].ordered_qty)

		new_requested_qty = frappe.db.sql("""select indented_qty from `tabBin` where \
			item_code= %s and warehouse= %s """, (mr.items[0].item_code, mr.items[0].warehouse))[0][0]
		
		self.assertEquals(requested_qty - po.qty, new_requested_qty)
		
		po.cancel()

		mr = frappe.get_doc("Material Request", mr.name)
		self.assertEquals(completed_qty, mr.items[0].ordered_qty)
		
		new_requested_qty = frappe.db.sql("""select indented_qty from `tabBin` where \
			item_code= %s and warehouse= %s """, (mr.items[0].item_code, mr.items[0].warehouse))[0][0]
		self.assertEquals(requested_qty, new_requested_qty)
Beispiel #3
0
def login_feed(login_manager):
	frappe.get_doc({
		"doctype": "Feed",
		"feed_type": "Login",
		"subject": _("{0} logged in").format(get_fullname(login_manager.user)),
		"full_name": get_fullname(login_manager.user)
	}).insert(ignore_permissions=True)
Beispiel #4
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 = frappe.db.get_value("Contact", {"email_id": frappe.session.user,
			"customer": party.name})
		contact = frappe.get_doc("Contact", contact_name)
		contact.first_name = fullname
		contact.last_name = None
		contact.customer_name = party.customer_name
		contact.mobile_no = mobile_no
		contact.phone = phone
		contact.ignore_permissions = True
		contact.save()

	party_doc = frappe.get_doc(party.as_dict())
	party_doc.ignore_permissions = True
	party_doc.save()

	qdoc = _get_cart_quotation(party)
	if not qdoc.get("__islocal"):
		qdoc.customer_name = company_name or fullname
		qdoc.run_method("set_missing_lead_customer_details")
		qdoc.ignore_permissions = True
		qdoc.save()
Beispiel #5
0
def set_tax_withholding_category(company):
	accounts = []
	abbr = frappe.get_value("Company", company, "abbr")
	tds_account = frappe.get_value("Account", 'TDS Payable - {0}'.format(abbr), 'name')

	if company and tds_account:
		accounts = [dict(company=company, account=tds_account)]

	fiscal_year = get_fiscal_year(today(), company=company)[0]
	docs = get_tds_details(accounts, fiscal_year)

	for d in docs:
		try:
			doc = frappe.get_doc(d)
			doc.flags.ignore_permissions = True
			doc.flags.ignore_mandatory = True
			doc.insert()
		except frappe.DuplicateEntryError:
			doc = frappe.get_doc("Tax Withholding Category", d.get("name"))
			doc.append("accounts", accounts[0])

			# if fiscal year don't match with any of the already entered data, append rate row
			fy_exist = [k for k in doc.get('rates') if k.get('fiscal_year')==fiscal_year]
			if not fy_exist:
				doc.append("rates", d.get('rates')[0])

			doc.save()
	def test_overlapping_allocation(self):		
		employee = frappe.get_doc("Employee", frappe.db.sql_list("select name from tabEmployee limit 1")[0])
		leaves = [
			{
				"doctype": "Leave Allocation",
				"__islocal": 1,
				"employee": employee.name,
				"employee_name": employee.employee_name,
				"leave_type": "_Test Leave Type",
				"from_date": getdate("2015-10-1"),
				"to_date": getdate("2015-10-31"),
				"new_leaves_allocated": 5,
				"docstatus": 1			
			},
			{
				"doctype": "Leave Allocation",
				"__islocal": 1,
				"employee": employee.name,
				"employee_name": employee.employee_name,
				"leave_type": "_Test Leave Type",
				"from_date": getdate("2015-09-1"),
				"to_date": getdate("2015-11-30"),
				"new_leaves_allocated": 5			
			}
		]

		frappe.get_doc(leaves[0]).save()
		self.assertRaises(frappe.ValidationError, frappe.get_doc(leaves[1]).save)
Beispiel #7
0
def update_feed(doc, method=None):
	"adds a new feed"
	if frappe.flags.in_patch or frappe.flags.in_install or frappe.flags.in_import:
		return

	if doc.doctype == "Feed":
		return

	if hasattr(doc, "get_feed"):
		feed = doc.get_feed()

		if feed:
			if isinstance(feed, basestring):
				feed = {"subject": feed}

			feed = frappe._dict(feed)
			doctype = feed.doctype or doc.doctype
			name = feed.name or doc.name

			# delete earlier feed
			frappe.db.sql("""delete from tabFeed
				where doc_type=%s and doc_name=%s
				and ifnull(feed_type,'')=''""", (doctype, name))

			frappe.get_doc({
				"doctype": "Feed",
				"feed_type": feed.feed_type or "",
				"doc_type": doctype,
				"doc_name": name,
				"subject": feed.subject,
				"full_name": get_fullname(doc.owner)
			}).insert(ignore_permissions=True)
	def test_expense_claim_status(self):
		payable_account = get_payable_account("Wind Power LLC")
		expense_claim = frappe.get_doc({
			 "doctype": "Expense Claim",
			 "employee": "_T-Employee-0001",
			 "payable_account": payable_account,
			 "approval_status": "Approved",
			 "expenses":
			 	[{ "expense_type": "Travel", "default_account": "Travel Expenses - WP", "claim_amount": 300, "sanctioned_amount": 200 }]
		})
		expense_claim.submit()

		je_dict = make_bank_entry(expense_claim.name)
		je = frappe.get_doc(je_dict)
		je.posting_date = nowdate()
		je.cheque_no = random_string(5)
		je.cheque_date = nowdate()
		je.submit()

		expense_claim = frappe.get_doc("Expense Claim", expense_claim.name)
		self.assertEqual(expense_claim.status, "Paid")
		
		je.cancel()
		expense_claim = frappe.get_doc("Expense Claim", expense_claim.name)
		self.assertEqual(expense_claim.status, "Unpaid")
Beispiel #9
0
	def test_import_only_children(self):
		user_email = "*****@*****.**"
		if frappe.db.exists("User", user_email):
			frappe.delete_doc("User", user_email)

		frappe.get_doc({"doctype": "User", "email": user_email, "first_name": "Test Import UserRole"}).insert()

		exporter.get_template("UserRole", "User", all_doctypes="No", with_data="No")
		content = read_csv_content(frappe.response.result)
		content.append(["", "*****@*****.**", "Blogger"])
		importer.upload(content)

		user = frappe.get_doc("User", user_email)
		self.assertEquals(len(user.get("user_roles")), 1)
		self.assertTrue(user.get("user_roles")[0].role, "Blogger")

		# overwrite
		exporter.get_template("UserRole", "User", all_doctypes="No", with_data="No")
		content = read_csv_content(frappe.response.result)
		content.append(["", "*****@*****.**", "Website Manager"])
		importer.upload(content, overwrite=True)

		user = frappe.get_doc("User", user_email)
		self.assertEquals(len(user.get("user_roles")), 1)
		self.assertTrue(user.get("user_roles")[0].role, "Website Manager")
Beispiel #10
0
	def enable_shopping_cart(self):
		settings = frappe.get_doc("Shopping Cart Settings", "Shopping Cart Settings")

		settings.update({
			"enabled": 1,
			"company": "_Test Company",
			"default_customer_group": "_Test Customer Group",
			"quotation_series": "_T-Quotation-",
			"price_list": "_Test Price List India"
		})

		# insert item price
		if not frappe.db.get_value("Item Price", {"price_list":  "_Test Price List India",
			"item_code": "_Test Item"}):
			frappe.get_doc({
				"doctype": "Item Price",
				"price_list": "_Test Price List India",
				"item_code": "_Test Item",
				"price_list_rate": 10
			}).insert()
			frappe.get_doc({
				"doctype": "Item Price",
				"price_list": "_Test Price List India",
				"item_code": "_Test Item 2",
				"price_list_rate": 20
			}).insert()

		settings.save()
		frappe.local.shopping_cart_settings = None
Beispiel #11
0
def notify_unreplied():
	"""Sends email notifications if there are unreplied Communications
		and `notify_if_unreplied` is set as true."""

	for email_account in frappe.get_all("Email Account", "name", filters={"enable_incoming": 1, "notify_if_unreplied": 1}):
		email_account = frappe.get_doc("Email Account", email_account.name)
		if email_account.append_to:

			# get open communications younger than x mins, for given doctype
			for comm in frappe.get_all("Communication", "name", filters={
					"sent_or_received": "Received",
					"reference_doctype": email_account.append_to,
					"unread_notification_sent": 0,
					"creation": ("<", datetime.now() - timedelta(seconds = (email_account.unreplied_for_mins or 30) * 60)),
					"creation": (">", datetime.now() - timedelta(seconds = (email_account.unreplied_for_mins or 30) * 60 * 3))
				}):
				comm = frappe.get_doc("Communication", comm.name)

				if frappe.db.get_value(comm.reference_doctype, comm.reference_name, "status")=="Open":
					# if status is still open
					frappe.sendmail(recipients=email_account.get_unreplied_notification_emails(),
						content=comm.content, subject=comm.subject, doctype= comm.reference_doctype,
						name=comm.reference_name, bulk=True)

				# update flag
				comm.db_set("unread_notification_sent", 1)
Beispiel #12
0
def make_item_price(item, price_list_name, item_price):
	frappe.get_doc({
		"doctype": "Item Price",
		"price_list": price_list_name,
		"item_code": item,
		"price_list_rate": item_price
	}).insert()
Beispiel #13
0
def create_fiscal_year_and_company(args):
	if (args.get('fy_start_date')):
		curr_fiscal_year = get_fy_details(args.get('fy_start_date'), args.get('fy_end_date'))
		frappe.get_doc({
		"doctype":"Fiscal Year",
		'year': curr_fiscal_year,
		'year_start_date': args.get('fy_start_date'),
		'year_end_date': args.get('fy_end_date'),
		}).insert()
		args["curr_fiscal_year"] = curr_fiscal_year

	# Company
	if (args.get('company_name')):
		frappe.get_doc({
			"doctype":"Company",
			'company_name':args.get('company_name').strip(),
			'abbr':args.get('company_abbr'),
			'default_currency':args.get('currency'),
			'country': args.get('country'),
			'create_chart_of_accounts_based_on': 'Standard Template',
			'chart_of_accounts': args.get('chart_of_accounts'),
			'domain': args.get('domain')
		}).insert()

		#Enable shopping cart
		enable_shopping_cart(args)

		# Bank Account
		create_bank_account(args)
Beispiel #14
0
	def test_make_item_variant_with_numeric_values(self):
		# cleanup
		for d in frappe.db.get_all('Item', filters={'variant_of':
				'_Test Numeric Template Item'}):
			frappe.delete_doc_if_exists("Item", d.name)

		frappe.delete_doc_if_exists("Item", "_Test Numeric Template Item")
		frappe.delete_doc_if_exists("Item Attribute", "Test Item Length")

		frappe.db.sql('''delete from `tabItem Variant Attribute`
			where attribute="Test Item Length"''')

		frappe.flags.attribute_values = None

		# make item attribute
		frappe.get_doc({
			"doctype": "Item Attribute",
			"attribute_name": "Test Item Length",
			"numeric_values": 1,
			"from_range": 0.0,
			"to_range": 100.0,
			"increment": 0.5
		}).insert()

		# make template item
		make_item("_Test Numeric Template Item", {
			"attributes": [
				{
					"attribute": "Test Size"
				},
				{
					"attribute": "Test Item Length",
					"numeric_values": 1,
					"from_range": 0.0,
					"to_range": 100.0,
					"increment": 0.5
				}
			],
			"item_defaults": [
				{
					"default_warehouse": "_Test Warehouse - _TC",
					"company": "_Test Company"
				}
			],
			"has_variants": 1
		})

		variant = create_variant("_Test Numeric Template Item",
			{"Test Size": "Large", "Test Item Length": 1.1})
		self.assertEqual(variant.item_code, "_Test Numeric Template Item-L-1.1")
		variant.item_code = "_Test Numeric Variant-L-1.1"
		variant.item_name = "_Test Numeric Variant Large 1.1m"
		self.assertRaises(InvalidItemAttributeValueError, variant.save)

		variant = create_variant("_Test Numeric Template Item",
			{"Test Size": "Large", "Test Item Length": 1.5})
		self.assertEqual(variant.item_code, "_Test Numeric Template Item-L-1.5")
		variant.item_code = "_Test Numeric Variant-L-1.5"
		variant.item_name = "_Test Numeric Variant Large 1.5m"
		variant.save()
Beispiel #15
0
def init_for_archive_request(doc):
	doc = json.loads(doc)
	validate_for_archive_request(doc)
	create_archive_request(doc)
	send_archive_notification(doc)
	comment = "File status Changed to Archive Pending for request type Archive."
	frappe.get_doc("IP File", doc.get("file_name")).add_comment(comment)
Beispiel #16
0
	def update_bin(self):
		# update bin
		bin_name = frappe.db.get_value("Bin", {
			"item_code": self.item_code,
			"warehouse": self.warehouse
		})

		if not bin_name:
			bin_doc = frappe.get_doc({
				"doctype": "Bin",
				"item_code": self.item_code,
				"warehouse": self.warehouse
			})
			bin_doc.insert(ignore_permissions=True)
		else:
			bin_doc = frappe.get_doc("Bin", bin_name)

		bin_doc.update({
			"valuation_rate": self.valuation_rate,
			"actual_qty": self.qty_after_transaction,
			"stock_value": self.stock_value
		})
		bin_doc.flags.via_stock_ledger_entry = True
		
		bin_doc.save(ignore_permissions=True)
Beispiel #17
0
	def test_copy_fields_from_template_to_variants(self):
		frappe.delete_doc_if_exists("Item", "_Test Variant Item-XL", force=1)

		fields = [{'field_name': 'item_group'}, {'field_name': 'is_stock_item'}]
		allow_fields = [d.get('field_name') for d in fields]
		set_item_variant_settings(fields)

		if not frappe.db.get_value('Item Attribute Value',
			{'parent': 'Test Size', 'attribute_value': 'Extra Large'}, 'name'):
			item_attribute = frappe.get_doc('Item Attribute', 'Test Size')
			item_attribute.append('item_attribute_values', {
				'attribute_value' : 'Extra Large',
				'abbr': 'XL'
			})
			item_attribute.save()

		template = frappe.get_doc('Item', '_Test Variant Item')
		template.item_group = "_Test Item Group D"
		template.save()

		variant = create_variant("_Test Variant Item", {"Test Size": "Extra Large"})
		variant.item_code = "_Test Variant Item-XL"
		variant.item_name = "_Test Variant Item-XL"
		variant.save()

		variant = frappe.get_doc('Item', '_Test Variant Item-XL')
		for fieldname in allow_fields:
			self.assertEqual(template.get(fieldname), variant.get(fieldname))

		template = frappe.get_doc('Item', '_Test Variant Item')
		template.item_group = "_Test Item Group Desktops"
		template.save()
Beispiel #18
0
	def on_submit(self):
		self.validate_pos_paid_amount()

		if not self.recurring_id:
			frappe.get_doc('Authorization Control').validate_approving_authority(self.doctype,
			 	self.company, self.base_grand_total, self)

		self.check_prev_docstatus()

		if self.is_return:
			# NOTE status updating bypassed for is_return
			self.status_updater = []

		self.update_status_updater_args()
		self.update_prevdoc_status()
		self.update_billing_status_in_dn()
		self.clear_unallocated_mode_of_payments()

		# Updating stock ledger should always be called after updating prevdoc status,
		# because updating reserved qty in bin depends upon updated delivered qty in SO
		if self.update_stock == 1:
			self.update_stock_ledger()

		# this sequence because outstanding may get -ve
		self.make_gl_entries()

		if not self.is_return:
			self.update_billing_status_for_zero_amount_refdoc("Sales Order")
			self.check_credit_limit()

		if not cint(self.is_pos) == 1 and not self.is_return:
			self.update_against_document_in_jv()

		self.update_time_sheet(self.name)
def create_feed_and_todo():
	"""update Activity feed and create todo for creation of item, customer, vendor"""
	frappe.get_doc({
		"doctype": "Feed",
		"feed_type": "Comment",
		"subject": "ERPNext Setup Complete!"
	}).insert(ignore_permissions=True)
Beispiel #20
0
	def test_insert_if_owner_with_user_permissions(self):
		"""If `If Owner` is checked for a Role, check if that document is allowed to be read, updated, submitted, etc. except be created, even if the document is restricted based on User Permissions."""
		self.set_user_permission_doctypes(["Blog Category"])
		self.if_owner_setup()

		frappe.set_user("*****@*****.**")

		doc = frappe.get_doc({
			"doctype": "Blog Post",
			"blog_category": "_Test Blog Category",
			"blogger": "_Test Blogger 1",
			"title": "_Test Blog Post Title",
			"content": "_Test Blog Post Content"
		})

		self.assertRaises(frappe.PermissionError, doc.insert)

		frappe.set_user("Administrator")
		frappe.permissions.add_user_permission("Blog Category", "_Test Blog Category",
			"*****@*****.**")

		frappe.set_user("*****@*****.**")
		doc.insert()

		frappe.set_user("Administrator")
		frappe.permissions.remove_user_permission("Blog Category", "_Test Blog Category",
			"*****@*****.**")

		frappe.set_user("*****@*****.**")
		doc = frappe.get_doc(doc.doctype, doc.name)
		self.assertTrue(doc.has_permission("read"))
		self.assertTrue(doc.has_permission("write"))
		self.assertFalse(doc.has_permission("create"))
def create_training_program(training_program):
	if not frappe.db.get_value("Training Program", training_program):
		frappe.get_doc({
			"doctype": "Training Program",
			"training_program": training_program,
			"description": training_program
		}).insert()
	def test_warehouse_user(self):
		set_perpetual_inventory(0)

		for role in ("Stock User", "Sales User"):
			set_user_permission_doctypes(doctype="Stock Entry", role=role,
				apply_user_permissions=1, user_permission_doctypes=["Warehouse"])

		frappe.defaults.add_default("Warehouse", "_Test Warehouse 1 - _TC", "*****@*****.**", "User Permission")
		frappe.defaults.add_default("Warehouse", "_Test Warehouse 2 - _TC1", "*****@*****.**", "User Permission")
		test_user = frappe.get_doc("User", "*****@*****.**")
		test_user.add_roles("Sales User", "Sales Manager", "Stock User")
		test_user.remove_roles("Stock Manager")

		frappe.get_doc("User", "*****@*****.**")\
			.add_roles("Sales User", "Sales Manager", "Stock User", "Stock Manager")

		frappe.set_user("*****@*****.**")
		st1 = frappe.copy_doc(test_records[0])
		st1.company = "_Test Company 1"
		st1.get("items")[0].t_warehouse="_Test Warehouse 2 - _TC1"
		self.assertRaises(frappe.PermissionError, st1.insert)

		frappe.set_user("*****@*****.**")
		st1 = frappe.copy_doc(test_records[0])
		st1.company = "_Test Company 1"
		st1.get("items")[0].t_warehouse="_Test Warehouse 2 - _TC1"
		st1.insert()
		st1.submit()

		frappe.defaults.clear_default("Warehouse", "_Test Warehouse 1 - _TC",
			"*****@*****.**", parenttype="User Permission")
		frappe.defaults.clear_default("Warehouse", "_Test Warehouse 2 - _TC1",
			"*****@*****.**", parenttype="User Permission")
Beispiel #23
0
def update_user_name(args):
	if args.get("email"):
		args['name'] = args.get("email")
		frappe.flags.mute_emails = True
		frappe.get_doc({
			"doctype":"User",
			"email": args.get("email"),
			"first_name": args.get("first_name"),
			"last_name": args.get("last_name")
		}).insert()
		frappe.flags.mute_emails = False
		from frappe.auth import _update_password
		_update_password(args.get("email"), args.get("password"))

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

		# Update User
		if not args.get('last_name') or args.get('last_name')=='None':
				args['last_name'] = None
		frappe.db.sql("""update `tabUser` SET first_name=%(first_name)s,
			last_name=%(last_name)s WHERE name=%(name)s""", args)

	if args.get("attach_user"):
		attach_user = args.get("attach_user").split(",")
		if len(attach_user)==3:
			filename, filetype, content = attach_user
			fileurl = save_file(filename, content, "User", args.get("name"), decode=True).file_url
			frappe.db.set_value("User", args.get("name"), "user_image", fileurl)

	add_all_roles_to(args.get("name"))
def save_file(fname, content, dt, dn, folder=None, decode=False):
	if decode:
		if isinstance(content, unicode):
			content = content.encode("utf-8")

		if "," in content:
			content = content.split(",")[1]
		content = base64.b64decode(content)

	file_size = check_max_file_size(content)
	content_hash = get_content_hash(content)
	content_type = mimetypes.guess_type(fname)[0]
	fname = get_file_name(fname, content_hash[-6:])
	file_data = get_file_data_from_hash(content_hash)
	if not file_data:
		method = get_hook_method('write_file', fallback=save_file_on_filesystem)
		file_data = method(fname, content, content_type=content_type)
		file_data = copy(file_data)

	file_data.update({
		"doctype": "File",
		"attached_to_doctype": dt,
		"attached_to_name": dn,
		"folder": folder,
		"file_size": file_size,
		"content_hash": content_hash,
	})

	f = frappe.get_doc(file_data)
	f.flags.ignore_permissions = True
	try:
		f.insert();
	except frappe.DuplicateEntryError:
		return frappe.get_doc("File", f.duplicate_entry)
	return f
Beispiel #25
0
def create_items(args):
	for i in xrange(1,6):
		item = args.get("item_" + str(i))
		if item:
			item_group = args.get("item_group_" + str(i))
			is_sales_item = args.get("is_sales_item_" + str(i))
			is_purchase_item = args.get("is_purchase_item_" + str(i))
			is_stock_item = item_group!=_("Services")
			default_warehouse = ""
			if is_stock_item:
				if is_sales_item:
					default_warehouse = _("Finished Goods") + " - " + args.get("company_abbr")
				else:
					default_warehouse = _("Stores") + " - " + args.get("company_abbr")

			frappe.get_doc({
				"doctype":"Item",
				"item_code": item,
				"item_name": item,
				"description": item,
				"is_sales_item": "Yes" if is_sales_item else "No",
				"is_purchase_item": "Yes" if is_purchase_item else "No",
				"show_in_website": 1,
				"is_stock_item": is_stock_item and "Yes" or "No",
				"item_group": item_group,
				"stock_uom": args.get("item_uom_" + str(i)),
				"default_warehouse": default_warehouse
			}).insert()

			if args.get("item_img_" + str(i)):
				item_image = args.get("item_img_" + str(i)).split(",")
				if len(item_image)==3:
					filename, filetype, content = item_image
					fileurl = save_file(filename, content, "Item", item, decode=True).file_url
					frappe.db.set_value("Item", item, "image", fileurl)
	def check_planned_qty(self):
		set_perpetual_inventory(0)

		planned0 = frappe.db.get_value("Bin", {"item_code": "_Test FG Item", "warehouse": "_Test Warehouse 1 - _TC"}, "planned_qty") or 0

		pro_doc = frappe.copy_doc(test_records[0])
		pro_doc.insert()
		pro_doc.submit()

		# add raw materials to stores
		test_stock_entry.make_stock_entry("_Test Item", None, "Stores - _TC", 100, 100)
		test_stock_entry.make_stock_entry("_Test Item Home Desktop 100", None, "Stores - _TC", 100, 100)

		# from stores to wip
		s = frappe.get_doc(make_stock_entry(pro_doc.name, "Material Transfer", 4))
		for d in s.get("mtn_details"):
			d.s_warehouse = "Stores - _TC"
		s.fiscal_year = "_Test Fiscal Year 2013"
		s.posting_date = "2013-01-02"
		s.insert()
		s.submit()

		# from wip to fg
		s = frappe.get_doc(make_stock_entry(pro_doc.name, "Manufacture", 4))
		s.fiscal_year = "_Test Fiscal Year 2013"
		s.posting_date = "2013-01-03"
		s.insert()
		s.submit()

		self.assertEqual(frappe.db.get_value("Production Order", pro_doc.name,
			"produced_qty"), 4)
		planned1 = frappe.db.get_value("Bin", {"item_code": "_Test FG Item", "warehouse": "_Test Warehouse 1 - _TC"}, "planned_qty")
		self.assertEqual(planned1 - planned0, 6)

		return pro_doc
Beispiel #27
0
	def test_duplicate_customer(self):
		frappe.db.sql("delete from `tabCustomer` where customer_name='_Test Customer 1'")

		if not frappe.db.get_value("Customer", "_Test Customer 1"):
			test_customer_1 = frappe.get_doc({
				 "customer_group": "_Test Customer Group",
				 "customer_name": "_Test Customer 1",
				 "customer_type": "Individual",
				 "doctype": "Customer",
				 "territory": "_Test Territory"
			}).insert(ignore_permissions=True)
		else:
			test_customer_1 = frappe.get_doc("Customer", "_Test Customer 1")

		duplicate_customer = frappe.get_doc({
			 "customer_group": "_Test Customer Group",
			 "customer_name": "_Test Customer 1",
			 "customer_type": "Individual",
			 "doctype": "Customer",
			 "territory": "_Test Territory"
		}).insert(ignore_permissions=True)

		self.assertEquals("_Test Customer 1", test_customer_1.name)
		self.assertEquals("_Test Customer 1 - 1", duplicate_customer.name)
		self.assertEquals(test_customer_1.customer_name, duplicate_customer.customer_name)
Beispiel #28
0
def add_support_communication(subject, content, sender, docname=None, mail=None):
	if docname:
		ticket = frappe.get_doc("Support Ticket", docname)
		ticket.status = 'Open'
		ticket.ignore_permissions = True
		ticket.save()
	else:
		ticket = frappe.get_doc(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.ignore_mandatory = True
		ticket.insert()
	
	_make(content=content, sender=sender, subject = subject,
		doctype="Support Ticket", name=ticket.name,
		date=mail.date if mail else today(), sent_or_received="Received")

	if mail:
		mail.save_attachments_in_doc(ticket)
		
	return ticket
Beispiel #29
0
def get_context(context):
	context.no_cache = 1
	context.show_sidebar = True
	context.doc = frappe.get_doc(frappe.form_dict.doctype, frappe.form_dict.name)
	if hasattr(context.doc, "set_indicator"):
		context.doc.set_indicator()

	if show_attachments():
		context.attachments = get_attachments(frappe.form_dict.doctype, frappe.form_dict.name)

	context.parents = frappe.form_dict.parents
	context.title = frappe.form_dict.name
	context.payment_ref = frappe.db.get_value("Payment Request",
		{"reference_name": frappe.form_dict.name}, "name")

	context.enabled_checkout = frappe.get_doc("Shopping Cart Settings").enable_checkout

	default_print_format = frappe.db.get_value('Property Setter', dict(property='default_print_format', doc_type=frappe.form_dict.doctype), "value")
	if default_print_format:
		context.print_format = default_print_format
	else:
		context.print_format = "Standard"

	if not frappe.has_website_permission(context.doc):
		frappe.throw(_("Not Permitted"), frappe.PermissionError)
	
	# check for the loyalty program of the customer
	customer_loyalty_program = frappe.db.get_value("Customer", context.doc.customer, "loyalty_program")	
	if customer_loyalty_program:
		from erpnext.accounts.doctype.loyalty_program.loyalty_program import get_loyalty_program_details_with_points
		loyalty_program_details = get_loyalty_program_details_with_points(context.doc.customer, customer_loyalty_program)
		context.available_loyalty_points = int(loyalty_program_details.get("loyalty_points"))
Beispiel #30
0
	def test_asset_sale(self):
		frappe.get_doc("Asset", "Macbook Pro 1").submit()
		post_depreciation_entries(date="2021-01-01")

		si = make_sales_invoice(asset="Macbook Pro 1", item_code="Macbook Pro", company="_Test Company")
		si.customer = "_Test Customer"
		si.due_date = nowdate()
		si.get("items")[0].rate = 25000
		si.insert()
		si.submit()

		self.assertEqual(frappe.db.get_value("Asset", "Macbook Pro 1", "status"), "Sold")

		expected_gle = (
			("_Test Accumulated Depreciations - _TC", 30000.0, 0.0),
			("_Test Fixed Asset - _TC", 0.0, 100000.0),
			("_Test Gain/Loss on Asset Disposal - _TC", 45000.0, 0.0),
			("Debtors - _TC", 25000.0, 0.0)
		)

		gle = frappe.db.sql("""select account, debit, credit from `tabGL Entry`
			where voucher_type='Sales Invoice' and voucher_no = %s
			order by account""", si.name)

		self.assertEqual(gle, expected_gle)

		si.cancel()

		self.assertEqual(frappe.db.get_value("Asset", "Macbook Pro 1", "status"), "Partially Depreciated")
Beispiel #31
0
def automatic_synchronization():
    settings = frappe.get_doc("Plaid Settings", "Plaid Settings")
    if settings.enabled == 1 and settings.automatic_sync == 1:
        enqueue_synchronization()
def execute():
    companies = [
        d.name for d in frappe.get_all('Company', filters={'country': 'India'})
    ]
    if not companies:
        return

    make_custom_fields()

    # update invoice copy value
    values = [
        "Original for Recipient", "Duplicate for Transporter",
        "Duplicate for Supplier", "Triplicate for Supplier"
    ]
    for d in values:
        frappe.db.sql(
            "update `tabSales Invoice` set invoice_copy=%s where invoice_copy=%s",
            (d, d))

    # update tax breakup in transactions made after 1st July 2017
    doctypes = [
        "Quotation", "Sales Order", "Delivery Note", "Sales Invoice",
        "Supplier Quotation", "Purchase Order", "Purchase Receipt",
        "Purchase Invoice"
    ]

    for doctype in doctypes:
        frappe.reload_doctype(doctype)

        date_field = "posting_date"
        if doctype in [
                "Quotation", "Sales Order", "Supplier Quotation",
                "Purchase Order"
        ]:
            date_field = "transaction_date"

        records = [
            d.name
            for d in frappe.get_all(doctype,
                                    filters={
                                        "docstatus": ["!=", 2],
                                        date_field: [">=", "2017-07-01"],
                                        "company": ["in", companies],
                                        "total_taxes_and_charges": [">", 0],
                                        "other_charges_calculation": ""
                                    })
        ]
        if records:
            frappe.db.sql(
                """
				update `tab%s Item` dt_item
				set gst_hsn_code = (select gst_hsn_code from tabItem where name=dt_item.item_code)
				where parent in (%s)
					and (gst_hsn_code is null or gst_hsn_code = '')
			""" % (doctype, ', '.join(['%s'] * len(records))), tuple(records))

            for record in records:
                doc = frappe.get_doc(doctype, record)
                html = get_itemised_tax_breakup_html(doc)
                doc.db_set("other_charges_calculation",
                           html,
                           update_modified=False)
Beispiel #33
0
def mark_as_seen(note):
    note = frappe.get_doc('Note', note)
    if frappe.session.user not in [d.user for d in note.seen_by]:
        note.append('seen_by', {'user': frappe.session.user})
        note.save(ignore_version=True)
Beispiel #34
0
def get_subscription_updates(name):
    """
	Use this to get the latest state of the given `Subscription`
	"""
    subscription = frappe.get_doc('Subscription', name)
    subscription.process()
Beispiel #35
0
def make_depreciation_entry(asset_name, date=None):
	frappe.has_permission('Journal Entry', throw=True)

	if not date:
		date = today()

	asset = frappe.get_doc("Asset", asset_name)
	fixed_asset_account, accumulated_depreciation_account, depreciation_expense_account = \
		get_depreciation_accounts(asset)

	depreciation_cost_center, depreciation_series = frappe.get_cached_value('Company',  asset.company,
		["depreciation_cost_center", "series_for_depreciation_entry"])

	depreciation_cost_center = asset.cost_center or depreciation_cost_center

	accounting_dimensions = get_checks_for_pl_and_bs_accounts()

	for d in asset.get("schedules"):
		if not d.journal_entry and getdate(d.schedule_date) <= getdate(date):
			je = frappe.new_doc("Journal Entry")
			je.voucher_type = "Depreciation Entry"
			je.naming_series = depreciation_series
			je.posting_date = d.schedule_date
			je.company = asset.company
			je.finance_book = d.finance_book
			je.remark = "Depreciation Entry against {0} worth {1}".format(asset_name, d.depreciation_amount)

			credit_entry = {
				"account": accumulated_depreciation_account,
				"credit_in_account_currency": d.depreciation_amount,
				"reference_type": "Asset",
				"reference_name": asset.name,
				"cost_center": ""
			}

			debit_entry = {
				"account": depreciation_expense_account,
				"debit_in_account_currency": d.depreciation_amount,
				"reference_type": "Asset",
				"reference_name": asset.name,
				"cost_center": depreciation_cost_center
			}

			for dimension in accounting_dimensions:
				if (asset.get(dimension['fieldname']) or dimension.get('mandatory_for_bs')):
					credit_entry.update({
						dimension['fieldname']: asset.get(dimension['fieldname']) or dimension.get('default_dimension')
					})

				if (asset.get(dimension['fieldname']) or dimension.get('mandatory_for_pl')):
					debit_entry.update({
						dimension['fieldname']: asset.get(dimension['fieldname']) or dimension.get('default_dimension')
					})

			je.append("accounts", credit_entry)

			je.append("accounts", debit_entry)

			je.flags.ignore_permissions = True
			je.save()
			if not je.meta.get_workflow():
				je.submit()

			d.db_set("journal_entry", je.name)

			idx = cint(d.finance_book_id)
			finance_books = asset.get('finance_books')[idx - 1]
			finance_books.value_after_depreciation -= d.depreciation_amount
			finance_books.db_update()

	asset.set_status()

	return asset
def make_purchase_invoice_of_sales_order(doc,method):
	for row in doc.taxes:

		if "22750 - Freight Payable" in row.account_head and row.tax_amount>0:
			purchase_invoice=frappe.get_doc(
				{
					'doctype': 'Purchase Invoice',
					"naming_series": "P-SO-",
					"remarks": doc.name,
					"cust_sales_order": doc.name,
					"docstatus": 1,
					"discount_amount": 0,
					"supplier": "LOADER BIKE",
					"supplier_name": "LOADER BIKE",
					"is_paid": 0,
					"company": doc.company,
					"set_posting_time": 0,
					"is_return": 0,
					"ignore_pricing_rule": 1,
					"update_stock": 0,
					"submit_on_creation": 1,
					"items": [
						{
							"item_code": "99999",
							"item_name": "FREIGHT CHARGES",
							"qty": 1,
							"cost_center": doc.cost_center,
							"rate": row.tax_amount,
							"received_qty": 1,
							"uom": "Nos",
							"conversion_factor": 1
						}
					]

				})
			purchase_invoice.flags.ignore_permissions == True
			purchase_invoice.insert(ignore_permissions = True)
			frappe.msgprint("Purchase Invoice has been Created.")

		if "22755 - Cutting / Fitting Charges" in row.account_head and row.tax_amount>0:
			purchase_invoice=frappe.get_doc(
				{
					'doctype': 'Purchase Invoice',
					"naming_series": "P-SO-",
					"remarks": doc.name,
					"cust_sales_order": doc.name,
					"docstatus": 1,
					"discount_amount": 0,
					"supplier": "Cutting / Fitting",
					"supplier_name": "Cutting / Fitting",
					"is_paid": 0,
					"company": doc.company,
					"set_posting_time": 0,
					"is_return": 0,
					"ignore_pricing_rule": 1,
					"update_stock": 0,
					"submit_on_creation": 1,
					"items": [
						{
							"item_code": "99998",
							"item_name": "Cutting / Fitting Charges",
							"qty": 1,
							"cost_center": doc.cost_center,
							"rate": row.tax_amount,
							"received_qty": 1,
							"uom": "Nos",
							"conversion_factor": 1
						}
					]

				})
			purchase_invoice.flags.ignore_permissions == True
			purchase_invoice.insert(ignore_permissions = True)
			frappe.msgprint("Purchase Invoice has been Created.")
Beispiel #37
0
def add_bank_accounts(response, bank, company):
    try:
        response = json.loads(response)
    except TypeError:
        pass

    bank = json.loads(bank)
    result = []

    default_gl_account = get_default_bank_cash_account(company, "Bank")
    if not default_gl_account:
        frappe.throw(
            _("Please setup a default bank account for company {0}").format(
                company))

    for account in response["accounts"]:
        acc_type = frappe.db.get_value("Bank Account Type", account["type"])
        if not acc_type:
            add_account_type(account["type"])

        acc_subtype = frappe.db.get_value("Bank Account Subtype",
                                          account["subtype"])
        if not acc_subtype:
            add_account_subtype(account["subtype"])

        bank_account_name = "{} - {}".format(account["name"],
                                             bank["bank_name"])
        existing_bank_account = frappe.db.exists("Bank Account",
                                                 bank_account_name)

        if not existing_bank_account:
            try:
                new_account = frappe.get_doc({
                    "doctype":
                    "Bank Account",
                    "bank":
                    bank["bank_name"],
                    "account":
                    default_gl_account.account,
                    "account_name":
                    account["name"],
                    "account_type":
                    account.get("type", ""),
                    "account_subtype":
                    account.get("subtype", ""),
                    "mask":
                    account.get("mask", ""),
                    "integration_id":
                    account["id"],
                    "is_company_account":
                    1,
                    "company":
                    company
                })
                new_account.insert()

                result.append(new_account.name)
            except frappe.UniqueValidationError:
                frappe.msgprint(
                    _("Bank account {0} already exists and could not be created again"
                      ).format(account["name"]))
            except Exception:
                frappe.log_error(frappe.get_traceback(),
                                 title=_("Plaid Link Error"))
                frappe.throw(_(
                    "There was an error creating Bank Account while linking with Plaid."
                ),
                             title=_("Plaid Link Failed"))

        else:
            try:
                existing_account = frappe.get_doc('Bank Account',
                                                  existing_bank_account)
                existing_account.update({
                    "bank":
                    bank["bank_name"],
                    "account_name":
                    account["name"],
                    "account_type":
                    account.get("type", ""),
                    "account_subtype":
                    account.get("subtype", ""),
                    "mask":
                    account.get("mask", ""),
                    "integration_id":
                    account["id"]
                })
                existing_account.save()
                result.append(existing_bank_account)
            except Exception:
                frappe.log_error(frappe.get_traceback(),
                                 title=_("Plaid Link Error"))
                frappe.throw(_(
                    "There was an error updating Bank Account {} while linking with Plaid."
                ).format(existing_bank_account),
                             title=_("Plaid Link Failed"))

    return result
Beispiel #38
0
def create_delivery_note(source_name, target_doc=None):
    pick_list = frappe.get_doc('Pick List', source_name)
    validate_item_locations(pick_list)

    sales_orders = [
        d.sales_order for d in pick_list.locations if d.sales_order
    ]
    sales_orders = set(sales_orders)

    delivery_note = None
    for sales_order in sales_orders:
        delivery_note = create_delivery_note_from_sales_order(
            sales_order, delivery_note, skip_item_mapping=True)

    # map rows without sales orders as well
    if not delivery_note:
        delivery_note = frappe.new_doc("Delivery Note")

    item_table_mapper = {
        'doctype':
        'Delivery Note Item',
        'field_map': {
            'rate': 'rate',
            'name': 'so_detail',
            'parent': 'against_sales_order',
        },
        'condition':
        lambda doc: abs(doc.delivered_qty) < abs(doc.qty) and doc.
        delivered_by_supplier != 1
    }

    item_table_mapper_without_so = {
        'doctype': 'Delivery Note Item',
        'field_map': {
            'rate': 'rate',
            'name': 'name',
            'parent': '',
        }
    }

    for location in pick_list.locations:
        if location.sales_order_item:
            sales_order_item = frappe.get_cached_doc(
                'Sales Order Item', {'name': location.sales_order_item})
        else:
            sales_order_item = None

        source_doc, table_mapper = [sales_order_item, item_table_mapper] if sales_order_item \
         else [location, item_table_mapper_without_so]

        dn_item = map_child_doc(source_doc, delivery_note, table_mapper)
        coa_batch = None
        if location.source_package_tag:
            coa_batch = frappe.db.get_value("Package Tag",
                                            location.source_package_tag,
                                            "coa_batch_no")

        if dn_item:
            dn_item.warehouse = location.warehouse
            dn_item.qty = location.picked_qty
            dn_item.batch_no = location.batch_no
            dn_item.serial_no = location.serial_no
            dn_item.coa_batch = coa_batch

            update_delivery_note_item(source_doc, dn_item, delivery_note)

    set_delivery_note_missing_values(delivery_note)

    delivery_note.pick_list = pick_list.name
    delivery_note.customer = pick_list.customer if pick_list.customer else None

    return delivery_note
Beispiel #39
0
 def test_parent_warehouse(self):
     parent_warehouse = frappe.get_doc("Warehouse",
                                       "_Test Warehouse Group - _TC")
     self.assertEquals(parent_warehouse.is_group, 1)
    def on_submit(self):
        # stock_account = frappe.get_list(
        #     "Account",
        #     filters={"company_name": self.company, "account_name": "Stock in Hand"},
        # )
        # print(stock_account)
        # expense = frappe.get_list(
        #     "Account",
        #     filters={"company_name": self.company, "account_name": "Stock Expense"},
        # )
        # print(expense)
        # JEl1 = {
        #     "credit": self.total_amount,
        #     "debit": 0,
        #     "account": stock_account[0].name,
        #     "party_type": "Customer",
        #     "party_name": self.customer,
        # }
        # JEl2 = {
        #     "credit": 0,
        #     "debit": self.total_amount,
        #     "account": expense[0].name,
        # }
        # JE = frappe.get_doc(
        #     {
        #         "doctype": "Journal Entry",
        #         "company": self.company,
        #         "entry_date": self.posting_date,
        #         "entry_lines": [JEl1, JEl2]
        #         # "reference_number": ,
        #         # "reference_date": ,
        #     }
        # )
        # JE.insert()

        gl_entry = frappe.get_doc(
            {
                "doctype": "GL Entry",
                "posting_date": self.posting_date,
                "transaction_date": self.posting_date,
                "account": self.debit_account,
                "party_type": "Customer",
                "party": self.customer,
                "debit": self.total_amount,
                "credit": 0,
                "against": self.credit_account,
                "against_voucher": "Delivery Note",
                "voucher_number": self.name,
                "company": self.company,
                "fiscal_year": "2020-2021"
            }
        )
        gl_entry.insert()
        gl_entry = frappe.get_doc(
            {
                "doctype": "GL Entry",
                "posting_date": self.posting_date,
                "transaction_date": self.posting_date,
                "account": self.credit_account,
                "party_type": "Customer",
                "party": self.customer,
                "debit": 0,
                "credit": self.total_amount,
                "against": self.debit_account,
                "against_voucher": "Delivery Note",
                "voucher_number": self.name,
                "company": self.company,
                "fiscal_year": "2020-2021"
            }
        )
        gl_entry.insert()
def get_file_data_from_hash(content_hash):
	for name in frappe.db.sql_list("select name from `tabFile Data` where content_hash=%s", content_hash):
		b = frappe.get_doc('File Data', name)
		return {k:b.get(k) for k in frappe.get_hooks()['write_file_keys']}
	return False
Beispiel #42
0
def create_users(args):
    if frappe.session.user == 'Administrator':
        return

    # create employee for self
    emp = frappe.get_doc({
        "doctype":
        "Employee",
        "employee_name":
        " ".join(filter(None, [args.get("first_name"),
                               args.get("last_name")])),
        "user_id":
        frappe.session.user,
        "status":
        "Active",
        "company":
        args.get("company_name")
    })
    emp.flags.ignore_mandatory = True
    emp.insert(ignore_permissions=True)

    for i in xrange(1, 5):
        email = args.get("user_email_" + str(i))
        fullname = args.get("user_fullname_" + str(i))
        if email:
            if not fullname:
                fullname = email.split("@")[0]

            parts = fullname.split(" ", 1)

            user = frappe.get_doc({
                "doctype": "User",
                "email": email,
                "first_name": parts[0],
                "last_name": parts[1] if len(parts) > 1 else "",
                "enabled": 1,
                "user_type": "System User"
            })

            # default roles
            user.append_roles("Projects User", "Stock User", "Support Team")

            if args.get("user_sales_" + str(i)):
                user.append_roles("Sales User", "Sales Manager",
                                  "Accounts User")
            if args.get("user_purchaser_" + str(i)):
                user.append_roles("Purchase User", "Purchase Manager",
                                  "Accounts User")
            if args.get("user_accountant_" + str(i)):
                user.append_roles("Accounts Manager", "Accounts User")

            user.flags.delay_emails = True

            if not frappe.db.get_value("User", email):
                user.insert(ignore_permissions=True)

                # create employee
                emp = frappe.get_doc({
                    "doctype": "Employee",
                    "employee_name": fullname,
                    "user_id": email,
                    "status": "Active",
                    "company": args.get("company_name")
                })
                emp.flags.ignore_mandatory = True
                emp.insert(ignore_permissions=True)
Beispiel #43
0
 def get_rate(self, arg):
     return frappe.get_doc('Purchase Common').get_rate(arg, self)
Beispiel #44
0
def get(chart_name=None, chart=None, no_cache=None, filters=None, from_date=None,
        to_date=None, timespan=None, time_interval=None, heatmap_year=None):
    if chart_name:
        chart = frappe.get_doc('Dashboard Chart', chart_name)
    else:
        chart = frappe._dict(frappe.parse_json(chart))

    filters = frappe.parse_json(filters)

    data = frappe.db.get_list('Medical Department', fields=['name'])
    if not filters:
        filters = {}

    status = ['Open', 'Scheduled', 'Closed', 'Cancelled']
    for department in data:
        filters['department'] = department.name
        department['total_appointments'] = frappe.db.count(
            'Patient Appointment', filters=filters)

        for entry in status:
            filters['status'] = entry
            department[frappe.scrub(entry)] = frappe.db.count(
                'Patient Appointment', filters=filters)
        filters.pop('status')

    sorted_department_map = sorted(
        data, key=lambda i: i['total_appointments'], reverse=True)

    if len(sorted_department_map) > 10:
        sorted_department_map = sorted_department_map[:10]

    labels = []
    open_appointments = []
    scheduled = []
    closed = []
    cancelled = []

    for department in sorted_department_map:
        labels.append(department.name)
        open_appointments.append(department.open)
        scheduled.append(department.scheduled)
        closed.append(department.closed)
        cancelled.append(department.cancelled)

    return {
        'labels': labels,
        'datasets': [
            {
                'name': 'Open',
                'values': open_appointments
            },
            {
                'name': 'Scheduled',
                'values': scheduled
            },
            {
                'name': 'Closed',
                'values': closed
            },
            {
                'name': 'Cancelled',
                'values': cancelled
            }
        ],
        'type': 'bar'
    }
Beispiel #45
0
def get_html(doc,
             name=None,
             print_format=None,
             meta=None,
             no_letterhead=None,
             trigger_print=False):

    if isinstance(no_letterhead, basestring):
        no_letterhead = cint(no_letterhead)
    elif no_letterhead is None:
        no_letterhead = not cint(
            frappe.db.get_single_value("Print Settings", "with_letterhead"))

    if isinstance(doc, basestring) and isinstance(name, basestring):
        doc = frappe.get_doc(doc, name)

    if isinstance(doc, basestring):
        doc = frappe.get_doc(json.loads(doc))

    doc.flags.in_print = True

    if not frappe.flags.ignore_print_permissions:
        validate_print_permission(doc)

    if hasattr(doc, "before_print"):
        doc.before_print()

    if not hasattr(doc, "print_heading"): doc.print_heading = None
    if not hasattr(doc, "sub_heading"): doc.sub_heading = None

    if not meta:
        meta = frappe.get_meta(doc.doctype)

    jenv = frappe.get_jenv()
    format_data, format_data_map = [], {}

    # determine template
    if print_format in ("Standard", standard_format):
        template = "standard"
    else:
        print_format = frappe.get_doc("Print Format", print_format)
        if print_format.custom_format:
            template = jenv.from_string(
                get_print_format(doc.doctype, print_format))

        elif print_format.format_data:
            # set format data
            format_data = json.loads(print_format.format_data)
            for df in format_data:
                format_data_map[df.get("fieldname")] = df
                if "visible_columns" in df:
                    for _df in df.get("visible_columns"):
                        format_data_map[_df.get("fieldname")] = _df

            doc.format_data_map = format_data_map

            template = "standard"

        else:
            # fallback
            template = "standard"

    if template == "standard":
        template = jenv.get_template("templates/print_formats/standard.html")

    args = {
        "doc": doc,
        "meta": frappe.get_meta(doc.doctype),
        "layout": make_layout(doc, meta, format_data),
        "no_letterhead": no_letterhead,
        "trigger_print": cint(trigger_print),
        "letter_head": get_letter_head(doc, no_letterhead)
    }

    html = template.render(args, filters={"len": len})

    return html
Beispiel #46
0
 def set_missing_values(source, target):
     doc = frappe.get_doc(target)
     doc.run_method("set_missing_values")
     doc.run_method("calculate_taxes_and_totals")
Beispiel #47
0
def print_via_printnode(action, **kwargs):
    settings = frappe.get_doc("Print Node Settings", "Print Node Settings")
    if not settings.api_key:
        frappe.throw(
            _("Your Print Node API Key is not configured in Print Node Settings"
              ))
    if not frappe.db.exists("Print Node Action", action):
        frappe.throw(
            _("Unable to find an action in Print settings to execute this print"
              ))
    else:
        action = frappe.get_doc("Print Node Action", action)
        if not kwargs.get('doctype') and action.get('print_format'):
            kwargs['doctype'] = frappe.db.get_value('Print Format',
                                                    action.print_format,
                                                    'doc_type')

    if action.get("capabilities"):
        print_settings = json.loads(action.capabilities)
    else:
        print_settings = {}

    if 'collate' in print_settings:
        print_settings['collate'] = bool(print_settings['collate'])

    printer = frappe.db.get_value("Print Node Hardware", action.printer,
                                  "hw_id")

    gateway = Gateway(apikey=settings.api_key)

    if action.printable_type == "Print Format":
        print_content = get_print_content(
            action.print_format if not action.use_standard else "Standard",
            kwargs.get("doctype"), kwargs.get("docname"),
            action.is_xml_esc_pos, action.is_raw_text)
        raw = action.is_xml_esc_pos or action.is_raw_text
        gateway.PrintJob(printer=int(printer),
                         job_type="raw" if raw else "pdf",
                         title=action.action,
                         base64=print_content,
                         options=print_settings)
    else:
        print_content = b64encode(get_file("File", kwargs.get("filename"))[1])
        gateway.PrintJob(
            printer=int(printer),
            job_type="pdf"
            if kwargs.get("filename", "").lower().endswith(".pdf") else "raw",
            base64=print_content,
            options=print_settings)

    job = frappe.new_doc("Print Node Job").update({
        "print_node_action":
        action.name,
        "printer_id":
        action.printer,
        "print_type":
        "File" if action.printable_type == "Attachment" else "Print Format",
        "file_link":
        kwargs.get("filename"),
        "print_format":
        action.print_format if not action.use_standard else "Standard",
        "ref_type":
        kwargs.get("doctype"),
        "ref_name":
        kwargs.get("docname"),
        "is_xml_esc_pos":
        action.is_xml_esc_pos,
        "is_raw_text":
        action.is_raw_text,
        "print_job_name":
        action.action,
        "copies":
        print_settings.get('copies', 1),
        "job_owner":
        frappe.local.session.user,
        "print_timestamp":
        now_datetime()
    })
    job.flags.ignore_permissions = True
    job.flags.ignore_links = True
    job.flags.ignore_validate = True
    job.insert()
def update_status(status, name):
	po = frappe.get_doc("Purchase Order", name)
	po.update_status(status)
	po.update_delivered_qty_in_sales_order()
def send_summary():
    '''Send summary to everyone'''
    for d in frappe.get_all('Daily Work Summary', dict(status='Open')):
        daily_work_summary = frappe.get_doc('Daily Work Summary', d.name)
        daily_work_summary.send_summary()
Beispiel #50
0
def execute():
    frappe.reload_doctype("System Settings")
    system_settings = frappe.get_doc("System Settings")
    system_settings.ignore_user_permissions_if_missing = 1
    system_settings.flags.ignore_mandatory = 1
    system_settings.save()
	def test_loyalty_points_for_dashboard(self):
		doc = frappe.get_doc('Customer', 'Test Loyalty Customer')
		company_wise_info = get_dashboard_info("Customer", doc.name, doc.loyalty_program)

		for d in company_wise_info:
			self.assertTrue(d.get("loyalty_points"))
def changeLevel(data):
    from frappe.auth import LoginManager
    login_manager = LoginManager()
    login_manager.authenticate("Administrator", "heyram108")
    login_manager.post_login()
    company = json.loads(data)
    logging.warning("blank+" + str(json.dumps(company)))
    if company["l1"] == None or company["l1"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='Small'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l2"] == None or company["l2"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='Med'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l3"] == None or company["l3"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='Wholesale'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l4"] == None or company["l4"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='SMR'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l5"] == None or company["l5"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='CC'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l6"] == None or company["l6"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='OR/DUN'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l7"] == None or company["l7"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='OM'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l8"] == None or company["l8"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='BV'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l9"] == None or company["l9"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='SFM'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l10"] == None or company["l10"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='IFL/AFCH'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l11"] == None or company["l11"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='IPP'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l12"] == None or company["l12"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='GMBL'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l13"] == None or company["l13"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='MNLY'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l14"] == None or company["l14"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='HWAI'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l15"] == None or company["l15"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='PANCH'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l16"] == None or company["l16"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='NSS'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l17"] == None or company["l17"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='WIN'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l18"] == None or company["l18"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='IBF/R'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l19"] == None or company["l19"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='IBI/K'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l20"] == None or company["l20"] == '':
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='BOND'""",
            company["name"])
        if data:
            delete(doctype='Item Price', name=data[0][0])

    if company["l1"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='Small'""",
            company["name"])
        if data:
            if not int(company["l1"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l1"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "Small",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "Small",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l1"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l2"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='Med'""",
            company["name"])
        if data:
            if not int(company["l2"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l1"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "Med",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "Med",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l2"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l3"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='Wholesale'""",
            company["name"])
        if data:
            if not int(company["l3"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l1"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "Wholesale",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "Wholesale",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l3"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l4"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='SMR'""",
            company["name"])
        if data:
            if not int(company["l4"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l1"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "SMR",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "SMR",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l4"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l5"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='CC'""",
            company["name"])
        if data:
            if not int(company["l5"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l1"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "CC",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "CC",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l5"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l6"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='OR/DUN'""",
            company["name"])
        if data:
            if not int(company["l6"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l1"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "OR/DUN",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "OR/DUN",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l6"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l7"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='OM'""",
            company["name"])
        if data:
            if not int(company["l7"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l1"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "OM",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "OM",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l7"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l8"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='BV'""",
            company["name"])
        if data:
            if not int(company["l8"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l1"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "BV",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "BV",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l8"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l9"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='SFM'""",
            company["name"])
        if data:
            if not int(company["l9"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l1"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "SFM",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "SFM",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l9"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l10"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='IFL/AFCH'""",
            company["name"])
        if data:
            if not int(company["l10"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l1"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "IFL/AFCH",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "IFL/AFCH",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l10"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l11"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='IPP'""",
            company["name"])
        if data:
            if not int(company["l11"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l11"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "IPP",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "IPP",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l11"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l12"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='GMBL'""",
            company["name"])
        if data:
            if not int(company["l12"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l12"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "GMBL",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "GMBL",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l12"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l13"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='MNLY'""",
            company["name"])
        if data:
            if not int(company["l13"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l13"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "MNLY",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "MNLY",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l13"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l14"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='HWAI'""",
            company["name"])
        if data:
            if not int(company["l14"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l14"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "HWAI",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "HWAI",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l14"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l15"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='PANCH'""",
            company["name"])
        if data:
            if not int(company["l15"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l15"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "PANCH",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "PANCH",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l15"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l16"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='NSS'""",
            company["name"])
        if data:
            if not int(company["l16"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l16"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "NSS",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "NSS",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l16"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l17"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='WIN'""",
            company["name"])
        if data:
            if not int(company["l17"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l17"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "WIN",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "WIN",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l17"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l18"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='IBF/R'""",
            company["name"])
        if data:
            if not int(company["l18"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l18"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "IBF/R",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "IBF/R",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l18"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l19"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='IBI/K'""",
            company["name"])
        if data:
            if not int(company["l19"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l19"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "IBI/K",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "IBI/K",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l19"]
            })
            d1 = d.insert(ignore_permissions=True)

    if company["l20"]:
        data = frappe.db.sql(
            """select name,price_list_rate from `tabItem Price` where item_code=%s and price_list='BOND'""",
            company["name"])
        if data:
            if not int(company["l20"]) == int(data[0][1]):
                logging.warning("Inside+" + str(data[0][0]))
                d2 = frappe.get_doc("Item Price", data[0][0])
                d = frappe.get_doc({
                    "price_list_rate": company["l20"],
                    "selling": 1,
                    "name": data[0][0],
                    "currency": "INR",
                    "price_list": "BOND",
                    "item_code": company["name"],
                    "doctype": "Item Price",
                    "docstatus": 0,
                    "buying": 0,
                    "modified": d2.modified
                })
                d1 = d.save()
        else:
            d = frappe.get_doc({
                "docstatus": 0,
                "doctype": "Item Price",
                "name": "New Item Price 1",
                "owner": "Administrator",
                "currency": "INR",
                "price_list": "BOND",
                "buying": 0,
                "selling": 1,
                "item_code": str(company["name"]),
                "price_list_rate": company["l20"]
            })
            d1 = d.insert(ignore_permissions=True)
def pull_from_email_account(email_account):
	'''Runs within a worker process'''
	email_account = frappe.get_doc("Email Account", email_account)
	email_account.receive()
def create_records():
	# create a new loyalty Account
	if frappe.db.exists("Account", "Loyalty - _TC"):
		return

	frappe.get_doc({
		"doctype": "Account",
		"account_name": "Loyalty",
		"parent_account": "Direct Expenses - _TC",
		"company": "_Test Company",
		"is_group": 0,
		"account_type": "Expense Account",
	}).insert()

	# create a new loyalty program Single tier
	frappe.get_doc({
		"doctype": "Loyalty Program",
		"loyalty_program_name": "Test Single Loyalty",
		"auto_opt_in": 1,
		"from_date": today(),
		"loyalty_program_type": "Single Tier Program",
		"conversion_factor": 1,
		"expiry_duration": 10,
		"company": "_Test Company",
		"cost_center": "Main - _TC",
		"expense_account": "Loyalty - _TC",
		"collection_rules": [{
			'tier_name': 'Silver',
			'collection_factor': 1000,
			'min_spent': 1000
		}]
	}).insert()

	# create a new customer
	frappe.get_doc({
		"customer_group": "_Test Customer Group",
		"customer_name": "Test Loyalty Customer",
		"customer_type": "Individual",
		"doctype": "Customer",
		"territory": "_Test Territory"
	}).insert()

	# create a new loyalty program Multiple tier
	frappe.get_doc({
		"doctype": "Loyalty Program",
		"loyalty_program_name": "Test Multiple Loyalty",
		"auto_opt_in": 1,
		"from_date": today(),
		"loyalty_program_type": "Multiple Tier Program",
		"conversion_factor": 1,
		"expiry_duration": 10,
		"company": "_Test Company",
		"cost_center": "Main - _TC",
		"expense_account": "Loyalty - _TC",
		"collection_rules": [
			{
				'tier_name': 'Silver',
				'collection_factor': 1000,
				'min_spent': 10000
			},
			{
				'tier_name': 'Gold',
				'collection_factor': 1000,
				'min_spent': 19000
			}
		]
	}).insert()

	# create an item
	item = frappe.get_doc({
		"doctype": "Item",
		"item_code": "Loyal Item",
		"item_name": "Loyal Item",
		"item_group": "All Item Groups",
		"company": "_Test Company",
		"is_stock_item": 1,
		"opening_stock": 100,
		"valuation_rate": 10000,
	}).insert()

	# create item price
	frappe.get_doc({
		"doctype": "Item Price",
		"price_list": "Standard Selling",
		"item_code": item.item_code,
		"price_list_rate": 10000
	}).insert()
		def _check_serial_no_values(serial_no, field_values):
			serial_no = frappe.get_doc("Serial No", serial_no)
			for field, value in iteritems(field_values):
				self.assertEqual(cstr(serial_no.get(field)), value)
Beispiel #56
0
 def after_insert(self):
     if self.account_type == 'Bank':
         company = frappe.get_doc('Company', self.company)
         if not company.default_bank_account:
             company.db_set('default_bank_account', self.account_name)
def submit_sales_order(sales_order):
	if (sales_order is None): return
	order_doc = frappe.get_doc("Sales Order", sales_order)
	if (order_doc.status == 'Draft'):
		order_doc.submit()
	def set_thread(self, communication, email):
		"""Appends communication to parent based on thread ID. Will extract
		parent communication and will link the communication to the reference of that
		communication. Also set the status of parent transaction to Open or Replied.

		If no thread id is found and `append_to` is set for the email account,
		it will create a new parent transaction (e.g. Issue)"""
		in_reply_to = (email.mail.get("In-Reply-To") or "").strip(" <>")
		parent = None

		if self.append_to:
			# set subject_field and sender_field
			meta_module = frappe.get_meta_module(self.append_to)
			meta = frappe.get_meta(self.append_to)
			subject_field = getattr(meta_module, "subject_field", "subject")
			if not meta.get_field(subject_field):
				subject_field = None
			sender_field = getattr(meta_module, "sender_field", "sender")
			if not meta.get_field(sender_field):
				sender_field = None

		if in_reply_to:
			if "@{0}".format(frappe.local.site) in in_reply_to:

				# reply to a communication sent from the system
				in_reply_to, domain = in_reply_to.split("@", 1)

				if frappe.db.exists("Communication", in_reply_to):
					parent = frappe.get_doc("Communication", in_reply_to)

					# set in_reply_to of current communication
					communication.in_reply_to = in_reply_to

					if parent.reference_name:
						parent = frappe.get_doc(parent.reference_doctype,
							parent.reference_name)

		if not parent and self.append_to and sender_field:
			if subject_field:
				# try and match by subject and sender
				# if sent by same sender with same subject,
				# append it to old coversation
				subject = strip(re.sub("^\s*(Re|RE)[^:]*:\s*", "", email.subject))

				parent = frappe.db.get_all(self.append_to, filters={
					sender_field: email.from_email,
					subject_field: ("like", "%{0}%".format(subject)),
					"creation": (">", (get_datetime() - relativedelta(days=10)).strftime(DATE_FORMAT))
				}, fields="name")

				# match only subject field
				# when the from_email is of a user in the system
				# and subject is atleast 10 chars long
				if not parent and len(subject) > 10 and is_system_user(email.from_email):
					parent = frappe.db.get_all(self.append_to, filters={
						subject_field: ("like", "%{0}%".format(subject)),
						"creation": (">", (get_datetime() - relativedelta(days=10)).strftime(DATE_FORMAT))
					}, fields="name")

			if parent:
				parent = frappe.get_doc(self.append_to, parent[0].name)

		if not parent and self.append_to and self.append_to!="Communication":
			# no parent found, but must be tagged
			# insert parent type doc
			parent = frappe.new_doc(self.append_to)

			if subject_field:
				parent.set(subject_field, email.subject)

			if sender_field:
				parent.set(sender_field, email.from_email)

			parent.flags.ignore_mandatory = True

			try:
				parent.insert(ignore_permissions=True)
			except frappe.DuplicateEntryError:
				# try and find matching parent
				parent_name = frappe.db.get_value(self.append_to, {sender_field: email.from_email})
				if parent_name:
					parent.name = parent_name
				else:
					parent = None

			# NOTE if parent isn't found and there's no subject match, it is likely that it is a new conversation thread and hence is_first = True
			communication.is_first = True

		if parent:
			communication.reference_doctype = parent.doctype
			communication.reference_name = parent.name
	def revert_used_corrugated_boards(self):
		for crg_order in self.crg_orders:
			order = frappe.get_doc("CM Corrugation Order", crg_order.crg_order)
			order.stock_batch_qty = order.stock_batch_qty + crg_order.board_count
			order.save()
	def test_subcontracting_over_receipt(self):
		"""
			Behaviour: Raise multiple PRs against one PO that in total
				receive more than the required qty in the PO.
			Expected Result: Error Raised for Over Receipt against PO.
		"""
		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
		from erpnext.buying.doctype.purchase_order.test_purchase_order import (update_backflush_based_on,
			make_subcontracted_item, create_purchase_order)
		from erpnext.buying.doctype.purchase_order.purchase_order import (make_purchase_receipt,
			make_rm_stock_entry as make_subcontract_transfer_entry)

		update_backflush_based_on("Material Transferred for Subcontract")
		item_code = "_Test Subcontracted FG Item 1"
		make_subcontracted_item(item_code=item_code)

		po = create_purchase_order(item_code=item_code, qty=1,
			is_subcontracted="Yes", supplier_warehouse="_Test Warehouse 1 - _TC")

		#stock raw materials in a warehouse before transfer
		make_stock_entry(target="_Test Warehouse - _TC",
			item_code="_Test Item Home Desktop 100", qty=1, basic_rate=100)
		make_stock_entry(target="_Test Warehouse - _TC",
			item_code = "Test Extra Item 1", qty=1, basic_rate=100)
		make_stock_entry(target="_Test Warehouse - _TC",
			item_code = "_Test Item", qty=1, basic_rate=100)

		rm_items = [
			{
				"item_code": item_code,
				"rm_item_code": po.supplied_items[0].rm_item_code,
				"item_name": "_Test Item",
				"qty": po.supplied_items[0].required_qty,
				"warehouse": "_Test Warehouse - _TC",
				"stock_uom": "Nos"
			},
			{
				"item_code": item_code,
				"rm_item_code": po.supplied_items[1].rm_item_code,
				"item_name": "Test Extra Item 1",
				"qty": po.supplied_items[1].required_qty,
				"warehouse": "_Test Warehouse - _TC",
				"stock_uom": "Nos"
			},
			{
				"item_code": item_code,
				"rm_item_code": po.supplied_items[2].rm_item_code,
				"item_name": "_Test Item Home Desktop 100",
				"qty": po.supplied_items[2].required_qty,
				"warehouse": "_Test Warehouse - _TC",
				"stock_uom": "Nos"
			}
		]
		rm_item_string = json.dumps(rm_items)
		se = frappe.get_doc(make_subcontract_transfer_entry(po.name, rm_item_string))
		se.to_warehouse = "_Test Warehouse 1 - _TC"
		se.save()
		se.submit()

		pr1 = make_purchase_receipt(po.name)
		pr2 = make_purchase_receipt(po.name)

		pr1.submit()
		self.assertRaises(frappe.ValidationError, pr2.submit)