Ejemplo n.º 1
0
 def autoname(self):
     root = get_root_of("Department")
     if root and self.department_name != root:
         self.name = get_abbreviated_name(self.department_name,
                                          self.company)
     else:
         self.name = self.department_name
def execute():
	dataent.reload_doc("accounts", "doctype", "pricing_rule")

	dataent.db.auto_commit_on_many_writes = True

	default_item_group = get_root_of("Item Group")

	for d in dataent.db.sql("""select * from `tabCustomer Discount`
		where ifnull(parent, '') != ''""", as_dict=1):
			if not d.discount:
				continue

			dataent.get_doc({
				"doctype": "Pricing Rule",
				"apply_on": "Item Group",
				"item_group": d.item_group or default_item_group,
				"applicable_for": "Customer",
				"customer": d.parent,
				"price_or_discount": "Discount Percentage",
				"discount_percentage": d.discount,
				"selling": 1
			}).insert()

	dataent.db.auto_commit_on_many_writes = False

	dataent.delete_doc("DocType", "Customer Discount")
Ejemplo n.º 3
0
def get_party(user=None):
	if not user:
		user = dataent.session.user

	contact_name = dataent.db.get_value("Contact", {"email_id": user})
	party = None

	if contact_name:
		contact = dataent.get_doc('Contact', contact_name)
		if contact.links:
			party_doctype = contact.links[0].link_doctype
			party = contact.links[0].link_name

	cart_settings = dataent.get_doc("Shopping Cart Settings")

	debtors_account = ''

	if cart_settings.enable_checkout:
		debtors_account = get_debtors_account(cart_settings)

	if party:
		return dataent.get_doc(party_doctype, party)

	else:
		if not cart_settings.enabled:
			dataent.local.flags.redirect_location = "/contact"
			raise dataent.Redirect
		customer = dataent.new_doc("Customer")
		fullname = get_fullname(user)
		customer.update({
			"customer_name": fullname,
			"customer_type": "Individual",
			"customer_group": get_shopping_cart_settings().default_customer_group,
			"territory": get_root_of("Territory")
		})

		if debtors_account:
			customer.update({
				"accounts": [{
					"company": cart_settings.company,
					"account": debtors_account
				}]
			})

		customer.flags.ignore_mandatory = True
		customer.insert(ignore_permissions=True)

		contact = dataent.new_doc("Contact")
		contact.update({
			"first_name": fullname,
			"email_id": user
		})
		contact.append('links', dict(link_doctype='Customer', link_name=customer.name))
		contact.flags.ignore_mandatory = True
		contact.insert(ignore_permissions=True)

		return customer
Ejemplo n.º 4
0
def guess_territory():
	territory = None
	geoip_country = dataent.session.get("session_country")
	if geoip_country:
		territory = dataent.db.get_value("Territory", geoip_country)

	return territory or \
		dataent.db.get_value("Shopping Cart Settings", None, "territory") or \
			get_root_of("Territory")
Ejemplo n.º 5
0
def setup_pos_profile():
	company_abbr = dataent.get_cached_value('Company',  epaas.get_default_company(),  "abbr")
	pos = dataent.new_doc('POS Profile')
	pos.user = dataent.db.get_global('demo_accounts_user')
	pos.name = "Demo POS Profile"
	pos.naming_series = 'SINV-'
	pos.update_stock = 0
	pos.write_off_account = 'Cost of Goods Sold - '+ company_abbr
	pos.write_off_cost_center = 'Main - '+ company_abbr
	pos.customer_group = get_root_of('Customer Group')
	pos.territory = get_root_of('Territory')

	pos.append('payments', {
		'mode_of_payment': dataent.db.get_value('Mode of Payment', {'type': 'Cash'}, 'name'),
		'amount': 0.0,
		'default': 1
	})

	pos.insert()
Ejemplo n.º 6
0
def create_territories():
    """create two default territories, one for home country and one named Rest of the World"""
    from dataent.utils.nestedset import get_root_of
    country = dataent.db.get_default("country")
    root_territory = get_root_of("Territory")

    for name in (country, _("Rest Of The World")):
        if name and not dataent.db.exists("Territory", name):
            dataent.get_doc({
                "doctype": "Territory",
                "territory_name": name.replace("'", ""),
                "parent_territory": root_territory,
                "is_group": "No"
            }).insert()
Ejemplo n.º 7
0
def get_tax_template(posting_date, args):
    """Get matching tax rule"""
    args = dataent._dict(args)
    conditions = [
        """(from_date is null or from_date <= '{0}')
		and (to_date is null or to_date >= '{0}')""".format(posting_date)
    ]

    for key, value in iteritems(args):
        if key == "use_for_shopping_cart":
            conditions.append(
                "use_for_shopping_cart = {0}".format(1 if value else 0))
        if key == 'customer_group':
            if not value: value = get_root_of("Customer Group")
            customer_group_condition = get_customer_group_condition(value)
            conditions.append("ifnull({0}, '') in ('', {1})".format(
                key, customer_group_condition))
        else:
            conditions.append("ifnull({0}, '') in ('', '{1}')".format(
                key, dataent.db.escape(cstr(value))))

    tax_rule = dataent.db.sql("""select * from `tabTax Rule`
		where {0}""".format(" and ".join(conditions)),
                              as_dict=True)

    if not tax_rule:
        return None

    for rule in tax_rule:
        rule.no_of_keys_matched = 0
        for key in args:
            if rule.get(key): rule.no_of_keys_matched += 1

    rule = sorted(
        tax_rule,
        key=functools.cmp_to_key(
            lambda b, a: cmp(a.no_of_keys_matched, b.no_of_keys_matched
                             ) or cmp(a.priority, b.priority)))[0]

    tax_template = rule.sales_tax_template or rule.purchase_tax_template
    doctype = "{0} Taxes and Charges Template".format(rule.tax_type)

    if dataent.db.get_value(doctype, tax_template, 'disabled') == 1:
        return None

    return tax_template
Ejemplo n.º 8
0
def get_children(doctype, parent=None, company=None, is_root=False):
    condition = ''
    if company == parent:
        condition = "name='{0}'".format(get_root_of("Department"))
    elif company:
        condition = "parent_department='{0}' and company='{1}'".format(
            parent, company)
    else:
        condition = "parent_department = '{0}'".format(parent)

    return dataent.db.sql("""
		select
			name as value,
			is_group as expandable
		from `tab{doctype}`
		where
			{condition}
		order by name""".format(doctype=doctype, condition=condition),
                          as_dict=1)
Ejemplo n.º 9
0
def create_price_list(pl_name, buying=0, selling=0):
    price_list = dataent.get_doc({
        "doctype":
        "Price List",
        "price_list_name":
        pl_name,
        "enabled":
        1,
        "buying":
        buying,
        "selling":
        selling,
        "currency":
        dataent.db.get_default("currency"),
        "territories": [{
            "territory": get_root_of("Territory")
        }]
    })
    price_list.insert()
Ejemplo n.º 10
0
def make_rfq(item, supplier, contact):
    # make rfq
    rfq = dataent.get_doc({
        'doctype':
        'Request for Quotation',
        'transaction_date':
        nowdate(),
        'status':
        'Draft',
        'company':
        dataent.db.get_single_value('Marketplace Settings', 'company'),
        'message_for_supplier':
        'Please supply the specified items at the best possible rates',
        'suppliers': [{
            'supplier': supplier.name,
            'contact': contact.name
        }],
        'items': [{
            'item_code':
            item.item_code,
            'qty':
            1,
            'schedule_date':
            nowdate(),
            'warehouse':
            item.default_warehouse or get_root_of("Warehouse"),
            'description':
            item.description,
            'uom':
            item.stock_uom
        }]
    }).insert()

    rfq.save()
    rfq.submit()
    return rfq
Ejemplo n.º 11
0
 def set_default_customer_group_and_territory(self):
     if not self.customer_group:
         self.customer_group = get_root_of('Customer Group')
     if not self.territory:
         self.territory = get_root_of('Territory')
Ejemplo n.º 12
0
 def validate(self):
     if not self.parent_supplier_group:
         self.parent_supplier_group = get_root_of("Supplier Group")
Ejemplo n.º 13
0
    def create_delete_custom_fields(self):
        if self.enable_sync:
            # create
            create_custom_field_id_and_check_status = False
            create_custom_field_email_check = False
            names = [
                "Customer-woocommerce_id", "Sales Order-woocommerce_id",
                "Item-woocommerce_id", "Address-woocommerce_id"
            ]
            names_check_box = [
                "Customer-woocommerce_check", "Sales Order-woocommerce_check",
                "Item-woocommerce_check", "Address-woocommerce_check"
            ]
            email_names = [
                "Customer-woocommerce_email", "Address-woocommerce_email"
            ]

            for i in zip(names, names_check_box):

                if not dataent.get_value("Custom Field", {
                        "name": i[0]
                }) or not dataent.get_value("Custom Field", {"name": i[1]}):
                    create_custom_field_id_and_check_status = True
                    break

            if create_custom_field_id_and_check_status:
                names = ["Customer", "Sales Order", "Item", "Address"]
                for name in names:
                    custom = dataent.new_doc("Custom Field")
                    custom.dt = name
                    custom.label = "woocommerce_id"
                    custom.read_only = 1
                    custom.save()

                    custom = dataent.new_doc("Custom Field")
                    custom.dt = name
                    custom.label = "woocommerce_check"
                    custom.fieldtype = "Check"
                    custom.read_only = 1
                    custom.save()

            for i in email_names:

                if not dataent.get_value("Custom Field", {"name": i}):
                    create_custom_field_email_check = True
                    break

            if create_custom_field_email_check:
                names = ["Customer", "Address"]
                for name in names:
                    custom = dataent.new_doc("Custom Field")
                    custom.dt = name
                    custom.label = "woocommerce_email"
                    custom.read_only = 1
                    custom.save()

            if not dataent.get_value("Item Group",
                                     {"name": _("WooCommerce Products")}):
                item_group = dataent.new_doc("Item Group")
                item_group.item_group_name = _("WooCommerce Products")
                item_group.parent_item_group = get_root_of("Item Group")
                item_group.save()

        elif not self.enable_sync:
            # delete
            names = [
                "Customer-woocommerce_id", "Sales Order-woocommerce_id",
                "Item-woocommerce_id", "Address-woocommerce_id"
            ]
            names_check_box = [
                "Customer-woocommerce_check", "Sales Order-woocommerce_check",
                "Item-woocommerce_check", "Address-woocommerce_check"
            ]
            email_names = [
                "Customer-woocommerce_email", "Address-woocommerce_email"
            ]
            for name in names:
                dataent.delete_doc("Custom Field", name)

            for name in names_check_box:
                dataent.delete_doc("Custom Field", name)

            for name in email_names:
                dataent.delete_doc("Custom Field", name)

            dataent.delete_doc("Item Group", _("WooCommerce Products"))

        dataent.db.commit()
Ejemplo n.º 14
0
def get_items(start, page_length, price_list, item_group, search_value="", pos_profile=None):
	data = dict()
	warehouse = ""
	display_items_in_stock = 0

	if pos_profile:
		warehouse, display_items_in_stock = dataent.db.get_value('POS Profile', pos_profile, ['warehouse', 'display_items_in_stock'])

	if not dataent.db.exists('Item Group', item_group):
		item_group = get_root_of('Item Group')

	if search_value:
		data = search_serial_or_batch_or_barcode_number(search_value)

	item_code = data.get("item_code") if data.get("item_code") else search_value
	serial_no = data.get("serial_no") if data.get("serial_no") else ""
	batch_no = data.get("batch_no") if data.get("batch_no") else ""
	barcode = data.get("barcode") if data.get("barcode") else ""

	item_code, condition = get_conditions(item_code, serial_no, batch_no, barcode)

	if pos_profile:
		condition += get_item_group_condition(pos_profile)

	lft, rgt = dataent.db.get_value('Item Group', item_group, ['lft', 'rgt'])
	# locate function is used to sort by closest match from the beginning of the value


	if display_items_in_stock == 0:
		res = dataent.db.sql("""select i.name as item_code, i.item_name, i.image as item_image, i.idx as idx,
			i.is_stock_item, item_det.price_list_rate, item_det.currency
			from `tabItem` i LEFT JOIN
				(select item_code, price_list_rate, currency from
					`tabItem Price`	where price_list=%(price_list)s) item_det
			ON
				(item_det.item_code=i.name or item_det.item_code=i.variant_of)
			where
				i.disabled = 0 and i.has_variants = 0 and i.is_sales_item = 1
				and i.item_group in (select name from `tabItem Group` where lft >= {lft} and rgt <= {rgt})
		        	and {condition} order by idx desc limit {start}, {page_length}""".format(start=start,page_length=page_length,lft=lft, rgt=rgt, 					condition=condition),
			{
				'item_code': item_code,
				'price_list': price_list
			} , as_dict=1)

		res = {
		'items': res
		}

	elif display_items_in_stock == 1:
		query = """select i.name as item_code, i.item_name, i.image as item_image, i.idx as idx,
				i.is_stock_item, item_det.price_list_rate, item_det.currency
				from `tabItem` i LEFT JOIN
					(select item_code, price_list_rate, currency from
						`tabItem Price`	where price_list=%(price_list)s) item_det
				ON
					(item_det.item_code=i.name or item_det.item_code=i.variant_of) INNER JOIN"""

		if warehouse is not None:
			query = query +  """ (select item_code,actual_qty from `tabBin` where warehouse=%(warehouse)s and actual_qty > 0 group by item_code) item_se"""
		else:
			query = query +  """ (select item_code,sum(actual_qty) as actual_qty from `tabBin` group by item_code) item_se"""

		res = dataent.db.sql(query +  """
			ON
				((item_se.item_code=i.name or item_det.item_code=i.variant_of) and item_se.actual_qty>0)
			where
				i.disabled = 0 and i.has_variants = 0 and i.is_sales_item = 1
				and i.item_group in (select name from `tabItem Group` where lft >= {lft} and rgt <= {rgt})
				and {condition} order by idx desc limit {start}, {page_length}""".format
				(start=start,page_length=page_length,lft=lft, 	rgt=rgt, condition=condition),
			{
				'item_code': item_code,
				'price_list': price_list,
				'warehouse': warehouse
			} , as_dict=1)

		res = {
		'items': res
		}

	if serial_no:
		res.update({
			'serial_no': serial_no
		})

	if batch_no:
		res.update({
			'batch_no': batch_no
		})

	if barcode:
		res.update({
			'barcode': barcode
		})

	return res
Ejemplo n.º 15
0
 def validate(self):
     if not self.parent_department:
         root = get_root_of("Department")
         if root:
             self.parent_department = root