1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2024-11-28 09:24:24 +01:00

Usage of the rails logger instead of printing to standard output

This commit is contained in:
Sylvain 2022-07-26 17:27:33 +02:00
parent eaaf3b9a73
commit bb7eec924c
24 changed files with 80 additions and 82 deletions

View File

@ -6,6 +6,7 @@
- Refactored and documented the availability-slot-reservation data model
- Display bookers names to connected users now apply to all resources
- Updated rails locales files
- Usage of the rails logger instead of printing to standard output
- Fix a bug: prevent same slot booking feature ignores canceled reservations
- Fix a bug: wrong currency on invoices files
- Fix a bug: unable to reserve if user's subscription plan is disabled

View File

@ -14,7 +14,7 @@ class SocialBotController < ActionController::Base
@training = Training.friendly.find(Regexp.last_match(3).to_s)
render :training, status: :ok
else
puts "unknown bot request : #{request.original_url}"
Rails.logger.warn "unknown bot request : #{request.original_url}"
end
end
end

View File

@ -25,7 +25,7 @@ class NotificationsMailer < NotifyWith::NotificationsMailer
send(notification.notification_type)
rescue StandardError => e
STDERR.puts "[NotificationsMailer] notification cannot be sent: #{e}"
Rails.logger.error "[NotificationsMailer] notification cannot be sent: #{e}"
end
def helpers

View File

@ -74,7 +74,7 @@ class Availability < ApplicationRecord
.joins(:slots)
.where('slots.availability_id = ?', id)
else
STDERR.puts "[safe_destroy] Availability with unknown type #{available_type}"
Rails.logger.warn "[safe_destroy] Availability with unknown type #{available_type}"
reservations = []
end
if reservations.size.zero?
@ -107,7 +107,7 @@ class Availability < ApplicationRecord
when 'space'
spaces.map(&:name).join(' - ')
else
STDERR.puts "[title] Availability with unknown type #{available_type}"
Rails.logger.warn "[title] Availability with unknown type #{available_type}"
'???'
end
end

View File

@ -175,8 +175,9 @@ class Invoice < PaymentDocument
return unless Setting.get('invoicing_module')
unless Rails.env.test?
puts "Creating an InvoiceWorker job to generate the following invoice: id(#{id}), main_item.object_id(#{main_item.object_id}), " \
"main_item.object_type(#{main_item.object_type}), user_id(#{invoicing_profile.user_id})"
Rails.logger.info "Creating an InvoiceWorker job to generate the following invoice: id(#{id}), " \
"main_item.object_id(#{main_item.object_id}), " \
"main_item.object_type(#{main_item.object_type}), user_id(#{invoicing_profile.user_id})"
end
InvoiceWorker.perform_async(id, user&.subscription&.expired_at)
end
@ -185,9 +186,7 @@ class Invoice < PaymentDocument
return if Rails.env.test?
return unless changed?
puts "WARNING: Invoice update triggered [ id: #{id}, reference: #{reference} ]"
puts '---------- changes ----------'
puts changes
puts '---------------------------------'
Rails.logger.warn "Invoice update triggered [ id: #{id}, reference: #{reference} ]\n" \
"---------- changes ----------#{changes}\n---------------------------------"
end
end

View File

@ -50,9 +50,7 @@ class InvoiceItem < Footprintable
return if Rails.env.test?
return unless changed?
puts "WARNING: InvoiceItem update triggered [ id: #{id}, invoice reference: #{invoice.reference} ]"
puts '---------- changes ----------'
puts changes
puts '---------------------------------'
Rails.logger.warn "InvoiceItem update triggered [ id: #{id}, invoice reference: #{invoice.reference} ]\n" \
"---------- changes ----------\n#{changes}\n---------------------------------"
end
end

View File

@ -100,8 +100,9 @@ class PaymentSchedule < PaymentDocument
return unless Setting.get('invoicing_module')
unless Rails.env.test?
puts "Creating an PaymentScheduleWorker job to generate the following payment schedule: id(#{id}), main_object.object_id(#{main_object.object_id}), " \
"main_object.object_type(#{main_object.object_type}), user_id(#{invoicing_profile.user_id})"
Rails.logger.info "Creating an PaymentScheduleWorker job to generate the following payment schedule: id(#{id}), " \
"main_object.object_id(#{main_object.object_id}), " \
"main_object.object_type(#{main_object.object_type}), user_id(#{invoicing_profile.user_id})"
end
PaymentScheduleWorker.perform_async(id)
end

View File

@ -122,7 +122,7 @@ class Plan < ApplicationRecord
if !stat_type.nil? && !stat_subtype.nil?
StatisticTypeSubType.create!(statistic_type: stat_type, statistic_sub_type: stat_subtype)
else
puts 'ERROR: Unable to create the statistics association for the new plan. ' \
Rails.logger.error 'Unable to create the statistics association for the new plan. ' \
'Possible causes: the type or the subtype were not created successfully.'
end
end

View File

@ -29,7 +29,7 @@ class PDF::Invoice < Prawn::Document
begin
image StringIO.new(Base64.decode64(img_b64)), fit: [415, 40]
rescue StandardError => e
puts "Unable to decode invoice logo from base64: #{e}"
Rails.logger.error "Unable to decode invoice logo from base64: #{e}"
end
move_down 20
# the following line is a special comment to workaround RubyMine inspection problem
@ -120,7 +120,7 @@ class PDF::Invoice < Prawn::Document
when 'StatisticProfilePrepaidPack'
object = I18n.t('invoices.prepaid_pack')
else
puts "ERROR : specified main_item.object_type type (#{invoice.main_item.object_type}) is unknown"
Rails.logger.error "specified main_item.object_type type (#{invoice.main_item.object_type}) is unknown"
end
end
text I18n.t('invoices.object') + ' ' + object
@ -233,12 +233,14 @@ class PDF::Invoice < Prawn::Document
# total verification
total = invoice.total / 100.00
puts "ERROR: totals are NOT equals => expected: #{total}, computed: #{total_calc}" if total_calc != total
Rails.logger.error "totals are NOT equals => expected: #{total}, computed: #{total_calc}" if total_calc != total
# TVA
vat_service = VatHistoryService.new
vat_rate_group = vat_service.invoice_vat(invoice)
if total_vat != 0
if total_vat.zero?
data += [[I18n.t('invoices.total_amount'), number_to_currency(total)]]
else
data += [[I18n.t('invoices.total_including_all_taxes'), number_to_currency(total)]]
vat_rate_group.each do |_type, rate|
data += [[I18n.t('invoices.including_VAT_RATE', RATE: rate[:vat_rate], AMOUNT: number_to_currency(rate[:amount] / 100.00)), number_to_currency(rate[:total_vat] / 100.00)]]
@ -247,13 +249,11 @@ class PDF::Invoice < Prawn::Document
data += [[I18n.t('invoices.including_amount_payed_on_ordering'), number_to_currency(total)]]
# checking the round number
rounded = sprintf('%.2f', total_vat / 100.00).to_f + sprintf('%.2f', total_ht / 100.00).to_f
if rounded != sprintf('%.2f', total_calc).to_f
puts 'ERROR: rounding the numbers cause an invoice inconsistency. ' \
"Total expected: #{sprintf('%.2f', total_calc)}, total computed: #{rounded}"
rounded = sprintf('%.2f', total_vat / 100.00).to_f + sprintf('%.2f', total_ht / 100.00)
if rounded != sprintf('%.2f', total_calc)
Rails.logger.error 'rounding the numbers cause an invoice inconsistency. ' \
"Total expected: #{sprintf('%.2f', total_calc)}, total computed: #{rounded}"
end
else
data += [[I18n.t('invoices.total_amount'), number_to_currency(total)]]
end
# display table
@ -305,7 +305,7 @@ class PDF::Invoice < Prawn::Document
when 'none'
payment_verbose = I18n.t('invoices.no_refund')
else
puts "ERROR : specified refunding method (#{payment_verbose}) is unknown"
Rails.logger.error "specified refunding method (#{payment_verbose}) is unknown"
end
payment_verbose += ' ' + I18n.t('invoices.for_an_amount_of_AMOUNT', AMOUNT: number_to_currency(total))
else

View File

@ -32,7 +32,7 @@ class PDF::PaymentSchedule < Prawn::Document
begin
image StringIO.new(Base64.decode64(img_b64)), fit: [415, 40]
rescue StandardError => e
puts "Unable to decode invoice logo from base64: #{e}"
Rails.logger.error "Unable to decode invoice logo from base64: #{e}"
end
move_down 20
font('Open-Sans', size: 10) do

View File

@ -135,7 +135,7 @@ class CartService
plan: plan_info[:plan],
new_subscription: plan_info[:new_subscription])
else
STDERR.puts "WARNING: the reservable #{reservable} is not implemented"
Rails.logger.warn "the reservable #{reservable} is not implemented"
raise NotImplementedError
end
end
@ -172,7 +172,7 @@ class CartService
plan: plan,
new_subscription: true)
else
STDERR.puts "WARNING: the reservable #{reservable} is not implemented"
Rails.logger.warn "WARNING: the reservable #{reservable} is not implemented"
raise NotImplementedError
end
end

View File

@ -51,19 +51,18 @@ class FootprintService
return saved if Rails.env.test?
if saved.nil?
puts "Debug data not found for #{klass} [ id: #{item.id} ]"
Rails.logger.debug { "Debug data not found for #{klass} [ id: #{item.id} ]" }
else
puts "Debug footprint for #{klass} [ id: #{item.id} ]"
puts '-----------------------------------------'
puts "columns: [ #{columns.join(', ')} ]"
puts "current: #{current}"
puts " saved: #{saved.format_data(item.id)}"
puts '-----------------------------------------'
Rails.logger.debug do
"Debug footprint for #{klass} [ id: #{item.id} ]\n" \
"-----------------------------------------\ncolumns: [ #{columns.join(', ')} ]\n" \
"current: #{current}\n saved: #{saved.format_data(item.id)}\n" \
'-----------------------------------------'
end
item.footprint_children.map(&:debug_footprint)
end
others = FootprintDebug.where('klass = ? AND data LIKE ? AND id != ?', klass, "#{item.id}%", saved&.id)
puts "other possible matches IDs: #{others.map(&:id)}"
puts '-----------------------------------------'
Rails.logger.debug { "other possible matches IDs: #{others.map(&:id)}\n-----------------------------------------" }
end
private

View File

@ -62,7 +62,7 @@ class VatExportService
vat_total = []
service = VatHistoryService.new
invoices.each do |i|
puts "processing invoice #{i.id}..." unless Rails.env.test?
Rails.logger.info "processing invoice #{i.id}..." unless Rails.env.test?
vat_total.push service.invoice_vat(i)
end
@ -83,7 +83,7 @@ class VatExportService
when 'amount'
row << format_number(amount / 100.0)
else
puts "Unsupported column: #{column}"
Rails.logger.warn "Unsupported column: #{column}"
end
row << separator
end

View File

@ -8,7 +8,7 @@ class PeriodStatisticsWorker
# @param period {String|Integer} date string or number of days until current date
def perform(period)
days = date_to_days(period)
puts "\n==> generating statistics for the last #{days} days <==\n"
Rails.logger.info "\n==> generating statistics for the last #{days} days <==\n"
if days.zero?
StatisticService.new.generate_statistic(start_date: DateTime.current.beginning_of_day, end_date: DateTime.current.end_of_day)
else

View File

@ -30,18 +30,12 @@ class StripeWorker
cpn = Stripe::Coupon.retrieve(coupon_code, api_key: Setting.get('stripe_secret_key'))
cpn.delete
rescue Stripe::InvalidRequestError => e
STDERR.puts "WARNING: Unable to delete the coupon on Stripe: #{e}"
warn "WARNING: Unable to delete the coupon on Stripe: #{e}"
end
def create_or_update_stp_product(class_name, id)
object = class_name.constantize.find(id)
if !object.payment_gateway_object.nil?
Stripe::Product.update(
object.payment_gateway_object.gateway_object_id,
{ name: object.name },
{ api_key: Setting.get('stripe_secret_key') }
)
else
if object.payment_gateway_object.nil?
product = Stripe::Product.create(
{
name: object.name,
@ -54,12 +48,18 @@ class StripeWorker
pgo = PaymentGatewayObject.new(item: object)
pgo.gateway_object = product
pgo.save!
puts "Stripe product was created for the #{class_name} \##{id}"
Rails.logger.info "Stripe product was created for the #{class_name} \##{id}"
else
Stripe::Product.update(
object.payment_gateway_object.gateway_object_id,
{ name: object.name },
{ api_key: Setting.get('stripe_secret_key') }
)
end
rescue Stripe::InvalidRequestError
obj_id = object.payment_gateway_object.gateway_object_id
STDERR.puts "WARNING: saved payment_gateway_object#id (#{obj_id}) does not match on Stripe, recreating..."
Rails.logger.warn "WARNING: saved payment_gateway_object#id (#{obj_id}) does not match on Stripe, recreating..."
product = Stripe::Product.create(
{
name: object.name,
@ -72,6 +72,6 @@ class StripeWorker
pgo = PaymentGatewayObject.new(item: object)
pgo.gateway_object = product
pgo.save!
puts "Stripe product was created for the #{class_name} \##{id}"
Rails.logger.info "Stripe product was created for the #{class_name} \##{id}"
end
end

View File

@ -7,10 +7,10 @@ class SyncObjectsOnStripeWorker
sidekiq_options lock: :until_executed, on_conflict: :reject, queue: :stripe
def perform(notify_user_id = nil)
logger.debug 'We create all non-existing customers on stripe. This may take a while...'
Rails.logger.info 'We create all non-existing customers on stripe. This may take a while...'
total = User.online_payers.count
User.online_payers.each_with_index do |member, index|
logger.debug "#{index} / #{total}"
Rails.logger.info "#{index} / #{total}"
begin
stp_customer = member.payment_gateway_object&.gateway_object&.retrieve
StripeWorker.new.create_stripe_customer(member.id) if stp_customer.nil? || stp_customer[:deleted]
@ -18,37 +18,37 @@ class SyncObjectsOnStripeWorker
begin
StripeWorker.new.create_stripe_customer(member.id)
rescue Stripe::InvalidRequestError => e
puts "Unable to create the customer #{member.id} do to a Stripe error: #{e}"
Rails.logger.error "Unable to create the customer #{member.id} do to a Stripe error: #{e}"
end
end
end
logger.debug 'We create all non-existing coupons on stripe. This may take a while...'
Rails.logger.info 'We create all non-existing coupons on stripe. This may take a while...'
total = Coupon.all.count
Coupon.all.each_with_index do |coupon, index|
logger.debug "#{index} / #{total}"
Rails.logger.info "#{index} / #{total}"
Stripe::Coupon.retrieve(coupon.code, api_key: Setting.get('stripe_secret_key'))
rescue Stripe::InvalidRequestError
begin
Stripe::Service.new.create_coupon(coupon.id)
rescue Stripe::InvalidRequestError => e
logger.warn "Unable to create coupon #{coupon.code} on stripe: #{e}"
Rails.logger.error "Unable to create coupon #{coupon.code} on stripe: #{e}"
end
end
w = StripeWorker.new
[Machine, Training, Space, Plan].each do |klass|
logger.debug "We create all non-existing #{klass} on stripe. This may take a while..."
Rails.logger.info "We create all non-existing #{klass} on stripe. This may take a while..."
total = klass.all.count
klass.all.each_with_index do |item, index|
logger.debug "#{index} / #{total}"
Rails.logger.info "#{index} / #{total}"
w.perform(:create_or_update_stp_product, klass.name, item.id)
end
end
logger.debug 'Sync is done'
Rails.logger.info 'Sync is done'
return unless notify_user_id
logger.debug "Notify user #{notify_user_id}"
Rails.logger.info "Notify user #{notify_user_id}"
user = User.find(notify_user_id)
NotificationCenter.call type: :notify_admin_objects_stripe_sync,
receiver: user,

View File

@ -4,7 +4,7 @@ class MigrateProfileToInvoicingProfile < ActiveRecord::Migration[4.2]
def up
User.all.each do |u|
p = u.profile
puts "WARNING: User #{u.id} has no profile" and next unless p
Rails.logger.warn "User #{u.id} has no profile" and next unless p
ip = InvoicingProfile.create!(
user: u,

View File

@ -4,7 +4,7 @@ class MigrateProfileToStatisticProfile < ActiveRecord::Migration[4.2]
def up
User.all.each do |u|
p = u.profile
puts "WARNING: User #{u.id} has no profile" and next unless p
Rails.logger.warn "User #{u.id} has no profile" and next unless p
StatisticProfile.create!(
user: u,
@ -20,7 +20,7 @@ class MigrateProfileToStatisticProfile < ActiveRecord::Migration[4.2]
def down
StatisticProfile.all.each do |sp|
p = sp.user.profile
puts "WARNING: User #{sp.user_id} has no profile" and next unless p
Rails.logger.warn "User #{sp.user_id} has no profile" and next unless p
p.update_attributes(
gender: sp.gender,

View File

@ -12,7 +12,7 @@ class MigrateInvoiceToInvoicingProfile < ActiveRecord::Migration[4.2]
# remove and save periods in memory
periods = Integrity::ArchiveHelper.backup_and_remove_periods
# migrate invoices
puts 'Migrating invoices. This may take a while...'
Rails.logger.info 'Migrating invoices. This may take a while...'
Invoice.order(:id).all.each do |i|
user = User.find(i.user_id)
operator = User.find_by(id: i.operator_id)

View File

@ -73,7 +73,7 @@ class AddObjectToInvoiceItem < ActiveRecord::Migration[5.2]
Invoice.reset_column_information
# chain records
puts 'Chaining all record. This may take a while...'
Rails.logger.info 'Chaining all record. This may take a while...'
InvoiceItem.order(:id).all.each(&:chain_record)
Invoice.order(:id).all.each(&:chain_record)
@ -121,7 +121,7 @@ class AddObjectToInvoiceItem < ActiveRecord::Migration[5.2]
Invoice.reset_column_information
# chain records
puts 'Chaining all record. This may take a while...'
Rails.logger.info 'Chaining all record. This may take a while...'
InvoiceItem.order(:id).all.each(&:chain_record)
Invoice.order(:id).all.each(&:chain_record)

View File

@ -48,7 +48,7 @@ class CreatePaymentScheduleObjects < ActiveRecord::Migration[5.2]
PaymentSchedule.reset_column_information
# chain records
puts 'Chaining all record. This may take a while...'
Rails.logger.info 'Chaining all record. This may take a while...'
PaymentScheduleItem.order(:id).all.each(&:chain_record)
PaymentSchedule.order(:id).all.each(&:chain_record)
end
@ -87,7 +87,7 @@ class CreatePaymentScheduleObjects < ActiveRecord::Migration[5.2]
PaymentSchedule.reset_column_information
# chain records
puts 'Chaining all record. This may take a while...'
Rails.logger.info 'Chaining all record. This may take a while...'
PaymentScheduleItem.order(:id).all.each(&:chain_record)
PaymentSchedule.order(:id).all.each(&:chain_record)
end

View File

@ -18,7 +18,7 @@ class MigratePaymentSchedulePaymentMethodCheck < ActiveRecord::Migration[5.2]
end
# chain all records
puts 'Chaining all record. This may take a while...'
Rails.logger.info 'Chaining all record. This may take a while...'
PaymentSchedule.order(:id).find_each(&:chain_record)
# re-create all archives from the memory dump

View File

@ -11,7 +11,7 @@ class Integrity::ArchiveHelper
def check_footprints
if AccountingPeriod.count.positive?
last_period = AccountingPeriod.order(start_at: :desc).first
puts "Checking invoices footprints from #{last_period.end_at}. This may take a while..."
Rails.logger.info "Checking invoices footprints from #{last_period.end_at}. This may take a while..."
Invoice.where('created_at > ?', last_period.end_at).order(:id).each do |i|
next if i.check_footprint
@ -19,7 +19,7 @@ class Integrity::ArchiveHelper
raise "Invalid footprint for invoice #{i.id}"
end
else
puts 'Checking all invoices footprints. This may take a while...'
Rails.logger.info 'Checking all invoices footprints. This may take a while...'
Invoice.order(:id).all.each do |i|
next if i.check_footprint
@ -34,7 +34,7 @@ class Integrity::ArchiveHelper
range_periods = get_periods(range_start: range_start, range_end: range_end)
return [] unless range_periods.count.positive?
puts 'Removing accounting archives...'
Rails.logger.info 'Removing accounting archives...'
# 1. remove protection for AccountingPeriods
execute("DROP RULE IF EXISTS accounting_periods_del_protect ON #{AccountingPeriod.arel_table.name};")
# 2. backup AccountingPeriods in memory
@ -58,7 +58,7 @@ class Integrity::ArchiveHelper
return unless periods.size.positive?
# 1. recreate AccountingPeriods
puts 'Recreating accounting archives. This may take a while...'
Rails.logger.info 'Recreating accounting archives. This may take a while...'
periods.each do |p|
AccountingPeriod.create!(
start_at: p[:start_at],

View File

@ -6,7 +6,7 @@ namespace :fablab do
desc 'switch the active authentication provider'
task :switch_provider, [:provider] => :environment do |_task, args|
providers = AuthProvider.all.inject('') { |str, item| str + item[:name] + ', ' }
providers = AuthProvider.all.inject('') { |str, item| "#{str}#{item[:name]}, " }
unless args.provider
puts "\e[0;31mERROR\e[0m: You must pass a provider name to activate. Available providers are: #{providers[0..-3]}"
next
@ -32,14 +32,14 @@ namespace :fablab do
AuthProvider.find_by(name: args.provider).update_attribute(:status, 'active')
# migrate the current users.
if AuthProvider.active.providable_type != DatabaseProvider.name
# Concerns any providers except local database
User.all.each(&:generate_auth_migration_token)
else
if AuthProvider.active.providable_type == DatabaseProvider.name
User.all.each do |user|
# Concerns local database provider
user.update_attribute(:auth_token, nil)
end
else
# Concerns any providers except local database
User.all.each(&:generate_auth_migration_token)
end
# ask the user to restart the application