Skip to content

Commit

Permalink
convert date range filter to client's timezone before filtering orders
Browse files Browse the repository at this point in the history
  • Loading branch information
abdellani committed Oct 3, 2023
1 parent b122c93 commit 7ebaa5c
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
4 changes: 4 additions & 0 deletions app/views/admin/reports/_date_range_form.html.haml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@
%span.range-divider
%i.icon-arrow-right
= f.text_field "#{field}_lt", :class => 'datetimepicker datepicker-to', :placeholder => t(:stop), data: { controller: "flatpickr", "flatpickr-enable-time-value": true, "flatpickr-default-date-value": "endOfDay" }
= hidden_field_tag "time_zone"
:javascript
document.querySelector("input[name='time_zone']").value = Intl.DateTimeFormat().resolvedOptions().timeZone

16 changes: 16 additions & 0 deletions lib/reporting/reports/customers/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ def filter_to_completed_at(orders)

return orders if min.blank? || max.blank?

if client_time_zone.present?
min = convert_to_client_time_zone(min)
max = convert_to_client_time_zone(max)
end
orders.where(completed_at: [min..max])
end

Expand All @@ -81,6 +85,18 @@ def last_completed_order(orders)
def last_completed_order_date(orders)
last_completed_order(orders).completed_at&.to_date
end

def convert_to_client_time_zone(datetime)
DateTime.parse(datetime).change(offset: utc_offset)
end

def client_time_zone
ActiveSupport::TimeZone[params[:time_zone] || ""]
end

def utc_offset
ActiveSupport::TimeZone[client_time_zone].formatted_offset
end
end
end
end
Expand Down
23 changes: 23 additions & 0 deletions spec/lib/reports/customers_report_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,29 @@ module Customers
allow(subject).to receive(:params).and_return(order_cycle_id: oc1.id)
expect(subject.filter(orders)).to eq([order1])
end

it "filters by date range using client's time zone" do
time_zone = ActiveSupport::TimeZone["Berlin"].formatted_offset
completed_at1 = DateTime.parse("2023/10/03 18:30")
completed_at2 = DateTime.parse("2023/10/03 19:30")

completed_at1 = completed_at1.change(offset: time_zone)
completed_at2 = completed_at2.change(offset: time_zone)

o1 = create(:order, completed_at: completed_at1)
o2 = create(:order, completed_at: completed_at2)

allow(subject).to receive(:params).and_return(
{
q: {
completed_at_gt: "2023/10/03 18:00",
completed_at_lt: "2023/10/03 19:00"
},
time_zone: "Berlin"
}
)
expect(subject.filter(orders)).to eq([o1])
end
end
end
end
Expand Down

0 comments on commit 7ebaa5c

Please sign in to comment.