Ejemplo n.º 1
0
	def test_item_defaults(self):
		frappe.delete_doc_if_exists("Item", "Test Item With Defaults", force=1)
		make_item("Test Item With Defaults", {
			"item_group": "_Test Item Group",
			"brand": "_Test Brand With Item Defaults",
			"item_defaults": [{
				"company": "_Test Company",
				"default_warehouse": "_Test Warehouse 2 - _TC",  # no override
				"expense_account": "_Test Account Stock Expenses - _TC",  # override brand default
				"buying_cost_center": "_Test Write Off Cost Center - _TC",  # override item group default
			}]
		})

		sales_item_check = {
			"item_code": "Test Item With Defaults",
			"warehouse": "_Test Warehouse 2 - _TC",  # from item
			"income_account": "_Test Account Sales - _TC",  # from brand
			"expense_account": "_Test Account Stock Expenses - _TC",  # from item
			"cost_center": "_Test Cost Center 2 - _TC",  # from item group
		}
		sales_item_details = get_item_details({
			"item_code": "Test Item With Defaults",
			"company": "_Test Company",
			"price_list": "_Test Price List",
			"currency": "_Test Currency",
			"doctype": "Sales Invoice",
			"conversion_rate": 1,
			"price_list_currency": "_Test Currency",
			"plc_conversion_rate": 1,
			"customer": "_Test Customer",
		})
		for key, value in iteritems(sales_item_check):
			self.assertEqual(value, sales_item_details.get(key))

		purchase_item_check = {
			"item_code": "Test Item With Defaults",
			"warehouse": "_Test Warehouse 2 - _TC",  # from item
			"expense_account": "_Test Account Stock Expenses - _TC",  # from item
			"income_account": "_Test Account Sales - _TC",  # from brand
			"cost_center": "_Test Write Off Cost Center - _TC"  # from item
		}
		purchase_item_details = get_item_details({
			"item_code": "Test Item With Defaults",
			"company": "_Test Company",
			"price_list": "_Test Price List",
			"currency": "_Test Currency",
			"doctype": "Purchase Invoice",
			"conversion_rate": 1,
			"price_list_currency": "_Test Currency",
			"plc_conversion_rate": 1,
			"supplier": "_Test Supplier",
		})
		for key, value in iteritems(purchase_item_check):
			self.assertEqual(value, purchase_item_details.get(key))
Ejemplo n.º 2
0
	def complete(self):
		if self.consume_stock and self.items:
			create_stock_entry(self)
		frappe.db.set_value("Clinical Procedure", self.name, "status", 'Completed')

		if self.items:
			consumable_total_amount = 0
			consumption_details = False
			for item in self.items:
				if item.invoice_separately_as_consumables:
					price_list, price_list_currency = frappe.db.get_values("Price List", {"selling": 1}, ['name', 'currency'])[0]
					args = {
						'doctype': "Sales Invoice",
						'item_code': item.item_code,
						'company': self.company,
						'warehouse': self.warehouse,
						'customer': frappe.db.get_value("Patient", self.patient, "customer"),
						'selling_price_list': price_list,
						'price_list_currency': price_list_currency,
						'plc_conversion_rate': 1.0,
						'conversion_rate': 1.0
					}
					item_details = get_item_details(args)
					item_price = item_details.price_list_rate * item.transfer_qty
					item_consumption_details = item_details.item_name+"\t"+str(item.qty)+" "+item.uom+"\t"+str(item_price)
					consumable_total_amount += item_price
					if not consumption_details:
						consumption_details = "Clinical Procedure ("+self.name+"):\n\t"+item_consumption_details
					else:
						consumption_details += "\n\t"+item_consumption_details
			if consumable_total_amount > 0:
				frappe.db.set_value("Clinical Procedure", self.name, "consumable_total_amount", consumable_total_amount)
				frappe.db.set_value("Clinical Procedure", self.name, "consumption_details", consumption_details)
Ejemplo n.º 3
0
	def set_missing_item_details(self, for_validate=False):
		"""set missing item values"""
		from erpnext.stock.get_item_details import get_item_details
		from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos

		if hasattr(self, "items"):
			parent_dict = {}
			for fieldname in self.meta.get_valid_columns():
				parent_dict[fieldname] = self.get(fieldname)

			if self.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
				document_type = "{} Item".format(self.doctype)
				parent_dict.update({"document_type": document_type})

			for item in self.get("items"):
				if item.get("item_code"):
					args = parent_dict.copy()
					args.update(item.as_dict())

					args["doctype"] = self.doctype
					args["name"] = self.name

					if not args.get("transaction_date"):
						args["transaction_date"] = args.get("posting_date")

					if self.get("is_subcontracted"):
						args["is_subcontracted"] = self.is_subcontracted
					ret = get_item_details(args)
					for fieldname, value in ret.items():
						if item.meta.get_field(fieldname) and value is not None:
							if (item.get(fieldname) is None or fieldname in force_item_fields):
								item.set(fieldname, value)

							elif fieldname in ['cost_center', 'conversion_factor'] and not item.get(fieldname):
								item.set(fieldname, value)

							elif fieldname == "serial_no":
								# Ensure that serial numbers are matched against Stock UOM
								item_conversion_factor = item.get("conversion_factor") or 1.0
								item_qty = abs(item.get("qty")) * item_conversion_factor

								if item_qty != len(get_serial_nos(item.get('serial_no'))):
									item.set(fieldname, value)

					if self.doctype in ["Purchase Invoice", "Sales Invoice"] and item.meta.get_field('is_fixed_asset'):
						item.set('is_fixed_asset', ret.get('is_fixed_asset', 0))

					if ret.get("pricing_rule"):
						# if user changed the discount percentage then set user's discount percentage ?
						item.set("pricing_rule", ret.get("pricing_rule"))
						item.set("discount_percentage", ret.get("discount_percentage"))
						if ret.get("pricing_rule_for") == "Rate":
							item.set("price_list_rate", ret.get("price_list_rate"))

						if item.price_list_rate:
							item.rate = flt(item.price_list_rate *
											(1.0 - (flt(item.discount_percentage) / 100.0)), item.precision("rate"))

			if self.doctype == "Purchase Invoice":
				self.set_expense_account(for_validate)
Ejemplo n.º 4
0
    def set_missing_item_details(self):
        """set missing item values"""
        from erpnext.stock.get_item_details import get_item_details
        if hasattr(self, "items"):
            parent_dict = {}
            for fieldname in self.meta.get_valid_columns():
                parent_dict[fieldname] = self.get(fieldname)

            for item in self.get("items"):
                if item.get("item_code"):
                    args = parent_dict.copy()
                    args.update(item.as_dict())
                    ret = get_item_details(args)

                    for fieldname, value in ret.items():
                        if item.meta.get_field(fieldname) and \
                         item.get(fieldname) is None and value is not None:
                            item.set(fieldname, value)

                        if fieldname == "cost_center" and item.meta.get_field("cost_center") \
                         and not item.get("cost_center") and value is not None:
                            item.set(fieldname, value)

                    if ret.get("pricing_rule"):
                        for field in [
                                "base_price_list_rate", "price_list_rate",
                                "discount_percentage", "base_rate", "rate"
                        ]:
                            item.set(field, ret.get(field))
Ejemplo n.º 5
0
def make_sales_invoice(reference_name, patient, company,
                       therapy_plan_template):
    from erpnext.stock.get_item_details import get_item_details
    si = frappe.new_doc('Sales Invoice')
    si.company = company
    si.patient = patient
    si.customer = frappe.db.get_value('Patient', patient, 'customer')

    item = frappe.db.get_value('Therapy Plan Template', therapy_plan_template,
                               'linked_item')
    price_list, price_list_currency = frappe.db.get_values(
        'Price List', {'selling': 1}, ['name', 'currency'])[0]
    args = {
        'doctype': 'Sales Invoice',
        'item_code': item,
        'company': company,
        'customer': si.customer,
        'selling_price_list': price_list,
        'price_list_currency': price_list_currency,
        'plc_conversion_rate': 1.0,
        'conversion_rate': 1.0
    }

    item_line = si.append('items', {})
    item_details = get_item_details(args)
    item_line.item_code = item
    item_line.qty = 1
    item_line.rate = item_details.price_list_rate
    item_line.amount = flt(item_line.rate) * flt(item_line.qty)
    item_line.reference_dt = 'Therapy Plan'
    item_line.reference_dn = reference_name
    item_line.description = item_details.description

    si.set_missing_values(for_validate=True)
    return si
Ejemplo n.º 6
0
def get_item_details_translated(args):

    from erpnext.stock.get_item_details import get_item_details
    out = get_item_details(args)

    args = process_args(args)

    lang = "fr"

    if args.get("customer"):
        lang = frappe.db.get_value("Customer", args.customer, "language")

    if args.get("supplier"):
        lang = frappe.db.get_value("Supplier", args.supplier, "language")

    out.update({
        "description":
        frappe.db.get_value("Item Language", {
            "parent": args.item_code,
            "language": lang
        }, "description")
        or frappe.db.get_value("Item", args.item_code, "description")
    })

    if print_debug: frappe.logger().debug(out)

    return out
Ejemplo n.º 7
0
def update_stock_default_sales_order(so_name, customer, selling_price_list,
                                     price_list_currency, transaction_date,
                                     company, plc_conversion_rate,
                                     conversion_rate):
    data_sales_item = frappe.db.sql(
        "SELECT * FROM `tabSales Order Item` WHERE parent='{}'".format(
            escape_string(so_name)),
        as_dict=1)
    for dsi in data_sales_item:
        args = {
            "item_code": dsi['item_code'],
            "warehouse": dsi['warehouse'],
            "company": company,
            "customer": customer,
            "conversion_rate": dsi['conversion_factor'],
            "selling_price_list": selling_price_list,
            "price_list_currency": price_list_currency,
            "plc_conversion_rate": plc_conversion_rate,
            "doctype": "Sales Order",
            "transaction_date": transaction_date,
            "conversion_rate": conversion_rate,
            "ignore_pricing_rule": 1
        }

        item_details = get_item_details(args)
        frappe.db.sql(
            "UPDATE `tabSales Order Item` SET actual_qty={}, projected_qty={}, stock_qty={} WHERE name='{}'"
            .format(item_details['actual_qty'], item_details['projected_qty'],
                    item_details['stock_qty'], escape_string(dsi['name'])))
        frappe.db.commit()

    return data_sales_item
	def set_missing_item_details(self):
		"""set missing item values"""
		from erpnext.stock.get_item_details import get_item_details

		if hasattr(self, "items"):
			parent_dict = {}
			for fieldname in self.meta.get_valid_columns():
				parent_dict[fieldname] = self.get(fieldname)

			for item in self.get("items"):
				if item.get("item_code"):
					args = parent_dict.copy()
					args.update(item.as_dict())
					if not args.get("transaction_date"):
						args["transaction_date"] = args.get("posting_date")
					ret = get_item_details(args)

					for fieldname, value in ret.items():
						if item.meta.get_field(fieldname) and \
							item.get(fieldname) is None and value is not None:
								item.set(fieldname, value)

						if fieldname == "cost_center" and item.meta.get_field("cost_center") \
							and not item.get("cost_center") and value is not None:
								item.set(fieldname, value)

					if ret.get("pricing_rule"):
						for field in ["base_price_list_rate", "price_list_rate",
							"discount_percentage", "base_rate", "rate"]:
								item.set(field, ret.get(field))
Ejemplo n.º 9
0
    def get_item(source_doc):
        ref_doctype = "Product Assembly"
        ref_docname = source_doc.product_assembly

        doctype = "Item"
        filters = {
            "ref_doctype": ref_doctype,
            "ref_docname": ref_docname,
        }

        errmsg = translate("Item not found for Product Assembly: {}")
        if not database.exists(doctype, filters):
            frappe.throw(errmsg.format(ref_docname))

        item_doc = frappe.get_doc(doctype, filters)

        args = {
            "item_code": item_doc.name,
            "item_name": item_doc.item_name,
            "parent": target_doc.name,
            "parentfield": "items",
            "parenttype": "Quotation",
            "description": source_doc.product_assembly_specification,
            "company": defaults.company,
            "doctype": "Quotation",
            "currency": source_doc.currency,
            "qty": source_doc.qty_to_produce,
            "rate": source_doc.rate_per_unit,
        }

        return get_item_details(args)
Ejemplo n.º 10
0
	def set_missing_item_details(self, for_validate=False):
		"""set missing item values"""
		from erpnext.stock.get_item_details import get_item_details
		from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos

		if hasattr(self, "items"):
			parent_dict = {}
			for fieldname in self.meta.get_valid_columns():
				parent_dict[fieldname] = self.get(fieldname)

			if self.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
				document_type = "{} Item".format(self.doctype)
				parent_dict.update({"document_type": document_type})

			for item in self.get("items"):
				if item.get("item_code"):
					args = parent_dict.copy()
					args.update(item.as_dict())

					args["doctype"] = self.doctype
					args["name"] = self.name

					if not args.get("transaction_date"):
						args["transaction_date"] = args.get("posting_date")

					if self.get("is_subcontracted"):
						args["is_subcontracted"] = self.is_subcontracted
					ret = get_item_details(args)
					for fieldname, value in ret.items():
						if item.meta.get_field(fieldname) and value is not None:
							if (item.get(fieldname) is None or fieldname in force_item_fields):
								item.set(fieldname, value)

							elif fieldname in ['cost_center', 'conversion_factor'] and not item.get(fieldname):
								item.set(fieldname, value)

							elif fieldname == "serial_no":
								# Ensure that serial numbers are matched against Stock UOM
								item_conversion_factor = item.get("conversion_factor") or 1.0
								item_qty = abs(item.get("qty")) * item_conversion_factor

								if item_qty != len(get_serial_nos(item.get('serial_no'))):
									item.set(fieldname, value)

					if self.doctype in ["Purchase Invoice", "Sales Invoice"] and item.meta.get_field('is_fixed_asset'):
						item.set('is_fixed_asset', ret.get('is_fixed_asset', 0))

					if ret.get("pricing_rule"):
						# if user changed the discount percentage then set user's discount percentage ?
						item.set("pricing_rule", ret.get("pricing_rule"))
						item.set("discount_percentage", ret.get("discount_percentage"))
						if ret.get("pricing_rule_for") == "Rate":
							item.set("price_list_rate", ret.get("price_list_rate"))

						if item.price_list_rate:
							item.rate = flt(item.price_list_rate *
											(1.0 - (flt(item.discount_percentage) / 100.0)), item.precision("rate"))

			if self.doctype == "Purchase Invoice":
				self.set_expense_account(for_validate)
Ejemplo n.º 11
0
    def test_get_item_details_alt_uom(self):
        to_check = {
            "item_code": "_Test Item With Contents UOM",
            "qty": 1.0,
            "alt_uom": "_Test UOM 1",
            "alt_uom_size": 5,
            "alt_uom_qty": 5
        }

        details = get_item_details({
            "item_code": "_Test Item With Contents UOM",
            "company": "_Test Company",
            "price_list": "_Test Price List",
            "currency": "_Test Currency",
            "doctype": "Sales Order",
            "conversion_rate": 1,
            "price_list_currency": "_Test Currency",
            "plc_conversion_rate": 1,
            "order_type": "Sales",
            "customer": "_Test Customer",
            "conversion_factor": 1,
            "price_list_uom_dependant": 1,
            "ignore_pricing_rule": 1
        })

        for key, value in iteritems(to_check):
            self.assertEqual(value, details.get(key))
Ejemplo n.º 12
0
    def test_batch_wise_item_price(self):
        if not frappe.db.get_value("Item", "_Test Batch Price Item"):
            frappe.get_doc({
                "doctype": "Item",
                "is_stock_item": 1,
                "item_code": "_Test Batch Price Item",
                "item_group": "Products",
                "has_batch_no": 1,
                "create_new_batch": 1,
            }).insert(ignore_permissions=True)

        batch1 = create_batch("_Test Batch Price Item", 200, 1)
        batch2 = create_batch("_Test Batch Price Item", 300, 1)
        batch3 = create_batch("_Test Batch Price Item", 400, 0)

        company = "_Test Company with perpetual inventory"
        currency = frappe.get_cached_value("Company", company,
                                           "default_currency")

        args = frappe._dict({
            "item_code": "_Test Batch Price Item",
            "company": company,
            "price_list": "_Test Price List",
            "currency": currency,
            "doctype": "Sales Invoice",
            "conversion_rate": 1,
            "price_list_currency": "_Test Currency",
            "plc_conversion_rate": 1,
            "customer": "_Test Customer",
            "name": None,
        })

        # test price for batch1
        args.update({"batch_no": batch1})
        details = get_item_details(args)
        self.assertEqual(details.get("price_list_rate"), 200)

        # test price for batch2
        args.update({"batch_no": batch2})
        details = get_item_details(args)
        self.assertEqual(details.get("price_list_rate"), 300)

        # test price for batch3
        args.update({"batch_no": batch3})
        details = get_item_details(args)
        self.assertEqual(details.get("price_list_rate"), 400)
Ejemplo n.º 13
0
 def update_item_detail(item_code, config_item):
     args.update({"item_code": item_code})
     item_detail = get_item_details(args)
     for field in ['valuation_rate', 'pricing_rule', 'discount_percentage', 'discount_amount', 'price_list_rate',
                   'stock_qty','uom']:
         config_item.update({field: item_detail.get(field)})
     config_item.update({'rate': item_detail.get('rate') or config_item.get('price_list_rate') or 0})
     config_item.update({'amount': config_item.get('rate') * config_item.get('qty')})
Ejemplo n.º 14
0
	def set_missing_item_details(self, for_validate=False):
		"""set missing item values"""
		from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos

		if hasattr(self, "items"):
			parent_dict = {}
			for fieldname in self.meta.get_valid_columns():
				parent_dict[fieldname] = self.get(fieldname)

			if self.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
				document_type = "{} Item".format(self.doctype)
				parent_dict.update({"document_type": document_type})

			# party_name field used for customer in quotation
			if self.doctype == "Quotation" and self.quotation_to == "Customer" and parent_dict.get("party_name"):
				parent_dict.update({"customer": parent_dict.get("party_name")})

			for item in self.get("items"):
				if item.get("item_code"):
					args = parent_dict.copy()
					args.update(item.as_dict())

					args["doctype"] = self.doctype
					args["name"] = self.name
					args["child_docname"] = item.name

					if not args.get("transaction_date"):
						args["transaction_date"] = args.get("posting_date")

					if self.get("is_subcontracted"):
						args["is_subcontracted"] = self.is_subcontracted

					ret = get_item_details(args, self, for_validate=True, overwrite_warehouse=False)

					for fieldname, value in ret.items():
						if item.meta.get_field(fieldname) and value is not None:
							if (item.get(fieldname) is None or fieldname in force_item_fields):
								item.set(fieldname, value)

							elif fieldname in ['cost_center', 'conversion_factor'] and not item.get(fieldname):
								item.set(fieldname, value)

							elif fieldname == "serial_no":
								# Ensure that serial numbers are matched against Stock UOM
								item_conversion_factor = item.get("conversion_factor") or 1.0
								item_qty = abs(item.get("qty")) * item_conversion_factor

								if item_qty != len(get_serial_nos(item.get('serial_no'))):
									item.set(fieldname, value)

					if self.doctype in ["Purchase Invoice", "Sales Invoice"] and item.meta.get_field('is_fixed_asset'):
						item.set('is_fixed_asset', ret.get('is_fixed_asset', 0))

					if ret.get("pricing_rules"):
						self.apply_pricing_rule_on_items(item, ret)

			if self.doctype == "Purchase Invoice":
				self.set_expense_account(for_validate)
Ejemplo n.º 15
0
def get_items_from_product_bundle(args):
    args = json.loads(args)
    items = []
    bundled_items = get_product_bundle_items(args["item_code"])
    for item in bundled_items:
        args.update({"item_code": item.item_code, "qty": flt(args["quantity"]) * flt(item.qty)})
        items.append(get_item_details(args))

    return items
Ejemplo n.º 16
0
def get_items_from_product_bundle(row):
	row, items = json.loads(row), []

	bundled_items = get_product_bundle_items(row["item_code"])
	for item in bundled_items:
		row.update({"item_code": item.item_code, "qty": flt(row["quantity"]) * flt(item.qty)})
		items.append(get_item_details(row))

	return items
Ejemplo n.º 17
0
	def set_missing_item_details(self):
		"""set missing item values"""
		from erpnext.stock.get_item_details import get_item_details
		
		if self.doctype == "Purchase Invoice":
			auto_accounting_for_stock = cint(frappe.defaults.get_global_default("auto_accounting_for_stock"))

			if auto_accounting_for_stock:
				stock_not_billed_account = self.get_company_default("stock_received_but_not_billed")
				
			stock_items = self.get_stock_items()

		if hasattr(self, "items"):
			parent_dict = {}
			for fieldname in self.meta.get_valid_columns():
				parent_dict[fieldname] = self.get(fieldname)

			for item in self.get("items"):
				if item.get("item_code"):
					args = parent_dict.copy()
					args.update(item.as_dict())
					if not args.get("transaction_date"):
						args["transaction_date"] = args.get("posting_date")

					if self.get("is_subcontracted"):
						args["is_subcontracted"] = self.is_subcontracted

					ret = get_item_details(args)

					for fieldname, value in ret.items():
						if item.meta.get_field(fieldname) and value is not None:
							if (item.get(fieldname) is None or fieldname in force_item_fields):
								item.set(fieldname, value)

							elif fieldname == "cost_center" and not item.get("cost_center"):
								item.set(fieldname, value)

							elif fieldname == "conversion_factor" and not item.get("conversion_factor"):
								item.set(fieldname, value)

					if ret.get("pricing_rule"):
						item.set("discount_percentage", ret.get("discount_percentage"))
						if ret.get("pricing_rule_for") == "Price":
							item.set("pricing_list_rate", ret.get("pricing_list_rate"))

						if item.price_list_rate:
							item.rate = flt(item.price_list_rate *
								(1.0 - (flt(item.discount_percentage) / 100.0)), item.precision("rate"))
								
					if self.doctype == "Purchase Invoice":
						if auto_accounting_for_stock and item.item_code in stock_items \
							and self.is_opening == 'No' \
							and (not item.po_detail or not frappe.db.get_value("Purchase Order Item", 
								item.po_detail, "delivered_by_supplier")):
				
								item.expense_account = stock_not_billed_account
								item.cost_center = None
Ejemplo n.º 18
0
def get_item_details(args,
                     doc=None,
                     for_validate=False,
                     overwrite_warehouse=True):
    from erpnext.stock.get_item_details import get_item_details

    _args = json.loads(args) if isinstance(args, string_types) else args
    return get_item_details(dissoc(_args, "item_tax_template"), doc,
                            for_validate, overwrite_warehouse)
Ejemplo n.º 19
0
    def test_mixed_conditions_for_item_group(self):
        for item in ["Mixed Cond Item 1", "Mixed Cond Item 2"]:
            make_item(item, {"item_group": "Products"})
            make_item_price(item, "_Test Price List", 100)

        test_record = {
            "doctype":
            "Pricing Rule",
            "title":
            "_Test Pricing Rule for Item Group",
            "apply_on":
            "Item Group",
            "item_groups": [
                {
                    "item_group": "Products",
                },
                {
                    "item_group": "Seed",
                },
            ],
            "selling":
            1,
            "mixed_conditions":
            1,
            "currency":
            "USD",
            "rate_or_discount":
            "Discount Percentage",
            "discount_percentage":
            10,
            "applicable_for":
            "Customer Group",
            "customer_group":
            "All Customer Groups",
            "company":
            "_Test Company"
        }
        frappe.get_doc(test_record.copy()).insert()

        args = frappe._dict({
            "item_code": "Mixed Cond Item 1",
            "item_group": "Products",
            "company": "_Test Company",
            "price_list": "_Test Price List",
            "currency": "_Test Currency",
            "doctype": "Sales Order",
            "conversion_rate": 1,
            "price_list_currency": "_Test Currency",
            "plc_conversion_rate": 1,
            "order_type": "Sales",
            "customer": "_Test Customer",
            "customer_group": "_Test Customer Group",
            "name": None
        })
        details = get_item_details(args)
        self.assertEquals(details.get("discount_percentage"), 10)
Ejemplo n.º 20
0
def set_healthcare_services(doc, checked_values):
    import json
    doc = frappe.get_doc(json.loads(doc))
    checked_values = json.loads(checked_values)
    doc.items = []
    from erpnext.stock.get_item_details import get_item_details
    for checked_item in checked_values:
        item_line = doc.append("items", {})
        price_list, price_list_currency = frappe.db.get_values(
            "Price List", {"selling": 1}, ['name', 'currency'])[0]
        args = {
            'doctype': "Sales Invoice",
            'item_code': checked_item['item'],
            'company': doc.company,
            'customer': frappe.db.get_value("Patient", doc.patient,
                                            "customer"),
            'selling_price_list': price_list,
            'price_list_currency': price_list_currency,
            'plc_conversion_rate': 1.0,
            'conversion_rate': 1.0
        }
        item_details = get_item_details(args)
        item_line.item_code = checked_item['item']
        item_line.qty = 1
        if checked_item['qty']:
            item_line.qty = checked_item['qty']
        if checked_item['rate']:
            item_line.rate = checked_item['rate']
        else:
            item_line.rate = item_details.price_list_rate
        item_line.amount = float(item_line.rate) * float(item_line.qty)
        if checked_item['income_account']:
            item_line.income_account = checked_item['income_account']
        if checked_item['dt']:
            item_line.reference_dt = checked_item['dt']
        if checked_item['dn']:
            item_line.reference_dn = checked_item['dn']
        if checked_item['description']:
            item_line.description = checked_item['description']
        hso_doc = frappe.get_doc(item_line.reference_dt,
                                 item_line.reference_dn)
        item_line.healthcare_practitioner = hso_doc.ordered_by
        if hso_doc.order_doctype == "Medication":
            item_line.healthcare_service_unit = frappe.get_value(
                hso_doc.order_reference_doctype, hso_doc.order_reference_name,
                "healthcare_service_unit")
        else:
            item_line.healthcare_service_unit = frappe.get_value(
                hso_doc.order_doctype, hso_doc.order,
                "healthcare_service_unit")
        item_line.warehouse = get_warehouse_from_service_unit(
            item_line.healthcare_service_unit)
    doc.set_missing_values(for_validate=True)
    doc.save()
    return doc.name
Ejemplo n.º 21
0
    def complete_procedure(self):
        if self.consume_stock and self.items:
            stock_entry = make_stock_entry(self)

        if self.items:
            consumable_total_amount = 0
            consumption_details = False
            customer = frappe.db.get_value("Patient", self.patient, "customer")
            if customer:
                for item in self.items:
                    if item.invoice_separately_as_consumables:
                        price_list, price_list_currency = frappe.db.get_values(
                            "Price List", {"selling": 1},
                            ["name", "currency"])[0]
                        args = {
                            "doctype": "Sales Invoice",
                            "item_code": item.item_code,
                            "company": self.company,
                            "warehouse": self.warehouse,
                            "customer": customer,
                            "selling_price_list": price_list,
                            "price_list_currency": price_list_currency,
                            "plc_conversion_rate": 1.0,
                            "conversion_rate": 1.0,
                        }
                        item_details = get_item_details(args)
                        item_price = item_details.price_list_rate * item.qty
                        item_consumption_details = (item_details.item_name +
                                                    " " + str(item.qty) + " " +
                                                    item.uom + " " +
                                                    str(item_price))
                        consumable_total_amount += item_price
                        if not consumption_details:
                            consumption_details = _(
                                "Clinical Procedure ({0}):").format(self.name)
                        consumption_details += "\n\t" + item_consumption_details

                if consumable_total_amount > 0:
                    frappe.db.set_value("Clinical Procedure", self.name,
                                        "consumable_total_amount",
                                        consumable_total_amount)
                    frappe.db.set_value("Clinical Procedure", self.name,
                                        "consumption_details",
                                        consumption_details)
            else:
                frappe.throw(
                    _("Please set Customer in Patient {0}").format(
                        frappe.bold(self.patient)),
                    title=_("Customer Not Found"),
                )

        self.db_set("status", "Completed")

        if self.consume_stock and self.items:
            return stock_entry
Ejemplo n.º 22
0
    def test_batch_wise_item_price(self):
        if not frappe.db.get_value('Item', '_Test Batch Price Item'):
            frappe.get_doc({
                'doctype': 'Item',
                'is_stock_item': 1,
                'item_code': '_Test Batch Price Item',
                'item_group': 'Products',
                'has_batch_no': 1,
                'create_new_batch': 1
            }).insert(ignore_permissions=True)

        batch1 = create_batch('_Test Batch Price Item', 200, 1)
        batch2 = create_batch('_Test Batch Price Item', 300, 1)
        batch3 = create_batch('_Test Batch Price Item', 400, 0)

        args = frappe._dict({
            "item_code": "_Test Batch Price Item",
            "company": "_Test Company with perpetual inventory",
            "price_list": "_Test Price List",
            "currency": "_Test Currency",
            "doctype": "Sales Invoice",
            "conversion_rate": 1,
            "price_list_currency": "_Test Currency",
            "plc_conversion_rate": 1,
            "customer": "_Test Customer",
            "name": None
        })

        #test price for batch1
        args.update({'batch_no': batch1})
        details = get_item_details(args)
        self.assertEqual(details.get('price_list_rate'), 200)

        #test price for batch2
        args.update({'batch_no': batch2})
        details = get_item_details(args)
        self.assertEqual(details.get('price_list_rate'), 300)

        #test price for batch3
        args.update({'batch_no': batch3})
        details = get_item_details(args)
        self.assertEqual(details.get('price_list_rate'), 400)
Ejemplo n.º 23
0
    def set_missing_item_details(self, for_validate=False):
        """set missing item values"""
        from erpnext.stock.get_item_details import get_item_details

        if hasattr(self, "items"):
            parent_dict = {}
            for fieldname in self.meta.get_valid_columns():
                parent_dict[fieldname] = self.get(fieldname)

            if self.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
                document_type = "{} Item".format(self.doctype)
                parent_dict.update({"document_type": document_type})

            for item in self.get("items"):
                if item.get("item_code"):
                    args = parent_dict.copy()
                    args.update(item.as_dict())

                    args["doctype"] = self.doctype
                    args["name"] = self.name

                    if not args.get("transaction_date"):
                        args["transaction_date"] = args.get("posting_date")

                    if self.get("is_subcontracted"):
                        args["is_subcontracted"] = self.is_subcontracted

                    ret = get_item_details(args)

                    for fieldname, value in ret.items():
                        if item.meta.get_field(fieldname) and value is not None:
                            if item.get(fieldname) is None or fieldname in force_item_fields:
                                item.set(fieldname, value)

                            elif fieldname == "cost_center" and not item.get("cost_center"):
                                item.set(fieldname, value)

                            elif fieldname == "conversion_factor" and not item.get("conversion_factor"):
                                item.set(fieldname, value)

                    if ret.get("pricing_rule"):
                        # if user changed the discount percentage then set user's discount percentage ?
                        item.set("discount_percentage", ret.get("discount_percentage"))
                        if ret.get("pricing_rule_for") == "Price":
                            item.set("pricing_list_rate", ret.get("pricing_list_rate"))

                        if item.price_list_rate:
                            item.rate = flt(
                                item.price_list_rate * (1.0 - (flt(item.discount_percentage) / 100.0)),
                                item.precision("rate"),
                            )

            if self.doctype == "Purchase Invoice":
                self.set_expense_account(for_validate)
Ejemplo n.º 24
0
 def set_missing_item_details(self):
     """set missing item values"""
     from erpnext.stock.get_item_details import get_item_details
     for item in self.doclist.get({"parentfield": self.fname}):
         if item.fields.get("item_code"):
             args = item.fields.copy().update(self.doc.fields)
             ret = get_item_details(args)
             for fieldname, value in ret.items():
                 if self.meta.get_field(fieldname, parentfield=self.fname) and \
                  item.fields.get(fieldname) is None and value is not None:
                     item.fields[fieldname] = value
Ejemplo n.º 25
0
	def set_missing_item_details(self):
		"""set missing item values"""
		from erpnext.stock.get_item_details import get_item_details

		if hasattr(self, "items"):
			parent_dict = {}
			for fieldname in self.meta.get_valid_columns():
				parent_dict[fieldname] = self.get(fieldname)

			if self.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
				document_type = "{} Item".format(self.doctype)
				parent_dict.update({"document_type": document_type})

			for item in self.get("items"):
				if item.get("item_code"):
					args = parent_dict.copy()
					args.update(item.as_dict())

					args["doctype"] = self.doctype
					args["name"] = self.name

					if not args.get("transaction_date"):
						args["transaction_date"] = args.get("posting_date")

					if self.get("is_subcontracted"):
						args["is_subcontracted"] = self.is_subcontracted

					ret = get_item_details(args)


					for fieldname, value in ret.items():
						if item.meta.get_field(fieldname) and value is not None:
							if (item.get(fieldname) is None or fieldname in force_item_fields):
								item.set(fieldname, value)

							elif fieldname == "cost_center" and not item.get("cost_center"):
								item.set(fieldname, value)

							elif fieldname == "conversion_factor" and not item.get("conversion_factor"):
								item.set(fieldname, value)

					if ret.get("pricing_rule"):
						# if user changed the discount percentage then set user's discount percentage ?
						item.set("discount_percentage", ret.get("discount_percentage"))
						if ret.get("pricing_rule_for") == "Price":
							item.set("pricing_list_rate", ret.get("pricing_list_rate"))

						if item.price_list_rate:
							item.rate = flt(item.price_list_rate *
								(1.0 - (flt(item.discount_percentage) / 100.0)), item.precision("rate"))

			if self.doctype == "Purchase Invoice":
				self.set_expense_account()
Ejemplo n.º 26
0
def get_item_details(args):
    from erpnext.stock.get_item_details import get_item_details

    out = get_item_details(args)
    args_dict = (frappe._dict(json.loads(args)) if isinstance(
        args, string_types) else args)
    default_warehouse = (frappe.db.get_value("Company", args_dict.company,
                                             "default_warehouse")
                         if args_dict.company else None)
    if default_warehouse and not out.warehouse:
        out.warehouse = default_warehouse
    return out
Ejemplo n.º 27
0
def get_items_from_product_bundle(args):
    args = json.loads(args)
    items = []
    bundled_items = get_product_bundle_items(args["item_code"])
    for item in bundled_items:
        args.update({
            "item_code": item.item_code,
            "qty": flt(args["quantity"]) * flt(item.qty)
        })
        items.append(get_item_details(args))

    return items
Ejemplo n.º 28
0
    def complete_procedure(self):
        if self.consume_stock and self.items:
            stock_entry = make_stock_entry(self)

        if self.items:
            consumable_total_amount = 0
            consumption_details = False
            customer = frappe.db.get_value('Patient', self.patient, 'customer')
            if customer:
                for item in self.items:
                    if item.invoice_separately_as_consumables:
                        price_list, price_list_currency = frappe.db.get_values(
                            'Price List', {'selling': 1},
                            ['name', 'currency'])[0]
                        args = {
                            'doctype': 'Sales Invoice',
                            'item_code': item.item_code,
                            'company': self.company,
                            'warehouse': self.warehouse,
                            'customer': customer,
                            'selling_price_list': price_list,
                            'price_list_currency': price_list_currency,
                            'plc_conversion_rate': 1.0,
                            'conversion_rate': 1.0
                        }
                        item_details = get_item_details(args)
                        item_price = item_details.price_list_rate * item.qty
                        item_consumption_details = item_details.item_name + ' ' + \
                            str(item.qty) + ' ' + item.uom + \
                            ' ' + str(item_price)
                        consumable_total_amount += item_price
                        if not consumption_details:
                            consumption_details = _(
                                'Clinical Procedure ({0}):').format(self.name)
                        consumption_details += '\n\t' + item_consumption_details

                if consumable_total_amount > 0:
                    frappe.db.set_value('Clinical Procedure', self.name,
                                        'consumable_total_amount',
                                        consumable_total_amount)
                    frappe.db.set_value('Clinical Procedure', self.name,
                                        'consumption_details',
                                        consumption_details)
            else:
                frappe.throw(_('Please set Customer in Patient {0}').format(
                    frappe.bold(self.patient)),
                             title=_('Customer Not Found'))

        self.db_set('status', 'Completed')

        if self.consume_stock and self.items:
            return stock_entry
Ejemplo n.º 29
0
    def set_missing_item_details(self):
        """set missing item values"""
        from erpnext.stock.get_item_details import get_item_details

        if hasattr(self, "items"):
            parent_dict = {}
            for fieldname in self.meta.get_valid_columns():
                parent_dict[fieldname] = self.get(fieldname)

            for item in self.get("items"):
                if item.get("item_code"):
                    args = parent_dict.copy()
                    args.update(item.as_dict())
                    if not args.get("transaction_date"):
                        args["transaction_date"] = args.get("posting_date")

                    if self.get("is_subcontracted"):
                        args["is_subcontracted"] = self.is_subcontracted

                    ret = get_item_details(args)

                    for fieldname, value in ret.items():
                        if item.meta.get_field(
                                fieldname) and value is not None:
                            if (item.get(fieldname) is None
                                    or fieldname in force_item_fields):
                                item.set(fieldname, value)

                            elif fieldname == "cost_center" and not item.get(
                                    "cost_center"):
                                item.set(fieldname, value)

                            elif fieldname == "conversion_factor" and not item.get(
                                    "conversion_factor"):
                                item.set(fieldname, value)

                    if ret.get("pricing_rule"):
                        item.set("discount_percentage",
                                 ret.get("discount_percentage"))
                        if ret.get("pricing_rule_for") == "Price":
                            item.set("pricing_list_rate",
                                     ret.get("pricing_list_rate"))

                        if item.price_list_rate:
                            item.rate = flt(
                                item.price_list_rate *
                                (1.0 -
                                 (flt(item.discount_percentage) / 100.0)),
                                item.precision("rate"))
Ejemplo n.º 30
0
    def test_get_item_details(self):
        # delete modified item price record and make as per test_records
        frappe.db.sql("""delete from `tabItem Price`""")

        to_check = {
            "item_code": "_Test Item",
            "item_name": "_Test Item",
            "description": "_Test Item 1",
            "warehouse": "_Test Warehouse - _TC",
            "income_account": "Sales - _TC",
            "expense_account": "_Test Account Cost for Goods Sold - _TC",
            "cost_center": "_Test Cost Center - _TC",
            "qty": 1.0,
            "price_list_rate": 100.0,
            "base_price_list_rate": 0.0,
            "discount_percentage": 0.0,
            "rate": 0.0,
            "base_rate": 0.0,
            "amount": 0.0,
            "base_amount": 0.0,
            "batch_no": None,
            "uom": "_Test UOM",
            "conversion_factor": 1.0,
        }

        make_test_objects("Item Price")

        company = "_Test Company"
        currency = frappe.get_cached_value("Company", company,
                                           "default_currency")

        details = get_item_details({
            "item_code": "_Test Item",
            "company": company,
            "price_list": "_Test Price List",
            "currency": currency,
            "doctype": "Sales Order",
            "conversion_rate": 1,
            "price_list_currency": currency,
            "plc_conversion_rate": 1,
            "order_type": "Sales",
            "customer": "_Test Customer",
            "conversion_factor": 1,
            "price_list_uom_dependant": 1,
            "ignore_pricing_rule": 1,
        })

        for key, value in to_check.items():
            self.assertEqual(value, details.get(key))
Ejemplo n.º 31
0
	def test_pricing_rule_for_margin(self):
		from erpnext.stock.get_item_details import get_item_details
		from frappe import MandatoryError

		frappe.db.sql("delete from `tabPricing Rule`")

		test_record = {
			"doctype": "Pricing Rule",
			"title": "_Test Pricing Rule",
			"apply_on": "Item Code",
			"item_code": "_Test FG Item 2",
			"selling": 1,
			"currency": "USD",
			"rate_or_discount": "Discount Percentage",
			"rate": 0,
			"margin_type": "Percentage",
			"margin_rate_or_amount": 10,
			"company": "_Test Company"
		}
		frappe.get_doc(test_record.copy()).insert()
		
		item_price = frappe.get_doc({
			"doctype": "Item Price",
			"price_list": "_Test Price List 2",
			"item_code": "_Test FG Item 2",
			"price_list_rate": 100
		})
		
		item_price.insert(ignore_permissions=True)

		args = frappe._dict({
			"item_code": "_Test FG Item 2",
			"company": "_Test Company",
			"price_list": "_Test Price List",
			"currency": "_Test Currency",
			"doctype": "Sales Order",
			"conversion_rate": 1,
			"price_list_currency": "_Test Currency",
			"plc_conversion_rate": 1,
			"order_type": "Sales",
			"customer": "_Test Customer",
			"name": None
		})
		details = get_item_details(args)
		self.assertEqual(details.get("margin_type"), "Percentage")
		self.assertEqual(details.get("margin_rate_or_amount"), 10)

		frappe.db.sql("delete from `tabPricing Rule`")
Ejemplo n.º 32
0
def kp_get_item_details(args):

    result = get_item_details(args)

    item_code = result.get("item_code")

    chapter_head = frappe.db.get_value("Item", {"item_code": item_code},
                                       "excise_chapter")

    #Item must have a chapter head. If not specified, return.
    if chapter_head == "":
        frappe.msgprint(
            _("Excise Chapter Head not specified for item '%s'!" %
              (item_code)))

    result["kirat_excise_duty_rate"] = frappe.db.get_value(
        "Item", item_code, "excise_duty_rate")
    result["kirat_excise_price"] = frappe.db.get_value("Item", item_code,
                                                       "excise_price")

    #Calculate final amount.
    item_rate = 0.0  #Set either to result[price_list_rate] or result[rate] depending on which is non-zero.
    item_rate_for_excise_calc = 0.0

    #Set item_rate
    if result["price_list_rate"] != 0.0:
        item_rate = result["price_list_rate"]
    else:
        item_rate = result["rate"]

    #Set item_rate_for_excise_calc
    #Deprecated: 160521: Excise Price will be entered for each item and excise calculation will use ONLY excise price.
    # if result["kirat_excise_price"] != 0.0:
    # 	item_rate_for_excise_calc = result["kirat_excise_price"]
    # else:
    # 	item_rate_for_excise_calc = item_rate
    item_rate_for_excise_calc = result["kirat_excise_price"]

    excise_duty_amt = kp_calculate_excise_duty_amt(
        result["qty"], item_rate_for_excise_calc,
        result["kirat_excise_duty_rate"])

    result["kirat_excise_duty_amt"] = excise_duty_amt
    result["kirat_total_amt_with_excise"] = excise_duty_amt + result["amount"]

    #result["customer_item_code"] =

    return result
Ejemplo n.º 33
0
	def test_pricing_rule_for_margin(self):
		from erpnext.stock.get_item_details import get_item_details
		from frappe import MandatoryError

		frappe.db.sql("delete from `tabPricing Rule`")

		test_record = {
			"doctype": "Pricing Rule",
			"title": "_Test Pricing Rule",
			"apply_on": "Item Code",
			"item_code": "_Test FG Item 2",
			"selling": 1,
			"price_or_discount": "Discount Percentage",
			"price": 0,
			"margin_type": "Percentage",
			"margin_rate_or_amount": 10,
			"company": "_Test Company"
		}
		frappe.get_doc(test_record.copy()).insert()
		
		item_price = frappe.get_doc({
			"doctype": "Item Price",
			"price_list": "_Test Price List 2",
			"item_code": "_Test FG Item 2",
			"price_list_rate": 100
		})
		
		item_price.insert(ignore_permissions=True)

		args = frappe._dict({
			"item_code": "_Test FG Item 2",
			"company": "_Test Company",
			"price_list": "_Test Price List",
			"currency": "_Test Currency",
			"doctype": "Sales Order",
			"conversion_rate": 1,
			"price_list_currency": "_Test Currency",
			"plc_conversion_rate": 1,
			"order_type": "Sales",
			"customer": "_Test Customer",
			"name": None
		})
		details = get_item_details(args)
		self.assertEquals(details.get("margin_type"), "Percentage")
		self.assertEquals(details.get("margin_rate_or_amount"), 10)

		frappe.db.sql("delete from `tabPricing Rule`")
Ejemplo n.º 34
0
	def test_get_item_details(self):
		# delete modified item price record and make as per test_records
		frappe.db.sql("""delete from `tabItem Price`""")

		to_check = {
			"item_code": "_Test Item",
			"item_name": "_Test Item",
			"description": "_Test Item 1",
			"warehouse": "_Test Warehouse - _TC",
			"income_account": "Sales - _TC",
			"expense_account": "_Test Account Cost for Goods Sold - _TC",
			"cost_center": "_Test Cost Center 2 - _TC",
			"qty": 1.0,
			"price_list_rate": 100.0,
			"base_price_list_rate": 0.0,
			"discount_percentage": 0.0,
			"rate": 0.0,
			"base_rate": 0.0,
			"amount": 0.0,
			"base_amount": 0.0,
			"batch_no": None,
			"item_tax_rate": '{}',
			"uom": "_Test UOM",
			"conversion_factor": 1.0,
		}

		make_test_objects("Item Price")
		print(frappe.get_all("Item Price"))

		details = get_item_details({
			"item_code": "_Test Item",
			"company": "_Test Company",
			"price_list": "_Test Price List",
			"currency": "_Test Currency",
			"doctype": "Sales Order",
			"conversion_rate": 1,
			"price_list_currency": "_Test Currency",
			"plc_conversion_rate": 1,
			"order_type": "Sales",
			"customer": "_Test Customer",
			"conversion_factor": 1,
			"price_list_uom_dependant": 1,
			"ignore_pricing_rule": 1
		})

		for key, value in to_check.iteritems():
			self.assertEquals(value, details.get(key))
Ejemplo n.º 35
0
	def set_missing_item_details(self):
		"""set missing item values"""
		from erpnext.stock.get_item_details import get_item_details
		if hasattr(self, "fname"):
			parent_dict = {"doctype": self.doctype}
			for fieldname in self.meta.get_valid_columns():
				parent_dict[fieldname] = self.get(fieldname)

			for item in self.get(self.fname):
				if item.get("item_code"):
					args = item.as_dict()
					args.update(parent_dict)
					ret = get_item_details(args)
					for fieldname, value in ret.items():
						if item.meta.get_field(fieldname) and \
							item.get(fieldname) is None and value is not None:
								item.set(fieldname, value)
Ejemplo n.º 36
0
def get_item_detail(item, doc=None, warehouse=None, price_list=None):
    item = json.loads(item)
    item_code = item.get("item_code")
    if warehouse and item.get("has_batch_no") and not item.get("batch_no"):
        item["batch_no"] = get_batch_no(item_code, warehouse, item.get("qty"),
                                        False, item.get("d"))
    item["selling_price_list"] = price_list
    max_discount = frappe.get_value("Item", item_code, "max_discount")
    res = get_item_details(
        item,
        doc,
        overwrite_warehouse=False,
    )
    if item.get("is_stock_item") and warehouse:
        res["actual_qty"] = get_stock_availability(item_code, warehouse)
    res["max_discount"] = max_discount
    return res
Ejemplo n.º 37
0
    def set_missing_item_details(self):
        """set missing item values"""
        from erpnext.stock.get_item_details import get_item_details
        if hasattr(self, "fname"):
            parent_dict = {"doctype": self.doctype}
            for fieldname in self.meta.get_valid_columns():
                parent_dict[fieldname] = self.get(fieldname)

            for item in self.get(self.fname):
                if item.get("item_code"):
                    args = item.as_dict()
                    args.update(parent_dict)
                    ret = get_item_details(args)
                    for fieldname, value in ret.items():
                        if item.meta.get_field(fieldname) and \
                         item.get(fieldname) is None and value is not None:
                            item.set(fieldname, value)
Ejemplo n.º 38
0
    def test_cumulative_pricing_rule(self):
        frappe.delete_doc_if_exists('Pricing Rule',
                                    '_Test Cumulative Pricing Rule')
        test_record = {
            "doctype": "Pricing Rule",
            "title": "_Test Cumulative Pricing Rule",
            "apply_on": "Item Code",
            "currency": "USD",
            "items": [{
                "item_code": "_Test Item",
            }],
            "is_cumulative": 1,
            "selling": 1,
            "applicable_for": "Customer",
            "customer": "_Test Customer",
            "rate_or_discount": "Discount Percentage",
            "rate": 0,
            "min_amt": 0,
            "max_amt": 10000,
            "discount_percentage": 17.5,
            "price_or_product_discount": "Price",
            "company": "_Test Company",
            "valid_from": frappe.utils.nowdate(),
            "valid_upto": frappe.utils.nowdate()
        }
        frappe.get_doc(test_record.copy()).insert()

        args = frappe._dict({
            "item_code": "_Test Item",
            "company": "_Test Company",
            "price_list": "_Test Price List",
            "currency": "_Test Currency",
            "doctype": "Sales Invoice",
            "conversion_rate": 1,
            "price_list_currency": "_Test Currency",
            "plc_conversion_rate": 1,
            "order_type": "Sales",
            "customer": "_Test Customer",
            "name": None,
            "transaction_date": frappe.utils.nowdate()
        })
        details = get_item_details(args)

        self.assertTrue(details)
Ejemplo n.º 39
0
	def test_get_item_details(self):
		from erpnext.stock.get_item_details import get_item_details
		to_check = {
			"item_code": "_Test Item",
			"item_name": "_Test Item",
			"description": "_Test Item 1",
			"warehouse": "_Test Warehouse - _TC",
			"income_account": "Sales - _TC",
			"expense_account": "_Test Account Cost for Goods Sold - _TC",
			"cost_center": "_Test Cost Center 2 - _TC",
			"qty": 1.0,
			"price_list_rate": 100.0,
			"base_price_list_rate": 0.0,
			"discount_percentage": 0.0,
			"rate": 0.0,
			"base_rate": 0.0,
			"amount": 0.0,
			"base_amount": 0.0,
			"batch_no": None,
			"item_tax_rate": '{}',
			"uom": "_Test UOM",
			"conversion_factor": 1.0,
		}

		make_test_records("Item Price")

		details = get_item_details({
			"item_code": "_Test Item",
			"company": "_Test Company",
			"price_list": "_Test Price List",
			"currency": "_Test Currency",

			"doctype": "Sales Order",
			"conversion_rate": 1,
			"price_list_currency": "_Test Currency",
			"plc_conversion_rate": 1,
			"order_type": "Sales",
			"customer": "_Test Customer"
		})

		for key, value in to_check.iteritems():
			self.assertEquals(value, details.get(key))
Ejemplo n.º 40
0
	def refresh_items(self):
		items = self.get("items")
		
		for i, d in enumerate(self.items):
			from erpnext.stock.get_item_details import get_item_details
			frappe.errprint(d)
			details = get_item_details({
				"item_code": d.item_code,
				"company": self.get("company"),
				"price_list": self.get("selling_price_list"),
				"currency": self.get("currency"),
				"doctype": self.get("doctype"),
				"conversion_rate": 1,
				"price_list_currency": self.get("price_list_currency"),
				"plc_conversion_rate": 1,
				"order_type": "Sales",
				"customer":  self.get("customer")
			})
			
			d.price_list_rate = details["price_list_rate"]
Ejemplo n.º 41
0
def kp_get_item_details(args):

	result = get_item_details(args)

	item_code = result.get("item_code")
	
	chapter_head = frappe.db.get_value("Item", {"item_code": item_code}, "excise_chapter")

	#Item must have a chapter head. If not specified, return.
	if chapter_head == "": 
		frappe.msgprint(_("Excise Chapter Head not specified for item '%s'!" % (item_code)))
	
	result["kirat_excise_duty_rate"] = frappe.db.get_value("Item", item_code, "excise_duty_rate")
	result["kirat_excise_price"] = frappe.db.get_value("Item", item_code, "excise_price")

	#Calculate final amount.
	item_rate = 0.0 #Set either to result[price_list_rate] or result[rate] depending on which is non-zero.
	item_rate_for_excise_calc = 0.0
	
	#Set item_rate
	if result["price_list_rate"] != 0.0:
		item_rate = result["price_list_rate"]
	else:
		item_rate = result["rate"]

	#Set item_rate_for_excise_calc
	#Deprecated: 160521: Excise Price will be entered for each item and excise calculation will use ONLY excise price.
	# if result["kirat_excise_price"] != 0.0:
	# 	item_rate_for_excise_calc = result["kirat_excise_price"]
	# else:
	# 	item_rate_for_excise_calc = item_rate
	item_rate_for_excise_calc = result["kirat_excise_price"]

	excise_duty_amt = kp_calculate_excise_duty_amt(result["qty"], item_rate_for_excise_calc, result["kirat_excise_duty_rate"])

	result["kirat_excise_duty_amt"] = excise_duty_amt
	result["kirat_total_amt_with_excise"] = excise_duty_amt + result["amount"]

	#result["customer_item_code"] = 
	
	return result
Ejemplo n.º 42
0
	def set_missing_item_details(self):
		"""set missing item values"""
		from erpnext.stock.get_item_details import get_item_details

		if hasattr(self, "items"):
			parent_dict = {}
			for fieldname in self.meta.get_valid_columns():
				parent_dict[fieldname] = self.get(fieldname)

			for item in self.get("items"):
				if item.get("item_code"):
					args = parent_dict.copy()
					args.update(item.as_dict())
					if not args.get("transaction_date"):
						args["transaction_date"] = args.get("posting_date")

					if self.get("is_subcontracted"):
						args["is_subcontracted"] = self.is_subcontracted

					ret = get_item_details(args)

					for fieldname, value in ret.items():
						if item.meta.get_field(fieldname) and value is not None:
							if (item.get(fieldname) is None or fieldname in force_item_fields):
								item.set(fieldname, value)

							elif fieldname == "cost_center" and not item.get("cost_center"):
								item.set(fieldname, value)

							elif fieldname == "conversion_factor" and not item.get("conversion_factor"):
								item.set(fieldname, value)

					if ret.get("pricing_rule"):
						item.set("discount_percentage", ret.get("discount_percentage"))
						if ret.get("pricing_rule_for") == "Price":
							item.set("pricing_list_rate", ret.get("pricing_list_rate"))

						if item.price_list_rate:
							item.rate = flt(item.price_list_rate *
								(1.0 - (flt(item.discount_percentage) / 100.0)), item.precision("rate"))
Ejemplo n.º 43
0
	def test_pricing_rule_for_variants(self):
		from erpnext.stock.get_item_details import get_item_details
		from frappe import MandatoryError

		frappe.db.sql("delete from `tabPricing Rule`")

		if not frappe.db.exists("Item", "Test Variant PRT"):
			frappe.get_doc({
				"doctype": "Item",
				"item_code": "Test Variant PRT",
				"item_name": "Test Variant PRT",
				"description": "Test Variant PRT",
				"item_group": "_Test Item Group",
				"is_stock_item": 1,
				"variant_of": "_Test Variant Item",
				"default_warehouse": "_Test Warehouse - _TC",
				"stock_uom": "_Test UOM",
				"attributes": [
					{
					  "attribute": "Test Size",
					  "attribute_value": "Medium"
					}
				],
			}).insert()

		frappe.get_doc({
			"doctype": "Pricing Rule",
			"title": "_Test Pricing Rule 1",
			"apply_on": "Item Code",
			"item_code": "_Test Variant Item",
			"selling": 1,
			"price_or_discount": "Discount Percentage",
			"price": 0,
			"discount_percentage": 7.5,
			"company": "_Test Company"
		}).insert()

		args = frappe._dict({
			"item_code": "Test Variant PRT",
			"company": "_Test Company",
			"price_list": "_Test Price List",
			"currency": "_Test Currency",
			"doctype": "Sales Order",
			"conversion_rate": 1,
			"price_list_currency": "_Test Currency",
			"plc_conversion_rate": 1,
			"order_type": "Sales",
			"customer": "_Test Customer",
			"name": None
		})

		details = get_item_details(args)
		self.assertEquals(details.get("discount_percentage"), 7.5)

		# add a new pricing rule for that item code, it should take priority
		frappe.get_doc({
			"doctype": "Pricing Rule",
			"title": "_Test Pricing Rule 2",
			"apply_on": "Item Code",
			"item_code": "Test Variant PRT",
			"selling": 1,
			"price_or_discount": "Discount Percentage",
			"price": 0,
			"discount_percentage": 17.5,
			"company": "_Test Company"
		}).insert()

		details = get_item_details(args)
		self.assertEquals(details.get("discount_percentage"), 17.5)
Ejemplo n.º 44
0
	def test_pricing_rule_for_discount(self):
		from erpnext.stock.get_item_details import get_item_details
		from frappe import MandatoryError

		frappe.db.sql("delete from `tabPricing Rule`")

		test_record = {
			"doctype": "Pricing Rule",
			"title": "_Test Pricing Rule",
			"apply_on": "Item Code",
			"item_code": "_Test Item",
			"selling": 1,
			"price_or_discount": "Discount Percentage",
			"price": 0,
			"discount_percentage": 10,
			"company": "_Test Company"
		}
		frappe.get_doc(test_record.copy()).insert()

		args = frappe._dict({
			"item_code": "_Test Item",
			"company": "_Test Company",
			"price_list": "_Test Price List",
			"currency": "_Test Currency",
			"doctype": "Sales Order",
			"conversion_rate": 1,
			"price_list_currency": "_Test Currency",
			"plc_conversion_rate": 1,
			"order_type": "Sales",
			"customer": "_Test Customer",
			"name": None
		})
		details = get_item_details(args)
		self.assertEquals(details.get("discount_percentage"), 10)

		prule = frappe.get_doc(test_record.copy())
		prule.applicable_for = "Customer"
		prule.title = "_Test Pricing Rule for Customer"
		self.assertRaises(MandatoryError, prule.insert)

		prule.customer = "_Test Customer"
		prule.discount_percentage = 20
		prule.insert()
		details = get_item_details(args)
		self.assertEquals(details.get("discount_percentage"), 20)

		prule = frappe.get_doc(test_record.copy())
		prule.apply_on = "Item Group"
		prule.item_group = "All Item Groups"
		prule.title = "_Test Pricing Rule for Item Group"
		prule.discount_percentage = 15
		prule.insert()

		args.customer = "_Test Customer 1"
		details = get_item_details(args)
		self.assertEquals(details.get("discount_percentage"), 10)

		prule = frappe.get_doc(test_record.copy())
		prule.applicable_for = "Campaign"
		prule.campaign = "_Test Campaign"
		prule.title = "_Test Pricing Rule for Campaign"
		prule.discount_percentage = 5
		prule.priority = 8
		prule.insert()

		args.campaign = "_Test Campaign"
		details = get_item_details(args)
		self.assertEquals(details.get("discount_percentage"), 5)

		frappe.db.sql("update `tabPricing Rule` set priority=NULL where campaign='_Test Campaign'")
		from erpnext.accounts.doctype.pricing_rule.pricing_rule	import MultiplePricingRuleConflict
		self.assertRaises(MultiplePricingRuleConflict, get_item_details, args)

		args.item_code = "_Test Item 2"
		details = get_item_details(args)
		self.assertEquals(details.get("discount_percentage"), 15)

		frappe.db.sql("delete from `tabPricing Rule`")
Ejemplo n.º 45
0
def kp_get_item_details(args):
	#frappe.msgprint(args)
	result = get_item_details(args)

	item_code = result.get("item_code")
	
	chapter_head = frappe.db.get_value("Item", {"item_code": item_code}, "excise_chapter")

	#Item must have a chapter head. If not specified, return.
	if chapter_head == "": 
		frappe.msgprint(_("Excise Chapter Head not specified for item '%s'!" % (item_code)))
	
	result["kirat_excise_duty_rate"] = frappe.db.get_value("Item", item_code, "excise_duty_rate")

	#160709: Kirat Excise Price now pulled from Item Price doctype. 
	#Item Price records for Zero price list will not have any excise price.
	#Also, ZPL will override the customer's price list when invoice type is Sample or Challan.
	#Therefore, case of ZPL, excise price will have to be fetched from the customer's default price list if it exists or standard selling.
	
	#Convert args to dict.
	args_json = json.loads(args)
	price_list_for_pulling_excise_price = args_json["price_list"] #Longname!

	#If Zero Price List, lookup customer's default price list. If not found, use Standard Selling.
	if (args_json["price_list"].find("Zero") != -1):
		#frappe.msgprint("Zero Rate price list found. Attempting to find default price list to pull excise price from.")
		price_list_for_pulling_excise_price = frappe.db.get_value("Customer", args_json["customer"], "default_price_list")
		if (not price_list_for_pulling_excise_price) or (price_list_for_pulling_excise_price == ""):
			#frappe.msgprint("Default price list not found. Pulling excise price from Standard Selling")
			price_list_for_pulling_excise_price = "Standard Selling"

	kep = frappe.db.get_value("Item Price", {"price_list": price_list_for_pulling_excise_price, "item_code": item_code}, "kirat_excise_price")

	if not kep:
		frappe.throw(_("Item '%s' does not have a valid excise price." % (item_code)))

	result["kirat_excise_price"] = kep
	#result["kirat_excise_price"] = frappe.db.get_value("Item", item_code, "excise_price")


	#Calculate final amount.
	item_rate = 0.0 #Set either to result[price_list_rate] or result[rate] depending on which is non-zero.
	item_rate_for_excise_calc = 0.0
	
	#Set item_rate
	if result["price_list_rate"] != 0.0:
		item_rate = result["price_list_rate"]
	else:
		item_rate = result["rate"]

	#Set item_rate_for_excise_calc
	#Deprecated: 160521: Excise Price will be entered for each item and excise calculation will use ONLY excise price.
	# if result["kirat_excise_price"] != 0.0:
	# 	item_rate_for_excise_calc = result["kirat_excise_price"]
	# else:
	# 	item_rate_for_excise_calc = item_rate
	item_rate_for_excise_calc = result["kirat_excise_price"]

	excise_duty_amt = kp_calculate_excise_duty_amt(result["qty"], item_rate_for_excise_calc, result["kirat_excise_duty_rate"])

	result["kirat_excise_duty_amt"] = excise_duty_amt
	result["kirat_total_amt_with_excise"] = excise_duty_amt + result["amount"]

	#result["customer_item_code"] = 
	
	return result