UNPKG

@ecomplus/storefront-template

Version:

Reusable & upgradable views and scripts for E-Com Plus storefront

124 lines (112 loc) 3.77 kB
import { modules } from '@ecomplus/client' import { price as getPrice } from '@ecomplus/utils' import emitter from './emitter' import { utm, sessionCoupon } from './persist-utm' window._info = window._info || {} const fetchInfoPromises = [] const modulesToFetch = Array.isArray(window.modulesToFetch) ? window.modulesToFetch : [ { endpoint: 'list_payments' }, { endpoint: 'calculate_shipping' } ] if (Object.keys(utm).length || sessionCoupon) { const { resource, body: contextBody } = (window.storefront && window.storefront.context) || {} const applyDiscountData = { utm } if (contextBody && contextBody._id) { if (resource === 'products') { applyDiscountData.items = [{ product_id: contextBody._id, categories: contextBody.categories, quantity: 1, price: getPrice(contextBody) }] } } if (sessionCoupon) { applyDiscountData.discount_coupon = sessionCoupon } modulesToFetch.push({ endpoint: 'apply_discount', reqOptions: { method: 'post', data: applyDiscountData } }) } modulesToFetch.forEach(({ endpoint, reqOptions }) => { const modInfo = {} window._info[endpoint] = modInfo const promise = new Promise(resolve => { modules({ url: `/${endpoint}.json`, ...reqOptions, axiosConfig: { timeout: 10000 } }) .then(({ data }) => { const { result } = data if (Array.isArray(result)) { result.forEach(({ error, response }) => { if (!error) { let field, val switch (endpoint) { case 'calculate_shipping': field = 'free_shipping_from_value' val = response[field] if (typeof val === 'number' && (modInfo[field] === undefined || val < modInfo[field])) { modInfo[field] = val } break case 'list_payments': field = 'installments_option' val = response[field] if (val && (!modInfo[field] || val.monthly_interest < modInfo[field].monthly_interest || val.max_number > modInfo[field].max_number)) { modInfo[field] = val } field = 'discount_option' val = response[field] if (val && (!modInfo[field] || val.value > modInfo[field].value)) { response.payment_gateways.forEach(({ discount }) => { if (discount && discount.apply_at !== 'freight' && discount.value === val.value) { modInfo[field] = { apply_at: discount.apply_at, ...val } } }) } field = 'loyalty_points_programs' val = response[field] if (val) { modInfo[field] = { ...modInfo[field], ...val } } break default: field = 'available_extra_discount' val = response[field] if (val && (!modInfo[field] || val.value > modInfo[field].value)) { modInfo[field] = val } } } }) } emitter.emit(`info:${endpoint}`, modInfo) }) .catch(err => { console.error(err) emitter.emit(`info:${endpoint}`, err) }) .finally(resolve) }) fetchInfoPromises.push(promise) }) Promise.all(fetchInfoPromises) .then(() => emitter.emit('info', window._info))