1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-01-30 19:52:20 +01:00

(quality) replace DateTime by Time

This commit is contained in:
Sylvain 2023-02-17 11:44:04 +01:00
parent 17aff339b2
commit 142eceb661
26 changed files with 125 additions and 135 deletions

View File

@ -15,7 +15,7 @@ class API::SubscriptionsController < API::ApiController
def cancel def cancel
authorize @subscription authorize @subscription
if @subscription.expire(DateTime.current) if @subscription.expire(Time.current)
render :show, status: :ok, location: @subscription render :show, status: :ok, location: @subscription
else else
render json: { error: 'already expired' }, status: :unprocessable_entity render json: { error: 'already expired' }, status: :unprocessable_entity

View File

@ -16,8 +16,8 @@ class OpenAPI::V1::AccountingController < OpenAPI::V1::BaseController
@lines = AccountingLine.order(date: :desc) @lines = AccountingLine.order(date: :desc)
.includes(:invoicing_profile, invoice: :payment_gateway_object) .includes(:invoicing_profile, invoice: :payment_gateway_object)
@lines = @lines.where('date >= ?', DateTime.parse(params[:after])) if params[:after].present? @lines = @lines.where('date >= ?', Time.zone.parse(params[:after])) if params[:after].present?
@lines = @lines.where('date <= ?', DateTime.parse(params[:before])) if params[:before].present? @lines = @lines.where('date <= ?', Time.zone.parse(params[:before])) if params[:before].present?
@lines = @lines.where(invoice_id: may_array(params[:invoice_id])) if params[:invoice_id].present? @lines = @lines.where(invoice_id: may_array(params[:invoice_id])) if params[:invoice_id].present?
@lines = @lines.where(line_type: may_array(params[:type])) if params[:type].present? @lines = @lines.where(line_type: may_array(params[:type])) if params[:type].present?

View File

@ -11,8 +11,8 @@ class OpenAPI::V1::SubscriptionsController < OpenAPI::V1::BaseController
.includes(:plan, statistic_profile: :user) .includes(:plan, statistic_profile: :user)
.references(:statistic_profile, :plan) .references(:statistic_profile, :plan)
@subscriptions = @subscriptions.where('created_at >= ?', DateTime.parse(params[:after])) if params[:after].present? @subscriptions = @subscriptions.where('created_at >= ?', Time.zone.parse(params[:after])) if params[:after].present?
@subscriptions = @subscriptions.where('created_at <= ?', DateTime.parse(params[:before])) if params[:before].present? @subscriptions = @subscriptions.where('created_at <= ?', Time.zone.parse(params[:before])) if params[:before].present?
@subscriptions = @subscriptions.where(plan_id: may_array(params[:plan_id])) if params[:plan_id].present? @subscriptions = @subscriptions.where(plan_id: may_array(params[:plan_id])) if params[:plan_id].present?
@subscriptions = @subscriptions.where(statistic_profiles: { user_id: may_array(params[:user_id]) }) if params[:user_id].present? @subscriptions = @subscriptions.where(statistic_profiles: { user_id: may_array(params[:user_id]) }) if params[:user_id].present?

View File

@ -14,7 +14,7 @@ class OpenAPI::V1::UsersController < OpenAPI::V1::BaseController
@users = @users.where(email: email_param) @users = @users.where(email: email_param)
end end
@users = @users.where(id: may_array(params[:user_id])) if params[:user_id].present? @users = @users.where(id: may_array(params[:user_id])) if params[:user_id].present?
@users = @users.where('created_at >= ?', DateTime.parse(params[:created_after])) if params[:created_after].present? @users = @users.where('created_at >= ?', Time.zone.parse(params[:created_after])) if params[:created_after].present?
return if params[:page].blank? return if params[:page].blank?

View File

@ -17,7 +17,7 @@ class Avoir < Invoice
end end
def expire_subscription def expire_subscription
user.subscription.expire(DateTime.current) user.subscription.expire(Time.current)
end end
private private

View File

@ -82,9 +82,9 @@ class Accounting::VatExportService
columns.each do |column| columns.each do |column|
case column case column
when 'start_date' when 'start_date'
row << DateTime.parse(start_date).strftime(date_format) row << Time.zone.parse(start_date).strftime(date_format)
when 'end_date' when 'end_date'
row << DateTime.parse(end_date).strftime(date_format) row << Time.zone.parse(end_date).strftime(date_format)
when 'vat_rate' when 'vat_rate'
row << vat_rate.to_s row << vat_rate.to_s
when 'amount' when 'amount'

View File

@ -104,7 +104,7 @@ class Cart::CreateCartItemService
if cart_subscription if cart_subscription
{ subscription: cart_subscription, new_subscription: true } { subscription: cart_subscription, new_subscription: true }
elsif @customer.subscribed_plan elsif @customer.subscribed_plan
{ subscription: @customer.subscription, new_subscription: false } unless @customer.subscription.expired_at < DateTime.current { subscription: @customer.subscription, new_subscription: false } unless @customer.subscription.expired_at < Time.current
else else
{ subscription: nil, new_subscription: false } { subscription: nil, new_subscription: false }
end end

View File

@ -31,7 +31,7 @@ class InvoicesService
unless filters[:date].nil? unless filters[:date].nil?
invoices = invoices.where( invoices = invoices.where(
"date_trunc('day', invoices.created_at) = :search", "date_trunc('day', invoices.created_at) = :search",
search: "%#{DateTime.iso8601(filters[:date]).to_time.to_date}%" search: "%#{Time.iso8601(filters[:date]).in_time_zone.to_date}%"
) )
end end

View File

@ -121,7 +121,7 @@ class Orders::OrderService
def filter_by_period(orders, filters) def filter_by_period(orders, filters)
return orders unless filters[:period_from].present? && filters[:period_to].present? return orders unless filters[:period_from].present? && filters[:period_to].present?
orders.where(created_at: DateTime.parse(filters[:period_from])..DateTime.parse(filters[:period_to]).end_of_day) orders.where(created_at: Time.zone.parse(filters[:period_from])..Time.zone.parse(filters[:period_to]).end_of_day)
end end
def orders_ordering(orders, filters) def orders_ordering(orders, filters)

View File

@ -58,23 +58,19 @@ class PaymentDocumentService
private private
##
# Output the given integer with leading zeros. If the given value is longer than the given # Output the given integer with leading zeros. If the given value is longer than the given
# length, it will be truncated. # length, it will be truncated.
# @param value {Integer} the integer to pad # @param value [Integer] the integer to pad
# @param length {Integer} the length of the resulting string. # @param length [Integer] the length of the resulting string.
##
def pad_and_truncate(value, length) def pad_and_truncate(value, length)
value.to_s.rjust(length, '0').gsub(/^.*(.{#{length},}?)$/m, '\1') value.to_s.rjust(length, '0').gsub(/^.*(.{#{length},}?)$/m, '\1')
end end
##
# Returns the number of current invoices in the given range around the current date. # Returns the number of current invoices in the given range around the current date.
# If range is invalid or not specified, the total number of invoices is returned. # If range is invalid or not specified, the total number of invoices is returned.
# @param range {String} 'day', 'month', 'year' # @param range [String] 'day', 'month', 'year'
# @param date {Date} the ending date # @param date [Date] the ending date
# @return {Integer} # @return [Integer]
##
def number_of_invoices(range, date = Time.current) def number_of_invoices(range, date = Time.current)
case range.to_s case range.to_s
when 'day' when 'day'
@ -94,11 +90,9 @@ class PaymentDocumentService
Order.where('created_at >= :start_date AND created_at <= :end_date', start_date: start, end_date: ending).length Order.where('created_at >= :start_date AND created_at <= :end_date', start_date: start, end_date: ending).length
end end
##
# Replace the date elements in the provided pattern with the date values, from the provided date # Replace the date elements in the provided pattern with the date values, from the provided date
# @param reference {string} # @param reference [String]
# @param date {DateTime} # @param date [Time]
##
def replace_date_pattern(reference, date) def replace_date_pattern(reference, date)
copy = reference.dup copy = reference.dup
@ -122,10 +116,9 @@ class PaymentDocumentService
copy copy
end end
##
# Replace the document number elements in the provided pattern with counts from the database # Replace the document number elements in the provided pattern with counts from the database
# @param reference {string} # @param reference [String]
## # @param date [Time]
def replace_invoice_number_pattern(reference, date) def replace_invoice_number_pattern(reference, date)
copy = reference.dup copy = reference.dup

View File

@ -2,14 +2,12 @@
# perform various operations on PaymentSchedules # perform various operations on PaymentSchedules
class PaymentScheduleService class PaymentScheduleService
##
# Compute a payment schedule for a new subscription to the provided plan # Compute a payment schedule for a new subscription to the provided plan
# @param plan {Plan} # @param plan [Plan]
# @param total {Number} Total amount of the current shopping cart (which includes this plan) - without coupon # @param total [Number] Total amount of the current shopping cart (which includes this plan) - without coupon
# @param customer {User} the customer # @param customer [User] the customer
# @param coupon {Coupon} apply this coupon, if any # @param coupon [Coupon] apply this coupon, if any
# @param start_at {DateTime} schedule the PaymentSchedule to start in the future # @param start_at [Time] schedule the PaymentSchedule to start in the future
##
def compute(plan, total, customer, coupon: nil, start_at: nil) def compute(plan, total, customer, coupon: nil, start_at: nil)
other_items = total - plan.amount other_items = total - plan.amount
# base monthly price of the plan # base monthly price of the plan
@ -91,12 +89,10 @@ class PaymentScheduleService
res res
end end
##
# Generate the invoice associated with the given PaymentScheduleItem, with the children elements (InvoiceItems). # Generate the invoice associated with the given PaymentScheduleItem, with the children elements (InvoiceItems).
# @param payment_method {String} the payment method or gateway in use # @param payment_method [String] the payment method or gateway in use
# @param payment_id {String} the identifier of the payment as provided by the payment gateway, in case of card payment # @param payment_id [String] the identifier of the payment as provided by the payment gateway, in case of card payment
# @param payment_type {String} the object type of payment_id # @param payment_type [String] the object type of payment_id
##
def generate_invoice(payment_schedule_item, payment_method: nil, payment_id: nil, payment_type: nil) def generate_invoice(payment_schedule_item, payment_method: nil, payment_id: nil, payment_type: nil)
# build the base invoice # build the base invoice
invoice = Invoice.new( invoice = Invoice.new(
@ -125,12 +121,10 @@ class PaymentScheduleService
payment_schedule_item.update(invoice_id: invoice.id) payment_schedule_item.update(invoice_id: invoice.id)
end end
##
# return a paginated list of PaymentSchedule, optionally filtered, with their associated PaymentScheduleItem # return a paginated list of PaymentSchedule, optionally filtered, with their associated PaymentScheduleItem
# @param page {number} page number, used to paginate results # @param page [Number] page number, used to paginate results
# @param size {number} number of items per page # @param size [Number] number of items per page
# @param filters {Hash} allowed filters: reference, customer, date. # @param filters [Hash] allowed filters: reference, customer, date.
##
def self.list(page, size, filters = {}) def self.list(page, size, filters = {})
ps = PaymentSchedule.includes(:operator_profile, :payment_schedule_items, invoicing_profile: [:user]) ps = PaymentSchedule.includes(:operator_profile, :payment_schedule_items, invoicing_profile: [:user])
.joins(:invoicing_profile) .joins(:invoicing_profile)

View File

@ -11,7 +11,7 @@ class Trainings::AuthorizationService
return unless training.authorization return unless training.authorization
training.statistic_profile_trainings training.statistic_profile_trainings
.where('created_at < ?', DateTime.current - training.authorization_period.months) .where('created_at < ?', Time.current - training.authorization_period.months)
.find_each do |spt| .find_each do |spt|
NotificationCenter.call type: 'notify_member_training_authorization_expired', NotificationCenter.call type: 'notify_member_training_authorization_expired',
receiver: spt.statistic_profile.user, receiver: spt.statistic_profile.user,

View File

@ -14,8 +14,8 @@ class Trainings::AutoCancelService
.includes(slots: :slots_reservations) .includes(slots: :slots_reservations)
.where(availabilities: { lock: false }) .where(availabilities: { lock: false })
.where('availabilities.start_at >= ? AND availabilities.start_at <= ?', .where('availabilities.start_at >= ? AND availabilities.start_at <= ?',
DateTime.current, Time.current,
DateTime.current + training.auto_cancel_deadline.hours) Time.current + training.auto_cancel_deadline.hours)
.find_each do |availability| .find_each do |availability|
next if availability.reservations.count >= training.auto_cancel_threshold next if availability.reservations.count >= training.auto_cancel_threshold
@ -33,7 +33,7 @@ class Trainings::AutoCancelService
attached_object: sr, attached_object: sr,
meta_data: { auto_refund: auto_refund } meta_data: { auto_refund: auto_refund }
sr.update(canceled_at: DateTime.current) sr.update(canceled_at: Time.current)
refund_after_cancel(sr.reservation) if auto_refund refund_after_cancel(sr.reservation) if auto_refund
end end
end end
@ -80,7 +80,7 @@ class Trainings::AutoCancelService
service = WalletService.new(user: reservation.user, wallet: reservation.user.wallet) service = WalletService.new(user: reservation.user, wallet: reservation.user.wallet)
transaction = service.credit(amount) transaction = service.credit(amount)
service.create_avoir(transaction, DateTime.current, I18n.t('trainings.refund_for_auto_cancel')) if transaction service.create_avoir(transaction, Time.current, I18n.t('trainings.refund_for_auto_cancel')) if transaction
end end
end end
end end

View File

@ -12,7 +12,7 @@ class Trainings::InvalidationService
return unless training.invalidation return unless training.invalidation
training.statistic_profile_trainings training.statistic_profile_trainings
.where('created_at < ?', DateTime.current - training.invalidation_period.months) .where('created_at < ?', Time.current - training.invalidation_period.months)
.find_each do |spt| .find_each do |spt|
reservations_since = spt.statistic_profile reservations_since = spt.statistic_profile
.reservations .reservations

View File

@ -1,5 +1,6 @@
# frozen_string_literal:true # frozen_string_literal:true
# Create Wallets, which are a way to virtually save money for users
class CreateWallets < ActiveRecord::Migration[4.2] class CreateWallets < ActiveRecord::Migration[4.2]
def up def up
create_table :wallets do |t| create_table :wallets do |t|
@ -10,9 +11,9 @@ class CreateWallets < ActiveRecord::Migration[4.2]
end end
# create all wallets # create all wallets
execute <<-SQL execute <<-SQL.squish
INSERT INTO wallets (user_id, amount, created_at, updated_at) INSERT INTO wallets (user_id, amount, created_at, updated_at)
SELECT users.id, 0, '#{DateTime.current.iso8601}', '#{DateTime.current.iso8601}' SELECT users.id, 0, '#{Time.current.iso8601}', '#{Time.current.iso8601}'
FROM users FROM users
SQL SQL
end end

View File

@ -1,5 +1,7 @@
# frozen_string_literal:true # frozen_string_literal:true
# Due to RGPD regulations, we cannot save trainings after the deletion of the user's account so we migrate those data
# to the StatisticProfile which is an anonymous ghost of the user's account
class MigrateUserTrainingsToStatisticProfileTrainings < ActiveRecord::Migration[4.2] class MigrateUserTrainingsToStatisticProfileTrainings < ActiveRecord::Migration[4.2]
def up def up
user_trainings = execute('SELECT * FROM user_trainings') user_trainings = execute('SELECT * FROM user_trainings')
@ -7,14 +9,16 @@ class MigrateUserTrainingsToStatisticProfileTrainings < ActiveRecord::Migration[
user_trainings.each do |ut| user_trainings.each do |ut|
user = User.find(ut['user_id']) user = User.find(ut['user_id'])
# here we use raw sql to prevent the notify_user callback the email the whole DB # here we use raw sql to prevent the notify_user callback the email the whole DB
# rubocop:disable Rails/SkipsModelValidations
spt_id = insert("INSERT INTO statistic_profile_trainings (statistic_profile_id, training_id, created_at, updated_at) spt_id = insert("INSERT INTO statistic_profile_trainings (statistic_profile_id, training_id, created_at, updated_at)
VALUES (#{user.statistic_profile.id}, #{ut['training_id']}, '#{ut['created_at']}', '#{DateTime.now.utc}')") VALUES (#{user.statistic_profile.id}, #{ut['training_id']}, '#{ut['created_at']}', '#{Time.current.utc}')")
# rubocop:enable Rails/SkipsModelValidations
# update notifications # update notifications
execute("UPDATE notifications SET execute("UPDATE notifications SET
attached_object_type = 'StatisticProfileTraining', attached_object_type = 'StatisticProfileTraining',
attached_object_id = #{spt_id}, attached_object_id = #{spt_id},
updated_at = '#{DateTime.now.utc}' updated_at = '#{Time.current.utc}'
WHERE attached_object_id = #{ut['id']} AND attached_object_type = 'UserTraining'") WHERE attached_object_id = #{ut['id']} AND attached_object_type = 'UserTraining'")
end end
end end
@ -23,11 +27,11 @@ class MigrateUserTrainingsToStatisticProfileTrainings < ActiveRecord::Migration[
StatisticProfileTraining.all.each do |spt| StatisticProfileTraining.all.each do |spt|
statistic_profile = StatisticProfile.find(spt.statistic_profile_id) statistic_profile = StatisticProfile.find(spt.statistic_profile_id)
ut_id = execute("INSERT INTO user_trainings (user_id, training_id, created_at, updated_at) ut_id = execute("INSERT INTO user_trainings (user_id, training_id, created_at, updated_at)
VALUES (#{statistic_profile.user_id}, #{spt.training_id}, '#{spt.created_at.utc}', '#{DateTime.now.utc}')") VALUES (#{statistic_profile.user_id}, #{spt.training_id}, '#{spt.created_at.utc}', '#{Time.current.utc}')")
execute("UPDATE notifications SET execute("UPDATE notifications SET
attached_object_type = 'UserTraining', attached_object_type = 'UserTraining',
attached_object_id = #{ut_id}, attached_object_id = #{ut_id},
updated_at = '#{DateTime.now.utc}' updated_at = '#{Time.current.utc}'
WHERE attached_object_id = #{spt.id} AND attached_object_type = 'StatisticProfileTraining'") WHERE attached_object_id = #{spt.id} AND attached_object_type = 'StatisticProfileTraining'")
end end
end end

View File

@ -1,50 +1,49 @@
# frozen_string_literal: true # frozen_string_literal: true
# Data mapping functions for SSO authentications (through OmniAuth) # Type-dependant aata mapping functions for SSO authentications (through OmniAuth)
module OmniAuth::DataMapping module OmniAuth::DataMapping::Base
# Type-dependant mapping functions extend ActiveSupport::Concern
module Base
extend ActiveSupport::Concern
included do # rubocop:disable Metrics/BlockLength
def local_sym(mapping) included do
(mapping.local_model + '.' + mapping.local_field).to_sym def local_sym(mapping)
end "#{mapping.local_model}.#{mapping.local_field}".to_sym
end
def map_transformation(transformation, raw_data) def map_transformation(transformation, raw_data)
value = nil value = nil
transformation['mapping']&.each do |m| transformation['mapping']&.each do |m|
if m['from'] == raw_data if m['from'] == raw_data
value = m['to'] value = m['to']
break break
end
end end
# if no transformation had set any value, return the raw value
value || raw_data
end end
# if no transformation had set any value, return the raw value
value || raw_data
end
def map_boolean(transformation, raw_data) def map_boolean(transformation, raw_data)
return false if raw_data == transformation['false_value'] return false if raw_data == transformation['false_value']
true if raw_data == transformation['true_value'] true if raw_data == transformation['true_value']
end end
def map_date(transformation, raw_data) def map_date(transformation, raw_data)
case transformation['format'] case transformation['format']
when 'iso8601' when 'iso8601'
DateTime.iso8601(raw_data) Time.zone.iso8601(raw_data)
when 'rfc2822' when 'rfc2822'
DateTime.rfc2822(raw_data) Time.rfc2822(raw_data).in_time_zone
when 'rfc3339' when 'rfc3339'
DateTime.rfc3339(raw_data) Time.rfc3339(raw_data).in_time_zone
when 'timestamp-s' when 'timestamp-s'
DateTime.strptime(raw_data, '%s') Time.zone.strptime(raw_data, '%s')
when 'timestamp-ms' when 'timestamp-ms'
DateTime.strptime(raw_data, '%Q') Time.zone.strptime(raw_data, '%Q')
else else
DateTime.parse(raw_data) Time.zone.parse(raw_data)
end
end end
end end
end end
# rubocop:enable Metrics/BlockLength
end end

View File

@ -21,7 +21,7 @@ module ArchiveHelper
archive_json = JSON.parse(archive) archive_json = JSON.parse(archive)
invoices = Invoice.where( invoices = Invoice.where(
'created_at >= :start_date AND created_at <= :end_date', 'created_at >= :start_date AND created_at <= :end_date',
start_date: accounting_period.start_at.to_datetime, end_date: accounting_period.end_at.to_datetime start_date: accounting_period.start_at.to_time.in_time_zone, end_date: accounting_period.end_at.to_time.in_time_zone
) )
assert_equal invoices.count, archive_json['invoices'].count assert_equal invoices.count, archive_json['invoices'].count

View File

@ -29,7 +29,7 @@ class Availabilities::AsAdminTest < ActionDispatch::IntegrationTest
m = Machine.find_by(slug: 'decoupeuse-vinyle') m = Machine.find_by(slug: 'decoupeuse-vinyle')
# this simulates a fullCalendar (v2) call # this simulates a fullCalendar (v2) call
start_date = DateTime.current.utc.strftime('%Y-%m-%d') start_date = Time.current.utc.strftime('%Y-%m-%d')
end_date = 7.days.from_now.utc.strftime('%Y-%m-%d') end_date = 7.days.from_now.utc.strftime('%Y-%m-%d')
tz = Time.zone.tzinfo.name tz = Time.zone.tzinfo.name
@ -54,7 +54,7 @@ class Availabilities::AsAdminTest < ActionDispatch::IntegrationTest
Setting.set('spaces_module', false) Setting.set('spaces_module', false)
# this simulates a fullCalendar (v2) call # this simulates a fullCalendar (v2) call
start_date = DateTime.current.utc.strftime('%Y-%m-%d') start_date = Time.current.utc.strftime('%Y-%m-%d')
end_date = 7.days.from_now.utc.strftime('%Y-%m-%d') end_date = 7.days.from_now.utc.strftime('%Y-%m-%d')
tz = Time.zone.tzinfo.name tz = Time.zone.tzinfo.name
get "/api/availabilities?start=#{start_date}&end=#{end_date}&timezone=#{tz}&_=1487169767960&#{all_machines}" get "/api/availabilities?start=#{start_date}&end=#{end_date}&timezone=#{tz}&_=1487169767960&#{all_machines}"
@ -76,7 +76,7 @@ class Availabilities::AsAdminTest < ActionDispatch::IntegrationTest
test 'get calendar availabilities with spaces' do test 'get calendar availabilities with spaces' do
# this simulates a fullCalendar (v2) call # this simulates a fullCalendar (v2) call
start_date = DateTime.current.utc.strftime('%Y-%m-%d') start_date = Time.current.utc.strftime('%Y-%m-%d')
end_date = 7.days.from_now.utc.strftime('%Y-%m-%d') end_date = 7.days.from_now.utc.strftime('%Y-%m-%d')
tz = Time.zone.tzinfo.name tz = Time.zone.tzinfo.name
get "/api/availabilities?start=#{start_date}&end=#{end_date}&timezone=#{tz}&_=1487169767960&#{all_spaces}" get "/api/availabilities?start=#{start_date}&end=#{end_date}&timezone=#{tz}&_=1487169767960&#{all_spaces}"
@ -94,7 +94,7 @@ class Availabilities::AsAdminTest < ActionDispatch::IntegrationTest
end end
test 'create availabilities' do test 'create availabilities' do
date = DateTime.current.change(hour: 8, min: 0, sec: 0) date = Time.current.change(hour: 8, min: 0, sec: 0)
slots_count = Slot.count slots_count = Slot.count
post '/api/availabilities', post '/api/availabilities',
@ -128,15 +128,15 @@ class Availabilities::AsAdminTest < ActionDispatch::IntegrationTest
assert_not_nil availability[:id], 'availability ID was unexpectedly nil' assert_not_nil availability[:id], 'availability ID was unexpectedly nil'
# Check the slots # Check the slots
assert_equal (availability[:start_at].to_datetime + (availability[:slot_duration].minutes * 4)).iso8601, assert_equal (availability[:start_at].to_time.in_time_zone + (availability[:slot_duration].minutes * 4)).iso8601,
availability[:end_at], availability[:end_at],
'expected end_at = start_at + 4 slots of 90 minutes' 'expected end_at = start_at + 4 slots of 90 minutes'
assert_equal (slots_count + (4 * 3)), Slot.count, 'expected (4*3) slots of 90 minutes were created' assert_equal (slots_count + (4 * 3)), Slot.count, 'expected (4*3) slots of 90 minutes were created'
assert_equal 90.minutes, Availability.find(availability[:id]).slots.first.duration assert_equal 90.minutes, Availability.find(availability[:id]).slots.first.duration
# Check the recurrence # Check the recurrence
assert_equal (availability[:start_at].to_datetime + 2.weeks).to_date, assert_equal (availability[:start_at].to_time.in_time_zone + 2.weeks).to_date,
availability[:end_date].to_datetime.utc.to_date, availability[:end_date].to_time.in_time_zone.to_date,
'expected end_date = start_at + 2 weeks' 'expected end_date = start_at + 2 weeks'
end end

View File

@ -4,8 +4,8 @@ require 'test_helper'
class Availabilities::AsPublicTest < ActionDispatch::IntegrationTest class Availabilities::AsPublicTest < ActionDispatch::IntegrationTest
test 'get public machines availabilities if machines module is active' do test 'get public machines availabilities if machines module is active' do
start_date = DateTime.current.to_date start_date = Time.current.to_date
end_date = (DateTime.current + 7.days).to_date end_date = 7.days.from_now.to_date
get "/api/availabilities/public?start=#{start_date}&end=#{end_date}&timezone=Europe%2FParis&#{all_machines}" get "/api/availabilities/public?start=#{start_date}&end=#{end_date}&timezone=Europe%2FParis&#{all_machines}"
@ -19,15 +19,15 @@ class Availabilities::AsPublicTest < ActionDispatch::IntegrationTest
availabilities.each_with_index do |a, index| availabilities.each_with_index do |a, index|
assert_not_nil a, "availability #{index} was unexpectedly nil" assert_not_nil a, "availability #{index} was unexpectedly nil"
assert_equal 'machines', a[:available_type], "availability #{index} is not a machines availability" assert_equal 'machines', a[:available_type], "availability #{index} is not a machines availability"
assert DateTime.parse(a[:start]) > start_date, "availability #{index} starts before the requested period" assert Time.zone.parse(a[:start]) > start_date, "availability #{index} starts before the requested period"
assert DateTime.parse(a[:end]) < end_date, "availability #{index} ends after the requested period" assert Time.zone.parse(a[:end]) < end_date, "availability #{index} ends after the requested period"
end end
end end
test 'get anymore machines availabilities if machines module is inactive' do test 'get anymore machines availabilities if machines module is inactive' do
Setting.set('machines_module', false) Setting.set('machines_module', false)
start_date = DateTime.current.to_date start_date = Time.current.to_date
end_date = (DateTime.current + 7.days).to_date end_date = 7.days.from_now.to_date
get "/api/availabilities/public?start=#{start_date}&end=#{end_date}&timezone=Europe%2FParis&#{all_machines}" get "/api/availabilities/public?start=#{start_date}&end=#{end_date}&timezone=Europe%2FParis&#{all_machines}"
@ -41,8 +41,8 @@ class Availabilities::AsPublicTest < ActionDispatch::IntegrationTest
end end
test 'get public trainings availabilities' do test 'get public trainings availabilities' do
start_date = DateTime.current.to_date start_date = Time.current.to_date
end_date = (DateTime.current + 7.days).to_date end_date = 7.days.from_now.to_date
get "/api/availabilities/public?start=#{start_date}&end=#{end_date}&timezone=Europe%2FParis&#{all_trainings}" get "/api/availabilities/public?start=#{start_date}&end=#{end_date}&timezone=Europe%2FParis&#{all_trainings}"
@ -56,14 +56,14 @@ class Availabilities::AsPublicTest < ActionDispatch::IntegrationTest
availabilities.each_with_index do |a, index| availabilities.each_with_index do |a, index|
assert_not_nil a, "availability #{index} was unexpectedly nil" assert_not_nil a, "availability #{index} was unexpectedly nil"
assert_equal 'training', a[:available_type], "availability #{index} is not a training availability" assert_equal 'training', a[:available_type], "availability #{index} is not a training availability"
assert DateTime.parse(a[:start]) > start_date, "availability #{index} starts before the requested period" assert Time.zone.parse(a[:start]) > start_date, "availability #{index} starts before the requested period"
assert DateTime.parse(a[:end]) < end_date, "availability #{index} ends after the requested period" assert Time.zone.parse(a[:end]) < end_date, "availability #{index} ends after the requested period"
end end
end end
test 'get public spaces availabilities' do test 'get public spaces availabilities' do
start_date = DateTime.current.to_date start_date = Time.current.to_date
end_date = (DateTime.current + 7.days).to_date end_date = 7.days.from_now.to_date
get "/api/availabilities/public?start=#{start_date}&end=#{end_date}&timezone=Europe%2FParis&#{all_spaces}" get "/api/availabilities/public?start=#{start_date}&end=#{end_date}&timezone=Europe%2FParis&#{all_spaces}"
@ -77,8 +77,8 @@ class Availabilities::AsPublicTest < ActionDispatch::IntegrationTest
availabilities.each_with_index do |a, index| availabilities.each_with_index do |a, index|
assert_not_nil a, "availability #{index} was unexpectedly nil" assert_not_nil a, "availability #{index} was unexpectedly nil"
assert_equal 'space', a[:available_type], "availability #{index} is not a space availability" assert_equal 'space', a[:available_type], "availability #{index} is not a space availability"
assert DateTime.parse(a[:start]) > start_date, "availability #{index} starts before the requested period" assert Time.zone.parse(a[:start]) > start_date, "availability #{index} starts before the requested period"
assert DateTime.parse(a[:end]) < end_date, "availability #{index} ends after the requested period" assert Time.zone.parse(a[:end]) < end_date, "availability #{index} ends after the requested period"
end end
end end
@ -98,8 +98,8 @@ class Availabilities::AsPublicTest < ActionDispatch::IntegrationTest
availabilities.each_with_index do |a, index| availabilities.each_with_index do |a, index|
assert_not_nil a, "availability #{index} was unexpectedly nil" assert_not_nil a, "availability #{index} was unexpectedly nil"
assert_equal 'event', a[:available_type], "availability #{index} is not a event availability" assert_equal 'event', a[:available_type], "availability #{index} is not a event availability"
assert DateTime.parse(a[:start]) > start_date, "availability #{index} starts before the requested period" assert Time.zone.parse(a[:start]) > start_date, "availability #{index} starts before the requested period"
assert DateTime.parse(a[:end]) < end_date, "availability #{index} ends after the requested period" assert Time.zone.parse(a[:end]) < end_date, "availability #{index} ends after the requested period"
end end
end end

View File

@ -12,7 +12,7 @@ class Availabilities::AsUserTest < ActionDispatch::IntegrationTest
m = Machine.find_by(slug: 'decoupeuse-vinyle') m = Machine.find_by(slug: 'decoupeuse-vinyle')
# this simulates a fullCalendar (v2) call # this simulates a fullCalendar (v2) call
start_date = DateTime.current.utc.strftime('%Y-%m-%d') start_date = Time.current.utc.strftime('%Y-%m-%d')
end_date = 7.days.from_now.utc.strftime('%Y-%m-%d') end_date = 7.days.from_now.utc.strftime('%Y-%m-%d')
tz = Time.zone.tzinfo.name tz = Time.zone.tzinfo.name
@ -29,13 +29,10 @@ class Availabilities::AsUserTest < ActionDispatch::IntegrationTest
assert_not_nil availabilities[0][:machine], "first availability's machine was unexpectedly nil" assert_not_nil availabilities[0][:machine], "first availability's machine was unexpectedly nil"
assert_equal m.id, availabilities[0][:machine][:id], "first availability's machine does not match the required machine" assert_equal m.id, availabilities[0][:machine][:id], "first availability's machine does not match the required machine"
# Check that we din't get availabilities from the past
availabilities.each do |a|
assert_not a[:start] < DateTime.current, 'retrieved a slot in the past'
end
# Check that we don't get availabilities in more than a month
availabilities.each do |a| availabilities.each do |a|
# Check that we din't get availabilities from the past
assert_not a[:start] < Time.current, 'retrieved a slot in the past'
# Check that we don't get availabilities in more than a month
assert_not a[:start] > 1.month.from_now, 'retrieved a slot in more than 1 month for user who has no yearly subscription' assert_not a[:start] > 1.month.from_now, 'retrieved a slot in more than 1 month for user who has no yearly subscription'
end end
end end

View File

@ -54,7 +54,7 @@ class OpenApi::AccountingTest < ActionDispatch::IntegrationTest
lines = json_response(response.body) lines = json_response(response.body)
assert lines[:lines].count.positive? assert lines[:lines].count.positive?
assert(lines[:lines].all? do |line| assert(lines[:lines].all? do |line|
date = DateTime.parse(line[:date]) date = Time.zone.parse(line[:date])
date >= '2022-09-01'.to_date && date <= '2022-09-30'.to_date date >= '2022-09-01'.to_date && date <= '2022-09-30'.to_date
end) end)
end end

View File

@ -81,6 +81,6 @@ class OpenApi::UsersTest < ActionDispatch::IntegrationTest
users = json_response(response.body) users = json_response(response.body)
assert users[:users].count.positive? assert users[:users].count.positive?
assert(users[:users].all? { |u| DateTime.parse(u[:created_at]) >= DateTime.parse('2018-01-01T00:00:00+01:00') }) assert(users[:users].all? { |u| Time.zone.parse(u[:created_at]) >= Time.zone.parse('2018-01-01T00:00:00+01:00') })
end end
end end

View File

@ -17,7 +17,7 @@ class Reservations::SpaceSeatsTest < ActionDispatch::IntegrationTest
space = Space.first space = Space.first
date = (DateTime.current + 1.day).change(hour: 8, min: 0, sec: 0) date = 1.day.from_now.change(hour: 8, min: 0, sec: 0)
post '/api/availabilities', post '/api/availabilities',
params: { params: {

View File

@ -1,16 +1,18 @@
# frozen_string_literal: true
require 'test_helper' require 'test_helper'
class CouponTest < ActiveSupport::TestCase class CouponTest < ActiveSupport::TestCase
test 'valid coupon with percentage' do test 'valid coupon with percentage' do
c = Coupon.new({name: 'Hot deals', code: 'HOT15', percent_off: 15, validity_per_user: 'once', valid_until: (DateTime.current + 2.weeks), max_usages: 100, active: true}) c = Coupon.new({ name: 'Hot deals', code: 'HOT15', percent_off: 15, validity_per_user: 'once', valid_until: 2.weeks.from_now,
max_usages: 100, active: true })
assert c.valid? assert c.valid?
assert_equal 'active', c.status, 'Invalid coupon status' assert_equal 'active', c.status, 'Invalid coupon status'
assert_equal 'percent_off', c.type, 'Invalid coupon type' assert_equal 'percent_off', c.type, 'Invalid coupon type'
end end
test 'coupon must have a valid percentage' do test 'coupon must have a valid percentage' do
c = Coupon.new({name: 'Amazing deal', code: 'DISCOUNT', percent_off: 200, validity_per_user: 'once'}) c = Coupon.new({ name: 'Amazing deal', code: 'DISCOUNT', percent_off: 200, validity_per_user: 'once' })
assert c.invalid? assert c.invalid?
end end
@ -20,19 +22,19 @@ class CouponTest < ActiveSupport::TestCase
end end
test 'two coupons cannot have the same code' do test 'two coupons cannot have the same code' do
c = Coupon.new({name: 'Summer deals', code: 'SUNNYFABLAB', percent_off: 15, validity_per_user: 'always'}) c = Coupon.new({ name: 'Summer deals', code: 'SUNNYFABLAB', percent_off: 15, validity_per_user: 'always' })
assert c.invalid? assert c.invalid?
end end
test 'valid coupon with cash amount' do test 'valid coupon with cash amount' do
c = Coupon.new({name: 'Essential Box', code: 'KWXX2M', amount_off: 2000, validity_per_user: 'once', max_usages: 1, active: true}) c = Coupon.new({ name: 'Essential Box', code: 'KWXX2M', amount_off: 2000, validity_per_user: 'once', max_usages: 1, active: true })
assert c.valid? assert c.valid?
assert_equal 'active', c.status, 'Invalid coupon status' assert_equal 'active', c.status, 'Invalid coupon status'
assert_equal 'amount_off', c.type, 'Invalid coupon type' assert_equal 'amount_off', c.type, 'Invalid coupon type'
end end
test 'coupon with cash amount cannot be used with cheaper cart' do test 'coupon with cash amount cannot be used with cheaper cart' do
c = Coupon.new({name: 'Premium Box', code: '6DDX2T44MQ', amount_off: 20000, validity_per_user: 'once', max_usages: 1, active: true}) c = Coupon.new({ name: 'Premium Box', code: '6DDX2T44MQ', amount_off: 20_000, validity_per_user: 'once', max_usages: 1, active: true })
assert_equal 'amount_exceeded', c.status(User.find_by(username: 'jdupond').id, 2000) assert_equal 'amount_exceeded', c.status(User.find_by(username: 'jdupond').id, 2000)
end end
end end

View File

@ -25,7 +25,7 @@ class PrepaidPackServiceTest < ActiveSupport::TestCase
test 'update user pack minutes' do test 'update user pack minutes' do
availabilities_service = Availabilities::AvailabilitiesService.new(@acamus) availabilities_service = Availabilities::AvailabilitiesService.new(@acamus)
slots = availabilities_service.machines([@machine], @acamus, { start: DateTime.now, end: 1.day.from_now }) slots = availabilities_service.machines([@machine], @acamus, { start: Time.current, end: 1.day.from_now })
reservation = Reservation.create( reservation = Reservation.create(
reservable_id: @machine.id, reservable_id: @machine.id,
reservable_type: Machine.name, reservable_type: Machine.name,