Create job for handling of closing order cycles

This commit is contained in:
Matt-Yorkley
2021-11-29 09:44:10 +00:00
committed by Sebastian Castro
parent 492325b74a
commit 887879f410
3 changed files with 61 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
# frozen_string_literal: true
class OrderCycleClosingJob < ActiveJob::Base
def perform
return if recently_closed_order_cycles.empty?
send_notifications
mark_as_processed
end
private
def recently_closed_order_cycles
@recently_closed_order_cycles ||= OrderCycle.closed.unprocessed.
where(
'order_cycles.orders_close_at BETWEEN (?) AND (?)', 1.hour.ago, Time.zone.now
).select(:id, :automatic_notifications).to_a
end
def send_notifications
recently_closed_order_cycles.each do |oc|
OrderCycleNotificationJob.perform_later(oc.id) if oc.automatic_notifications?
end
end
def mark_as_processed
OrderCycle.where(id: recently_closed_order_cycles).update_all(
processed_at: Time.zone.now,
updated_at: Time.zone.now
)
end
end

View File

@@ -14,3 +14,5 @@
every: "5m"
SubscriptionConfirmJob:
every: "5m"
OrderCycleClosingJob:
every: "5m"

View File

@@ -0,0 +1,27 @@
# frozen_string_literal: true
require 'spec_helper'
describe OrderCycleClosingJob do
let(:order_cycle1) {
create(:order_cycle, automatic_notifications: true, orders_close_at: Time.zone.now - 1.minute)
}
let(:order_cycle2) {
create(:order_cycle, automatic_notifications: true, orders_close_at: Time.zone.now + 1.minute)
}
let(:order_cycle3) {
create(:order_cycle, automatic_notifications: false, orders_close_at: Time.zone.now - 1.minute)
}
it "sends notifications for recently closed order cycles with automatic notifications enabled" do
expect(OrderCycleNotificationJob).to receive(:perform_later).with(order_cycle1.id)
expect(OrderCycleNotificationJob).to_not receive(:perform_later).with(order_cycle2.id)
expect(OrderCycleNotificationJob).to_not receive(:perform_later).with(order_cycle3.id)
OrderCycleClosingJob.perform_now
end
it "marks order cycles as processed" do
expect{ OrderCycleClosingJob.perform_now }.to change{ order_cycle1.reload.processed_at }
end
end