Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Storefront: open source remaining helpers
Damian Legawiec1473f7054978
diff --git a/storefront/app/helpers/spree/checkout_analytics_helper.rb b/storefront/app/helpers/spree/checkout_analytics_helper.rbnew file mode 100644index 0000000000..63203f374d--- /dev/null+++ b/storefront/app/helpers/spree/checkout_analytics_helper.rb@@ -0,0 +1,77 @@+module Spree+ module CheckoutAnalyticsHelper+ def coupon_tracking_params+ {+ order: @order,+ coupon_code: params[:coupon_code],+ coupon_handler: @result+ }+ end++ def clean_analytics_session+ session.delete(:checkout_started)+ session.delete(:checkout_step_viewed)+ session.delete(:checkout_step_completed)+ end++ def clear_checkout_completed_session+ session.delete(:checkout_completed)+ end++ def order_tracking_params+ tracking_params = {+ last_ip_address: request.remote_ip,+ }++ tracking_params[:ahoy_visit_id] = current_visit.id if @order.respond_to?(:ahoy_visit) && defined?(current_visit) && current_visit&.id+ tracking_params+ end++ def track_checkout_started+ # server-side tracking+ track_event('checkout_started', { order: @order })++ # client-side tracking+ session[:checkout_started] = true+ end++ def track_checkout_entered_email+ return unless @order.email.present?+ return unless params.dig(:order, :email).present?++ track_event('checkout_email_entered', { order: @order, email: @order.email })+ end++ def track_payment_info_entered+ return unless @order.payment_method.present?+ return unless params.dig(:order, :payments_attributes).present?++ track_event('payment_info_entered', { order: @order })+ end++ def track_checkout_step_viewed+ # server-side tracking+ track_event('checkout_step_viewed', { order: @order, step: params[:state] || @order.state })++ # client-side tracking+ trackable_checkout_steps = @order.checkout_steps[0..2]+ session[:checkout_step_viewed] = true if trackable_checkout_steps.include? @order.state+ end++ def track_checkout_step_completed+ # server-side tracking+ track_event('checkout_step_completed', { order: @order, step: @previous_state })++ # client-side tracking+ session[:checkout_step_completed] = @previous_state # for 3rd party frontend tracking+ end++ def track_checkout_completed+ # server-side tracking+ track_event('checkout_completed', { order: @order })++ # client-side tracking+ session[:checkout_completed] = true+ end+ end+enddiff --git a/storefront/app/helpers/spree/checkout_helper.rb b/storefront/app/helpers/spree/checkout_helper.rbnew file mode 100644index 0000000000..5ea7611aee--- /dev/null+++ b/storefront/app/helpers/spree/checkout_helper.rb@@ -0,0 +1,58 @@+module Spree+ module CheckoutHelper+ def checkout_progress(numbers: false)+ states = (@order.checkout_steps - ['complete']).unshift('cart')+ items = states.each_with_index.map do |state, i|+ text = Spree.t("order_state.#{state}").titleize+ text.prepend("#{i.succ}. ") if numbers++ css_classes = ['breadcrumb-item']+ current_index = states.index(@order.state)+ state_index = states.index(state)++ if state_index < current_index+ link_content = text+ if state == 'cart'+ link_url = spree.cart_url(host: current_store.url_or_custom_domain, order_token: @order.token)+ else+ link_url = spree.checkout_state_path(@order.token, state)+ end++ text = link_to(link_content, link_url)+ css_classes << 'text-primary'+ content_tag('li', text, class: css_classes.join(' '))+ else+ content_tag('li', text, class: "breadcrumb-item #{state == @order.state ? 'font-bold' : 'text-text'}")+ end+ end+ content = content_tag('ol', raw(items.join("\n")), class: 'breadcrumb flex items-center py-6 gap-2', id: "checkout-step-#{@order.state}")+ content+ end++ def checkout_available_payment_methods+ @checkout_available_payment_methods ||= @order.available_payment_methods+ end++ def checkout_started?+ @order.state == 'address' && @order.state_was == 'cart'+ end++ def already_have_an_account?+ @already_have_an_account ||= @order.email.present? && Spree.user_class.confirmed.exists?(email: @order.email.downcase)+ end++ def checkout_payment_sources(payment_method = nil)+ return [] unless try_spree_current_user.respond_to?(:payment_sources)++ payment_method.present? ? try_spree_current_user.payment_sources.where(payment_method: payment_method) : try_spree_current_user.payment_sources+ end++ def quick_checkout_enabled?(order)+ order.payment_required? && order.shipments.count <= 1+ end++ def can_use_store_credit_on_checkout?(order)+ order.could_use_store_credit? && !order.gift_card.present?+ end+ end+enddiff --git a/storefront/app/helpers/spree/filters_helper.rb b/storefront/app/helpers/spree/filters_helper.rbnew file mode 100644index 0000000000..ee1739dc07--- /dev/null+++ b/storefront/app/helpers/spree/filters_helper.rb@@ -0,0 +1,172 @@+module Spree+ module FiltersHelper+ def products_for_filters_default_scope+ scope = storefront_products_scope+ scope = scope.in_taxon(@taxon) if @taxon.present?+ scope = scope.search_by_name(params[:q].strip).unscope(:order) if params[:q].present?+ scope+ end++ def products_for_filters_scope(except_filters: [])+ products_finder = Spree::Dependencies.products_finder.constantize++ finder_params = default_products_finder_params+ finder_params[:filter] = finder_params[:filter].except(*except_filters) if except_filters.any?++ products = products_finder.new(scope: storefront_products_scope, params: finder_params).execute+ current_store.products.where(id: products.unscope(:order).ids)+ end++ def storefront_products_for_filters+ @storefront_products_for_filters ||= products_for_filters_scope+ end++ def default_storefront_products_for_filters+ @default_storefront_products_for_filters ||= products_for_filters_default_scope.unscope(:order)+ end++ def product_filters_aggregations+ @product_filters_aggregations ||= storefront_products_for_filters.+ joins(variants_including_master: :option_values).+ group("#{Spree::OptionValue.table_name}.id").+ distinct.+ count+ end++ def product_single_filter_aggregations+ @product_single_filter_aggregations ||= default_storefront_products_for_filters.+ joins(variants_including_master: :option_values).+ group("#{Spree::OptionValue.table_name}.id").+ distinct.+ count+ end++ def products_count_for_filter(name, value_id)+ aggregations = single_option_filter_selected?(name) ? product_single_filter_aggregations : product_filters_aggregations+ aggregations.fetch(value_id, 0)+ end++ def filter_price_range+ @filter_price_range ||= begin+ product_ids = products_for_filters_scope(except_filters: [:price]).ids++ {+ min: Spree::Price.for_products(product_ids).minimum(:amount) || 0.to_d,+ max: Spree::Price.for_products(product_ids).maximum(:amount) || 0.to_d+ }+ end+ end++ def filter_stock_count+ @filter_stock_count ||= begin+ products_scope = products_for_filters_scope(except_filters: [:purchasable, :out_of_stock])++ {+ in_stock: products_scope.in_stock.distinct.count,+ out_of_stock: products_scope.out_of_stock.distinct.count+ }+ end+ end++ def default_storefront_filter_values_scope+ Spree::OptionValue.for_products(products_for_filters_default_scope).distinct+ end++ def storefront_filter_values_scope(filter_selected)+ if filter_selected+ default_storefront_filter_values_scope+ else+ Spree::OptionValue.for_products(storefront_products_for_filters).distinct+ end+ end++ def filter_values_for_filter(filter)+ selected = single_option_filter_selected?(filter.name)+ filter.option_values.where(id: storefront_filter_values_scope(selected))+ end++ def storefront_products_for_taxon_filters+ @storefront_products_for_taxon_filters ||= products_for_filters_scope(except_filters: [:taxons])+ end++ def filter_taxon_ids+ @filter_taxon_ids ||= begin+ scope = storefront_products_for_taxon_filters.joins(:classifications)+ scope = scope.in_taxon(@taxon).unscope(:order) if @taxon.present?+ scope.distinct.pluck(:taxon_id)+ end+ end++ def filter_taxons_for_taxonomy(taxonomy)+ taxon_depth = @taxon.present? ? @taxon.depth + 1 : 1++ taxonomy.taxons.where(depth: taxon_depth).order(:lft).find_all do |taxon|+ (taxon.cached_self_and_descendants_ids & filter_taxon_ids).any?+ end+ end++ def product_taxon_aggregations+ @product_taxon_aggregations ||= current_store.taxons.+ joins(:classifications).+ where("#{Spree::Classification.table_name}.product_id" => storefront_products_for_taxon_filters.ids).+ group(+ "#{Spree::Taxon.table_name}.id",+ "#{Spree::Classification.table_name}.product_id"+ ).+ unscope(:order).+ count("#{Spree::Classification.table_name}.product_id")+ end++ def products_count_for_taxon(taxon)+ taxon_self_and_descendants_ids = taxon.cached_self_and_descendants_ids+ aggregations = product_taxon_aggregations.select { |key, _value| key[0].in?(taxon_self_and_descendants_ids) }++ # We want to count unique products across the taxon tree+ aggregations.uniq { |key, _value| key[1] }.sum(&:last)+ end++ def filter_form_fields+ return '' if products_filters_params.blank?++ map_filters_params_to_form_fields(products_filters_params)+ end++ def map_filters_params_to_form_fields(filters_params, prefix_key = nil)+ filters_params.to_h.map do |key, value|+ key = CGI.escapeHTML(key)+ key = [prefix_key, key].join('][') if prefix_key.present?++ if value.is_a?(Array)+ value.map do |v|+ v = CGI.escapeHTML(v)+ "<input type='hidden' name='filter[#{key}][]' value='#{v}' />"+ end.join+ elsif value.is_a?(Hash)+ map_filters_params_to_form_fields(value, key)+ else+ value = CGI.escapeHTML(value)+ "<input type='hidden' name='filter[#{key}]' value='#{value}' />"+ end+ end.join.html_safe+ end++ def single_option_filter_selected?(filter_name)+ options_filter = permitted_products_params.dig(:filter, :options) || {}++ !price_filtered? && !taxons_filtered? &&+ options_filter.keys.length == 1 && options_filter.key?(filter_name)+ end++ def price_filtered?+ min_price = permitted_products_params.dig(:filter, :min_price).presence+ max_price = permitted_products_params.dig(:filter, :max_price).presence++ (min_price.present? && min_price.to_d >= filter_price_range[:min]) ||+ (max_price.present? && max_price.to_d <= filter_price_range[:max])+ end++ def taxons_filtered?+ permitted_products_params.dig(:filter, :taxon_ids)&.any?+ end+ end+enddiff --git a/storefront/app/helpers/spree/orders_helper.rb b/storefront/app/helpers/spree/orders_helper.rbnew file mode 100644index 0000000000..6c5863dc03--- /dev/null+++ b/storefront/app/helpers/spree/orders_helper.rb@@ -0,0 +1,7 @@+module Spree+ module OrdersHelper+ def order_just_completed?+ @order.present? && @order.completed? && session[:checkout_completed].present?+ end+ end+enddiff --git a/storefront/app/helpers/spree/posts_helper.rb b/storefront/app/helpers/spree/posts_helper.rbnew file mode 100644index 0000000000..e126dc7561--- /dev/null+++ b/storefront/app/helpers/spree/posts_helper.rb@@ -0,0 +1,42 @@+module Spree+ module PostsHelper+ def posts_json_ld_breadcrumbs(post)+ json_ld = {+ '@context' => 'https://schema.org',+ '@type' => 'BreadcrumbList',+ 'itemListElement' => [+ {+ '@type' => 'ListItem',+ 'position' => 1,+ 'name' => Spree.t(:homepage),+ 'item' => spree.root_url(host: current_store.url_or_custom_domain)+ },+ {+ '@type' => 'ListItem',+ 'position' => 2,+ 'name' => Spree.t(:blog),+ 'item' => spree.posts_url(host: current_store.url_or_custom_domain)+ }+ ]+ }++ post_breadcrumb = { '@type' => 'ListItem', 'name' => post.title }+ post_category = post.post_category++ if post_category.present?+ json_ld['itemListElement'] << {+ '@type' => 'ListItem',+ 'position' => 3,+ 'name' => post_category.title,+ 'item' => spree.category_posts_url(category_id: post.post_category.slug, host: current_store.url_or_custom_domain)+ }++ json_ld['itemListElement'] << post_breadcrumb.merge('position' => 4)+ else+ json_ld['itemListElement'] << post_breadcrumb.merge('position' => 3)+ end++ json_ld+ end+ end+enddiff --git a/storefront/app/helpers/spree/products_helper.rb b/storefront/app/helpers/spree/products_helper.rbnew file mode 100644index 0000000000..8342bb2a0f--- /dev/null+++ b/storefront/app/helpers/spree/products_helper.rb@@ -0,0 +1,198 @@+module Spree+ module ProductsHelper+ include BaseHelper++ def product_cache_key(product)+ [+ current_theme,+ current_store,+ try_spree_current_user,+ current_currency,+ I18n.locale,+ product.cache_key_with_version,+ product.available?,+ product.discontinued?,+ ]+ end++ def should_display_compare_at_price?(product_or_variant)+ price = product_or_variant.price_in(current_currency)+ price.compare_at_amount.present? && (price.compare_at_amount > price.amount)+ end++ def weeks_online(product)+ (Time.current - product.activated_at.in_time_zone(current_store.preferred_timezone)).seconds.in_weeks.to_i.abs+ end++ def brand_name(product)+ product.brand&.name || product.vendor&.display_name+ end++ def product_not_selected_options(product, selected_variant, options_param_name: :options)+ product.option_types.map do |option_type|+ if product_selected_option_for_option(+ option_type,+ product: product,+ selected_variant: selected_variant,+ options_param_name: options_param_name+ ).present?+ next+ else+ option_type+ end+ end.compact_blank+ end++ def product_selected_option_for_option(option_type, product:, selected_variant: nil, options_param_name: :options)+ @memoized_values ||= {}+ memoized_key = "#{product.id}-#{selected_variant&.id}-#{option_type.id}-#{options_param_name}"++ product_selected_options_hash = if params[options_param_name].present?+ params[options_param_name].split(',').to_h do |option|+ key, *value = option.split(':')+ [key, value.join(':')]+ end+ else+ {}+ end++ @memoized_values[memoized_key] ||=+ if selected_variant.present?+ selected_variant.option_values.find { |ov| ov.option_type_id == option_type.id }+ elsif product_selected_options_hash.present? && product_selected_options_hash[option_type.id.to_s].present? # user selected variant which is not available+ option_type.option_values.find { |v| v.name == product_selected_options_hash[option_type.id.to_s] }+ elsif option_type.color? && (available_variant = product.first_available_variant(current_currency))+ available_variant.option_values.find { |ov| ov.option_type_id == option_type.id }+ elsif option_type.color? && product.first_available_variant(current_currency).nil?+ product.variants.first&.option_values&.find { |ov| ov.option_type_id == option_type.id }+ end+ end++ def product_option_values_for_option(option_type, product:)+ product.option_values.includes(:option_type).+ find_all { |option_value| option_value.option_type_id == option_type.id }.+ uniq { |ov| [ov.name, ov.option_type&.name] }+ end++ def product_media_gallery_images(product, selected_variant:, variant_from_options:, options_param_name: :options)+ images = selected_variant&.images&.to_a || []+ images ||= variant_from_options&.images&.to_a if images.empty?++ if images.compact.empty?+ first_option_type = product.option_types.first++ if first_option_type.present?+ variant_for_first_option = product_variant_for_selected_option(+ first_option_type, product: product, selected_variant: selected_variant, options_param_name: options_param_name+ )++ images << variant_for_first_option.images.to_a if variant_for_first_option.present?+ end+ end++ images << product.master&.images&.to_a+ images << product.default_image if images.flatten.compact.empty?++ images.flatten.compact.uniq(&:id)+ end++ def variant_featured_image(variant)+ return nil unless variant++ variant.images.first+ end++ def image_alt(image)+ @memoized_image_alts ||= {}+ key = image.id++ @memoized_image_alts[key] ||=+ image.alt.presence ||+ (image.viewable.descriptive_name if image.viewable_type == 'Spree::Variant') ||+ @product.name+ end++ def product_variant_for_selected_option(option_type, product:, selected_variant:, options_param_name: :options)+ selected_value_for_option = product_selected_option_for_option(+ option_type,+ product: product,+ selected_variant: selected_variant,+ options_param_name: options_param_name+ )+ return unless selected_value_for_option.present?++ product.variants.with_option_value(option_type.name, selected_value_for_option.name).first+ end++ def products_selected_filters_count+ params[:filters].present? ? params[:filters].split(',').count : 0+ end++ def products_sort+ @products_sort ||= permitted_products_params[:sort_by]&.strip_html_tags.presence || default_products_sort+ end++ def taxons_sort_options+ @taxons_sort_options ||= [+ { name: Spree.t('products_sort_options.relevance'), value: 'manual' },+ { name: Spree.t('products_sort_options.best_selling'), value: 'best-selling' },+ { name: Spree.t('products_sort_options.name_a_z'), value: 'name-a-z' },+ { name: Spree.t('products_sort_options.name_z_a'), value: 'name-z-a' },+ { name: Spree.t('products_sort_options.price_low_to_high'), value: 'price-low-to-high' },+ { name: Spree.t('products_sort_options.price_high_to_low'), value: 'price-high-to-low' },+ { name: Spree.t('products_sort_options.newest_first'), value: 'newest-first' },+ { name: Spree.t('products_sort_options.oldest_first'), value: 'oldest-first' }+ ]+ end++ def product_breadcrumb_taxons(product)+ return Spree::Taxon.none if product.taxons.empty?++ product.main_taxon.self_and_ancestors.where.not(depth: 0)+ end++ def product_list_json_ld_elements(product_slugs)+ product_slugs.each_with_index.map do |product_slug, index|+ {+ '@type' => 'ListItem',+ 'position' => index + 1,+ 'url' => spree.product_url(product_slug)+ }+ end+ end++ def product_json_ld_breadcrumbs(product)+ json_ld = {+ '@context' => 'https://schema.org',+ '@type' => 'BreadcrumbList',+ 'itemListElement' => [+ {+ '@type': 'ListItem',+ 'position' => 1,+ 'name' => 'Homepage',+ 'item' => spree.root_url(host: current_store.url_or_custom_domain)+ }+ ]+ }++ if product.main_taxon.present?+ product.main_taxon.self_and_ancestors.each_with_index do |taxon, index|+ json_ld['itemListElement'] << {+ '@type' => 'ListItem',+ 'position' => index + 2,+ 'name' => taxon.name,+ 'item' => spree.nested_taxons_url(taxon, host: current_store.url_or_custom_domain)+ }+ end+ end++ json_ld['itemListElement'] << {+ '@type' => 'ListItem',+ 'position' => json_ld['itemListElement'].length + 1,+ 'name' => product.name+ }++ json_ld+ end+ end+end