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
New reports (#12363)
Damian Legawiec080cab898ac0
diff --git a/admin/app/controllers/spree/admin/reports_controller.rb b/admin/app/controllers/spree/admin/reports_controller.rbnew file mode 100644index 0000000000..5eb46e73e5--- /dev/null+++ b/admin/app/controllers/spree/admin/reports_controller.rb@@ -0,0 +1,54 @@+module Spree+ module Admin+ class ReportsController < ResourceController+ include ActiveStorage::SetCurrent++ respond_to :html, :csv++ before_action :set_user, only: [:new, :create]++ def show+ redirect_to @object.attachment.url, status: :see_other, allow_other_host: true+ end++ private++ def set_user+ @object.user = try_spree_current_user+ end++ def create_turbo_stream_enabled?+ true+ end++ def message_after_create+ Spree.t('admin.report_created')+ end++ def location_after_save+ spree.admin_reports_path+ end++ def build_resource+ model_class.new(store: current_store, date_from: params[:date_from], date_to: params[:date_to], currency: params[:currency])+ end++ def model_class+ @model_class = if params[:type].present?+ report_type = "Spree::Reports::#{params[:type].classify}"+ if allowed_report_types.include?(report_type)+ report_type.constantize+ else+ raise 'Unknown report type'+ end+ else+ Spree::Report+ end+ end++ def allowed_report_types+ Rails.application.config.spree.reports.map(&:to_s)+ end+ end+ end+enddiff --git a/admin/app/views/spree/admin/reports/_report.html.erb b/admin/app/views/spree/admin/reports/_report.html.erbnew file mode 100644index 0000000000..660c181948--- /dev/null+++ b/admin/app/views/spree/admin/reports/_report.html.erb@@ -0,0 +1,22 @@+<div class="card-lg p-0">+ <div class="table-responsive">+ <table class="table">+ <thead class="text-muted">+ <tr>+ <% @report.line_item_class.headers.each do |header| %>+ <th><%= header[:label] %></th>+ <% end %>+ </tr>+ </thead>+ <tbody>+ <% @report.line_items.each do |line_item| %>+ <tr>+ <% line_item.class.attribute_types.keys.each do |key| %>+ <td><%= line_item.send(key) %></td>+ <% end %>+ </tr>+ <% end %>+ </tbody>+ </table>+ </div>+</div>\ No newline at end of filediff --git a/admin/app/views/spree/admin/reports/create.turbo_stream.erb b/admin/app/views/spree/admin/reports/create.turbo_stream.erbnew file mode 100644index 0000000000..d9fb79328e--- /dev/null+++ b/admin/app/views/spree/admin/reports/create.turbo_stream.erb@@ -0,0 +1 @@+<%= turbo_render_alerts %>\ No newline at end of filediff --git a/admin/app/views/spree/admin/reports/index.html.erb b/admin/app/views/spree/admin/reports/index.html.erbnew file mode 100644index 0000000000..ecf2b453fe--- /dev/null+++ b/admin/app/views/spree/admin/reports/index.html.erb@@ -0,0 +1,28 @@+<% content_for :page_title do %>+ <%= Spree.t(:reports) %>+<% end %>++<div class="card">+ <div class="table-responsive">+ <table class="table">+ <thead>+ <tr>+ <th><%= Spree.t(:name) %></th>+ <th class="text-right"><%= Spree.t(:action) %></th>+ </tr>+ </thead>+ <tbody>+ <% Spree.t(:report_names).keys.each do |report_type| %>+ <tr data-controller="row-link">+ <td class="cursor-pointer w-90" data-action="click->row-link#openLink">+ <%= Spree.t("report_names.#{report_type}") %>+ </td>+ <td class="text-right w-10">+ <%= link_to Spree.t(:show_report), spree.new_admin_report_path(type: report_type), class: 'btn btn-primary btn-sm', data: { row_link_target: :link } %>+ </td>+ </tr>+ <% end %>+ </tbody>+ </table>+ </div>+</div>diff --git a/admin/app/views/spree/admin/reports/new.html.erb b/admin/app/views/spree/admin/reports/new.html.erbnew file mode 100644index 0000000000..7ea3a4f4d6--- /dev/null+++ b/admin/app/views/spree/admin/reports/new.html.erb@@ -0,0 +1,39 @@+<% content_for :page_title do %>+ <%= page_header_back_button spree.admin_reports_path %>+ <%= Spree.t("report_names.#{params[:type]}") %>+<% end %>++ <%= content_for :page_actions do %>+ <%= form_for @report, url: spree.admin_reports_path, as: :report, html: { class: 'd-inline-block' } do |f| %>+ <%= f.hidden_field :type %>+ <%= f.hidden_field :date_from %>+ <%= f.hidden_field :date_to %>+ <%= f.hidden_field :currency %>+ <button class="btn btn-light with-tip" title="Export report in a CSV format">+ <%= icon('table-export') %>+ <%= Spree.t(:export) %>+ </button>+ <% end %>+<% end %>++<div class="mb-2">+ <%= form_tag spree.new_admin_report_path, method: :get, data: { controller: 'auto-submit' } do %>+ <%= hidden_field_tag :type, params[:type] %>++ <div class="d-flex gap-2">+ <%= render 'spree/admin/shared/calendar_range_picker',+ date_from_value: @report.date_from,+ date_to_value: @report.date_to,+ css_classes: 'custom-select d-flex cursor-default' %>++ <div class="form-group">+ <%= select_tag :currency,+ options_for_select(current_store.supported_currencies_list, @report.currency),+ class: 'custom-select',+ data: { action: 'change->auto-submit#submit' } %>+ </div>+ </div>+ <% end %>+</div>++<%= render @report %>\ No newline at end of filediff --git a/admin/app/views/spree/admin/shared/_calendar_range_picker.html.erb b/admin/app/views/spree/admin/shared/_calendar_range_picker.html.erbindex 2d742a953f..c936302efb 100644--- a/admin/app/views/spree/admin/shared/_calendar_range_picker.html.erb+++ b/admin/app/views/spree/admin/shared/_calendar_range_picker.html.erb@@ -1,6 +1,6 @@<% date_from_input_name ||= :date_from %><% date_to_input_name ||= :date_to %>-<% css_classes ||= "btn btn-light d-inline-flex align-items-center h-100" %>+<% css_classes ||= "btn btn-light d-inline-flex align-items-center h-100 dropdown-toggle" %><% date_from_value ||= params[date_from_input_name] %><% date_to_value ||= params[date_to_input_name] %>@@ -10,15 +10,14 @@<div data-controller="calendar-range" class="dropdown h-100"data-action="click->calendar-range#open"><div class="<%= css_classes %>" data-toggle="dropdown">- <%= icon('calendar') %>+ <%= icon('calendar', class: 'mr-2') %><div data-calendar-range-target="label"><% if date_from_value.present? && date_to_value.present? %><%= date_from_value.to_date %> - <%= date_to_value.to_date %><% else %>- All time+ <%= Spree.t(:all_time) %><% end %></div>- <%= icon 'chevron-down', class: 'arrow mr-0 ml-2 text-muted' %></div><div class="dropdown-menu dropdown-menu-<%= dropdown_direction %> pb-0 pr-0 pl-1 pt-1" onclick="event.stopPropagation()"><div data-calendar-range-target="picker" class="d-none"></div>diff --git a/admin/config/locales/en.yml b/admin/config/locales/en.ymlindex f81c6cb15e..96a29a8f27 100644--- a/admin/config/locales/en.yml+++ b/admin/config/locales/en.yml@@ -72,6 +72,7 @@ en:product_kinds:physical: Physicaldigital: Digital+ report_created: Your report is being generated. You will receive an email with a download link when it is ready!tab:configuration: Configurationcontent: Contentdiff --git a/admin/config/routes.rb b/admin/config/routes.rbindex fe99eace86..e916f816b3 100644--- a/admin/config/routes.rb+++ b/admin/config/routes.rb@@ -99,7 +99,10 @@ Spree::Core::Engine.add_routes doresources :translations, only: [:edit, :update], path: '/translations/:resource_type'# audit log- resources :exports, only: %i[new create show index]+ resources :exports, only: [:index, :new, :create, :show]++ # reporting+ resources :reports, only: [:index, :new, :create, :show]# profile settingsresource :profile, controller: 'profile', only: %i[edit update]diff --git a/admin/spec/controllers/spree/admin/reports_controller_spec.rb b/admin/spec/controllers/spree/admin/reports_controller_spec.rbnew file mode 100644index 0000000000..1ec3f28910--- /dev/null+++ b/admin/spec/controllers/spree/admin/reports_controller_spec.rb@@ -0,0 +1,74 @@+require 'spec_helper'++describe Spree::Admin::ReportsController, type: :controller do+ stub_authorization!++ let(:store) { Spree::Store.default }++ describe '#index' do+ subject { get :index }++ it 'renders the index template' do+ expect(subject).to render_template(:index)+ end+ end++ describe '#new' do+ subject { get :new, params: { type: 'sales_total' } }++ it 'builds a new report' do+ subject+ expect(assigns(:object)).to be_a_new(Spree::Reports::SalesTotal)+ expect(assigns(:object).store).to eq(store)+ end++ it 'sets the current user' do+ subject+ expect(assigns(:object).user).to eq(controller.try_spree_current_user)+ end++ it 'renders the new template' do+ expect(subject).to render_template(:new)+ end++ context 'with invalid report type' do+ subject { get :new, params: { type: 'invalid_type' } }++ it 'raises an error' do+ expect { subject }.to raise_error('Unknown report type')+ end+ end+ end++ describe '#create' do+ let(:report_params) do+ {+ type: 'sales_total',+ date_from: 1.month.ago,+ date_to: Time.current,+ currency: 'USD'+ }+ end++ subject { post :create, params: { report: report_params } }++ it 'creates a new report' do+ expect { subject }.to change(Spree::Report, :count).by(1)+ end++ it 'sets the store' do+ subject+ expect(assigns(:object).store).to eq(store)+ end++ it 'sets the current user' do+ subject+ expect(assigns(:object).user).to eq(controller.try_spree_current_user)+ end++ it 'sets success flash message' do+ subject+ expect(flash[:success]).to eq Spree.t('admin.report_created')+ end+ end+enddiff --git a/core/app/jobs/spree/reports/generate_job.rb b/core/app/jobs/spree/reports/generate_job.rbnew file mode 100644index 0000000000..937a86edf8--- /dev/null+++ b/core/app/jobs/spree/reports/generate_job.rb@@ -0,0 +1,12 @@+module Spree+ module Reports+ class GenerateJob < Spree::BaseJob+ queue_as Spree.queues.reports++ def perform(report_id)+ report = Spree::Report.find(report_id)+ report.generate+ end+ end+ end+enddiff --git a/core/app/mailers/spree/report_mailer.rb b/core/app/mailers/spree/report_mailer.rbnew file mode 100644index 0000000000..0a8c116189--- /dev/null+++ b/core/app/mailers/spree/report_mailer.rb@@ -0,0 +1,20 @@+module Spree+ class ReportMailer < BaseMailer+ def report_done(report)+ @report = report++ mail(+ to: @report.user.email,+ subject: Spree.t('report_mailer.report_done.subject', report_name: @report.human_name).to_s,+ from: from_address,+ reply_to: reply_to_address+ )+ end++ private++ def current_store+ @current_store ||= @report.store+ end+ end+enddiff --git a/core/app/models/spree/line_item.rb b/core/app/models/spree/line_item.rbindex 00a1a122cd..c96fa039a1 100644--- a/core/app/models/spree/line_item.rb+++ b/core/app/models/spree/line_item.rb@@ -83,7 +83,7 @@ module Spreeextend DisplayMoneymoney_methods :amount, :subtotal, :discounted_amount, :final_amount, :total, :price,:adjustment_total, :additional_tax_total, :promo_total, :included_tax_total,- :pre_tax_amount+ :pre_tax_amount, :shipping_cost, :tax_totalalias single_money display_pricealias single_display_amount display_price@@ -157,7 +157,6 @@ module Spreeendend-def options=(options = {})return unless options.present?diff --git a/core/app/models/spree/report.rb b/core/app/models/spree/report.rbnew file mode 100644index 0000000000..4280ebdc27--- /dev/null+++ b/core/app/models/spree/report.rb@@ -0,0 +1,110 @@+module Spree+ class Report < Spree.base_class+ include Spree::SingleStoreResource+ include Spree::VendorConcern if defined?(Spree::VendorConcern)++ #+ # Associations+ #+ belongs_to :store, class_name: 'Spree::Store'+ belongs_to :user, class_name: Spree.admin_user_class.to_s, optional: true++ #+ # Callbacks+ #+ after_initialize :set_default_values+ after_commit :generate_async, on: :create++ #+ # Validations+ #+ validates :store, :date_from, :date_to, :currency, presence: true++ #+ # Attachments+ #+ has_one_attached :attachment, service: Spree.private_storage_service_name++ # Returns a scope of records to be used for generating report lines+ #+ # @return [ActiveRecord::Relation]+ def line_items_scope+ raise NotImplementedError, "Subclass #{self.class.name} must implement #line_items_scope"+ end++ # Returns an array of report lines+ #+ # @return [Array<Spree::ReportLineItem>]+ def line_items(options = {})+ scope = line_items_scope+ scope = scope.limit(options[:limit]) if options[:limit].present?++ scope.map { |record| line_item_class.new(record: record, report: self) }+ end++ def to_partial_path+ "spree/admin/reports/report"+ end++ def human_name+ [Spree.t("report_names.#{type.demodulize.underscore}"), store.name, date_from.strftime('%Y-%m-%d'), date_to.strftime('%Y-%m-%d')].join(' - ')+ end++ def generate_async+ Spree::Reports::GenerateJob.perform_later(id)+ end++ def generate+ generate_csv+ handle_attachment+ send_report_done_email+ end++ def generate_csv+ ::CSV.open(report_tmp_file_path, 'wb', encoding: 'UTF-8', col_sep: ',', row_sep: "\r\n") do |csv|+ csv << line_item_class.csv_headers+ line_items_scope.find_in_batches do |batch|+ batch.each do |record|+ csv << line_item_class.new(record: record, report: self).to_csv+ end+ end+ end+ end++ def handle_attachment+ file = ::File.open(report_tmp_file_path)+ attachment.attach(io: file, filename: attachment_file_name)+ ::File.delete(report_tmp_file_path) if ::File.exist?(report_tmp_file_path)+ end++ def send_report_done_email+ return unless user.present?++ Spree::ReportMailer.report_done(self).deliver_later+ end++ # eg. Spree::ReportLineItems::SalesTotal+ def line_item_class+ "Spree::ReportLineItems::#{type.demodulize}".safe_constantize+ end++ # eg. "store-sales-total-report-20250201120000.csv"+ def attachment_file_name+ @attachment_file_name ||= "#{store.code}-#{type.demodulize.parameterize}-report-#{created_at.strftime('%Y%m%d%H%M%S')}.csv"+ end++ private++ def report_tmp_file_path+ Rails.root.join('tmp', attachment_file_name)+ end++ def set_default_values+ return if store.blank?++ self.currency ||= store.default_currency+ self.date_from ||= 1.month.ago.in_time_zone(store.preferred_timezone).beginning_of_day+ self.date_to ||= Time.current.in_time_zone(store.preferred_timezone).end_of_day+ end+ end+enddiff --git a/core/app/models/spree/report_line_item.rb b/core/app/models/spree/report_line_item.rbnew file mode 100644index 0000000000..46eea83e82--- /dev/null+++ b/core/app/models/spree/report_line_item.rb@@ -0,0 +1,27 @@+module Spree+ class ReportLineItem+ include ActiveModel::Model+ include ActiveModel::Attributes++ attr_accessor :record, :report++ delegate :store, :currency, to: :report+ delegate :id, to: :record, prefix: true++ def self.headers+ attribute_types.keys.map do |attribute|+ { name: attribute.to_sym, label: Spree.t(attribute.to_sym) }+ end+ end++ def self.csv_headers+ attribute_types.keys+ end++ def to_csv+ self.class.attribute_types.keys.map do |attribute|+ send(attribute)+ end+ end+ end+enddiff --git a/core/app/models/spree/report_line_items/products_performance.rb b/core/app/models/spree/report_line_items/products_performance.rbnew file mode 100644index 0000000000..7185d37fec--- /dev/null+++ b/core/app/models/spree/report_line_items/products_performance.rb@@ -0,0 +1,74 @@+module Spree+ module ReportLineItems+ class ProductsPerformance < Spree::ReportLineItem+ attribute :sku, :string+ attribute :name, :string+ attribute :vendor, :string+ attribute :brand, :string+ attribute :category_lvl0, :string+ attribute :category_lvl1, :string+ attribute :category_lvl2, :string+ attribute :price, :string+ attribute :weeks_online, :integer+ attribute :pre_tax_amount, :string+ attribute :tax_total, :string+ attribute :quantity, :integer+ attribute :promo_total, :string+ attribute :total, :string++ delegate :sku, :name, to: :record++ def vendor+ record.vendor_name+ end++ def brand+ record.brand_name+ end++ def category_lvl0+ mapped_categories[0]+ end++ def category_lvl1+ mapped_categories[1]+ end++ def category_lvl2+ mapped_categories[2]+ end++ def price+ record.price_in(currency).display_amount+ end++ def pre_tax_amount+ Spree::Money.new(record.pre_tax_amount, currency: currency)+ end++ def promo_total+ Spree::Money.new(record.promo_total, currency: currency)+ end++ def tax_total+ Spree::Money.new(record.tax_total, currency: currency)+ end++ def quantity+ record.quantity+ end++ def total+ Spree::Money.new(record.total, currency: currency)+ end++ def weeks_online+ (Time.current - record.activated_at.in_time_zone(store.preferred_timezone)).seconds.in_weeks.to_i+ end++ def mapped_categories+ @mapped_categories ||= record.main_taxon&.pretty_name&.split('->')&.map(&:strip)+ end+ end+ end+enddiff --git a/core/app/models/spree/report_line_items/sales_total.rb b/core/app/models/spree/report_line_items/sales_total.rbnew file mode 100644index 0000000000..829e665a8c--- /dev/null+++ b/core/app/models/spree/report_line_items/sales_total.rb@@ -0,0 +1,46 @@+module Spree+ module ReportLineItems+ class SalesTotal < Spree::ReportLineItem+ attribute :date, :string+ attribute :order, :string+ attribute :product, :string+ attribute :pre_tax_amount, :decimal+ attribute :promo_total, :decimal+ attribute :shipment_total, :decimal+ attribute :tax_total, :decimal+ attribute :total, :decimal++ def date+ record.order.completed_at.strftime('%Y-%m-%d')+ end++ def order+ record.order.number+ end++ def product+ record.variant.descriptive_name+ end++ def total+ Spree::Money.new(record.final_amount + record.shipping_cost, currency: record.currency)+ end++ def promo_total+ record.display_promo_total+ end++ def pre_tax_amount+ record.display_pre_tax_amount+ end++ def shipment_total+ record.display_shipping_cost+ end++ def tax_total+ record.display_tax_total+ end+ end+ end+enddiff --git a/core/app/models/spree/reports/products_performance.rb b/core/app/models/spree/reports/products_performance.rbnew file mode 100644index 0000000000..e6636e8189--- /dev/null+++ b/core/app/models/spree/reports/products_performance.rb@@ -0,0 +1,44 @@+module Spree+ module Reports+ class ProductsPerformance < Spree::Report+ def line_items_scope+ line_items_scope = Spree::LineItem.+ select("+ #{Spree::LineItem.table_name}.quantity as quantity,+ #{Spree::LineItem.table_name}.pre_tax_amount as pre_tax_amount,+ #{Spree::LineItem.table_name}.promo_total as promo_total,+ #{Spree::LineItem.table_name}.included_tax_total + #{Spree::LineItem.table_name}.additional_tax_total AS tax_total,+ #{Spree::LineItem.table_name}.pre_tax_amount + #{Spree::LineItem.table_name}.adjustment_total AS total,+ #{Spree::Variant.table_name}.product_id AS product_id+ ").+ joins(:variant, :order).+ where(+ spree_line_items: {+ currency: currency+ },+ spree_orders: {+ completed_at: (date_from.to_time.beginning_of_day)..(date_to.to_time.end_of_day)+ }+ )++ return Spree::Product.none if line_items_scope.empty?++ line_items_sql = line_items_scope.to_sql++ product_scope = store.products+ product_scope = product_scope.where(vendor_id: vendor.id) if defined?(vendor) && vendor.present?++ product_scope.includes(:taxons, :tax_category, variants: :prices, master: :prices).+ joins("LEFT JOIN (#{line_items_sql}) AS line_items ON #{Spree::Product.table_name}.id = line_items.product_id").+ select("+ spree_products.*,+ COALESCE(SUM(line_items.pre_tax_amount), 0.0) AS pre_tax_amount,+ COALESCE(SUM(line_items.quantity), 0) AS quantity,+ COALESCE(SUM(line_items.promo_total), 0.0) AS promo_total,+ COALESCE(SUM(line_items.tax_total), 0.0) AS tax_total,+ COALESCE(SUM(line_items.total), 0.0) AS total+ ").group('spree_products.id')+ end+ end+ end+enddiff --git a/core/app/models/spree/reports/sales_total.rb b/core/app/models/spree/reports/sales_total.rbnew file mode 100644index 0000000000..3c0349c527--- /dev/null+++ b/core/app/models/spree/reports/sales_total.rb@@ -0,0 +1,14 @@+module Spree+ module Reports+ class SalesTotal < Spree::Report+ def line_items_scope+ store.line_items.where(+ order: Spree::Order.complete.where(+ currency: currency,+ completed_at: (date_from.to_time.beginning_of_day)..(date_to.to_time.end_of_day)+ )+ ).includes(:order, variant: :product)+ end+ end+ end+enddiff --git a/core/app/models/spree/store.rb b/core/app/models/spree/store.rbindex acf388130d..f43b50a1b5 100644--- a/core/app/models/spree/store.rb+++ b/core/app/models/spree/store.rb@@ -93,6 +93,9 @@ module Spreebelongs_to :default_country, class_name: 'Spree::Country'belongs_to :checkout_zone, class_name: 'Spree::Zone'+ has_many :reports, class_name: 'Spree::Report'+ has_many :exports, class_name: 'Spree::Export'+has_many :custom_domains, class_name: 'Spree::CustomDomain', dependent: :destroyhas_one :default_custom_domain, -> { where(default: true) }, class_name: 'Spree::CustomDomain'diff --git a/core/app/views/spree/report_mailer/report_done.html.erb b/core/app/views/spree/report_mailer/report_done.html.erbnew file mode 100644index 0000000000..4cb2b9f462--- /dev/null+++ b/core/app/views/spree/report_mailer/report_done.html.erb@@ -0,0 +1,15 @@+<h1>+ <%= Spree.t('report_mailer.greeting', user_name: @report.user&.first_name) %>+</h1>+<p>+ <%= Spree.t('report_mailer.report_done.message') %>+</p>+<% if spree.respond_to?(:admin_report_url) %>+ <p>+ <%= link_to @report.attachment.filename, spree.admin_report_url(@report, host: @current_store.formatted_url) %>+ </p>+<% end %>+<p>+ <%= Spree.t('report_mailer.thanks') %><br />+ <%= "#{current_store.name}" %>+</p>diff --git a/core/config/locales/en.yml b/core/config/locales/en.ymlindex 427254a02e..357e1f9cdd 100644--- a/core/config/locales/en.yml+++ b/core/config/locales/en.yml@@ -1445,6 +1445,15 @@ en:provider: Providerprovider_settings_warning: If you are changing the provider type, you must save first before you can edit the provider settingspurchased_quantity: Purchased Quantity+ report_mailer:+ greeting: Hi %{user_name},+ thanks: Thank you,+ report_done:+ subject: 'Your report %{report_name} is ready'+ message: Please use the link below to download it.+ report_names:+ products_performance: Products performance+ sales_total: Sales totalqty: Qtyquantity: Quantityquantity_returned: Quantity Returneddiff --git a/core/db/migrate/20250204162453_create_spree_reports.rb b/core/db/migrate/20250204162453_create_spree_reports.rbnew file mode 100644index 0000000000..d8f2bc5cc7--- /dev/null+++ b/core/db/migrate/20250204162453_create_spree_reports.rb@@ -0,0 +1,13 @@+class CreateSpreeReports < ActiveRecord::Migration[6.1]+ def change+ create_table :spree_reports do |t|+ t.references :store, null: false+ t.references :user+ t.string 'type'+ t.string 'currency'+ t.datetime 'date_from'+ t.datetime 'date_to'+ t.timestamps+ end+ end+enddiff --git a/core/lib/spree/core.rb b/core/lib/spree/core.rbindex eaf4e36d86..7fbe413692 100644--- a/core/lib/spree/core.rb+++ b/core/lib/spree/core.rb@@ -96,6 +96,7 @@ module Spree@@queues ||= OpenStruct.new(default: :default,exports: :default,+ reports: :default,variants: :default,taxons: :default,stock_location_stock_items: :default,diff --git a/core/lib/spree/core/engine.rb b/core/lib/spree/core/engine.rbindex ec98e04273..b16d91293d 100644--- a/core/lib/spree/core/engine.rb+++ b/core/lib/spree/core/engine.rb@@ -225,7 +225,10 @@ module SpreeSpree::PageBlocks::Products::BuyButtons]- Rails.application.config.spree.reports = []+ Rails.application.config.spree.reports = [+ Spree::Reports::ProductsPerformance,+ Spree::Reports::SalesTotal+ ]endinitializer 'spree.promo.register.promotions.actions' do |app|diff --git a/core/lib/spree/testing_support/factories/report_factory.rb b/core/lib/spree/testing_support/factories/report_factory.rbnew file mode 100644index 0000000000..2bc455abe2--- /dev/null+++ b/core/lib/spree/testing_support/factories/report_factory.rb@@ -0,0 +1,33 @@+# == Schema Information+#+# Table name: spree_reports+#+# id :bigint not null, primary key+# type :string+# currency :string+# date_from :datetime+# date_to :datetime+# created_at :datetime not null+# updated_at :datetime not null+# store_id :bigint not null+# user_id :bigint+#+FactoryBot.define do+ factory :report, class: 'Spree::Reports::SalesTotal' do+ store { create(:store) }+ user { create(:admin_user) }+ type { 'Spree::Reports::SalesTotal' }+ currency { 'USD' }+ date_from { 1.month.ago }+ date_to { Time.current }+ end++ factory :products_performance_report, class: 'Spree::Reports::ProductsPerformance' do+ store { create(:store) }+ user { create(:admin_user) }+ type { 'Spree::Reports::ProductsPerformance' }+ currency { 'USD' }+ date_from { 1.month.ago }+ date_to { Time.current }+ end+enddiff --git a/core/spec/mailers/spree/report_mailer_spec.rb b/core/spec/mailers/spree/report_mailer_spec.rbnew file mode 100644index 0000000000..b485aeef70--- /dev/null+++ b/core/spec/mailers/spree/report_mailer_spec.rb@@ -0,0 +1,38 @@+require 'spec_helper'++RSpec.describe Spree::ReportMailer, type: :mailer do+ let(:store) { Spree::Store.default }+ let(:user) { create(:admin_user) }+ let(:report) { create(:report, store: store, user: user) }+ let(:spree) { Spree::Core::Engine.routes.url_helpers }++ describe '#report_done' do+ subject(:mail) { described_class.report_done(report) }++ before do+ allow(spree).to receive(:admin_report_url).and_return("http://test.com/admin/reports/#{report.id}")+ end++ it 'renders the subject' do+ expect(mail.subject).to eq(+ Spree.t('report_mailer.report_done.subject', report_name: report.human_name)+ )+ end++ it 'sends to the correct recipient' do+ expect(mail.to).to eq([user.email])+ end++ it 'sends from the store mail from address' do+ expect(mail.from).to eq([store.mail_from_address])+ end++ it 'sets reply-to as the store mail from address' do+ expect(mail.reply_to).to eq([store.mail_from_address])+ end++ it 'includes download link in the body' do+ expect(mail.body.encoded).to include("/admin/reports/#{report.id}")+ end+ end+enddiff --git a/core/spec/models/spree/report_line_item_spec.rb b/core/spec/models/spree/report_line_item_spec.rbnew file mode 100644index 0000000000..458635c531--- /dev/null+++ b/core/spec/models/spree/report_line_item_spec.rb@@ -0,0 +1,35 @@+require 'spec_helper'++RSpec.describe Spree::ReportLineItem do+ let(:store) { Spree::Store.default }+ let(:order) { create(:order, store: store) }+ let(:report) { create(:report, store: store, currency: 'USD') }+ let(:report_line_item) { described_class.new(report: report, record: order) }++ describe '.headers' do+ it 'returns array of hashes with name and label' do+ allow(described_class).to receive(:attribute_types).and_return({ 'foo' => nil })+ allow(Spree).to receive(:t).with(:foo).and_return('Foo Label')++ expect(described_class.headers).to eq([{name: :foo, label: 'Foo Label'}])+ end+ end++ describe '.csv_headers' do+ it 'returns array of attribute keys' do+ allow(described_class).to receive(:attribute_types).and_return({ 'foo' => nil, 'bar' => nil })+ expect(described_class.csv_headers).to eq(['foo', 'bar'])+ end+ end++ describe '#to_csv' do+ it 'returns array of attribute values' do+ allow(described_class).to receive(:attribute_types).and_return({ 'foo' => nil, 'bar' => nil })+ report_line_item = described_class.new+ allow(report_line_item).to receive(:foo).and_return('foo_value')+ allow(report_line_item).to receive(:bar).and_return('bar_value')++ expect(report_line_item.to_csv).to eq(['foo_value', 'bar_value'])+ end+ end+enddiff --git a/core/spec/models/spree/report_line_items/sales_total_spec.rb b/core/spec/models/spree/report_line_items/sales_total_spec.rbnew file mode 100644index 0000000000..c7520dab6b--- /dev/null+++ b/core/spec/models/spree/report_line_items/sales_total_spec.rb@@ -0,0 +1,56 @@+require 'spec_helper'++RSpec.describe Spree::ReportLineItems::SalesTotal do+ let(:order) { create(:completed_order_with_totals) }+ let(:line_item) { order.line_items.first }+ let(:sales_total) { described_class.new(record: line_item) }++ describe '#date' do+ it 'returns formatted completed_at date' do+ expect(sales_total.date).to eq(order.completed_at.strftime('%Y-%m-%d'))+ end+ end++ describe '#order' do+ it 'returns order number' do+ expect(sales_total.order).to eq(order.number)+ end+ end++ describe '#product' do+ it 'returns variant descriptive name' do+ expect(sales_total.product).to eq(line_item.variant.descriptive_name)+ end+ end++ describe '#total' do+ it 'returns money object with final amount plus shipping' do+ total = Spree::Money.new(line_item.final_amount + line_item.shipping_cost, currency: line_item.currency)+ expect(sales_total.total).to eq(total)+ end+ end++ describe '#promo_total' do+ it 'returns display promo total' do+ expect(sales_total.promo_total).to eq(line_item.display_promo_total)+ end+ end++ describe '#pre_tax_amount' do+ it 'returns display pre tax amount' do+ expect(sales_total.pre_tax_amount).to eq(line_item.display_pre_tax_amount)+ end+ end++ describe '#shipment_total' do+ it 'returns display shipping cost' do+ expect(sales_total.shipment_total).to eq(line_item.display_shipping_cost)+ end+ end++ describe '#tax_total' do+ it 'returns display tax total' do+ expect(sales_total.tax_total).to eq(line_item.display_tax_total)+ end+ end+enddiff --git a/core/spec/models/spree/report_spec.rb b/core/spec/models/spree/report_spec.rbnew file mode 100644index 0000000000..e09c79b5d9--- /dev/null+++ b/core/spec/models/spree/report_spec.rb@@ -0,0 +1,71 @@+require 'spec_helper'++RSpec.describe Spree::Report, type: :model do+ let(:store) { Spree::Store.default }+ let(:user) { create(:admin_user) }+ let(:report) { build(:report, store: store, user: user) }++ describe '#human_name' do+ before { report.save! }++ it 'returns formatted name with store, dates and report type' do+ expected_name = [+ "Sales total",+ store.name,+ report.date_from.strftime('%Y-%m-%d'),+ report.date_to.strftime('%Y-%m-%d')+ ].join(' - ')++ expect(report.human_name).to eq(expected_name)+ end+ end++ describe '#generate' do+ before { report.save! }++ it 'generates CSV file and attaches it' do+ expect { report.generate }.to change(report.attachment, :attached?).from(false).to(true)+ end++ it 'sends report done email when user is present' do+ expect { report.generate }.to have_enqueued_job(ActionMailer::MailDeliveryJob)+ end++ context 'when user is not present' do+ let(:report) { build(:report, store: store, user: nil) }++ it 'does not send report done email' do+ expect { report.generate }.not_to have_enqueued_job(ActionMailer::MailDeliveryJob)+ end+ end+ end++ describe '#attachment_file_name' do+ before { report.save! }++ it 'returns the correct file name format' do+ expect(report.attachment_file_name).to match(/#{store.code}-salestotal-report-\d{14}\.csv/)+ end+ end++ describe 'callbacks' do+ describe 'after_commit on create' do+ it 'enqueues generate job' do+ expect { report.save! }.to have_enqueued_job(Spree::Reports::GenerateJob).with(report.id)+ end+ end++ describe 'after_initialize' do+ let(:new_report) { Spree::Report.new(store: store) }++ it 'sets default currency from store' do+ expect(new_report.currency).to eq(store.default_currency)+ end++ it 'sets default date range' do+ expect(new_report.date_from).to be_within(1.day).of(1.month.ago)+ expect(new_report.date_to).to be_within(1.day).of(Time.current)+ end+ end+ end+enddiff --git a/core/spec/models/spree/reports/products_performance_spec.rb b/core/spec/models/spree/reports/products_performance_spec.rbnew file mode 100644index 0000000000..5df76529e9--- /dev/null+++ b/core/spec/models/spree/reports/products_performance_spec.rb@@ -0,0 +1,49 @@+require 'spec_helper'++RSpec.describe Spree::Reports::ProductsPerformance do+ let(:store) { Spree::Store.default }+ let(:report) { create(:products_performance_report, store: store) }+ let(:product) { create(:product, stores: [store]) }+ let(:variant) { create(:variant, product: product) }+ let(:order) { create(:completed_order_with_totals, store: store, currency: report.currency) }+ let(:line_item) { create(:line_item, order: order, variant: variant) }++ describe '#line_items_scope' do+ context 'when order is within date range' do+ before do+ order.update(completed_at: report.date_from + 1.day)+ line_item.save!+ end++ it 'includes products with sales data' do+ result = report.line_items_scope.first++ expect(result.pre_tax_amount.to_f).to eq(line_item.pre_tax_amount)+ expect(result.quantity).to eq(line_item.quantity)+ expect(result.promo_total.to_f).to eq(line_item.promo_total)+ expect(result.tax_total.to_f).to eq(line_item.included_tax_total + line_item.additional_tax_total)+ expect(result.total.to_f).to eq(line_item.pre_tax_amount + line_item.adjustment_total)+ end+ end++ context 'when order is outside date range' do+ before do+ order.update(completed_at: report.date_from - 1.day)+ end++ it 'excludes products from orders outside date range' do+ expect(report.line_items_scope).to be_empty+ end+ end++ context 'when order has different currency' do+ before do+ order.update(currency: 'EUR')+ end++ it 'excludes products with different currency' do+ expect(report.line_items_scope).to be_empty+ end+ end+ end+enddiff --git a/core/spec/models/spree/reports/sales_total_spec.rb b/core/spec/models/spree/reports/sales_total_spec.rbnew file mode 100644index 0000000000..2d57cb1354--- /dev/null+++ b/core/spec/models/spree/reports/sales_total_spec.rb@@ -0,0 +1,66 @@+require 'spec_helper'++RSpec.describe Spree::Reports::SalesTotal do+ let(:store) { Spree::Store.default }+ let(:report) { create(:report, store: store) }+ let(:order) { create(:completed_order_with_totals, store: store, currency: report.currency) }+ let!(:line_item) { order.line_items.first }++ describe '#line_items_scope' do+ context 'when order is within date range' do+ before do+ order.update(completed_at: report.date_from + 1.day)+ end++ it 'includes line items from completed orders within date range' do+ expect(report.line_items_scope).to include(line_item)+ end+ end++ context 'when order is outside date range' do+ before do+ order.update(completed_at: report.date_from - 1.day)+ end++ it 'excludes line items from orders outside date range' do+ expect(report.line_items_scope).not_to include(line_item)+ end+ end++ context 'when order has different currency' do+ before do+ order.update(currency: 'EUR')+ end++ it 'excludes line items with different currency' do+ expect(report.line_items_scope).not_to include(line_item)+ end+ end++ context 'when order is incomplete' do+ before do+ order.update(completed_at: nil)+ end++ it 'excludes line items from incomplete orders' do+ expect(report.line_items_scope).not_to include(line_item)+ end+ end+ end++ describe '#return_line_items' do+ let(:return_line_item) { report.line_items.first }++ it 'returns line items' do+ expect(return_line_item).to be_a(Spree::ReportLineItems::SalesTotal)++ expect(return_line_item.date).to eq(order.completed_at.strftime('%Y-%m-%d'))+ expect(return_line_item.order).to eq(order.number)+ expect(return_line_item.product).to eq(line_item.variant.descriptive_name)+ expect(return_line_item.tax_total).to eq(line_item.display_tax_total)+ expect(return_line_item.promo_total).to eq(line_item.display_promo_total)+ expect(return_line_item.pre_tax_amount).to eq(line_item.display_pre_tax_amount)+ expect(return_line_item.shipment_total).to eq(line_item.display_shipping_cost)+ end+ end+end