Beispiel #1
0
def get_item_group_defaults(item, company):
    item = dataent.get_cached_doc("Item", item)
    item_group = dataent.get_cached_doc("Item Group", item.item_group)

    for d in item_group.item_group_defaults or []:
        if d.company == company:
            row = copy.deepcopy(d.as_dict())
            row.pop("name")
            return row

    return dataent._dict()
Beispiel #2
0
def get_pos_profile(company, pos_profile=None, user=None):
	if pos_profile: return dataent.get_cached_doc('POS Profile', pos_profile)

	if not user:
		user = dataent.session['user']

	condition = "pfu.user = %(user)s AND pfu.default=1"
	if user and company:
		condition = "pfu.user = %(user)s AND pf.company = %(company)s AND pfu.default=1"

	pos_profile = dataent.db.sql("""SELECT pf.*
		FROM
			`tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
		ON
				pf.name = pfu.parent
		WHERE
			{cond} AND pf.disabled = 0
	""".format(cond = condition), {
		'user': user,
		'company': company
	}, as_dict=1)

	if not pos_profile and company:
		pos_profile = dataent.db.sql("""SELECT pf.*
			FROM
				`tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
			ON
					pf.name = pfu.parent
			WHERE
				pf.company = %(company)s AND pf.disabled = 0
		""", {
			'company': company
		}, as_dict=1)

	return pos_profile and pos_profile[0] or None
Beispiel #3
0
def calculate_service_end_date(args, item=None):
	args = process_args(args)
	if not item:
		item = dataent.get_cached_doc("Item", args.item_code)

	doctype = args.get("parenttype") or args.get("doctype")
	if doctype == "Sales Invoice":
		enable_deferred = "enable_deferred_revenue"
		no_of_months = "no_of_months"
		account = "deferred_revenue_account"
	else:
		enable_deferred = "enable_deferred_expense"
		no_of_months = "no_of_months_exp"
		account = "deferred_expense_account"

	service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
	service_end_date = add_months(service_start_date, item.get(no_of_months))
	deferred_detail = {
		"service_start_date": service_start_date,
		"service_end_date": service_end_date
	}
	deferred_detail[enable_deferred] = item.get(enable_deferred)
	deferred_detail[account] = get_default_deferred_account(args, item, fieldname=account)

	return deferred_detail
Beispiel #4
0
    def make_material_request(self):
        '''Create Material Requests grouped by Sales Order and Material Request Type'''
        material_request_list = []
        material_request_map = {}

        for item in self.mr_items:
            item_doc = dataent.get_cached_doc('Item', item.item_code)

            # key for Sales Order:Material Request Type
            key = '{}:{}'.format(item.sales_order,
                                 item_doc.default_material_request_type)
            schedule_date = add_days(nowdate(), cint(item_doc.lead_time_days))

            if not key in material_request_map:
                # make a new MR for the combination
                material_request_map[key] = dataent.new_doc("Material Request")
                material_request = material_request_map[key]
                material_request.update({
                    "transaction_date":
                    nowdate(),
                    "status":
                    "Draft",
                    "company":
                    self.company,
                    "requested_by":
                    dataent.session.user,
                    'material_request_type':
                    item_doc.default_material_request_type
                })
                material_request_list.append(material_request)
            else:
                material_request = material_request_map[key]

            # add item
            material_request.append("items", {
             "item_code": item.item_code,
             "qty": item.quantity,
             "schedule_date": schedule_date,
             "warehouse": item.warehouse,
             "sales_order": item.sales_order,
             'production_plan': self.name,
             'material_request_plan_item': item.name,
             "project": dataent.db.get_value("Sales Order", item.sales_order, "project") \
              if item.sales_order else None
            })

        for material_request in material_request_list:
            # submit
            material_request.flags.ignore_permissions = 1
            material_request.run_method("set_missing_values")
            material_request.submit()

        dataent.flags.mute_messages = False

        if material_request_list:
            material_request_list = ["""<a href="#Form/Material Request/{0}">{1}</a>""".format(m.name, m.name) \
             for m in material_request_list]
            msgprint(_("{0} created").format(comma_and(material_request_list)))
        else:
            msgprint(_("No material request created"))
Beispiel #5
0
def get_item_groups(pos_profile):
	item_groups = []
	pos_profile = dataent.get_cached_doc('POS Profile', pos_profile)

	if pos_profile.get('item_groups'):
		# Get items based on the item groups defined in the POS profile
		for data in pos_profile.get('item_groups'):
			item_groups.extend(["'%s'" % dataent.db.escape(d.name) for d in get_child_nodes('Item Group', data.item_group)])

	return list(set(item_groups))
Beispiel #6
0
def get_item_defaults(item_code, company):
    item = dataent.get_cached_doc('Item', item_code)

    out = item.as_dict()

    for d in item.item_defaults:
        if d.company == company:
            row = copy.deepcopy(d.as_dict())
            row.pop("name")
            out.update(row)
    return out
Beispiel #7
0
def get_product_list_for_group(product_group=None,
                               start=0,
                               limit=10,
                               search=None):
    if product_group:
        item_group = dataent.get_cached_doc('Item Group', product_group)
        if item_group.is_group:
            # return child item groups if the type is of "Is Group"
            return get_child_groups_for_list_in_html(item_group, start, limit,
                                                     search)

    child_groups = ", ".join([
        '"' + dataent.db.escape(i[0]) + '"'
        for i in get_child_groups(product_group)
    ])

    # base query
    query = """select I.name, I.item_name, I.item_code, I.route, I.image, I.website_image, I.thumbnail, I.item_group,
			I.description, I.web_long_description as website_description, I.is_stock_item,
			case when (S.actual_qty - S.reserved_qty) > 0 then 1 else 0 end as in_stock, I.website_warehouse,
			I.has_batch_no
		from `tabItem` I
		left join tabBin S on I.item_code = S.item_code and I.website_warehouse = S.warehouse
		where I.show_in_website = 1
			and I.disabled = 0
			and (I.end_of_life is null or I.end_of_life='0000-00-00' or I.end_of_life > %(today)s)
			and (I.variant_of = '' or I.variant_of is null)
			and (I.item_group in ({child_groups})
			or I.name in (select parent from `tabWebsite Item Group` where item_group in ({child_groups})))
			""".format(child_groups=child_groups)
    # search term condition
    if search:
        query += """ and (I.web_long_description like %(search)s
				or I.item_name like %(search)s
				or I.name like %(search)s)"""
        search = "%" + cstr(search) + "%"

    query += """order by I.weightage desc, in_stock desc, I.modified desc limit %s, %s""" % (
        start, limit)

    data = dataent.db.sql(query, {
        "product_group": product_group,
        "search": search,
        "today": nowdate()
    },
                          as_dict=1)
    data = adjust_qty_for_expired_items(data)

    if cint(dataent.db.get_single_value("Shopping Cart Settings", "enabled")):
        for item in data:
            set_product_info_for_website(item)

    return [get_item_for_list_in_html(r) for r in data]
Beispiel #8
0
def set_item_default(item_code, company, fieldname, value):
    item = dataent.get_cached_doc('Item', item_code)

    for d in item.item_defaults:
        if d.company == company:
            if not d.get(fieldname):
                dataent.db.set_value(d.doctype, d.name, fieldname, value)
            return

    # no row found, add a new row for the company
    d = item.append('item_defaults', {fieldname: value, "company": company})
    d.db_insert()
    item.clear_cache()
Beispiel #9
0
    def link_address(self):
        """Link address based on owner"""
        if not self.links and not self.is_your_company_address:
            contact_name = dataent.db.get_value("Contact",
                                                {"email_id": self.owner})
            if contact_name:
                contact = dataent.get_cached_doc('Contact', contact_name)
                for link in contact.links:
                    self.append(
                        'links',
                        dict(link_doctype=link.link_doctype,
                             link_name=link.link_name))
                return True

        return False
Beispiel #10
0
def get_territory_from_address(address):
    """Tries to match city, state and country of address to existing territory"""
    if not address:
        return

    if isinstance(address, string_types):
        address = dataent.get_cached_doc("Address", address)

    territory = None
    for fieldname in ("city", "state", "country"):
        if address.get(fieldname):
            territory = dataent.db.get_value("Territory",
                                             address.get(fieldname))
            if territory:
                break

    return territory
Beispiel #11
0
def make_raw_material_request(items, company, sales_order, project=None):
    if not dataent.has_permission("Sales Order", "write"):
        dataent.throw(_("Not permitted"), dataent.PermissionError)

    if isinstance(items, string_types):
        items = dataent._dict(json.loads(items))

    for item in items.get('items'):
        item["include_exploded_items"] = items.get('include_exploded_items')
        item["ignore_existing_ordered_qty"] = items.get(
            'ignore_existing_ordered_qty')
        item["include_raw_materials_from_sales_order"] = items.get(
            'include_raw_materials_from_sales_order')

    raw_materials = get_items_for_material_requests(items, sales_order,
                                                    company)
    if not raw_materials:
        dataent.msgprint(
            _("Material Request not created, as quantity for Raw Materials already available."
              ))
        return

    material_request = dataent.new_doc('Material Request')
    material_request.update(
        dict(doctype='Material Request',
             transaction_date=nowdate(),
             company=company,
             requested_by=dataent.session.user,
             material_request_type='Purchase'))
    for item in raw_materials:
        item_doc = dataent.get_cached_doc('Item', item.get('item_code'))
        schedule_date = add_days(nowdate(), cint(item_doc.lead_time_days))
        material_request.append(
            'items', {
                'item_code': item.get('item_code'),
                'qty': item.get('quantity'),
                'schedule_date': schedule_date,
                'warehouse': item.get('warehouse'),
                'sales_order': sales_order,
                'project': project
            })
    material_request.insert()
    material_request.flags.ignore_permissions = 1
    material_request.run_method("set_missing_values")
    material_request.submit()
    return material_request
Beispiel #12
0
def get_item_details(args):
	"""
		args = {
			"item_code": "",
			"warehouse": None,
			"customer": "",
			"conversion_rate": 1.0,
			"selling_price_list": None,
			"price_list_currency": None,
			"plc_conversion_rate": 1.0,
			"doctype": "",
			"name": "",
			"supplier": None,
			"transaction_date": None,
			"conversion_rate": 1.0,
			"buying_price_list": None,
			"is_subcontracted": "Yes" / "No",
			"ignore_pricing_rule": 0/1
			"project": ""
			"set_warehouse": ""
		}
	"""
	args = process_args(args)
	item = dataent.get_cached_doc("Item", args.item_code)
	validate_item_details(args, item)

	out = get_basic_details(args, item)

	get_party_item_code(args, item, out)

	set_valuation_rate(out, args)

	update_party_blanket_order(args, out)

	get_price_list_rate(args, item, out)

	if args.customer and cint(args.is_pos):
		out.update(get_pos_profile_item_details(args.company, args))

	if out.get("warehouse"):
		out.update(get_bin_details(args.item_code, out.warehouse))

	# update args with out, if key or value not exists
	for key, value in iteritems(out):
		if args.get(key) is None:
			args[key] = value

	out.update(get_pricing_rule_for_item(args))

	update_stock(args, out)

	if args.transaction_date and item.lead_time_days:
		out.schedule_date = out.lead_time_date = add_days(args.transaction_date,
			item.lead_time_days)

	if args.get("is_subcontracted") == "Yes":
		out.bom = args.get('bom') or get_default_bom(args.item_code)

	get_gross_profit(out)
	if args.doctype == 'Material Request':
		out.rate = args.rate or out.price_list_rate
		out.amount = flt(args.qty * out.rate)

	return out