-
-
Save basilkhan05/d48319001db76dc8c10d586f1c78bd85 to your computer and use it in GitHub Desktop.
simple-bundles-cart-expander.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Simple Bundles Cart Expander v5 | |
| * | |
| * Supports: | |
| * - Simple Bundles (fixed components) | |
| * - Infinite Options Bundles (customer-selected variants) | |
| * - Selling plan passthrough for subscription apps like Ordergroove | |
| * | |
| * IMPORTANT: This script ONLY expands bundles when a selling_plan is present. | |
| * Non-subscription bundle purchases pass through normally to Simple Bundles. | |
| * | |
| * For IO bundles, parses the _bundle_selection property to match | |
| * customer selections against bundle_component_selections metafield. | |
| */ | |
| (function() { | |
| 'use strict'; | |
| var CONFIG = { | |
| debug: true, | |
| selectors: { | |
| productForm: 'form[action="/cart/add"], form[action*="/cart/add"]', | |
| variantInput: 'input[name="id"], select[name="id"]', | |
| sellingPlanInput: 'input[name="selling_plan"], select[name="selling_plan"]', | |
| quantityInput: 'input[name="quantity"]', | |
| addToCartButton: '[type="submit"], .add-to-cart, .product-form__submit' | |
| } | |
| }; | |
| var Logger = { | |
| prefix: '[SB-Expander]', | |
| log: function() { | |
| if (CONFIG.debug) { | |
| var args = [this.prefix].concat(Array.prototype.slice.call(arguments)); | |
| console.log.apply(console, args); | |
| } | |
| }, | |
| warn: function() { | |
| var args = [this.prefix].concat(Array.prototype.slice.call(arguments)); | |
| console.warn.apply(console, args); | |
| }, | |
| error: function() { | |
| var args = [this.prefix].concat(Array.prototype.slice.call(arguments)); | |
| console.error.apply(console, args); | |
| } | |
| }; | |
| // ========================================= | |
| // METAFIELD CACHE | |
| // ========================================= | |
| var MetafieldCache = { | |
| _cache: {}, | |
| get: function(vid) { return this._cache[String(vid)]; }, | |
| set: function(vid, data) { this._cache[String(vid)] = data; }, | |
| has: function(vid) { return String(vid) in this._cache; } | |
| }; | |
| // ========================================= | |
| // METAFIELD FETCHER | |
| // ========================================= | |
| var MetafieldFetcher = { | |
| fetch: function(variantId) { | |
| var vid = String(variantId); | |
| if (MetafieldCache.has(vid)) { | |
| return MetafieldCache.get(vid); | |
| } | |
| var metafields = { | |
| simpleComponents: null, | |
| ioSelections: null, | |
| bundleType: null | |
| }; | |
| if (window.__SB_VARIANT_METAFIELDS__ && window.__SB_VARIANT_METAFIELDS__[vid]) { | |
| var data = window.__SB_VARIANT_METAFIELDS__[vid]; | |
| metafields.simpleComponents = data.simple_bundle_components; | |
| metafields.ioSelections = this._parseIOSelections(data.bundle_component_selections); | |
| metafields.bundleType = data.bundle_type; | |
| Logger.log('Loaded metafields for variant', vid, metafields); | |
| } else { | |
| Logger.warn('No metafield data found for variant:', vid); | |
| } | |
| MetafieldCache.set(vid, metafields); | |
| return metafields; | |
| }, | |
| _parseIOSelections: function(value) { | |
| if (!value) return null; | |
| if (Array.isArray(value)) return value; | |
| if (typeof value === 'string') { | |
| try { | |
| return JSON.parse(value); | |
| } catch (e) { | |
| Logger.error('Failed to parse IO selections:', e); | |
| return null; | |
| } | |
| } | |
| return null; | |
| } | |
| }; | |
| // ========================================= | |
| // BUNDLE DETECTOR | |
| // ========================================= | |
| var BundleDetector = { | |
| isBundle: function(mf) { | |
| if (!mf) return false; | |
| var hasSimple = mf.simpleComponents && Array.isArray(mf.simpleComponents) && mf.simpleComponents.length > 0; | |
| var hasIO = mf.ioSelections && Array.isArray(mf.ioSelections) && mf.ioSelections.length > 0; | |
| return hasSimple || hasIO; | |
| }, | |
| getBundleType: function(mf) { | |
| if (!mf) return null; | |
| // Check explicit bundle_type first | |
| if (mf.bundleType) return mf.bundleType; | |
| // Infer from available data | |
| if (mf.ioSelections && Array.isArray(mf.ioSelections) && mf.ioSelections.length > 0) { | |
| return 'infinite_options'; | |
| } | |
| if (mf.simpleComponents && Array.isArray(mf.simpleComponents) && mf.simpleComponents.length > 0) { | |
| return 'simple'; | |
| } | |
| return null; | |
| } | |
| }; | |
| // ========================================= | |
| // COMPONENT RESOLVER | |
| // ========================================= | |
| var ComponentResolver = { | |
| /** | |
| * Resolve Simple Bundle components | |
| */ | |
| resolveSimpleBundle: function(components, qty) { | |
| qty = qty || 1; | |
| Logger.log('Resolving Simple Bundle:', components.length, 'components, qty:', qty); | |
| if (!Array.isArray(components)) return []; | |
| var result = []; | |
| for (var i = 0; i < components.length; i++) { | |
| var item = components[i]; | |
| var variantId, itemQty; | |
| if (Array.isArray(item)) { | |
| variantId = item[0]; | |
| itemQty = item[1] || 1; | |
| } else if (item && typeof item === 'object') { | |
| variantId = item.variant_id || item.id; | |
| itemQty = item.quantity || item.quantity_in_bundle || 1; | |
| } else { | |
| continue; | |
| } | |
| result.push({ | |
| id: parseInt(variantId), | |
| quantity: parseInt(itemQty) * qty | |
| }); | |
| } | |
| Logger.log('Resolved Simple Bundle:', result); | |
| return result.filter(function(item) { return item.id && item.quantity > 0; }); | |
| }, | |
| /** | |
| * Resolve IO Bundle components by matching _bundle_selection against bundle_component_selections | |
| */ | |
| resolveIOBundle: function(ioSelections, bundleSelectionString, qty) { | |
| qty = qty || 1; | |
| Logger.log('Resolving IO Bundle'); | |
| Logger.log(' _bundle_selection:', bundleSelectionString); | |
| Logger.log(' ioSelections:', ioSelections); | |
| if (!Array.isArray(ioSelections) || !bundleSelectionString) { | |
| Logger.error('Invalid IO bundle data'); | |
| return []; | |
| } | |
| // Parse the _bundle_selection string | |
| // Format: "Option A <> Option B <> Option C" | |
| var selectedOptions = bundleSelectionString.split('<>').map(function(s) { | |
| return s.trim(); | |
| }); | |
| Logger.log(' Parsed selections:', selectedOptions); | |
| var resolved = []; | |
| // For each selected option, find the matching variant in ioSelections | |
| for (var i = 0; i < selectedOptions.length; i++) { | |
| var selection = selectedOptions[i]; | |
| var found = false; | |
| // Search through each group in ioSelections | |
| for (var j = 0; j < ioSelections.length; j++) { | |
| var group = ioSelections[j]; | |
| if (group && typeof group === 'object') { | |
| // Check if this selection exists in this group | |
| var keys = Object.keys(group); | |
| for (var k = 0; k < keys.length; k++) { | |
| var optionName = keys[k]; | |
| // Exact match or close match | |
| if (optionName === selection || | |
| optionName.toLowerCase() === selection.toLowerCase() || | |
| selection.toLowerCase().indexOf(optionName.toLowerCase()) !== -1 || | |
| optionName.toLowerCase().indexOf(selection.toLowerCase()) !== -1) { | |
| var variantData = group[optionName]; | |
| if (Array.isArray(variantData)) { | |
| for (var v = 0; v < variantData.length; v++) { | |
| var vd = variantData[v]; | |
| if (Array.isArray(vd) && vd.length >= 1) { | |
| resolved.push({ | |
| id: parseInt(vd[0]), | |
| quantity: parseInt(vd[1] || 1) * qty | |
| }); | |
| Logger.log(' Matched:', selection, '→ variant', vd[0]); | |
| found = true; | |
| } | |
| } | |
| } | |
| if (found) break; | |
| } | |
| } | |
| } | |
| if (found) break; | |
| } | |
| if (!found) { | |
| Logger.warn(' No match found for selection:', selection); | |
| } | |
| } | |
| Logger.log('Resolved IO Bundle:', resolved); | |
| return resolved.filter(function(item) { return item.id && item.quantity > 0; }); | |
| }, | |
| /** | |
| * Extract _bundle_selection from properties | |
| */ | |
| extractBundleSelection: function(properties) { | |
| if (!properties) return null; | |
| // Check for _bundle_selection property | |
| if (properties['_bundle_selection']) { | |
| return properties['_bundle_selection']; | |
| } | |
| // URL decode if needed | |
| if (properties['_bundle_selection']) { | |
| try { | |
| return decodeURIComponent(properties['_bundle_selection'].replace(/\+/g, ' ')); | |
| } catch (e) { | |
| return properties['_bundle_selection']; | |
| } | |
| } | |
| return null; | |
| } | |
| }; | |
| // ========================================= | |
| // CART API | |
| // ========================================= | |
| var _originalFetch = window.fetch.bind(window); | |
| var CartAPI = { | |
| addItems: function(items) { | |
| Logger.log('Adding items to cart:', items); | |
| return _originalFetch('/cart/add.js', { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| 'Accept': 'application/json' | |
| }, | |
| body: JSON.stringify({ items: items }) | |
| }).then(function(response) { | |
| if (!response.ok) { | |
| throw new Error('Cart add failed: ' + response.status); | |
| } | |
| return response.json(); | |
| }); | |
| }, | |
| getCart: function() { | |
| return _originalFetch('/cart.js').then(function(r) { return r.json(); }); | |
| }, | |
| triggerEvents: function(cart) { | |
| document.dispatchEvent(new CustomEvent('cart:updated', { detail: { cart: cart } })); | |
| document.dispatchEvent(new CustomEvent('cart:refresh')); | |
| document.dispatchEvent(new CustomEvent('ajaxProduct:added')); | |
| if (window.jQuery) { | |
| jQuery(document).trigger('cart.requestComplete', [cart]); | |
| jQuery(document).trigger('ajaxCart.afterCartLoad', [cart]); | |
| } | |
| } | |
| }; | |
| // ========================================= | |
| // INTERCEPTOR | |
| // ========================================= | |
| var Interceptor = { | |
| _initialized: false, | |
| _processing: new WeakSet(), | |
| init: function() { | |
| if (this._initialized) return; | |
| this._interceptFetch(); | |
| this._interceptForms(); | |
| this._initialized = true; | |
| Logger.log('Interceptor initialized'); | |
| }, | |
| _interceptFetch: function() { | |
| var self = this; | |
| window.fetch = function(url, options) { | |
| options = options || {}; | |
| var urlStr = String(url); | |
| var isCartAdd = urlStr.indexOf('/cart/add') !== -1 && | |
| options.method && | |
| options.method.toUpperCase() === 'POST'; | |
| if (!isCartAdd) { | |
| return _originalFetch(url, options); | |
| } | |
| Logger.log('Intercepted fetch to /cart/add'); | |
| return self._handleCartAdd(options.body).then(function(result) { | |
| if (result) { | |
| return result; | |
| } | |
| return _originalFetch(url, options); | |
| }).catch(function(err) { | |
| Logger.error('Fetch intercept error:', err); | |
| return _originalFetch(url, options); | |
| }); | |
| }; | |
| }, | |
| _handleCartAdd: function(body) { | |
| var self = this; | |
| var data; | |
| // Parse body | |
| if (body instanceof FormData) { | |
| data = {}; | |
| body.forEach(function(v, k) { data[k] = v; }); | |
| } else if (typeof body === 'string') { | |
| try { | |
| data = JSON.parse(body); | |
| } catch (e) { | |
| data = {}; | |
| var params = new URLSearchParams(body); | |
| params.forEach(function(v, k) { data[k] = v; }); | |
| } | |
| } else { | |
| return Promise.resolve(null); | |
| } | |
| Logger.log('Cart add data:', data); | |
| // Extract properties if they exist as separate keys | |
| var properties = data.properties || {}; | |
| // Check for properties in form data format: properties[key] = value | |
| Object.keys(data).forEach(function(key) { | |
| var match = key.match(/^properties\[(.+)\]$/); | |
| if (match) { | |
| properties[match[1]] = data[key]; | |
| } | |
| }); | |
| // Build items array | |
| var items; | |
| if (data.items && Array.isArray(data.items)) { | |
| items = data.items; | |
| } else if (data.id) { | |
| items = [{ | |
| id: data.id, | |
| quantity: data.quantity || 1, | |
| selling_plan: data.selling_plan, | |
| properties: properties | |
| }]; | |
| } else { | |
| return Promise.resolve(null); | |
| } | |
| Logger.log('Items to process:', items); | |
| Logger.log('Properties:', properties); | |
| // Process items | |
| var expandedItems = []; | |
| var hasBundle = false; | |
| for (var i = 0; i < items.length; i++) { | |
| var item = items[i]; | |
| var itemProperties = item.properties || properties; | |
| var metafields = MetafieldFetcher.fetch(item.id); | |
| var bundleType = BundleDetector.getBundleType(metafields); | |
| Logger.log('Processing item', item.id, '- Bundle type:', bundleType, '- Selling plan:', item.selling_plan); | |
| // Only expand bundles when a selling_plan is present (subscription) | |
| // Non-subscription bundles pass through to Simple Bundles normal flow | |
| if (BundleDetector.isBundle(metafields) && item.selling_plan) { | |
| hasBundle = true; | |
| var components = []; | |
| var qty = parseInt(item.quantity) || 1; | |
| if (bundleType === 'simple') { | |
| components = ComponentResolver.resolveSimpleBundle(metafields.simpleComponents, qty); | |
| } else if (bundleType === 'infinite_options') { | |
| var bundleSelection = ComponentResolver.extractBundleSelection(itemProperties); | |
| if (bundleSelection) { | |
| components = ComponentResolver.resolveIOBundle(metafields.ioSelections, bundleSelection, qty); | |
| } else { | |
| Logger.warn('No _bundle_selection found for IO bundle'); | |
| } | |
| } | |
| if (components.length > 0) { | |
| // Add selling_plan to each component | |
| for (var c = 0; c < components.length; c++) { | |
| if (item.selling_plan) { | |
| components[c].selling_plan = item.selling_plan; | |
| } | |
| } | |
| expandedItems = expandedItems.concat(components); | |
| Logger.log('Expanded into', components.length, 'components'); | |
| } else { | |
| Logger.warn('No components resolved, adding original item'); | |
| expandedItems.push(item); | |
| } | |
| } else { | |
| expandedItems.push(item); | |
| } | |
| } | |
| if (!hasBundle) { | |
| Logger.log('No bundles detected, using original fetch'); | |
| return Promise.resolve(null); | |
| } | |
| Logger.log('Adding expanded items:', expandedItems); | |
| return CartAPI.addItems(expandedItems).then(function(response) { | |
| return CartAPI.getCart().then(function(cart) { | |
| CartAPI.triggerEvents(cart); | |
| return new Response(JSON.stringify(response), { | |
| status: 200, | |
| headers: { 'Content-Type': 'application/json' } | |
| }); | |
| }); | |
| }); | |
| }, | |
| _interceptForms: function() { | |
| var self = this; | |
| document.addEventListener('submit', function(e) { | |
| var form = e.target; | |
| if (!form.matches || !form.matches(CONFIG.selectors.productForm)) return; | |
| if (self._processing.has(form)) return; | |
| var variantInput = form.querySelector(CONFIG.selectors.variantInput); | |
| if (!variantInput) return; | |
| var variantId = variantInput.value; | |
| var metafields = MetafieldFetcher.fetch(variantId); | |
| // Check for selling plan | |
| var spInput = form.querySelector(CONFIG.selectors.sellingPlanInput); | |
| var sellingPlan = spInput ? spInput.value : null; | |
| // Only expand bundles when a selling_plan is present (subscription) | |
| // Non-subscription bundles pass through to Simple Bundles normal flow | |
| if (!BundleDetector.isBundle(metafields) || !sellingPlan) { | |
| Logger.log('Form: Not a bundle or no selling plan - passing through'); | |
| return; | |
| } | |
| Logger.log('Form: Bundle with subscription detected'); | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| self._processing.add(form); | |
| self._handleFormSubmit(form, variantId, metafields).then(function() { | |
| self._processing.delete(form); | |
| }).catch(function(err) { | |
| Logger.error('Form error:', err); | |
| self._processing.delete(form); | |
| }); | |
| }, true); | |
| }, | |
| _handleFormSubmit: function(form, variantId, metafields) { | |
| var bundleType = BundleDetector.getBundleType(metafields); | |
| var qtyInput = form.querySelector(CONFIG.selectors.quantityInput); | |
| var qty = parseInt(qtyInput ? qtyInput.value : 1) || 1; | |
| var spInput = form.querySelector(CONFIG.selectors.sellingPlanInput); | |
| var sellingPlan = spInput ? spInput.value : null; | |
| Logger.log('Form submit - Type:', bundleType, 'Qty:', qty, 'Selling plan:', sellingPlan); | |
| var components = []; | |
| if (bundleType === 'simple') { | |
| components = ComponentResolver.resolveSimpleBundle(metafields.simpleComponents, qty); | |
| } else if (bundleType === 'infinite_options') { | |
| // Get _bundle_selection from form | |
| var bundleSelectionInput = form.querySelector('[name="properties[_bundle_selection]"]'); | |
| var bundleSelection = bundleSelectionInput ? bundleSelectionInput.value : null; | |
| if (bundleSelection) { | |
| components = ComponentResolver.resolveIOBundle(metafields.ioSelections, bundleSelection, qty); | |
| } else { | |
| Logger.warn('No _bundle_selection input found in form'); | |
| } | |
| } | |
| if (components.length === 0) { | |
| return Promise.reject(new Error('No components resolved')); | |
| } | |
| // Add selling plan to each component | |
| if (sellingPlan) { | |
| for (var i = 0; i < components.length; i++) { | |
| components[i].selling_plan = sellingPlan; | |
| } | |
| } | |
| Logger.log('Adding components:', components); | |
| return CartAPI.addItems(components).then(function() { | |
| return CartAPI.getCart(); | |
| }).then(function(cart) { | |
| CartAPI.triggerEvents(cart); | |
| // Redirect to cart | |
| window.location.href = '/cart'; | |
| }); | |
| } | |
| }; | |
| // ========================================= | |
| // DEBUG HELPERS | |
| // ========================================= | |
| window.SBExpanderDebug = { | |
| checkVariant: function(variantId) { | |
| var mf = MetafieldFetcher.fetch(variantId); | |
| console.log('=== Variant', variantId, '==='); | |
| console.log('Metafields:', mf); | |
| console.log('Is Bundle:', BundleDetector.isBundle(mf)); | |
| console.log('Bundle Type:', BundleDetector.getBundleType(mf)); | |
| if (mf.simpleComponents) { | |
| console.log('Simple Components:', ComponentResolver.resolveSimpleBundle(mf.simpleComponents, 1)); | |
| } | |
| if (mf.ioSelections) { | |
| console.log('IO Selections:', mf.ioSelections); | |
| } | |
| return mf; | |
| }, | |
| showLiquidData: function() { | |
| console.log('Liquid metafields:', window.__SB_VARIANT_METAFIELDS__); | |
| }, | |
| testIOMatch: function(variantId, bundleSelectionString) { | |
| var mf = MetafieldFetcher.fetch(variantId); | |
| if (!mf.ioSelections) { | |
| console.log('No IO selections for this variant'); | |
| return []; | |
| } | |
| var result = ComponentResolver.resolveIOBundle(mf.ioSelections, bundleSelectionString, 1); | |
| console.log('Would add:', result); | |
| return result; | |
| } | |
| }; | |
| // ========================================= | |
| // INIT | |
| // ========================================= | |
| if (document.readyState === 'loading') { | |
| document.addEventListener('DOMContentLoaded', function() { Interceptor.init(); }); | |
| } else { | |
| Interceptor.init(); | |
| } | |
| window.SimpleBundlesExpander = { | |
| CONFIG: CONFIG, | |
| Interceptor: Interceptor, | |
| MetafieldFetcher: MetafieldFetcher, | |
| BundleDetector: BundleDetector, | |
| ComponentResolver: ComponentResolver, | |
| CartAPI: CartAPI, | |
| Logger: Logger | |
| }; | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment