Files
openfoodnetwork/lib/tasks/data/remove_transient_data.rb
cyrillefr 659111932c Fixes Rails/RelativeDateConstant offense
- Cop: Rails/RelativeDateConstant
- raises offense if Constant is relative data (ie: since, ago)
- Reason: relative data will be evaluated only once
- BUT here, Date should not be evaluated in a class method, and have a different
- value for each call. But the data should be the same for an instance
- Therefore: move the ago in init method
- Cf. https://docs.rubocop.org/rubocop-rails/cops_rails.html#railsrelativedateconstant

- Since there is no constant to be called form a class, but a date from an instance, the
  spec has been modified accordingly. The RemoveTransientData.new.call had to be splitted.
2024-06-21 23:07:16 +02:00

50 lines
1.5 KiB
Ruby

# frozen_string_literal: true
class RemoveTransientData
RETENTION_PERIOD = 3.months
# This model lets us operate on the sessions DB table using ActiveRecord's
# methods within the scope of this service. This relies on the AR's
# convention where a Session model maps to a sessions table.
class Session < ApplicationRecord
end
attr_reader :expiration_date
def initialize
@expiration_date = RETENTION_PERIOD.ago.to_date
end
def call
Rails.logger.info("#{self.class.name}: processing")
Spree::StateChange.where("created_at < ?", @expiration_date).delete_all
Spree::LogEntry.where("created_at < ?", @expiration_date).delete_all
Session.where("updated_at < ?", @expiration_date).delete_all
clear_old_cart_data!
end
private
def clear_old_cart_data!
old_carts = Spree::Order.
where("spree_orders.state = 'cart' AND spree_orders.updated_at < ?", @expiration_date).
merge(orders_without_payments)
old_cart_line_items = Spree::LineItem.where(order_id: old_carts)
old_cart_adjustments = Spree::Adjustment.where(order_id: old_carts)
old_cart_adjustments.delete_all
old_cart_line_items.delete_all
old_carts.delete_all
end
def orders_without_payments
# Carts with failed payments are ignored, as they contain potentially useful data
Spree::Order.
joins("LEFT OUTER JOIN spree_payments ON spree_orders.id = spree_payments.order_id").
where(spree_payments: { id: nil })
end
end