def build_embed_context(context, is_backend=False):
	"""Convenience method that adds gateway information for a page's context"""

	context["data"] = {}
	gateways = get_gateways(is_backend=is_backend)


	# Build billing address context
	context["billing_countries"] = [ x for x in frappe.get_list("Country", fields=["country_name", "name"], ignore_permissions=1) ]
	context["is_backend"] = is_backend

	default_country = frappe.get_value("System Settings", "System Settings", "country")
	default_country_doc = next((x for x in context["billing_countries"] if x.name == default_country), None)
	customer = get_current_customer()
	if customer:
		context["addresses"] = frappe.get_all("Address", filters={"customer" : customer.name, "disabled" : 0}, fields="*")

	country_idx = context["billing_countries"].index(default_country_doc)
	context["billing_countries"].pop(country_idx)
	context["billing_countries"] = [default_country_doc] + context["billing_countries"]

	context["gateway_scripts"] = ['/assets/js/gateway_selector_embed.js']
	context["gateway_styles"] = ['/assets/css/gateway_selector_embed.css']
	context["gateways"] = gateways

	for gateway in gateways:
		if gateway.get('embed_form'):
			context["gateway_scripts"].append(gateway.get('embed_form').get("script_url"))
			context["gateway_styles"].append(gateway.get('embed_form').get("style_url"))
Ejemplo n.º 2
0
def set_missing_values(warranty_claim, method):
	if not warranty_claim.customer:
		customer = get_current_customer()
		warranty_claim.customer = customer.name
	else:
		customer = frappe.get_doc("Customer", warranty_claim.customer)

	warranty_claim.update({
		"customer_name": customer.customer_name,
		"contact_email": customer.email_id,
		"contact_person": get_default_contact("Customer", customer.name)
	})

	if not warranty_claim.contact_mobile:
		warranty_claim.contact_mobile = customer.mobile_no

	if not warranty_claim.serial_no and frappe.db.exists("Serial No", warranty_claim.unlinked_serial_no):
		warranty_claim.serial_no = warranty_claim.unlinked_serial_no

	if warranty_claim.serial_no:
		serial_no = frappe.get_doc("Serial No", warranty_claim.serial_no)

		warranty_claim.update({
			"item_code": serial_no.item_code,
			"item_name": serial_no.item_name,
			"item_group": serial_no.item_group,
			"description": serial_no.description,
			"warranty_amc_status": serial_no.maintenance_status,
			"warranty_expiry_date": serial_no.warranty_expiry_date,
			"amc_expiry_date": serial_no.amc_expiry_date,
			"is_under_warranty": serial_no.maintenance_status in ["Under Warranty", "Under AMC"]
		})
Ejemplo n.º 3
0
def get_context(context):
    """This is a controller extension for erpnext.templates.pages.cart"""

    context["no_cache"] = 1

    settings = frappe.db.get("Awc Settings")
    awc_session = get_awc_session()

    context["countries"] = [
        x for x in frappe.get_list(
            "Country", fields=["country_name", "name"], ignore_permissions=1)
    ]

    default_country = frappe.get_value("System Settings", "System Settings",
                                       "country")
    default_country_doc = next(
        (x for x in context["countries"] if x.name == default_country), None)

    if frappe.session.user != "Guest":
        context["addresses"] = frappe.get_all("Address",
                                              filters={
                                                  "customer":
                                                  get_current_customer().name,
                                                  "disabled":
                                                  False
                                              },
                                              fields="*")

    country_idx = context["countries"].index(default_country_doc)
    context["countries"].pop(country_idx)
    context["countries"] = [default_country_doc] + context["countries"]

    context["shipping_rate_api"] = frappe.get_hooks("shipping_rate_api")[0]
    context["selected_customer"] = awc_session.get("selected_customer")

    # remove? shipping is essential here anyways
    context.shipping_enabled = 1 if settings.awc_shipping_enabled else 0

    # flag to display login form
    context.is_logged = awc.is_logged_in()
    login.apply_context(context)

    if context.is_logged:
        # load gateway provider into context
        gateway_provider = frappe.get_hooks('awc_gateway_form_provider')
        if gateway_provider and len(gateway_provider) > 0:
            context['gateway_provider'] = frappe.call(
                gateway_provider[0],
                context=dict(use_address_same_as=1,
                             address_same_as_label="Same as Shipping Address",
                             address_same_as_source="#awc-shipping-form"))

    awc.reset_shipping()

    return context
Ejemplo n.º 4
0
	def is_available(self, context={}, is_backend=0):

		# never available to backend
		if is_backend:
			return False

		customer = get_current_customer()

		if customer:
			# disabled until Eric figures out if JHA wants to check against credit
			#return context["total_credit"] > 0
			self.get_embed_context(context)

			# test for either allow_billme_later or can_billme_later role

			return customer.get("allow_billme_later", False) or "Bill Me Later User" in frappe.get_roles()

		return False
Ejemplo n.º 5
0
def get_context(context):
    from awesome_cart.compat.customer import get_current_customer
    if frappe.session.user == 'Guest':
        frappe.throw(_("You need to be logged in to access this page"),
                     frappe.PermissionError)

    context.show_sidebar = True

    customer = get_current_customer()

    context["total_unpaid"] = frappe.db.sql(
        """select sum(outstanding_amount)
	from `tabSales Invoice`
	where customer=%s and docstatus = 1""", customer.name)[0][0] or ""

    context["credit_limit"] = customer.credit_limit
    context["credit_days_based_on"] = customer.credit_days_based_on
    context["credit_days"] = customer.credit_days

    return context
Ejemplo n.º 6
0
    def is_available(self, context={}, is_backend=0):

        print("Credit gateway...{0}".format(is_backend))
        print(pretty_json(context))

        # never available to backend
        if is_backend:
            return False

        customer = get_current_customer()
        print("Customer: {0}".format(customer))

        if customer:
            print(pretty_json(customer.as_dict()))
            # disabled until Eric figures out if JHA wants to check against credit
            #return context["total_credit"] > 0
            self.get_embed_context(context)

            return customer.get("allow_billme_later", False)

        return False
Ejemplo n.º 7
0
def get_quick_cache(key, awc_session=None, customer=None, prefix=None):

    if not prefix:
        prefix = "awc-sku"

    if not awc_session:
        awc_session = get_awc_session()

    if not customer:
        from awesome_cart.compat.customer import get_current_customer
        customer = get_current_customer()

    customer_lbl = "None"
    if customer:
        customer_lbl = customer.customer_group

    cache_prefix = prefix  #.format(customer_lbl)
    cache_data = get_cache("{}-{}".format(customer_lbl, key),
                           session=awc_session,
                           prefix=cache_prefix)

    return cache_data, cache_prefix, awc_session
Ejemplo n.º 8
0
def get_context(context):
	"""This is a controller extension for erpnext.templates.pages.cart"""

	context["no_cache"] = 1

	settings = frappe.db.get("Awc Settings")
	awc_session = get_awc_session()
	customer = get_current_customer()

	context["countries"] = [ x for x in frappe.get_list("Country", fields=["country_name", "name"], ignore_permissions=1) ]

	default_country = frappe.get_value("System Settings", "System Settings", "country")
	default_country_doc = next((x for x in context["countries"] if x.name == default_country), None)

	if frappe.session.user != "Guest":
		address_links = frappe.get_all("Dynamic Link", filters={"link_name" : customer.name}, fields=["parent"])
		addresses = []
		for address in address_links:
			addresses.extend(frappe.get_all("Address", filters={"name" : address.parent, "disabled" : False}, fields="*"))
		context['addresses'] = addresses

		customer_info = frappe.db.get_values("Customer", customer.name, ["has_shipping_account", "fedex_account_number"])[0]
		context["customer_info"] = {
			"has_shipping_acc": customer_info[0],
			"fedex_acc_number": customer_info[1]
		}

	country_idx = context["countries"].index(default_country_doc)
	context["countries"].pop(country_idx)
	context["countries"] = [default_country_doc] + context["countries"]

	context["shipping_rate_api"] = frappe.get_hooks("shipping_rate_api")[0]
	context["selected_customer"] = awc_session.get("selected_customer")

	# ensures clearing address and method selection when visiting checkout page as
	# shipping address widget won't pre-select them.
	awc.reset_shipping(None, awc_session=awc_session, customer=customer)

	# remove? shipping is essential here anyways
	context.shipping_enabled = 1 if settings.awc_shipping_enabled else 0

	related_items = []
	skus_in_cart = []
	# build upsell sku list using or building cache if necessary
	for item in awc_session.get("cart", {}).get("items", []):
		# build cart sku list to dedup later
		skus_in_cart += [item.get("sku")]

		# fetches related items to this sku
		item_related_items = awc.get_related_products_by_sku(
			item.get("sku"), awc_session=awc_session, customer=customer)

		# quick list deduping
		related_items = related_items + list(set(item_related_items) - set(related_items))

	# builds upsell item objects using cache if necessary
	upsell = []
	for sku in related_items:
		if sku not in skus_in_cart:
			# fetches product data to build upsell widget
			product_response = awc.get_product_by_sku(sku, awc_session=awc_session)
			if product_response.get("success"):
				upsell += [product_response.get("data")]

	# upsell widget data is made available to the context here
	context["upsell"] = dict(related_products=upsell)

	# flag to display login form
	context.is_logged = awc.is_logged_in()
	login.apply_context(context)

	if frappe.response.get("awc_alert"):
		context["awc_alert"] = frappe.response.get("awc_alert")


	if context.is_logged:
		# load gateway provider into context
		gateway_provider = frappe.get_hooks('awc_gateway_form_provider')
		if gateway_provider and len(gateway_provider) > 0:
			context['gateway_provider'] = frappe.call(gateway_provider[0], context=dict(
				use_address_same_as=1,
				address_same_as_label="Same as Shipping Address",
				address_same_as_source="#awc-shipping-form"
			))

	return context
Ejemplo n.º 9
0
def get_context(context):
    if frappe.session.user == 'Guest':
        frappe.throw(_("You need to be logged in to access this page"),
                     frappe.PermissionError)

    context.no_cache = 1

    # get request name from query string
    proxy_name = frappe.form_dict.get("id")
    # or from pathname, this works better for redirection on auth errors
    if not proxy_name:
        path_parts = context.get("pathname", "").split('/')
        proxy_name = path_parts[-1]

    # attempt to fetch AuthorizeNet Request record
    try:
        proxy = frappe.get_doc("Gateway Selector Proxy", proxy_name)
    except Exception as ex:
        proxy = None

    # Captured/Authorized transaction redirected to home page
    # TODO: Should we redirec to a "Payment already received" Page?
    if not proxy:
        frappe.local.flags.redirect_location = '/'
        raise frappe.Redirect

    build_embed_context(context)

    if proxy_name and proxy:
        context["data"] = {key: proxy.get(key) for key in expected_keys}

        context["billing_countries"] = [
            x for x in frappe.get_list("Country",
                                       fields=["country_name", "name"],
                                       ignore_permissions=1)
        ]

        default_country = frappe.get_value("System Settings",
                                           "System Settings", "country")
        default_country_doc = next((x for x in context["billing_countries"]
                                    if x.name == default_country), None)

        context["addresses"] = frappe.get_all("Address",
                                              filters={
                                                  "customer":
                                                  get_current_customer().name,
                                                  "disabled":
                                                  0
                                              },
                                              fields="*")

        country_idx = context["billing_countries"].index(default_country_doc)
        context["billing_countries"].pop(country_idx)
        context["billing_countries"] = [default_country_doc
                                        ] + context["billing_countries"]

    else:
        frappe.redirect_to_message(
            _('Some information is missing'),
            _('Looks like someone sent you to an incomplete URL. Please ask them to look into it.'
              ))
        frappe.local.flags.redirect_location = frappe.local.response.location
        raise frappe.Redirect

    return context
Ejemplo n.º 10
0
def get_context(context):
    """This is a controller extension for erpnext.templates.pages.cart"""

    context["no_cache"] = 1

    settings = frappe.db.get("Awc Settings")
    awc_session = get_awc_session()
    customer = get_current_customer()

    context["countries"] = [
        x for x in frappe.get_list(
            "Country", fields=["country_name", "name"], ignore_permissions=1)
    ]

    default_country = frappe.get_value("System Settings", "System Settings",
                                       "country")
    default_country_doc = next(
        (x for x in context["countries"] if x.name == default_country), None)

    if frappe.session.user != "Guest":
        address_links = frappe.get_all("Dynamic Link",
                                       filters={"link_name": customer.name},
                                       fields=["parent"])
        addresses = []
        for address in address_links:
            addresses.extend(
                frappe.get_all("Address",
                               filters={
                                   "name": address.parent,
                                   "disabled": False
                               },
                               fields="*"))
        context['addresses'] = addresses

        customer_info = frappe.db.get_values(
            "Customer", customer.name,
            ["has_shipping_account", "fedex_account_number"])[0]
        context["customer_info"] = {
            "has_shipping_acc": customer_info[0],
            "fedex_acc_number": customer_info[1]
        }

    country_idx = context["countries"].index(default_country_doc)
    context["countries"].pop(country_idx)
    context["countries"] = [default_country_doc] + context["countries"]

    context["shipping_rate_api"] = frappe.get_hooks("shipping_rate_api")[0]
    context["selected_customer"] = awc_session.get("selected_customer", False)

    # ensures clearing address and method selection when visiting checkout page as
    # shipping address widget won't pre-select them.
    awc.reset_shipping(None, awc_session=awc_session, customer=customer)

    # remove? shipping is essential here anyways
    context.shipping_enabled = 1 if settings.awc_shipping_enabled else 0

    related_items = []
    skus_in_cart = []
    # build upsell sku list using or building cache if necessary
    for item in awc_session.get("cart", {}).get("items", []):
        # build cart sku list to dedup later
        skus_in_cart += [item.get("sku")]

        # fetches related items to this sku
        item_related_items = awc.get_related_products_by_sku(
            item.get("sku"), awc_session=awc_session, customer=customer)

        # quick list deduping
        related_items = related_items + list(
            set(item_related_items) - set(related_items))

    # builds upsell item objects using cache if necessary
    upsell = []
    for sku in related_items:
        if sku not in skus_in_cart:
            # fetches product data to build upsell widget
            product_response = awc.get_product_by_sku(sku,
                                                      awc_session=awc_session)
            if product_response.get("success"):
                upsell += [product_response.get("data")]

    # upsell widget data is made available to the context here
    context["upsell"] = dict(related_products=upsell)

    # flag to display login form
    context.is_logged = frappe.session.user != "Guest"
    # get settings from site config
    context["disable_signup"] = cint(
        frappe.db.get_single_value("Website Settings", "disable_signup"))

    for provider in ("google", "github", "facebook", "frappe"):
        if get_oauth_keys(provider):
            context["{provider}_login".format(
                provider=provider)] = get_oauth2_authorize_url(provider,
                                                               redirect_to="/")
            context["social_login"] = True

    ldap_settings = LDAPSettings.get_ldap_client_settings()
    context["ldap_settings"] = ldap_settings

    return context

    if frappe.response.get("awc_alert"):
        context["awc_alert"] = frappe.response.get("awc_alert")

    user_doc = frappe.get_doc("User", frappe.session.user)

    context['enable_contacts'] = False

    if context["selected_customer"] and (user_doc.get("is_power_user") or \
     has_role([
      "Administrator",
      "Sales User",
      "Sales Manager",
      "System Manager"
     ], user_doc.name)):

        # find olddest is_primary or oldest contact
        context['customer_contacts'] = frappe.db.sql(
            """
			SELECT
				c.name as name,
				c.email_id as email_id,
				c.first_name as first_name,
				c.last_name as last_name,
				c.is_primary_contact as is_primary_contact
			FROM
				`tabContact` c
			LEFT JOIN
				`tabDynamic Link` dl ON dl.parent=c.name
			WHERE
				dl.link_doctype='Customer' AND
				dl.link_name=%(customer_name)s
			ORDER BY
				c.is_primary_contact DESC,
				c.creation asc
		""", {"customer_name": context["selected_customer"]},
            as_dict=True)

        context['enable_contacts'] = True if len(
            context['customer_contacts']) > 1 else False

    if context.is_logged:
        # load gateway provider into context
        gateway_provider = frappe.get_hooks('awc_gateway_form_provider')
        if gateway_provider and len(gateway_provider) > 0:
            context['gateway_provider'] = frappe.call(
                gateway_provider[0],
                context=dict(use_address_same_as=1,
                             address_same_as_label="Same as Shipping Address",
                             address_same_as_source="#awc-shipping-form"))

    return context