chore: rubocop

chore: fix api test conventions

chore: rubocop -A spec/

chore: more rubocop -A

fix failing test

rubocop fixes

removes helper methods that are in my opinion dead code

more rubocop fixes

rubocop -a --auto-gen-config
This commit is contained in:
Philipp Rothmann 2023-05-12 13:01:12 +02:00 committed by Philipp Rothmann
parent f6fb804bbe
commit fb2b4d8a8a
331 changed files with 4263 additions and 4507 deletions

View file

@ -3,39 +3,39 @@ class Admin::BankAccountsController < Admin::BaseController
def new
@bank_account = BankAccount.new(params[:bank_account])
render :layout => false
render layout: false
end
def edit
@bank_account = BankAccount.find(params[:id])
render action: 'new', layout: false
end
def create
@bank_account = BankAccount.new(params[:bank_account])
if @bank_account.valid? && @bank_account.save
redirect_to update_bank_accounts_admin_finances_url, :status => 303
redirect_to update_bank_accounts_admin_finances_url, status: :see_other
else
render :action => 'new', :layout => false
render action: 'new', layout: false
end
end
def edit
@bank_account = BankAccount.find(params[:id])
render :action => 'new', :layout => false
end
def update
@bank_account = BankAccount.find(params[:id])
if @bank_account.update(params[:bank_account])
redirect_to update_bank_accounts_admin_finances_url, :status => 303
redirect_to update_bank_accounts_admin_finances_url, status: :see_other
else
render :action => 'new', :layout => false
render action: 'new', layout: false
end
end
def destroy
@bank_account = BankAccount.find(params[:id])
@bank_account.destroy
redirect_to update_bank_accounts_admin_finances_url, :status => 303
rescue => error
flash.now[:alert] = error.message
redirect_to update_bank_accounts_admin_finances_url, status: :see_other
rescue StandardError => e
flash.now[:alert] = e.message
render template: 'shared/alert'
end
end

View file

@ -6,6 +6,11 @@ class Admin::BankGatewaysController < Admin::BaseController
render layout: false
end
def edit
@bank_gateway = BankGateway.find(params[:id])
render action: 'new', layout: false
end
def create
@bank_gateway = BankGateway.new(params[:bank_gateway])
if @bank_gateway.valid? && @bank_gateway.save
@ -15,11 +20,6 @@ class Admin::BankGatewaysController < Admin::BaseController
end
end
def edit
@bank_gateway = BankGateway.find(params[:id])
render action: 'new', layout: false
end
def update
@bank_gateway = BankGateway.find(params[:id])

View file

@ -1,5 +1,5 @@
class Admin::ConfigsController < Admin::BaseController
before_action :get_tabs, only: [:show, :list]
before_action :get_tabs, only: %i[show list]
def show
@current_tab = @tabs.include?(params[:tab]) ? params[:tab] : @tabs.first
@ -16,7 +16,7 @@ class Admin::ConfigsController < Admin::BaseController
def update
parse_recurring_selects! params[:config][:order_schedule]
ActiveRecord::Base.transaction do
# TODO support nested configuration keys
# TODO: support nested configuration keys
params[:config].each do |key, val|
FoodsoftConfig[key] = convert_config_value val
end
@ -29,7 +29,7 @@ class Admin::ConfigsController < Admin::BaseController
# Set configuration tab names as `@tabs`
def get_tabs
@tabs = %w(foodcoop payment tasks messages layout language security others)
@tabs = %w[foodcoop payment tasks messages layout language security others]
# allow engines to modify this list
engines = Rails::Engine.subclasses.map(&:instance).select { |e| e.respond_to?(:configuration) }
engines.each { |e| e.configuration(@tabs, self) }
@ -38,16 +38,16 @@ class Admin::ConfigsController < Admin::BaseController
# turn recurring rules into something palatable
def parse_recurring_selects!(config)
if config
for k in [:pickup, :boxfill, :ends] do
if config[k]
# allow clearing it using dummy value '{}' ('' would break recurring_select)
if config[k][:recurr].present? && config[k][:recurr] != '{}'
config[k][:recurr] = ActiveSupport::JSON.decode(config[k][:recurr])
config[k][:recurr] = FoodsoftDateUtil.rule_from(config[k][:recurr]).to_ical if config[k][:recurr]
else
config[k] = nil
end
return unless config
for k in %i[pickup boxfill ends] do
if config[k]
# allow clearing it using dummy value '{}' ('' would break recurring_select)
if config[k][:recurr].present? && config[k][:recurr] != '{}'
config[k][:recurr] = ActiveSupport::JSON.decode(config[k][:recurr])
config[k][:recurr] = FoodsoftDateUtil.rule_from(config[k][:recurr]).to_ical if config[k][:recurr]
else
config[k] = nil
end
end
end

View file

@ -10,21 +10,21 @@ class Admin::FinancesController < Admin::BaseController
def update_bank_accounts
@bank_accounts = BankAccount.order('name')
render :layout => false
render layout: false
end
def update_bank_gateways
@bank_gateways = BankGateway.order('name')
render :layout => false
render layout: false
end
def update_transaction_types
@financial_transaction_classes = FinancialTransactionClass.includes(:financial_transaction_types).order('name ASC')
render :layout => false
render layout: false
end
def update_supplier_categories
@supplier_categories = SupplierCategory.order('name')
render :layout => false
render layout: false
end
end

View file

@ -6,25 +6,25 @@ class Admin::FinancialTransactionClassesController < Admin::BaseController
render layout: false
end
def create
@financial_transaction_class = FinancialTransactionClass.new(params[:financial_transaction_class])
if @financial_transaction_class.save
redirect_to update_transaction_types_admin_finances_url, status: 303
else
render action: 'new', layout: false
end
end
def edit
@financial_transaction_class = FinancialTransactionClass.find(params[:id])
render action: 'new', layout: false
end
def create
@financial_transaction_class = FinancialTransactionClass.new(params[:financial_transaction_class])
if @financial_transaction_class.save
redirect_to update_transaction_types_admin_finances_url, status: :see_other
else
render action: 'new', layout: false
end
end
def update
@financial_transaction_class = FinancialTransactionClass.find(params[:id])
if @financial_transaction_class.update(params[:financial_transaction_class])
redirect_to update_transaction_types_admin_finances_url, status: 303
redirect_to update_transaction_types_admin_finances_url, status: :see_other
else
render action: 'new', layout: false
end
@ -33,9 +33,9 @@ class Admin::FinancialTransactionClassesController < Admin::BaseController
def destroy
@financial_transaction_class = FinancialTransactionClass.find(params[:id])
@financial_transaction_class.destroy!
redirect_to update_transaction_types_admin_finances_url, status: 303
rescue => error
flash.now[:alert] = error.message
redirect_to update_transaction_types_admin_finances_url, status: :see_other
rescue StandardError => e
flash.now[:alert] = e.message
render template: 'shared/alert'
end
end

View file

@ -7,25 +7,25 @@ class Admin::FinancialTransactionTypesController < Admin::BaseController
render layout: false
end
def create
@financial_transaction_type = FinancialTransactionType.new(params[:financial_transaction_type])
if @financial_transaction_type.save
redirect_to update_transaction_types_admin_finances_url, status: 303
else
render action: 'new', layout: false
end
end
def edit
@financial_transaction_type = FinancialTransactionType.find(params[:id])
render action: 'new', layout: false
end
def create
@financial_transaction_type = FinancialTransactionType.new(params[:financial_transaction_type])
if @financial_transaction_type.save
redirect_to update_transaction_types_admin_finances_url, status: :see_other
else
render action: 'new', layout: false
end
end
def update
@financial_transaction_type = FinancialTransactionType.find(params[:id])
if @financial_transaction_type.update(params[:financial_transaction_type])
redirect_to update_transaction_types_admin_finances_url, status: 303
redirect_to update_transaction_types_admin_finances_url, status: :see_other
else
render action: 'new', layout: false
end
@ -34,9 +34,9 @@ class Admin::FinancialTransactionTypesController < Admin::BaseController
def destroy
@financial_transaction_type = FinancialTransactionType.find(params[:id])
@financial_transaction_type.destroy!
redirect_to update_transaction_types_admin_finances_url, status: 303
rescue => error
flash.now[:alert] = error.message
redirect_to update_transaction_types_admin_finances_url, status: :see_other
rescue StandardError => e
flash.now[:alert] = e.message
render template: 'shared/alert'
end
end

View file

@ -3,28 +3,28 @@ class Admin::MailDeliveryStatusController < Admin::BaseController
def index
@maildeliverystatus = MailDeliveryStatus.order(created_at: :desc)
@maildeliverystatus = @maildeliverystatus.where(email: params[:email]) unless params[:email].blank?
@maildeliverystatus = @maildeliverystatus.where(email: params[:email]) if params[:email].present?
@maildeliverystatus = @maildeliverystatus.page(params[:page]).per(@per_page)
end
def show
@maildeliverystatus = MailDeliveryStatus.find(params[:id])
filename = "maildeliverystatus_#{params[:id]}.#{MIME::Types[@maildeliverystatus.attachment_mime].first.preferred_extension}"
send_data(@maildeliverystatus.attachment_data, :filename => filename, :type => @maildeliverystatus.attachment_mime)
send_data(@maildeliverystatus.attachment_data, filename: filename, type: @maildeliverystatus.attachment_mime)
end
def destroy_all
@maildeliverystatus = MailDeliveryStatus.delete_all
redirect_to admin_mail_delivery_status_index_path, notice: t('.notice')
rescue => error
redirect_to admin_mail_delivery_status_index_path, alert: I18n.t('errors.general_msg', msg: error.message)
rescue StandardError => e
redirect_to admin_mail_delivery_status_index_path, alert: I18n.t('errors.general_msg', msg: e.message)
end
def destroy
@maildeliverystatus = MailDeliveryStatus.find(params[:id])
@maildeliverystatus.destroy
redirect_to admin_mail_delivery_status_index_path, notice: t('.notice')
rescue => error
redirect_to admin_mail_delivery_status_index_path, alert: I18n.t('errors.general_msg', msg: error.message)
rescue StandardError => e
redirect_to admin_mail_delivery_status_index_path, alert: I18n.t('errors.general_msg', msg: e.message)
end
end

View file

@ -2,16 +2,15 @@ class Admin::OrdergroupsController < Admin::BaseController
inherit_resources
def index
@ordergroups = Ordergroup.undeleted.sort_by_param(params["sort"])
@ordergroups = Ordergroup.undeleted.sort_by_param(params['sort'])
if request.format.csv?
send_data OrdergroupsCsv.new(@ordergroups).to_csv, filename: 'ordergroups.csv', type: 'text/csv'
send_data OrdergroupsCsv.new(@ordergroups).to_csv, filename: 'ordergroups.csv',
type: 'text/csv'
end
# if somebody uses the search field:
unless params[:query].blank?
@ordergroups = @ordergroups.where('name LIKE ?', "%#{params[:query]}%")
end
@ordergroups = @ordergroups.where('name LIKE ?', "%#{params[:query]}%") if params[:query].present?
@ordergroups = @ordergroups.page(params[:page]).per(@per_page)
end
@ -19,8 +18,8 @@ class Admin::OrdergroupsController < Admin::BaseController
def destroy
@ordergroup = Ordergroup.find(params[:id])
@ordergroup.mark_as_deleted
redirect_to admin_ordergroups_url, notice: t('admin.ordergroups.destroy.notice')
rescue => error
redirect_to admin_ordergroups_url, alert: t('admin.ordergroups.destroy.error')
redirect_to admin_ordergroups_url, notice: t('.notice')
rescue StandardError => e
redirect_to admin_ordergroups_url, alert: t('.error')
end
end

View file

@ -6,6 +6,11 @@ class Admin::SupplierCategoriesController < Admin::BaseController
render layout: false
end
def edit
@supplier_category = SupplierCategory.find(params[:id])
render action: 'new', layout: false
end
def create
@supplier_category = SupplierCategory.new(params[:supplier_category])
if @supplier_category.valid? && @supplier_category.save
@ -15,11 +20,6 @@ class Admin::SupplierCategoriesController < Admin::BaseController
end
end
def edit
@supplier_category = SupplierCategory.find(params[:id])
render action: 'new', layout: false
end
def update
@supplier_category = SupplierCategory.find(params[:id])

View file

@ -3,16 +3,14 @@ class Admin::UsersController < Admin::BaseController
def index
@users = params[:show_deleted] ? User.deleted : User.undeleted
@users = @users.sort_by_param(params["sort"])
@users = @users.sort_by_param(params['sort'])
@users = @users.includes(:mail_delivery_status)
if request.format.csv?
send_data UsersCsv.new(@users).to_csv, filename: 'users.csv', type: 'text/csv'
end
send_data UsersCsv.new(@users).to_csv, filename: 'users.csv', type: 'text/csv' if request.format.csv?
# if somebody uses the search field:
@users = @users.natural_search(params[:user_name]) unless params[:user_name].blank?
@users = @users.natural_search(params[:user_name]) if params[:user_name].present?
@users = @users.page(params[:page]).per(@per_page)
end
@ -20,17 +18,17 @@ class Admin::UsersController < Admin::BaseController
def destroy
@user = User.find(params[:id])
@user.mark_as_deleted
redirect_to admin_users_url, notice: t('admin.users.destroy.notice')
rescue => error
redirect_to admin_users_url, alert: t('admin.users.destroy.error', error: error.message)
redirect_to admin_users_url, notice: t('.notice')
rescue StandardError => e
redirect_to admin_users_url, alert: t('.error', error: e.message)
end
def restore
@user = User.find(params[:id])
@user.restore
redirect_to admin_users_url, notice: t('admin.users.restore.notice')
rescue => error
redirect_to admin_users_url, alert: t('admin.users.restore.error', error: error.message)
redirect_to admin_users_url, notice: t('.notice')
rescue StandardError => e
redirect_to admin_users_url, alert: t('.error', error: e.message)
end
def sudo

View file

@ -4,7 +4,7 @@ class Admin::WorkgroupsController < Admin::BaseController
def index
@workgroups = Workgroup.order('name ASC')
# if somebody uses the search field:
@workgroups = @workgroups.where('name LIKE ?', "%#{params[:query]}%") unless params[:query].blank?
@workgroups = @workgroups.where('name LIKE ?', "%#{params[:query]}%") if params[:query].present?
@workgroups = @workgroups.page(params[:page]).per(@per_page)
end
@ -12,8 +12,8 @@ class Admin::WorkgroupsController < Admin::BaseController
def destroy
@workgroup = Workgroup.find(params[:id])
@workgroup.destroy
redirect_to admin_workgroups_url, notice: t('admin.workgroups.destroy.notice')
rescue => error
redirect_to admin_workgroups_url, alert: t('admin.workgroups.destroy.error', error: error.message)
redirect_to admin_workgroups_url, notice: t('.notice')
rescue StandardError => e
redirect_to admin_workgroups_url, alert: t('.error', error: e.message)
end
end

View file

@ -20,29 +20,30 @@ class Api::V1::BaseController < ApplicationController
def require_ordergroup
authenticate
unless current_ordergroup.present?
raise Api::Errors::PermissionRequired.new('Forbidden, must be in an ordergroup')
end
return if current_ordergroup.present?
raise Api::Errors::PermissionRequired, 'Forbidden, must be in an ordergroup'
end
def require_minimum_balance
minimum_balance = FoodsoftConfig[:minimum_balance] or return
if current_ordergroup.account_balance < minimum_balance
raise Api::Errors::PermissionRequired.new(t('application.controller.error_minimum_balance', min: minimum_balance))
end
return unless current_ordergroup.account_balance < minimum_balance
raise Api::Errors::PermissionRequired, t('application.controller.error_minimum_balance', min: minimum_balance)
end
def require_enough_apples
if current_ordergroup.not_enough_apples?
s = t('group_orders.messages.not_enough_apples', apples: current_ordergroup.apples, stop_ordering_under: FoodsoftConfig[:stop_ordering_under])
raise Api::Errors::PermissionRequired.new(s)
end
return unless current_ordergroup.not_enough_apples?
s = t('group_orders.messages.not_enough_apples', apples: current_ordergroup.apples,
stop_ordering_under: FoodsoftConfig[:stop_ordering_under])
raise Api::Errors::PermissionRequired, s
end
def require_config_enabled(config)
unless FoodsoftConfig[config]
raise Api::Errors::PermissionRequired.new(t('application.controller.error_not_enabled', config: config))
end
return if FoodsoftConfig[config]
raise Api::Errors::PermissionRequired, t('application.controller.error_not_enabled', config: config)
end
def skip_session
@ -52,12 +53,12 @@ class Api::V1::BaseController < ApplicationController
def not_found_handler(e)
# remove where-clauses from error message (not suitable for end-users)
msg = e.message.try { |m| m.sub(/\s*\[.*?\]\s*$/, '') } || 'Not found'
render status: 404, json: { error: 'not_found', error_description: msg }
render status: :not_found, json: { error: 'not_found', error_description: msg }
end
def not_acceptable_handler(e)
msg = e.message || 'Data not acceptable'
render status: 422, json: { error: 'not_acceptable', error_description: msg }
render status: :unprocessable_entity, json: { error: 'not_acceptable', error_description: msg }
end
def doorkeeper_unauthorized_render_options(error:)
@ -70,11 +71,11 @@ class Api::V1::BaseController < ApplicationController
def permission_required_handler(e)
msg = e.message || 'Forbidden, user has no access'
render status: 403, json: { error: 'forbidden', error_description: msg }
render status: :forbidden, json: { error: 'forbidden', error_description: msg }
end
# @todo something with ApplicationHelper#show_user
def show_user(user = current_user, **options)
def show_user(user = current_user, **_options)
user.display
end
end

View file

@ -16,7 +16,8 @@ class Api::V1::User::FinancialTransactionsController < Api::V1::BaseController
def create
transaction_type = FinancialTransactionType.find(create_params[:financial_transaction_type_id])
ft = current_ordergroup.add_financial_transaction!(create_params[:amount], create_params[:note], current_user, transaction_type)
ft = current_ordergroup.add_financial_transaction!(create_params[:amount], create_params[:note], current_user,
transaction_type)
render json: ft
end

View file

@ -4,8 +4,8 @@ class Api::V1::User::GroupOrderArticlesController < Api::V1::BaseController
before_action -> { doorkeeper_authorize! 'group_orders:user' }
before_action :require_ordergroup
before_action :require_minimum_balance, only: [:create, :update] # destroy is ok
before_action :require_enough_apples, only: [:create, :update] # destroy is ok
before_action :require_minimum_balance, only: %i[create update] # destroy is ok
before_action :require_enough_apples, only: %i[create update] # destroy is ok
# @todo allow decreasing amounts when minimum balance isn't met
def index
@ -35,7 +35,8 @@ class Api::V1::User::GroupOrderArticlesController < Api::V1::BaseController
goa = nil
GroupOrderArticle.transaction do
goa = scope_for_update.includes(:group_order_article_quantities).find(params.require(:id))
goa.update_quantities((update_params[:quantity] || goa.quantity).to_i, (update_params[:tolerance] || goa.tolerance).to_i)
goa.update_quantities((update_params[:quantity] || goa.quantity).to_i,
(update_params[:tolerance] || goa.tolerance).to_i)
goa.order_article.update_results!
goa.group_order.update_price!
goa.group_order.update!(updated_by: current_user)

View file

@ -8,13 +8,13 @@ class Api::V1::User::OrdergroupController < Api::V1::BaseController
financial_overview: {
account_balance: ordergroup.account_balance.to_f,
available_funds: ordergroup.get_available_funds.to_f,
financial_transaction_class_sums: FinancialTransactionClass.sorted.map { |c|
financial_transaction_class_sums: FinancialTransactionClass.sorted.map do |c|
{
id: c.id,
name: c.display,
amount: ordergroup["sum_of_class_#{c.id}"].to_f
}
}
end
}
}
end

View file

@ -19,10 +19,10 @@ class ApplicationController < ActionController::Base
private
def set_user_last_activity
if current_user && (session[:last_activity] == nil || session[:last_activity] < 1.minutes.ago)
current_user.update_attribute(:last_activity, Time.now)
session[:last_activity] = Time.now
end
return unless current_user && (session[:last_activity].nil? || session[:last_activity] < 1.minute.ago)
current_user.update_attribute(:last_activity, Time.now)
session[:last_activity] = Time.now
end
# Many plugins can be turned on and off on the fly with a `use_` configuration option.
@ -64,11 +64,11 @@ class ApplicationController < ActionController::Base
end
def items_per_page
if params[:per_page] && params[:per_page].to_i > 0 && params[:per_page].to_i <= 500
@per_page = params[:per_page].to_i
else
@per_page = 20
end
@per_page = if params[:per_page] && params[:per_page].to_i > 0 && params[:per_page].to_i <= 500
params[:per_page].to_i
else
20
end
end
# Set timezone according to foodcoop preference.

View file

@ -4,17 +4,17 @@ class ArticleCategoriesController < ApplicationController
before_action :authenticate_article_meta
def create
create!(:notice => I18n.t('article_categories.create.notice')) { article_categories_path }
create!(notice: I18n.t('article_categories.create.notice')) { article_categories_path }
end
def update
update!(:notice => I18n.t('article_categories.update.notice')) { article_categories_path }
update!(notice: I18n.t('article_categories.update.notice')) { article_categories_path }
end
def destroy
destroy!
rescue => error
redirect_to article_categories_path, alert: I18n.t('article_categories.destroy.error', message: error.message)
rescue StandardError => e
redirect_to article_categories_path, alert: I18n.t('article_categories.destroy.error', message: e.message)
end
protected

View file

@ -2,24 +2,24 @@ class ArticlesController < ApplicationController
before_action :authenticate_article_meta, :find_supplier
def index
if params['sort']
sort = case params['sort']
when "name" then "articles.name"
when "unit" then "articles.unit"
when "article_category" then "article_categories.name"
when "note" then "articles.note"
when "availability" then "articles.availability"
when "name_reverse" then "articles.name DESC"
when "unit_reverse" then "articles.unit DESC"
when "article_category_reverse" then "article_categories.name DESC"
when "note_reverse" then "articles.note DESC"
when "availability_reverse" then "articles.availability DESC"
sort = if params['sort']
case params['sort']
when 'name' then 'articles.name'
when 'unit' then 'articles.unit'
when 'article_category' then 'article_categories.name'
when 'note' then 'articles.note'
when 'availability' then 'articles.availability'
when 'name_reverse' then 'articles.name DESC'
when 'unit_reverse' then 'articles.unit DESC'
when 'article_category_reverse' then 'article_categories.name DESC'
when 'note_reverse' then 'articles.note DESC'
when 'availability_reverse' then 'articles.availability DESC'
end
else
sort = "article_categories.name, articles.name"
end
else
'article_categories.name, articles.name'
end
@articles = Article.undeleted.where(supplier_id: @supplier, :type => nil).includes(:article_category).order(sort)
@articles = Article.undeleted.where(supplier_id: @supplier, type: nil).includes(:article_category).order(sort)
if request.format.csv?
send_data ArticlesCsv.new(@articles, encoding: 'utf-8').to_csv, filename: 'articles.csv', type: 'text/csv'
@ -32,42 +32,42 @@ class ArticlesController < ApplicationController
respond_to do |format|
format.html
format.js { render :layout => false }
format.js { render layout: false }
end
end
def new
@article = @supplier.articles.build(:tax => FoodsoftConfig[:tax_default])
render :layout => false
@article = @supplier.articles.build(tax: FoodsoftConfig[:tax_default])
render layout: false
end
def copy
@article = @supplier.articles.find(params[:article_id]).dup
render :layout => false
render layout: false
end
def edit
@article = Article.find(params[:id])
render action: 'new', layout: false
end
def create
@article = Article.new(params[:article])
if @article.valid? && @article.save
render :layout => false
render layout: false
else
render :action => 'new', :layout => false
render action: 'new', layout: false
end
end
def edit
@article = Article.find(params[:id])
render :action => 'new', :layout => false
end
# Updates one Article and highlights the line if succeded
def update
@article = Article.find(params[:id])
if @article.update(params[:article])
render :layout => false
render layout: false
else
render :action => 'new', :layout => false
render action: 'new', layout: false
end
end
@ -75,7 +75,7 @@ class ArticlesController < ApplicationController
def destroy
@article = Article.find(params[:id])
@article.mark_as_deleted unless @order = @article.in_open_order # If article is in an active Order, the Order will be returned
render :layout => false
render layout: false
end
# Renders a form for editing all articles from a supplier
@ -87,19 +87,17 @@ class ArticlesController < ApplicationController
def update_all
invalid_articles = false
begin
Article.transaction do
unless params[:articles].blank?
# Update other article attributes...
@articles = Article.find(params[:articles].keys)
@articles.each do |article|
unless article.update(params[:articles][article.id.to_s])
invalid_articles = true unless invalid_articles # Remember that there are validation errors
end
Article.transaction do
if params[:articles].present?
# Update other article attributes...
@articles = Article.find(params[:articles].keys)
@articles.each do |article|
unless article.update(params[:articles][article.id.to_s])
invalid_articles ||= true # Remember that there are validation errors
end
raise ActiveRecord::Rollback if invalid_articles # Rollback all changes
end
raise ActiveRecord::Rollback if invalid_articles # Rollback all changes
end
end
@ -134,16 +132,15 @@ class ArticlesController < ApplicationController
end
end
# action succeded
redirect_to supplier_articles_url(@supplier, :per_page => params[:per_page])
rescue => error
redirect_to supplier_articles_url(@supplier, :per_page => params[:per_page]),
:alert => I18n.t('errors.general_msg', :msg => error)
redirect_to supplier_articles_url(@supplier, per_page: params[:per_page])
rescue StandardError => e
redirect_to supplier_articles_url(@supplier, per_page: params[:per_page]),
alert: I18n.t('errors.general_msg', msg: e)
end
# lets start with parsing articles from uploaded file, yeah
# Renders the upload form
def upload
end
def upload; end
# Update articles from a spreadsheet
def parse_upload
@ -151,13 +148,15 @@ class ArticlesController < ApplicationController
options = { filename: uploaded_file.original_filename }
options[:outlist_absent] = (params[:articles]['outlist_absent'] == '1')
options[:convert_units] = (params[:articles]['convert_units'] == '1')
@updated_article_pairs, @outlisted_articles, @new_articles = @supplier.sync_from_file uploaded_file.tempfile, options
@updated_article_pairs, @outlisted_articles, @new_articles = @supplier.sync_from_file uploaded_file.tempfile,
options
if @updated_article_pairs.empty? && @outlisted_articles.empty? && @new_articles.empty?
redirect_to supplier_articles_path(@supplier), :notice => I18n.t('articles.controller.parse_upload.notice')
redirect_to supplier_articles_path(@supplier),
notice: I18n.t('articles.controller.parse_upload.notice')
end
@ignored_article_count = 0
rescue => error
redirect_to upload_supplier_articles_path(@supplier), :alert => I18n.t('errors.general_msg', :msg => error.message)
rescue StandardError => e
redirect_to upload_supplier_articles_path(@supplier), alert: I18n.t('errors.general_msg', msg: e.message)
end
# sync all articles with the external database
@ -165,13 +164,14 @@ class ArticlesController < ApplicationController
def sync
# check if there is an shared_supplier
unless @supplier.shared_supplier
redirect_to supplier_articles_url(@supplier), :alert => I18n.t('articles.controller.sync.shared_alert', :supplier => @supplier.name)
redirect_to supplier_articles_url(@supplier),
alert: I18n.t('articles.controller.sync.shared_alert', supplier: @supplier.name)
end
# sync articles against external database
@updated_article_pairs, @outlisted_articles, @new_articles = @supplier.sync_all
if @updated_article_pairs.empty? && @outlisted_articles.empty? && @new_articles.empty?
redirect_to supplier_articles_path(@supplier), :notice => I18n.t('articles.controller.sync.notice')
end
return unless @updated_article_pairs.empty? && @outlisted_articles.empty? && @new_articles.empty?
redirect_to supplier_articles_path(@supplier), notice: I18n.t('articles.controller.sync.notice')
end
# Updates, deletes articles when upload or sync form is submitted
@ -186,7 +186,7 @@ class ArticlesController < ApplicationController
# delete articles
begin
@outlisted_articles.each(&:mark_as_deleted)
rescue
rescue StandardError
# raises an exception when used in current order
has_error = true
end
@ -198,15 +198,15 @@ class ArticlesController < ApplicationController
raise ActiveRecord::Rollback if has_error
end
if !has_error
redirect_to supplier_articles_path(@supplier), notice: I18n.t('articles.controller.update_sync.notice')
else
if has_error
@updated_article_pairs = @updated_articles.map do |article|
orig_article = Article.find(article.id)
[article, orig_article.unequal_attributes(article)]
end
flash.now.alert = I18n.t('articles.controller.error_invalid')
render params[:from_action] == 'sync' ? :sync : :parse_upload
else
redirect_to supplier_articles_path(@supplier), notice: I18n.t('articles.controller.update_sync.notice')
end
end
@ -218,18 +218,18 @@ class ArticlesController < ApplicationController
q[:name_cont_all] = params.fetch(:name_cont_all_joined, '').split(' ')
search = @supplier.shared_supplier.shared_articles.ransack(q)
@articles = search.result.page(params[:page]).per(10)
render :layout => false
render layout: false
end
# fills a form whith values of the selected shared_article
# when the direct parameter is set and the article is valid, it is imported directly
def import
@article = SharedArticle.find(params[:shared_article_id]).build_new_article(@supplier)
@article.article_category_id = params[:article_category_id] unless params[:article_category_id].blank?
if params[:direct] && !params[:article_category_id].blank? && @article.valid? && @article.save
render :action => 'create', :layout => false
@article.article_category_id = params[:article_category_id] if params[:article_category_id].present?
if params[:direct] && params[:article_category_id].present? && @article.valid? && @article.save
render action: 'create', layout: false
else
render :action => 'new', :layout => false
render action: 'new', layout: false
end
end

View file

@ -9,15 +9,19 @@ module Concerns::Auth
def current_user
# check if there is a valid session and return the logged-in user (its object)
if session[:user_id] && params[:foodcoop]
# for shared-host installations. check if the cookie-subdomain fits to request.
@current_user ||= User.undeleted.find_by_id(session[:user_id]) if session[:scope] == FoodsoftConfig.scope
end
return unless session[:user_id] && params[:foodcoop]
# for shared-host installations. check if the cookie-subdomain fits to request.
@current_user ||= User.undeleted.find_by_id(session[:user_id]) if session[:scope] == FoodsoftConfig.scope
end
def deny_access
session[:return_to] = request.original_url
redirect_to root_url, alert: I18n.t('application.controller.error_denied', sign_in: ActionController::Base.helpers.link_to(t('application.controller.error_denied_sign_in'), login_path))
redirect_to root_url,
alert: I18n.t('application.controller.error_denied',
sign_in: ActionController::Base.helpers.link_to(
t('application.controller.error_denied_sign_in'), login_path
))
end
private
@ -47,12 +51,7 @@ module Concerns::Auth
def authenticate(role = 'any')
# Attempt to retrieve authenticated user from controller instance or session...
if !current_user
# No user at all: redirect to login page.
logout
session[:return_to] = request.original_url
redirect_to_login :alert => I18n.t('application.controller.error_authn')
else
if current_user
# We have an authenticated user, now check role...
# Roles gets the user through his memberships.
hasRole = case role
@ -73,6 +72,11 @@ module Concerns::Auth
else
deny_access
end
else
# No user at all: redirect to login page.
logout
session[:return_to] = request.original_url
redirect_to_login alert: I18n.t('application.controller.error_authn')
end
end
@ -116,13 +120,13 @@ module Concerns::Auth
# if fails the user will redirected to startpage
def authenticate_membership_or_admin(group_id = params[:id])
@group = Group.find(group_id)
unless @group.member?(@current_user) || @current_user.role_admin?
redirect_to root_path, alert: I18n.t('application.controller.error_members_only')
end
return if @group.member?(@current_user) || @current_user.role_admin?
redirect_to root_path, alert: I18n.t('application.controller.error_members_only')
end
def authenticate_or_token(prefix, role = 'any')
if not params[:token].blank?
if params[:token].present?
begin
TokenVerifier.new(prefix).verify(params[:token])
rescue ActiveSupport::MessageVerifier::InvalidSignature

View file

@ -36,9 +36,9 @@ module Concerns::AuthApi
# Make sure that at least one the given OAuth scopes is valid for the current user's permissions.
# @raise Api::Errors::PermissionsRequired
def doorkeeper_authorize_roles!(*scopes)
unless scopes.any? { |scope| doorkeeper_scope_permitted?(scope) }
raise Api::Errors::PermissionRequired.new('Forbidden, no permission')
end
return if scopes.any? { |scope| doorkeeper_scope_permitted?(scope) }
raise Api::Errors::PermissionRequired, 'Forbidden, no permission'
end
# Check whether a given OAuth scope is permitted for the current user.
@ -48,9 +48,7 @@ module Concerns::AuthApi
def doorkeeper_scope_permitted?(scope)
scope_parts = scope.split(':')
# user sub-scopes like +config:user+ are always permitted
if scope_parts.last == 'user'
return true
end
return true if scope_parts.last == 'user'
case scope_parts.first
when 'user' then return true # access to the current user's own profile
@ -64,8 +62,8 @@ module Concerns::AuthApi
end
case scope
when 'orders:read' then return true
when 'orders:write' then return current_user.role_orders?
when 'orders:read' then true
when 'orders:write' then current_user.role_orders?
end
end
end

View file

@ -24,12 +24,12 @@ module Concerns::FoodcoopScope
elsif FoodsoftConfig.allowed_foodcoop? foodcoop
FoodsoftConfig.select_foodcoop foodcoop
else
raise ActionController::RoutingError.new 'Foodcoop Not Found'
raise ActionController::RoutingError, 'Foodcoop Not Found'
end
end
# Always stay in foodcoop url scope
def default_url_options(options = {})
def default_url_options(_options = {})
super().merge({ foodcoop: FoodsoftConfig.scope })
end
end

View file

@ -18,7 +18,7 @@ module Concerns::Locale
end
def browser_language
request.env['HTTP_ACCEPT_LANGUAGE'] ? request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first : nil
request.env['HTTP_ACCEPT_LANGUAGE']&.scan(/^[a-z]{2}/)&.first
end
def default_language
@ -30,7 +30,7 @@ module Concerns::Locale
def select_language_according_to_priority
language = explicitly_requested_language || session_language || user_settings_language
language ||= browser_language unless FoodsoftConfig[:ignore_browser_locale]
language.presence&.to_sym unless language.blank?
language.presence&.to_sym if language.present?
end
def available_locales
@ -38,11 +38,11 @@ module Concerns::Locale
end
def set_locale
if available_locales.include?(select_language_according_to_priority)
::I18n.locale = select_language_according_to_priority
else
::I18n.locale = default_language
end
::I18n.locale = if available_locales.include?(select_language_according_to_priority)
select_language_according_to_priority
else
default_language
end
locale = session[:locale] = ::I18n.locale
logger.info("Set locale to #{locale}")

View file

@ -3,7 +3,7 @@ module Concerns::SendOrderPdf
protected
def send_order_pdf order, document
def send_order_pdf(order, document)
klass = case document
when 'groups' then OrderByGroups
when 'articles' then OrderByArticles

View file

@ -1,5 +1,5 @@
class DeliveriesController < ApplicationController
before_action :find_supplier, :exclude => :fill_new_stock_article_form
before_action :find_supplier, exclude: :fill_new_stock_article_form
def index
@deliveries = @supplier.deliveries.order('date DESC')
@ -15,6 +15,10 @@ class DeliveriesController < ApplicationController
@delivery.date = Date.today # TODO: move to model/database
end
def edit
@delivery = Delivery.find(params[:id])
end
def create
@delivery = Delivery.new(params[:delivery])
@ -22,14 +26,10 @@ class DeliveriesController < ApplicationController
flash[:notice] = I18n.t('deliveries.create.notice')
redirect_to [@supplier, @delivery]
else
render :action => "new"
render action: 'new'
end
end
def edit
@delivery = Delivery.find(params[:id])
end
def update
@delivery = Delivery.find(params[:id])
@ -37,7 +37,7 @@ class DeliveriesController < ApplicationController
flash[:notice] = I18n.t('deliveries.update.notice')
redirect_to [@supplier, @delivery]
else
render :action => "edit"
render action: 'edit'
end
end
@ -52,18 +52,18 @@ class DeliveriesController < ApplicationController
def add_stock_change
@stock_change = StockChange.new
@stock_change.stock_article = StockArticle.find(params[:stock_article_id])
render :layout => false
render layout: false
end
def form_on_stock_article_create # See publish/subscribe design pattern in /doc.
@stock_article = StockArticle.find(params[:id])
render :layout => false
render layout: false
end
def form_on_stock_article_update # See publish/subscribe design pattern in /doc.
@stock_article = StockArticle.find(params[:id])
render :layout => false
render layout: false
end
end

View file

@ -1,13 +1,12 @@
class FeedbackController < ApplicationController
def new
end
def new; end
def create
if params[:message].present?
Mailer.feedback(current_user, params[:message]).deliver_now
redirect_to root_url, notice: t('feedback.create.notice')
redirect_to root_url, notice: t('.notice')
else
render :action => 'new'
render action: 'new'
end
end
end

View file

@ -5,7 +5,7 @@ class Finance::BalancingController < Finance::BaseController
def new
@order = Order.find(params[:order_id])
flash.now.alert = t('finance.balancing.new.alert') if @order.closed?
flash.now.alert = t('.alert') if @order.closed?
@comments = @order.comments
@articles = @order.order_articles.ordered_or_member.includes(:article, :article_price,
@ -13,13 +13,13 @@ class Finance::BalancingController < Finance::BaseController
sort_param = params['sort'] || 'name'
@articles = case sort_param
when 'name' then
when 'name'
@articles.order('articles.name ASC')
when 'name_reverse' then
when 'name_reverse'
@articles.order('articles.name DESC')
when 'order_number' then
when 'order_number'
@articles.order('articles.order_number ASC')
when 'order_number_reverse' then
when 'order_number_reverse'
@articles.order('articles.order_number DESC')
else
@articles
@ -31,13 +31,13 @@ class Finance::BalancingController < Finance::BaseController
def new_on_order_article_create # See publish/subscribe design pattern in /doc.
@order_article = OrderArticle.find(params[:order_article_id])
render :layout => false
render layout: false
end
def new_on_order_article_update # See publish/subscribe design pattern in /doc.
@order_article = OrderArticle.find(params[:order_article_id])
render :layout => false
render layout: false
end
def update_summary
@ -46,29 +46,29 @@ class Finance::BalancingController < Finance::BaseController
def edit_note
@order = Order.find(params[:id])
render :layout => false
render layout: false
end
def update_note
@order = Order.find(params[:id])
if @order.update(params[:order])
render :layout => false
render layout: false
else
render :action => :edit_note, :layout => false
render action: :edit_note, layout: false
end
end
def edit_transport
@order = Order.find(params[:id])
render :layout => false
render layout: false
end
def update_transport
@order = Order.find(params[:id])
@order.update!(params[:order])
redirect_to new_finance_order_path(order_id: @order.id)
rescue => error
redirect_to new_finance_order_path(order_id: @order.id), alert: t('errors.general_msg', msg: error.message)
rescue StandardError => e
redirect_to new_finance_order_path(order_id: @order.id), alert: t('errors.general_msg', msg: e.message)
end
# before the order will booked, a view lists all Ordergroups and its order_prices
@ -81,18 +81,18 @@ class Finance::BalancingController < Finance::BaseController
@order = Order.find(params[:id])
@type = FinancialTransactionType.find_by_id(params.permit(:type)[:type])
@order.close!(@current_user, @type)
redirect_to finance_order_index_url, notice: t('finance.balancing.close.notice')
rescue => error
redirect_to new_finance_order_url(order_id: @order.id), alert: t('finance.balancing.close.alert', message: error.message)
redirect_to finance_order_index_url, notice: t('.notice')
rescue StandardError => e
redirect_to new_finance_order_url(order_id: @order.id), alert: t('.alert', message: e.message)
end
# Close the order directly, without automaticly updating ordergroups account balances
def close_direct
@order = Order.find(params[:id])
@order.close_direct!(@current_user)
redirect_to finance_order_index_url, notice: t('finance.balancing.close_direct.notice')
rescue => error
redirect_to finance_order_index_url, alert: t('finance.balancing.close_direct.alert', message: error.message)
redirect_to finance_order_index_url, notice: t('.notice')
rescue StandardError => e
redirect_to finance_order_index_url, alert: t('.alert', message: e.message)
end
def close_all_direct_with_invoice
@ -103,8 +103,8 @@ class Finance::BalancingController < Finance::BaseController
count += 1
end
end
redirect_to finance_order_index_url, notice: t('finance.balancing.close_all_direct_with_invoice.notice', count: count)
rescue => error
redirect_to finance_order_index_url, alert: t('errors.general_msg', msg: error.message)
redirect_to finance_order_index_url, notice: t('.notice', count: count)
rescue StandardError => e
redirect_to finance_order_index_url, alert: t('errors.general_msg', msg: e.message)
end
end

View file

@ -8,8 +8,8 @@ class Finance::BankAccountsController < Finance::BaseController
@bank_account = BankAccount.find(params[:id])
count = @bank_account.assign_unlinked_transactions
redirect_to finance_bank_account_transactions_url(@bank_account), notice: t('.notice', count: count)
rescue => error
redirect_to finance_bank_account_transactions_url(@bank_account), alert: t('errors.general_msg', msg: error.message)
rescue StandardError => e
redirect_to finance_bank_account_transactions_url(@bank_account), alert: t('errors.general_msg', msg: e.message)
end
def import
@ -33,8 +33,8 @@ class Finance::BankAccountsController < Finance::BaseController
end
needs_redirect = ok
rescue => error
flash.alert = t('errors.general_msg', msg: error.message)
rescue StandardError => e
flash.alert = t('errors.general_msg', msg: e.message)
needs_redirect = true
ensure
return unless needs_redirect

View file

@ -3,26 +3,30 @@ class Finance::BankTransactionsController < ApplicationController
inherit_resources
def index
if params["sort"]
sort = case params["sort"]
when "date" then "date"
when "amount" then "amount"
when "financial_link" then "financial_link_id"
when "date_reverse" then "date DESC"
when "amount_reverse" then "amount DESC"
when "financial_link_reverse" then "financial_link_id DESC"
sort = if params['sort']
case params['sort']
when 'date' then 'date'
when 'amount' then 'amount'
when 'financial_link' then 'financial_link_id'
when 'date_reverse' then 'date DESC'
when 'amount_reverse' then 'amount DESC'
when 'financial_link_reverse' then 'financial_link_id DESC'
end
else
sort = "date DESC"
end
else
'date DESC'
end
@bank_account = BankAccount.find(params[:bank_account_id])
@bank_transactions_all = @bank_account.bank_transactions.order(sort).includes(:financial_link)
@bank_transactions_all = @bank_transactions_all.where('reference LIKE ? OR text LIKE ?', "%#{params[:query]}%", "%#{params[:query]}%") unless params[:query].nil?
unless params[:query].nil?
@bank_transactions_all = @bank_transactions_all.where('reference LIKE ? OR text LIKE ?', "%#{params[:query]}%",
"%#{params[:query]}%")
end
@bank_transactions = @bank_transactions_all.page(params[:page]).per(@per_page)
respond_to do |format|
format.js; format.html { render }
format.js
format.html { render }
format.csv do
send_data BankTransactionsCsv.new(@bank_transactions_all).to_csv, filename: 'transactions.csv', type: 'text/csv'
end

View file

@ -1,5 +1,5 @@
class Finance::FinancialLinksController < Finance::BaseController
before_action :find_financial_link, except: [:create, :incomplete]
before_action :find_financial_link, except: %i[create incomplete]
def show
@items = @financial_link.bank_transactions.map do |bt|
@ -37,7 +37,7 @@ class Finance::FinancialLinksController < Finance::BaseController
def create
@financial_link = FinancialLink.first_unused_or_create
if params[:bank_transaction] then
if params[:bank_transaction]
bank_transaction = BankTransaction.find(params[:bank_transaction])
bank_transaction.update_attribute :financial_link, @financial_link
end
@ -72,14 +72,16 @@ class Finance::FinancialLinksController < Finance::BaseController
def create_financial_transaction
financial_transaction = FinancialTransaction.new(financial_transaction_params)
financial_transaction.ordergroup.add_financial_transaction! financial_transaction.amount, financial_transaction.note, current_user, financial_transaction.financial_transaction_type, @financial_link
financial_transaction.ordergroup.add_financial_transaction! financial_transaction.amount,
financial_transaction.note, current_user, financial_transaction.financial_transaction_type, @financial_link
redirect_to finance_link_url(@financial_link), notice: t('.notice')
rescue => error
redirect_to finance_link_url(@financial_link), alert: t('errors.general_msg', msg: error)
rescue StandardError => e
redirect_to finance_link_url(@financial_link), alert: t('errors.general_msg', msg: e)
end
def index_financial_transaction
@financial_transactions = FinancialTransaction.without_financial_link.includes(:financial_transaction_type, :ordergroup)
@financial_transactions = FinancialTransaction.without_financial_link.includes(:financial_transaction_type,
:ordergroup)
end
def add_financial_transaction
@ -123,7 +125,7 @@ class Finance::FinancialLinksController < Finance::BaseController
end
def find_best_fitting_ordergroup_id_for_financial_link(financial_link_id)
FinancialTransaction.joins(<<-SQL).order(created_on: :desc).pluck(:ordergroup_id).first
FinancialTransaction.joins(<<-SQL).order(created_on: :desc).pick(:ordergroup_id)
JOIN bank_transactions a ON financial_transactions.financial_link_id = a.financial_link_id
JOIN bank_transactions b ON a.iban = b.iban AND b.financial_link_id = #{financial_link_id.to_i}
SQL

View file

@ -1,22 +1,22 @@
class Finance::FinancialTransactionsController < ApplicationController
before_action :authenticate_finance
before_action :find_ordergroup, :except => [:new_collection, :create_collection, :index_collection]
before_action :find_ordergroup, except: %i[new_collection create_collection index_collection]
inherit_resources
# belongs_to :ordergroup
def index
if params['sort']
sort = case params['sort']
when "date" then "created_on"
when "note" then "note"
when "amount" then "amount"
when "date_reverse" then "created_on DESC"
when "note_reverse" then "note DESC"
when "amount_reverse" then "amount DESC"
sort = if params['sort']
case params['sort']
when 'date' then 'created_on'
when 'note' then 'note'
when 'amount' then 'amount'
when 'date_reverse' then 'created_on DESC'
when 'note_reverse' then 'note DESC'
when 'amount_reverse' then 'amount DESC'
end
else
sort = "created_on DESC"
end
else
'created_on DESC'
end
@q = FinancialTransaction.ransack(params[:q])
@financial_transactions_all = @q.result(distinct: true).includes(:user).order(sort)
@ -26,9 +26,11 @@ class Finance::FinancialTransactionsController < ApplicationController
@financial_transactions = @financial_transactions_all.page(params[:page]).per(@per_page)
respond_to do |format|
format.js; format.html { render }
format.js
format.html { render }
format.csv do
send_data FinancialTransactionsCsv.new(@financial_transactions_all).to_csv, filename: 'transactions.csv', type: 'text/csv'
send_data FinancialTransactionsCsv.new(@financial_transactions_all).to_csv, filename: 'transactions.csv',
type: 'text/csv'
end
end
end
@ -38,11 +40,11 @@ class Finance::FinancialTransactionsController < ApplicationController
end
def new
if @ordergroup
@financial_transaction = @ordergroup.financial_transactions.build
else
@financial_transaction = FinancialTransaction.new
end
@financial_transaction = if @ordergroup
@ordergroup.financial_transactions.build
else
FinancialTransaction.new
end
end
def create
@ -53,16 +55,18 @@ class Finance::FinancialTransactionsController < ApplicationController
else
@financial_transaction.save!
end
redirect_to finance_group_transactions_path(@ordergroup), notice: I18n.t('finance.financial_transactions.controller.create.notice')
rescue ActiveRecord::RecordInvalid => error
flash.now[:alert] = error.message
render :action => :new
redirect_to finance_group_transactions_path(@ordergroup),
notice: I18n.t('finance.financial_transactions.controller.create.notice')
rescue ActiveRecord::RecordInvalid => e
flash.now[:alert] = e.message
render action: :new
end
def destroy
transaction = FinancialTransaction.find(params[:id])
transaction.revert!(current_user)
redirect_to finance_group_transactions_path(transaction.ordergroup), notice: t('finance.financial_transactions.controller.destroy.notice')
redirect_to finance_group_transactions_path(transaction.ordergroup),
notice: t('finance.financial_transactions.controller.destroy.notice')
end
def new_collection
@ -88,17 +92,17 @@ class Finance::FinancialTransactionsController < ApplicationController
params[:financial_transactions].each do |trans|
# ignore empty amount fields ...
unless trans[:amount].blank?
amount = LocalizeInput.parse(trans[:amount]).to_f
note = params[:note]
ordergroup = Ordergroup.find(trans[:ordergroup_id])
if params[:set_balance]
note += " (#{amount})"
amount -= ordergroup.financial_transaction_class_balance(type.financial_transaction_class)
end
ordergroup.add_financial_transaction!(amount, note, @current_user, type, financial_link)
foodcoop_amount -= amount
next if trans[:amount].blank?
amount = LocalizeInput.parse(trans[:amount]).to_f
note = params[:note]
ordergroup = Ordergroup.find(trans[:ordergroup_id])
if params[:set_balance]
note += " (#{amount})"
amount -= ordergroup.financial_transaction_class_balance(type.financial_transaction_class)
end
ordergroup.add_financial_transaction!(amount, note, @current_user, type, financial_link)
foodcoop_amount -= amount
end
if params[:create_foodcoop_transaction]
@ -107,7 +111,7 @@ class Finance::FinancialTransactionsController < ApplicationController
user: @current_user,
amount: foodcoop_amount,
note: params[:note],
financial_link: financial_link,
financial_link: financial_link
})
ft.save!
end
@ -117,8 +121,8 @@ class Finance::FinancialTransactionsController < ApplicationController
url = financial_link ? finance_link_url(financial_link.id) : finance_ordergroups_url
redirect_to url, notice: I18n.t('finance.financial_transactions.controller.create_collection.notice')
rescue => error
flash.now[:alert] = error.message
rescue StandardError => e
flash.now[:alert] = e.message
render action: :new_collection
end

View file

@ -1,15 +1,16 @@
class Finance::InvoicesController < ApplicationController
before_action :authenticate_finance_or_invoices
before_action :find_invoice, only: [:show, :edit, :update, :destroy]
before_action :ensure_can_edit, only: [:edit, :update, :destroy]
before_action :find_invoice, only: %i[show edit update destroy]
before_action :ensure_can_edit, only: %i[edit update destroy]
def index
@invoices_all = Invoice.includes(:supplier, :deliveries, :orders).order('date DESC')
@invoices = @invoices_all.page(params[:page]).per(@per_page)
respond_to do |format|
format.js; format.html { render }
format.js
format.html { render }
format.csv do
send_data InvoicesCsv.new(@invoices_all).to_csv, filename: 'invoices.csv', type: 'text/csv'
end
@ -20,11 +21,10 @@ class Finance::InvoicesController < ApplicationController
@suppliers = Supplier.includes(:invoices).where('invoices.paid_on IS NULL').references(:invoices)
end
def show
end
def show; end
def new
@invoice = Invoice.new :supplier_id => params[:supplier_id]
@invoice = Invoice.new supplier_id: params[:supplier_id]
@invoice.deliveries << Delivery.find_by_id(params[:delivery_id]) if params[:delivery_id]
@invoice.orders << Order.find_by_id(params[:order_id]) if params[:order_id]
fill_deliveries_and_orders_collection @invoice.id, @invoice.supplier_id
@ -36,12 +36,14 @@ class Finance::InvoicesController < ApplicationController
def form_on_supplier_id_change
fill_deliveries_and_orders_collection params[:invoice_id], params[:supplier_id]
render :layout => false
render layout: false
end
def fill_deliveries_and_orders_collection(invoice_id, supplier_id)
@deliveries_collection = Delivery.where('invoice_id = ? OR (invoice_id IS NULL AND supplier_id = ?)', invoice_id, supplier_id).order(date: :desc).limit(25)
@orders_collection = Order.where('invoice_id = ? OR (invoice_id IS NULL AND supplier_id = ?)', invoice_id, supplier_id).order(ends: :desc).limit(25)
@deliveries_collection = Delivery.where('invoice_id = ? OR (invoice_id IS NULL AND supplier_id = ?)', invoice_id,
supplier_id).order(date: :desc).limit(25)
@orders_collection = Order.where('invoice_id = ? OR (invoice_id IS NULL AND supplier_id = ?)', invoice_id,
supplier_id).order(ends: :desc).limit(25)
end
def create
@ -58,7 +60,7 @@ class Finance::InvoicesController < ApplicationController
end
else
fill_deliveries_and_orders_collection @invoice.id, @invoice.supplier_id
render :action => "new"
render action: 'new'
end
end
@ -81,7 +83,7 @@ class Finance::InvoicesController < ApplicationController
@invoice = Invoice.find(params[:invoice_id])
type = MIME::Types[@invoice.attachment_mime].first
filename = "invoice_#{@invoice.id}_attachment.#{type.preferred_extension}"
send_data(@invoice.attachment_data, :filename => filename, :type => type)
send_data(@invoice.attachment_data, filename: filename, type: type)
end
private
@ -92,8 +94,8 @@ class Finance::InvoicesController < ApplicationController
# Returns true if @current_user can edit the invoice..
def ensure_can_edit
unless @invoice.user_can_edit?(current_user)
deny_access
end
return if @invoice.user_can_edit?(current_user)
deny_access
end
end

View file

@ -1,11 +1,11 @@
class Finance::OrdergroupsController < Finance::BaseController
def index
m = /^(?<col>name|sum_of_class_\d+)(?<reverse>_reverse)?$/.match params["sort"]
m = /^(?<col>name|sum_of_class_\d+)(?<reverse>_reverse)?$/.match params['sort']
if m
sort = m[:col]
sort += ' DESC' if m[:reverse]
else
sort = "name"
sort = 'name'
end
@ordergroups = Ordergroup.undeleted.order(sort)

View file

@ -1,20 +1,16 @@
class Foodcoop::OrdergroupsController < ApplicationController
def index
@ordergroups = Ordergroup.undeleted.sort_by_param(params["sort"])
@ordergroups = Ordergroup.undeleted.sort_by_param(params['sort'])
unless params[:name].blank? # Search by name
@ordergroups = @ordergroups.where('name LIKE ?', "%#{params[:name]}%")
end
@ordergroups = @ordergroups.where('name LIKE ?', "%#{params[:name]}%") if params[:name].present? # Search by name
if params[:only_active] # Select only active groups
@ordergroups = @ordergroups.active
end
@ordergroups = @ordergroups.active if params[:only_active] # Select only active groups
@ordergroups = @ordergroups.page(params[:page]).per(@per_page)
respond_to do |format|
format.html # index.html.erb
format.js { render :layout => false }
format.js { render layout: false }
end
end
end

View file

@ -1,19 +1,20 @@
class Foodcoop::UsersController < ApplicationController
def index
@users = User.undeleted.sort_by_param(params["sort"])
@users = User.undeleted.sort_by_param(params['sort'])
# if somebody uses the search field:
@users = @users.natural_search(params[:user_name]) unless params[:user_name].blank?
@users = @users.natural_search(params[:user_name]) if params[:user_name].present?
if params[:ordergroup_name]
@users = @users.joins(:groups).where("groups.type = 'Ordergroup' AND groups.name LIKE ?", "%#{params[:ordergroup_name]}%")
@users = @users.joins(:groups).where("groups.type = 'Ordergroup' AND groups.name LIKE ?",
"%#{params[:ordergroup_name]}%")
end
@users = @users.page(params[:page]).per(@per_page)
respond_to do |format|
format.html # index.html.haml
format.js { render :layout => false } # index.js.erb
format.js { render layout: false } # index.js.erb
end
end
end

View file

@ -1,9 +1,9 @@
class Foodcoop::WorkgroupsController < ApplicationController
before_action :authenticate_membership_or_admin,
:except => [:index]
except: [:index]
def index
@workgroups = Workgroup.order("name")
@workgroups = Workgroup.order('name')
end
def edit
@ -13,9 +13,9 @@ class Foodcoop::WorkgroupsController < ApplicationController
def update
@workgroup = Workgroup.find(params[:id])
if @workgroup.update(params[:workgroup])
redirect_to foodcoop_workgroups_url, :notice => I18n.t('workgroups.update.notice')
redirect_to foodcoop_workgroups_url, notice: I18n.t('workgroups.update.notice')
else
render :action => 'edit'
render action: 'edit'
end
end
end

View file

@ -1,6 +1,6 @@
class GroupOrderArticlesController < ApplicationController
before_action :authenticate_finance
before_action :find_group_order_article, except: [:new, :create]
before_action :find_group_order_article, except: %i[new create]
layout false # We only use this controller to server js snippets, no need for layout rendering

View file

@ -3,9 +3,9 @@
class GroupOrdersController < ApplicationController
# Security
before_action :ensure_ordergroup_member
before_action :ensure_open_order, :only => [:new, :create, :edit, :update, :order, :stock_order, :saveOrder]
before_action :ensure_my_group_order, only: [:show, :edit, :update]
before_action :enough_apples?, only: [:new, :create]
before_action :ensure_open_order, only: %i[new create edit update order stock_order saveOrder]
before_action :ensure_my_group_order, only: %i[show edit update]
before_action :enough_apples?, only: %i[new create]
# Index page.
def index
@ -13,9 +13,17 @@ class GroupOrdersController < ApplicationController
@finished_not_closed_orders_including_group_order = Order.finished_not_closed.ordergroup_group_orders_map(@ordergroup)
end
def show
@order = @group_order.order
end
def new
ordergroup = params[:stock_order] ? nil : @ordergroup
@group_order = @order.group_orders.build(:ordergroup => ordergroup, :updated_by => current_user)
@group_order = @order.group_orders.build(ordergroup: ordergroup, updated_by: current_user)
@ordering_data = @group_order.load_data
end
def edit
@ordering_data = @group_order.load_data
end
@ -23,34 +31,26 @@ class GroupOrdersController < ApplicationController
@group_order = GroupOrder.new(params[:group_order])
begin
@group_order.save_ordering!
redirect_to group_order_url(@group_order), :notice => I18n.t('group_orders.create.notice')
redirect_to group_order_url(@group_order), notice: I18n.t('group_orders.create.notice')
rescue ActiveRecord::StaleObjectError
redirect_to group_orders_url, :alert => I18n.t('group_orders.create.error_stale')
rescue => exception
logger.error('Failed to update order: ' + exception.message)
redirect_to group_orders_url, :alert => I18n.t('group_orders.create.error_general')
redirect_to group_orders_url, alert: I18n.t('group_orders.create.error_stale')
rescue StandardError => e
logger.error('Failed to update order: ' + e.message)
redirect_to group_orders_url, alert: I18n.t('group_orders.create.error_general')
end
end
def show
@order = @group_order.order
end
def edit
@ordering_data = @group_order.load_data
end
def update
@group_order.attributes = params[:group_order]
@group_order.updated_by = current_user
begin
@group_order.save_ordering!
redirect_to group_order_url(@group_order), :notice => I18n.t('group_orders.update.notice')
redirect_to group_order_url(@group_order), notice: I18n.t('group_orders.update.notice')
rescue ActiveRecord::StaleObjectError
redirect_to group_orders_url, :alert => I18n.t('group_orders.update.error_stale')
rescue => exception
logger.error('Failed to update order: ' + exception.message)
redirect_to group_orders_url, :alert => I18n.t('group_orders.update.error_general')
redirect_to group_orders_url, alert: I18n.t('group_orders.update.error_stale')
rescue StandardError => e
logger.error('Failed to update order: ' + e.message)
redirect_to group_orders_url, alert: I18n.t('group_orders.update.error_general')
end
end
@ -74,16 +74,16 @@ class GroupOrdersController < ApplicationController
# Used as a :before_action by OrdersController.
def ensure_ordergroup_member
@ordergroup = @current_user.ordergroup
if @ordergroup.nil?
redirect_to root_url, :alert => I18n.t('group_orders.errors.no_member')
end
return unless @ordergroup.nil?
redirect_to root_url, alert: I18n.t('group_orders.errors.no_member')
end
def ensure_open_order
@order = Order.includes([:supplier, :order_articles]).find(order_id_param)
@order = Order.includes(%i[supplier order_articles]).find(order_id_param)
unless @order.open?
flash[:notice] = I18n.t('group_orders.errors.closed')
redirect_to :action => 'index'
redirect_to action: 'index'
end
rescue ActiveRecord::RecordNotFound
redirect_to group_orders_url, alert: I18n.t('group_orders.errors.notfound')
@ -91,17 +91,17 @@ class GroupOrdersController < ApplicationController
def ensure_my_group_order
@group_order = GroupOrder.find(params[:id])
if @group_order.ordergroup != @ordergroup && (@group_order.ordergroup || !current_user.role_orders?)
redirect_to group_orders_url, alert: I18n.t('group_orders.errors.notfound')
end
return unless @group_order.ordergroup != @ordergroup && (@group_order.ordergroup || !current_user.role_orders?)
redirect_to group_orders_url, alert: I18n.t('group_orders.errors.notfound')
end
def enough_apples?
if @ordergroup.not_enough_apples?
redirect_to group_orders_url,
alert: t('not_enough_apples', scope: 'group_orders.messages', apples: @ordergroup.apples,
stop_ordering_under: FoodsoftConfig[:stop_ordering_under])
end
return unless @ordergroup.not_enough_apples?
redirect_to group_orders_url,
alert: t('not_enough_apples', scope: 'group_orders.messages', apples: @ordergroup.apples,
stop_ordering_under: FoodsoftConfig[:stop_ordering_under])
end
def order_id_param

View file

@ -9,8 +9,7 @@ class HomeController < ApplicationController
@unassigned_tasks = Task.order(:due_date).next_unassigned_tasks_for(current_user)
end
def profile
end
def profile; end
def reference_calculator
if current_user.ordergroup
@ -36,40 +35,43 @@ class HomeController < ApplicationController
@user = @current_user
@ordergroup = @user.ordergroup
unless @ordergroup.nil?
if @ordergroup.nil?
redirect_to root_path, alert: I18n.t('home.no_ordergroups')
else
@ordergroup = Ordergroup.include_transaction_class_sum.find(@ordergroup.id)
if params['sort']
sort = case params['sort']
when "date" then "created_on"
when "note" then "note"
when "amount" then "amount"
when "date_reverse" then "created_on DESC"
when "note_reverse" then "note DESC"
when "amount_reverse" then "amount DESC"
sort = if params['sort']
case params['sort']
when 'date' then 'created_on'
when 'note' then 'note'
when 'amount' then 'amount'
when 'date_reverse' then 'created_on DESC'
when 'note_reverse' then 'note DESC'
when 'amount_reverse' then 'amount DESC'
end
else
sort = "created_on DESC"
end
else
'created_on DESC'
end
@financial_transactions = @ordergroup.financial_transactions.visible.page(params[:page]).per(@per_page).order(sort)
@financial_transactions = @financial_transactions.where('financial_transactions.note LIKE ?', "%#{params[:query]}%") if params[:query].present?
if params[:query].present?
@financial_transactions = @financial_transactions.where('financial_transactions.note LIKE ?',
"%#{params[:query]}%")
end
else
redirect_to root_path, alert: I18n.t('home.no_ordergroups')
end
end
# cancel personal memberships direct from the myProfile-page
def cancel_membership
if params[:membership_id]
membership = @current_user.memberships.find(params[:membership_id])
else
membership = @current_user.memberships.find_by_group_id!(params[:group_id])
end
membership = if params[:membership_id]
@current_user.memberships.find(params[:membership_id])
else
@current_user.memberships.find_by_group_id!(params[:group_id])
end
membership.destroy
redirect_to my_profile_path, notice: I18n.t('home.ordergroup_cancelled', :group => membership.group.name)
redirect_to my_profile_path, notice: I18n.t('home.ordergroup_cancelled', group: membership.group.name)
end
protected
@ -82,8 +84,8 @@ class HomeController < ApplicationController
end
def ordergroup_params
if params[:user][:ordergroup]
params.require(:user).require(:ordergroup).permit(:contact_address)
end
return unless params[:user][:ordergroup]
params.require(:user).require(:ordergroup).permit(:contact_address)
end
end

View file

@ -3,7 +3,7 @@ class InvitesController < ApplicationController
before_action -> { require_config_disabled :disable_invite }
def new
@invite = Invite.new(:user => @current_user, :group => @group)
@invite = Invite.new(user: @current_user, group: @group)
end
def create
@ -27,6 +27,10 @@ class InvitesController < ApplicationController
protected
def authenticate_membership_or_admin_for_invites
authenticate_membership_or_admin((params[:invite][:group_id] rescue params[:id]))
authenticate_membership_or_admin(begin
params[:invite][:group_id]
rescue StandardError
params[:id]
end)
end
end

View file

@ -1,6 +1,6 @@
class LoginController < ApplicationController
skip_before_action :authenticate # no authentication since this is the login page
before_action :validate_token, :only => [:new_password, :update_password]
before_action :validate_token, only: %i[new_password update_password]
# Display the form to enter an email address requesting a token to set a new password.
def forgot_password
@ -9,20 +9,17 @@ class LoginController < ApplicationController
# Sends an email to a user with the token that allows setting a new password through action "password".
def reset_password
if request.get? || params[:user].nil? # Catch for get request and give better error message.
redirect_to forgot_password_url, alert: I18n.t('errors.general_again') and return
end
redirect_to forgot_password_url, alert: I18n.t('errors.general_again') and return if request.get? || params[:user].nil? # Catch for get request and give better error message.
if (user = User.undeleted.find_by_email(params[:user][:email]))
user.request_password_reset!
end
redirect_to login_url, :notice => I18n.t('login.controller.reset_password.notice')
redirect_to login_url, notice: I18n.t('login.controller.reset_password.notice')
end
# Set a new password with a token from the password reminder email.
# Called with params :id => User.id and :token => User.reset_password_token to specify a new password.
def new_password
end
def new_password; end
# Sets a new password.
# Called with params :id => User.id and :token => User.reset_password_token to specify a new password.
@ -32,7 +29,7 @@ class LoginController < ApplicationController
@user.reset_password_token = nil
@user.reset_password_expires = nil
@user.save
redirect_to login_url, :notice => I18n.t('login.controller.update_password.notice')
redirect_to login_url, notice: I18n.t('login.controller.update_password.notice')
else
render :new_password
end
@ -50,14 +47,14 @@ class LoginController < ApplicationController
@user = User.new(params[:user])
@user.email = @invite.email
if @user.save
Membership.new(:user => @user, :group => @invite.group).save!
Membership.new(user: @user, group: @invite.group).save!
@invite.destroy
session[:locale] = @user.locale
redirect_to login_url, notice: I18n.t('login.controller.accept_invitation.notice')
end
end
else
@user = User.new(:email => @invite.email)
@user = User.new(email: @invite.email)
end
end
@ -65,8 +62,8 @@ class LoginController < ApplicationController
def validate_token
@user = User.find_by_id_and_reset_password_token(params[:id], params[:token])
if (@user.nil? || @user.reset_password_expires < Time.now)
redirect_to forgot_password_url, alert: I18n.t('login.controller.error_token_invalid')
end
return unless @user.nil? || @user.reset_password_expires < Time.now
redirect_to forgot_password_url, alert: I18n.t('login.controller.error_token_invalid')
end
end

View file

@ -1,7 +1,7 @@
class OrderArticlesController < ApplicationController
before_action :fetch_order, except: :destroy
before_action :authenticate_finance_or_invoices, except: [:new, :create]
before_action :authenticate_finance_orders_or_pickup, except: [:edit, :update, :destroy]
before_action :authenticate_finance_or_invoices, except: %i[new create]
before_action :authenticate_finance_orders_or_pickup, except: %i[edit update destroy]
layout false # We only use this controller to serve js snippets, no need for layout rendering
@ -9,28 +9,26 @@ class OrderArticlesController < ApplicationController
@order_article = @order.order_articles.build(params[:order_article])
end
def edit
@order_article = OrderArticle.find(params[:id])
end
def create
# The article may be ordered with zero units - in that case do not complain.
# If order_article is ordered and a new order_article is created, an error message will be
# given mentioning that the article already exists, which is desired.
@order_article = @order.order_articles.where(:article_id => params[:order_article][:article_id]).first
unless @order_article && @order_article.units_to_order == 0
@order_article = @order.order_articles.build(params[:order_article])
end
@order_article = @order.order_articles.where(article_id: params[:order_article][:article_id]).first
@order_article = @order.order_articles.build(params[:order_article]) unless @order_article && @order_article.units_to_order == 0
@order_article.save!
rescue
rescue StandardError
render action: :new
end
def edit
@order_article = OrderArticle.find(params[:id])
end
def update
@order_article = OrderArticle.find(params[:id])
begin
@order_article.update_article_and_price!(params[:order_article], params[:article], params[:article_price])
rescue
rescue StandardError
render action: :edit
end
end

View file

@ -1,15 +1,15 @@
class OrderCommentsController < ApplicationController
def new
@order = Order.find(params[:order_id])
@order_comment = @order.comments.build(:user => current_user)
@order_comment = @order.comments.build(user: current_user)
end
def create
@order_comment = OrderComment.new(params[:order_comment])
if @order_comment.save
render :layout => false
render layout: false
else
render :action => :new, :layout => false
render action: :new, layout: false
end
end
end

View file

@ -5,25 +5,26 @@ class OrdersController < ApplicationController
include Concerns::SendOrderPdf
before_action :authenticate_pickups_or_orders
before_action :authenticate_orders, except: [:receive, :receive_on_order_article_create, :receive_on_order_article_update, :show]
before_action :remove_empty_article, only: [:create, :update]
before_action :authenticate_orders,
except: %i[receive receive_on_order_article_create receive_on_order_article_update show]
before_action :remove_empty_article, only: %i[create update]
# List orders
def index
@open_orders = Order.open.includes(:supplier)
@finished_orders = Order.finished_not_closed.includes(:supplier)
@per_page = 15
if params['sort']
sort = case params['sort']
when "supplier" then "suppliers.name, ends DESC"
when "pickup" then "pickup DESC"
when "ends" then "ends DESC"
when "supplier_reverse" then "suppliers.name DESC"
when "ends_reverse" then "ends"
sort = if params['sort']
case params['sort']
when 'supplier' then 'suppliers.name, ends DESC'
when 'pickup' then 'pickup DESC'
when 'ends' then 'ends DESC'
when 'supplier_reverse' then 'suppliers.name DESC'
when 'ends_reverse' then 'ends'
end
else
sort = "ends DESC"
end
else
'ends DESC'
end
@suppliers = Supplier.having_articles.order('suppliers.name')
@orders = Order.closed.includes(:supplier).reorder(sort).page(params[:page]).per(@per_page)
end
@ -43,7 +44,7 @@ class OrdersController < ApplicationController
respond_to do |format|
format.html
format.js do
render :layout => false
render layout: false
end
format.pdf do
send_order_pdf @order, params[:document]
@ -66,8 +67,14 @@ class OrdersController < ApplicationController
else
@order = Order.new(supplier_id: params[:supplier_id]).init_dates
end
rescue => error
redirect_to orders_url, alert: t('errors.general_msg', msg: error.message)
rescue StandardError => e
redirect_to orders_url, alert: t('errors.general_msg', msg: e.message)
end
# Page to edit an exsiting order.
# editing finished orders is done in FinanceController
def edit
@order = Order.includes(:articles).find(params[:id])
end
# Save a new order.
@ -81,31 +88,25 @@ class OrdersController < ApplicationController
redirect_to @order
else
logger.debug "[debug] order errors: #{@order.errors.messages}"
render :action => 'new'
render action: 'new'
end
end
# Page to edit an exsiting order.
# editing finished orders is done in FinanceController
def edit
@order = Order.includes(:articles).find(params[:id])
end
# Update an existing order.
def update
@order = Order.find params[:id]
if @order.update(params[:order].merge(updated_by: current_user))
flash[:notice] = I18n.t('orders.update.notice')
redirect_to :action => 'show', :id => @order
redirect_to action: 'show', id: @order
else
render :action => 'edit'
render action: 'edit'
end
end
# Delete an order.
def destroy
Order.find(params[:id]).destroy
redirect_to :action => 'index'
redirect_to action: 'index'
end
# Finish a current order.
@ -113,8 +114,8 @@ class OrdersController < ApplicationController
order = Order.find(params[:id])
order.finish!(@current_user)
redirect_to order, notice: I18n.t('orders.finish.notice')
rescue => error
redirect_to orders_url, alert: I18n.t('errors.general_msg', :msg => error.message)
rescue StandardError => e
redirect_to orders_url, alert: I18n.t('errors.general_msg', msg: e.message)
end
# Send a order to the supplier.
@ -122,20 +123,18 @@ class OrdersController < ApplicationController
order = Order.find(params[:id])
order.send_to_supplier!(@current_user)
redirect_to order, notice: I18n.t('orders.send_to_supplier.notice')
rescue => error
redirect_to order, alert: I18n.t('errors.general_msg', :msg => error.message)
rescue StandardError => e
redirect_to order, alert: I18n.t('errors.general_msg', msg: e.message)
end
def receive
@order = Order.find(params[:id])
unless request.post?
@order_articles = @order.order_articles.ordered_or_member.includes(:article).order('articles.order_number, articles.name')
else
if request.post?
Order.transaction do
s = update_order_amounts
@order.update_attribute(:state, 'received') if @order.state != 'received'
flash[:notice] = (s ? I18n.t('orders.receive.notice', :msg => s) : I18n.t('orders.receive.notice_none'))
flash[:notice] = (s ? I18n.t('orders.receive.notice', msg: s) : I18n.t('orders.receive.notice_none'))
end
NotifyReceivedOrderJob.perform_later(@order)
if current_user.role_orders? || current_user.role_finance?
@ -145,23 +144,25 @@ class OrdersController < ApplicationController
else
redirect_to receive_order_path(@order)
end
else
@order_articles = @order.order_articles.ordered_or_member.includes(:article).order('articles.order_number, articles.name')
end
end
def receive_on_order_article_create # See publish/subscribe design pattern in /doc.
@order_article = OrderArticle.find(params[:order_article_id])
render :layout => false
render layout: false
end
def receive_on_order_article_update # See publish/subscribe design pattern in /doc.
@order_article = OrderArticle.find(params[:order_article_id])
render :layout => false
render layout: false
end
protected
def update_order_amounts
return if not params[:order_articles]
return unless params[:order_articles]
# where to leave remainder during redistribution
rest_to = []
@ -176,35 +177,42 @@ class OrdersController < ApplicationController
# "MySQL lock timeout exceeded" errors. It's ok to do
# this article-by-article anway.
params[:order_articles].each do |oa_id, oa_params|
unless oa_params.blank?
oa = OrderArticle.find(oa_id)
# update attributes; don't use update_attribute because it calls save
# which makes received_changed? not work anymore
oa.attributes = oa_params
if oa.units_received_changed?
counts[0] += 1
unless oa.units_received.blank?
cunits[0] += oa.units_received * oa.article.unit_quantity
oacounts = oa.redistribute oa.units_received * oa.price.unit_quantity, rest_to
oacounts.each_with_index { |c, i| cunits[i + 1] += c; counts[i + 1] += 1 if c > 0 }
next if oa_params.blank?
oa = OrderArticle.find(oa_id)
# update attributes; don't use update_attribute because it calls save
# which makes received_changed? not work anymore
oa.attributes = oa_params
if oa.units_received_changed?
counts[0] += 1
if oa.units_received.present?
cunits[0] += oa.units_received * oa.article.unit_quantity
oacounts = oa.redistribute oa.units_received * oa.price.unit_quantity, rest_to
oacounts.each_with_index do |c, i|
cunits[i + 1] += c
counts[i + 1] += 1 if c > 0
end
end
oa.save!
end
oa.save!
end
return nil if counts[0] == 0
notice = []
notice << I18n.t('orders.update_order_amounts.msg1', count: counts[0], units: cunits[0])
notice << I18n.t('orders.update_order_amounts.msg2', count: counts[1], units: cunits[1]) if params[:rest_to_tolerance]
if params[:rest_to_tolerance]
notice << I18n.t('orders.update_order_amounts.msg2', count: counts[1],
units: cunits[1])
end
notice << I18n.t('orders.update_order_amounts.msg3', count: counts[2], units: cunits[2]) if params[:rest_to_stock]
if counts[3] > 0 || cunits[3] > 0
notice << I18n.t('orders.update_order_amounts.msg4', count: counts[3], units: cunits[3])
notice << I18n.t('orders.update_order_amounts.msg4', count: counts[3],
units: cunits[3])
end
notice.join(', ')
end
def remove_empty_article
params[:order][:article_ids].reject!(&:blank?) if params[:order] && params[:order][:article_ids]
params[:order][:article_ids].compact_blank! if params[:order] && params[:order][:article_ids]
end
end

View file

@ -12,10 +12,10 @@ class SessionsController < ApplicationController
user = User.authenticate(params[:nick], params[:password])
if user
user.update_attribute(:last_login, Time.now)
login_and_redirect_to_return_to user, :notice => I18n.t('sessions.logged_in')
login_and_redirect_to_return_to user, notice: I18n.t('sessions.logged_in')
else
flash.now.alert = I18n.t(FoodsoftConfig[:use_nick] ? 'sessions.login_invalid_nick' : 'sessions.login_invalid_email')
render "new"
render 'new'
end
end
@ -24,7 +24,7 @@ class SessionsController < ApplicationController
if FoodsoftConfig[:logout_redirect_url].present?
redirect_to FoodsoftConfig[:logout_redirect_url]
else
redirect_to login_url, :notice => I18n.t('sessions.logged_out')
redirect_to login_url, notice: I18n.t('sessions.logged_out')
end
end

View file

@ -7,21 +7,21 @@ class StockTakingsController < ApplicationController
def new
@stock_taking = StockTaking.new
StockArticle.undeleted.each { |a| @stock_taking.stock_changes.build(:stock_article => a) }
StockArticle.undeleted.each { |a| @stock_taking.stock_changes.build(stock_article: a) }
end
def new_on_stock_article_create # See publish/subscribe design pattern in /doc.
stock_article = StockArticle.find(params[:stock_article_id])
@stock_change = StockChange.new(:stock_article => stock_article)
@stock_change = StockChange.new(stock_article: stock_article)
render :layout => false
render layout: false
end
def create
create!(:notice => I18n.t('stock_takings.create.notice'))
create!(notice: I18n.t('stock_takings.create.notice'))
end
def update
update!(:notice => I18n.t('stock_takings.update.notice'))
update!(notice: I18n.t('stock_takings.update.notice'))
end
end

View file

@ -7,57 +7,13 @@ class StockitController < ApplicationController
def index_on_stock_article_create # See publish/subscribe design pattern in /doc.
@stock_article = StockArticle.find(params[:id])
render :layout => false
render layout: false
end
def index_on_stock_article_update # See publish/subscribe design pattern in /doc.
@stock_article = StockArticle.find(params[:id])
render :layout => false
end
# three possibilites to fill a new_stock_article form
# (1) start from blank or use params
def new
@stock_article = StockArticle.new(params[:stock_article])
render :layout => false
end
# (2) StockArticle as template
def copy
@stock_article = StockArticle.find(params[:stock_article_id]).dup
render :layout => false
end
# (3) non-stock Article as template
def derive
@stock_article = Article.find(params[:old_article_id]).becomes(StockArticle).dup
render :layout => false
end
def create
@stock_article = StockArticle.new({ quantity: 0 }.merge(params[:stock_article]))
@stock_article.save!
render :layout => false
rescue ActiveRecord::RecordInvalid
render :action => 'new', :layout => false
end
def edit
@stock_article = StockArticle.find(params[:id])
render :layout => false
end
def update
@stock_article = StockArticle.find(params[:id])
@stock_article.update!(params[:stock_article])
render :layout => false
rescue ActiveRecord::RecordInvalid
render :action => 'edit', :layout => false
render layout: false
end
def show
@ -65,24 +21,68 @@ class StockitController < ApplicationController
@stock_changes = @stock_article.stock_changes.order('stock_changes.created_at DESC')
end
# three possibilites to fill a new_stock_article form
# (1) start from blank or use params
def new
@stock_article = StockArticle.new(params[:stock_article])
render layout: false
end
# (2) StockArticle as template
def copy
@stock_article = StockArticle.find(params[:stock_article_id]).dup
render layout: false
end
# (3) non-stock Article as template
def derive
@stock_article = Article.find(params[:old_article_id]).becomes(StockArticle).dup
render layout: false
end
def edit
@stock_article = StockArticle.find(params[:id])
render layout: false
end
def create
@stock_article = StockArticle.new({ quantity: 0 }.merge(params[:stock_article]))
@stock_article.save!
render layout: false
rescue ActiveRecord::RecordInvalid
render action: 'new', layout: false
end
def update
@stock_article = StockArticle.find(params[:id])
@stock_article.update!(params[:stock_article])
render layout: false
rescue ActiveRecord::RecordInvalid
render action: 'edit', layout: false
end
def show_on_stock_article_update # See publish/subscribe design pattern in /doc.
@stock_article = StockArticle.find(params[:id])
render :layout => false
render layout: false
end
def destroy
@stock_article = StockArticle.find(params[:id])
@stock_article.mark_as_deleted
render :layout => false
rescue => error
render :partial => "destroy_fail", :layout => false,
:locals => { :fail_msg => I18n.t('errors.general_msg', :msg => error.message) }
render layout: false
rescue StandardError => e
render partial: 'destroy_fail', layout: false,
locals: { fail_msg: I18n.t('errors.general_msg', msg: e.message) }
end
# TODO: Fix this!!
def articles_search
@articles = Article.not_in_stock.limit(8).where('name LIKE ?', "%#{params[:term]}%")
render :json => @articles.map(&:name)
render json: @articles.map(&:name)
end
end

View file

@ -9,7 +9,7 @@ class StylesController < ApplicationController
def foodcoop
css = FoodsoftConfig[:custom_css]
if css.blank?
render body: nil, content_type: 'text/css', status: 404
render body: nil, content_type: 'text/css', status: :not_found
else
expires_in 1.week, public: true if params[:md5].present?
render body: css, content_type: 'text/css'

View file

@ -1,5 +1,5 @@
class SuppliersController < ApplicationController
before_action :authenticate_suppliers, :except => [:index, :list]
before_action :authenticate_suppliers, except: %i[index list]
helper :deliveries
def index
@ -24,6 +24,10 @@ class SuppliersController < ApplicationController
end
end
def edit
@supplier = Supplier.find(params[:id])
end
def create
@supplier = Supplier.new(supplier_params)
@supplier.supplier_category ||= SupplierCategory.first
@ -31,21 +35,17 @@ class SuppliersController < ApplicationController
flash[:notice] = I18n.t('suppliers.create.notice')
redirect_to suppliers_path
else
render :action => 'new'
render action: 'new'
end
end
def edit
@supplier = Supplier.find(params[:id])
end
def update
@supplier = Supplier.find(params[:id])
if @supplier.update(supplier_params)
flash[:notice] = I18n.t('suppliers.update.notice')
redirect_to @supplier
else
render :action => 'edit'
render action: 'edit'
end
end
@ -54,8 +54,8 @@ class SuppliersController < ApplicationController
@supplier.mark_as_deleted
flash[:notice] = I18n.t('suppliers.destroy.notice')
redirect_to suppliers_path
rescue => e
flash[:error] = I18n.t('errors.general_msg', :msg => e.message)
rescue StandardError => e
flash[:error] = I18n.t('errors.general_msg', msg: e.message)
redirect_to @supplier
end

View file

@ -11,35 +11,33 @@ class TasksController < ApplicationController
@accepted_tasks = Task.accepted_tasks_for(current_user)
end
def new
@task = Task.new(current_user_id: current_user.id)
end
def create
@task = Task.new(current_user_id: current_user.id)
@task.created_by = current_user
@task.attributes = (task_params)
if params[:periodic]
@task.periodic_task_group = PeriodicTaskGroup.new
end
if @task.save
@task.periodic_task_group.create_tasks_for_upfront_days if params[:periodic]
redirect_to tasks_url, :notice => I18n.t('tasks.create.notice')
else
render :template => "tasks/new"
end
end
def show
@task = Task.find(params[:id])
end
def new
@task = Task.new(current_user_id: current_user.id)
end
def edit
@task = Task.find(params[:id])
@periodic = !!params[:periodic]
@task.current_user_id = current_user.id
end
def create
@task = Task.new(current_user_id: current_user.id)
@task.created_by = current_user
@task.attributes = (task_params)
@task.periodic_task_group = PeriodicTaskGroup.new if params[:periodic]
if @task.save
@task.periodic_task_group.create_tasks_for_upfront_days if params[:periodic]
redirect_to tasks_url, notice: I18n.t('tasks.create.notice')
else
render template: 'tasks/new'
end
end
def update
@task = Task.find(params[:id])
task_group = @task.periodic_task_group
@ -50,16 +48,14 @@ class TasksController < ApplicationController
if @task.errors.empty? && @task.save
task_group.update_tasks_including(@task, prev_due_date) if params[:periodic]
flash[:notice] = I18n.t('tasks.update.notice')
if was_periodic && !@task.periodic?
flash[:notice] = I18n.t('tasks.update.notice_converted')
end
flash[:notice] = I18n.t('tasks.update.notice_converted') if was_periodic && !@task.periodic?
if @task.workgroup
redirect_to workgroup_tasks_url(workgroup_id: @task.workgroup_id)
else
redirect_to tasks_url
end
else
render :template => "tasks/edit"
render template: 'tasks/edit'
end
end
@ -75,7 +71,7 @@ class TasksController < ApplicationController
end
task.update_ordergroup_stats(user_ids)
redirect_to tasks_url, :notice => I18n.t('tasks.destroy.notice')
redirect_to tasks_url, notice: I18n.t('tasks.destroy.notice')
end
# assign current_user to the task and set the assignment to "accepted"
@ -85,20 +81,20 @@ class TasksController < ApplicationController
if ass = task.is_assigned?(current_user)
ass.update_attribute(:accepted, true)
else
task.assignments.create(:user => current_user, :accepted => true)
task.assignments.create(user: current_user, accepted: true)
end
redirect_to user_tasks_path, :notice => I18n.t('tasks.accept.notice')
redirect_to user_tasks_path, notice: I18n.t('tasks.accept.notice')
end
# deletes assignment between current_user and given taskcurrent_user_id: current_user.id
def reject
Task.find(params[:id]).users.delete(current_user)
redirect_to :action => "index"
redirect_to action: 'index'
end
def set_done
Task.find(params[:id]).update_attribute :done, true
redirect_to tasks_url, :notice => I18n.t('tasks.set_done.notice')
redirect_to tasks_url, notice: I18n.t('tasks.set_done.notice')
end
# Shows all tasks, which are already done
@ -109,9 +105,9 @@ class TasksController < ApplicationController
# shows workgroup (normal group) to edit weekly_tasks_template
def workgroup
@group = Group.find(params[:workgroup_id])
if @group.is_a? Ordergroup
redirect_to tasks_url, :alert => I18n.t('tasks.error_not_found')
end
return unless @group.is_a? Ordergroup
redirect_to tasks_url, alert: I18n.t('tasks.error_not_found')
end
private

View file

@ -3,7 +3,7 @@ class UsersController < ApplicationController
def index
@users = User.undeleted.natural_search(params[:q])
respond_to do |format|
format.json { render :json => @users.map(&:token_attributes).to_json }
format.json { render json: @users.map(&:token_attributes).to_json }
end
end
end