diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index c85842af..7830d550 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -29,491 +29,6 @@ Gemspec/RequiredRubyVersion: - 'plugins/uservoice/foodsoft_uservoice.gemspec' - 'plugins/wiki/foodsoft_wiki.gemspec' -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: outdent, indent -Layout/AccessModifierIndentation: - Exclude: - - 'app/controllers/finance/financial_links_controller.rb' - - 'app/models/invite.rb' - - 'db/migrate/20130622095040_move_weekly_tasks.rb' - -# Offense count: 13 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: with_first_argument, with_fixed_indentation -Layout/ArgumentAlignment: - Exclude: - - 'app/controllers/finance/balancing_controller.rb' - - 'app/controllers/foodcoop/workgroups_controller.rb' - - 'app/helpers/deliveries_helper.rb' - - 'app/helpers/stockit_helper.rb' - - 'db/migrate/20140102170431_add_result_computed_to_group_order_articles.rb' - - 'plugins/discourse/app/controllers/discourse_login_controller.rb' - - 'plugins/discourse/app/controllers/discourse_sso_controller.rb' - - 'plugins/messages/lib/foodsoft_messages/user_link.rb' - - 'plugins/polls/app/controllers/polls_controller.rb' - - 'spec/models/user_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: with_first_element, with_fixed_indentation -Layout/ArrayAlignment: - Exclude: - - 'lib/render_pdf.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyleAlignWith. -# SupportedStylesAlignWith: either, start_of_block, start_of_line -Layout/BlockAlignment: - Exclude: - - 'db/migrate/008_create_orders.rb' - - 'db/migrate/20090120184410_road_to_version_three.rb' - - 'spec/api/v1/user/group_order_articles_spec.rb' - -# Offense count: 86 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentOneStep, IndentationWidth. -# SupportedStyles: case, end -Layout/CaseIndentation: - Enabled: false - -# Offense count: 5 -# Cop supports --auto-correct. -Layout/ClosingParenthesisIndentation: - Exclude: - - 'app/helpers/stockit_helper.rb' - - 'app/models/group_order_article.rb' - - 'app/models/shared_article.rb' - - 'db/seeds/minimal.seeds.rb' - -# Offense count: 4 -# Cop supports --auto-correct. -Layout/CommentIndentation: - Exclude: - - 'app/controllers/concerns/auth_api.rb' - - 'app/controllers/finance/financial_transactions_controller.rb' - - 'app/documents/order_fax.rb' - - 'db/migrate/20090120184410_road_to_version_three.rb' - -# Offense count: 51 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: leading, trailing -Layout/DotPosition: - Exclude: - - 'app/controllers/api/v1/user/group_order_articles_controller.rb' - - 'app/controllers/stockit_controller.rb' - - 'app/documents/order_fax.rb' - - 'app/models/order.rb' - - 'app/models/stock_article.rb' - - 'app/models/task.rb' - - 'lib/order_pdf.rb' - - 'plugins/current_orders/app/controllers/current_orders/group_orders_controller.rb' - - 'plugins/current_orders/app/controllers/current_orders/ordergroups_controller.rb' - - 'plugins/current_orders/app/documents/multiple_orders_by_articles.rb' - - 'plugins/current_orders/app/documents/multiple_orders_by_groups.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -Layout/ElseAlignment: - Exclude: - - 'app/helpers/group_orders_helper.rb' - -# Offense count: 70 -# Cop supports --auto-correct. -Layout/EmptyLineAfterGuardClause: - Enabled: false - -# Offense count: 38 -# Cop supports --auto-correct. -Layout/EmptyLineAfterMagicComment: - Enabled: false - -# Offense count: 15 -# Cop supports --auto-correct. -# Configuration parameters: EmptyLineBetweenMethodDefs, EmptyLineBetweenClassDefs, EmptyLineBetweenModuleDefs, AllowAdjacentOneLineDefs, NumberOfEmptyLines. -Layout/EmptyLineBetweenDefs: - Exclude: - - 'app/helpers/finance/invoices_helper.rb' - - 'app/helpers/orders_helper.rb' - - 'app/models/group_order.rb' - - 'app/models/ordergroup.rb' - - 'app/models/task.rb' - - 'db/migrate/20181201000400_create_supplier_categories.rb' - - 'db/migrate/20181204000000_clear_invalid_invoices_from_orders.rb' - - 'db/migrate/20181204070000_create_stock_events.rb' - - 'lib/api/errors.rb' - - 'lib/foodsoft/expansion_variables.rb' - - 'lib/token_verifier.rb' - - 'plugins/wiki/app/helpers/pages_helper.rb' - - 'spec/support/shared_database.rb' - -# Offense count: 55 -# Cop supports --auto-correct. -Layout/EmptyLines: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: around, only_before -Layout/EmptyLinesAroundAccessModifier: - Exclude: - - 'db/migrate/20130622095040_move_weekly_tasks.rb' - -# Offense count: 85 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: empty_lines, no_empty_lines -Layout/EmptyLinesAroundBlockBody: - Enabled: false - -# Offense count: 147 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines, beginning_only, ending_only -Layout/EmptyLinesAroundClassBody: - Enabled: false - -# Offense count: 3 -# Cop supports --auto-correct. -Layout/EmptyLinesAroundExceptionHandlingKeywords: - Exclude: - - 'app/controllers/articles_controller.rb' - - 'app/controllers/finance/balancing_controller.rb' - - 'plugins/wiki/app/controllers/pages_controller.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -Layout/EmptyLinesAroundMethodBody: - Exclude: - - 'app/helpers/application_helper.rb' - - 'db/migrate/002_create_groups.rb' - -# Offense count: 37 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines -Layout/EmptyLinesAroundModuleBody: - Enabled: false - -# Offense count: 9 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyleAlignWith, Severity. -# SupportedStylesAlignWith: keyword, variable, start_of_line -Layout/EndAlignment: - Exclude: - - 'app/controllers/articles_controller.rb' - - 'app/controllers/concerns/auth.rb' - - 'app/controllers/concerns/send_order_pdf.rb' - - 'app/controllers/finance/financial_transactions_controller.rb' - - 'app/controllers/home_controller.rb' - - 'app/controllers/orders_controller.rb' - - 'app/helpers/group_orders_helper.rb' - - 'plugins/wiki/app/controllers/pages_controller.rb' - -# Offense count: 57 -# Cop supports --auto-correct. -# Configuration parameters: AllowForAlignment, AllowBeforeTrailingComments, ForceEqualSignAlignment. -Layout/ExtraSpacing: - Enabled: false - -# Offense count: 6 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: consistent, consistent_relative_to_receiver, special_for_inner_method_call, special_for_inner_method_call_in_parentheses -Layout/FirstArgumentIndentation: - Exclude: - - 'app/models/group_order_article.rb' - - 'app/models/shared_article.rb' - - 'db/seeds/minimal.seeds.rb' - - 'plugins/current_orders/app/controllers/current_orders/articles_controller.rb' - - 'plugins/current_orders/app/controllers/current_orders/ordergroups_controller.rb' - -# Offense count: 8 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: special_inside_parentheses, consistent, align_brackets -Layout/FirstArrayElementIndentation: - Exclude: - - 'db/seeds/small.en.seeds.rb' - - 'db/seeds/small.nl.seeds.rb' - - 'lib/financial_transactions_csv.rb' - - 'lib/order_csv.rb' - -# Offense count: 9 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: special_inside_parentheses, consistent, align_braces -Layout/FirstHashElementIndentation: - Exclude: - - 'app/controllers/finance/financial_transactions_controller.rb' - - 'app/helpers/application_helper.rb' - - 'app/models/group_order.rb' - - 'db/migrate/20130718183101_migrate_user_settings.rb' - - 'lib/bank_account_information_importer.rb' - -# Offense count: 83 -# Cop supports --auto-correct. -# Configuration parameters: AllowMultipleStyles, EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle. -# SupportedHashRocketStyles: key, separator, table -# SupportedColonStyles: key, separator, table -# SupportedLastArgumentHashStyles: always_inspect, always_ignore, ignore_implicit, ignore_explicit -Layout/HashAlignment: - Enabled: false - -# Offense count: 9 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: normal, indented_internal_methods -Layout/IndentationConsistency: - Exclude: - - 'db/migrate/003_create_suppliers.rb' - - 'db/migrate/007_create_article_prices.rb' - - 'db/migrate/008_create_orders.rb' - - 'db/migrate/010_user_password_reset.rb' - - 'db/migrate/20090120184410_road_to_version_three.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: IndentationWidth, EnforcedStyle. -# SupportedStyles: spaces, tabs -Layout/IndentationStyle: - Exclude: - - 'db/migrate/010_user_password_reset.rb' - -# Offense count: 12 -# Cop supports --auto-correct. -# Configuration parameters: Width, IgnoredPatterns. -Layout/IndentationWidth: - Exclude: - - 'app/helpers/admin/configs_helper.rb' - - 'app/helpers/group_orders_helper.rb' - - 'app/models/user.rb' - - 'db/migrate/003_create_suppliers.rb' - - 'db/migrate/007_create_article_prices.rb' - - 'db/migrate/008_create_orders.rb' - - 'db/migrate/20090120184410_road_to_version_three.rb' - - 'lib/tasks/multicoops.rake' - - 'spec/api/v1/user/group_order_articles_spec.rb' - - 'spec/spec_helper.rb' - -# Offense count: 39 -# Cop supports --auto-correct. -# Configuration parameters: AllowDoxygenCommentStyle, AllowGemfileRubyComment. -Layout/LeadingCommentSpace: - Enabled: false - -# Offense count: 5 -# Cop supports --auto-correct. -Layout/LeadingEmptyLines: - Exclude: - - 'db/migrate/20090120184410_road_to_version_three.rb' - - 'db/seeds/seed_helper.rb' - - 'lib/order_txt.rb' - - 'spec/support/integration.rb' - - 'spec/support/session_helper.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: symmetrical, new_line, same_line -Layout/MultilineMethodCallBraceLayout: - Exclude: - - 'app/helpers/stockit_helper.rb' - -# Offense count: 42 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: aligned, indented, indented_relative_to_receiver -Layout/MultilineMethodCallIndentation: - Exclude: - - 'app/controllers/stockit_controller.rb' - - 'app/models/order.rb' - - 'app/models/ordergroup.rb' - - 'app/models/stock_article.rb' - - 'app/models/task.rb' - - 'lib/foodsoft/expansion_variables.rb' - - 'lib/order_pdf.rb' - - 'plugins/current_orders/app/controllers/current_orders/group_orders_controller.rb' - - 'plugins/current_orders/app/controllers/current_orders/ordergroups_controller.rb' - - 'plugins/current_orders/app/documents/multiple_orders_by_groups.rb' - - 'spec/api/v1/user/group_order_articles_spec.rb' - -# Offense count: 9 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: aligned, indented -Layout/MultilineOperationIndentation: - Exclude: - - 'app/helpers/orders_helper.rb' - - 'app/inputs/date_picker_time_input.rb' - - 'app/models/ordergroup.rb' - - 'app/models/task.rb' - - 'lib/apple_bar.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Layout/RescueEnsureAlignment: - Exclude: - - 'app/controllers/suppliers_controller.rb' - -# Offense count: 9 -# Cop supports --auto-correct. -Layout/SpaceAfterColon: - Exclude: - - 'app/controllers/styles_controller.rb' - - 'spec/integration/articles_spec.rb' - - 'spec/integration/balancing_spec.rb' - - 'spec/integration/order_spec.rb' - - 'spec/integration/receive_spec.rb' - - 'spec/integration/supplier_spec.rb' - - 'spec/models/order_article_spec.rb' - - 'spec/models/ordergroup_spec.rb' - -# Offense count: 110 -# Cop supports --auto-correct. -Layout/SpaceAfterComma: - Enabled: false - -# Offense count: 8 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyleInsidePipes. -# SupportedStylesInsidePipes: space, no_space -Layout/SpaceAroundBlockParameters: - Exclude: - - 'app/models/group_order_article.rb' - - 'db/migrate/008_create_orders.rb' - -# Offense count: 50 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: space, no_space -Layout/SpaceAroundEqualsInParameterDefault: - Enabled: false - -# Offense count: 109 -# Cop supports --auto-correct. -# Configuration parameters: AllowForAlignment, EnforcedStyleForExponentOperator. -# SupportedStylesForExponentOperator: space, no_space -Layout/SpaceAroundOperators: - Enabled: false - -# Offense count: 73 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces. -# SupportedStyles: space, no_space -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceBeforeBlockBraces: - Enabled: false - -# Offense count: 2 -# Cop supports --auto-correct. -Layout/SpaceBeforeComma: - Exclude: - - 'db/migrate/016_add_shared_lists_connection.rb' - - 'lib/render_pdf.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Layout/SpaceBeforeComment: - Exclude: - - 'plugins/wiki/lib/foodsoft_wiki/wiki_parser.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: AllowForAlignment. -Layout/SpaceBeforeFirstArg: - Exclude: - - 'app/controllers/application_controller.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: require_no_space, require_space -Layout/SpaceInLambdaLiteral: - Exclude: - - 'plugins/messages/app/models/message.rb' - -# Offense count: 7 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBrackets. -# SupportedStyles: space, no_space, compact -# SupportedStylesForEmptyBrackets: space, no_space -Layout/SpaceInsideArrayLiteralBrackets: - Exclude: - - 'app/helpers/orders_helper.rb' - - 'config/application.rb' - - 'config/environments/production.rb' - - 'db/migrate/20130718183100_create_settings.rb' - -# Offense count: 148 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters. -# SupportedStyles: space, no_space -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceInsideBlockBraces: - Enabled: false - -# Offense count: 374 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces. -# SupportedStyles: space, no_space, compact -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceInsideHashLiteralBraces: - Enabled: false - -# Offense count: 6 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: space, no_space -Layout/SpaceInsideParens: - Exclude: - - 'app/helpers/group_orders_helper.rb' - - 'db/migrate/006_create_articles.rb' - - 'spec/api/v1/user/group_order_articles_spec.rb' - -# Offense count: 14 -# Cop supports --auto-correct. -Layout/SpaceInsidePercentLiteralDelimiters: - Exclude: - - 'lib/tasks/foodsoft_setup.rake' - -# Offense count: 7 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBrackets. -# SupportedStyles: space, no_space -# SupportedStylesForEmptyBrackets: space, no_space -Layout/SpaceInsideReferenceBrackets: - Exclude: - - 'lib/bank_account_information_importer.rb' - - 'lib/foodsoft_config.rb' - - 'spec/api/v1/user/ordergroup_spec.rb' - -# Offense count: 7 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: final_newline, final_blank_line -Layout/TrailingEmptyLines: - Exclude: - - 'app/models/ordergroup.rb' - - 'config/initializers/bullet.rb' - - 'config/initializers/new_rails_defaults.rb' - - 'db/migrate/20130718183101_migrate_user_settings.rb' - - 'lib/apple_bar.rb' - - 'lib/tasks/foodsoft_setup.rake' - - 'spec/support/faker.rb' - -# Offense count: 111 -# Cop supports --auto-correct. -# Configuration parameters: AllowInHeredoc. -Layout/TrailingWhitespace: - Enabled: false - # Offense count: 8 Lint/AmbiguousBlockAssociation: Exclude: @@ -529,13 +44,12 @@ Lint/AmbiguousOperator: - 'app/mailers/mailer.rb' - 'spec/models/order_article_spec.rb' -# Offense count: 3 +# Offense count: 2 # Cop supports --auto-correct. Lint/AmbiguousRegexpLiteral: Exclude: - 'app/models/article_category.rb' - 'lib/foodsoft/expansion_variables.rb' - - 'lib/foodsoft_config.rb' # Offense count: 40 # Configuration parameters: AllowSafeAssignment. @@ -626,7 +140,7 @@ Lint/ParenthesesAsGroupedExpression: - 'spec/lib/token_verifier_spec.rb' - 'spec/models/order_article_spec.rb' -# Offense count: 2 +# Offense count: 1 Lint/ReturnInVoidContext: Exclude: - 'lib/foodsoft_config.rb' @@ -721,12 +235,11 @@ Lint/UnusedMethodArgument: - 'lib/render_pdf.rb' - 'plugins/wiki/lib/foodsoft_wiki/mailer.rb' -# Offense count: 3 +# Offense count: 2 # Cop supports --auto-correct. # Configuration parameters: ContextCreatingMethods, MethodCreatingMethods. Lint/UselessAccessModifier: Exclude: - - 'lib/foodsoft_config.rb' - 'lib/token_verifier.rb' - 'plugins/messages/app/models/messagegroup.rb' @@ -746,6 +259,12 @@ Lint/UselessAssignment: - 'plugins/current_orders/app/documents/multiple_orders_by_groups.rb' - 'spec/lib/foodsoft_config_spec.rb' +# Offense count: 1 +# Configuration parameters: CheckForMethodsWithNoSideEffects. +Lint/Void: + Exclude: + - 'lib/foodsoft_config.rb' + # Offense count: 158 # Configuration parameters: IgnoredMethods, CountRepeatedAttributes. Metrics/AbcSize: @@ -1082,7 +601,7 @@ RSpec/MultipleMemoizedHelpers: RSpec/NestedGroups: Max: 6 -# Offense count: 32 +# Offense count: 31 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. # SupportedStyles: not_to, to_not @@ -1092,7 +611,6 @@ RSpec/NotToNot: - 'spec/api/v1/user/group_order_articles_spec.rb' - 'spec/integration/balancing_spec.rb' - 'spec/integration/login_spec.rb' - - 'spec/integration/order_spec.rb' - 'spec/integration/receive_spec.rb' - 'spec/integration/session_spec.rb' - 'spec/lib/token_verifier_spec.rb' @@ -1520,14 +1038,13 @@ Security/YAMLLoad: - 'lib/foodsoft_config.rb' - 'spec/api/v1/swagger_spec.rb' -# Offense count: 4 +# Offense count: 3 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. # SupportedStyles: prefer_alias, prefer_alias_method Style/Alias: Exclude: - 'config/initializers/session_store.rb' - - 'lib/foodsoft_config.rb' - 'plugins/discourse/lib/foodsoft_discourse/redirect_to_login.rb' - 'plugins/printer/lib/foodsoft_printer/order_printer_jobs.rb' @@ -1685,7 +1202,7 @@ Style/DefWithParentheses: Exclude: - 'app/models/user.rb' -# Offense count: 306 +# Offense count: 307 Style/Documentation: Enabled: false @@ -1735,11 +1252,6 @@ Style/EmptyMethod: - 'db/migrate/20140318173000_delete_empty_group_order_articles.rb' - 'lib/bank_account_connector.rb' -# Offense count: 40 -# Cop supports --auto-correct. -Style/Encoding: - Enabled: false - # Offense count: 21 # Cop supports --auto-correct. Style/ExpandPathArguments: @@ -1809,7 +1321,7 @@ Style/GlobalStdStream: - 'lib/tasks/foodsoft.rake' - 'lib/tasks/foodsoft_setup.rake' -# Offense count: 63 +# Offense count: 62 # Configuration parameters: MinBodyLength. Style/GuardClause: Enabled: false @@ -1822,7 +1334,7 @@ Style/HashAsLastArrayItem: Exclude: - 'app/models/order.rb' -# Offense count: 7 +# Offense count: 6 # Cop supports --auto-correct. # Configuration parameters: AllowSplatArgument. Style/HashConversion: @@ -1831,7 +1343,6 @@ Style/HashConversion: - 'app/models/article.rb' - 'app/models/order.rb' - 'lib/bank_account_information_importer.rb' - - 'lib/foodsoft_config.rb' - 'plugins/wiki/app/controllers/pages_controller.rb' - 'spec/api/v1/user/ordergroup_spec.rb' @@ -2201,7 +1712,7 @@ Style/RedundantRegexpEscape: - 'plugins/documents/app/controllers/documents_controller.rb' - 'plugins/wiki/app/models/page.rb' -# Offense count: 18 +# Offense count: 15 # Cop supports --auto-correct. # Configuration parameters: AllowMultipleReturnValues. Style/RedundantReturn: @@ -2216,7 +1727,6 @@ Style/RedundantReturn: - 'app/models/periodic_task_group.rb' - 'app/models/supplier.rb' - 'lib/bank_transaction_reference.rb' - - 'lib/foodsoft_config.rb' # Offense count: 85 # Cop supports --auto-correct. @@ -2435,9 +1945,9 @@ Style/ZeroLengthPredicate: - 'plugins/current_orders/app/documents/multiple_orders_by_articles.rb' - 'plugins/current_orders/app/documents/multiple_orders_by_groups.rb' -# Offense count: 436 +# Offense count: 447 # Cop supports --auto-correct. # Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. # URISchemes: http, https Layout/LineLength: - Max: 414 + Max: 420 diff --git a/Gemfile b/Gemfile index 9a94aa69..1a56b334 100644 --- a/Gemfile +++ b/Gemfile @@ -9,7 +9,6 @@ gem 'uglifier', '>= 1.0.3' # See https://github.com/sstephenson/execjs#readme for more supported runtimes gem 'therubyracer', platforms: :ruby - gem 'jquery-rails' gem 'select2-rails' gem 'rails_tokeninput' @@ -67,10 +66,9 @@ gem 'foodsoft_links', path: 'plugins/links' gem 'foodsoft_polls', path: 'plugins/polls' # plugins not enabled by default -#gem 'foodsoft_current_orders', path: 'plugins/current_orders' -#gem 'foodsoft_printer', path: 'plugins/printer' -#gem 'foodsoft_uservoice', path: 'plugins/uservoice' - +# gem 'foodsoft_current_orders', path: 'plugins/current_orders' +# gem 'foodsoft_printer', path: 'plugins/printer' +# gem 'foodsoft_uservoice', path: 'plugins/uservoice' group :development do gem 'sqlite3', '~> 1.3.6' diff --git a/app/controllers/admin/base_controller.rb b/app/controllers/admin/base_controller.rb index 8b520f06..ee084289 100644 --- a/app/controllers/admin/base_controller.rb +++ b/app/controllers/admin/base_controller.rb @@ -6,5 +6,4 @@ class Admin::BaseController < ApplicationController @groups = Group.where(deleted_at: nil).order('created_on DESC').limit(10) @users = User.order('created_on DESC').limit(10) end - end diff --git a/app/controllers/admin/configs_controller.rb b/app/controllers/admin/configs_controller.rb index 813a50e2..516113af 100644 --- a/app/controllers/admin/configs_controller.rb +++ b/app/controllers/admin/configs_controller.rb @@ -1,5 +1,4 @@ class Admin::ConfigsController < Admin::BaseController - before_action :get_tabs, only: [:show, :list] def show @@ -11,7 +10,7 @@ class Admin::ConfigsController < Admin::BaseController @current_tab = 'list' @cfg = FoodsoftConfig @dfl = FoodsoftConfig.config - @keys = FoodsoftConfig.keys.select {|k| FoodsoftConfig.allowed_key?(k)}.sort + @keys = FoodsoftConfig.keys.select { |k| FoodsoftConfig.allowed_key?(k) }.sort end def update @@ -56,10 +55,9 @@ class Admin::ConfigsController < Admin::BaseController def convert_config_value(value) if value.is_a? ActionController::Parameters - value.transform_values{ |v| convert_config_value(v) }.to_hash + value.transform_values { |v| convert_config_value(v) }.to_hash else value end end - end diff --git a/app/controllers/admin/finances_controller.rb b/app/controllers/admin/finances_controller.rb index 3b18da5b..5eaea177 100644 --- a/app/controllers/admin/finances_controller.rb +++ b/app/controllers/admin/finances_controller.rb @@ -15,5 +15,4 @@ class Admin::FinancesController < Admin::BaseController @financial_transaction_classes = FinancialTransactionClass.includes(:financial_transaction_types).order('name ASC') render :layout => false end - end diff --git a/app/controllers/admin/ordergroups_controller.rb b/app/controllers/admin/ordergroups_controller.rb index 7bac6b8e..279cccdf 100644 --- a/app/controllers/admin/ordergroups_controller.rb +++ b/app/controllers/admin/ordergroups_controller.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 class Admin::OrdergroupsController < Admin::BaseController inherit_resources diff --git a/app/controllers/admin/workgroups_controller.rb b/app/controllers/admin/workgroups_controller.rb index 77d73177..184000bd 100644 --- a/app/controllers/admin/workgroups_controller.rb +++ b/app/controllers/admin/workgroups_controller.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 class Admin::WorkgroupsController < Admin::BaseController inherit_resources diff --git a/app/controllers/api/v1/article_categories_controller.rb b/app/controllers/api/v1/article_categories_controller.rb index ce29cb0e..7670cf1f 100644 --- a/app/controllers/api/v1/article_categories_controller.rb +++ b/app/controllers/api/v1/article_categories_controller.rb @@ -22,5 +22,4 @@ class Api::V1::ArticleCategoriesController < Api::V1::BaseController def scope ArticleCategory.all end - end diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rb index 44c793a0..13e903f1 100644 --- a/app/controllers/api/v1/base_controller.rb +++ b/app/controllers/api/v1/base_controller.rb @@ -51,26 +51,26 @@ 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} + msg = e.message.try { |m| m.sub(/\s*\[.*?\]\s*$/, '') } || 'Not found' + render status: 404, 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: 422, json: { error: 'not_acceptable', error_description: msg } end def doorkeeper_unauthorized_render_options(error:) - {json: {error: error.name, error_description: error.description}} + { json: { error: error.name, error_description: error.description } } end def doorkeeper_forbidden_render_options(error:) - {json: {error: error.name, error_description: error.description}} + { json: { error: error.name, error_description: error.description } } end def permission_required_handler(e) msg = e.message || 'Forbidden, user has no access' - render status: 403, json: {error: 'forbidden', error_description: msg} + render status: 403, json: { error: 'forbidden', error_description: msg } end # @todo something with ApplicationHelper#show_user diff --git a/app/controllers/api/v1/configs_controller.rb b/app/controllers/api/v1/configs_controller.rb index 8edb73c4..a82533fd 100644 --- a/app/controllers/api/v1/configs_controller.rb +++ b/app/controllers/api/v1/configs_controller.rb @@ -1,9 +1,7 @@ class Api::V1::ConfigsController < Api::V1::BaseController - - before_action ->{ doorkeeper_authorize! 'config:user', 'config:read', 'config:write' } + before_action -> { doorkeeper_authorize! 'config:user', 'config:read', 'config:write' } def show render json: FoodsoftConfig, serializer: ConfigSerializer, root: 'config' end - end diff --git a/app/controllers/api/v1/financial_transaction_classes_controller.rb b/app/controllers/api/v1/financial_transaction_classes_controller.rb index 4eb38ba9..f3660aa1 100644 --- a/app/controllers/api/v1/financial_transaction_classes_controller.rb +++ b/app/controllers/api/v1/financial_transaction_classes_controller.rb @@ -22,5 +22,4 @@ class Api::V1::FinancialTransactionClassesController < Api::V1::BaseController def scope FinancialTransactionClass.all end - end diff --git a/app/controllers/api/v1/financial_transaction_types_controller.rb b/app/controllers/api/v1/financial_transaction_types_controller.rb index 76552375..06c8492b 100644 --- a/app/controllers/api/v1/financial_transaction_types_controller.rb +++ b/app/controllers/api/v1/financial_transaction_types_controller.rb @@ -22,5 +22,4 @@ class Api::V1::FinancialTransactionTypesController < Api::V1::BaseController def scope FinancialTransactionType.includes(:bank_account, :financial_transaction_class) end - end diff --git a/app/controllers/api/v1/financial_transactions_controller.rb b/app/controllers/api/v1/financial_transactions_controller.rb index 539b7f6b..b37e36e9 100644 --- a/app/controllers/api/v1/financial_transactions_controller.rb +++ b/app/controllers/api/v1/financial_transactions_controller.rb @@ -1,7 +1,7 @@ class Api::V1::FinancialTransactionsController < Api::V1::BaseController include Concerns::CollectionScope - before_action ->{ doorkeeper_authorize! 'finance:read', 'finance:write' } + before_action -> { doorkeeper_authorize! 'finance:read', 'finance:write' } def index render_collection search_scope @@ -20,5 +20,4 @@ class Api::V1::FinancialTransactionsController < Api::V1::BaseController def ransack_auth_object :finance end - end diff --git a/app/controllers/api/v1/navigations_controller.rb b/app/controllers/api/v1/navigations_controller.rb index 6cd4ef0d..cce695f3 100644 --- a/app/controllers/api/v1/navigations_controller.rb +++ b/app/controllers/api/v1/navigations_controller.rb @@ -1,5 +1,4 @@ class Api::V1::NavigationsController < Api::V1::BaseController - def show # we don't use active_model_serializers here, because source is a Hash render json: { navigation: transform(navigation) } @@ -20,5 +19,4 @@ class Api::V1::NavigationsController < Api::V1::BaseController r end end - end diff --git a/app/controllers/api/v1/order_articles_controller.rb b/app/controllers/api/v1/order_articles_controller.rb index 02874a69..6e7d220d 100644 --- a/app/controllers/api/v1/order_articles_controller.rb +++ b/app/controllers/api/v1/order_articles_controller.rb @@ -1,7 +1,7 @@ class Api::V1::OrderArticlesController < Api::V1::BaseController include Concerns::CollectionScope - before_action ->{ doorkeeper_authorize! 'orders:read', 'orders:write' } + before_action -> { doorkeeper_authorize! 'orders:read', 'orders:write' } def index render_collection search_scope diff --git a/app/controllers/api/v1/orders_controller.rb b/app/controllers/api/v1/orders_controller.rb index 8eb2a066..b4e0ed84 100644 --- a/app/controllers/api/v1/orders_controller.rb +++ b/app/controllers/api/v1/orders_controller.rb @@ -1,7 +1,7 @@ class Api::V1::OrdersController < Api::V1::BaseController include Concerns::CollectionScope - before_action ->{ doorkeeper_authorize! 'orders:read', 'orders:write' } + before_action -> { doorkeeper_authorize! 'orders:read', 'orders:write' } def index render_collection search_scope diff --git a/app/controllers/api/v1/user/financial_transactions_controller.rb b/app/controllers/api/v1/user/financial_transactions_controller.rb index 947bc4aa..96b32e28 100644 --- a/app/controllers/api/v1/user/financial_transactions_controller.rb +++ b/app/controllers/api/v1/user/financial_transactions_controller.rb @@ -1,7 +1,7 @@ class Api::V1::User::FinancialTransactionsController < Api::V1::BaseController include Concerns::CollectionScope - before_action ->{ doorkeeper_authorize! 'finance:user' } + before_action -> { doorkeeper_authorize! 'finance:user' } before_action :require_ordergroup before_action :require_minimum_balance, only: [:create] before_action -> { require_config_enabled :use_self_service }, only: [:create] @@ -29,5 +29,4 @@ class Api::V1::User::FinancialTransactionsController < Api::V1::BaseController def create_params params.require(:financial_transaction).permit(:amount, :financial_transaction_type_id, :note) end - end diff --git a/app/controllers/api/v1/user/group_order_articles_controller.rb b/app/controllers/api/v1/user/group_order_articles_controller.rb index 86841065..eeeb122c 100644 --- a/app/controllers/api/v1/user/group_order_articles_controller.rb +++ b/app/controllers/api/v1/user/group_order_articles_controller.rb @@ -1,7 +1,7 @@ class Api::V1::User::GroupOrderArticlesController < Api::V1::BaseController include Concerns::CollectionScope - before_action ->{ doorkeeper_authorize! 'group_orders:user' } + before_action -> { doorkeeper_authorize! 'group_orders:user' } before_action :require_ordergroup before_action :require_minimum_balance, only: [:create, :update] # destroy is ok @@ -62,10 +62,10 @@ class Api::V1::User::GroupOrderArticlesController < Api::V1::BaseController end def scope - GroupOrderArticle. - joins(:group_order). - includes(order_article: :article, group_order: :order). - where(group_orders: { ordergroup_id: current_ordergroup.id }) + GroupOrderArticle + .joins(:group_order) + .includes(order_article: :article, group_order: :order) + .where(group_orders: { ordergroup_id: current_ordergroup.id }) end def scope_for_update diff --git a/app/controllers/api/v1/user/ordergroup_controller.rb b/app/controllers/api/v1/user/ordergroup_controller.rb index 7af268f2..08c12b4c 100644 --- a/app/controllers/api/v1/user/ordergroup_controller.rb +++ b/app/controllers/api/v1/user/ordergroup_controller.rb @@ -1,6 +1,5 @@ class Api::V1::User::OrdergroupController < Api::V1::BaseController - - before_action ->{ doorkeeper_authorize! 'finance:user' }, only: [:financial_overview] + before_action -> { doorkeeper_authorize! 'finance:user' }, only: [:financial_overview] def financial_overview ordergroup = Ordergroup.include_transaction_class_sum.find(current_ordergroup.id) @@ -19,5 +18,4 @@ class Api::V1::User::OrdergroupController < Api::V1::BaseController } } end - end diff --git a/app/controllers/api/v1/user/users_controller.rb b/app/controllers/api/v1/user/users_controller.rb index e95e4790..9b983c2d 100644 --- a/app/controllers/api/v1/user/users_controller.rb +++ b/app/controllers/api/v1/user/users_controller.rb @@ -1,9 +1,7 @@ class Api::V1::User::UsersController < Api::V1::BaseController - - before_action ->{ doorkeeper_authorize! 'user:read', 'user:write' } + before_action -> { doorkeeper_authorize! 'user:read', 'user:write' } def show render json: current_user end - end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 456968d7..eb90f9b4 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 class ApplicationController < ActionController::Base include Concerns::FoodcoopScope include Concerns::Auth @@ -8,11 +7,10 @@ class ApplicationController < ActionController::Base helper_method :available_locales protect_from_forgery - before_action :authenticate, :set_user_last_activity, :store_controller, :items_per_page + before_action :authenticate, :set_user_last_activity, :store_controller, :items_per_page after_action :remove_controller around_action :set_time_zone, :set_currency - # Returns the controller handling the current request. def self.current Thread.current[:application_controller] @@ -90,10 +88,9 @@ class ApplicationController < ActionController::Base old_currency = ::I18n.t('number.currency.format.unit') new_currency = FoodsoftConfig[:currency_unit] || '' new_currency += "\u202f" if FoodsoftConfig[:currency_space] - ::I18n.backend.store_translations(::I18n.locale, number: {currency: {format: {unit: new_currency}}}) + ::I18n.backend.store_translations(::I18n.locale, number: { currency: { format: { unit: new_currency } } }) yield ensure - ::I18n.backend.store_translations(::I18n.locale, number: {currency: {format: {unit: old_currency}}}) + ::I18n.backend.store_translations(::I18n.locale, number: { currency: { format: { unit: old_currency } } }) end - end diff --git a/app/controllers/article_categories_controller.rb b/app/controllers/article_categories_controller.rb index 75189f78..bfa601d3 100644 --- a/app/controllers/article_categories_controller.rb +++ b/app/controllers/article_categories_controller.rb @@ -1,5 +1,4 @@ class ArticleCategoriesController < ApplicationController - inherit_resources # Build default REST Actions via plugin before_action :authenticate_article_meta @@ -23,5 +22,4 @@ class ArticleCategoriesController < ApplicationController def collection @article_categories = ArticleCategory.order('name') end - end diff --git a/app/controllers/articles_controller.rb b/app/controllers/articles_controller.rb index ec1ac386..5e8c402d 100644 --- a/app/controllers/articles_controller.rb +++ b/app/controllers/articles_controller.rb @@ -1,21 +1,20 @@ -# encoding: utf-8 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" - end + 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 @@ -99,7 +98,7 @@ class ArticlesController < ApplicationController end end - raise ActiveRecord::Rollback if invalid_articles # Rollback all changes + raise ActiveRecord::Rollback if invalid_articles # Rollback all changes end end end @@ -117,25 +116,25 @@ class ArticlesController < ApplicationController # makes different actions on selected articles def update_selected raise I18n.t('articles.controller.error_nosel') if params[:selected_articles].nil? + articles = Article.find(params[:selected_articles]) Article.transaction do case params[:selected_action] - when 'destroy' - articles.each(&:mark_as_deleted) - flash[:notice] = I18n.t('articles.controller.update_sel.notice_destroy') - when 'setNotAvailable' - articles.each {|a| a.update_attribute(:availability, false) } - flash[:notice] = I18n.t('articles.controller.update_sel.notice_unavail') - when 'setAvailable' - articles.each {|a| a.update_attribute(:availability, true) } - flash[:notice] = I18n.t('articles.controller.update_sel.notice_avail') - else - flash[:alert] = I18n.t('articles.controller.update_sel.notice_noaction') + when 'destroy' + articles.each(&:mark_as_deleted) + flash[:notice] = I18n.t('articles.controller.update_sel.notice_destroy') + when 'setNotAvailable' + articles.each { |a| a.update_attribute(:availability, false) } + flash[:notice] = I18n.t('articles.controller.update_sel.notice_unavail') + when 'setAvailable' + articles.each { |a| a.update_attribute(:availability, true) } + flash[:notice] = I18n.t('articles.controller.update_sel.notice_avail') + else + flash[:alert] = I18n.t('articles.controller.update_sel.notice_noaction') 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) @@ -149,7 +148,7 @@ class ArticlesController < ApplicationController # Update articles from a spreadsheet def parse_upload uploaded_file = params[:articles]['file'] or raise I18n.t('articles.controller.parse_upload.no_file') - options = {filename: uploaded_file.original_filename} + 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 @@ -177,10 +176,10 @@ class ArticlesController < ApplicationController # Updates, deletes articles when upload or sync form is submitted def update_synchronized - @outlisted_articles = Article.find(params[:outlisted_articles].try(:keys)||[]) - @updated_articles = Article.find(params[:articles].try(:keys)||[]) - @updated_articles.map{|a| a.assign_attributes(params[:articles][a.id.to_s]) } - @new_articles = (params[:new_articles]||[]).map{|a| @supplier.articles.build(a) } + @outlisted_articles = Article.find(params[:outlisted_articles].try(:keys) || []) + @updated_articles = Article.find(params[:articles].try(:keys) || []) + @updated_articles.map { |a| a.assign_attributes(params[:articles][a.id.to_s]) } + @new_articles = (params[:new_articles] || []).map { |a| @supplier.articles.build(a) } has_error = false Article.transaction do @@ -192,9 +191,9 @@ class ArticlesController < ApplicationController has_error = true end # Update articles - @updated_articles.each {|a| a.save or has_error=true } + @updated_articles.each { |a| a.save or has_error = true } # Add new articles - @new_articles.each {|a| a.save or has_error=true } + @new_articles.each { |a| a.save or has_error = true } raise ActiveRecord::Rollback if has_error end diff --git a/app/controllers/concerns/auth.rb b/app/controllers/concerns/auth.rb index fbf32a23..277acd69 100644 --- a/app/controllers/concerns/auth.rb +++ b/app/controllers/concerns/auth.rb @@ -24,7 +24,7 @@ module Concerns::Auth def login(user) session[:user_id] = user.id - session[:scope] = FoodsoftConfig.scope # Save scope in session to not allow switching between foodcoops with one account + session[:scope] = FoodsoftConfig.scope # Save scope in session to not allow switching between foodcoops with one account session[:locale] = user.locale end @@ -56,18 +56,18 @@ module Concerns::Auth # We have an authenticated user, now check role... # Roles gets the user through his memberships. hasRole = case role - when 'admin' then current_user.role_admin? - when 'finance' then current_user.role_finance? - when 'article_meta' then current_user.role_article_meta? - when 'pickups' then current_user.role_pickups? - when 'suppliers' then current_user.role_suppliers? - when 'orders' then current_user.role_orders? - when 'finance_or_invoices' then (current_user.role_finance? || current_user.role_invoices?) - when 'finance_or_orders' then (current_user.role_finance? || current_user.role_orders?) - when 'pickups_or_orders' then (current_user.role_pickups? || current_user.role_orders?) - when 'any' then true # no role required - else false # any unknown role will always fail - end + when 'admin' then current_user.role_admin? + when 'finance' then current_user.role_finance? + when 'article_meta' then current_user.role_article_meta? + when 'pickups' then current_user.role_pickups? + when 'suppliers' then current_user.role_suppliers? + when 'orders' then current_user.role_orders? + when 'finance_or_invoices' then (current_user.role_finance? || current_user.role_invoices?) + when 'finance_or_orders' then (current_user.role_finance? || current_user.role_orders?) + when 'pickups_or_orders' then (current_user.role_pickups? || current_user.role_orders?) + when 'any' then true # no role required + else false # any unknown role will always fail + end if hasRole current_user else @@ -137,6 +137,7 @@ module Concerns::Auth # @see https://github.com/doorkeeper-gem/doorkeeper/issues/71#issuecomment-5471317 def expire_access_tokens return unless @current_user + Doorkeeper::AccessToken.transaction do token_scope = Doorkeeper::AccessToken.where(revoked_at: nil, resource_owner_id: @current_user.id) token_scope.each do |token| @@ -146,8 +147,7 @@ module Concerns::Auth end # Redirect to the login page, used in authenticate, plugins can override this. - def redirect_to_login(options={}) + def redirect_to_login(options = {}) redirect_to login_url, options end - end diff --git a/app/controllers/concerns/auth_api.rb b/app/controllers/concerns/auth_api.rb index fe93af97..2c80dddf 100644 --- a/app/controllers/concerns/auth_api.rb +++ b/app/controllers/concerns/auth_api.rb @@ -36,7 +36,7 @@ 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) } + unless scopes.any? { |scope| doorkeeper_scope_permitted?(scope) } raise Api::Errors::PermissionRequired.new('Forbidden, no permission') end end @@ -60,7 +60,7 @@ module Concerns::AuthApi when 'suppliers' then return current_user.role_suppliers? when 'group_orders' then return current_user.role_orders? when 'finance' then return current_user.role_finance? - # please note that offline_access does not belong here, since it is not used for permission checking + # please note that offline_access does not belong here, since it is not used for permission checking end case scope diff --git a/app/controllers/concerns/collection_scope.rb b/app/controllers/concerns/collection_scope.rb index c4ddf798..d65f22b6 100644 --- a/app/controllers/concerns/collection_scope.rb +++ b/app/controllers/concerns/collection_scope.rb @@ -54,5 +54,4 @@ module Concerns::CollectionScope def ransack_auth_object nil end - end diff --git a/app/controllers/concerns/foodcoop_scope.rb b/app/controllers/concerns/foodcoop_scope.rb index 416ad2ee..0a8e382e 100644 --- a/app/controllers/concerns/foodcoop_scope.rb +++ b/app/controllers/concerns/foodcoop_scope.rb @@ -30,7 +30,6 @@ module Concerns::FoodcoopScope # Always stay in foodcoop url scope def default_url_options(options = {}) - super().merge({foodcoop: FoodsoftConfig.scope}) + super().merge({ foodcoop: FoodsoftConfig.scope }) end - end diff --git a/app/controllers/concerns/locale.rb b/app/controllers/concerns/locale.rb index e8a4c285..22686c15 100644 --- a/app/controllers/concerns/locale.rb +++ b/app/controllers/concerns/locale.rb @@ -47,5 +47,4 @@ module Concerns::Locale locale = session[:locale] = ::I18n.locale logger.info("Set locale to #{locale}") end - end diff --git a/app/controllers/concerns/send_order_pdf.rb b/app/controllers/concerns/send_order_pdf.rb index 26003e9f..09225b7c 100644 --- a/app/controllers/concerns/send_order_pdf.rb +++ b/app/controllers/concerns/send_order_pdf.rb @@ -9,9 +9,8 @@ module Concerns::SendOrderPdf when 'articles' then OrderByArticles when 'fax' then OrderFax when 'matrix' then OrderMatrix - end + end pdf = klass.new order send_data pdf.to_pdf, filename: pdf.filename, type: 'application/pdf' end - end diff --git a/app/controllers/deliveries_controller.rb b/app/controllers/deliveries_controller.rb index 5ecb4888..21ae0c71 100644 --- a/app/controllers/deliveries_controller.rb +++ b/app/controllers/deliveries_controller.rb @@ -1,6 +1,4 @@ -# encoding: utf-8 class DeliveriesController < ApplicationController - before_action :find_supplier, :exclude => :fill_new_stock_article_form def index @@ -14,7 +12,7 @@ class DeliveriesController < ApplicationController def new @delivery = @supplier.deliveries.build - @delivery.date = Date.today #TODO: move to model/database + @delivery.date = Date.today # TODO: move to model/database end def create @@ -37,7 +35,7 @@ class DeliveriesController < ApplicationController if @delivery.update_attributes(params[:delivery]) flash[:notice] = I18n.t('deliveries.update.notice') - redirect_to [@supplier,@delivery] + redirect_to [@supplier, @delivery] else render :action => "edit" end @@ -68,5 +66,4 @@ class DeliveriesController < ApplicationController render :layout => false end - end diff --git a/app/controllers/feedback_controller.rb b/app/controllers/feedback_controller.rb index 73ed9d9f..ada72859 100644 --- a/app/controllers/feedback_controller.rb +++ b/app/controllers/feedback_controller.rb @@ -1,5 +1,4 @@ class FeedbackController < ApplicationController - def new end @@ -11,5 +10,4 @@ class FeedbackController < ApplicationController render :action => 'new' end end - end diff --git a/app/controllers/finance/balancing_controller.rb b/app/controllers/finance/balancing_controller.rb index 016199da..09c109f8 100644 --- a/app/controllers/finance/balancing_controller.rb +++ b/app/controllers/finance/balancing_controller.rb @@ -1,6 +1,4 @@ -# encoding: utf-8 class Finance::BalancingController < Finance::BaseController - def index @orders = Order.finished.page(params[:page]).per(@per_page).order('ends DESC') end @@ -11,20 +9,20 @@ class Finance::BalancingController < Finance::BaseController @comments = @order.comments @articles = @order.order_articles.ordered_or_member.includes(:article, :article_price, - group_order_articles: {group_order: :ordergroup}) + group_order_articles: { group_order: :ordergroup }) sort_param = params['sort'] || 'name' @articles = case sort_param - when 'name' then - @articles.order('articles.name ASC') - when 'name_reverse' then - @articles.order('articles.name DESC') - when 'order_number' then - @articles.order('articles.order_number ASC') - when 'order_number_reverse' then - @articles.order('articles.order_number DESC') - else - @articles + when 'name' then + @articles.order('articles.name ASC') + when 'name_reverse' then + @articles.order('articles.name DESC') + when 'order_number' then + @articles.order('articles.order_number ASC') + when 'order_number_reverse' then + @articles.order('articles.order_number DESC') + else + @articles end render layout: false if request.xhr? @@ -84,7 +82,6 @@ class Finance::BalancingController < Finance::BaseController @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) end @@ -110,5 +107,4 @@ class Finance::BalancingController < Finance::BaseController rescue => error redirect_to finance_order_index_url, alert: t('errors.general_msg', msg: error.message) end - end diff --git a/app/controllers/finance/bank_accounts_controller.rb b/app/controllers/finance/bank_accounts_controller.rb index cdea8760..66d9fddd 100644 --- a/app/controllers/finance/bank_accounts_controller.rb +++ b/app/controllers/finance/bank_accounts_controller.rb @@ -1,5 +1,4 @@ class Finance::BankAccountsController < Finance::BaseController - def index @bank_accounts = BankAccount.order('name') redirect_to finance_bank_account_transactions_url(@bank_accounts.first) if @bank_accounts.count == 1 @@ -26,7 +25,7 @@ class Finance::BankAccountsController < Finance::BaseController flash.notice = t('.notice', count: importer.count) if ok @auto_submit = importer.auto_submit @controls = importer.controls - #TODO: encrypt state + # TODO: encrypt state @state = YAML.dump importer.dump else ok = true @@ -39,6 +38,7 @@ class Finance::BankAccountsController < Finance::BaseController needs_redirect = true ensure return unless needs_redirect + redirect_path = finance_bank_account_transactions_url(@bank_account) if request.post? @js_redirect = redirect_path @@ -46,5 +46,4 @@ class Finance::BankAccountsController < Finance::BaseController redirect_to redirect_path end end - end diff --git a/app/controllers/finance/bank_transactions_controller.rb b/app/controllers/finance/bank_transactions_controller.rb index 32ad94a5..53c35168 100644 --- a/app/controllers/finance/bank_transactions_controller.rb +++ b/app/controllers/finance/bank_transactions_controller.rb @@ -5,12 +5,12 @@ class Finance::BankTransactionsController < ApplicationController 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" + 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" diff --git a/app/controllers/finance/financial_links_controller.rb b/app/controllers/finance/financial_links_controller.rb index 0392a800..17d8399a 100644 --- a/app/controllers/finance/financial_links_controller.rb +++ b/app/controllers/finance/financial_links_controller.rb @@ -110,13 +110,13 @@ class Finance::FinancialLinksController < Finance::BaseController redirect_to finance_link_url(@financial_link), notice: t('.notice') end -protected + protected def find_financial_link @financial_link = FinancialLink.find(params[:id]) end -private + private def financial_transaction_params params.require(:financial_transaction).permit(:financial_transaction_type_id, :ordergroup_id, :amount, :note) @@ -128,5 +128,4 @@ private JOIN bank_transactions b ON a.iban = b.iban AND b.financial_link_id = #{financial_link_id.to_i} SQL end - end diff --git a/app/controllers/finance/financial_transactions_controller.rb b/app/controllers/finance/financial_transactions_controller.rb index 46dbbe67..8b9d372d 100644 --- a/app/controllers/finance/financial_transactions_controller.rb +++ b/app/controllers/finance/financial_transactions_controller.rb @@ -1,20 +1,19 @@ -# encoding: utf-8 class Finance::FinancialTransactionsController < ApplicationController before_action :authenticate_finance before_action :find_ordergroup, :except => [:new_collection, :create_collection, :index_collection] inherit_resources -# belongs_to :ordergroup + # 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" - end + 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 @@ -79,6 +78,7 @@ class Finance::FinancialTransactionsController < ApplicationController def create_collection raise I18n.t('finance.financial_transactions.controller.create_collection.error_note_required') if params[:note].blank? + type = FinancialTransactionType.find_by_id(params[:type_id]) financial_link = nil @@ -103,12 +103,12 @@ class Finance::FinancialTransactionsController < ApplicationController if params[:create_foodcoop_transaction] ft = FinancialTransaction.new({ - financial_transaction_type: type, - user: @current_user, - amount: foodcoop_amount, - note: params[:note], - financial_link: financial_link, - }) + financial_transaction_type: type, + user: @current_user, + amount: foodcoop_amount, + note: params[:note], + financial_link: financial_link, + }) ft.save! end @@ -131,5 +131,4 @@ class Finance::FinancialTransactionsController < ApplicationController @foodcoop = true end end - end diff --git a/app/controllers/finance/ordergroups_controller.rb b/app/controllers/finance/ordergroups_controller.rb index 6aeacc9e..cb661571 100644 --- a/app/controllers/finance/ordergroups_controller.rb +++ b/app/controllers/finance/ordergroups_controller.rb @@ -1,5 +1,4 @@ class Finance::OrdergroupsController < Finance::BaseController - def index m = /^(?name|sum_of_class_\d+)(?_reverse)?$/.match params["sort"] if m diff --git a/app/controllers/foodcoop/ordergroups_controller.rb b/app/controllers/foodcoop/ordergroups_controller.rb index d557cb72..6ef90245 100644 --- a/app/controllers/foodcoop/ordergroups_controller.rb +++ b/app/controllers/foodcoop/ordergroups_controller.rb @@ -1,5 +1,4 @@ class Foodcoop::OrdergroupsController < ApplicationController - def index @ordergroups = Ordergroup.undeleted.order('name') diff --git a/app/controllers/foodcoop/users_controller.rb b/app/controllers/foodcoop/users_controller.rb index 880d4407..a3a8bd45 100644 --- a/app/controllers/foodcoop/users_controller.rb +++ b/app/controllers/foodcoop/users_controller.rb @@ -1,5 +1,4 @@ class Foodcoop::UsersController < ApplicationController - def index @users = User.undeleted.natural_order @@ -17,5 +16,4 @@ class Foodcoop::UsersController < ApplicationController format.js { render :layout => false } # index.js.erb end end - end diff --git a/app/controllers/foodcoop/workgroups_controller.rb b/app/controllers/foodcoop/workgroups_controller.rb index 72f7fb90..794c21a0 100644 --- a/app/controllers/foodcoop/workgroups_controller.rb +++ b/app/controllers/foodcoop/workgroups_controller.rb @@ -1,16 +1,15 @@ class Foodcoop::WorkgroupsController < ApplicationController - before_action :authenticate_membership_or_admin, - :except => [:index] + :except => [:index] def index @workgroups = Workgroup.order("name") end - + def edit @workgroup = Workgroup.find(params[:id]) end - + def update @workgroup = Workgroup.find(params[:id]) if @workgroup.update_attributes(params[:workgroup]) diff --git a/app/controllers/group_order_articles_controller.rb b/app/controllers/group_order_articles_controller.rb index 3fcba631..d34db7a1 100644 --- a/app/controllers/group_order_articles_controller.rb +++ b/app/controllers/group_order_articles_controller.rb @@ -1,5 +1,4 @@ class GroupOrderArticlesController < ApplicationController - before_action :authenticate_finance before_action :find_group_order_article, except: [:new, :create] @@ -30,7 +29,7 @@ class GroupOrderArticlesController < ApplicationController update_summaries(@group_order_article) render :create - else # Validation failed, show form + else # Validation failed, show form render :new end end @@ -50,7 +49,7 @@ class GroupOrderArticlesController < ApplicationController def destroy # only destroy if quantity and tolerance was zero already, so that we don't # lose what the user ordered, if any - if @group_order_article.quantity > 0 || @group_order_article.tolerance >0 + if @group_order_article.quantity > 0 || @group_order_article.tolerance > 0 @group_order_article.update_attribute(:result, 0) else @group_order_article.destroy diff --git a/app/controllers/group_orders_controller.rb b/app/controllers/group_orders_controller.rb index 2b87dc3e..686f0617 100644 --- a/app/controllers/group_orders_controller.rb +++ b/app/controllers/group_orders_controller.rb @@ -33,7 +33,7 @@ class GroupOrdersController < ApplicationController end def show - @order= @group_order.order + @order = @group_order.order end def edit @@ -100,12 +100,11 @@ class GroupOrdersController < ApplicationController 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]) + stop_ordering_under: FoodsoftConfig[:stop_ordering_under]) end end def order_id_param params[:order_id] || (params[:group_order] && params[:group_order][:order_id]) end - end diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index 87062876..6f677b6b 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -1,6 +1,4 @@ -# encoding: utf-8 class HomeController < ApplicationController - def index # unaccepted tasks @unaccepted_tasks = Task.order(:due_date).unaccepted_tasks_for(current_user) @@ -44,13 +42,13 @@ class HomeController < ApplicationController 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" - end + 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 @@ -88,5 +86,4 @@ class HomeController < ApplicationController params.require(:user).require(:ordergroup).permit(:contact_address) end end - end diff --git a/app/controllers/invites_controller.rb b/app/controllers/invites_controller.rb index b6fee901..37fc757b 100644 --- a/app/controllers/invites_controller.rb +++ b/app/controllers/invites_controller.rb @@ -1,12 +1,11 @@ class InvitesController < ApplicationController - before_action :authenticate_membership_or_admin_for_invites before_action -> { require_config_disabled :disable_invite } def new @invite = Invite.new(:user => @current_user, :group => @group) end - + def create authenticate_membership_or_admin params[:invite][:group_id] @invite = Invite.new(params[:invite]) diff --git a/app/controllers/login_controller.rb b/app/controllers/login_controller.rb index 73ca00cc..052231c5 100644 --- a/app/controllers/login_controller.rb +++ b/app/controllers/login_controller.rb @@ -1,13 +1,12 @@ -# encoding: utf-8 class LoginController < ApplicationController - skip_before_action :authenticate # no authentication since this is the login page + skip_before_action :authenticate # no authentication since this is the login page before_action :validate_token, :only => [:new_password, :update_password] # Display the form to enter an email address requesting a token to set a new password. def forgot_password @user = User.new end - + # 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. @@ -19,12 +18,12 @@ class LoginController < ApplicationController end 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 - + # Sets a new password. # Called with params :id => User.id and :token => User.reset_password_token to specify a new password. def update_password diff --git a/app/controllers/order_comments_controller.rb b/app/controllers/order_comments_controller.rb index a047dc3a..39067577 100644 --- a/app/controllers/order_comments_controller.rb +++ b/app/controllers/order_comments_controller.rb @@ -1,5 +1,4 @@ class OrderCommentsController < ApplicationController - def new @order = Order.find(params[:order_id]) @order_comment = @order.comments.build(:user => current_user) diff --git a/app/controllers/orders_controller.rb b/app/controllers/orders_controller.rb index 43ede670..9323670f 100644 --- a/app/controllers/orders_controller.rb +++ b/app/controllers/orders_controller.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 # # Controller for managing orders, i.e. all actions that require the "orders" role. # Normal ordering actions of members of order groups is handled by the OrderingController. @@ -16,12 +15,12 @@ class OrdersController < ApplicationController @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" - end + 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 @@ -32,13 +31,13 @@ class OrdersController < ApplicationController # Gives a view for the results to a specific order # Renders also the pdf def show - @order= Order.find(params[:id]) + @order = Order.find(params[:id]) @view = (params[:view] || 'default').gsub(/[^-_a-zA-Z0-9]/, '') @partial = case @view - when 'default' then 'articles' - when 'groups' then 'shared/articles_by/groups' - when 'articles' then 'shared/articles_by/articles' - else 'articles' + when 'default' then 'articles' + when 'groups' then 'shared/articles_by/groups' + when 'articles' then 'shared/articles_by/articles' + else 'articles' end respond_to do |format| @@ -50,10 +49,10 @@ class OrdersController < ApplicationController send_order_pdf @order, params[:document] end format.csv do - send_data OrderCsv.new(@order).to_csv, filename: @order.name+'.csv', type: 'text/csv' + send_data OrderCsv.new(@order).to_csv, filename: @order.name + '.csv', type: 'text/csv' end format.text do - send_data OrderTxt.new(@order).to_txt, filename: @order.name+'.txt', type: 'text/plain' + send_data OrderTxt.new(@order).to_txt, filename: @order.name + '.txt', type: 'text/plain' end end end @@ -163,6 +162,7 @@ class OrdersController < ApplicationController def update_order_amounts return if not params[:order_articles] + # where to leave remainder during redistribution rest_to = [] rest_to << :tolerance if params[:rest_to_tolerance] @@ -186,18 +186,19 @@ class OrdersController < ApplicationController 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 } + oacounts.each_with_index { |c, i| cunits[i + 1] += c; counts[i + 1] += 1 if c > 0 } end end oa.save! end 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] 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 + if counts[3] > 0 || cunits[3] > 0 notice << I18n.t('orders.update_order_amounts.msg4', count: counts[3], units: cunits[3]) end notice.join(', ') @@ -206,5 +207,4 @@ class OrdersController < ApplicationController def remove_empty_article params[:order][:article_ids].reject!(&:blank?) if params[:order] && params[:order][:article_ids] end - end diff --git a/app/controllers/pickups_controller.rb b/app/controllers/pickups_controller.rb index 62c07d1b..38929bcc 100644 --- a/app/controllers/pickups_controller.rb +++ b/app/controllers/pickups_controller.rb @@ -1,5 +1,4 @@ class PickupsController < ApplicationController - before_action :authenticate_pickups def index diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index e89e5771..5b3d0780 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -1,5 +1,4 @@ class SessionsController < ApplicationController - skip_before_action :authenticate layout 'login' @@ -30,5 +29,4 @@ class SessionsController < ApplicationController def redirect_to_foodcoop redirect_to root_path end - end diff --git a/app/controllers/stockit_controller.rb b/app/controllers/stockit_controller.rb index d04d866b..c44e3380 100644 --- a/app/controllers/stockit_controller.rb +++ b/app/controllers/stockit_controller.rb @@ -1,8 +1,7 @@ class StockitController < ApplicationController - def index - @stock_articles = StockArticle.undeleted.includes(:supplier, :article_category). - order('suppliers.name, article_categories.name, articles.name') + @stock_articles = StockArticle.undeleted.includes(:supplier, :article_category) + .order('suppliers.name, article_categories.name, articles.name') end def index_on_stock_article_create # See publish/subscribe design pattern in /doc. @@ -40,7 +39,7 @@ class StockitController < ApplicationController end def create - @stock_article = StockArticle.new({quantity: 0}.merge(params[:stock_article])) + @stock_article = StockArticle.new({ quantity: 0 }.merge(params[:stock_article])) @stock_article.save! render :layout => false rescue ActiveRecord::RecordInvalid @@ -78,10 +77,10 @@ class StockitController < ApplicationController render :layout => false rescue => error render :partial => "destroy_fail", :layout => false, - :locals => { :fail_msg => I18n.t('errors.general_msg', :msg => error.message) } + :locals => { :fail_msg => I18n.t('errors.general_msg', :msg => error.message) } end - #TODO: Fix this!! + # TODO: Fix this!! def articles_search @articles = Article.not_in_stock.limit(8).where('name LIKE ?', "%#{params[:term]}%") render :json => @articles.map(&:name) diff --git a/app/controllers/styles_controller.rb b/app/controllers/styles_controller.rb index fe45d316..5636ec03 100644 --- a/app/controllers/styles_controller.rb +++ b/app/controllers/styles_controller.rb @@ -11,7 +11,7 @@ class StylesController < ApplicationController if css.blank? render body: nil, content_type: 'text/css', status: 404 else - expires_in 1.week, public:true if params[:md5].present? + expires_in 1.week, public: true if params[:md5].present? render body: css, content_type: 'text/css' end end diff --git a/app/controllers/suppliers_controller.rb b/app/controllers/suppliers_controller.rb index 7e805dca..058c4fbc 100644 --- a/app/controllers/suppliers_controller.rb +++ b/app/controllers/suppliers_controller.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 class SuppliersController < ApplicationController before_action :authenticate_suppliers, :except => [:index, :list] helper :deliveries @@ -18,7 +17,7 @@ class SuppliersController < ApplicationController # if shared_supplier_id is given, the new supplier will filled whith its attributes def new if params[:shared_supplier_id] - shared_supplier = SharedSupplier.find(params[:shared_supplier_id]) + shared_supplier = SharedSupplier.find(params[:shared_supplier_id]) @supplier = shared_supplier.suppliers.new(shared_supplier.autofill_attributes) else @supplier = Supplier.new @@ -55,9 +54,9 @@ 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) - redirect_to @supplier + rescue => e + flash[:error] = I18n.t('errors.general_msg', :msg => e.message) + redirect_to @supplier end # gives a list with all available shared_suppliers @@ -74,5 +73,4 @@ class SuppliersController < ApplicationController :iban, :custom_fields, :delivery_days, :order_howto, :note, :supplier_category_id, :shared_supplier_id, :min_order_quantity, :shared_sync_method) end - end diff --git a/app/controllers/tasks_controller.rb b/app/controllers/tasks_controller.rb index 92de0081..db4ca1ab 100644 --- a/app/controllers/tasks_controller.rb +++ b/app/controllers/tasks_controller.rb @@ -1,10 +1,9 @@ -# encoding: utf-8 class TasksController < ApplicationController - #auto_complete_for :user, :nick + # auto_complete_for :user, :nick def index @non_group_tasks = Task.non_group.order('due_date', 'name').includes(assignments: :user) - @groups = Workgroup.order(:name).includes(open_tasks: {assignments: :user}) + @groups = Workgroup.order(:name).includes(open_tasks: { assignments: :user }) end def user @@ -19,7 +18,7 @@ class TasksController < ApplicationController def create @task = Task.new(current_user_id: current_user.id) @task.created_by = current_user - @task.attributes=(task_params) + @task.attributes = (task_params) if params[:periodic] @task.periodic_task_group = PeriodicTaskGroup.new end @@ -47,7 +46,7 @@ class TasksController < ApplicationController was_periodic = @task.periodic? prev_due_date = @task.due_date @task.current_user_id = current_user.id - @task.attributes=(task_params) + @task.attributes = (task_params) 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') @@ -122,5 +121,4 @@ class TasksController < ApplicationController .require(:task) .permit(:name, :description, :duration, :user_list, :required_users, :workgroup_id, :due_date, :done) end - end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 71bede1d..503bc79b 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,5 +1,4 @@ class UsersController < ApplicationController - # Currently used to display users nick and ids for autocomplete def index @users = User.undeleted.natural_search(params[:q]) @@ -7,5 +6,4 @@ class UsersController < ApplicationController format.json { render :json => @users.map(&:token_attributes).to_json } end end - end diff --git a/app/documents/order_by_articles.rb b/app/documents/order_by_articles.rb index fabfcb9e..84fb5c00 100644 --- a/app/documents/order_by_articles.rb +++ b/app/documents/order_by_articles.rb @@ -1,13 +1,11 @@ -# encoding: utf-8 class OrderByArticles < OrderPdf - def filename I18n.t('documents.order_by_articles.filename', :name => order.name, :date => order.ends.to_date) + '.pdf' end def title I18n.t('documents.order_by_articles.title', :name => order.name, - :date => order.ends.strftime(I18n.t('date.formats.default'))) + :date => order.ends.strftime(I18n.t('date.formats.default'))) end def body diff --git a/app/documents/order_by_groups.rb b/app/documents/order_by_groups.rb index 7245593a..d6711731 100644 --- a/app/documents/order_by_groups.rb +++ b/app/documents/order_by_groups.rb @@ -1,13 +1,11 @@ -# encoding: utf-8 class OrderByGroups < OrderPdf - def filename I18n.t('documents.order_by_groups.filename', :name => order.name, :date => order.ends.to_date) + '.pdf' end def title I18n.t('documents.order_by_groups.title', :name => order.name, - :date => order.ends.strftime(I18n.t('date.formats.default'))) + :date => order.ends.strftime(I18n.t('date.formats.default'))) end def body @@ -25,14 +23,15 @@ class OrderByGroups < OrderPdf each_group_order_article_for_ordergroup(oa_id) do |goa| dimrows << rows.length if goa.result == 0 - rows << [goa.order_article.article.name, - goa.group_order.order.name, - group_order_article_quantity_with_tolerance(goa), - group_order_article_result(goa), - order_article_price_per_unit(goa.order_article), - number_to_currency(goa.total_price)] + rows << [goa.order_article.article.name, + goa.group_order.order.name, + group_order_article_quantity_with_tolerance(goa), + group_order_article_result(goa), + order_article_price_per_unit(goa.order_article), + number_to_currency(goa.total_price)] end next unless rows.length > 1 + rows << [nil, nil, nil, nil, nil, number_to_currency(oa_total)] if has_transport rows << [GroupOrder.human_attribute_name(:transport), nil, nil, nil, nil, number_to_currency(oa_transport)] @@ -64,5 +63,4 @@ class OrderByGroups < OrderPdf end end end - end diff --git a/app/documents/order_fax.rb b/app/documents/order_fax.rb index 33dbbe2b..b4b50577 100644 --- a/app/documents/order_fax.rb +++ b/app/documents/order_fax.rb @@ -1,6 +1,4 @@ -# encoding: utf-8 class OrderFax < OrderPdf - BATCH_SIZE = 250 def filename @@ -15,7 +13,7 @@ class OrderFax < OrderPdf contact = FoodsoftConfig[:contact].symbolize_keys # From paragraph - bounding_box [margin_box.right-200,margin_box.top], width: 200 do + bounding_box [margin_box.right - 200, margin_box.top], width: 200 do text FoodsoftConfig[:name], size: fontsize(9), align: :right move_down 5 text contact[:street], size: fontsize(9), align: :right @@ -36,7 +34,7 @@ class OrderFax < OrderPdf end # Recipient - bounding_box [margin_box.left,margin_box.top-60], width: 200 do + bounding_box [margin_box.left, margin_box.top - 60], width: 200 do text order.name move_down 5 text order.supplier.try(:address).to_s @@ -72,7 +70,7 @@ class OrderFax < OrderPdf number_to_currency(subtotal)] end data << [I18n.t('documents.order_fax.total'), nil, nil, nil, nil, nil, number_to_currency(total)] - table data, cell_style: {size: fontsize(8), overflow: :shrink_to_fit} do |table| + table data, cell_style: { size: fontsize(8), overflow: :shrink_to_fit } do |table| table.header = true table.cells.border_width = 1 table.cells.border_color = '666666' @@ -80,28 +78,27 @@ class OrderFax < OrderPdf table.row(0).border_bottom_width = 2 table.columns(1).align = :right table.columns(3..6).align = :right - table.row(data.length-1).columns(0..5).borders = [:top, :bottom] - table.row(data.length-1).columns(0).borders = [:top, :bottom, :left] - table.row(data.length-1).border_top_width = 2 + table.row(data.length - 1).columns(0..5).borders = [:top, :bottom] + table.row(data.length - 1).columns(0).borders = [:top, :bottom, :left] + table.row(data.length - 1).border_top_width = 2 end - #font_size: fontsize(8), - #vertical_padding: 3, - #border_style: :grid, - #headers: ["BestellNr.", "Menge","Name", "Gebinde", "Einheit","Preis/Einheit"], - #align: {0 => :left} + # font_size: fontsize(8), + # vertical_padding: 3, + # border_style: :grid, + # headers: ["BestellNr.", "Menge","Name", "Gebinde", "Einheit","Preis/Einheit"], + # align: {0 => :left} end private def order_articles - order.order_articles.ordered. - joins(:article). - order('articles.order_number').order('articles.name'). - preload(:article, :article_price) + order.order_articles.ordered + .joins(:article) + .order('articles.order_number').order('articles.name') + .preload(:article, :article_price) end def each_order_article - order_articles.find_each_with_order(batch_size: BATCH_SIZE) {|oa| yield oa } + order_articles.find_each_with_order(batch_size: BATCH_SIZE) { |oa| yield oa } end - end diff --git a/app/documents/order_matrix.rb b/app/documents/order_matrix.rb index a3217765..7269feaf 100644 --- a/app/documents/order_matrix.rb +++ b/app/documents/order_matrix.rb @@ -1,5 +1,4 @@ class OrderMatrix < OrderPdf - HEADER_ROTATE = -30 PLACEHOLDER_CHAR = 'X' @@ -9,7 +8,7 @@ class OrderMatrix < OrderPdf def title I18n.t('documents.order_matrix.title', :name => @order.name, - :date => @order.ends.strftime(I18n.t('date.formats.default'))) + :date => @order.ends.strftime(I18n.t('date.formats.default'))) end def body @@ -31,7 +30,7 @@ class OrderMatrix < OrderPdf order_articles_data.each { |row| row.delete_at 1 } unless @options[:show_supplier] - name = I18n.t('documents.order_matrix.heading', count: order_articles_data.size-1) + name = I18n.t('documents.order_matrix.heading', count: order_articles_data.size - 1) nice_table name, order_articles_data do |table| if @options[:show_supplier] table.column(0).width = bounds.width / 3 @@ -82,7 +81,7 @@ class OrderMatrix < OrderPdf rows << row end - table rows, header: true, cell_style: {overflow: :shrink_to_fit} do |table| + table rows, header: true, cell_style: { overflow: :shrink_to_fit } do |table| table.cells.padding = [0, 0, 2, 0] table.cells.borders = [:left] table.cells.border_width = 0.5 @@ -95,8 +94,8 @@ class OrderMatrix < OrderPdf table.column(1).align = :right table.column(1).padding = [0, 3, 2, 0] table.column(2..-1).align = :center - table.cells[0,0].borders = [] - table.cells[0,1].borders = [] + table.cells[0, 0].borders = [] + table.cells[0, 1].borders = [] table.column(0).overflow = :truncate table.column(0).width = col_width_0 @@ -104,7 +103,7 @@ class OrderMatrix < OrderPdf table.column(2..-1).width = col_width_2 (0..batch_size).step(5).each do |idx| - table.column(2+idx).border_width = 2 + table.column(2 + idx).border_width = 2 end table.row_colors = ['dddddd', 'ffffff'] @@ -113,5 +112,4 @@ class OrderMatrix < OrderPdf first_page = false end end - end diff --git a/app/helpers/admin/configs_helper.rb b/app/helpers/admin/configs_helper.rb index fcf60c29..0185a0df 100644 --- a/app/helpers/admin/configs_helper.rb +++ b/app/helpers/admin/configs_helper.rb @@ -11,13 +11,14 @@ module Admin::ConfigsHelper # @todo find way to pass current value to time_zone input without using default def config_input(form, key, options = {}, &block) return unless @cfg.allowed_key? key + options[:label] ||= config_input_label(form, key) options[:required] ||= false options[:input_html] ||= {} config_input_field_options form, key, options[:input_html] config_input_tooltip_options form, key, options[:input_html] if options[:as] == :boolean - options[:input_html][:checked] = 'checked' if v=options[:input_html].delete(:value) && v!='false' + options[:input_html][:checked] = 'checked' if v = options[:input_html].delete(:value) && v != 'false' options[:checked_value] = 'true' if options[:checked_value].nil? options[:unchecked_value] = 'false' if options[:unchecked_value].nil? elsif options[:collection] || options[:as] == :select @@ -47,13 +48,14 @@ module Admin::ConfigsHelper # @todo find out how to pass +checked_value+ and +unchecked_value+ to +input_field+ def config_input_field(form, key, options = {}) return unless @cfg.allowed_key? :key + options[:required] ||= false config_input_field_options form, key, options config_input_tooltip_options form, key, options if options[:as] == :boolean checked_value = options.delete(:checked_value) || 'true' unchecked_value = options.delete(:unchecked_value) || 'false' - options[:checked] = 'checked' if v=options.delete(:value) && v!='false' + options[:checked] = 'checked' if v = options.delete(:value) && v != 'false' # different key for hidden field so that allow clocking on label focuses the control form.hidden_field(key, id: "#{key}_", value: unchecked_value, as: :hidden) + form.check_box(key, options, checked_value, false) elsif options[:as] == :select_recurring @@ -73,13 +75,13 @@ module Admin::ConfigsHelper # @option options [String] :label Label to show def config_use_heading(form, key, options = {}) head = content_tag :label do - lbl = options[:label] || config_input_label(form, key) - field = config_input_field(form, key, as: :boolean, boolean_style: :inline, - data: {toggle: 'collapse', target: "##{key}-fields"}) - content_tag :h4 do - # put in span to keep space for tooltip at right - content_tag :span, (lbl + field).html_safe, config_input_tooltip_options(form, key, {}) - end + lbl = options[:label] || config_input_label(form, key) + field = config_input_field(form, key, as: :boolean, boolean_style: :inline, + data: { toggle: 'collapse', target: "##{key}-fields" }) + content_tag :h4 do + # put in span to keep space for tooltip at right + content_tag :span, (lbl + field).html_safe, config_input_tooltip_options(form, key, {}) + end end fields = content_tag(:fieldset, id: "#{key}-fields", class: "collapse#{' in' if @cfg[key]}") do yield @@ -99,12 +101,12 @@ module Admin::ConfigsHelper '(protected)' elsif value.is_a? Hash content_tag :ul do - value.map do |k,v| + value.map do |k, v| content_tag :li, content_tag(:tt, "#{k}: ") + show_config_value(k, v).to_s end.join.html_safe end elsif value.is_a? Enumerable - content_tag :ul, value.map {|v| content_tag :li, h(v)}.join.html_safe + content_tag :ul, value.map { |v| content_tag :li, h(v) }.join.html_safe elsif key =~ /url|website|www|homepage/ link_to(value, value.to_s).html_safe else @@ -115,7 +117,7 @@ module Admin::ConfigsHelper # @return [String] Tooltip element (span) # @param form [ActionView::Helpers::FormBuilder] Form object. # @param key [Symbol, String] Configuration key of a boolean (e.g. +use_messages+). - def config_tooltip(form, key, options={}, &block) + def config_tooltip(form, key, options = {}, &block) content_tag :span, config_input_tooltip_options(form, key, options), &block end @@ -139,7 +141,7 @@ module Admin::ConfigsHelper # set current value unless options.has_key?(:value) value = @cfg - cfg_path.each {|n| value = value[n] if value.respond_to? :[] } + cfg_path.each { |n| value = value[n] if value.respond_to? :[] } options[:value] = value end options diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index e6b08554..cbc99a5f 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 # # Methods added to this helper will be available to all templates in the application. module ApplicationHelper @@ -27,14 +26,14 @@ module ApplicationHelper # Splits an IBAN into groups of 4 digits displayed with margins in between def format_iban(iban) - iban.scan(/..?.?.?/).map{ |item| content_tag(:span, item, style: "margin-right: 0.5em;") }.join.html_safe + iban.scan(/..?.?.?/).map { |item| content_tag(:span, item, style: "margin-right: 0.5em;") }.join.html_safe end # Creates ajax-controlled-links for pagination def pagination_links_remote(collection, options = {}) per_page = options[:per_page] || @per_page params = options[:params] || {} - params = params.merge({:per_page => per_page}) + params = params.merge({ :per_page => per_page }) paginate collection, :params => params, :remote => true end @@ -45,7 +44,7 @@ module ApplicationHelper params = params || {} links = per_page_options.map do |per_page| - params.merge!({:per_page => per_page}) + params.merge!({ :per_page => per_page }) link_class = 'btn' link_class << ' disabled' if per_page == current link_to(per_page, params, :remote => true, class: link_class) @@ -58,33 +57,31 @@ module ApplicationHelper links.join.html_safe end end - end def sort_link_helper(text, key, options = {}) # Hmtl options remote = options[:remote].nil? ? true : options[:remote] class_name = case params[:sort] - when key then - 'sortup' - when key + '_reverse' then - 'sortdown' - else - nil + when key then + 'sortup' + when key + '_reverse' then + 'sortdown' + else + nil end html_options = { - :title => I18n.t('helpers.application.sort_by', text: text), - :remote => remote, - :class => class_name + :title => I18n.t('helpers.application.sort_by', text: text), + :remote => remote, + :class => class_name } - # Url options key += "_reverse" if params[:sort] == key per_page = options[:per_page] || @per_page url_options = params.merge(per_page: per_page, sort: key) - url_options.merge!({page: params[:page]}) if params[:page] - url_options.merge!({query: params[:query]}) if params[:query] + url_options.merge!({ page: params[:page] }) if params[:page] + url_options.merge!({ query: params[:query] }) if params[:query] link_to(text, url_for(url_options), html_options) end @@ -98,13 +95,13 @@ module ApplicationHelper # be overridden by the option 'desc'. # Other options are passed through to I18n. def heading_helper(model, attribute, options = {}) - i18nopts = {count: 2}.merge(options.select {|a| !['short', 'desc'].include?(a) }) + i18nopts = { count: 2 }.merge(options.select { |a| !['short', 'desc'].include?(a) }) s = model.human_attribute_name(attribute, i18nopts) if options[:short] desc = options[:desc] - desc ||= model.human_attribute_name("#{attribute}_desc".to_sym, options.merge({fallback: true, default: '', count: 2})) + desc ||= model.human_attribute_name("#{attribute}_desc".to_sym, options.merge({ fallback: true, default: '', count: 2 })) desc.blank? && desc = s - sshort = model.human_attribute_name("#{attribute}_short".to_sym, options.merge({fallback: true, default: '', count: 2})) + sshort = model.human_attribute_name("#{attribute}_short".to_sym, options.merge({ fallback: true, default: '', count: 2 })) s = raw "#{sshort}" unless sshort.blank? end s @@ -134,24 +131,24 @@ module ApplicationHelper end def tab_is_active?(tab) - tab[:active].detect {|c| controller.controller_path.match(c) } + tab[:active].detect { |c| controller.controller_path.match(c) } end - def icon(name, options={}) + def icon(name, options = {}) icons = { - :delete => { :file => 'b_drop.png', :alt => I18n.t('ui.delete')}, - :edit => { :file => 'b_edit.png', :alt => I18n.t('ui.edit')}, - :members => { :file => 'b_users.png', :alt => I18n.t('helpers.application.edit_user')} + :delete => { :file => 'b_drop.png', :alt => I18n.t('ui.delete') }, + :edit => { :file => 'b_edit.png', :alt => I18n.t('ui.edit') }, + :members => { :file => 'b_users.png', :alt => I18n.t('helpers.application.edit_user') } } options[:alt] ||= icons[name][:alt] options[:title] ||= icons[name][:title] - options.merge!({:size => '16x16',:border => "0"}) + options.merge!({ :size => '16x16', :border => "0" }) image_tag icons[name][:file], options end # Remote links with default 'loader'.gif during request - def remote_link_to(text, options={}) + def remote_link_to(text, options = {}) remote_options = { :before => "Element.show('loader')", :success => "Element.hide('loader')", @@ -160,20 +157,20 @@ module ApplicationHelper link_to(text, options[:url], remote_options.merge(options)) end - def format_roles(record, icon=false) + def format_roles(record, icon = false) roles = %w(suppliers article_meta orders pickups finance invoices admin) - roles.select! {|role| record.send "role_#{role}?"} - names = Hash[roles.map{|r| [r, I18n.t("helpers.application.role_#{r}")]}] + roles.select! { |role| record.send "role_#{role}?" } + names = Hash[roles.map { |r| [r, I18n.t("helpers.application.role_#{r}")] }] if icon - roles.map{|r| image_tag("role-#{r}.png", size: '22x22', border: 0, alt: names[r], title: names[r])}.join(' ').html_safe + roles.map { |r| image_tag("role-#{r}.png", size: '22x22', border: 0, alt: names[r], title: names[r]) }.join(' ').html_safe else - roles.map{|r| names[r]}.join(', ') + roles.map { |r| names[r] }.join(', ') end end def link_to_gmaps(address) link_to h(address), "http://maps.google.com/?q=#{h(address)}", :title => I18n.t('helpers.application.show_google_maps'), - :target => "_blank" + :target => "_blank" end # Returns flash messages html. @@ -200,12 +197,13 @@ module ApplicationHelper # http://railsapps.github.io/twitter-bootstrap-rails.html def base_errors resource return '' if resource.errors.empty? || resource.errors[:base].empty? + messages = resource.errors[:base].map { |msg| content_tag(:li, msg) }.join - render :partial => 'shared/base_errors', :locals => {:error_messages => messages} + render :partial => 'shared/base_errors', :locals => { :error_messages => messages } end # show a user, depending on settings - def show_user(user=@current_user, options = {}) + def show_user(user = @current_user, options = {}) if user.nil? "?" elsif FoodsoftConfig[:use_nick] @@ -223,13 +221,14 @@ module ApplicationHelper end # render user presentation linking to default action (plugins can override this) - def show_user_link(user=@current_user) + def show_user_link(user = @current_user) show_user user end # allow truncate to add title when tooltip option is given - def truncate(text, options={}, &block) + def truncate(text, options = {}, &block) return text if !text || text.length <= (options[:length] || 30) + text_truncated = super(text, options, &block) if options[:tooltip] content_tag :span, text_truncated, title: text @@ -240,29 +239,28 @@ module ApplicationHelper # Expand variables in text # @see Foodsoft::ExpansionVariables#expand - def expand(text, options={}) + def expand(text, options = {}) Foodsoft::ExpansionVariables.expand(text, options) end # @param dismiss [String, Symbol] Bootstrap dismiss value (modal, alert) # @return [String] HTML for close button dismissing def close_button(dismiss) - content_tag :button, type: 'button', class: 'close', data: {dismiss: dismiss} do + content_tag :button, type: 'button', class: 'close', data: { dismiss: dismiss } do I18n.t('ui.marks.close').html_safe end end # @return [String] path to foodcoop CSS style (with MD5 parameter for caching) - def foodcoop_css_path(options={}) - super(options.merge({md5: Digest::MD5.hexdigest(FoodsoftConfig[:custom_css].to_s)})) + def foodcoop_css_path(options = {}) + super(options.merge({ md5: Digest::MD5.hexdigest(FoodsoftConfig[:custom_css].to_s) })) end # @return [String] stylesheet tag for foodcoop CSS style (+custom_css+ foodcoop config) # @see #foodcoop_css_path - def foodcoop_css_tag(options={}) + def foodcoop_css_tag(options = {}) unless FoodsoftConfig[:custom_css].blank? stylesheet_link_tag foodcoop_css_path, media: 'all' end end - end diff --git a/app/helpers/articles_helper.rb b/app/helpers/articles_helper.rb index 4f679af8..add1c6ba 100644 --- a/app/helpers/articles_helper.rb +++ b/app/helpers/articles_helper.rb @@ -1,8 +1,8 @@ module ArticlesHelper - # useful for highlighting attributes, when synchronizing articles def highlight_new(unequal_attributes, attribute) return unless unequal_attributes + unequal_attributes.has_key?(attribute) ? "background-color: yellow" : "" end diff --git a/app/helpers/deliveries_helper.rb b/app/helpers/deliveries_helper.rb index f8a4c370..a97a7df7 100644 --- a/app/helpers/deliveries_helper.rb +++ b/app/helpers/deliveries_helper.rb @@ -1,33 +1,32 @@ module DeliveriesHelper - def link_to_invoice(delivery) if delivery.invoice link_to number_to_currency(delivery.invoice.amount), [:finance, delivery.invoice], - title: I18n.t('helpers.deliveries.show_invoice') + title: I18n.t('helpers.deliveries.show_invoice') else link_to I18n.t('helpers.deliveries.new_invoice'), new_finance_invoice_path(supplier_id: delivery.supplier.id, delivery_id: delivery.id), - class: 'btn btn-mini' + class: 'btn btn-mini' end end - + def articles_for_select2(articles, except = [], &block) articles = articles.reorder('articles.name ASC') - articles = articles.reject {|a| not except.index(a.id).nil? } if except - block_given? or block = Proc.new {|a| "#{a.name} (#{number_to_currency a.price}/#{a.unit})" } + articles = articles.reject { |a| not except.index(a.id).nil? } if except + block_given? or block = Proc.new { |a| "#{a.name} (#{number_to_currency a.price}/#{a.unit})" } articles.map do |a| - {:id => a.id, :text => block.call(a)} - end.unshift({:id => '', :text => ''}) + { :id => a.id, :text => block.call(a) } + end.unshift({ :id => '', :text => '' }) end - + def articles_for_table(articles) articles.undeleted.reorder('articles.name ASC') end - + def stock_change_remove_link(stock_change_form) return link_to t('deliveries.stock_change_fields.remove_article'), "#", :class => 'remove_new_stock_change btn btn-small' if stock_change_form.object.new_record? + output = stock_change_form.hidden_field :_destroy output += link_to t('deliveries.stock_change_fields.remove_article'), "#", :class => 'destroy_stock_change btn btn-small' return output.html_safe end - end diff --git a/app/helpers/finance/balancing_helper.rb b/app/helpers/finance/balancing_helper.rb index e81a9f98..bc528f04 100644 --- a/app/helpers/finance/balancing_helper.rb +++ b/app/helpers/finance/balancing_helper.rb @@ -2,12 +2,12 @@ module Finance::BalancingHelper def balancing_view_partial view = params[:view] || 'edit_results' case view - when 'edit_results' then - 'edit_results_by_articles' - when 'groups_overview' then - 'shared/articles_by/groups' - when 'articles_overview' then - 'shared/articles_by/articles' + when 'edit_results' then + 'edit_results_by_articles' + when 'groups_overview' then + 'shared/articles_by/groups' + when 'articles_overview' then + 'shared/articles_by/articles' end end end diff --git a/app/helpers/finance/invoices_helper.rb b/app/helpers/finance/invoices_helper.rb index 4ed13bd4..ef01a275 100644 --- a/app/helpers/finance/invoices_helper.rb +++ b/app/helpers/finance/invoices_helper.rb @@ -2,6 +2,7 @@ module Finance::InvoicesHelper def format_delivery_item delivery format_date(delivery.date) end + def format_order_item order "#{format_date(order.ends)} (#{number_to_currency(order.sum)})" end diff --git a/app/helpers/group_order_articles_helper.rb b/app/helpers/group_order_articles_helper.rb index cbed7f89..ff003731 100644 --- a/app/helpers/group_order_articles_helper.rb +++ b/app/helpers/group_order_articles_helper.rb @@ -1,15 +1,13 @@ module GroupOrderArticlesHelper - # return an edit field for a GroupOrderArticle result def group_order_article_edit_result(goa) result = number_with_precision goa.result, strip_insignificant_zeros: true unless goa.group_order.order.finished? && current_user.role_finance? result else - simple_form_for goa, remote: true, html: {'data-submit-onchange' => 'changed', class: 'delta-input'} do |f| - f.input_field :result, as: :delta, class: 'input-nano', data: {min: 0}, id: "r_#{goa.id}", value: result + simple_form_for goa, remote: true, html: { 'data-submit-onchange' => 'changed', class: 'delta-input' } do |f| + f.input_field :result, as: :delta, class: 'input-nano', data: { min: 0 }, id: "r_#{goa.id}", value: result end end end - end diff --git a/app/helpers/group_orders_helper.rb b/app/helpers/group_orders_helper.rb index 37e13d53..c5e27c66 100644 --- a/app/helpers/group_orders_helper.rb +++ b/app/helpers/group_orders_helper.rb @@ -12,12 +12,12 @@ module GroupOrdersHelper def link_to_ordering(order, options = {}, &block) group_order = order.group_order(current_user.ordergroup) path = if options[:show] && group_order - group_order_path(group_order) - elsif group_order - edit_group_order_path(group_order, :order_id => order.id) - else - new_group_order_path(:order_id => order.id) - end + group_order_path(group_order) + elsif group_order + edit_group_order_path(group_order, :order_id => order.id) + else + new_group_order_path(:order_id => order.id) + end options.delete(:show) name = block_given? ? capture(&block) : order.name path ? link_to(name, path, options) : name @@ -36,18 +36,18 @@ module GroupOrdersHelper def get_order_results(order_article, group_order_id) goa = order_article.group_order_articles.detect { |goa| goa.group_order_id == group_order_id } quantity, tolerance, result, sub_total = if goa.present? - [goa.quantity, goa.tolerance, goa.result, goa.total_price(order_article)] - else - [0, 0, 0, 0] - end + [goa.quantity, goa.tolerance, goa.result, goa.total_price(order_article)] + else + [0, 0, 0, 0] + end - {group_order_article: goa, quantity: quantity, tolerance: tolerance, result: result, sub_total: sub_total} + { group_order_article: goa, quantity: quantity, tolerance: tolerance, result: result, sub_total: sub_total } end def get_missing_units_css_class(quantity_missing) - if ( quantity_missing == 1 ) + if (quantity_missing == 1) return 'missing-few'; - elsif ( quantity_missing == 0 ) + elsif (quantity_missing == 0) return '' else return 'missing-many' diff --git a/app/helpers/order_articles_helper.rb b/app/helpers/order_articles_helper.rb index c2dc232f..b4290e84 100644 --- a/app/helpers/order_articles_helper.rb +++ b/app/helpers/order_articles_helper.rb @@ -1,8 +1,6 @@ module OrderArticlesHelper - def article_label_with_unit(article) pkg_info = pkg_helper(article, plain: true) "#{article.name} (#{[article.unit, pkg_info].reject(&:blank?).join(' ')})" end - end diff --git a/app/helpers/orders_helper.rb b/app/helpers/orders_helper.rb index 1a99ba54..ff238730 100644 --- a/app/helpers/orders_helper.rb +++ b/app/helpers/orders_helper.rb @@ -1,8 +1,6 @@ -# encoding: utf-8 module OrdersHelper - - def update_articles_link(order, text, view, options={}) - options = {remote: true, id: "view_#{view}_btn", class: ''}.merge(options) + def update_articles_link(order, text, view, options = {}) + options = { remote: true, id: "view_#{view}_btn", class: '' }.merge(options) options[:class] += ' active' if view.to_s == @view.to_s link_to text, order_path(order, view: view), options end @@ -13,20 +11,20 @@ module OrdersHelper # @param options [Hash] Options passed to +link_to+ # @return [String] Link to order document # @see OrdersController#show - def order_pdf(order, document, text, options={}) + def order_pdf(order, document, text, options = {}) options = options.merge(title: I18n.t('helpers.orders.order_pdf')) link_to text, order_path(order, document: document, format: :pdf), options end def options_for_suppliers_to_select options = [[I18n.t('helpers.orders.option_choose')]] - options += Supplier.map {|s| [ s.name, url_for(action: "new", supplier_id: s.id)] } + options += Supplier.map { |s| [s.name, url_for(action: "new", supplier_id: s.id)] } options += [[I18n.t('helpers.orders.option_stock'), url_for(action: 'new', supplier_id: nil)]] options_for_select(options) end # "1×2 ordered, 2×2 billed, 2×2 received" - def units_history_line(order_article, options={}) + def units_history_line(order_article, options = {}) if order_article.order.open? nil else @@ -49,8 +47,9 @@ module OrdersHelper # @option options [String] :soft_uq +true+ to hide unit quantity specifier on small screens. # Sensible in tables with multiple columns. # @return [String] Text showing unit and unit quantity when applicable. - def pkg_helper(article, options={}) + def pkg_helper(article, options = {}) return '' if !article || article.unit_quantity == 1 + uq_text = "× #{article.unit_quantity}" uq_text = content_tag(:span, uq_text, class: 'hidden-phone') if options[:soft_uq] if options[:plain] @@ -61,11 +60,12 @@ module OrdersHelper pkg_helper_icon(uq_text, tag: :span) end end + # @param c [Symbol, String] Tag to use # @option options [String] :class CSS class(es) (in addition to +package+) # @return [String] Icon used for displaying the unit quantity - def pkg_helper_icon(c=nil, options={}) - options = {tag: 'i', class: ''}.merge(options) + def pkg_helper_icon(c = nil, options = {}) + options = { tag: 'i', class: '' }.merge(options) if c.nil? c = " ".html_safe options[:class] += " icon-only" @@ -73,8 +73,9 @@ module OrdersHelper content_tag(options[:tag], c, class: "package #{options[:class]}").html_safe end - def article_price_change_hint(order_article, gross=false) + def article_price_change_hint(order_article, gross = false) return nil if order_article.article.price == order_article.price.price + title = "#{t('helpers.orders.old_price')}: #{number_to_currency order_article.article.price}" title += " / #{number_to_currency order_article.article.gross_price}" if gross content_tag(:i, nil, class: 'icon-asterisk', title: j(title)).html_safe @@ -83,14 +84,14 @@ module OrdersHelper def receive_input_field(form) order_article = form.object units_expected = (order_article.units_billed || order_article.units_to_order) * - 1.0 * order_article.article.unit_quantity / order_article.article_price.unit_quantity + 1.0 * order_article.article.unit_quantity / order_article.article_price.unit_quantity input_classes = 'input input-nano units_received' input_classes += ' package' unless order_article.article_price.unit_quantity == 1 input_html = form.text_field :units_received, class: input_classes, - data: {'units-expected' => units_expected}, - disabled: order_article.result_manually_changed?, - autocomplete: 'off' + data: { 'units-expected' => units_expected }, + disabled: order_article.result_manually_changed?, + autocomplete: 'off' if order_article.result_manually_changed? input_html = content_tag(:span, class: 'input-prepend intable', title: t('orders.edit_amount.field_locked_title', default: '')) { @@ -111,7 +112,7 @@ module OrdersHelper if group_orders.count == 0 return txt else - desc = group_orders.includes(:ordergroup).map {|g| g.ordergroup_name}.join(', ') + desc = group_orders.includes(:ordergroup).map { |g| g.ordergroup_name }.join(', ') content_tag(:abbr, txt, title: desc).html_safe end end @@ -147,7 +148,7 @@ module OrdersHelper # @param order [Order] # @option options [String] :class Classes added to the button's class attribute. # @return [String] Order receive button. - def receive_button(order, options={}) + def receive_button(order, options = {}) if order.stockit? content_tag :div, t('orders.index.action_receive'), class: "btn disabled #{options[:class]}" else diff --git a/app/helpers/path_helper.rb b/app/helpers/path_helper.rb index 7d72ed85..4fee35fb 100644 --- a/app/helpers/path_helper.rb +++ b/app/helpers/path_helper.rb @@ -1,5 +1,4 @@ module PathHelper - def finance_group_transactions_path(ordergroup) if ordergroup finance_ordergroup_transactions_path(ordergroup) @@ -7,5 +6,4 @@ module PathHelper finance_foodcoop_financial_transactions_path end end - end diff --git a/app/helpers/shared_helper.rb b/app/helpers/shared_helper.rb index befd61c4..1da24748 100644 --- a/app/helpers/shared_helper.rb +++ b/app/helpers/shared_helper.rb @@ -1,13 +1,11 @@ module SharedHelper - # provide input_html for password autocompletion def autocomplete_flag_to_password_html(password_autocomplete) case password_autocomplete - when true then {autocomplete: 'on'} - when false then {autocomplete: 'off'} - when 'store-only' then {autocomplete: 'off', data: {store: 'on'}} - else {} + when true then { autocomplete: 'on' } + when false then { autocomplete: 'off' } + when 'store-only' then { autocomplete: 'off', data: { store: 'on' } } + else {} end end - end diff --git a/app/helpers/stockit_helper.rb b/app/helpers/stockit_helper.rb index f6d36896..a08e8335 100644 --- a/app/helpers/stockit_helper.rb +++ b/app/helpers/stockit_helper.rb @@ -18,9 +18,7 @@ module StockitHelper def stock_article_price_hint(stock_article) t('simple_form.hints.stock_article.edit_stock_article.price', :stock_article_copy_link => link_to(t('stockit.form.copy_stock_article'), - stock_article_copy_path(stock_article), - :remote => true - ) - ) + stock_article_copy_path(stock_article), + :remote => true)) end end diff --git a/app/helpers/suppliers_helper.rb b/app/helpers/suppliers_helper.rb index ffd54216..507d2035 100644 --- a/app/helpers/suppliers_helper.rb +++ b/app/helpers/suppliers_helper.rb @@ -1,5 +1,4 @@ module SuppliersHelper - def associated_supplier_names(shared_supplier) "(#{shared_supplier.suppliers.map(&:name).join(', ')})" end diff --git a/app/helpers/tasks_helper.rb b/app/helpers/tasks_helper.rb index e9db9e22..f6f1fa14 100644 --- a/app/helpers/tasks_helper.rb +++ b/app/helpers/tasks_helper.rb @@ -1,5 +1,4 @@ module TasksHelper - def task_assignments(task) task.assignments.map do |ass| content_tag :span, show_user(ass.user), :class => (ass.accepted? ? 'accepted' : 'unaccepted') @@ -10,7 +9,7 @@ module TasksHelper def highlighted_required_users(task) unless task.enough_users_assigned? content_tag :span, task.still_required_users, class: 'badge badge-important', - title: I18n.t('helpers.tasks.required_users', :count => task.still_required_users) + title: I18n.t('helpers.tasks.required_users', :count => task.still_required_users) end end diff --git a/app/inputs/date_picker_time_input.rb b/app/inputs/date_picker_time_input.rb index f5548d23..2819413d 100644 --- a/app/inputs/date_picker_time_input.rb +++ b/app/inputs/date_picker_time_input.rb @@ -12,12 +12,12 @@ class DatePickerTimeInput < SimpleForm::Inputs::StringInput # In the future, use html5 date&time inputs. This needs modernizr or equiv. to avoid # double widgets, and perhaps conditional css to adjust input width (chrome). value = @builder.object.send attribute_name - date_options = {as: :string, class: 'input-small datepicker'} - time_options = {as: :string, class: 'input-mini'} + date_options = { as: :string, class: 'input-small datepicker' } + time_options = { as: :string, class: 'input-mini' } @builder.input_field("#{attribute_name}_date_value", options.merge(date_options)) + ' ' + - @builder.input_field("#{attribute_name}_time_value", options.merge(time_options)) + @builder.input_field("#{attribute_name}_time_value", options.merge(time_options)) # time_select requires a date_select - #@builder.time_select("#{attribute_name}_time", {ignore_date: true}, input_html_options.merge(time_options)) + # @builder.time_select("#{attribute_name}_time", {ignore_date: true}, input_html_options.merge(time_options)) end def label_target diff --git a/app/inputs/delta_input.rb b/app/inputs/delta_input.rb index c14fdcff..adc08960 100644 --- a/app/inputs/delta_input.rb +++ b/app/inputs/delta_input.rb @@ -1,5 +1,3 @@ -# encoding: utf-8 - class DeltaInput < SimpleForm::Inputs::StringInput # for now, need to pass id or it won't work def input(wrapper_options) @@ -16,12 +14,12 @@ class DeltaInput < SimpleForm::Inputs::StringInput delta_button(content_tag(:i, nil, class: 'icon icon-plus'), 1, options) end end - #template.button_tag('−', type: :submit, data: {decrement: options[:id]}, tabindex: -1, class: 'btn') + + # template.button_tag('−', type: :submit, data: {decrement: options[:id]}, tabindex: -1, class: 'btn') + private def delta_button(title, direction, options) - data = { (direction>0 ? 'increment' : 'decrement') => options[:id] } + data = { (direction > 0 ? 'increment' : 'decrement') => options[:id] } delta = direction * options[:data][:delta] template.button_tag(title, type: :button, name: 'delta', value: delta, data: data, tabindex: -1, class: 'btn') end diff --git a/app/mail_receivers/bounce_mail_receiver.rb b/app/mail_receivers/bounce_mail_receiver.rb index 89cbced9..d647f6d5 100644 --- a/app/mail_receivers/bounce_mail_receiver.rb +++ b/app/mail_receivers/bounce_mail_receiver.rb @@ -1,5 +1,4 @@ class BounceMailReceiver - def self.regexp /bounce\+(?.*)=(?[^=]+)/ end @@ -16,5 +15,4 @@ class BounceMailReceiver attachment_mime: 'message/rfc822', attachment_data: data end - end diff --git a/app/mailers/mailer.rb b/app/mailers/mailer.rb index cc0c69b6..40a8d1de 100644 --- a/app/mailers/mailer.rb +++ b/app/mailers/mailer.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 # ActionMailer class that handles all emails for Foodsoft. class Mailer < ActionMailer::Base # XXX Quick fix to allow the use of show_user. Proper take would be one of @@ -7,7 +6,7 @@ class Mailer < ActionMailer::Base helper :application include ApplicationHelper - layout 'email' # Use views/layouts/email.txt.erb + layout 'email' # Use views/layouts/email.txt.erb default from: "#{I18n.t('layouts.foodsoft')} <#{FoodsoftConfig[:email_sender]}>", 'X-Auto-Response-Suppress' => 'All' @@ -71,7 +70,7 @@ class Mailer < ActionMailer::Base @scarce_articles = order_articles.select { |oa| oa.difference_received_ordered.negative? } mail to: user, - subject: I18n.t('mailer.order_received.subject', name: group_order.order.name) + subject: I18n.t('mailer.order_received.subject', name: group_order.order.name) end # Sends order result to the supplier @@ -92,7 +91,7 @@ class Mailer < ActionMailer::Base end # Notify user if account balance is less than zero - def negative_balance(user,transaction) + def negative_balance(user, transaction) @group = user.ordergroup @transaction = transaction @@ -180,5 +179,4 @@ class Mailer < ActionMailer::Base address.display_name = name address.format end - end diff --git a/app/models/article.rb b/app/models/article.rb index 64c0dd34..8e441c36 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 class Article < ApplicationRecord include PriceCalculation @@ -66,8 +65,8 @@ class Article < ApplicationRecord validates_numericality_of :price, :greater_than_or_equal_to => 0 validates_numericality_of :unit_quantity, :greater_than => 0 validates_numericality_of :deposit, :tax - #validates_uniqueness_of :name, :scope => [:supplier_id, :deleted_at, :type], if: Proc.new {|a| a.supplier.shared_sync_method.blank? or a.supplier.shared_sync_method == 'import' } - #validates_uniqueness_of :name, :scope => [:supplier_id, :deleted_at, :type, :unit, :unit_quantity] + # validates_uniqueness_of :name, :scope => [:supplier_id, :deleted_at, :type], if: Proc.new {|a| a.supplier.shared_sync_method.blank? or a.supplier.shared_sync_method == 'import' } + # validates_uniqueness_of :name, :scope => [:supplier_id, :deleted_at, :type, :unit, :unit_quantity] validate :uniqueness_of_name # Callbacks @@ -91,7 +90,7 @@ class Article < ApplicationRecord def in_open_order @in_open_order ||= begin order_articles = OrderArticle.where(order_id: Order.open.collect(&:id)) - order_article = order_articles.detect {|oa| oa.article_id == id } + order_article = order_articles.detect { |oa| oa.article_id == id } order_article ? order_article.order : nil end end @@ -124,7 +123,7 @@ class Article < ApplicationRecord # @param new_article [Article] New article to update self # @option options [Boolean] :convert_units Omit or set to +true+ to keep current unit and recompute unit quantity and price. # @return [Hash] Attributes with new values - def unequal_attributes(new_article, options={}) + def unequal_attributes(new_article, options = {}) # try to convert different units when desired if options[:convert_units] == false new_price, new_unit_quantity = nil, nil @@ -162,7 +161,7 @@ class Article < ApplicationRecord # @return [Hash] Changed attributes with new values def self.compare_attributes(attributes) unequal_attributes = attributes.select { |name, values| values[0] != values[1] && !(values[0].blank? && values[1].blank?) } - Hash[unequal_attributes.to_a.map {|a| [a[0], a[1].last]}] + Hash[unequal_attributes.to_a.map { |a| [a[0], a[1].last] }] end # to get the correspondent shared article @@ -183,7 +182,7 @@ class Article < ApplicationRecord # try to match the size out of its name, e.g. "banana 10-12 St" => 10 new_unit_quantity = /[0-9\-\s]+(St)/.match(new_article.name).to_s.to_i if new_unit_quantity && new_unit_quantity > 0 - new_price = (new_article.price/new_unit_quantity.to_f).round(2) + new_price = (new_article.price / new_unit_quantity.to_f).round(2) [new_price, new_unit_quantity] else false @@ -250,5 +249,4 @@ class Article < ApplicationRecord errors.add :name, :taken_with_unit if matches.where(unit: unit, unit_quantity: unit_quantity).any? end end - end diff --git a/app/models/article_category.rb b/app/models/article_category.rb index 7e4ecd11..28597a59 100644 --- a/app/models/article_category.rb +++ b/app/models/article_category.rb @@ -1,6 +1,5 @@ # Article category class ArticleCategory < ApplicationRecord - # @!attribute name # @return [String] Title of the category. # @!attrubute description @@ -34,15 +33,16 @@ class ArticleCategory < ApplicationRecord # TODO more intelligence like remembering earlier associations (global and/or per-supplier) def self.find_match(category) return if category.blank? || category.length < 3 + c = nil ## exact match - not needed, will be returned by next query as well - #c ||= ArticleCategory.where(name: category).first + # c ||= ArticleCategory.where(name: category).first # case-insensitive substring match (take the closest match = shortest) c = ArticleCategory.where('name LIKE ?', "%#{category}%") unless c && c.any? # case-insensitive phrase present in category description - c = ArticleCategory.where('description LIKE ?', "%#{category}%").select {|s| s.description.match /(^|,)\s*#{category}\s*(,|$)/i} unless c && c.any? + c = ArticleCategory.where('description LIKE ?', "%#{category}%").select { |s| s.description.match /(^|,)\s*#{category}\s*(,|$)/i } unless c && c.any? # return closest match if there are multiple - c = c.sort_by {|s| s.name.length}.first if c.respond_to? :sort_by + c = c.sort_by { |s| s.name.length }.first if c.respond_to? :sort_by c end @@ -52,5 +52,4 @@ class ArticleCategory < ApplicationRecord def check_for_associated_articles raise I18n.t('activerecord.errors.has_many_left', collection: Article.model_name.human) if articles.undeleted.exists? end - end diff --git a/app/models/article_price.rb b/app/models/article_price.rb index 30f1a6df..cca4c200 100644 --- a/app/models/article_price.rb +++ b/app/models/article_price.rb @@ -27,5 +27,4 @@ class ArticlePrice < ApplicationRecord validates_numericality_of :price, :greater_than_or_equal_to => 0 validates_numericality_of :unit_quantity, :greater_than => 0 validates_numericality_of :deposit, :tax - end diff --git a/app/models/assignment.rb b/app/models/assignment.rb index 8a0fa9d0..538fafc4 100644 --- a/app/models/assignment.rb +++ b/app/models/assignment.rb @@ -1,5 +1,4 @@ class Assignment < ApplicationRecord - belongs_to :user belongs_to :task end diff --git a/app/models/bank_account.rb b/app/models/bank_account.rb index 04242162..bb77b587 100644 --- a/app/models/bank_account.rb +++ b/app/models/bank_account.rb @@ -1,5 +1,4 @@ class BankAccount < ApplicationRecord - has_many :bank_transactions, dependent: :destroy normalize_attributes :name, :iban, :description diff --git a/app/models/bank_transaction.rb b/app/models/bank_transaction.rb index 877060b8..7d3db208 100644 --- a/app/models/bank_transaction.rb +++ b/app/models/bank_transaction.rb @@ -1,5 +1,4 @@ class BankTransaction < ApplicationRecord - # @!attribute external_id # @return [String] Unique Identifier of the transaction within the bank account. # @!attribute date @@ -39,13 +38,13 @@ class BankTransaction < ApplicationRecord content = text content += "\n" + reference if reference.present? - invoices = supplier.invoices.unpaid.select {|i| content.include? i.number} + invoices = supplier.invoices.unpaid.select { |i| content.include? i.number } invoices_sum = invoices.map(&:amount).sum return false if amount != -invoices_sum transaction do link = FinancialLink.new - invoices.each {|i| i.update_attributes! financial_link: link, paid_on: date } + invoices.each { |i| i.update_attributes! financial_link: link, paid_on: date } update_attribute :financial_link, link end @@ -57,8 +56,10 @@ class BankTransaction < ApplicationRecord return unless m return false if m[:parts].values.sum != amount + group = Ordergroup.find_by_id(m[:group]) return false unless group + usr = m[:user] ? User.find_by_id(m[:user]) : group.users.first return false unless usr @@ -69,6 +70,7 @@ class BankTransaction < ApplicationRecord m[:parts].each do |short, value| ftt = FinancialTransactionType.find_by_name_short(short) return false unless ftt + group.add_financial_transaction! value, note, usr, ftt, link if value > 0 end diff --git a/app/models/concerns/custom_fields.rb b/app/models/concerns/custom_fields.rb index 04373d60..d54cebe5 100644 --- a/app/models/concerns/custom_fields.rb +++ b/app/models/concerns/custom_fields.rb @@ -6,7 +6,7 @@ module CustomFields included do after_initialize do - settings.defaults['custom_fields'] = { } unless settings.custom_fields + settings.defaults['custom_fields'] = {} unless settings.custom_fields end after_save do diff --git a/app/models/concerns/find_each_with_order.rb b/app/models/concerns/find_each_with_order.rb index bbd21e96..0e7cd5cd 100644 --- a/app/models/concerns/find_each_with_order.rb +++ b/app/models/concerns/find_each_with_order.rb @@ -3,7 +3,6 @@ module FindEachWithOrder extend ActiveSupport::Concern class_methods do - def find_each_with_order(options = {}) find_in_batches_with_order(options) do |records| records.each { |record| yield record } @@ -34,6 +33,5 @@ module FindEachWithOrder records = relation.offset(start).to_a end end - end end diff --git a/app/models/concerns/mark_as_deleted_with_name.rb b/app/models/concerns/mark_as_deleted_with_name.rb index cd9292e9..4b888438 100644 --- a/app/models/concerns/mark_as_deleted_with_name.rb +++ b/app/models/concerns/mark_as_deleted_with_name.rb @@ -12,7 +12,7 @@ module MarkAsDeletedWithName n = '' begin append = " \u2020" + n - deleted_name = name.truncate(max_length-append.length, omission: '') + append + deleted_name = name.truncate(max_length - append.length, omission: '') + append if n.blank? n = 'A' else diff --git a/app/models/delivery.rb b/app/models/delivery.rb index c5bf7958..ab5ca5ec 100644 --- a/app/models/delivery.rb +++ b/app/models/delivery.rb @@ -1,5 +1,4 @@ class Delivery < StockEvent - belongs_to :supplier belongs_to :invoice, optional: true @@ -17,7 +16,7 @@ class Delivery < StockEvent end def includes_article?(article) - self.stock_changes.map{|stock_change| stock_change.stock_article.id}.include? article.id + self.stock_changes.map { |stock_change| stock_change.stock_article.id }.include? article.id end def sum(type = :gross) @@ -26,12 +25,12 @@ class Delivery < StockEvent article = sc.stock_article quantity = sc.quantity case type - when :net - total += quantity * article.price - when :gross - total += quantity * article.gross_price - when :fc - total += quantity * article.fc_price + when :net + total += quantity * article.price + when :gross + total += quantity * article.gross_price + when :fc + total += quantity * article.fc_price end end total @@ -40,9 +39,8 @@ class Delivery < StockEvent protected def stock_articles_must_be_unique - unless stock_changes.reject{|sc| sc.marked_for_destruction?}.map {|sc| sc.stock_article.id}.uniq!.nil? + unless stock_changes.reject { |sc| sc.marked_for_destruction? }.map { |sc| sc.stock_article.id }.uniq!.nil? errors.add(:base, I18n.t('model.delivery.each_stock_article_must_be_unique')) end end - end diff --git a/app/models/financial_link.rb b/app/models/financial_link.rb index 1ad5214e..30a1955c 100644 --- a/app/models/financial_link.rb +++ b/app/models/financial_link.rb @@ -8,7 +8,7 @@ class FinancialLink < ApplicationRecord includes(:bank_transactions, :financial_transactions, :invoices) .where(bank_transactions: { financial_link_id: nil }) .where(financial_transactions: { financial_link_id: nil }) - .where(invoices: { financial_link_id: nil}) + .where(invoices: { financial_link_id: nil }) } scope :with_full_sum, -> { select(:id, :note, :full_sum).joins(<<-SQL) diff --git a/app/models/financial_transaction.rb b/app/models/financial_transaction.rb index 4979a415..5c26058b 100644 --- a/app/models/financial_transaction.rb +++ b/app/models/financial_transaction.rb @@ -11,7 +11,7 @@ class FinancialTransaction < ApplicationRecord validates_presence_of :amount, :note, :user_id validates_numericality_of :amount, greater_then: -100_000, - less_than: 100_000 + less_than: 100_000 scope :visible, -> { joins('LEFT JOIN financial_transactions r ON financial_transactions.id = r.reverts_id').where('r.id IS NULL').where(reverts: nil) } scope :without_financial_link, -> { where(financial_link: nil) } diff --git a/app/models/group.rb b/app/models/group.rb index 4034fe68..a667ea5a 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 # Groups organize the User. # A Member gets the roles from the Group class Group < ApplicationRecord @@ -8,7 +7,7 @@ class Group < ApplicationRecord has_many :memberships, dependent: :destroy has_many :users, -> { where(deleted_at: nil) }, through: :memberships - validates :name, :presence => true, :length => {:in => 1..25} + validates :name, :presence => true, :length => { :in => 1..25 } validates_uniqueness_of :name attr_reader :user_tokens diff --git a/app/models/group_order.rb b/app/models/group_order.rb index d4cc7477..c789ef4e 100644 --- a/app/models/group_order.rb +++ b/app/models/group_order.rb @@ -13,7 +13,7 @@ class GroupOrder < ApplicationRecord validates_presence_of :order_id validates_numericality_of :price - validates_uniqueness_of :ordergroup_id, :scope => :order_id # order groups can only order once per order + validates_uniqueness_of :ordergroup_id, :scope => :order_id # order groups can only order once per order scope :in_open_orders, -> { joins(:order).merge(Order.open) } scope :in_finished_orders, -> { joins(:order).merge(Order.finished_not_closed) } @@ -39,23 +39,22 @@ class GroupOrder < ApplicationRecord data[:order_articles] = {} order.articles_grouped_by_category.each do |article_category, order_articles| order_articles.each do |order_article| - # Get the result of last time ordering, if possible goa = group_order_articles.detect { |goa| goa.order_article_id == order_article.id } # Build hash with relevant data data[:order_articles][order_article.id] = { - :price => order_article.article.fc_price, - :unit => order_article.article.unit_quantity, - :quantity => (goa ? goa.quantity : 0), - :others_quantity => order_article.quantity - (goa ? goa.quantity : 0), - :used_quantity => (goa ? goa.result(:quantity) : 0), - :tolerance => (goa ? goa.tolerance : 0), - :others_tolerance => order_article.tolerance - (goa ? goa.tolerance : 0), - :used_tolerance => (goa ? goa.result(:tolerance) : 0), - :total_price => (goa ? goa.total_price : 0), - :missing_units => order_article.missing_units, - :quantity_available => (order.stockit? ? order_article.article.quantity_available : 0) + :price => order_article.article.fc_price, + :unit => order_article.article.unit_quantity, + :quantity => (goa ? goa.quantity : 0), + :others_quantity => order_article.quantity - (goa ? goa.quantity : 0), + :used_quantity => (goa ? goa.result(:quantity) : 0), + :tolerance => (goa ? goa.tolerance : 0), + :others_tolerance => order_article.tolerance - (goa ? goa.tolerance : 0), + :used_tolerance => (goa ? goa.result(:tolerance) : 0), + :total_price => (goa ? goa.total_price : 0), + :missing_units => order_article.missing_units, + :quantity_available => (order.stockit? ? order_article.article.quantity_available : 0) } end end @@ -70,7 +69,7 @@ class GroupOrder < ApplicationRecord # Get ordered quantities and update group_order_articles/_quantities... if group_order_articles_attributes - quantities = group_order_articles_attributes.fetch(order_article.id.to_s, {:quantity => 0, :tolerance => 0}) + quantities = group_order_articles_attributes.fetch(order_article.id.to_s, { :quantity => 0, :tolerance => 0 }) group_order_article.update_quantities(quantities[:quantity].to_i, quantities[:tolerance].to_i) end @@ -88,7 +87,6 @@ class GroupOrder < ApplicationRecord update_attribute(:price, total) end - # Save GroupOrder and updates group_order_articles/quantities accordingly def save_ordering! transaction do @@ -104,7 +102,7 @@ class GroupOrder < ApplicationRecord def total return price + transport if transport + price end - end diff --git a/app/models/group_order_article.rb b/app/models/group_order_article.rb index 538a16ce..8df4fa59 100644 --- a/app/models/group_order_article.rb +++ b/app/models/group_order_article.rb @@ -2,13 +2,12 @@ # The chronologically order of the Ordergroup - activity are stored in GroupOrderArticleQuantity # class GroupOrderArticle < ApplicationRecord - belongs_to :group_order belongs_to :order_article has_many :group_order_article_quantities, dependent: :destroy validates_presence_of :group_order, :order_article - validates_uniqueness_of :order_article_id, :scope => :group_order_id # just once an article per group order + validates_uniqueness_of :order_article_id, :scope => :group_order_id # just once an article per group order validate :check_order_not_closed # don't allow changes to closed (aka settled) orders validates :quantity, :tolerance, numericality: { only_integer: true, greater_than_or_equal_to: 0 } @@ -83,10 +82,10 @@ class GroupOrderArticle < ApplicationRecord if (quantity > self.quantity || tolerance > self.tolerance) logger.debug("Inserting a new GroupOrderArticleQuantity") quantities.insert(0, GroupOrderArticleQuantity.new( - :group_order_article => self, - :quantity => (quantity > self.quantity ? quantity - self.quantity : 0), - :tolerance => (tolerance > self.tolerance ? tolerance - self.tolerance : 0) - )) + :group_order_article => self, + :quantity => (quantity > self.quantity ? quantity - self.quantity : 0), + :tolerance => (tolerance > self.tolerance ? tolerance - self.tolerance : 0) + )) # Recalc totals: self.quantity += quantities[0].quantity self.tolerance += quantities[0].tolerance @@ -99,11 +98,11 @@ class GroupOrderArticle < ApplicationRecord end # Remove zero-only items. - quantities = quantities.reject { | q | q.quantity == 0 && q.tolerance == 0} + quantities = quantities.reject { |q| q.quantity == 0 && q.tolerance == 0 } # Save transaction do - quantities.each { | i | i.save! } + quantities.each { |i| i.save! } self.group_order_article_quantities = quantities save! end @@ -169,7 +168,7 @@ class GroupOrderArticle < ApplicationRecord end # memoize result unless a total is given - r = {:quantity => quantity, :tolerance => tolerance, :total => quantity + tolerance} + r = { :quantity => quantity, :tolerance => tolerance, :total => quantity + tolerance } @calculate_result = r if total.nil? r end diff --git a/app/models/group_order_article_quantity.rb b/app/models/group_order_article_quantity.rb index de68aa50..1e29985f 100644 --- a/app/models/group_order_article_quantity.rb +++ b/app/models/group_order_article_quantity.rb @@ -2,7 +2,6 @@ # Considers every update of an article-order, so may rows for one group_order_article ar possible. class GroupOrderArticleQuantity < ApplicationRecord - belongs_to :group_order_article validates_presence_of :group_order_article_id diff --git a/app/models/invite.rb b/app/models/invite.rb index 65a5a8eb..e37a8a18 100644 --- a/app/models/invite.rb +++ b/app/models/invite.rb @@ -14,7 +14,7 @@ class Invite < ApplicationRecord before_validation :set_token_and_expires_at - protected + protected # Before validation, set token and expires_at. def set_token_and_expires_at @@ -22,7 +22,7 @@ class Invite < ApplicationRecord self.expires_at = Time.now.advance(:days => 7) end - private + private # Custom validation: check that email does not already belong to a registered user. def email_not_already_registered @@ -30,5 +30,4 @@ class Invite < ApplicationRecord errors.add(:email, I18n.t('invites.errors.already_member')) end end - end diff --git a/app/models/membership.rb b/app/models/membership.rb index 36354bcb..bebf00e2 100644 --- a/app/models/membership.rb +++ b/app/models/membership.rb @@ -1,11 +1,9 @@ class Membership < ApplicationRecord - belongs_to :user belongs_to :group before_destroy :check_last_admin - protected # check if this is the last admin-membership and deny diff --git a/app/models/order.rb b/app/models/order.rb index c70d3810..eb6df572 100644 --- a/app/models/order.rb +++ b/app/models/order.rb @@ -1,5 +1,3 @@ -# encoding: utf-8 -# class Order < ApplicationRecord attr_accessor :ignore_warnings, :transport_distribution @@ -71,8 +69,8 @@ class Order < ApplicationRecord if stockit? # make sure to include those articles which are no longer available # but which have already been ordered in this stock order - StockArticle.available.includes(:article_category). - order('article_categories.name', 'articles.name').reject{ |a| + StockArticle.available.includes(:article_category) + .order('article_categories.name', 'articles.name').reject { |a| a.quantity_available <= 0 && !a.ordered_in_order?(self) }.group_by { |a| a.article_category.name } else @@ -151,7 +149,7 @@ class Order < ApplicationRecord def self.ordergroup_group_orders_map(ordergroup) orders = includes(:supplier) group_orders = GroupOrder.where(ordergroup_id: ordergroup.id, order_id: orders.map(&:id)) - group_orders_hash = Hash[group_orders.collect {|go| [go.order_id, go]}] + group_orders_hash = Hash[group_orders.collect { |go| [go.order_id, go] }] orders.map do |order| { order: order, @@ -173,22 +171,22 @@ class Order < ApplicationRecord # The array has the following form: # e.g: [["drugs",[teethpaste, toiletpaper]], ["fruits" => [apple, banana, lemon]]] def articles_grouped_by_category - @articles_grouped_by_category ||= order_articles. - includes([:article_price, :group_order_articles, :article => :article_category]). - order('articles.name'). - group_by { |a| a.article.article_category.name }. - sort { |a, b| a[0] <=> b[0] } + @articles_grouped_by_category ||= order_articles + .includes([:article_price, :group_order_articles, :article => :article_category]) + .order('articles.name') + .group_by { |a| a.article.article_category.name } + .sort { |a, b| a[0] <=> b[0] } end def articles_sort_by_category - order_articles.includes(:article).order('articles.name').sort do |a,b| + order_articles.includes(:article).order('articles.name').sort do |a, b| a.article.article_category.name <=> b.article.article_category.name end end # Returns the defecit/benefit for the foodcoop # Requires a valid invoice, belonging to this order - #FIXME: Consider order.foodcoop_result + # FIXME: Consider order.foodcoop_result def profit(options = {}) markup = options[:without_markup] || false if invoice @@ -208,22 +206,22 @@ class Order < ApplicationRecord for oa in order_articles.ordered.includes(:article, :article_price) quantity = oa.units * oa.price.unit_quantity case type - when :net - total += quantity * oa.price.price - when :gross - total += quantity * oa.price.gross_price - when :fc - total += quantity * oa.price.fc_price + when :net + total += quantity * oa.price.price + when :gross + total += quantity * oa.price.gross_price + when :fc + total += quantity * oa.price.fc_price end end elsif type == :groups || type == :groups_without_markup - for go in group_orders.includes(group_order_articles: {order_article: [:article, :article_price]}) + for go in group_orders.includes(group_order_articles: { order_article: [:article, :article_price] }) for goa in go.group_order_articles case type - when :groups - total += goa.result * goa.order_article.price.fc_price - when :groups_without_markup - total += goa.result * goa.order_article.price.gross_price + when :groups + total += goa.result * goa.order_article.price.fc_price + when :groups_without_markup + total += goa.result * goa.order_article.price.gross_price end end end @@ -251,7 +249,7 @@ class Order < ApplicationRecord # A: Yes, we do - for redistributing articles when the number of articles # delivered changes, and for statistics on popular articles. Records # with both tolerance and quantity zero can be deleted. - #goa.group_order_article_quantities.clear + # goa.group_order_article_quantities.clear end end @@ -279,7 +277,7 @@ class Order < ApplicationRecord if stockit? # Decreases the quantity of stock_articles for oa in order_articles.includes(:article) oa.update_results! # Update units_to_order of order_article - stock_changes.create! :stock_article => oa.article, :quantity => oa.units_to_order*-1 + stock_changes.create! :stock_article => oa.article, :quantity => oa.units_to_order * -1 end end @@ -290,6 +288,7 @@ class Order < ApplicationRecord # Close the order directly, without automaticly updating ordergroups account balances def close_direct!(user) raise I18n.t('orders.model.error_closed') if closed? + comments.create(user: user, text: I18n.t('orders.model.close_direct_message')) unless FoodsoftConfig[:charge_members_manually] update_attributes! state: 'closed', updated_by: user end @@ -319,7 +318,7 @@ class Order < ApplicationRecord begin order.do_end_action! rescue => error - ExceptionNotifier.notify_exception(error, data: {foodcoop: FoodsoftConfig.scope, order_id: order.id}) + ExceptionNotifier.notify_exception(error, data: { foodcoop: FoodsoftConfig.scope, order_id: order.id }) end end end @@ -328,9 +327,9 @@ class Order < ApplicationRecord def starts_before_ends delta = Rails.env.test? ? 1 : 0 # since Rails 4.2 tests appear to have time differences, with this validation failing - errors.add(:ends, I18n.t('orders.model.error_starts_before_ends')) if ends && starts && ends <= (starts-delta) - errors.add(:ends, I18n.t('orders.model.error_boxfill_before_ends')) if ends && boxfill && ends <= (boxfill-delta) - errors.add(:boxfill, I18n.t('orders.model.error_starts_before_boxfill')) if boxfill && starts && boxfill <= (starts-delta) + errors.add(:ends, I18n.t('orders.model.error_starts_before_ends')) if ends && starts && ends <= (starts - delta) + errors.add(:ends, I18n.t('orders.model.error_boxfill_before_ends')) if ends && boxfill && ends <= (boxfill - delta) + errors.add(:boxfill, I18n.t('orders.model.error_starts_before_boxfill')) if boxfill && starts && boxfill <= (starts - delta) end def include_articles @@ -362,6 +361,7 @@ class Order < ApplicationRecord def distribute_transport return unless group_orders.any? + case transport_distribution.try(&:to_i) when Order.transport_distributions[:ordergroup] then amount = transport / group_orders.size diff --git a/app/models/order_article.rb b/app/models/order_article.rb index b4bc7fdb..38f353ab 100644 --- a/app/models/order_article.rb +++ b/app/models/order_article.rb @@ -38,6 +38,7 @@ class OrderArticle < ApplicationRecord def units return units_received unless units_received.nil? return units_billed unless units_billed.nil? + units_to_order end @@ -45,7 +46,7 @@ class OrderArticle < ApplicationRecord # In balancing this can differ from ordered (by supplier) quantity for this article. def group_orders_sum quantity = group_order_articles.collect(&:result).sum - {:quantity => quantity, :price => quantity * price.fc_price} + { :quantity => quantity, :price => quantity * price.fc_price } end # Update quantity/tolerance/units_to_order from group_order_articles @@ -96,7 +97,7 @@ class OrderArticle < ApplicationRecord units * price.unit_quantity * price.gross_price end - def ordered_quantities_different_from_group_orders?(ordered_mark="!", billed_mark="?", received_mark="?") + def ordered_quantities_different_from_group_orders?(ordered_mark = "!", billed_mark = "?", received_mark = "?") if not units_received.nil? ((units_received * price.unit_quantity) == group_orders_sum[:quantity]) ? false : received_mark elsif not units_billed.nil? @@ -123,12 +124,12 @@ class OrderArticle < ApplicationRecord if surplus.index(:tolerance).nil? qty_for_members = [qty_left, self.quantity].min else - qty_for_members = [qty_left, self.quantity+self.tolerance].min - counts[surplus.index(:tolerance)] = [0, qty_for_members-self.quantity].max + qty_for_members = [qty_left, self.quantity + self.tolerance].min + counts[surplus.index(:tolerance)] = [0, qty_for_members - self.quantity].max end # Recompute - group_order_articles.each {|goa| goa.save_results! qty_for_members } + group_order_articles.each { |goa| goa.save_results! qty_for_members } qty_left -= qty_for_members # if there's anything left, move to stock if wanted @@ -185,7 +186,7 @@ class OrderArticle < ApplicationRecord end def update_global_price=(value) - @update_global_price = (value == true || value == '1') ? true : false + @update_global_price = (value == true || value == '1') ? true : false end # @return [Number] Units missing for the last +unit_quantity+ of the article. @@ -199,7 +200,7 @@ class OrderArticle < ApplicationRecord # Check if the result of any associated GroupOrderArticle was overridden manually def result_manually_changed? - group_order_articles.any? {|goa| goa.result_manually_changed?} + group_order_articles.any? { |goa| goa.result_manually_changed? } end def difference_received_ordered @@ -245,7 +246,7 @@ class OrderArticle < ApplicationRecord end def _missing_units(unit_quantity, quantity, tolerance) - units = unit_quantity - ((quantity % unit_quantity) + tolerance) + units = unit_quantity - ((quantity % unit_quantity) + tolerance) units = 0 if units < 0 units = 0 if units == unit_quantity units diff --git a/app/models/order_comment.rb b/app/models/order_comment.rb index 2f29d385..5f35d98c 100644 --- a/app/models/order_comment.rb +++ b/app/models/order_comment.rb @@ -1,5 +1,4 @@ class OrderComment < ApplicationRecord - belongs_to :order belongs_to :user diff --git a/app/models/ordergroup.rb b/app/models/ordergroup.rb index da16db07..0e7be28d 100644 --- a/app/models/ordergroup.rb +++ b/app/models/ordergroup.rb @@ -1,13 +1,12 @@ -# encoding: utf-8 # # Ordergroups can order, they are "children" of the class Group -# +# # Ordergroup have the following attributes, in addition to Group # * account_balance (decimal) class Ordergroup < Group include CustomFields - APPLE_MONTH_AGO = 6 # How many month back we will count tasks and orders sum + APPLE_MONTH_AGO = 6 # How many month back we will count tasks and orders sum serialize :stats @@ -24,6 +23,7 @@ class Ordergroup < Group def contact "#{contact_phone} (#{contact_person})" end + def non_members User.natural_order.all.reject { |u| (users.include?(u) || u.ordergroup) } end @@ -43,6 +43,7 @@ class Ordergroup < Group def self.custom_fields fields = FoodsoftConfig[:custom_fields] && FoodsoftConfig[:custom_fields][:ordergroup] return [] unless fields + fields.map(&:deep_symbolize_keys) end @@ -59,11 +60,11 @@ class Ordergroup < Group end def value_of_open_orders(exclude = nil) - group_orders.in_open_orders.reject{|go| go == exclude}.collect(&:price).sum + group_orders.in_open_orders.reject { |go| go == exclude }.collect(&:price).sum end - + def value_of_finished_orders(exclude = nil) - group_orders.in_finished_orders.reject{|go| go == exclude}.collect(&:price).sum + group_orders.in_finished_orders.reject { |go| go == exclude }.collect(&:price).sum end # Returns the available funds for this order group (the account_balance minus price of all non-closed GroupOrders of this group). @@ -75,7 +76,7 @@ class Ordergroup < Group def financial_transaction_class_balance(klass) financial_transactions .joins(:financial_transaction_type) - .where(financial_transaction_types: {financial_transaction_class_id: klass}) + .where(financial_transaction_types: { financial_transaction_class_id: klass }) .sum(:amount) end @@ -101,14 +102,14 @@ class Ordergroup < Group orders_sum = group_orders.includes(:order).merge(Order.finished).where('orders.ends >= ?', APPLE_MONTH_AGO.month.ago).references(:orders).sum(:price) @readonly = false # Dirty hack, avoid getting RecordReadOnly exception when called in task after_save callback. A rails bug? - update_attribute(:stats, {:jobs_size => jobs, :orders_sum => orders_sum}) + update_attribute(:stats, { :jobs_size => jobs, :orders_sum => orders_sum }) end def update_balance! new_account_balance = financial_transactions - .joins(financial_transaction_type: [:financial_transaction_class]) - .where({ financial_transaction_classes: { ignore_for_account_balance: false} }) - .sum(:amount) + .joins(financial_transaction_type: [:financial_transaction_class]) + .where({ financial_transaction_classes: { ignore_for_account_balance: false } }) + .sum(:amount) update_attribute :account_balance, new_account_balance end @@ -116,7 +117,7 @@ class Ordergroup < Group stats[:jobs_size].to_f / stats[:orders_sum].to_f rescue 0 end - # This is the ordergroup job per euro performance + # This is the ordergroup job per euro performance # in comparison to the hole foodcoop average def apples ((avg_jobs_per_euro / Ordergroup.avg_jobs_per_euro) * 100).to_i rescue 0 @@ -128,23 +129,23 @@ class Ordergroup < Group # Only ordergroups, which have participated in more than 5 orders in total and more than 2 orders in apple time period def not_enough_apples? FoodsoftConfig[:use_apple_points] && - FoodsoftConfig[:stop_ordering_under].present? && - !ignore_apple_restriction && - apples < FoodsoftConfig[:stop_ordering_under] && - group_orders.count > 5 && - group_orders.joins(:order).merge(Order.finished).where('orders.ends >= ?', APPLE_MONTH_AGO.month.ago).count > 2 + FoodsoftConfig[:stop_ordering_under].present? && + !ignore_apple_restriction && + apples < FoodsoftConfig[:stop_ordering_under] && + group_orders.count > 5 && + group_orders.joins(:order).merge(Order.finished).where('orders.ends >= ?', APPLE_MONTH_AGO.month.ago).count > 2 end # Global average def self.avg_jobs_per_euro stats = Ordergroup.pluck(:stats) - stats.sum {|s| s[:jobs_size].to_f } / stats.sum {|s| s[:orders_sum].to_f } rescue 0 + stats.sum { |s| s[:jobs_size].to_f } / stats.sum { |s| s[:orders_sum].to_f } rescue 0 end def account_updated financial_transactions.last.try(:created_on) || created_on end - + private # Make sure, that a user can only be in one ordergroup @@ -163,6 +164,4 @@ class Ordergroup < Group errors.add :name, message end end - end - diff --git a/app/models/periodic_task_group.rb b/app/models/periodic_task_group.rb index 1eccacc9..c0a2b10f 100644 --- a/app/models/periodic_task_group.rb +++ b/app/models/periodic_task_group.rb @@ -4,6 +4,7 @@ class PeriodicTaskGroup < ApplicationRecord def has_next_task? return false if tasks.empty? return false if tasks.first.due_date.nil? + return true end diff --git a/app/models/shared_article.rb b/app/models/shared_article.rb index a02dfa31..238b48f0 100644 --- a/app/models/shared_article.rb +++ b/app/models/shared_article.rb @@ -1,5 +1,4 @@ class SharedArticle < ApplicationRecord - # connect to database from sharedLists-Application SharedArticle.establish_connection(FoodsoftConfig[:shared_lists]) # set correct table_name in external DB @@ -9,19 +8,19 @@ class SharedArticle < ApplicationRecord def build_new_article(supplier) supplier.articles.build( - :name => name, - :unit => unit, - :note => note, - :manufacturer => manufacturer, - :origin => origin, - :price => price, - :tax => tax, - :deposit => deposit, - :unit_quantity => unit_quantity, - :order_number => number, - :article_category => ArticleCategory.find_match(category), - # convert to db-compatible-string - :shared_updated_on => updated_on.to_formatted_s(:db) + :name => name, + :unit => unit, + :note => note, + :manufacturer => manufacturer, + :origin => origin, + :price => price, + :tax => tax, + :deposit => deposit, + :unit_quantity => unit_quantity, + :order_number => number, + :article_category => ArticleCategory.find_match(category), + # convert to db-compatible-string + :shared_updated_on => updated_on.to_formatted_s(:db) ) end end diff --git a/app/models/shared_supplier.rb b/app/models/shared_supplier.rb index 3e2a9012..29c9c1ab 100644 --- a/app/models/shared_supplier.rb +++ b/app/models/shared_supplier.rb @@ -1,5 +1,4 @@ class SharedSupplier < ApplicationRecord - # connect to database from sharedLists-Application SharedSupplier.establish_connection(FoodsoftConfig[:shared_lists]) # set correct table_name in external DB @@ -8,7 +7,6 @@ class SharedSupplier < ApplicationRecord has_many :suppliers, -> { undeleted } has_many :shared_articles, :foreign_key => :supplier_id - def find_article_by_number(order_number) # note that `shared_articles` uses number instead order_number cached_articles.detect { |a| a.number == order_number } @@ -22,7 +20,7 @@ class SharedSupplier < ApplicationRecord # when created by import from shared supplier feature. def autofill_attributes whitelist = %w(name address phone fax email url delivery_days note) - attributes.select { |k,_v| whitelist.include?(k) } + attributes.select { |k, _v| whitelist.include?(k) } end # return list of synchronisation methods available for this supplier diff --git a/app/models/stock_article.rb b/app/models/stock_article.rb index ba3b4d1b..42a06d49 100644 --- a/app/models/stock_article.rb +++ b/app/models/stock_article.rb @@ -1,11 +1,9 @@ -# encoding: utf-8 class StockArticle < Article - has_many :stock_changes scope :available, -> { undeleted.where('quantity > 0') } - validates :quantity, presence: true, numericality: {greater_than_or_equal_to: 0} + validates :quantity, presence: true, numericality: { greater_than_or_equal_to: 0 } before_destroy :check_quantity @@ -30,12 +28,12 @@ class StockArticle < Article end def quantity_ordered - OrderArticle.where(article_id: id). - joins(:order).where(orders: {state: %w[open finished received]}).sum(:units_to_order) + OrderArticle.where(article_id: id) + .joins(:order).where(orders: { state: %w[open finished received] }).sum(:units_to_order) end def quantity_history - stock_changes.reorder('stock_changes.created_at ASC').map{|s| s.quantity}.cumulative_sum + stock_changes.reorder('stock_changes.created_at ASC').map { |s| s.quantity }.cumulative_sum end def self.stock_value diff --git a/app/models/stock_event.rb b/app/models/stock_event.rb index e98e5b5f..4fd82864 100644 --- a/app/models/stock_event.rb +++ b/app/models/stock_event.rb @@ -1,8 +1,6 @@ class StockEvent < ApplicationRecord - has_many :stock_changes, dependent: :destroy has_many :stock_articles, through: :stock_changes validates_presence_of :date - end diff --git a/app/models/supplier.rb b/app/models/supplier.rb index d6ebbb00..862f5c24 100644 --- a/app/models/supplier.rb +++ b/app/models/supplier.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 class Supplier < ApplicationRecord include MarkAsDeletedWithName include CustomFields @@ -9,7 +8,7 @@ class Supplier < ApplicationRecord has_many :deliveries has_many :invoices belongs_to :supplier_category - belongs_to :shared_supplier, optional: true # for the sharedLists-App + belongs_to :shared_supplier, optional: true # for the sharedLists-App validates :name, :presence => true, :length => { :in => 4..30 } validates :phone, :presence => true, :length => { :in => 8..25 } @@ -65,7 +64,7 @@ class Supplier < ApplicationRecord .find_each { |new_shared_article| new_articles << new_shared_article.build_new_article(self) } # make them unavailable when desired if shared_sync_method == 'all_unavailable' - new_articles.each {|new_article| new_article.availability = false } + new_articles.each { |new_article| new_article.availability = false } end end return [updated_article_pairs, outlisted_articles, new_articles] @@ -77,7 +76,7 @@ class Supplier < ApplicationRecord # @param options [Hash] Options passed to {FoodsoftFile#parse} except when listed here. # @option options [Boolean] :outlist_absent Set to +true+ to remove articles not in spreadsheet. # @option options [Boolean] :convert_units Omit or set to +true+ to keep current units, recomputing unit quantity and price. - def sync_from_file(file, options={}) + def sync_from_file(file, options = {}) all_order_numbers = [] updated_article_pairs, outlisted_articles, new_articles = [], [], [] FoodsoftFile::parse file, options do |status, new_attrs, line| @@ -108,7 +107,7 @@ class Supplier < ApplicationRecord all_order_numbers << article.order_number if article end if options[:outlist_absent] - outlisted_articles += articles.undeleted.where.not(order_number: all_order_numbers+[nil]) + outlisted_articles += articles.undeleted.where.not(order_number: all_order_numbers + [nil]) end return [updated_article_pairs, outlisted_articles, new_articles] end @@ -116,6 +115,7 @@ class Supplier < ApplicationRecord # default value def shared_sync_method return unless shared_supplier + self[:shared_sync_method] || 'import' end diff --git a/app/models/supplier_category.rb b/app/models/supplier_category.rb index 915bab0e..02c726e0 100644 --- a/app/models/supplier_category.rb +++ b/app/models/supplier_category.rb @@ -1,5 +1,4 @@ class SupplierCategory < ActiveRecord::Base - belongs_to :financial_transaction_class has_many :suppliers @@ -15,5 +14,4 @@ class SupplierCategory < ActiveRecord::Base def check_for_associated_suppliers raise I18n.t('activerecord.errors.has_many_left', collection: Supplier.model_name.human) if suppliers.undeleted.any? end - end diff --git a/app/models/task.rb b/app/models/task.rb index a7e29197..cd748eb3 100644 --- a/app/models/task.rb +++ b/app/models/task.rb @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- class Task < ApplicationRecord has_many :assignments, :dependent => :destroy has_many :users, :through => :assignments @@ -25,19 +24,18 @@ class Task < ApplicationRecord # Find all tasks, for which the current user should be responsible # but which aren't accepted yet def self.unaccepted_tasks_for(user) - user.tasks.undone.where(assignments: {accepted: false}) + user.tasks.undone.where(assignments: { accepted: false }) end # Find all accepted tasks, which aren't done def self.accepted_tasks_for(user) - user.tasks.undone.where(assignments: {accepted: true}) + user.tasks.undone.where(assignments: { accepted: true }) end - # find all tasks in the period (or another number of days) def self.next_assigned_tasks_for(user, number = FoodsoftConfig[:tasks_period_days].to_i) - user.tasks.undone.where(assignments: {accepted: true}). - where(["tasks.due_date >= ? AND tasks.due_date <= ?", Time.now, number.days.from_now]) + user.tasks.undone.where(assignments: { accepted: true }) + .where(["tasks.due_date >= ? AND tasks.due_date <= ?", Time.now, number.days.from_now]) end # count tasks with not enough responsible people @@ -45,7 +43,7 @@ class Task < ApplicationRecord def self.unassigned_tasks_for(user) undone.includes(:assignments, workgroup: :memberships).select do |task| !task.enough_users_assigned? and - (!task.workgroup or task.workgroup.memberships.detect { |m| m.user_id == user.id }) + (!task.workgroup or task.workgroup.memberships.detect { |m| m.user_id == user.id }) end end @@ -53,6 +51,7 @@ class Task < ApplicationRecord periodic_task_group_count = {} self.unassigned_tasks_for(user).reject do |item| next false unless item.periodic_task_group + count = periodic_task_group_count[item.periodic_task_group] || 0 periodic_task_group_count[item.periodic_task_group] = count + 1 count >= max @@ -64,11 +63,11 @@ class Task < ApplicationRecord end def is_assigned?(user) - self.assignments.detect {|ass| ass.user_id == user.id } + self.assignments.detect { |ass| ass.user_id == user.id } end def is_accepted?(user) - self.assignments.detect {|ass| ass.user_id == user.id && ass.accepted } + self.assignments.detect { |ass| ass.user_id == user.id && ass.accepted } end def enough_users_assigned? @@ -98,7 +97,7 @@ class Task < ApplicationRecord if user.blank? errors.add(:user_list) else - if id == current_user_id.to_i + if id == current_user_id.to_i # current_user will accept, when he puts himself to the list of users self.assignments.build :user => user, :accepted => true else @@ -115,7 +114,7 @@ class Task < ApplicationRecord end def update_ordergroup_stats(user_ids = self.user_ids) - Ordergroup.joins(:users).where(users: {id: user_ids}).each(&:update_stats!) + Ordergroup.joins(:users).where(users: { id: user_ids }).each(&:update_stats!) end def exclude_from_periodic_task_group diff --git a/app/models/user.rb b/app/models/user.rb index dff03a4a..17c4b7ab 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,16 +1,14 @@ -# encoding: utf-8 - require 'digest/sha1' # specific user rights through memberships (see Group) class User < ApplicationRecord include CustomFields - #TODO: acts_as_paraniod ?? + # TODO: acts_as_paraniod ?? has_many :memberships, :dependent => :destroy has_many :groups, :through => :memberships - #has_one :ordergroup, :through => :memberships, :source => :group, :class_name => "Ordergroup" + # has_one :ordergroup, :through => :memberships, :source => :group, :class_name => "Ordergroup" def ordergroup - Ordergroup.joins(:memberships).where(memberships: {user_id: self.id}).first + Ordergroup.joins(:memberships).where(memberships: { user_id: self.id }).first end has_many :workgroups, :through => :memberships, :source => :group, :class_name => "Workgroup" @@ -49,7 +47,7 @@ class User < ApplicationRecord after_initialize do settings.defaults['profile'] = { 'language' => I18n.default_locale } unless settings.profile settings.defaults['messages'] = { 'send_as_email' => true } unless settings.messages - settings.defaults['notify'] = { 'upcoming_tasks' => true } unless settings.notify + settings.defaults['notify'] = { 'upcoming_tasks' => true } unless settings.notify end before_save do @@ -63,18 +61,18 @@ class User < ApplicationRecord settings_attributes.each do |key, value| value.each do |k, v| case v - when '1' - value[k] = true - when '0' - value[k] = false + when '1' + value[k] = true + when '0' + value[k] = false end end self.settings.merge!(key, value) end if settings_attributes if ActiveModel::Type::Boolean.new.cast(create_ordergroup) - og = Ordergroup.new({name: name}) - og.memberships.build({user: self}) + og = Ordergroup.new({ name: name }) + og.memberships.build({ user: self }) og.save! end @@ -103,7 +101,7 @@ class User < ApplicationRecord match_nick = users[:nick].matches("%#{q}%") # or each word matches either first or last name match_name = q.split.map do |a| - users[:first_name].matches("%#{a}%").or users[:last_name].matches("%#{a}%") + users[:first_name].matches("%#{a}%").or users[:last_name].matches("%#{a}%") end.reduce(:and) User.where(match_nick.or match_name) end @@ -123,7 +121,7 @@ class User < ApplicationRecord # Sets the user's password. It will be stored encrypted along with a random salt. def set_password unless password.blank? - salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp + salt = [Array.new(6) { rand(256).chr }.join].pack("m").chomp self.password_hash, self.password_salt = Digest::SHA1.hexdigest(password + salt), salt end end @@ -161,37 +159,37 @@ class User < ApplicationRecord # Checks the admin role def role_admin? - groups.detect {|group| group.role_admin?} + groups.detect { |group| group.role_admin? } end # Checks the finance role def role_finance? - FoodsoftConfig[:default_role_finance] || groups.detect {|group| group.role_finance?} + FoodsoftConfig[:default_role_finance] || groups.detect { |group| group.role_finance? } end # Checks the invoices role def role_invoices? - FoodsoftConfig[:default_role_invoices] || groups.detect {|group| group.role_invoices?} + FoodsoftConfig[:default_role_invoices] || groups.detect { |group| group.role_invoices? } end # Checks the article_meta role def role_article_meta? - FoodsoftConfig[:default_role_article_meta] || groups.detect {|group| group.role_article_meta?} + FoodsoftConfig[:default_role_article_meta] || groups.detect { |group| group.role_article_meta? } end # Checks the suppliers role def role_suppliers? - FoodsoftConfig[:default_role_suppliers] || groups.detect {|group| group.role_suppliers?} + FoodsoftConfig[:default_role_suppliers] || groups.detect { |group| group.role_suppliers? } end # Checks the invoices role def role_pickups? - FoodsoftConfig[:default_role_pickups] || groups.detect {|group| group.role_pickups?} + FoodsoftConfig[:default_role_pickups] || groups.detect { |group| group.role_pickups? } end # Checks the orders role def role_orders? - FoodsoftConfig[:default_role_orders] || groups.detect {|group| group.role_orders?} + FoodsoftConfig[:default_role_orders] || groups.detect { |group| group.role_orders? } end def ordergroup_name @@ -203,9 +201,9 @@ class User < ApplicationRecord group.users.exists?(self.id) end - #Returns an array with the users groups (but without the Ordergroups -> because tpye=>"") + # Returns an array with the users groups (but without the Ordergroups -> because tpye=>"") def member_of_groups() - self.groups.where(type: '') + self.groups.where(type: '') end def deleted? @@ -232,6 +230,7 @@ class User < ApplicationRecord def self.custom_fields fields = FoodsoftConfig[:custom_fields] && FoodsoftConfig[:custom_fields][:user] return [] unless fields + fields.map(&:deep_symbolize_keys) end @@ -249,7 +248,6 @@ class User < ApplicationRecord def token_attributes # would be sensible to match ApplicationController#show_user # this should not be part of the model anyway - {:id => id, :name => "#{display} (#{ordergroup.try(:name)})"} + { :id => id, :name => "#{display} (#{ordergroup.try(:name)})" } end - end diff --git a/app/models/workgroup.rb b/app/models/workgroup.rb index 4b5c4595..bf50c27b 100644 --- a/app/models/workgroup.rb +++ b/app/models/workgroup.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 class Workgroup < Group include CustomFields @@ -26,5 +25,4 @@ class Workgroup < Group errors.add(:role_admin, I18n.t('workgroups.error_last_admin_role')) end end - end diff --git a/app/serializers/config_serializer.rb b/app/serializers/config_serializer.rb index d5b6c138..0456cf21 100644 --- a/app/serializers/config_serializer.rb +++ b/app/serializers/config_serializer.rb @@ -12,7 +12,6 @@ class ConfigSerializer < ActiveModel::Serializer # help and version attributes :applepear_url, :help_url, :foodsoft - def foodsoft { version: Foodsoft::VERSION, diff --git a/app/workers/user_notifier.rb b/app/workers/user_notifier.rb index 4f15e2cf..014444b7 100644 --- a/app/workers/user_notifier.rb +++ b/app/workers/user_notifier.rb @@ -12,6 +12,7 @@ class UserNotifier order_id = args.first Order.find(order_id).group_orders.each do |group_order| next if group_order.ordergroup.nil? + group_order.ordergroup.users.each do |user| if user.settings.notify['order_finished'] Mailer.deliver_now_with_user_locale user do diff --git a/config.ru b/config.ru index 5c12528f..e0faca0f 100644 --- a/config.ru +++ b/config.ru @@ -1,6 +1,6 @@ # This file is used by Rack-based servers to start the application. -require ::File.expand_path('../config/environment', __FILE__) +require ::File.expand_path('../config/environment', __FILE__) # https://gist.github.com/ebeigarts/5450422 map ENV['RAILS_RELATIVE_URL_ROOT'] || '/' do diff --git a/config/application.rb b/config/application.rb index 50f40161..e3f63146 100644 --- a/config/application.rb +++ b/config/application.rb @@ -29,7 +29,7 @@ module Foodsoft # Internationalization. config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '*.yml')] - config.i18n.available_locales = Pathname.glob(Rails.root.join('config', 'locales', '{??,???}{-*,}.yml')).map{|p| p.basename('.yml').to_s } + config.i18n.available_locales = Pathname.glob(Rails.root.join('config', 'locales', '{??,???}{-*,}.yml')).map { |p| p.basename('.yml').to_s } config.i18n.default_locale = :en config.i18n.fallbacks = [:en] @@ -58,7 +58,7 @@ module Foodsoft config.assets.initialize_on_precompile = true # Load legacy scripts from vendor - config.assets.precompile += [ 'vendor/assets/javascripts/*.js' ] + config.assets.precompile += ['vendor/assets/javascripts/*.js'] # CORS for API config.middleware.insert_before 0, Rack::Cors do diff --git a/config/environments/production.rb b/config/environments/production.rb index a4dd695f..0723fa18 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -52,7 +52,7 @@ Rails.application.configure do config.log_level = :info # Prepend all log lines with the following tags. - config.log_tags = [ :request_id ] + config.log_tags = [:request_id] # Don't dump schema in production (especially useful for Docker) config.active_record.dump_schema_after_migration = false diff --git a/config/initializers/bullet.rb b/config/initializers/bullet.rb index 99e9a127..73e6e9b4 100644 --- a/config/initializers/bullet.rb +++ b/config/initializers/bullet.rb @@ -3,4 +3,4 @@ if defined? Bullet # Bullet.alert = true Bullet.bullet_logger = true Bullet.console = true -end \ No newline at end of file +end diff --git a/config/initializers/currency_display.rb b/config/initializers/currency_display.rb index 191f255c..7caa6a64 100644 --- a/config/initializers/currency_display.rb +++ b/config/initializers/currency_display.rb @@ -2,6 +2,6 @@ # have it shown in all other languages too ::I18n.available_locales.each do |locale| unless locale == ::I18n.default_locale - ::I18n.backend.store_translations(locale, number: {currency: {format: {unit: nil}}}) + ::I18n.backend.store_translations(locale, number: { currency: { format: { unit: nil } } }) end end diff --git a/config/initializers/exception_notification.rb b/config/initializers/exception_notification.rb index a941fbb5..10107865 100644 --- a/config/initializers/exception_notification.rb +++ b/config/initializers/exception_notification.rb @@ -1,6 +1,5 @@ require 'exception_notification/rails' - require 'resque/failure/multiple' require 'resque/failure/redis' require 'exception_notification/resque' @@ -8,7 +7,6 @@ require 'exception_notification/resque' Resque::Failure::Multiple.classes = [Resque::Failure::Redis, ExceptionNotification::Resque] Resque::Failure.backend = Resque::Failure::Multiple - ExceptionNotification.configure do |config| # Ignore additional exception types. # ActiveRecord::RecordNotFound, Mongoid::Errors::DocumentNotFound, AbstractController::ActionNotFound and ActionController::RoutingError are already added. @@ -25,8 +23,8 @@ ExceptionNotification.configure do |config| # Email notifier sends notifications by email. if notification = FoodsoftConfig[:notification] config.add_notifier :email, { - :email_prefix => notification[:email_prefix], - :sender_address => notification[:sender_address], + :email_prefix => notification[:email_prefix], + :sender_address => notification[:sender_address], :exception_recipients => notification[:error_recipients], } end @@ -49,5 +47,4 @@ ExceptionNotification.configure do |config| # :url => 'http://example.com:5555/hubot/path', # :http_method => :post # } - end diff --git a/config/initializers/extensions.rb b/config/initializers/extensions.rb index 1f71d542..799f52e6 100644 --- a/config/initializers/extensions.rb +++ b/config/initializers/extensions.rb @@ -1,6 +1,5 @@ # extend the BigDecimal class class String - # remove comma from decimal inputs def self.delocalized_decimal(string) if !string.blank? and string.is_a?(String) @@ -14,6 +13,6 @@ end class Array def cumulative_sum csum = 0 - self.map{|val| csum += val} + self.map { |val| csum += val } end end diff --git a/config/initializers/new_rails_defaults.rb b/config/initializers/new_rails_defaults.rb index 78e0117c..a6adb905 100644 --- a/config/initializers/new_rails_defaults.rb +++ b/config/initializers/new_rails_defaults.rb @@ -14,4 +14,4 @@ ActiveSupport.use_standard_json_time_format = true # Don't escape HTML entities in JSON, leave that for the #json_escape helper. # if you're including raw json in an HTML page. -ActiveSupport.escape_html_entities_in_json = false \ No newline at end of file +ActiveSupport.escape_html_entities_in_json = false diff --git a/config/initializers/ruby_units.rb b/config/initializers/ruby_units.rb index dcbe7315..b8b56cca 100644 --- a/config/initializers/ruby_units.rb +++ b/config/initializers/ruby_units.rb @@ -29,7 +29,7 @@ if defined? RubyUnits # we use pc for piece, not parsec RubyUnits::Unit.redefine!('parsec') do |unit| - unit.aliases = unit.aliases.reject {|u| u=='pc'} + unit.aliases = unit.aliases.reject { |u| u == 'pc' } unit.display_name = 'parsec' end @@ -37,7 +37,7 @@ if defined? RubyUnits # default precision of 8 which same as all database definitions in db/migrate/20131213002332_*.rb class Rational alias orig_to_d to_d - def to_d(precision=8) + def to_d(precision = 8) orig_to_d(precision) end end diff --git a/config/initializers/session_store.rb b/config/initializers/session_store.rb index 17e027ea..d7841180 100644 --- a/config/initializers/session_store.rb +++ b/config/initializers/session_store.rb @@ -10,6 +10,7 @@ module ActionDispatch path = request.original_fullpath[script_name.size..-1] slug = path.split('/', 2).first return if slug.blank? + cookie[:path] = script_name + slug end orig_set_cookie request, session_id, cookie diff --git a/config/initializers/simple_form.rb b/config/initializers/simple_form.rb index bb683629..8a07c0ef 100644 --- a/config/initializers/simple_form.rb +++ b/config/initializers/simple_form.rb @@ -6,7 +6,7 @@ SimpleForm.setup do |config| # stack. The options given below are used to wrap the # whole input. config.wrappers :default, class: :input, - hint_class: :field_with_hint, error_class: :field_with_errors do |b| + hint_class: :field_with_hint, error_class: :field_with_errors do |b| ## Extensions enabled by default # Any of these extensions can be disabled for a # given input by passing: `f.input EXTENSION_NAME => false`. diff --git a/config/navigation.rb b/config/navigation.rb index b621412a..c8b7d088 100644 --- a/config/navigation.rb +++ b/config/navigation.rb @@ -1,12 +1,10 @@ -# -*- coding: utf-8 -*- # Configures your navigation SimpleNavigation::Configuration.run do |navigation| - # allow engines to add to the menu - https://gist.github.com/mjtko/4873ee0c112b6bd646f8 engines = Rails::Engine.subclasses.map(&:instance).select { |e| e.respond_to?(:navigation) } # to include an engine but keep it from modifying the menu: - #engines.reject! { |e| e.instance_of? FoodsoftMyplugin::Engine } + # engines.reject! { |e| e.instance_of? FoodsoftMyplugin::Engine } navigation.items do |primary| primary.dom_class = 'nav' @@ -54,5 +52,4 @@ SimpleNavigation::Configuration.run do |navigation| engines.each { |e| e.navigation(primary, self) } end - end diff --git a/config/routes.rb b/config/routes.rb index 07b49cb9..d7ec44a7 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,5 +1,4 @@ Rails.application.routes.draw do - get "order_comments/new" get "comments/new" @@ -9,7 +8,6 @@ Rails.application.routes.draw do root to: 'sessions#redirect_to_foodcoop', as: nil scope '/:foodcoop' do - use_doorkeeper # Root path @@ -217,7 +215,6 @@ Rails.application.routes.draw do end resources :bank_transactions, only: [:index, :show] - end ########### Administration @@ -265,7 +262,7 @@ Rails.application.routes.draw do namespace :user do root to: 'users#show' - get :financial_overview, to: 'ordergroup#financial_overview' + get :financial_overview, to: 'ordergroup#financial_overview' resources :financial_transactions, only: [:index, :show, :create] resources :group_order_articles end @@ -287,6 +284,5 @@ Rails.application.routes.draw do ############## The rest resources :users, only: [:index] - end # End of /:foodcoop scope end diff --git a/db/migrate/001_create_users.rb b/db/migrate/001_create_users.rb index 70f54df6..ab4a560a 100644 --- a/db/migrate/001_create_users.rb +++ b/db/migrate/001_create_users.rb @@ -16,13 +16,13 @@ class CreateUsers < ActiveRecord::Migration[4.2] end add_index(:users, :nick, :unique => true) add_index(:users, :email, :unique => true) - + # Create the default admin user... puts "Creating user #{USER_ADMIN} with password 'secret'..." user = User.new(:nick => USER_ADMIN, :first_name => "Anton", :last_name => "Administrator", :email => "admin@foo.test") user.password = "secret" raise "Failed!" unless user.save && User.find_by_nick(USER_ADMIN).has_password("secret") - + # Create a normal user... puts "Creating user #{USER_TEST} with password 'foobar'..." user = User.new(:nick => USER_TEST, :first_name => "Tim", :last_name => "Tester", :email => "test@foo.test") diff --git a/db/migrate/002_create_groups.rb b/db/migrate/002_create_groups.rb index 15b2ce11..bb7427b9 100644 --- a/db/migrate/002_create_groups.rb +++ b/db/migrate/002_create_groups.rb @@ -1,49 +1,50 @@ class CreateGroups < ActiveRecord::Migration[4.2] GROUP_ADMIN = 'Administrators' GROUP_ORDER = 'Sample Order Group' - + def self.up create_table :groups do |t| t.column :type, :string, :null => false # inheritance, types: Group, OrderGroup t.column :name, :string, :null => false t.column :description, :string - t.column :actual_size, :integer # OrderGroup column - t.column :account_balance, :decimal, :precision => 8, :scale => 2, :null => false, :default => 0 # OrderGroup column - t.column :account_updated, :timestamp # OrderGroup column + t.column :actual_size, :integer # OrderGroup column + t.column :account_balance, :decimal, :precision => 8, :scale => 2, :null => false, :default => 0 # OrderGroup column + t.column :account_updated, :timestamp # OrderGroup column t.column :created_on, :timestamp, :null => false t.column :role_admin, :boolean, :default => false, :null => false end add_index(:groups, :name, :unique => true) - + create_table :memberships do |t| t.column :group_id, :integer, :null => false t.column :user_id, :integer, :null => false end add_index(:memberships, [:user_id, :group_id], :unique => true) - + # Create the default "Administrators" group... puts "Creating group #{GROUP_ADMIN}..." Group.create(:name => GROUP_ADMIN, :description => "System administrators.", :role_admin => true) raise 'Failed!' unless administrators = Group.find_by_name(GROUP_ADMIN) - + # Create a sample order group... puts "Creating order group #{GROUP_ORDER}..." ordergroup = OrderGroup.create!(:name => GROUP_ORDER, :description => "A sample order group created by the migration.", :actual_size => 1, :account_updated => Time.now) raise "Wrong type created!" unless ordergroup.is_a?(OrderGroup) - + # Get the admin user and join the admin group... raise "User #{CreateUsers::USER_ADMIN} not found, cannot join group '#{administrators.name}'!" unless admin = User.find_by_nick(CreateUsers::USER_ADMIN) + puts "Joining #{CreateUsers::USER_ADMIN} user to new '#{administrators.name}' group as a group admin..." membership = Membership.create(:group => administrators, :user => admin) raise "Failed!" unless admin.memberships.first == membership raise "User #{CreateUsers::USER_ADMIN} has no admin_roles" unless admin.role_admin? - + # Get the test user and join the order group... raise "User #{CreateUsers::USER_TEST} not found, cannot join group '#{ordergroup.name}'!" unless test = User.find_by_nick(CreateUsers::USER_TEST) + puts "Joining #{CreateUsers::USER_TEST} user to new '#{ordergroup.name}' group as a group admin..." membership = Membership.create(:group => ordergroup, :user => test) raise "Failed!" unless test.memberships.first == membership - end def self.down diff --git a/db/migrate/003_create_suppliers.rb b/db/migrate/003_create_suppliers.rb index e3ff260a..2b38c9c1 100644 --- a/db/migrate/003_create_suppliers.rb +++ b/db/migrate/003_create_suppliers.rb @@ -1,18 +1,18 @@ class CreateSuppliers < ActiveRecord::Migration[4.2] - SUPPLIER_SAMPLE = 'Sample Supplier' - - def self.up + SUPPLIER_SAMPLE = 'Sample Supplier' + + def self.up add_column :groups, :role_suppliers, :boolean, :default => false, :null => false Group.reset_column_information puts "Give #{CreateGroups::GROUP_ADMIN} the role supplier .." raise "Failed" unless Group.find_by_name(CreateGroups::GROUP_ADMIN).update_attribute(:role_suppliers, true) raise "Cannot find admin user!" unless admin = User.find_by_nick(CreateUsers::USER_ADMIN) raise "Failed to enable role_suppliers with admin user!" unless admin.role_suppliers? - + create_table :suppliers do |t| - t.column :name, :string, :null => false - t.column :address, :string, :null => false - t.column :phone, :string, :null => false + t.column :name, :string, :null => false + t.column :address, :string, :null => false + t.column :phone, :string, :null => false t.column :phone2, :string t.column :fax, :string t.column :email, :string @@ -23,12 +23,12 @@ class CreateSuppliers < ActiveRecord::Migration[4.2] t.column :order_howto, :string t.column :note, :string end - add_index(:suppliers, :name, :unique => true) - + add_index(:suppliers, :name, :unique => true) + # Create sample supplier... puts "Creating sample supplier '#{SUPPLIER_SAMPLE}'..." Supplier.create(:name => SUPPLIER_SAMPLE, :address => "Organic City", :phone => "0123-555555") - raise "Failed!" unless supplier = Supplier.find_by_name(SUPPLIER_SAMPLE) + raise "Failed!" unless supplier = Supplier.find_by_name(SUPPLIER_SAMPLE) end def self.down diff --git a/db/migrate/004_create_article_meta.rb b/db/migrate/004_create_article_meta.rb index 6362765b..eb81f550 100644 --- a/db/migrate/004_create_article_meta.rb +++ b/db/migrate/004_create_article_meta.rb @@ -2,28 +2,27 @@ class CreateArticleMeta < ActiveRecord::Migration[4.2] CATEGORY_SAMPLE = 'Sample Category' TAX_STANDARD = 'Standard' TAX_REDUCED = 'Reduced' - + def self.up # Add user roles... - add_column :groups, :role_article_meta, :boolean, :default => false, :null => false + add_column :groups, :role_article_meta, :boolean, :default => false, :null => false Group.reset_column_information puts "Give #{CreateGroups::GROUP_ADMIN} the role article_meta .." raise "Failed" unless Group.find_by_name(CreateGroups::GROUP_ADMIN).update_attribute(:role_article_meta, true) raise 'Cannot find admin user!' unless admin = User.find_by_nick(CreateUsers::USER_ADMIN) raise 'Failed to enable role_article_meta with admin user!' unless admin.role_article_meta? - + # ArticleCategories create_table :article_categories do |t| t.column :name, :string, :null => false t.column :description, :string end add_index(:article_categories, :name, :unique => true) - + # Create sample category... puts "Creating sample article category '#{CATEGORY_SAMPLE}'..." ArticleCategory.create(:name => CATEGORY_SAMPLE, :description => "This is just a sample article category.") - raise "Failed!" unless category = ArticleCategory.find_by_name(CATEGORY_SAMPLE) - + raise "Failed!" unless category = ArticleCategory.find_by_name(CATEGORY_SAMPLE) end def self.down diff --git a/db/migrate/005_create_financial_transactions.rb b/db/migrate/005_create_financial_transactions.rb index 73d53a93..0b1cef89 100644 --- a/db/migrate/005_create_financial_transactions.rb +++ b/db/migrate/005_create_financial_transactions.rb @@ -21,16 +21,16 @@ class CreateFinancialTransactions < ActiveRecord::Migration[4.2] # Add transactions to the sample order group puts "Add 30 transactions to the group '#{CreateGroups::GROUP_ORDER}'..." raise "Group '#{CreateGroups::GROUP_ORDER}' not found!" unless ordergroup = Group.find_by_name(CreateGroups::GROUP_ORDER) + balance = 0 for i in 1..30 ordergroup.addFinancialTransaction(i, "Sample Transaction Nr. #{i}", admin) balance += i end - raise "Failed!" unless financial_transaction = FinancialTransaction.find_by_note('Sample Transaction Nr. 1') + raise "Failed!" unless financial_transaction = FinancialTransaction.find_by_note('Sample Transaction Nr. 1') raise "Failed to update account_balance!" unless OrderGroup.find(ordergroup.id).account_balance == balance - end - + def self.down remove_column :groups, :role_finance drop_table :financial_transactions diff --git a/db/migrate/006_create_articles.rb b/db/migrate/006_create_articles.rb index 1e7f7e57..9a43c8dc 100644 --- a/db/migrate/006_create_articles.rb +++ b/db/migrate/006_create_articles.rb @@ -1,5 +1,5 @@ class CreateArticles < ActiveRecord::Migration[4.2] - SAMPLE_ARTICLE_NAMES = ['banana', 'kiwi', 'strawberry'] + SAMPLE_ARTICLE_NAMES = ['banana', 'kiwi', 'strawberry'] def self.up create_table :articles do |t| @@ -11,23 +11,23 @@ class CreateArticles < ActiveRecord::Migration[4.2] t.column :availability, :boolean, :default => true, :null => false t.column :current_price_id, :integer end - add_index(:articles, :name, :unique => true) - + add_index(:articles, :name, :unique => true) + # Create 30 sample articles... puts "Create 3 articles of the supplier '#{CreateSuppliers::SUPPLIER_SAMPLE}'..." raise "Supplier '#{CreateSuppliers::SUPPLIER_SAMPLE}' not found!" unless supplier = Supplier.find_by_name(CreateSuppliers::SUPPLIER_SAMPLE) raise "Category '#{CreateArticleMeta::CATEGORY_SAMPLE}' not found!" unless category = ArticleCategory.find_by_name(CreateArticleMeta::CATEGORY_SAMPLE) + SAMPLE_ARTICLE_NAMES.each do |a| - puts 'Create Article ' + a - Article.create( :name => a, - :supplier => supplier, - :article_category => category, - :unit => '500g', - :note => 'delicious', - :availability => true) - end + puts 'Create Article ' + a + Article.create(:name => a, + :supplier => supplier, + :article_category => category, + :unit => '500g', + :note => 'delicious', + :availability => true) + end raise "Failed!" unless Article.find(:all).length == SAMPLE_ARTICLE_NAMES.length - end def self.down diff --git a/db/migrate/007_create_article_prices.rb b/db/migrate/007_create_article_prices.rb index 18954fd0..32488794 100644 --- a/db/migrate/007_create_article_prices.rb +++ b/db/migrate/007_create_article_prices.rb @@ -3,30 +3,30 @@ class CreateArticlePrices < ActiveRecord::Migration[4.2] create_table :article_prices do |t| t.column :article_id, :int, :null => false t.column :clear_price, :decimal, :precision => 8, :scale => 2, :null => false - t.column :gross_price, :decimal, :precision => 8, :scale => 2, :null => false #gross price, incl. vat, refund and price markup + t.column :gross_price, :decimal, :precision => 8, :scale => 2, :null => false # gross price, incl. vat, refund and price markup t.column :tax, :float, :null => false, :default => 0 t.column :refund, :decimal, :precision => 8, :scale => 2, :null => false, :default => 0 t.column :updated_on, :datetime t.column :unit_quantity, :int, :default => 1, :null => false t.column :order_number, :string end - add_index(:article_prices, :article_id) - - #add some prices ... - puts 'add prices to the sample articles' - CreateArticles::SAMPLE_ARTICLE_NAMES.each do |a| - puts 'Create Price for article ' + a - raise 'article #{a} not found!' unless article = Article.find_by_name(a) - new_price = ArticlePrice.new(:clear_price => rand(4)+1, - :tax => 7.0, - :refund => 0, - :unit_quantity => rand(10)+1, - :order_number => rand(9999)) - article.add_price(new_price) - raise 'Failed!' unless ArticlePrice.find_by_article_id(article.id) - end - raise 'Failed!' unless ArticlePrice.find(:all).length == CreateArticles::SAMPLE_ARTICLE_NAMES.length - + add_index(:article_prices, :article_id) + + # add some prices ... + puts 'add prices to the sample articles' + CreateArticles::SAMPLE_ARTICLE_NAMES.each do |a| + puts 'Create Price for article ' + a + raise 'article #{a} not found!' unless article = Article.find_by_name(a) + + new_price = ArticlePrice.new(:clear_price => rand(4) + 1, + :tax => 7.0, + :refund => 0, + :unit_quantity => rand(10) + 1, + :order_number => rand(9999)) + article.add_price(new_price) + raise 'Failed!' unless ArticlePrice.find_by_article_id(article.id) + end + raise 'Failed!' unless ArticlePrice.find(:all).length == CreateArticles::SAMPLE_ARTICLE_NAMES.length end def self.down diff --git a/db/migrate/008_create_orders.rb b/db/migrate/008_create_orders.rb index d785c293..6eb8c921 100644 --- a/db/migrate/008_create_orders.rb +++ b/db/migrate/008_create_orders.rb @@ -1,7 +1,7 @@ class CreateOrders < ActiveRecord::Migration[4.2] ORDER_TEST = 'Test Order' GROUP_ORDER = 'Orders' - + def self.up # Order role add_column :groups, :role_orders, :boolean, :default => false, :null => false @@ -10,12 +10,12 @@ class CreateOrders < ActiveRecord::Migration[4.2] raise "Failed" unless Group.find_by_name(CreateGroups::GROUP_ADMIN).update_attribute(:role_orders, true) raise 'Cannot find admin user!' unless admin = User.find_by_nick(CreateUsers::USER_ADMIN) raise 'Failed to enable role_orders with admin user!' unless admin.role_orders? - + # Create the default "Order" group... puts 'Creating group "Orders"...' Group.create(:name => GROUP_ORDER, :description => "working group for managing orders", :role_orders => true) raise "Failed!" unless Group.find_by_name(GROUP_ORDER) - + # Order create_table :orders do |t| t.column :name, :string, :null => false @@ -31,9 +31,10 @@ class CreateOrders < ActiveRecord::Migration[4.2] add_index(:orders, :starts) add_index(:orders, :ends) add_index(:orders, :finished) - + puts "Creating order '#{ORDER_TEST}'..." raise "Supplier '#{CreateSuppliers::SUPPLIER_SAMPLE}' not found!" unless supplier = Supplier.find_by_name(CreateSuppliers::SUPPLIER_SAMPLE) + Order.create(:name => ORDER_TEST, :supplier => supplier, :starts => Time.now) raise 'Creating test order failed!' unless order = Order.find_by_name(ORDER_TEST) @@ -47,17 +48,18 @@ class CreateOrders < ActiveRecord::Migration[4.2] t.column :lock_version, :integer, :null => false, :default => 0 end add_index(:order_articles, [:order_id, :article_id], :unique => true) - + puts 'Adding articles to the order...' - CreateArticles::SAMPLE_ARTICLE_NAMES.each { | a | - puts "Article #{a}..." - raise 'Article not found!' unless article = Article.find_by_name(a) - raise 'No price found for article!' unless price = article.current_price - OrderArticle.create(:order => order, :article => article) - raise 'Creating OrderArticle failed!' unless OrderArticle.find_by_order_id_and_article_id(order.id, article.id) - } - raise 'Creating OrderArticles failed!' unless order.articles.size == CreateArticles::SAMPLE_ARTICLE_NAMES.length - + CreateArticles::SAMPLE_ARTICLE_NAMES.each { |a| + puts "Article #{a}..." + raise 'Article not found!' unless article = Article.find_by_name(a) + raise 'No price found for article!' unless price = article.current_price + + OrderArticle.create(:order => order, :article => article) + raise 'Creating OrderArticle failed!' unless OrderArticle.find_by_order_id_and_article_id(order.id, article.id) + } + raise 'Creating OrderArticles failed!' unless order.articles.size == CreateArticles::SAMPLE_ARTICLE_NAMES.length + # GroupOrder create_table :group_orders do |t| t.column :order_group_id, :integer, :null => false @@ -67,14 +69,15 @@ class CreateOrders < ActiveRecord::Migration[4.2] t.column :updated_on, :timestamp, :null => false t.column :updated_by_user_id, :integer, :null => false end - add_index(:group_orders, [:order_group_id, :order_id], :unique => true) - + add_index(:group_orders, [:order_group_id, :order_id], :unique => true) + puts 'Adding group order...' raise "Cannot find user #{CreateUsers::USER_TEST}" unless user = User.find_by_nick(CreateUsers::USER_TEST) raise "Cannot find OrderGroup '#{CreateGroups::GROUP_ORDER}'!" unless orderGroup = OrderGroup.find_by_name(CreateGroups::GROUP_ORDER) + GroupOrder.create(:order_group => orderGroup, :order => order, :price => 0, :updated_by => user) raise 'Retrieving group order failed!' unless groupOrder = orderGroup.group_orders.find(:first, :conditions => "order_id = #{order.id}") - + # GroupOrderArticles create_table :group_order_articles do |t| t.column :group_order_id, :integer, :null => false @@ -82,7 +85,7 @@ class CreateOrders < ActiveRecord::Migration[4.2] t.column :quantity, :integer, :null => false t.column :tolerance, :integer, :null => false t.column :updated_on, :timestamp, :null => false - end + end add_index(:group_order_articles, [:group_order_id, :order_article_id], :unique => true, :name => "goa_index") # GroupOrderArticleQuantity create_table :group_order_article_quantities do |t| @@ -91,20 +94,22 @@ class CreateOrders < ActiveRecord::Migration[4.2] t.column :tolerance, :int, :default => 0 t.column :created_on, :timestamp, :null => false end - + puts 'Adding articles to group order...' - order.order_articles.each { | orderArticle | + order.order_articles.each { |orderArticle| puts "Article #{orderArticle.article.name}..." GroupOrderArticle.create(:group_order => groupOrder, :order_article => orderArticle, :quantity => 0, :tolerance => 0) raise 'Failed to create order!' unless article = GroupOrderArticle.find(:first, :conditions => "group_order_id = #{groupOrder.id} AND order_article_id = #{orderArticle.id}") + article.updateQuantities(rand(6) + 1, rand(4) + 1) } - raise 'Failed to create orders!' unless groupOrder.order_articles.size == order.order_articles.size + raise 'Failed to create orders!' unless groupOrder.order_articles.size == order.order_articles.size + groupOrder.updatePrice - raise 'Failed to update GroupOrder.price' unless groupOrder.save! - + raise 'Failed to update GroupOrder.price' unless groupOrder.save! + # Update order - order.updateQuantities + order.updateQuantities end def self.down diff --git a/db/migrate/009_create_order_results.rb b/db/migrate/009_create_order_results.rb index 4288b7c7..20b75193 100644 --- a/db/migrate/009_create_order_results.rb +++ b/db/migrate/009_create_order_results.rb @@ -6,7 +6,7 @@ class CreateOrderResults < ActiveRecord::Migration[4.2] t.column :price, :decimal, :precision => 8, :scale => 2, :null => false, :default => 0 end add_index(:group_order_results, [:group_name, :order_id], :unique => true) - + create_table :order_article_results do |t| t.column :order_id, :int, :null => false t.column :name, :string, :null => false @@ -22,7 +22,7 @@ class CreateOrderResults < ActiveRecord::Migration[4.2] t.column :units_to_order, :int, :null => false end add_index(:order_article_results, :order_id) - + create_table :group_order_article_results do |t| t.column :order_article_result_id, :int, :null => false t.column :group_order_result_id, :int, :null => false diff --git a/db/migrate/010_user_password_reset.rb b/db/migrate/010_user_password_reset.rb index 598104b5..3eadafd2 100644 --- a/db/migrate/010_user_password_reset.rb +++ b/db/migrate/010_user_password_reset.rb @@ -1,8 +1,7 @@ class UserPasswordReset < ActiveRecord::Migration[4.2] - def self.up add_column :users, :reset_password_token, :string - add_column :users, :reset_password_expires, :timestamp + add_column :users, :reset_password_expires, :timestamp end def self.down diff --git a/db/migrate/011_create_comments.rb b/db/migrate/011_create_comments.rb index f3142ba4..28fc0428 100644 --- a/db/migrate/011_create_comments.rb +++ b/db/migrate/011_create_comments.rb @@ -6,13 +6,13 @@ class CreateComments < ActiveRecord::Migration[4.2] t.column :created_at, :datetime, :null => false t.column :commentable_id, :integer, :default => 0, :null => false t.column :commentable_type, :string, :limit => 15, - :default => "", :null => false + :default => "", :null => false t.column :user_id, :integer, :default => 0, :null => false end - + add_index :comments, ["user_id"], :name => "fk_comments_user" end - + def self.down drop_table :comments end diff --git a/db/migrate/012_create_order_clearing.rb b/db/migrate/012_create_order_clearing.rb index 0b1a7ac9..1d3133fd 100644 --- a/db/migrate/012_create_order_clearing.rb +++ b/db/migrate/012_create_order_clearing.rb @@ -1,5 +1,4 @@ class CreateOrderClearing < ActiveRecord::Migration[4.2] - def self.up add_column :orders, :invoice_amount, :decimal, :precision => 8, :scale => 2, :null => false, :default => 0 add_column :orders, :refund, :decimal, :precision => 8, :scale => 2, :null => false, :default => 0 diff --git a/db/migrate/013_add_messaging.rb b/db/migrate/013_add_messaging.rb index da3b0bcb..84ba8d6f 100644 --- a/db/migrate/013_add_messaging.rb +++ b/db/migrate/013_add_messaging.rb @@ -13,7 +13,7 @@ class AddMessaging < ActiveRecord::Migration[4.2] end add_index(:messages, :sender_id) add_index(:messages, :recipient_id) - + # Setup acts_as_configurable plugin for user options etc. ConfigurableSetting.create_table end diff --git a/db/migrate/014_create_tasks.rb b/db/migrate/014_create_tasks.rb index ad8e0242..db878546 100644 --- a/db/migrate/014_create_tasks.rb +++ b/db/migrate/014_create_tasks.rb @@ -12,14 +12,14 @@ class CreateTasks < ActiveRecord::Migration[4.2] end add_index :tasks, :name add_index :tasks, :due_date - + create_table :assignments do |t| t.column :user_id, :integer, :null => false t.column :task_id, :integer, :null => false t.column :accepted, :boolean, :default => false end add_index :assignments, [:user_id, :task_id], :unique => true - + add_column :groups, :weekly_task, :boolean, :default => false # if group has an job for every week add_column :groups, :weekday, :integer # e.g. 1 means monday, 2 = tuesday an so on add_column :groups, :task_name, :string # the name of the weekly task diff --git a/db/migrate/015_change_result_quantities.rb b/db/migrate/015_change_result_quantities.rb index 9f4589bb..23731334 100644 --- a/db/migrate/015_change_result_quantities.rb +++ b/db/migrate/015_change_result_quantities.rb @@ -6,6 +6,6 @@ class ChangeResultQuantities < ActiveRecord::Migration[4.2] def self.down change_column :group_order_article_results, :quantity, :integer, :null => false - change_column :order_article_results, :units_to_order,:integer, :default => 0, :null => false + change_column :order_article_results, :units_to_order, :integer, :default => 0, :null => false end end diff --git a/db/migrate/016_add_shared_lists_connection.rb b/db/migrate/016_add_shared_lists_connection.rb index f9950b28..1b052061 100644 --- a/db/migrate/016_add_shared_lists_connection.rb +++ b/db/migrate/016_add_shared_lists_connection.rb @@ -1,7 +1,7 @@ class AddSharedListsConnection < ActiveRecord::Migration[4.2] def self.up add_column :suppliers, :shared_supplier_id, :integer - add_column :articles, :manufacturer , :string + add_column :articles, :manufacturer, :string add_column :articles, :origin, :string add_column :articles, :shared_updated_on, :timestamp end diff --git a/db/migrate/021_remove_table_article_prices.rb b/db/migrate/021_remove_table_article_prices.rb index 17cf6b45..dc664347 100644 --- a/db/migrate/021_remove_table_article_prices.rb +++ b/db/migrate/021_remove_table_article_prices.rb @@ -1,6 +1,5 @@ class RemoveTableArticlePrices < ActiveRecord::Migration[4.2] def self.up - puts "create columns in articles ..." add_column "articles", "clear_price", :decimal, :precision => 8, :scale => 2, :default => 0.0, :null => false add_column "articles", "gross_price", :decimal, :precision => 8, :scale => 2, :default => 0.0, :null => false @@ -10,24 +9,23 @@ class RemoveTableArticlePrices < ActiveRecord::Migration[4.2] add_column "articles", "order_number", :string add_column "articles", "created_at", :datetime add_column "articles", "updated_at", :datetime - + # stop auto-updating the timestamps to make the data-copy safe! Article.record_timestamps = false - + puts "now copy values of article_prices into new articles-columns..." Article.find(:all).each do |article| price = article.current_price article.update_attributes!(:clear_price => price.clear_price, - :gross_price => price.gross_price, - :tax => price.tax, - :refund => price.refund, - :unit_quantity => price.unit_quantity, - :order_number => price.order_number, - :updated_at => price.updated_on, - :created_at => price.updated_on) + :gross_price => price.gross_price, + :tax => price.tax, + :refund => price.refund, + :unit_quantity => price.unit_quantity, + :order_number => price.order_number, + :updated_at => price.updated_on, + :created_at => price.updated_on) end - - + puts "delete article_prices, current_price attribute" drop_table :article_prices remove_column :articles, :current_price_id @@ -40,29 +38,28 @@ class RemoveTableArticlePrices < ActiveRecord::Migration[4.2] t.decimal "clear_price", :precision => 8, :scale => 2, :default => 0.0, :null => false t.decimal "gross_price", :precision => 8, :scale => 2, :default => 0.0, :null => false t.float "tax", :default => 0.0, :null => false - t.decimal "refund", :precision => 8, :scale => 2, :default => 0.0, :null => false + t.decimal "refund", :precision => 8, :scale => 2, :default => 0.0, :null => false t.datetime "updated_on" - t.integer "unit_quantity", :default => 1, :null => false + t.integer "unit_quantity", :default => 1, :null => false t.string "order_number" end - + # copy data from article now into old ArticlePrice-object Article.find(:all).each do |article| price = ArticlePrice.create(:clear_price => article.clear_price, - :gross_price => article.gross_price, - :tax => article.tax, - :refund => article.refund, - :unit_quantity => article.unit_quantity, - :order_number => article.order_number.blank? ? nil : article.order_number, - :updated_on => article.updated_at) - + :gross_price => article.gross_price, + :tax => article.tax, + :refund => article.refund, + :unit_quantity => article.unit_quantity, + :order_number => article.order_number.blank? ? nil : article.order_number, + :updated_on => article.updated_at) + article.update_attribute(:current_price, price) price.update_attribute(:article, article) - end - + # remove new columns - remove_column "articles", "clear_price" + remove_column "articles", "clear_price" remove_column "articles", "gross_price" remove_column "articles", "tax" remove_column "articles", "refund" @@ -70,6 +67,5 @@ class RemoveTableArticlePrices < ActiveRecord::Migration[4.2] remove_column "articles", "order_number" remove_column "articles", "created_at" remove_column "articles", "updated_at" - end end diff --git a/db/migrate/023_new_wording.rb b/db/migrate/023_new_wording.rb index e2fb77e8..21daf421 100644 --- a/db/migrate/023_new_wording.rb +++ b/db/migrate/023_new_wording.rb @@ -2,10 +2,10 @@ class NewWording < ActiveRecord::Migration[4.2] def self.up rename_column :articles, :clear_price, :net_price rename_column :articles, :refund, :deposit - + rename_column :order_article_results, :clear_price, :net_price rename_column :order_article_results, :refund, :deposit - + rename_column :orders, :refund, :deposit rename_column :orders, :refund_credit, :deposit_credit end @@ -13,10 +13,10 @@ class NewWording < ActiveRecord::Migration[4.2] def self.down rename_column :articles, :net_price, :clear_price rename_column :articles, :deposit, :refund - + rename_column :order_article_results, :net_price, :clear_price rename_column :order_article_results, :deposit, :refund - + rename_column :orders, :deposit, :refund rename_column :orders, :deposit_credit, :refund_credit end diff --git a/db/migrate/20090120184410_road_to_version_three.rb b/db/migrate/20090120184410_road_to_version_three.rb index be53b11d..4b8aa9ab 100644 --- a/db/migrate/20090120184410_road_to_version_three.rb +++ b/db/migrate/20090120184410_road_to_version_three.rb @@ -1,4 +1,3 @@ - class OrderGroup < Group; end # Needed for renaming of OrderGroup to Ordergroup class RoadToVersionThree < ActiveRecord::Migration[4.2] @@ -30,7 +29,7 @@ class RoadToVersionThree < ActiveRecord::Migration[4.2] end # == Ordergroups - remove_column :groups, :actual_size # Useless, desposits are better stored within a transaction.note + remove_column :groups, :actual_size # Useless, desposits are better stored within a transaction.note # rename from OrderGroup to Ordergroup rename_column :financial_transactions, :order_group_id, :ordergroup_id rename_column :group_orders, :order_group_id, :ordergroup_id @@ -49,7 +48,7 @@ class RoadToVersionThree < ActiveRecord::Migration[4.2] contact = ordergroup.users.first if contact ordergroup.update_attributes :contact_person => contact.name, - :contact_phone => contact.phone, :contact_address => contact.address + :contact_phone => contact.phone, :contact_address => contact.address end end remove_column :users, :address @@ -66,7 +65,7 @@ class RoadToVersionThree < ActiveRecord::Migration[4.2] t.text :note t.datetime :starts t.datetime :ends - t.string :state, :default => "open" # Statemachine ... open -> finished -> closed + t.string :state, :default => "open" # Statemachine ... open -> finished -> closed t.integer :lock_version, :default => 0, :null => false t.integer :updated_by_user_id end @@ -81,13 +80,13 @@ class RoadToVersionThree < ActiveRecord::Migration[4.2] t.date :paid_on t.text :note t.decimal :amount, :null => false, :precision => 8, :scale => 2, :default => 0.0 - t.decimal :deposit, :precision => 8, :scale => 2, :default => 0.0, :null => false - t.decimal :deposit_credit, :precision => 8, :scale => 2, :default => 0.0, :null => false + t.decimal :deposit, :precision => 8, :scale => 2, :default => 0.0, :null => false + t.decimal :deposit_credit, :precision => 8, :scale => 2, :default => 0.0, :null => false t.timestamps end # == Delivery - create_table :deliveries do |t| + create_table :deliveries do |t| t.integer :supplier_id t.date :delivered_on t.datetime :created_at @@ -118,11 +117,11 @@ class RoadToVersionThree < ActiveRecord::Migration[4.2] # Create price history for every Article Article.all.each do |a| a.article_prices.create :price => a.price, :tax => a.tax, - :deposit => a.deposit, :unit_quantity => a.unit_quantity + :deposit => a.deposit, :unit_quantity => a.unit_quantity end # Every Article has now a Category. Fix it if neccessary. Article.all(:conditions => { :article_category_id => nil }).each do |article| - article.update_attribute(:article_category, ArticleCategory.first) + article.update_attribute(:article_category, ArticleCategory.first) end # order-articles add_column :order_articles, :article_price_id, :integer diff --git a/db/migrate/20090317175355_add_profit_to_orders.rb b/db/migrate/20090317175355_add_profit_to_orders.rb index 508e6982..59f79609 100644 --- a/db/migrate/20090317175355_add_profit_to_orders.rb +++ b/db/migrate/20090317175355_add_profit_to_orders.rb @@ -1,7 +1,7 @@ class AddProfitToOrders < ActiveRecord::Migration[4.2] def self.up add_column :orders, :foodcoop_result, :decimal, :precision => 8, :scale => 2 - + Order.closed.each do |order| order.update_attribute(:foodcoop_result, order.profit) end diff --git a/db/migrate/20090907120012_add_missing_indexes.rb b/db/migrate/20090907120012_add_missing_indexes.rb index 03dc43cd..189b0417 100644 --- a/db/migrate/20090907120012_add_missing_indexes.rb +++ b/db/migrate/20090907120012_add_missing_indexes.rb @@ -1,11 +1,11 @@ class AddMissingIndexes < ActiveRecord::Migration[4.2] def self.up add_index "article_prices", ["article_id"] - + add_index "articles", ["supplier_id"] add_index "articles", ["article_category_id"] add_index "articles", ["type"] - + add_index "deliveries", ["supplier_id"] add_index "financial_transactions", ["ordergroup_id"] @@ -18,16 +18,16 @@ class AddMissingIndexes < ActiveRecord::Migration[4.2] add_index "invoices", ["delivery_id"] add_index "order_articles", ["order_id"] - + add_index "order_comments", ["order_id"] - + add_index "orders", ["state"] - add_index "stock_changes", ["delivery_id"] - add_index "stock_changes", ["stock_article_id"] + add_index "stock_changes", ["delivery_id"] + add_index "stock_changes", ["stock_article_id"] add_index "stock_changes", ["stock_taking_id"] - add_index "tasks", ["workgroup_id"] + add_index "tasks", ["workgroup_id"] end def self.down diff --git a/db/migrate/20130622095040_move_weekly_tasks.rb b/db/migrate/20130622095040_move_weekly_tasks.rb index 3ca266ae..b780f3e9 100644 --- a/db/migrate/20130622095040_move_weekly_tasks.rb +++ b/db/migrate/20130622095040_move_weekly_tasks.rb @@ -33,7 +33,8 @@ class MoveWeeklyTasks < ActiveRecord::Migration[4.2] end end -private + private + def weekly_task?(workgroup, task) return false if task.due_date.nil? diff --git a/db/migrate/20130718183100_create_settings.rb b/db/migrate/20130718183100_create_settings.rb index f6e2a9ad..9928a9b3 100644 --- a/db/migrate/20130718183100_create_settings.rb +++ b/db/migrate/20130718183100_create_settings.rb @@ -7,8 +7,8 @@ class CreateSettings < ActiveRecord::Migration[4.2] t.string :thing_type, limit: 30, null: true t.timestamps end - - add_index :settings, [ :thing_type, :thing_id, :var ], unique: true + + add_index :settings, [:thing_type, :thing_id, :var], unique: true end def self.down diff --git a/db/migrate/20130718183101_migrate_user_settings.rb b/db/migrate/20130718183101_migrate_user_settings.rb index 1a13efba..cd173e45 100644 --- a/db/migrate/20130718183101_migrate_user_settings.rb +++ b/db/migrate/20130718183101_migrate_user_settings.rb @@ -1,7 +1,6 @@ class MigrateUserSettings < ActiveRecord::Migration[4.2] def up say_with_time 'Save old user settings in new RailsSettings module' do - # Allow setting default locale via env parameter # This is used, when setting users language settings default_locale = I18n.default_locale @@ -15,7 +14,7 @@ class MigrateUserSettings < ActiveRecord::Migration[4.2] type = old_setting.configurable_type id = old_setting.configurable_id begin - user = type.constantize.find(id) + user = type.constantize.find(id) rescue ActiveRecord::RecordNotFound Rails.logger.debug "Can't find configurable object with type: #{type.inspect}, id: #{id.inspect}" next @@ -32,9 +31,9 @@ class MigrateUserSettings < ActiveRecord::Migration[4.2] # set the settings_attributes (thanks to settings.merge! we can set them one by one) user.settings_attributes = { - "#{namespace}" => { - "#{key}" => value - } + "#{namespace}" => { + "#{key}" => value + } } # save the user to apply after_save callback @@ -52,4 +51,4 @@ class MigrateUserSettings < ActiveRecord::Migration[4.2] end # this is the base class of all configurable settings -class ConfigurableSetting < ActiveRecord::Base; end \ No newline at end of file +class ConfigurableSetting < ActiveRecord::Base; end diff --git a/db/migrate/20140102170431_add_result_computed_to_group_order_articles.rb b/db/migrate/20140102170431_add_result_computed_to_group_order_articles.rb index 3a5f2634..dd9fc407 100644 --- a/db/migrate/20140102170431_add_result_computed_to_group_order_articles.rb +++ b/db/migrate/20140102170431_add_result_computed_to_group_order_articles.rb @@ -1,6 +1,6 @@ class AddResultComputedToGroupOrderArticles < ActiveRecord::Migration[4.2] def change add_column :group_order_articles, :result_computed, - :decimal, :precision => 8, :scale => 3 + :decimal, :precision => 8, :scale => 3 end end diff --git a/db/migrate/20160309153440_create_doorkeeper_tables.rb b/db/migrate/20160309153440_create_doorkeeper_tables.rb index 37ecbe7b..8e9ac257 100644 --- a/db/migrate/20160309153440_create_doorkeeper_tables.rb +++ b/db/migrate/20160309153440_create_doorkeeper_tables.rb @@ -27,11 +27,11 @@ class CreateDoorkeeperTables < ActiveRecord::Migration[4.2] create_table :oauth_access_tokens do |t| t.integer :resource_owner_id t.integer :application_id - t.string :token, null: false + t.string :token, null: false t.string :refresh_token t.integer :expires_in t.datetime :revoked_at - t.datetime :created_at, null: false + t.datetime :created_at, null: false t.string :scopes end diff --git a/db/migrate/20181201000400_create_supplier_categories.rb b/db/migrate/20181201000400_create_supplier_categories.rb index f831bb30..3c1671c6 100644 --- a/db/migrate/20181201000400_create_supplier_categories.rb +++ b/db/migrate/20181201000400_create_supplier_categories.rb @@ -1,6 +1,8 @@ class CreateSupplierCategories < ActiveRecord::Migration[4.2] class FinancialTransactionClass < ActiveRecord::Base; end + class SupplierCategory < ActiveRecord::Base; end + class Supplier < ActiveRecord::Base; end def change diff --git a/db/migrate/20181204000000_clear_invalid_invoices_from_orders.rb b/db/migrate/20181204000000_clear_invalid_invoices_from_orders.rb index 5980fd3e..766551e7 100644 --- a/db/migrate/20181204000000_clear_invalid_invoices_from_orders.rb +++ b/db/migrate/20181204000000_clear_invalid_invoices_from_orders.rb @@ -1,5 +1,6 @@ class ClearInvalidInvoicesFromOrders < ActiveRecord::Migration[4.2] class Order < ActiveRecord::Base; end + class Invoice < ActiveRecord::Base; end def up diff --git a/db/migrate/20181204070000_create_stock_events.rb b/db/migrate/20181204070000_create_stock_events.rb index 6de2c6cc..2b6a78e5 100644 --- a/db/migrate/20181204070000_create_stock_events.rb +++ b/db/migrate/20181204070000_create_stock_events.rb @@ -1,5 +1,6 @@ class CreateStockEvents < ActiveRecord::Migration[4.2] class StockEvent < ActiveRecord::Base; end + class StockTaking < ActiveRecord::Base; end def change diff --git a/db/seeds/minimal.seeds.rb b/db/seeds/minimal.seeds.rb index c0ef7f0c..d38ef10e 100644 --- a/db/seeds/minimal.seeds.rb +++ b/db/seeds/minimal.seeds.rb @@ -2,24 +2,24 @@ # Create working group with full rights administrators = Workgroup.create!( - :name => "Administrators", - :description => "System administrators.", - :role_admin => true, - :role_finance => true, - :role_article_meta => true, - :role_pickups => true, - :role_suppliers => true, - :role_orders => true + :name => "Administrators", + :description => "System administrators.", + :role_admin => true, + :role_finance => true, + :role_article_meta => true, + :role_pickups => true, + :role_suppliers => true, + :role_orders => true ) # Create admin user User.create!( - :nick => "admin", - :first_name => "Anton", - :last_name => "Administrator", - :email => "admin@foo.test", - :password => "secret", - :groups => [administrators] + :nick => "admin", + :first_name => "Anton", + :last_name => "Administrator", + :email => "admin@foo.test", + :password => "secret", + :groups => [administrators] ) # First entry for financial transaction types diff --git a/db/seeds/seed_helper.rb b/db/seeds/seed_helper.rb index 5a05fb2a..574be356 100644 --- a/db/seeds/seed_helper.rb +++ b/db/seeds/seed_helper.rb @@ -1,4 +1,3 @@ - # only works properly for open orders, at the moment def seed_group_orders Order.all.each do |order| @@ -6,12 +5,13 @@ def seed_group_orders Ordergroup.all.each do |og| # 20% of the order-ordergroup combinations don't order next if rand(10) < 2 + # order 3..12 times a random article go = og.group_orders.create!(order: order, updated_by_user_id: 1) - (3+rand(10)).times do + (3 + rand(10)).times do goa = go.group_order_articles.find_or_create_by!(order_article: order.order_articles.offset(rand(noas)).first) unit_quantity = goa.order_article.price.unit_quantity - goa.update_quantities rand([4, 2*unit_quantity+2].max), rand(unit_quantity) + goa.update_quantities rand([4, 2 * unit_quantity + 2].max), rand(unit_quantity) end end # update totals @@ -20,8 +20,8 @@ def seed_group_orders end end -def seed_order(options={}) - options[:article_ids] ||= (options[:supplier]||Supplier.find(options[:supplier_id])).articles.map(&:id) +def seed_order(options = {}) + options[:article_ids] ||= (options[:supplier] || Supplier.find(options[:supplier_id])).articles.map(&:id) options[:created_by_user_id] ||= 1 options[:updated_by_user_id] ||= 1 Order.create! options diff --git a/db/seeds/small.en.seeds.rb b/db/seeds/small.en.seeds.rb index 5e33a1e7..40c338ac 100644 --- a/db/seeds/small.en.seeds.rb +++ b/db/seeds/small.en.seeds.rb @@ -10,11 +10,11 @@ FinancialTransactionClass.create!(:id => 2, :name => 'Foodsoft') SupplierCategory.create!(:id => 1, :name => "Other", :financial_transaction_class_id => 1) Supplier.create!([ - {:id => 1, :name => "Beautiful bakery", :supplier_category_id => 1, :address => "Smallstreet 1, Cookilage", :phone => "0123456789", :email => "info@bbakery.test", :min_order_quantity => "100"}, - {:id => 2, :name => "Chocolatiers", :supplier_category_id => 1, :address => "Multatuliroad 1, Amsterdam", :phone => "0123456789", :email => "info@chocolatiers.test", :url => "http://www.chocolatiers.test/", :contact_person => "Max Pure", :delivery_days => "Tue, Fr (Amsterdam)"}, - {:id => 3, :name => "Cheesemaker", :supplier_category_id => 1, :address => "Cheesestreet 5, London", :phone => "0123456789", :url => "http://www.cheesemaker.test/"}, - {:id => 4, :name => "The Nuthome", :supplier_category_id => 1, :address => "Alexanderplatz, Berlin", :phone => "0123456789", :email => "info@thenuthome.test", :url => "http://www.thenuthome.test/", :note => "delivery in Berlin; €9 delivery costs for orders under €123"} -]) + { :id => 1, :name => "Beautiful bakery", :supplier_category_id => 1, :address => "Smallstreet 1, Cookilage", :phone => "0123456789", :email => "info@bbakery.test", :min_order_quantity => "100" }, + { :id => 2, :name => "Chocolatiers", :supplier_category_id => 1, :address => "Multatuliroad 1, Amsterdam", :phone => "0123456789", :email => "info@chocolatiers.test", :url => "http://www.chocolatiers.test/", :contact_person => "Max Pure", :delivery_days => "Tue, Fr (Amsterdam)" }, + { :id => 3, :name => "Cheesemaker", :supplier_category_id => 1, :address => "Cheesestreet 5, London", :phone => "0123456789", :url => "http://www.cheesemaker.test/" }, + { :id => 4, :name => "The Nuthome", :supplier_category_id => 1, :address => "Alexanderplatz, Berlin", :phone => "0123456789", :email => "info@thenuthome.test", :url => "http://www.thenuthome.test/", :note => "delivery in Berlin; €9 delivery costs for orders under €123" } + ]) ArticleCategory.create!(:id => 1, :name => "Other", :description => "other, misc, unknown") ArticleCategory.create!(:id => 2, :name => "Fruit") @@ -140,7 +140,6 @@ Article.create!(:name => "Blueberries", :supplier_id => 4, :article_category_id Article.create!(:name => "Chia seeds", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.55555E3, :tax => 6.0, :deposit => 0.0, :unit_quantity => 1, :order_number => ":416d57b") Article.create!(:name => "Coconut grated", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.55E0, :tax => 6.0, :deposit => 0.0, :unit_quantity => 1, :order_number => ":b3f65e4") - ## Members & groups User.create!(:id => 1, :nick => "admin", :password => "secret", :first_name => "Anton", :last_name => "Administrator", :email => "admin@foo.test", :created_on => 'Wed, 15 Jan 2014 16:15:33 UTC +00:00') @@ -153,10 +152,10 @@ Workgroup.create!(:id => 1, :name => "Administrators", :description => "System a Workgroup.create!(:id => 2, :name => "Finances", :account_balance => 0.0, :created_on => 'Sun, 19 Jan 2014 17:40:03 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => true, :role_orders => false, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) Workgroup.create!(:id => 3, :name => "Ordering", :account_balance => 0.0, :created_on => 'Thu, 20 Feb 2014 14:44:47 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => true, :role_finance => false, :role_orders => true, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) Workgroup.create!(:id => 4, :name => "Assortment", :account_balance => 0.0, :created_on => 'Wed, 09 Apr 2014 12:24:55 UTC +00:00', :role_admin => false, :role_suppliers => true, :role_article_meta => true, :role_finance => false, :role_orders => false, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) -Ordergroup.create!(:id => 5, :name => "Admin Administrator", :account_balance => 0.0, :created_on => 'Sat, 18 Jan 2014 00:38:48 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :stats => {:jobs_size=>0, :orders_sum=>1021.74}, :next_weekly_tasks_number => 8, :ignore_apple_restriction => true) -Ordergroup.create!(:id => 6, :name => "Pete's house", :account_balance => -0.35E2, :created_on => 'Sat, 25 Jan 2014 20:20:37 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :contact_person => "Piet Pieterssen", :stats => {:jobs_size=>0, :orders_sum=>60.96}, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) -Ordergroup.create!(:id => 7, :name => "Jan Klaassen", :account_balance => -0.35E2, :created_on => 'Mon, 27 Jan 2014 16:22:14 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :contact_person => "Jan Klaassen", :stats => {:jobs_size=>0, :orders_sum=>0}, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) -Ordergroup.create!(:id => 8, :name => "John Doe", :account_balance => 0.90E2, :created_on => 'Wed, 09 Apr 2014 12:23:29 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :contact_person => "John Doe", :stats => {:jobs_size=>0, :orders_sum=>0}, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) +Ordergroup.create!(:id => 5, :name => "Admin Administrator", :account_balance => 0.0, :created_on => 'Sat, 18 Jan 2014 00:38:48 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :stats => { :jobs_size => 0, :orders_sum => 1021.74 }, :next_weekly_tasks_number => 8, :ignore_apple_restriction => true) +Ordergroup.create!(:id => 6, :name => "Pete's house", :account_balance => -0.35E2, :created_on => 'Sat, 25 Jan 2014 20:20:37 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :contact_person => "Piet Pieterssen", :stats => { :jobs_size => 0, :orders_sum => 60.96 }, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) +Ordergroup.create!(:id => 7, :name => "Jan Klaassen", :account_balance => -0.35E2, :created_on => 'Mon, 27 Jan 2014 16:22:14 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :contact_person => "Jan Klaassen", :stats => { :jobs_size => 0, :orders_sum => 0 }, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) +Ordergroup.create!(:id => 8, :name => "John Doe", :account_balance => 0.90E2, :created_on => 'Wed, 09 Apr 2014 12:23:29 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :contact_person => "John Doe", :stats => { :jobs_size => 0, :orders_sum => 0 }, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) Membership.create!(:group_id => 1, :user_id => 1) Membership.create!(:group_id => 5, :user_id => 1) @@ -170,19 +169,16 @@ Membership.create!(:group_id => 7, :user_id => 5) Membership.create!(:group_id => 3, :user_id => 5) Membership.create!(:group_id => 4, :user_id => 5) - ## Orders & OrderArticles seed_order(supplier_id: 1, starts: 2.days.ago, ends: 5.days.from_now) seed_order(supplier_id: 3, starts: 2.days.ago, ends: 5.days.from_now) seed_order(supplier_id: 2, starts: 2.days.ago, ends: 4.days.from_now) - ## GroupOrders & such seed_group_orders - ## Finances FinancialTransactionType.create!(:id => 1, :name => "Foodcoop", :financial_transaction_class_id => 1) diff --git a/db/seeds/small.nl.seeds.rb b/db/seeds/small.nl.seeds.rb index 8a64797e..afa9cc04 100644 --- a/db/seeds/small.nl.seeds.rb +++ b/db/seeds/small.nl.seeds.rb @@ -10,11 +10,11 @@ FinancialTransactionClass.create!(:id => 2, :name => 'Foodsoft') SupplierCategory.create!(:id => 1, :name => "Other", :financial_transaction_class_id => 1) Supplier.create!([ - {:id => 1, :name => "Koekenbakker", :supplier_category_id => 1, :address => "Dorpsstraat 1, Koekange", :phone => "012 3456789", :email => "info@dekoekenbakker.test", :min_order_quantity => "100"}, - {:id => 2, :name => "Chocolademakkers", :supplier_category_id => 1, :address => "Multatuliweg 1, Amsterdam", :phone => "012 3456789", :email => "info@chocolademakkers.test", :url => "http://www.chocolademakkers.test/", :contact_person => "Max Puur", :delivery_days => "di, vr (Amsterdam)"}, - {:id => 3, :name => "Kaasmaker", :supplier_category_id => 1, :address => "Waagplein, Alkmaar", :phone => "012 3456789", :url => "http://www.kaaskamer.test/"}, - {:id => 4, :name => "Notenhuis", :supplier_category_id => 1, :address => "Damrak 1, Amsterdam", :phone => "012 3456789", :email => "info@notenhuis.test", :url => "http://www.notenhuis.test/", :note => "leveren in Amsterdam; €9 leverkosten bij bestellingen onder €123"} -]) + { :id => 1, :name => "Koekenbakker", :supplier_category_id => 1, :address => "Dorpsstraat 1, Koekange", :phone => "012 3456789", :email => "info@dekoekenbakker.test", :min_order_quantity => "100" }, + { :id => 2, :name => "Chocolademakkers", :supplier_category_id => 1, :address => "Multatuliweg 1, Amsterdam", :phone => "012 3456789", :email => "info@chocolademakkers.test", :url => "http://www.chocolademakkers.test/", :contact_person => "Max Puur", :delivery_days => "di, vr (Amsterdam)" }, + { :id => 3, :name => "Kaasmaker", :supplier_category_id => 1, :address => "Waagplein, Alkmaar", :phone => "012 3456789", :url => "http://www.kaaskamer.test/" }, + { :id => 4, :name => "Notenhuis", :supplier_category_id => 1, :address => "Damrak 1, Amsterdam", :phone => "012 3456789", :email => "info@notenhuis.test", :url => "http://www.notenhuis.test/", :note => "leveren in Amsterdam; €9 leverkosten bij bestellingen onder €123" } + ]) ArticleCategory.create!(:id => 1, :name => "Other", :description => "overig, anders, onbekend") ArticleCategory.create!(:id => 2, :name => "Fruit") @@ -140,7 +140,6 @@ Article.create!(:name => "Blueberries", :supplier_id => 4, :article_category_id Article.create!(:name => "Chia zaad", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.55555E3, :tax => 6.0, :deposit => 0.0, :unit_quantity => 1, :order_number => ":416d57b") Article.create!(:name => "Cocos Rasp", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.55E0, :tax => 6.0, :deposit => 0.0, :unit_quantity => 1, :order_number => ":b3f65e4") - ## Members & groups User.create!(:id => 1, :nick => "admin", :password => "secret", :first_name => "Anton", :last_name => "Administrator", :email => "admin@foo.test", :created_on => 'Wed, 15 Jan 2014 16:15:33 UTC +00:00') @@ -153,10 +152,10 @@ Workgroup.create!(:id => 1, :name => "Admins", :description => "Beheerders", :ac Workgroup.create!(:id => 2, :name => "Financiën", :account_balance => 0.0, :created_on => 'Sun, 19 Jan 2014 17:40:03 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => true, :role_orders => false, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) Workgroup.create!(:id => 3, :name => "Bestellen", :account_balance => 0.0, :created_on => 'Thu, 20 Feb 2014 14:44:47 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => true, :role_finance => false, :role_orders => true, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) Workgroup.create!(:id => 4, :name => "Assortiment", :account_balance => 0.0, :created_on => 'Wed, 09 Apr 2014 12:24:55 UTC +00:00', :role_admin => false, :role_suppliers => true, :role_article_meta => true, :role_finance => false, :role_orders => false, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) -Ordergroup.create!(:id => 5, :name => "Admin Administrator", :account_balance => 0.0, :created_on => 'Sat, 18 Jan 2014 00:38:48 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :stats => {:jobs_size=>0, :orders_sum=>1021.74}, :next_weekly_tasks_number => 8, :ignore_apple_restriction => true) -Ordergroup.create!(:id => 6, :name => "Peter's huis", :account_balance => -0.35E2, :created_on => 'Sat, 25 Jan 2014 20:20:37 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :contact_person => "Piet Pieterssen", :stats => {:jobs_size=>0, :orders_sum=>60.96}, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) -Ordergroup.create!(:id => 7, :name => "Jan Klaassen", :account_balance => -0.35E2, :created_on => 'Mon, 27 Jan 2014 16:22:14 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :contact_person => "Jan Klaassen", :stats => {:jobs_size=>0, :orders_sum=>0}, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) -Ordergroup.create!(:id => 8, :name => "John Doe", :account_balance => 0.90E2, :created_on => 'Wed, 09 Apr 2014 12:23:29 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :contact_person => "John Doe", :stats => {:jobs_size=>0, :orders_sum=>0}, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) +Ordergroup.create!(:id => 5, :name => "Admin Administrator", :account_balance => 0.0, :created_on => 'Sat, 18 Jan 2014 00:38:48 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :stats => { :jobs_size => 0, :orders_sum => 1021.74 }, :next_weekly_tasks_number => 8, :ignore_apple_restriction => true) +Ordergroup.create!(:id => 6, :name => "Peter's huis", :account_balance => -0.35E2, :created_on => 'Sat, 25 Jan 2014 20:20:37 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :contact_person => "Piet Pieterssen", :stats => { :jobs_size => 0, :orders_sum => 60.96 }, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) +Ordergroup.create!(:id => 7, :name => "Jan Klaassen", :account_balance => -0.35E2, :created_on => 'Mon, 27 Jan 2014 16:22:14 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :contact_person => "Jan Klaassen", :stats => { :jobs_size => 0, :orders_sum => 0 }, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) +Ordergroup.create!(:id => 8, :name => "John Doe", :account_balance => 0.90E2, :created_on => 'Wed, 09 Apr 2014 12:23:29 UTC +00:00', :role_admin => false, :role_suppliers => false, :role_article_meta => false, :role_finance => false, :role_orders => false, :contact_person => "John Doe", :stats => { :jobs_size => 0, :orders_sum => 0 }, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) Membership.create!(:group_id => 1, :user_id => 1) Membership.create!(:group_id => 5, :user_id => 1) @@ -170,19 +169,16 @@ Membership.create!(:group_id => 7, :user_id => 5) Membership.create!(:group_id => 3, :user_id => 5) Membership.create!(:group_id => 4, :user_id => 5) - ## Orders & OrderArticles seed_order(supplier_id: 1, starts: 2.days.ago, ends: 5.days.from_now) seed_order(supplier_id: 3, starts: 2.days.ago, ends: 5.days.from_now) seed_order(supplier_id: 2, starts: 2.days.ago, ends: 4.days.from_now) - ## GroupOrders & such seed_group_orders - ## Finances FinancialTransactionType.create!(:id => 1, :name => "Foodcoop", :financial_transaction_class_id => 1) diff --git a/lib/api/errors.rb b/lib/api/errors.rb index ba1c5745..b4eb49c7 100644 --- a/lib/api/errors.rb +++ b/lib/api/errors.rb @@ -1,5 +1,6 @@ module Api::Errors class Error < StandardError; end + # Authentication is handled by Doorkeeper, so no errors for that here class PermissionRequired < Error; end end diff --git a/lib/apple_bar.rb b/lib/apple_bar.rb index 8249a296..a2176ea3 100644 --- a/lib/apple_bar.rb +++ b/lib/apple_bar.rb @@ -1,5 +1,4 @@ class AppleBar - attr_reader :ordergroup def initialize(ordergroup) @@ -17,7 +16,7 @@ class AppleBar 'success' else if FoodsoftConfig[:stop_ordering_under].present? and - apples >= FoodsoftConfig[:stop_ordering_under] + apples >= FoodsoftConfig[:stop_ordering_under] 'warning' else 'danger' @@ -31,7 +30,7 @@ class AppleBar end def mean_order_amount_per_job - (1/@global_avg).round rescue 0 + (1 / @global_avg).round rescue 0 end def apples @@ -41,4 +40,4 @@ class AppleBar def with_restriction? FoodsoftConfig[:stop_ordering_under].present? end -end \ No newline at end of file +end diff --git a/lib/bank_account_connector.rb b/lib/bank_account_connector.rb index 4f4ecf79..93e7cc7c 100644 --- a/lib/bank_account_connector.rb +++ b/lib/bank_account_connector.rb @@ -1,5 +1,4 @@ class BankAccountConnector - class TextItem def initialize(text) @text = text @@ -12,7 +11,6 @@ class BankAccountConnector def text @text end - end class TextField @@ -40,22 +38,17 @@ class BankAccountConnector end class PasswordField < TextField - def type :password end - end class HiddenField < TextField - def type :hidden end - end - @@registered_classes = Set.new def self.register(klass) @@ -111,7 +104,7 @@ class BankAccountConnector nil end - def text_field(name, value=nil) + def text_field(name, value = nil) @controls += [TextField.new(name, value, t(name))] end @@ -119,7 +112,7 @@ class BankAccountConnector @controls += [HiddenField.new(name, value, 'HIDDEN')] end - def password_field(name, value=nil) + def password_field(name, value = nil) @controls += [PasswordField.new(name, value, t(name))] end @@ -139,7 +132,7 @@ class BankAccountConnector @bank_account.import_continuation_point = data end - def update_or_create_transaction(external_id, data={}) + def update_or_create_transaction(external_id, data = {}) @bank_account.bank_transactions.where(external_id: external_id).first_or_create.update(data) @count += 1 end @@ -155,8 +148,9 @@ class BankAccountConnector def dump end - def t(key, args={}) + def t(key, args = {}) return t(".fields.#{key}") unless key.is_a? String + I18n.t 'bank_account_connector' + key, args end end diff --git a/lib/bank_account_connector_external.rb b/lib/bank_account_connector_external.rb index 9d11d5cc..7c391826 100644 --- a/lib/bank_account_connector_external.rb +++ b/lib/bank_account_connector_external.rb @@ -1,5 +1,4 @@ class BankAccountConnectorExternal < BankAccountConnector - def load(data) @connector = create_connector @connector.load data @@ -23,9 +22,9 @@ class BankAccountConnectorExternal < BankAccountConnector def import(data) return false unless connector_login(data) + connector_import connector_logout true end - end diff --git a/lib/bank_account_information_importer.rb b/lib/bank_account_information_importer.rb index 1b24ce9d..517f91c2 100644 --- a/lib/bank_account_information_importer.rb +++ b/lib/bank_account_information_importer.rb @@ -1,14 +1,15 @@ class BankAccountInformationImporter - def initialize(bank_account) @bank_account = bank_account end def import!(content) return nil if content.empty? + data = JSON.parse content, symbolize_names: true return 0 if data.empty? + booked = data.fetch(:transactions, {}).fetch(:booked, []) ret = 0 @@ -18,17 +19,17 @@ class BankAccountInformationImporter entityAccount = amount < 0 ? t[:creditorAccount] : t[:debtorAccount] @bank_account.bank_transactions.where(external_id: t[:transactionId]).first_or_create.update({ - date: t[:bookingDate], - amount: amount, - iban: entityAccount && entityAccount[:iban], - reference: t[:remittanceInformationUnstructured], - text: entityName, - receipt: t[:additionalInformation], - }) + date: t[:bookingDate], + amount: amount, + iban: entityAccount && entityAccount[:iban], + reference: t[:remittanceInformationUnstructured], + text: entityName, + receipt: t[:additionalInformation], + }) ret += 1 end - balances = Hash[ data[:balances] ? data[:balances].map { |b| [b[:balanceType], b[:balanceAmount]] } : [] ] + balances = Hash[data[:balances] ? data[:balances].map { |b| [b[:balanceType], b[:balanceAmount]] } : []] balance = balances.values.first %w(closingBooked expected authorised openingBooked interimAvailable forwardAvailable nonInvoiced).each do |type| value = balances[type] @@ -51,5 +52,4 @@ class BankAccountInformationImporter def parse_account_information_amount(value) value && value[:amount].to_f end - end diff --git a/lib/bank_transaction_reference.rb b/lib/bank_transaction_reference.rb index 2f677ea9..d033c544 100644 --- a/lib/bank_transaction_reference.rb +++ b/lib/bank_transaction_reference.rb @@ -1,5 +1,4 @@ class BankTransactionReference - # parses a string from a bank transaction field def self.parse(data) m = /(^|[^\w\.])FS(?\d+)(\.(?\d+))?(?([A-Za-z]+\d+(\.\d+)?)+)([^\w\.]|$)/.match(data) @@ -30,5 +29,4 @@ class BankTransactionReference } } end - end diff --git a/lib/date_time_attribute_validate.rb b/lib/date_time_attribute_validate.rb index 4a486195..08138d02 100644 --- a/lib/date_time_attribute_validate.rb +++ b/lib/date_time_attribute_validate.rb @@ -6,12 +6,10 @@ module DateTimeAttributeValidate include DateTimeAttribute module ClassMethods - def date_time_attribute(*attributes) super attributes.each do |attribute| - validate -> { self.send("#{attribute}_datetime_value_valid") } # allow resetting the field to nil @@ -39,10 +37,10 @@ module DateTimeAttributeValidate # fallback to field when values are not set define_method("#{attribute}_date_value") do - self.instance_variable_get("@#{attribute}_date_value") || self.send("#{attribute}_date").try {|e| e.strftime('%Y-%m-%d')} + self.instance_variable_get("@#{attribute}_date_value") || self.send("#{attribute}_date").try { |e| e.strftime('%Y-%m-%d') } end define_method("#{attribute}_time_value") do - self.instance_variable_get("@#{attribute}_time_value") || self.send("#{attribute}_time").try {|e| e.strftime('%H:%M')} + self.instance_variable_get("@#{attribute}_time_value") || self.send("#{attribute}_time").try { |e| e.strftime('%H:%M') } end private @@ -58,9 +56,7 @@ module DateTimeAttributeValidate errors.add(attribute, "is not a valid time") # @todo I18n end end - end end - end end diff --git a/lib/financial_transactions_csv.rb b/lib/financial_transactions_csv.rb index b5f934a3..dc21d892 100644 --- a/lib/financial_transactions_csv.rb +++ b/lib/financial_transactions_csv.rb @@ -19,15 +19,15 @@ class FinancialTransactionsCsv < RenderCSV def data @object.includes(:user, :ordergroup, :financial_transaction_type).each do |t| yield [ - t.created_on, - t.ordergroup_id, - t.ordergroup_name, - show_user(t.user), - t.financial_transaction_type.financial_transaction_class.name, - t.financial_transaction_type.name, - t.note, - number_to_currency(t.amount) - ] + t.created_on, + t.ordergroup_id, + t.ordergroup_name, + show_user(t.user), + t.financial_transaction_type.financial_transaction_class.name, + t.financial_transaction_type.name, + t.note, + number_to_currency(t.amount) + ] end end end diff --git a/lib/foodsoft/expansion_variables.rb b/lib/foodsoft/expansion_variables.rb index aba70013..bcf67e7a 100644 --- a/lib/foodsoft/expansion_variables.rb +++ b/lib/foodsoft/expansion_variables.rb @@ -8,7 +8,6 @@ module Foodsoft # Please be thoughful when choosing names as to avoid collisions. # Do not put non-public info in variables. module ExpansionVariables - ACTIVE_MONTHS = 3 # @return [Hash] Variables and their values @@ -16,31 +15,31 @@ module Foodsoft # Hash of variables. Note that keys are Strings. @@variables = { - 'scope' => ->{ FoodsoftConfig.scope }, - 'name' => ->{ FoodsoftConfig[:name] }, - 'contact.street' => ->{ FoodsoftConfig[:contact][:street] }, - 'contact.zip_code' => ->{ FoodsoftConfig[:contact][:zip_code] }, - 'contact.city' => ->{ FoodsoftConfig[:contact][:city] }, - 'contact.country' => ->{ FoodsoftConfig[:contact][:country] }, - 'contact.email' => ->{ FoodsoftConfig[:contact][:email] }, - 'contact.phone' => ->{ FoodsoftConfig[:contact][:phone] }, - 'price_markup' => ->{ FoodsoftConfig[:price_markup] }, - 'homepage' => ->{ FoodsoftConfig[:homepage] }, + 'scope' => -> { FoodsoftConfig.scope }, + 'name' => -> { FoodsoftConfig[:name] }, + 'contact.street' => -> { FoodsoftConfig[:contact][:street] }, + 'contact.zip_code' => -> { FoodsoftConfig[:contact][:zip_code] }, + 'contact.city' => -> { FoodsoftConfig[:contact][:city] }, + 'contact.country' => -> { FoodsoftConfig[:contact][:country] }, + 'contact.email' => -> { FoodsoftConfig[:contact][:email] }, + 'contact.phone' => -> { FoodsoftConfig[:contact][:phone] }, + 'price_markup' => -> { FoodsoftConfig[:price_markup] }, + 'homepage' => -> { FoodsoftConfig[:homepage] }, - 'help_url' => ->{ FoodsoftConfig[:help_url] }, - 'applepear_url' => ->{ FoodsoftConfig[:applepear_url] }, + 'help_url' => -> { FoodsoftConfig[:help_url] }, + 'applepear_url' => -> { FoodsoftConfig[:applepear_url] }, - 'foodsoft.url' => ->{ FoodsoftConfig[:foodsoft_url] }, - 'foodsoft.version' => Foodsoft::VERSION, - 'foodsoft.revision' => Foodsoft::REVISION, + 'foodsoft.url' => -> { FoodsoftConfig[:foodsoft_url] }, + 'foodsoft.version' => Foodsoft::VERSION, + 'foodsoft.revision' => Foodsoft::REVISION, - 'user_count' => ->{ User.undeleted.count }, - 'ordergroup_count' => ->{ Ordergroup.undeleted.count }, - 'active_ordergroup_count' => ->{ active_ordergroup_count }, - 'supplier_count' => ->{ Supplier.undeleted.count }, - 'active_supplier_count' => ->{ active_supplier_count }, - 'active_suppliers' => ->{ active_suppliers }, - 'first_order_date' => ->{ I18n.l Order.first.try{|o| o.starts.to_date} } + 'user_count' => -> { User.undeleted.count }, + 'ordergroup_count' => -> { Ordergroup.undeleted.count }, + 'active_ordergroup_count' => -> { active_ordergroup_count }, + 'supplier_count' => -> { Supplier.undeleted.count }, + 'active_supplier_count' => -> { active_supplier_count }, + 'active_suppliers' => -> { active_suppliers }, + 'first_order_date' => -> { I18n.l Order.first.try { |o| o.starts.to_date } } } # Return expanded variable @@ -60,7 +59,6 @@ module Foodsoft end end - # @return [Number] Number of ordergroups that have been active in the past 3 months def self.active_ordergroup_count GroupOrder @@ -78,10 +76,9 @@ module Foodsoft # @return [String] Comma-separated list of suppliers that has been ordered from in the past 3 months def self.active_suppliers Supplier.joins(:orders) - .where('orders.starts > ?', ACTIVE_MONTHS.months.ago) - .order(:name).select(:name).distinct - .map(&:name).join(', ') + .where('orders.starts > ?', ACTIVE_MONTHS.months.ago) + .order(:name).select(:name).distinct + .map(&:name).join(', ') end - end end diff --git a/lib/foodsoft_config.rb b/lib/foodsoft_config.rb index 6e8c3d45..052c1d68 100644 --- a/lib/foodsoft_config.rb +++ b/lib/foodsoft_config.rb @@ -1,5 +1,3 @@ -# encoding: utf-8 -# # Foodcoop-specific configuration. # # This is loaded from +config/app_config.yml+, which contains a root @@ -34,7 +32,6 @@ # then you can whitelist specific attributes setting them to +false+. # class FoodsoftConfig - # @!attribute scope # Returns the current foodcoop scope for the multicoops feature, otherwise # the value of the foodcoop configuration key +default_scope+ is used. @@ -61,7 +58,6 @@ class FoodsoftConfig end class << self - # Load and initialize foodcoop configuration file. # @param filename [String] Override configuration file def init(filename = APP_CONFIG_FILE) @@ -135,6 +131,7 @@ class FoodsoftConfig # @return [Boolean] Whether storing succeeded (fails when key is not allowed to be set in database). def []=(key, value) return false unless allowed_key?(key) + value = normalize_value value # then update database if config[key] == value || (config[key].nil? && value == false) @@ -147,13 +144,13 @@ class FoodsoftConfig # or store RailsSettings::CachedSettings["foodcoop.#{self.scope}.#{key}"] = value end - return true + true end # @return [Array] Configuration keys that are set (either in +app_config.yml+ or database). def keys keys = RailsSettings::CachedSettings.get_all("foodcoop.#{self.scope}.").try(:keys) || [] - keys.map! {|k| k.gsub /^foodcoop\.#{self.scope}\./, ''} + keys.map! { |k| k.gsub(/^foodcoop\.#{self.scope}\./, '') } keys += config.keys keys.map(&:to_s).uniq end @@ -183,22 +180,20 @@ class FoodsoftConfig def allowed_key?(key) # fast check for keys without nesting if self.config[:protected].include? key - return !self.config[:protected][key] + !self.config[:protected][key] else - return !self.config[:protected][:all] + !self.config[:protected][:all] end # @todo allow to check nested keys as well end # @return [Hash] Full configuration. def to_hash - Hash[keys.map {|k| [k, self[k]]} ] + keys.map { |k| [k, self[k]] }.to_h end # for using active_model_serializer in the api/v1/configs controller - alias :read_attribute_for_serialization :[] - - protected + alias read_attribute_for_serialization [] # @!attribute default_config # Returns the program-default foodcoop configuration. @@ -223,11 +218,11 @@ class FoodsoftConfig # @return [Hash] Default configuration values mattr_accessor :default_config - private def set_config(foodcoop) raise "No config for this environment (#{foodcoop}) available!" if APP_CONFIG[foodcoop].nil? + self.config = APP_CONFIG[foodcoop] self.scope = foodcoop set_missing @@ -288,20 +283,18 @@ class FoodsoftConfig # Normalize value recursively (which can be entered as strings, but we want to store it properly) def normalize_value(value) - value = value.map{|v| normalize_value(v)} if value.is_a? Array + value = value.map { |v| normalize_value(v) } if value.is_a? Array if value.is_a? Hash - value = ActiveSupport::HashWithIndifferentAccess[ value.to_a.map{|a| [a[0], normalize_value(a[1])]} ] + value = ActiveSupport::HashWithIndifferentAccess[value.to_a.map { |a| [a[0], normalize_value(a[1])] }] end case value - when 'true' then true - when 'false' then false - when /^[-+0-9]+$/ then value.to_i - when /^[-+0-9.]+([eE][-+0-9]+)?$/ then value.to_f - when '' then nil - else value + when 'true' then true + when 'false' then false + when /^[-+0-9]+$/ then value.to_i + when /^[-+0-9.]+([eE][-+0-9]+)?$/ then value.to_f + when '' then nil + else value end end - - end end diff --git a/lib/foodsoft_date_util.rb b/lib/foodsoft_date_util.rb index 7cb069d2..98dc1c61 100644 --- a/lib/foodsoft_date_util.rb +++ b/lib/foodsoft_date_util.rb @@ -1,6 +1,6 @@ module FoodsoftDateUtil # find next occurence given a recurring ical string and time - def self.next_occurrence(start=Time.now, from=start, options={}) + def self.next_occurrence(start = Time.now, from = start, options = {}) occ = nil if options && options[:recurr] schedule = IceCube::Schedule.new(start) @@ -25,5 +25,4 @@ module FoodsoftDateUtil p end end - end diff --git a/lib/foodsoft_file.rb b/lib/foodsoft_file.rb index 0977051c..95d06c60 100644 --- a/lib/foodsoft_file.rb +++ b/lib/foodsoft_file.rb @@ -1,6 +1,5 @@ # Foodsoft-file import class FoodsoftFile - # parses a string from a foodsoft-file # returns two arrays with articles and outlisted_articles # the parsed article is a simple hash @@ -8,7 +7,7 @@ class FoodsoftFile SpreadsheetFile.parse file, options do |row, row_index| next if row[2].blank? - article = {:order_number => row[1], + article = { :order_number => row[1], :name => row[2], :note => row[3], :manufacturer => row[4], @@ -18,10 +17,9 @@ class FoodsoftFile :tax => row[8], :deposit => (row[9].nil? ? "0" : row[9]), :unit_quantity => row[10], - :article_category => row[13]} + :article_category => row[13] } status = row[0] && row[0].strip.downcase == 'x' ? :outlisted : nil yield status, article, row_index end end - end diff --git a/lib/foodsoft_mail_receiver.rb b/lib/foodsoft_mail_receiver.rb index b0d85aff..560e7edd 100644 --- a/lib/foodsoft_mail_receiver.rb +++ b/lib/foodsoft_mail_receiver.rb @@ -2,7 +2,6 @@ require 'mail' require 'midi-smtp-server' class FoodsoftMailReceiver < MidiSmtpServer::Smtpd - @@registered_classes = Set.new def self.register(klass) @@ -46,6 +45,7 @@ class FoodsoftMailReceiver < MidiSmtpServer::Smtpd m = /(?[^@\.]+)\.(?
[^@]+)(@(?[^@]+))?/.match recipient raise "recipient is missing or has an invalid format" if m.nil? raise "Foodcoop '#{m[:foodcoop]}' could not be found" unless FoodsoftConfig.allowed_foodcoop? m[:foodcoop] + FoodsoftConfig.select_multifoodcoop m[:foodcoop] @@registered_classes.each do |klass| @@ -57,5 +57,4 @@ class FoodsoftMailReceiver < MidiSmtpServer::Smtpd raise "invalid format for recipient" end - end diff --git a/lib/order_csv.rb b/lib/order_csv.rb index 4fe92a25..6ec96581 100644 --- a/lib/order_csv.rb +++ b/lib/order_csv.rb @@ -1,7 +1,6 @@ require 'csv' class OrderCsv < RenderCSV - def header [ OrderArticle.human_attribute_name(:units_to_order), @@ -17,15 +16,14 @@ class OrderCsv < RenderCSV def data @object.order_articles.ordered.includes([:article, :article_price]).all.map do |oa| yield [ - oa.units_to_order, - oa.article.order_number, - oa.article.name, - oa.article.unit, - oa.price.unit_quantity > 1 ? oa.price.unit_quantity : nil, - number_to_currency(oa.price.price * oa.price.unit_quantity), - number_to_currency(oa.total_price) - ] + oa.units_to_order, + oa.article.order_number, + oa.article.name, + oa.article.unit, + oa.price.unit_quantity > 1 ? oa.price.unit_quantity : nil, + number_to_currency(oa.price.price * oa.price.unit_quantity), + number_to_currency(oa.total_price) + ] end end - end diff --git a/lib/order_pdf.rb b/lib/order_pdf.rb index c2dbae37..034ca51f 100644 --- a/lib/order_pdf.rb +++ b/lib/order_pdf.rb @@ -1,5 +1,4 @@ class OrderPdf < RenderPDF - attr_reader :order def initialize(order, options = {}) @@ -9,9 +8,9 @@ class OrderPdf < RenderPDF end def nice_table(name, data, dimrows = []) - name_options = {size: 10, style: :bold} + name_options = { size: 10, style: :bold } name_height = height_of name, name_options - made_table = make_table data, width: bounds.width, cell_style: {size: 8, overflow: :shrink_to_fit} do |table| + made_table = make_table data, width: bounds.width, cell_style: { size: 8, overflow: :shrink_to_fit } do |table| # borders table.cells.borders = [:bottom] table.cells.padding_top = 2 @@ -64,29 +63,29 @@ class OrderPdf < RenderPDF end def group_order_articles(ordergroup) - GroupOrderArticle. - includes(:group_order). - where(group_orders: {order_id: @orders, ordergroup_id: ordergroup}) + GroupOrderArticle + .includes(:group_order) + .where(group_orders: { order_id: @orders, ordergroup_id: ordergroup }) end def order_articles - OrderArticle. - ordered. - includes(article: :supplier). - includes(group_order_articles: {group_order: :ordergroup}). - where(order: @orders). - order('suppliers.name, articles.name, groups.name'). - preload(:article_price) + OrderArticle + .ordered + .includes(article: :supplier) + .includes(group_order_articles: { group_order: :ordergroup }) + .where(order: @orders) + .order('suppliers.name, articles.name, groups.name') + .preload(:article_price) end def ordergroups(offset = nil, limit = nil) - result = GroupOrder. - ordered. - where(order: @orders). - group('groups.id'). - offset(offset). - limit(limit). - pluck('groups.name', 'SUM(group_orders.price)', 'ordergroup_id', 'SUM(group_orders.transport)') + result = GroupOrder + .ordered + .where(order: @orders) + .group('groups.id') + .offset(offset) + .limit(limit) + .pluck('groups.name', 'SUM(group_orders.price)', 'ordergroup_id', 'SUM(group_orders.transport)') result.map do |item| [item.first || stock_ordergroup_name] + item[1..-1] @@ -113,8 +112,8 @@ class OrderPdf < RenderPDF # get quantity for each article and ordergroup goa_records = group_order_articles(group_ids) - .group('group_order_articles.order_article_id, group_orders.ordergroup_id') - .pluck('group_order_articles.order_article_id', 'group_orders.ordergroup_id', 'SUM(COALESCE(group_order_articles.result, group_order_articles.quantity))') + .group('group_order_articles.order_article_id, group_orders.ordergroup_id') + .pluck('group_order_articles.order_article_id', 'group_orders.ordergroup_id', 'SUM(COALESCE(group_order_articles.result, group_order_articles.quantity))') # transform the flat list of results in a hash (with the article as key), which contains an array for all ordergroups results = goa_records.group_by(&:first).transform_values do |value| @@ -135,20 +134,19 @@ class OrderPdf < RenderPDF def each_group_order_article_for_ordergroup(ordergroup, &block) group_order_articles(ordergroup) - .includes(order_article: {article: [:supplier]}) + .includes(order_article: { article: [:supplier] }) .order('suppliers.name, articles.name') .preload(order_article: [:article_price, :order]) .each(&block) end def stock_ordergroup_name - users = GroupOrder.stock. - eager_load(:updated_by). - where(order: @orders). - map(&:updated_by). - map{ |u| u.try(&:name) || '?' } + users = GroupOrder.stock + .eager_load(:updated_by) + .where(order: @orders) + .map(&:updated_by) + .map { |u| u.try(&:name) || '?' } I18n.t('model.group_order.stock_ordergroup_name', user: users.uniq.sort.join(', ')) end - end diff --git a/lib/order_txt.rb b/lib/order_txt.rb index f14035ad..acde6ac8 100644 --- a/lib/order_txt.rb +++ b/lib/order_txt.rb @@ -1,6 +1,5 @@ - class OrderTxt - def initialize(order, options={}) + def initialize(order, options = {}) @order = order end @@ -16,16 +15,16 @@ class OrderTxt text += "****** " + I18n.t('orders.fax.to_address') + "\n\n" text += "#{FoodsoftConfig[:name]}\n#{contact[:street]}\n#{contact[:zip_code]} #{contact[:city]}\n\n" text += "****** " + I18n.t('orders.fax.articles') + "\n\n" - text += "%8s %8s %s\n"%[I18n.t('orders.fax.number'), I18n.t('orders.fax.amount'), I18n.t('orders.fax.name')] + text += "%8s %8s %s\n" % [I18n.t('orders.fax.number'), I18n.t('orders.fax.amount'), I18n.t('orders.fax.name')] # now display all ordered articles @order.order_articles.ordered.includes([:article, :article_price]).each do |oa| - text += "%8s %8d %s\n"%[oa.article.order_number, oa.units_to_order.to_i, oa.article.name] + text += "%8s %8d %s\n" % [oa.article.order_number, oa.units_to_order.to_i, oa.article.name] end text end # Helper method to test pdf via rails console: OrderTxt.new(order).save_tmp def save_tmp - File.open("#{Rails.root}/tmp/#{self.class.to_s.underscore}.txt", 'w') {|f| f.write(to_csv.force_encoding("UTF-8")) } + File.open("#{Rails.root}/tmp/#{self.class.to_s.underscore}.txt", 'w') { |f| f.write(to_csv.force_encoding("UTF-8")) } end end diff --git a/lib/render_csv.rb b/lib/render_csv.rb index 8574e2f5..aad84251 100644 --- a/lib/render_csv.rb +++ b/lib/render_csv.rb @@ -3,7 +3,7 @@ require 'csv' class RenderCSV include ActionView::Helpers::NumberHelper - def initialize(object, options={}) + def initialize(object, options = {}) @object = object @options = options # defaults to please Microsoft Excel ... @@ -13,12 +13,12 @@ class RenderCSV end def to_csv - options = @options.select {|k| %w(col_sep row_sep).include? k.to_s} + options = @options.select { |k| %w(col_sep row_sep).include? k.to_s } ret = CSV.generate options do |csv| if h = header csv << h end - data {|d| csv << d} + data { |d| csv << d } end ret.encode(@options[:encoding], invalid: :replace, undef: :replace) end @@ -34,11 +34,11 @@ class RenderCSV # Helper method to test pdf via rails console: OrderCsv.new(order).save_tmp def save_tmp encoding = @options[:encoding] || 'UTF-8' - File.open("#{Rails.root}/tmp/#{self.class.to_s.underscore}.csv", 'w') {|f| f.write(to_csv.force_encoding(encoding)) } + File.open("#{Rails.root}/tmp/#{self.class.to_s.underscore}.csv", 'w') { |f| f.write(to_csv.force_encoding(encoding)) } end # XXX disable unit to avoid encoding problems, both in unit and whitespace. Also allows computations in spreadsheet. - def number_to_currency(number, options={}) - super(number, options.merge({unit: ''})) + def number_to_currency(number, options = {}) + super(number, options.merge({ unit: '' })) end end diff --git a/lib/render_pdf.rb b/lib/render_pdf.rb index 1adf3b15..b79e2a55 100644 --- a/lib/render_pdf.rb +++ b/lib/render_pdf.rb @@ -1,8 +1,7 @@ require 'prawn/measurement_extensions' class RotatedCell < Prawn::Table::Cell::Text - - def initialize(pdf, text, options={}) + def initialize(pdf, text, options = {}) options[:content] = text options[:valign] = :center options[:align] = :center @@ -32,8 +31,8 @@ class RotatedCell < Prawn::Table::Cell::Text def draw_borders(pt) @pdf.mask(:line_width, :stroke_color) do x, y = pt - from = [[x - skew , y + (border_top_width / 2.0)], - to = [x, y - height - (border_bottom_width / 2.0)]] + from = [[x - skew, y + (border_top_width / 2.0)], + to = [x, y - height - (border_bottom_width / 2.0)]] @pdf.line_width = @border_widths[3] @pdf.stroke_color = @border_colors[3] @@ -47,11 +46,10 @@ class RotatedCell < Prawn::Table::Cell::Text with_text_color do text_box(width: spanned_content_width + FPTolerance + skew, height: spanned_content_height + FPTolerance, - at: [1-skew, @pdf.cursor]).render + at: [1 - skew, @pdf.cursor]).render end end end - end class RenderPDF < Prawn::Document @@ -116,17 +114,17 @@ class RenderPDF < Prawn::Document end def to_pdf - body # Add content, which is defined in subclasses - render # Render pdf + body # Add content, which is defined in subclasses + render # Render pdf end # Helper method to test pdf via rails console: OrderByGroups.new(order).save_tmp def save_tmp - File.open("#{Rails.root}/tmp/#{self.class.to_s.underscore}.pdf", 'w') {|f| f.write(to_pdf.force_encoding("UTF-8")) } + File.open("#{Rails.root}/tmp/#{self.class.to_s.underscore}.pdf", 'w') { |f| f.write(to_pdf.force_encoding("UTF-8")) } end # @todo avoid underscore instead of unicode whitespace in pdf :/ - def number_to_currency(number, options={}) + def number_to_currency(number, options = {}) super(number, options).gsub("\u202f", ' ') if number end @@ -136,7 +134,7 @@ class RenderPDF < Prawn::Document end # add pagebreak or vertical whitespace, depending on configuration - def down_or_page(space=10) + def down_or_page(space = 10) if @first_page @first_page = false return @@ -155,7 +153,7 @@ class RenderPDF < Prawn::Document end # return whether pagebreak or vertical whitespace is used for breaks - def pdf_add_page_breaks?(docid=nil) + def pdf_add_page_breaks?(docid = nil) docid ||= self.class.name.underscore cfg = FoodsoftConfig[:pdf_add_page_breaks] if cfg.is_a? Array diff --git a/lib/spreadsheet_file.rb b/lib/spreadsheet_file.rb index 88936032..dbca9c90 100644 --- a/lib/spreadsheet_file.rb +++ b/lib/spreadsheet_file.rb @@ -1,13 +1,12 @@ require 'roo' class SpreadsheetFile - def self.parse(file, options = {}) filepath = file.is_a?(String) ? file : file.to_path filename = options.delete(:filename) || filepath fileext = File.extname(filename) - options[:csv_options] = {col_sep: ';', encoding: 'utf-8'}.merge(options[:csv_options]||{}) - s = Roo::Spreadsheet.open(filepath, options.merge({extension: fileext})) + options[:csv_options] = { col_sep: ';', encoding: 'utf-8' }.merge(options[:csv_options] || {}) + s = Roo::Spreadsheet.open(filepath, options.merge({ extension: fileext })) row_index = 1 s.each do |row| @@ -20,5 +19,4 @@ class SpreadsheetFile end row_index end - end diff --git a/lib/tasks/foodsoft.rake b/lib/tasks/foodsoft.rake index 42e92873..26ef5230 100644 --- a/lib/tasks/foodsoft.rake +++ b/lib/tasks/foodsoft.rake @@ -69,9 +69,11 @@ namespace :foodsoft do BankAccount.find_each do |ba| importer = ba.find_connector next unless importer + importer.load nil ok = importer.import nil next unless ok + importer.finish assign_count = ba.assign_unlinked_transactions rake_say "#{ba.name}: imported #{importer.count}, assigned #{assign_count}" diff --git a/lib/tasks/foodsoft_setup.rake b/lib/tasks/foodsoft_setup.rake index 123cd6c4..0338cc43 100644 --- a/lib/tasks/foodsoft_setup.rake +++ b/lib/tasks/foodsoft_setup.rake @@ -7,16 +7,16 @@ module Colors def colorize(text, color_code) "\033[#{color_code}m#{text}\033[0m" end - + { - :black => 30, - :red => 31, - :green => 32, - :yellow => 33, - :blue => 34, - :magenta => 35, - :cyan => 36, - :white => 37 + :black => 30, + :red => 31, + :green => 32, + :yellow => 33, + :blue => 34, + :magenta => 35, + :cyan => 36, + :white => 37 }.each do |key, color_code| define_method key do |text| colorize(text, color_code) @@ -49,9 +49,9 @@ end def setup_bundler puts yellow "Installing bundler if not installed..." - %x( if [ -z `which bundle` ]; then gem install bundler --no-rdoc --no-ri; fi ) + %x(if [ -z `which bundle` ]; then gem install bundler --no-rdoc --no-ri; fi) puts yellow "Executing bundle install..." - %x( bundle install ) + %x(bundle install) end def setup_database @@ -61,18 +61,18 @@ def setup_database return nil end return nil if skip?(file) - - database = ask("What kind of database do you use?\nOptions:\n(1) MySQL\n(2) SQLite", ["1","2"]) + + database = ask("What kind of database do you use?\nOptions:\n(1) MySQL\n(2) SQLite", ["1", "2"]) if database == "1" puts yellow "Using MySQL..." - %x( cp #{Rails.root.join("#{file}.MySQL_SAMPLE")} #{Rails.root.join(file)} ) + %x(cp #{Rails.root.join("#{file}.MySQL_SAMPLE")} #{Rails.root.join(file)}) elsif database == "2" puts yellow "Using SQLite..." - %x( cp #{Rails.root.join("#{file}.SQLite_SAMPLE")} #{Rails.root.join(file)} ) + %x(cp #{Rails.root.join("#{file}.SQLite_SAMPLE")} #{Rails.root.join(file)}) end - + reminder(file) - + puts blue "IMPORTANT: Edit (rake-generated) config/database.yml with valid username and password for EACH env before continuing!" finished = ask("Finished?\nOptions:\n(y) Yes", ["y"]) if finished @@ -86,27 +86,28 @@ def setup_app_config file = 'config/app_config.yml' sample = Rails.root.join("#{file}.SAMPLE") return nil if skip?(file) - + puts yellow "Copying #{file}..." - %x( cp #{sample} #{Rails.root.join(file)} ) + %x(cp #{sample} #{Rails.root.join(file)}) reminder(file) end def setup_development file = 'config/environments/development.rb' return nil if skip?(file) - + puts yellow "Copying #{file}..." - %x( cp #{Rails.root.join("#{file}.SAMPLE")} #{Rails.root.join(file)} ) + %x(cp #{Rails.root.join("#{file}.SAMPLE")} #{Rails.root.join(file)}) reminder(file) end def start_mailcatcher return nil if ENV['MAILCATCHER_PORT'] # skip when it has an existing Docker container - mailcatcher = ask("Do you want to start mailcatcher?\nOptions:\n(y) Yes\n(n) No", ["y","n"]) + + mailcatcher = ask("Do you want to start mailcatcher?\nOptions:\n(y) Yes\n(n) No", ["y", "n"]) if mailcatcher === "y" puts yellow "Starting mailcatcher at http://localhost:1080..." - %x( mailcatcher ) + %x(mailcatcher) end end @@ -128,7 +129,7 @@ end def skip?(file) output = false - skip = ask(cyan("We found #{file}!\nOptions:\n(1) Skip step\n(2) Force rewrite"), ["1","2"]) if File.exists?(Rails.root.join(file)) + skip = ask(cyan("We found #{file}!\nOptions:\n(1) Skip step\n(2) Force rewrite"), ["1", "2"]) if File.exists?(Rails.root.join(file)) output = true if skip == "1" output end @@ -145,4 +146,3 @@ def capture_stdout ensure $stdout = STDOUT end - diff --git a/lib/tasks/multicoops.rake b/lib/tasks/multicoops.rake index bdd1ae9b..cb2f280a 100644 --- a/lib/tasks/multicoops.rake +++ b/lib/tasks/multicoops.rake @@ -3,7 +3,6 @@ # for each foodcoop is used. namespace :multicoops do - desc 'Runs a specific rake task for each registered foodcoop, use rake multicoops:run TASK=db:migrate' task :run => :environment do task_to_run = ENV['TASK'] @@ -14,7 +13,7 @@ namespace :multicoops do Rake::Task[task_to_run].execute rescue => error last_error = error - ExceptionNotifier.notify_exception(error, data: {foodcoop: coop}) + ExceptionNotifier.notify_exception(error, data: { foodcoop: coop }) end end raise last_error if last_error @@ -27,11 +26,9 @@ namespace :multicoops do rake_say "Run '#{task_to_run}' for #{ENV['FOODCOOP']}" Rake::Task[task_to_run].execute end - end - # Helper def rake_say(message) - puts message unless Rake.application.options.silent + puts message unless Rake.application.options.silent end diff --git a/lib/tasks/resque.rake b/lib/tasks/resque.rake index f90a6f63..2c50bf69 100644 --- a/lib/tasks/resque.rake +++ b/lib/tasks/resque.rake @@ -2,9 +2,9 @@ require "resque/tasks" def run_worker(queue, count = 1) puts "Starting #{count} worker(s) with QUEUE: #{queue}" - ops = {:pgroup => true, :err => ["log/resque_worker_foodsoft_notifier.log", "a"], - :out => ["log/resque_worker_foodsoft_notifier.log", "a"]} - env_vars = {"QUEUE" => queue.to_s, "PIDFILE" => "tmp/pids/resque_worker_foodsoft_notifier.pid"} + ops = { :pgroup => true, :err => ["log/resque_worker_foodsoft_notifier.log", "a"], + :out => ["log/resque_worker_foodsoft_notifier.log", "a"] } + env_vars = { "QUEUE" => queue.to_s, "PIDFILE" => "tmp/pids/resque_worker_foodsoft_notifier.pid" } count.times { ## Using Kernel.spawn and Process.detach because regular system() call would ## cause the processes to quit when capistrano finishes @@ -21,7 +21,7 @@ namespace :resque do Rake::Task['resque:stop_workers'].invoke Rake::Task['resque:start_workers'].invoke end - + desc "Quit running workers" task :stop_workers do pids = File.read('tmp/pids/resque_worker_foodsoft_notifier.pid').split("\n") @@ -33,9 +33,9 @@ namespace :resque do system(syscmd) end end - + desc "Start workers" task :start_workers do - run_worker("foodsoft_notifier") + run_worker("foodsoft_notifier") end end diff --git a/lib/tasks/rspec.rake b/lib/tasks/rspec.rake index 4ebbe191..4f0c4081 100644 --- a/lib/tasks/rspec.rake +++ b/lib/tasks/rspec.rake @@ -6,8 +6,8 @@ begin # Use `rspec` to run a single test. When a test fails in rake but not # with rspec, you can use the following to run a single test using rake: - #RSpec::Core::RakeTask.new('spec:foo') do |t| - # t.pattern = "spec/integration/foo_spec.rb" - #end + # RSpec::Core::RakeTask.new('spec:foo') do |t| + # t.pattern = "spec/integration/foo_spec.rb" + # end rescue LoadError end diff --git a/lib/token_verifier.rb b/lib/token_verifier.rb index 0e973a42..a8a0f1eb 100644 --- a/lib/token_verifier.rb +++ b/lib/token_verifier.rb @@ -1,13 +1,12 @@ # Generic token verifier with foodcoop scope # @todo use +Rails.application.message_verifier+ when possible class TokenVerifier < ActiveSupport::MessageVerifier - def initialize(prefix) super(self.class.secret) @_prefix = prefix.is_a?(Array) ? prefix.join(':') : prefix.to_s end - def generate(message=nil) + def generate(message = nil) fullmessage = [FoodsoftConfig.scope, @_prefix] fullmessage.append(message) unless message.nil? super(fullmessage) @@ -18,6 +17,7 @@ class TokenVerifier < ActiveSupport::MessageVerifier raise InvalidMessage unless r.is_a?(Array) && r.length >= 2 && r.length <= 3 raise InvalidScope unless r[0] == FoodsoftConfig.scope raise InvalidPrefix unless r[1] == @_prefix + # return original message if r.length > 2 r[2] @@ -27,7 +27,9 @@ class TokenVerifier < ActiveSupport::MessageVerifier end class InvalidMessage < ActiveSupport::MessageVerifier::InvalidSignature; end + class InvalidScope < ActiveSupport::MessageVerifier::InvalidSignature; end + class InvalidPrefix < ActiveSupport::MessageVerifier::InvalidSignature; end protected @@ -36,5 +38,4 @@ class TokenVerifier < ActiveSupport::MessageVerifier # secret_key_base for Rails 4, but Rails 3 initializer may still be used Foodsoft::Application.config.secret_key_base || Foodsoft::Application.config.secret_token end - end diff --git a/plugins/current_orders/app/controllers/current_orders/articles_controller.rb b/plugins/current_orders/app/controllers/current_orders/articles_controller.rb index 4f33f98e..0e4b7dd9 100644 --- a/plugins/current_orders/app/controllers/current_orders/articles_controller.rb +++ b/plugins/current_orders/app/controllers/current_orders/articles_controller.rb @@ -1,6 +1,4 @@ -# encoding: utf-8 class CurrentOrders::ArticlesController < ApplicationController - before_action :authenticate_orders before_action :find_order_and_order_article, only: [:index, :show] @@ -21,7 +19,7 @@ class CurrentOrders::ArticlesController < ApplicationController end def show_on_group_order_article_update - #@goa = GroupOrderArticle.find(params[:group_order_article_id]) + # @goa = GroupOrderArticle.find(params[:group_order_article_id]) end protected @@ -40,7 +38,7 @@ class CurrentOrders::ArticlesController < ApplicationController end helper_method \ - def ordergroups_for_adding + def ordergroups_for_adding Ordergroup.undeleted.order(:name) end end diff --git a/plugins/current_orders/app/controllers/current_orders/group_orders_controller.rb b/plugins/current_orders/app/controllers/current_orders/group_orders_controller.rb index 3ab4fbda..717ebba8 100644 --- a/plugins/current_orders/app/controllers/current_orders/group_orders_controller.rb +++ b/plugins/current_orders/app/controllers/current_orders/group_orders_controller.rb @@ -5,12 +5,12 @@ class CurrentOrders::GroupOrdersController < ApplicationController def index # XXX code duplication lib/foodsoft_current_orders/app/controllers/current_orders/ordergroups_controller.rb @order_ids = Order.where(state: ['open', 'finished']).all.map(&:id) - @goas = GroupOrderArticle.includes(:group_order => :ordergroup).includes(:order_article). - where(group_orders: {order_id: @order_ids, ordergroup_id: @ordergroup.id}).ordered - @articles_grouped_by_category = @goas.includes(:order_article => {:article => :article_category}). - order('articles.name'). - group_by { |a| a.order_article.article.article_category.name }. - sort { |a, b| a[0] <=> b[0] } + @goas = GroupOrderArticle.includes(:group_order => :ordergroup).includes(:order_article) + .where(group_orders: { order_id: @order_ids, ordergroup_id: @ordergroup.id }).ordered + @articles_grouped_by_category = @goas.includes(:order_article => { :article => :article_category }) + .order('articles.name') + .group_by { |a| a.order_article.article.article_category.name } + .sort { |a, b| a[0] <=> b[0] } end private @@ -22,5 +22,4 @@ class CurrentOrders::GroupOrdersController < ApplicationController redirect_to root_url, :alert => I18n.t('group_orders.errors.no_member') end end - end diff --git a/plugins/current_orders/app/controllers/current_orders/ordergroups_controller.rb b/plugins/current_orders/app/controllers/current_orders/ordergroups_controller.rb index 339209ab..708016a9 100644 --- a/plugins/current_orders/app/controllers/current_orders/ordergroups_controller.rb +++ b/plugins/current_orders/app/controllers/current_orders/ordergroups_controller.rb @@ -1,6 +1,4 @@ -# encoding: utf-8 class CurrentOrders::OrdergroupsController < ApplicationController - before_action :authenticate_orders before_action :find_group_orders, only: [:index, :show] @@ -21,7 +19,7 @@ class CurrentOrders::OrdergroupsController < ApplicationController end def show_on_group_order_article_update - #@goa = GroupOrderArticle.find(params[:group_order_article_id]) + # @goa = GroupOrderArticle.find(params[:group_order_article_id]) @group_order = GroupOrder.find(params[:group_order_id]) @ordergroup = @group_order.ordergroup end @@ -33,15 +31,15 @@ class CurrentOrders::OrdergroupsController < ApplicationController @all_ordergroups = Ordergroup.undeleted.order(:name).to_a @ordered_group_ids = GroupOrder.where(order_id: @order_ids).pluck('DISTINCT(ordergroup_id)') - @all_ordergroups.sort_by! {|o| @ordered_group_ids.include?(o.id) ? o.name : "ZZZZZ#{o.name}" } + @all_ordergroups.sort_by! { |o| @ordered_group_ids.include?(o.id) ? o.name : "ZZZZZ#{o.name}" } @ordergroup = Ordergroup.find(params[:id]) unless params[:id].nil? - @goas = GroupOrderArticle.includes(:group_order, :order_article => [:article, :article_price]). - where(group_orders: {order_id: @order_ids, ordergroup_id: @ordergroup.id}).ordered.all unless @ordergroup.nil? + @goas = GroupOrderArticle.includes(:group_order, :order_article => [:article, :article_price]) + .where(group_orders: { order_id: @order_ids, ordergroup_id: @ordergroup.id }).ordered.all unless @ordergroup.nil? end helper_method \ - def articles_for_adding + def articles_for_adding OrderArticle.includes(:article, :article_price).where(order_id: @order_ids) end end diff --git a/plugins/current_orders/app/controllers/current_orders/orders_controller.rb b/plugins/current_orders/app/controllers/current_orders/orders_controller.rb index a84570f2..7731ae00 100644 --- a/plugins/current_orders/app/controllers/current_orders/orders_controller.rb +++ b/plugins/current_orders/app/controllers/current_orders/orders_controller.rb @@ -1,5 +1,4 @@ class CurrentOrders::OrdersController < ApplicationController - before_action :authenticate_orders, except: :my def show @@ -14,8 +13,8 @@ class CurrentOrders::OrdersController < ApplicationController respond_to do |format| format.pdf do pdf = case params[:document] - when 'groups' then MultipleOrdersByGroups.new(@order_ids, @doc_options) - when 'articles' then MultipleOrdersByArticles.new(@order_ids, @doc_options) + when 'groups' then MultipleOrdersByGroups.new(@order_ids, @doc_options) + when 'articles' then MultipleOrdersByArticles.new(@order_ids, @doc_options) end send_data pdf.to_pdf, filename: pdf.filename, type: 'application/pdf' end @@ -36,5 +35,4 @@ class CurrentOrders::OrdersController < ApplicationController def receive @orders = Order.finished_not_closed.includes(:supplier) end - end diff --git a/plugins/current_orders/app/controllers/current_orders_controller.rb b/plugins/current_orders/app/controllers/current_orders_controller.rb index c2488ad1..27bd2b1b 100644 --- a/plugins/current_orders/app/controllers/current_orders_controller.rb +++ b/plugins/current_orders/app/controllers/current_orders_controller.rb @@ -1,6 +1,3 @@ -# encoding: utf-8 class CurrentOrdersController < ApplicationController - before_action :authenticate_orders - end diff --git a/plugins/current_orders/app/documents/multiple_orders_by_articles.rb b/plugins/current_orders/app/documents/multiple_orders_by_articles.rb index 0e18d073..48d8a058 100644 --- a/plugins/current_orders/app/documents/multiple_orders_by_articles.rb +++ b/plugins/current_orders/app/documents/multiple_orders_by_articles.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 class MultipleOrdersByArticles < OrderPdf include OrdersHelper @@ -32,28 +31,29 @@ class MultipleOrdersByArticles < OrderPdf dimrows << rows.length if goa.result == 0 end next if rows.length == 0 + sum = order_article.group_orders_sum rows.unshift I18n.t('documents.order_by_articles.rows').dup # table header rows << [I18n.t('documents.order_by_groups.sum'), order_article.tolerance > 0 ? "#{order_article.quantity} + #{order_article.tolerance}" : order_article.quantity, sum[:quantity], - nil] #number_to_currency(sum[:price])] + nil] # number_to_currency(sum[:price])] text "#{order_article.article.name} " + "(#{order_article.article.unit}; #{number_to_currency order_article.price.fc_price}; " + units_history_line(order_article, plain: true) + ')', size: fontsize(10), inline_format: true - table rows, cell_style: {size: fontsize(8), overflow: :shrink_to_fit} do |table| + table rows, cell_style: { size: fontsize(8), overflow: :shrink_to_fit } do |table| # borders table.cells.borders = [:bottom] table.cells.border_width = 0.02 table.cells.border_color = 'dddddd' table.rows(0).border_width = 1 table.rows(0).border_color = '666666' - table.row(rows.length-2).border_width = 1 - table.row(rows.length-2).border_color = '666666' - table.row(rows.length-1).borders = [] + table.row(rows.length - 2).border_width = 1 + table.row(rows.length - 2).border_color = '666666' + table.row(rows.length - 1).borders = [] table.column(0).width = 200 table.columns(1..2).align = :center @@ -73,25 +73,24 @@ class MultipleOrdersByArticles < OrderPdf end def order_articles - OrderArticle.where(order_id: order).ordered. - includes(:article).references(:article). - reorder('order_articles.order_id, articles.name'). - preload(:article_price). # preload not join, just in case it went missing - preload(:order, :group_order_articles => {:group_order => :ordergroup}) + OrderArticle.where(order_id: order).ordered + .includes(:article).references(:article) + .reorder('order_articles.order_id, articles.name') + .preload(:article_price) # preload not join, just in case it went missing + .preload(:order, :group_order_articles => { :group_order => :ordergroup }) end def each_order_article - order_articles.find_each_with_order(batch_size: BATCH_SIZE) {|oa| yield oa } + order_articles.find_each_with_order(batch_size: BATCH_SIZE) { |oa| yield oa } end def group_order_articles_for(order_article) goas = order_article.group_order_articles.to_a - goas.sort_by! {|goa| goa.group_order.ordergroup_name } + goas.sort_by! { |goa| goa.group_order.ordergroup_name } goas end def each_group_order_article_for(group_order) - group_order_articles_for(group_order).each {|goa| yield goa } + group_order_articles_for(group_order).each { |goa| yield goa } end - end diff --git a/plugins/current_orders/app/documents/multiple_orders_by_groups.rb b/plugins/current_orders/app/documents/multiple_orders_by_groups.rb index adb4c184..0c9eefa9 100644 --- a/plugins/current_orders/app/documents/multiple_orders_by_groups.rb +++ b/plugins/current_orders/app/documents/multiple_orders_by_groups.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 class MultipleOrdersByGroups < OrderPdf include OrdersHelper @@ -23,12 +22,12 @@ class MultipleOrdersByGroups < OrderPdf down_or_page 15 total = 0 - taxes = Hash.new {0} + taxes = Hash.new { 0 } rows = [] dimrows = [] has_tolerance = false - each_group_order_article_for(ordergroup) do |goa| + each_group_order_article_for(ordergroup) do |goa| has_tolerance = true if goa.order_article.price.unit_quantity > 1 price = goa.order_article.price.fc_price sub_total = goa.total_price @@ -46,7 +45,7 @@ class MultipleOrdersByGroups < OrderPdf next if rows.length == 0 # total - rows << [{content: I18n.t('documents.order_by_groups.sum'), colspan: 6}, number_to_currency(total), nil] + rows << [{ content: I18n.t('documents.order_by_groups.sum'), colspan: 6 }, number_to_currency(total), nil] # table header rows.unshift [ @@ -57,14 +56,14 @@ class MultipleOrdersByGroups < OrderPdf I18n.t('shared.articles.ordered'), I18n.t('shared.articles.received'), I18n.t('shared.articles_by.price_sum'), - {image: "#{Rails.root}/app/assets/images/package-bg.png", scale: 0.6, position: :center} + { image: "#{Rails.root}/app/assets/images/package-bg.png", scale: 0.6, position: :center } ] # last column showing unit_quantity is useless if they're all one - rows.each {|row| row[-1] = nil} unless has_tolerance + rows.each { |row| row[-1] = nil } unless has_tolerance text ordergroup.name, size: fontsize(13), style: :bold - table rows, width: bounds.width, cell_style: {size: fontsize(8), overflow: :shrink_to_fit} do |table| + table rows, width: bounds.width, cell_style: { size: fontsize(8), overflow: :shrink_to_fit } do |table| # borders table.cells.borders = [:bottom] table.cells.border_width = 0.02 @@ -72,9 +71,9 @@ class MultipleOrdersByGroups < OrderPdf table.rows(0).border_width = 1 table.rows(0).border_color = '666666' table.rows(0).column(5).font_style = :bold - table.row(rows.length-2).border_width = 1 - table.row(rows.length-2).border_color = '666666' - table.row(rows.length-1).borders = [] + table.row(rows.length - 2).border_width = 1 + table.row(rows.length - 2).border_color = '666666' + table.row(rows.length - 1).borders = [] table.column(0).width = 180 # @todo would like to set minimum width here table.column(1).width = 62 @@ -105,34 +104,33 @@ class MultipleOrdersByGroups < OrderPdf end def ordergroups - s = Ordergroup. - includes(:group_orders). - where(group_orders: {order_id: order}). - group(:id). - reorder(:name) + s = Ordergroup + .includes(:group_orders) + .where(group_orders: { order_id: order }) + .group(:id) + .reorder(:name) s = s.where(id: @options[:ordergroup]) if @options[:ordergroup] s end def each_ordergroup ordergroups.find_in_batches_with_order(batch_size: BATCH_SIZE) do |ordergroups| - @group_order_article_batch = GroupOrderArticle. - joins(:group_order). - where(group_orders: {order_id: order}). - where(group_orders: {ordergroup_id: ordergroups.map(&:id)}). - order('group_orders.order_id, group_order_articles.id'). - preload(group_orders: {order: :supplier}). - preload(order_article: [:article, :article_price, :order]) - ordergroups.each {|ordergroup| yield ordergroup } + @group_order_article_batch = GroupOrderArticle + .joins(:group_order) + .where(group_orders: { order_id: order }) + .where(group_orders: { ordergroup_id: ordergroups.map(&:id) }) + .order('group_orders.order_id, group_order_articles.id') + .preload(group_orders: { order: :supplier }) + .preload(order_article: [:article, :article_price, :order]) + ordergroups.each { |ordergroup| yield ordergroup } end end def group_order_articles_for(ordergroup) - @group_order_article_batch.select {|goa| goa.group_order.ordergroup_id == ordergroup.id } + @group_order_article_batch.select { |goa| goa.group_order.ordergroup_id == ordergroup.id } end def each_group_order_article_for(ordergroup) - group_order_articles_for(ordergroup).each {|goa| yield goa } + group_order_articles_for(ordergroup).each { |goa| yield goa } end - end diff --git a/plugins/current_orders/app/helpers/current_orders_helper.rb b/plugins/current_orders/app/helpers/current_orders_helper.rb index 53d0f699..3bbab482 100644 --- a/plugins/current_orders/app/helpers/current_orders_helper.rb +++ b/plugins/current_orders/app/helpers/current_orders_helper.rb @@ -1,5 +1,4 @@ module CurrentOrdersHelper - def to_pay_message(ordergroup) funds = ordergroup.get_available_funds if funds > 0 @@ -10,5 +9,4 @@ module CurrentOrdersHelper content_tag :b, I18n.t('helpers.current_orders.pay_amount', amount: number_to_currency(-ordergroup.get_available_funds)) end end - end diff --git a/plugins/current_orders/lib/foodsoft_current_orders/engine.rb b/plugins/current_orders/lib/foodsoft_current_orders/engine.rb index a29893a3..07427b56 100644 --- a/plugins/current_orders/lib/foodsoft_current_orders/engine.rb +++ b/plugins/current_orders/lib/foodsoft_current_orders/engine.rb @@ -3,13 +3,14 @@ module FoodsoftCurrentOrders def navigation(primary, context) return unless FoodsoftCurrentOrders.enabled? return if primary[:orders].nil? + cond = Proc.new { current_user.role_orders? } [ SimpleNavigation::Item.new(primary, :stage_divider, nil, nil, class: 'divider', if: cond), SimpleNavigation::Item.new(primary, :current_orders_receive, I18n.t('current_orders.navigation.receive'), context.receive_current_orders_orders_path, if: cond), SimpleNavigation::Item.new(primary, :current_orders_articles, I18n.t('current_orders.navigation.articles'), context.current_orders_articles_path, if: cond), SimpleNavigation::Item.new(primary, :current_orders_ordergroups, I18n.t('current_orders.navigation.ordergroups'), context.current_orders_ordergroups_path, if: cond) - ].each {|i| primary[:orders].sub_navigation.items << i } + ].each { |i| primary[:orders].sub_navigation.items << i } end end end diff --git a/plugins/discourse/Rakefile b/plugins/discourse/Rakefile index 7b1c2793..cb56e2e5 100644 --- a/plugins/discourse/Rakefile +++ b/plugins/discourse/Rakefile @@ -23,8 +23,6 @@ end APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) load 'rails/tasks/engine.rake' - - Bundler::GemHelper.install_tasks require 'rake/testtask' @@ -36,5 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end - task :default => :test diff --git a/plugins/discourse/app/controllers/discourse_controller.rb b/plugins/discourse/app/controllers/discourse_controller.rb index 7ad2904a..5a65f61c 100644 --- a/plugins/discourse/app/controllers/discourse_controller.rb +++ b/plugins/discourse/app/controllers/discourse_controller.rb @@ -1,11 +1,11 @@ class DiscourseController < ApplicationController - before_action -> { require_plugin_enabled FoodsoftDiscourse } protected def valid_signature? return false if params[:sso].blank? || params[:sig].blank? + get_hmac_hex_string(params[:sso]) == params[:sig] end diff --git a/plugins/discourse/app/controllers/discourse_login_controller.rb b/plugins/discourse/app/controllers/discourse_login_controller.rb index c5dfb5e7..1c8fe938 100644 --- a/plugins/discourse/app/controllers/discourse_login_controller.rb +++ b/plugins/discourse/app/controllers/discourse_login_controller.rb @@ -1,5 +1,4 @@ class DiscourseLoginController < DiscourseController - before_action -> { require_config_disabled :discourse_sso } skip_before_action :authenticate @@ -11,8 +10,8 @@ class DiscourseLoginController < DiscourseController session[:discourse_sso_nonce] = nonce redirect_to_with_payload "#{discourse_url}/session/sso_provider", - nonce: nonce, - return_sso_url: return_sso_url + nonce: nonce, + return_sso_url: return_sso_url end def callback @@ -21,6 +20,7 @@ class DiscourseLoginController < DiscourseController payload = parse_payload raise I18n.t('discourse.callback.invalid_nonce') if payload[:nonce] != session[:discourse_sso_nonce] + session[:discourse_sso_nonce] = nil id = payload[:external_id].to_i @@ -39,5 +39,4 @@ class DiscourseLoginController < DiscourseController rescue => error redirect_to login_url, alert: error.to_s end - end diff --git a/plugins/discourse/app/controllers/discourse_sso_controller.rb b/plugins/discourse/app/controllers/discourse_sso_controller.rb index f11397a4..e8f742b6 100644 --- a/plugins/discourse/app/controllers/discourse_sso_controller.rb +++ b/plugins/discourse/app/controllers/discourse_sso_controller.rb @@ -1,5 +1,4 @@ class DiscourseSsoController < DiscourseController - before_action -> { require_config_enabled :discourse_sso } def sso @@ -12,14 +11,13 @@ class DiscourseSsoController < DiscourseController raise I18n.t('discourse.sso.nonce_missing') if nonce.blank? redirect_to_with_payload return_sso_url, - nonce: nonce, - email: current_user.email, - require_activation: true, - external_id: "#{FoodsoftConfig.scope}/#{current_user.id}", - username: current_user.nick, - name: current_user.name + nonce: nonce, + email: current_user.email, + require_activation: true, + external_id: "#{FoodsoftConfig.scope}/#{current_user.id}", + username: current_user.nick, + name: current_user.name rescue => error redirect_to root_url, alert: error.to_s end - end diff --git a/plugins/discourse/config/routes.rb b/plugins/discourse/config/routes.rb index da408523..05848c1b 100644 --- a/plugins/discourse/config/routes.rb +++ b/plugins/discourse/config/routes.rb @@ -1,11 +1,7 @@ Rails.application.routes.draw do - scope '/:foodcoop' do - get '/discourse/callback' => 'discourse_login#callback' get '/discourse/initiate' => 'discourse_login#initiate' get '/discourse/sso' => 'discourse_sso#sso' - end - end diff --git a/plugins/discourse/lib/foodsoft_discourse/redirect_to_login.rb b/plugins/discourse/lib/foodsoft_discourse/redirect_to_login.rb index 95cedbd2..901979b1 100644 --- a/plugins/discourse/lib/foodsoft_discourse/redirect_to_login.rb +++ b/plugins/discourse/lib/foodsoft_discourse/redirect_to_login.rb @@ -1,23 +1,19 @@ module FoodsoftDiscourse - module RedirectToLogin def self.included(base) # :nodoc: base.class_eval do - alias foodsoft_discourse_orig_redirect_to_login redirect_to_login - def redirect_to_login(options={}) + def redirect_to_login(options = {}) if FoodsoftDiscourse.enabled? && !FoodsoftConfig[:discourse_sso] redirect_to discourse_initiate_path else foodsoft_discourse_orig_redirect_to_login(options) end end - end end end - end # modify existing helper diff --git a/plugins/documents/Rakefile b/plugins/documents/Rakefile index 070cb3df..2834c5f3 100644 --- a/plugins/documents/Rakefile +++ b/plugins/documents/Rakefile @@ -23,8 +23,6 @@ end APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) load 'rails/tasks/engine.rake' - - Bundler::GemHelper.install_tasks require 'rake/testtask' @@ -36,5 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end - task :default => :test diff --git a/plugins/documents/app/controllers/documents_controller.rb b/plugins/documents/app/controllers/documents_controller.rb index ca29d4b1..b97470a5 100644 --- a/plugins/documents/app/controllers/documents_controller.rb +++ b/plugins/documents/app/controllers/documents_controller.rb @@ -6,10 +6,10 @@ class DocumentsController < ApplicationController def index if params["sort"] sort = case params["sort"] - when "name" then "data IS NULL DESC, name" - when "created_at" then "created_at" - when "name_reverse" then "data IS NULL, name DESC" - when "created_at_reverse" then "created_at DESC" + when "name" then "data IS NULL DESC, name" + when "created_at" then "created_at" + when "name_reverse" then "data IS NULL, name DESC" + when "created_at_reverse" then "created_at DESC" end else sort = "data IS NULL DESC, name" @@ -31,6 +31,7 @@ class DocumentsController < ApplicationController @document.data = data.read @document.mime = FileMagic.new(FileMagic::MAGIC_MIME).buffer(@document.data) raise t('.not_allowed_mime', mime: @document.mime) unless allowed_mime? @document.mime + if @document.name.empty? name = File.basename(data.original_filename) @document.name = name.gsub(/[^\w\.\-]/, '_') diff --git a/plugins/documents/app/models/document.rb b/plugins/documents/app/models/document.rb index 58cf4728..38608bfd 100644 --- a/plugins/documents/app/models/document.rb +++ b/plugins/documents/app/models/document.rb @@ -27,5 +27,4 @@ class Document < ApplicationRecord "#{name}.#{types.first.preferred_extension}" end - end diff --git a/plugins/documents/config/routes.rb b/plugins/documents/config/routes.rb index 279aa55f..c2f970a2 100644 --- a/plugins/documents/config/routes.rb +++ b/plugins/documents/config/routes.rb @@ -1,13 +1,9 @@ Rails.application.routes.draw do - scope '/:foodcoop' do - resources :documents do get :move get :new get :new_folder end - end - end diff --git a/plugins/documents/lib/foodsoft_documents/engine.rb b/plugins/documents/lib/foodsoft_documents/engine.rb index e2e8ed7c..970b3aa5 100644 --- a/plugins/documents/lib/foodsoft_documents/engine.rb +++ b/plugins/documents/lib/foodsoft_documents/engine.rb @@ -3,6 +3,7 @@ module FoodsoftDocuments def navigation(primary, context) return unless FoodsoftDocuments.enabled? return if primary[:foodcoop].nil? + sub_nav = primary[:foodcoop].sub_navigation sub_nav.items << SimpleNavigation::Item.new(primary, :documents, I18n.t('navigation.documents'), context.documents_path) diff --git a/plugins/links/Rakefile b/plugins/links/Rakefile index c59f5ec5..fb6356f8 100644 --- a/plugins/links/Rakefile +++ b/plugins/links/Rakefile @@ -23,8 +23,6 @@ end APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) load 'rails/tasks/engine.rake' - - Bundler::GemHelper.install_tasks require 'rake/testtask' @@ -36,5 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end - task :default => :test diff --git a/plugins/links/config/routes.rb b/plugins/links/config/routes.rb index 63a77349..55d55872 100644 --- a/plugins/links/config/routes.rb +++ b/plugins/links/config/routes.rb @@ -1,13 +1,9 @@ Rails.application.routes.draw do - scope '/:foodcoop' do - resources :links, only: [:show] namespace :admin do resources :links end - end - end diff --git a/plugins/links/lib/foodsoft_links/engine.rb b/plugins/links/lib/foodsoft_links/engine.rb index 69ca2f09..ab6d9175 100644 --- a/plugins/links/lib/foodsoft_links/engine.rb +++ b/plugins/links/lib/foodsoft_links/engine.rb @@ -1,7 +1,7 @@ module FoodsoftLinks class Engine < ::Rails::Engine def navigation(primary, context) - primary.item :links, I18n.t('navigation.links'), '#', if: Proc.new { visble_links(context).any? } do |subnav| + primary.item :links, I18n.t('navigation.links'), '#', if: Proc.new { visble_links(context).any? } do |subnav| visble_links(context).each do |link| subnav.item link.id, link.name, context.link_path(link) end diff --git a/plugins/messages/Rakefile b/plugins/messages/Rakefile index 85903547..ac014bdd 100644 --- a/plugins/messages/Rakefile +++ b/plugins/messages/Rakefile @@ -23,8 +23,6 @@ end APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) load 'rails/tasks/engine.rake' - - Bundler::GemHelper.install_tasks require 'rake/testtask' @@ -36,5 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end - task :default => :test diff --git a/plugins/messages/app/controllers/admin/messagegroups_controller.rb b/plugins/messages/app/controllers/admin/messagegroups_controller.rb index dcbeff98..cce57474 100644 --- a/plugins/messages/app/controllers/admin/messagegroups_controller.rb +++ b/plugins/messages/app/controllers/admin/messagegroups_controller.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 class Admin::MessagegroupsController < Admin::BaseController inherit_resources diff --git a/plugins/messages/app/controllers/message_threads_controller.rb b/plugins/messages/app/controllers/message_threads_controller.rb index ea8d5cb5..12b815d4 100644 --- a/plugins/messages/app/controllers/message_threads_controller.rb +++ b/plugins/messages/app/controllers/message_threads_controller.rb @@ -1,5 +1,4 @@ class MessageThreadsController < ApplicationController - before_action -> { require_plugin_enabled FoodsoftMessages } def index diff --git a/plugins/messages/app/controllers/messagegroups_controller.rb b/plugins/messages/app/controllers/messagegroups_controller.rb index c3d66d6a..e9ba6770 100644 --- a/plugins/messages/app/controllers/messagegroups_controller.rb +++ b/plugins/messages/app/controllers/messagegroups_controller.rb @@ -1,5 +1,4 @@ class MessagegroupsController < ApplicationController - def index @messagegroups = Messagegroup.order("name") end diff --git a/plugins/messages/app/controllers/messages_controller.rb b/plugins/messages/app/controllers/messages_controller.rb index 7a6ccd12..8ba6e4a0 100644 --- a/plugins/messages/app/controllers/messages_controller.rb +++ b/plugins/messages/app/controllers/messages_controller.rb @@ -1,5 +1,4 @@ class MessagesController < ApplicationController - before_action -> { require_plugin_enabled FoodsoftMessages } # Renders the "inbox" action. @@ -22,7 +21,7 @@ class MessagesController < ApplicationController @message.private = original_message.private @message.subject = I18n.t('messages.model.reply_subject', :subject => original_message.subject) @message.body = I18n.t('messages.model.reply_header', :user => original_message.sender.display, :when => I18n.l(original_message.created_at, :format => :short)) + "\n" - original_message.body.each_line{ |l| @message.body += I18n.t('messages.model.reply_indent', :line => l) } + original_message.body.each_line { |l| @message.body += I18n.t('messages.model.reply_indent', :line => l) } else redirect_to new_message_url, alert: I18n.t('messages.new.error_private') end diff --git a/plugins/messages/app/helpers/messages_helper.rb b/plugins/messages/app/helpers/messages_helper.rb index 25e74c3e..d5371fe4 100644 --- a/plugins/messages/app/helpers/messages_helper.rb +++ b/plugins/messages/app/helpers/messages_helper.rb @@ -15,7 +15,6 @@ module MessagesHelper link_text = content_tag :i, nil, class: 'icon-envelope' link_text << " #{options[:text]}" if options[:text].present? link_to(link_text.html_safe, new_message_path(message: messages_params), class: 'btn', - title: I18n.t('helpers.submit.message.create')) + title: I18n.t('helpers.submit.message.create')) end - end diff --git a/plugins/messages/app/mail_receivers/messages_mail_receiver.rb b/plugins/messages/app/mail_receivers/messages_mail_receiver.rb index be9b2f50..c66cb0e6 100644 --- a/plugins/messages/app/mail_receivers/messages_mail_receiver.rb +++ b/plugins/messages/app/mail_receivers/messages_mail_receiver.rb @@ -1,7 +1,6 @@ require "email_reply_trimmer" class MessagesMailReceiver - def self.regexp /(?\d+)\.(?\d+)\.(?\w+)/ end @@ -37,9 +36,9 @@ class MessagesMailReceiver raise BlankBodyException if body.empty? message = @user.send_messages.new body: body, - group: @message.group, - private: @message.private, - received_email: data + group: @message.group, + private: @message.private, + received_email: data if @message.reply_to message.reply_to_message = @message.reply_to_message else @@ -73,11 +72,8 @@ class MessagesMailReceiver end class BlankBodyException < MidiSmtpServer::SmtpdException - def initialize(msg = nil) super msg, 541, 'The recipient address rejected your message because of a blank plain body' end - end - end diff --git a/plugins/messages/app/models/message.rb b/plugins/messages/app/models/message.rb index 69b89738..f6b03c10 100644 --- a/plugins/messages/app/models/message.rb +++ b/plugins/messages/app/models/message.rb @@ -10,8 +10,8 @@ class Message < ApplicationRecord attr_accessor :send_method, :recipient_tokens, :order_id scope :threads, -> { where(:reply_to => nil) } - scope :thread, -> (id) { where("id = ? OR reply_to = ?", id, id) } - scope :readable_for, -> (user) { + scope :thread, ->(id) { where("id = ? OR reply_to = ?", id, id) } + scope :readable_for, ->(user) { user_id = user.try(&:id) joins(:message_recipients) @@ -128,12 +128,13 @@ class Message < ApplicationRecord def can_toggle_private?(user) return true if sender == user return false if private? + user.role_admin? end private def create_salt - self.salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp + self.salt = [Array.new(6) { rand(256).chr }.join].pack("m").chomp end end diff --git a/plugins/messages/app/models/messagegroup.rb b/plugins/messages/app/models/messagegroup.rb index d5b66576..7c7f6c03 100644 --- a/plugins/messages/app/models/messagegroup.rb +++ b/plugins/messages/app/models/messagegroup.rb @@ -1,6 +1,4 @@ -# encoding: utf-8 class Messagegroup < Group - validates_uniqueness_of :name protected diff --git a/plugins/messages/lib/foodsoft_messages/engine.rb b/plugins/messages/lib/foodsoft_messages/engine.rb index 237197cf..0f67abb7 100644 --- a/plugins/messages/lib/foodsoft_messages/engine.rb +++ b/plugins/messages/lib/foodsoft_messages/engine.rb @@ -2,6 +2,7 @@ module FoodsoftMessages class Engine < ::Rails::Engine def navigation(primary, context) return unless FoodsoftMessages.enabled? + unless primary[:foodcoop].nil? sub_nav = primary[:foodcoop].sub_navigation sub_nav.items << diff --git a/plugins/messages/lib/foodsoft_messages/user_link.rb b/plugins/messages/lib/foodsoft_messages/user_link.rb index aa34bf46..bfab42b6 100644 --- a/plugins/messages/lib/foodsoft_messages/user_link.rb +++ b/plugins/messages/lib/foodsoft_messages/user_link.rb @@ -1,23 +1,19 @@ module FoodsoftMessages - module UserLink def self.included(base) # :nodoc: base.class_eval do - # modify user presentation link to writing a message for the user - def show_user_link(user=@current_user) + def show_user_link(user = @current_user) if user.nil? || !FoodsoftMessages.enabled? show_user user else link_to show_user(user), new_message_path('message[mail_to]' => user.id), - :title => I18n.t('helpers.messages.write_message') + :title => I18n.t('helpers.messages.write_message') end end - end end end - end # modify existing helper diff --git a/plugins/polls/Rakefile b/plugins/polls/Rakefile index 070cb3df..2834c5f3 100644 --- a/plugins/polls/Rakefile +++ b/plugins/polls/Rakefile @@ -23,8 +23,6 @@ end APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) load 'rails/tasks/engine.rake' - - Bundler::GemHelper.install_tasks require 'rake/testtask' @@ -36,5 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end - task :default => :test diff --git a/plugins/polls/app/controllers/polls_controller.rb b/plugins/polls/app/controllers/polls_controller.rb index 90811a36..aac4ef0e 100644 --- a/plugins/polls/app/controllers/polls_controller.rb +++ b/plugins/polls/app/controllers/polls_controller.rb @@ -63,6 +63,7 @@ class PollsController < ApplicationController if @poll.one_vote_per_ordergroup ordergroup = current_user.ordergroup return redirect_to polls_path, alert: t('.no_ordergroup') unless ordergroup + attributes = { ordergroup: ordergroup } else attributes = { user: current_user } @@ -103,8 +104,8 @@ class PollsController < ApplicationController params .require(:poll) .permit(:name, :starts_date_value, :starts_time_value, :ends_date_value, - :ends_time_value, :description, :one_vote_per_ordergroup, :voting_method, - :multi_select_count, :min_points, :max_points, choices: [], - required_ordergroup_custom_fields: [], required_user_custom_fields: []) + :ends_time_value, :description, :one_vote_per_ordergroup, :voting_method, + :multi_select_count, :min_points, :max_points, choices: [], + required_ordergroup_custom_fields: [], required_user_custom_fields: []) end end diff --git a/plugins/polls/app/models/poll.rb b/plugins/polls/app/models/poll.rb index fe5eabdc..e06df907 100644 --- a/plugins/polls/app/models/poll.rb +++ b/plugins/polls/app/models/poll.rb @@ -1,5 +1,4 @@ class Poll < ActiveRecord::Base - # @!attribute required_ordergroup_custom_fields # A list of custom_fileds, which are required to poll. # If the required field on the ordergroup of the user @@ -29,6 +28,7 @@ class Poll < ActiveRecord::Base def available_points return 0...0 if min_points.nil? || max_points.nil? + min_points..max_points end diff --git a/plugins/polls/config/routes.rb b/plugins/polls/config/routes.rb index 5375342c..ace61b0e 100644 --- a/plugins/polls/config/routes.rb +++ b/plugins/polls/config/routes.rb @@ -1,14 +1,10 @@ Rails.application.routes.draw do - scope '/:foodcoop' do - resources :polls do member do get :vote post :vote end end - end - end diff --git a/plugins/polls/lib/foodsoft_polls/engine.rb b/plugins/polls/lib/foodsoft_polls/engine.rb index b8bd1226..a76399f0 100644 --- a/plugins/polls/lib/foodsoft_polls/engine.rb +++ b/plugins/polls/lib/foodsoft_polls/engine.rb @@ -3,6 +3,7 @@ module FoodsoftPolls def navigation(primary, context) return unless FoodsoftPolls.enabled? return if primary[:foodcoop].nil? + sub_nav = primary[:foodcoop].sub_navigation sub_nav.items << SimpleNavigation::Item.new(primary, :polls, I18n.t('navigation.polls'), context.polls_path) diff --git a/plugins/printer/Rakefile b/plugins/printer/Rakefile index c5b09895..1c9d9839 100644 --- a/plugins/printer/Rakefile +++ b/plugins/printer/Rakefile @@ -23,8 +23,6 @@ end APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) load 'rails/tasks/engine.rake' - - Bundler::GemHelper.install_tasks require 'rake/testtask' @@ -36,5 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end - task :default => :test diff --git a/plugins/printer/app/controllers/printer_controller.rb b/plugins/printer/app/controllers/printer_controller.rb index 2ac8dc08..178787da 100644 --- a/plugins/printer/app/controllers/printer_controller.rb +++ b/plugins/printer/app/controllers/printer_controller.rb @@ -36,6 +36,7 @@ class PrinterController < ApplicationController json = JSON.parse data, symbolize_names: true job = PrinterJob.unfinished.find_by_id(json[:id]) return unless job + if json[:state] job.add_update! json[:state], json[:message] end @@ -54,5 +55,4 @@ class PrinterController < ApplicationController return head(:unauthorized) unless bearer_token return head(:forbidden) if bearer_token != FoodsoftConfig[:printer_token] end - end diff --git a/plugins/printer/app/controllers/printer_jobs_controller.rb b/plugins/printer/app/controllers/printer_jobs_controller.rb index 4a4002bc..17333fb5 100644 --- a/plugins/printer/app/controllers/printer_jobs_controller.rb +++ b/plugins/printer/app/controllers/printer_jobs_controller.rb @@ -17,6 +17,7 @@ class PrinterJobsController < ApplicationController PrinterJob.transaction do %w(articles fax groups matrix).each do |document| next unless FoodsoftConfig["printer_print_order_#{document}"] + job = PrinterJob.create! order: order, document: document, created_by: current_user job.add_update! state count += 1 diff --git a/plugins/printer/app/models/printer_job.rb b/plugins/printer/app/models/printer_job.rb index fc1fb6ce..2a0e1ec6 100644 --- a/plugins/printer/app/models/printer_job.rb +++ b/plugins/printer/app/models/printer_job.rb @@ -1,5 +1,4 @@ class PrinterJob < ActiveRecord::Base - belongs_to :order belongs_to :created_by, class_name: 'User', foreign_key: 'created_by_user_id' belongs_to :finished_by, optional: true, class_name: 'User', foreign_key: 'finished_by_user_id' @@ -7,8 +6,8 @@ class PrinterJob < ActiveRecord::Base scope :finished, -> { where.not(finished_at: nil) } scope :unfinished, -> { where(finished_at: nil).order(:id) } - scope :pending, -> { unfinished.includes(:order).where.not(orders: {state: 'open'}) } - scope :queued, -> { unfinished.includes(:order).where(orders: {state: 'open'}) } + scope :pending, -> { unfinished.includes(:order).where.not(orders: { state: 'open' }) } + scope :queued, -> { unfinished.includes(:order).where(orders: { state: 'open' }) } def last_update_at printer_job_updates.order(:created_at).last.try(&:created_at) @@ -18,14 +17,15 @@ class PrinterJob < ActiveRecord::Base printer_job_updates.order(:created_at).last.try(&:state) end - def add_update!(state, message=nil) + def add_update!(state, message = nil) return unless finished_at.nil? + PrinterJobUpdate.create! printer_job: self, state: state, message: message end - def finish!(user=nil) + def finish!(user = nil) return unless finished_at.nil? + update_attributes finished_at: Time.now, finished_by: user end - end diff --git a/plugins/printer/app/models/printer_job_update.rb b/plugins/printer/app/models/printer_job_update.rb index 14e4c0a5..643463e4 100644 --- a/plugins/printer/app/models/printer_job_update.rb +++ b/plugins/printer/app/models/printer_job_update.rb @@ -1,5 +1,3 @@ class PrinterJobUpdate < ActiveRecord::Base - belongs_to :printer_job - end diff --git a/plugins/printer/lib/foodsoft_printer/engine.rb b/plugins/printer/lib/foodsoft_printer/engine.rb index 22c3768f..22144e30 100644 --- a/plugins/printer/lib/foodsoft_printer/engine.rb +++ b/plugins/printer/lib/foodsoft_printer/engine.rb @@ -2,6 +2,7 @@ module FoodsoftPrinter class Engine < ::Rails::Engine def navigation(primary, context) return unless FoodsoftPrinter.enabled? + unless primary[:orders].nil? sub_nav = primary[:orders].sub_navigation sub_nav.items << diff --git a/plugins/printer/lib/foodsoft_printer/order_printer_jobs.rb b/plugins/printer/lib/foodsoft_printer/order_printer_jobs.rb index 62b02e64..7501a69e 100644 --- a/plugins/printer/lib/foodsoft_printer/order_printer_jobs.rb +++ b/plugins/printer/lib/foodsoft_printer/order_printer_jobs.rb @@ -1,5 +1,4 @@ module FoodsoftPrinter - module OrderPrinterJobs def self.included(base) # :nodoc: base.class_eval do @@ -22,5 +21,4 @@ module FoodsoftPrinter Order.send :include, self end end - end diff --git a/plugins/uservoice/lib/foodsoft_uservoice.rb b/plugins/uservoice/lib/foodsoft_uservoice.rb index 3ad9a85c..b4718445 100644 --- a/plugins/uservoice/lib/foodsoft_uservoice.rb +++ b/plugins/uservoice/lib/foodsoft_uservoice.rb @@ -23,13 +23,13 @@ module FoodsoftUservoice js_load = "var uv=document.createElement('script');uv.type='text/javascript';uv.async=true;uv.src='//widget.uservoice.com/#{view_context.j api_key}.js';var s=document.getElementsByTagName('script')[0];s.parentNode.insertBefore(uv,s);" # configuration - sections = FoodsoftConfig[:uservoice].reject {|k,v| k=='api_key'} - sections.each_pair do |k,v| + sections = FoodsoftConfig[:uservoice].reject { |k, v| k == 'api_key' } + sections.each_pair do |k, v| if k == 'identify' v['id'] = current_user.try(:id) if v.include?('id') v['name'] = current_user.try(:display) if v.include?('name') v['email'] = current_user.try(:email) if v.include?('email') - v['created_at'] = current_user.try {|u| u.created_on.to_i} if v.include?('created_at') + v['created_at'] = current_user.try { |u| u.created_on.to_i } if v.include?('created_at') elsif k == 'set' v['locale'] = I18n.locale end @@ -40,7 +40,7 @@ module FoodsoftUservoice js_load = "$(function() { if(!$('[data-role=page]')[0]){#{js_load}} });" # include in layout - content_for :javascript, view_context.javascript_tag(js_pre+js_load) + content_for :javascript, view_context.javascript_tag(js_pre + js_load) end end end diff --git a/plugins/wiki/Rakefile b/plugins/wiki/Rakefile index a3d12088..5d2e31db 100644 --- a/plugins/wiki/Rakefile +++ b/plugins/wiki/Rakefile @@ -23,8 +23,6 @@ end APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) load 'rails/tasks/engine.rake' - - Bundler::GemHelper.install_tasks require 'rake/testtask' @@ -36,5 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end - task :default => :test diff --git a/plugins/wiki/app/controllers/pages_controller.rb b/plugins/wiki/app/controllers/pages_controller.rb index e8ae9e73..c065abe7 100644 --- a/plugins/wiki/app/controllers/pages_controller.rb +++ b/plugins/wiki/app/controllers/pages_controller.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 class PagesController < ApplicationController before_action -> { require_plugin_enabled FoodsoftWiki } before_action :catch_special_pages, only: [:show, :new] @@ -33,7 +32,7 @@ class PagesController < ApplicationController redirect_to wiki_page_path(page.permalink) and return end end - + if @page.nil? redirect_to new_page_path(:title => params[:permalink]) elsif @page.redirect? @@ -61,7 +60,7 @@ class PagesController < ApplicationController end def create - @page = Page.new(params[:page].merge({:user => current_user})) + @page = Page.new(params[:page].merge({ :user => current_user })) if params[:preview] render :action => 'new' @@ -77,7 +76,7 @@ class PagesController < ApplicationController def update @page = Page.find(params[:id]) - @page.attributes = params[:page].merge({:user => current_user}) + @page.attributes = params[:page].merge({ :user => current_user }) if params[:preview] @page.attributes = params[:page] @@ -92,7 +91,6 @@ class PagesController < ApplicationController render :action => "edit" end end - rescue ActiveRecord::StaleObjectError flash[:error] = I18n.t('pages.error_stale_object') redirect_to wiki_page_path(@page.permalink) @@ -116,11 +114,11 @@ class PagesController < ApplicationController end if params[:sort] sort = case params[:sort] - when "title" then "title" - when "title_reverse" then "title DESC" - when "last_updated" then "updated_at DESC" - when "last_updated_reverse" then "updated_at" - end + when "title" then "title" + when "title_reverse" then "title DESC" + when "last_updated" then "updated_at DESC" + when "last_updated_reverse" then "updated_at" + end else sort = "title" end @@ -152,7 +150,7 @@ class PagesController < ApplicationController def variables keys = Foodsoft::ExpansionVariables.variables.keys - @variables = Hash[keys.map {|k| [k, Foodsoft::ExpansionVariables.get(k)]}] + @variables = Hash[keys.map { |k| [k, Foodsoft::ExpansionVariables.get(k)] }] render 'variables' end diff --git a/plugins/wiki/app/helpers/pages_helper.rb b/plugins/wiki/app/helpers/pages_helper.rb index ca43f6c3..551a169d 100644 --- a/plugins/wiki/app/helpers/pages_helper.rb +++ b/plugins/wiki/app/helpers/pages_helper.rb @@ -6,7 +6,7 @@ module PagesHelper end def wikified_body(body, title = nil) - FoodsoftWiki::WikiParser.new(data: body+"\n", params: {referer: title}).to_html(noedit: true).html_safe + FoodsoftWiki::WikiParser.new(data: body + "\n", params: { referer: title }).to_html(noedit: true).html_safe rescue => e # try the following with line breaks: === one === == two == = three = content_tag :span, class: 'alert alert-error' do @@ -22,13 +22,12 @@ module PagesHelper end end - def link_to_wikipage_by_permalink(permalink, text = nil) unless permalink.blank? page = Page.find_by_permalink(permalink) if page.nil? if text.nil? - link_to permalink, new_page_path(:title => permalink) + link_to permalink, new_page_path(:title => permalink) else link_to text, new_page_path(:title => permalink) end @@ -65,9 +64,8 @@ module PagesHelper end # return url for all_pages rss feed - def all_pages_rss_url(options={}) + def all_pages_rss_url(options = {}) token = TokenVerifier.new(['wiki', 'all']).generate - all_pages_url({:format => 'rss', :token => token}.merge(options)) + all_pages_url({ :format => 'rss', :token => token }.merge(options)) end - end diff --git a/plugins/wiki/app/models/page.rb b/plugins/wiki/app/models/page.rb index f5680e8d..e773afa7 100644 --- a/plugins/wiki/app/models/page.rb +++ b/plugins/wiki/app/models/page.rb @@ -76,10 +76,10 @@ class Page < ApplicationRecord def create_redirect unless old_title.blank? Page.create :redirect => id, - :title => old_title, - :body => I18n.t('model.page.redirect', :title => title), - :permalink => Page.permalink(old_title), - :updated_by => updated_by + :title => old_title, + :body => I18n.t('model.page.redirect', :title => title), + :permalink => Page.permalink(old_title), + :updated_by => updated_by end end end diff --git a/plugins/wiki/config/routes.rb b/plugins/wiki/config/routes.rb index d579cd15..4ebad572 100644 --- a/plugins/wiki/config/routes.rb +++ b/plugins/wiki/config/routes.rb @@ -1,7 +1,5 @@ Rails.application.routes.draw do - scope '/:foodcoop' do - resources :pages do get :all, :on => :collection get :version, :on => :member @@ -9,8 +7,6 @@ Rails.application.routes.draw do get :diff, :on => :member end get '/wiki/:permalink' => 'pages#show', :as => 'wiki_page' # , :constraints => {:permalink => /[^\s]+/} - get '/wiki' => 'pages#show', :defaults => {:permalink => 'Home'}, :as => 'wiki' - + get '/wiki' => 'pages#show', :defaults => { :permalink => 'Home' }, :as => 'wiki' end - end diff --git a/plugins/wiki/lib/foodsoft_wiki/engine.rb b/plugins/wiki/lib/foodsoft_wiki/engine.rb index e61fece7..4cc20f6a 100644 --- a/plugins/wiki/lib/foodsoft_wiki/engine.rb +++ b/plugins/wiki/lib/foodsoft_wiki/engine.rb @@ -2,13 +2,14 @@ module FoodsoftWiki class Engine < ::Rails::Engine def navigation(primary, ctx) return unless FoodsoftWiki.enabled? + primary.item :wiki, I18n.t('navigation.wiki.title'), '#', id: nil do |subnav| subnav.item :wiki_home, I18n.t('navigation.wiki.home'), ctx.wiki_path, id: nil subnav.item :all_pages, I18n.t('navigation.wiki.all_pages'), ctx.all_pages_path, id: nil end # move this last added item to just after the foodcoop menu if i = primary.items.index(primary[:foodcoop]) - primary.items.insert(i+1, primary.items.delete_at(-1)) + primary.items.insert(i + 1, primary.items.delete_at(-1)) end end diff --git a/plugins/wiki/lib/foodsoft_wiki/mailer.rb b/plugins/wiki/lib/foodsoft_wiki/mailer.rb index ba584ae7..83a110f1 100644 --- a/plugins/wiki/lib/foodsoft_wiki/mailer.rb +++ b/plugins/wiki/lib/foodsoft_wiki/mailer.rb @@ -1,20 +1,16 @@ module FoodsoftWiki - module Mailer def self.included(base) # :nodoc: base.class_eval do - # modify user presentation link to writing a message for the user def additonal_welcome_text(user) if FoodsoftWiki.enabled? && (page = Page.welcome_mail) page.body end end - end end end - end # modify existing helper diff --git a/plugins/wiki/lib/foodsoft_wiki/wiki_parser.rb b/plugins/wiki/lib/foodsoft_wiki/wiki_parser.rb index a15504e5..37e58465 100644 --- a/plugins/wiki/lib/foodsoft_wiki/wiki_parser.rb +++ b/plugins/wiki/lib/foodsoft_wiki/wiki_parser.rb @@ -1,6 +1,5 @@ module FoodsoftWiki class WikiParser < WikiCloth::Parser - template do |template| Foodsoft::ExpansionVariables.get(template) end @@ -31,12 +30,11 @@ module FoodsoftWiki super(render_options) end - private def link_attributes_if_number_sign_contained_in_nonexistent(page, referer) # Interpret the part after the last number sign as anchor. - arr = page.split('#', -1)# `-1` preserves empty anchor + arr = page.split('#', -1) # `-1` preserves empty anchor page = arr[0...-1].join('#') anchor = arr[-1] @@ -52,9 +50,8 @@ module FoodsoftWiki end end - def url_for(path_name, options={}) - Rails.application.routes.url_helpers.send path_name, options.merge({foodcoop: FoodsoftConfig.scope}) + def url_for(path_name, options = {}) + Rails.application.routes.url_helpers.send path_name, options.merge({ foodcoop: FoodsoftConfig.scope }) end - end end diff --git a/script/rails b/script/rails index f8da2cff..bd79dce5 100755 --- a/script/rails +++ b/script/rails @@ -1,6 +1,6 @@ #!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. -APP_PATH = File.expand_path('../../config/application', __FILE__) -require File.expand_path('../../config/boot', __FILE__) +APP_PATH = File.expand_path('../../config/application', __FILE__) +require File.expand_path('../../config/boot', __FILE__) require 'rails/commands' diff --git a/spec/api/v1/order_articles_spec.rb b/spec/api/v1/order_articles_spec.rb index 62ab60bf..2639a41d 100644 --- a/spec/api/v1/order_articles_spec.rb +++ b/spec/api/v1/order_articles_spec.rb @@ -6,7 +6,7 @@ describe Api::V1::OrderArticlesController, type: :controller do let(:api_scopes) { ['orders:read'] } let(:json_order_articles) { json_response['order_articles'] } - let(:json_order_article_ids) { json_order_articles.map {|joa| joa["id"] } } + let(:json_order_article_ids) { json_order_articles.map { |joa| joa["id"] } } describe "GET :index" do context "with param q[ordered]" do diff --git a/spec/api/v1/swagger_spec.rb b/spec/api/v1/swagger_spec.rb index 0710b8a7..a481155c 100644 --- a/spec/api/v1/swagger_spec.rb +++ b/spec/api/v1/swagger_spec.rb @@ -44,7 +44,7 @@ describe 'API v1', type: :apivore, order: :defined do context 'without ordergroup' do it { is_expected.to validate(:get, '/user/financial_transactions', 403, api_auth) } - it { is_expected.to validate(:get, '/user/financial_transactions/{id}', 403, api_auth({'id' => other_ft_1.id})) } + it { is_expected.to validate(:get, '/user/financial_transactions/{id}', 403, api_auth({ 'id' => other_ft_1.id })) } end context 'with ordergroup' do @@ -54,11 +54,11 @@ describe 'API v1', type: :apivore, order: :defined do let!(:ft_3) { create :financial_transaction, ordergroup: user.ordergroup } it { is_expected.to validate(:get, '/user/financial_transactions', 200, api_auth) } - it { is_expected.to validate(:get, '/user/financial_transactions/{id}', 200, api_auth({'id' => ft_2.id})) } - it { is_expected.to validate(:get, '/user/financial_transactions/{id}', 404, api_auth({'id' => other_ft_1.id})) } - it { is_expected.to validate(:get, '/user/financial_transactions/{id}', 404, api_auth({'id' => FinancialTransaction.last.id + 1})) } + it { is_expected.to validate(:get, '/user/financial_transactions/{id}', 200, api_auth({ 'id' => ft_2.id })) } + it { is_expected.to validate(:get, '/user/financial_transactions/{id}', 404, api_auth({ 'id' => other_ft_1.id })) } + it { is_expected.to validate(:get, '/user/financial_transactions/{id}', 404, api_auth({ 'id' => FinancialTransaction.last.id + 1 })) } - let(:create_params) { {'_data' => {financial_transaction: {amount: 1, financial_transaction_type_id: ft_1.financial_transaction_type.id, note: 'note'}}} } + let(:create_params) { { '_data' => { financial_transaction: { amount: 1, financial_transaction_type_id: ft_1.financial_transaction_type.id, note: 'note' } } } } context 'without using self service' do it { is_expected.to validate(:post, '/user/financial_transactions', 403, api_auth(create_params)) } @@ -70,13 +70,13 @@ describe 'API v1', type: :apivore, order: :defined do it { is_expected.to validate(:post, '/user/financial_transactions', 200, api_auth(create_params)) } context 'with invalid financial transaction type' do - let(:create_params) { {'_data' => {financial_transaction: {amount: 1, financial_transaction_type_id: -1, note: 'note'}}} } + let(:create_params) { { '_data' => { financial_transaction: { amount: 1, financial_transaction_type_id: -1, note: 'note' } } } } it { is_expected.to validate(:post, '/user/financial_transactions', 404, api_auth(create_params)) } end context 'without note' do - let(:create_params) { {'_data' => {financial_transaction: {amount: 1, financial_transaction_type_id: ft_1.financial_transaction_type.id}}} } + let(:create_params) { { '_data' => { financial_transaction: { amount: 1, financial_transaction_type_id: ft_1.financial_transaction_type.id } } } } it { is_expected.to validate(:post, '/user/financial_transactions', 422, api_auth(create_params)) } end @@ -88,8 +88,8 @@ describe 'API v1', type: :apivore, order: :defined do end it_handles_invalid_token_and_scope(:get, '/user/financial_transactions') - it_handles_invalid_token_and_scope(:post, '/user/financial_transactions', ->{ api_auth(create_params) }) - it_handles_invalid_token_and_scope(:get, '/user/financial_transactions/{id}', ->{ api_auth('id' => ft_2.id) }) + it_handles_invalid_token_and_scope(:post, '/user/financial_transactions', -> { api_auth(create_params) }) + it_handles_invalid_token_and_scope(:get, '/user/financial_transactions/{id}', -> { api_auth('id' => ft_2.id) }) end end @@ -104,7 +104,7 @@ describe 'API v1', type: :apivore, order: :defined do context 'without ordergroup' do it { is_expected.to validate(:get, '/user/group_order_articles', 403, api_auth) } - it { is_expected.to validate(:get, '/user/group_order_articles/{id}', 403, api_auth({'id' => goa_2.id})) } + it { is_expected.to validate(:get, '/user/group_order_articles/{id}', 403, api_auth({ 'id' => goa_2.id })) } end context 'with ordergroup' do @@ -114,26 +114,26 @@ describe 'API v1', type: :apivore, order: :defined do before { group_order.update_price!; user.ordergroup.update_stats! } it { is_expected.to validate(:get, '/user/group_order_articles', 200, api_auth) } - it { is_expected.to validate(:get, '/user/group_order_articles/{id}', 200, api_auth({'id' => goa.id})) } - it { is_expected.to validate(:get, '/user/group_order_articles/{id}', 404, api_auth({'id' => goa_2.id})) } - it { is_expected.to validate(:get, '/user/group_order_articles/{id}', 404, api_auth({'id' => GroupOrderArticle.last.id + 1})) } + it { is_expected.to validate(:get, '/user/group_order_articles/{id}', 200, api_auth({ 'id' => goa.id })) } + it { is_expected.to validate(:get, '/user/group_order_articles/{id}', 404, api_auth({ 'id' => goa_2.id })) } + it { is_expected.to validate(:get, '/user/group_order_articles/{id}', 404, api_auth({ 'id' => GroupOrderArticle.last.id + 1 })) } - let(:create_params) { {'_data' => {group_order_article: {order_article_id: order.order_articles[1].id, quantity: 1}}} } - let(:update_params) { {'id' => goa.id, '_data' => {group_order_article: {quantity: goa.quantity + 1, tolerance: 0}}} } + let(:create_params) { { '_data' => { group_order_article: { order_article_id: order.order_articles[1].id, quantity: 1 } } } } + let(:update_params) { { 'id' => goa.id, '_data' => { group_order_article: { quantity: goa.quantity + 1, tolerance: 0 } } } } it { is_expected.to validate(:post, '/user/group_order_articles', 200, api_auth(create_params)) } it { is_expected.to validate(:patch, '/user/group_order_articles/{id}', 200, api_auth(update_params)) } - it { is_expected.to validate(:delete, '/user/group_order_articles/{id}', 200, api_auth({'id' => goa.id})) } + it { is_expected.to validate(:delete, '/user/group_order_articles/{id}', 200, api_auth({ 'id' => goa.id })) } context 'with an existing group_order_article' do - let(:create_params) { {'_data' => {group_order_article: {order_article_id: order.order_articles[0].id, quantity: 1}}} } + let(:create_params) { { '_data' => { group_order_article: { order_article_id: order.order_articles[0].id, quantity: 1 } } } } it { is_expected.to validate(:post, '/user/group_order_articles', 422, api_auth(create_params)) } end context 'with invalid parameter values' do - let(:create_params) { {'_data' => {group_order_article: {order_article_id: order.order_articles[0].id, quantity: -1}}} } - let(:update_params) { {'id' => goa.id, '_data' => {group_order_article: {quantity: -1, tolerance: 0}}} } + let(:create_params) { { '_data' => { group_order_article: { order_article_id: order.order_articles[0].id, quantity: -1 } } } } + let(:update_params) { { 'id' => goa.id, '_data' => { group_order_article: { quantity: -1, tolerance: 0 } } } } it { is_expected.to validate(:post, '/user/group_order_articles', 422, api_auth(create_params)) } it { is_expected.to validate(:patch, '/user/group_order_articles/{id}', 422, api_auth(update_params)) } @@ -144,28 +144,28 @@ describe 'API v1', type: :apivore, order: :defined do it { is_expected.to validate(:post, '/user/group_order_articles', 404, api_auth(create_params)) } it { is_expected.to validate(:patch, '/user/group_order_articles/{id}', 404, api_auth(update_params)) } - it { is_expected.to validate(:delete, '/user/group_order_articles/{id}', 404, api_auth({'id' => goa.id})) } + it { is_expected.to validate(:delete, '/user/group_order_articles/{id}', 404, api_auth({ 'id' => goa.id })) } end context 'without enough balance' do before { FoodsoftConfig[:minimum_balance] = 1000 } it { is_expected.to validate(:post, '/user/group_order_articles', 403, api_auth(create_params)) } it { is_expected.to validate(:patch, '/user/group_order_articles/{id}', 403, api_auth(update_params)) } - it { is_expected.to validate(:delete, '/user/group_order_articles/{id}', 200, api_auth({'id' => goa.id})) } + it { is_expected.to validate(:delete, '/user/group_order_articles/{id}', 200, api_auth({ 'id' => goa.id })) } end context 'without enough apple points' do - before { allow_any_instance_of(Ordergroup).to receive(:not_enough_apples?).and_return(true) } + before { allow_any_instance_of(Ordergroup).to receive(:not_enough_apples?).and_return(true) } it { is_expected.to validate(:post, '/user/group_order_articles', 403, api_auth(create_params)) } it { is_expected.to validate(:patch, '/user/group_order_articles/{id}', 403, api_auth(update_params)) } - it { is_expected.to validate(:delete, '/user/group_order_articles/{id}', 200, api_auth({'id' => goa.id})) } + it { is_expected.to validate(:delete, '/user/group_order_articles/{id}', 200, api_auth({ 'id' => goa.id })) } end it_handles_invalid_token_and_scope(:get, '/user/group_order_articles') - it_handles_invalid_token_and_scope(:post, '/user/group_order_articles', ->{ api_auth(create_params) }) - it_handles_invalid_token_and_scope(:get, '/user/group_order_articles/{id}', ->{ api_auth({'id' => goa.id}) }) - it_handles_invalid_token_and_scope(:patch, '/user/group_order_articles/{id}', ->{ api_auth(update_params) }) - it_handles_invalid_token_and_scope(:delete, '/user/group_order_articles/{id}', ->{ api_auth({'id' => goa.id}) }) + it_handles_invalid_token_and_scope(:post, '/user/group_order_articles', -> { api_auth(create_params) }) + it_handles_invalid_token_and_scope(:get, '/user/group_order_articles/{id}', -> { api_auth({ 'id' => goa.id }) }) + it_handles_invalid_token_and_scope(:patch, '/user/group_order_articles/{id}', -> { api_auth(update_params) }) + it_handles_invalid_token_and_scope(:delete, '/user/group_order_articles/{id}', -> { api_auth({ 'id' => goa.id }) }) end end @@ -193,17 +193,17 @@ describe 'API v1', type: :apivore, order: :defined do let!(:ft_2) { create :financial_transaction, ordergroup: other_user.ordergroup } it { is_expected.to validate(:get, '/financial_transactions', 200, api_auth) } - it { is_expected.to validate(:get, '/financial_transactions/{id}', 200, api_auth({'id' => ft_2.id})) } - it { is_expected.to validate(:get, '/financial_transactions/{id}', 404, api_auth({'id' => FinancialTransaction.last.id + 1})) } + it { is_expected.to validate(:get, '/financial_transactions/{id}', 200, api_auth({ 'id' => ft_2.id })) } + it { is_expected.to validate(:get, '/financial_transactions/{id}', 404, api_auth({ 'id' => FinancialTransaction.last.id + 1 })) } context 'without role_finance' do let(:user) { create(:user) } it { is_expected.to validate(:get, '/financial_transactions', 403, api_auth) } - it { is_expected.to validate(:get, '/financial_transactions/{id}', 403, api_auth({'id' => ft_2.id})) } + it { is_expected.to validate(:get, '/financial_transactions/{id}', 403, api_auth({ 'id' => ft_2.id })) } end it_handles_invalid_token_and_scope(:get, '/financial_transactions') - it_handles_invalid_token_and_scope(:get, '/financial_transactions/{id}', ->{ api_auth({'id' => ft_2.id}) }) + it_handles_invalid_token_and_scope(:get, '/financial_transactions/{id}', -> { api_auth({ 'id' => ft_2.id }) }) end context 'financial_transaction_classes' do @@ -211,11 +211,11 @@ describe 'API v1', type: :apivore, order: :defined do let!(:cla_2) { create :financial_transaction_class } it { is_expected.to validate(:get, '/financial_transaction_classes', 200, api_auth) } - it { is_expected.to validate(:get, '/financial_transaction_classes/{id}', 200, api_auth({'id' => cla_2.id})) } - it { is_expected.to validate(:get, '/financial_transaction_classes/{id}', 404, api_auth({'id' => cla_2.id + 1})) } + it { is_expected.to validate(:get, '/financial_transaction_classes/{id}', 200, api_auth({ 'id' => cla_2.id })) } + it { is_expected.to validate(:get, '/financial_transaction_classes/{id}', 404, api_auth({ 'id' => cla_2.id + 1 })) } it_handles_invalid_token(:get, '/financial_transaction_classes') - it_handles_invalid_token(:get, '/financial_transaction_classes/{id}', ->{ api_auth({'id' => cla_1.id }) }) + it_handles_invalid_token(:get, '/financial_transaction_classes/{id}', -> { api_auth({ 'id' => cla_1.id }) }) end context 'financial_transaction_types' do @@ -223,11 +223,11 @@ describe 'API v1', type: :apivore, order: :defined do let!(:tpy_2) { create :financial_transaction_type } it { is_expected.to validate(:get, '/financial_transaction_types', 200, api_auth) } - it { is_expected.to validate(:get, '/financial_transaction_types/{id}', 200, api_auth({'id' => tpy_2.id})) } - it { is_expected.to validate(:get, '/financial_transaction_types/{id}', 404, api_auth({'id' => tpy_2.id + 1})) } + it { is_expected.to validate(:get, '/financial_transaction_types/{id}', 200, api_auth({ 'id' => tpy_2.id })) } + it { is_expected.to validate(:get, '/financial_transaction_types/{id}', 404, api_auth({ 'id' => tpy_2.id + 1 })) } it_handles_invalid_token(:get, '/financial_transaction_types') - it_handles_invalid_token(:get, '/financial_transaction_types/{id}', ->{ api_auth({'id' => tpy_1.id }) }) + it_handles_invalid_token(:get, '/financial_transaction_types/{id}', -> { api_auth({ 'id' => tpy_1.id }) }) end context 'orders' do @@ -235,11 +235,11 @@ describe 'API v1', type: :apivore, order: :defined do let!(:order) { create :order } it { is_expected.to validate(:get, '/orders', 200, api_auth) } - it { is_expected.to validate(:get, '/orders/{id}', 200, api_auth({'id' => order.id})) } - it { is_expected.to validate(:get, '/orders/{id}', 404, api_auth({'id' => Order.last.id + 1})) } + it { is_expected.to validate(:get, '/orders/{id}', 200, api_auth({ 'id' => order.id })) } + it { is_expected.to validate(:get, '/orders/{id}', 404, api_auth({ 'id' => Order.last.id + 1 })) } it_handles_invalid_token_and_scope(:get, '/orders') - it_handles_invalid_token_and_scope(:get, '/orders/{id}', ->{ api_auth({'id' => order.id}) }) + it_handles_invalid_token_and_scope(:get, '/orders/{id}', -> { api_auth({ 'id' => order.id }) }) end context 'order_articles' do @@ -249,12 +249,12 @@ describe 'API v1', type: :apivore, order: :defined do let!(:stock_order_article) { create(:stock_order, article_ids: [stock_article.id]).order_articles.first } it { is_expected.to validate(:get, '/order_articles', 200, api_auth) } - it { is_expected.to validate(:get, '/order_articles/{id}', 200, api_auth({'id' => order_article.id})) } - it { is_expected.to validate(:get, '/order_articles/{id}', 200, api_auth({'id' => stock_order_article.id})) } - it { is_expected.to validate(:get, '/order_articles/{id}', 404, api_auth({'id' => Article.last.id + 1})) } + it { is_expected.to validate(:get, '/order_articles/{id}', 200, api_auth({ 'id' => order_article.id })) } + it { is_expected.to validate(:get, '/order_articles/{id}', 200, api_auth({ 'id' => stock_order_article.id })) } + it { is_expected.to validate(:get, '/order_articles/{id}', 404, api_auth({ 'id' => Article.last.id + 1 })) } it_handles_invalid_token_and_scope(:get, '/order_articles') - it_handles_invalid_token_and_scope(:get, '/order_articles/{id}', ->{ api_auth({'id' => order_article.id}) }) + it_handles_invalid_token_and_scope(:get, '/order_articles/{id}', -> { api_auth({ 'id' => order_article.id }) }) end context 'article_categories' do @@ -262,11 +262,11 @@ describe 'API v1', type: :apivore, order: :defined do let!(:cat_2) { create :article_category } it { is_expected.to validate(:get, '/article_categories', 200, api_auth) } - it { is_expected.to validate(:get, '/article_categories/{id}', 200, api_auth({'id' => cat_2.id})) } - it { is_expected.to validate(:get, '/article_categories/{id}', 404, api_auth({'id' => cat_2.id + 1})) } + it { is_expected.to validate(:get, '/article_categories/{id}', 200, api_auth({ 'id' => cat_2.id })) } + it { is_expected.to validate(:get, '/article_categories/{id}', 404, api_auth({ 'id' => cat_2.id + 1 })) } it_handles_invalid_token(:get, '/article_categories') - it_handles_invalid_token(:get, '/article_categories/{id}', ->{ api_auth({'id' => cat_1.id }) }) + it_handles_invalid_token(:get, '/article_categories/{id}', -> { api_auth({ 'id' => cat_1.id }) }) end end diff --git a/spec/api/v1/user/financial_transactions_spec.rb b/spec/api/v1/user/financial_transactions_spec.rb index d7f0c6b3..a5952b67 100644 --- a/spec/api/v1/user/financial_transactions_spec.rb +++ b/spec/api/v1/user/financial_transactions_spec.rb @@ -47,7 +47,6 @@ describe Api::V1::User::FinancialTransactionsController, type: :controller do end end - shared_examples "financial_transactions endpoint failure" do |status| it "returns status #{status}" do request @@ -67,7 +66,6 @@ describe Api::V1::User::FinancialTransactionsController, type: :controller do end end - describe "POST :create" do let(:ft_params) { { amount: amount, financial_transaction_type_id: ftt1.id, note: note } } let(:request) { post :create, params: { financial_transaction: ft_params, foodcoop: 'f' } } diff --git a/spec/api/v1/user/group_order_articles_spec.rb b/spec/api/v1/user/group_order_articles_spec.rb index 8b940813..27fbe843 100644 --- a/spec/api/v1/user/group_order_articles_spec.rb +++ b/spec/api/v1/user/group_order_articles_spec.rb @@ -12,14 +12,13 @@ describe Api::V1::User::GroupOrderArticlesController, type: :controller do let(:other_quantity) { rand(1..10) } let(:other_tolerance) { rand(1..10) } let(:user_other) { create(:user, :ordergroup) } - let!(:go_other) { create(:group_order, order: order, ordergroup: user_other.ordergroup ) } + let!(:go_other) { create(:group_order, order: order, ordergroup: user_other.ordergroup) } let!(:goa_other) { create(:group_order_article, group_order: go_other, order_article: oa_1, quantity: other_quantity, tolerance: other_tolerance) } before { go_other.update_price!; user_other.ordergroup.update_stats! } let(:json_goa) { json_response['group_order_article'] } let(:json_oa) { json_response['order_article'] } - shared_examples "group_order_articles endpoint success" do before { request } @@ -38,8 +37,8 @@ describe Api::V1::User::GroupOrderArticlesController, type: :controller do expect { request go = user.ordergroup.group_orders.where(order: order).last - }.to change { go&.updated_by }.to(user) - .and change { go&.price } + }.to change { go&.updated_by }.to(user) + .and change { go&.price } end end @@ -61,7 +60,6 @@ describe Api::V1::User::GroupOrderArticlesController, type: :controller do end end - shared_examples "group_order_articles endpoint failure" do |status| it "returns status #{status}" do request @@ -78,13 +76,12 @@ describe Api::V1::User::GroupOrderArticlesController, type: :controller do it "does not change the group_order_article" do expect { request }.to_not change { goa = GroupOrderArticle.joins(:group_order) - .where(order_article_id: oa_1.id, group_orders: { ordergroup: user.ordergroup }).last + .where(order_article_id: oa_1.id, group_orders: { ordergroup: user.ordergroup }).last goa&.attributes } end end - describe "POST :create" do let(:new_quantity) { rand(1..10) } let(:new_tolerance) { rand(1..10) } @@ -109,7 +106,7 @@ describe Api::V1::User::GroupOrderArticlesController, type: :controller do end context "with invalid parameter values" do - let(:goa_params) { { order_article_id: oa_1.id, quantity: -1, tolerance: new_tolerance} } + let(:goa_params) { { order_article_id: oa_1.id, quantity: -1, tolerance: new_tolerance } } include_examples "group_order_articles endpoint failure", 422 end @@ -124,7 +121,7 @@ describe Api::V1::User::GroupOrderArticlesController, type: :controller do end context 'without enough apple points' do - before { allow_any_instance_of(Ordergroup).to receive(:not_enough_apples?).and_return(true) } + before { allow_any_instance_of(Ordergroup).to receive(:not_enough_apples?).and_return(true) } include_examples "group_order_articles endpoint failure", 403 end end @@ -145,7 +142,7 @@ describe Api::V1::User::GroupOrderArticlesController, type: :controller do end context "with invalid parameter values" do - let(:goa_params) { { order_article_id: oa_1.id, quantity: -1, tolerance: new_tolerance} } + let(:goa_params) { { order_article_id: oa_1.id, quantity: -1, tolerance: new_tolerance } } include_examples "group_order_articles endpoint failure", 422 end @@ -160,7 +157,7 @@ describe Api::V1::User::GroupOrderArticlesController, type: :controller do end context 'without enough apple points' do - before { allow_any_instance_of(Ordergroup).to receive(:not_enough_apples?).and_return(true) } + before { allow_any_instance_of(Ordergroup).to receive(:not_enough_apples?).and_return(true) } include_examples "group_order_articles endpoint failure", 403 end end @@ -175,7 +172,6 @@ describe Api::V1::User::GroupOrderArticlesController, type: :controller do let(:request) { delete :destroy, params: { id: goa.id, foodcoop: 'f' } } - shared_examples "group_order_articles destroy success" do include_examples "group_order_articles endpoint success" @@ -188,7 +184,6 @@ describe Api::V1::User::GroupOrderArticlesController, type: :controller do end end - context "happy flow" do include_examples "group_order_articles destroy success" end @@ -204,7 +199,7 @@ describe Api::V1::User::GroupOrderArticlesController, type: :controller do end context 'without enough apple points' do - before { allow_any_instance_of(Ordergroup).to receive(:not_enough_apples?).and_return(true) } + before { allow_any_instance_of(Ordergroup).to receive(:not_enough_apples?).and_return(true) } include_examples "group_order_articles destroy success" end end diff --git a/spec/api/v1/user/ordergroup_spec.rb b/spec/api/v1/user/ordergroup_spec.rb index 06cca3e2..32d1053a 100644 --- a/spec/api/v1/user/ordergroup_spec.rb +++ b/spec/api/v1/user/ordergroup_spec.rb @@ -41,7 +41,7 @@ describe Api::V1::User::OrdergroupController, type: :controller do expect(json_financial_overview['account_balance']).to eq 444 expect(json_financial_overview['available_funds']).to eq 444 - go.price - ftcs = Hash[ json_financial_overview['financial_transaction_class_sums'].map { |x| [x['id'], x] } ] + ftcs = Hash[json_financial_overview['financial_transaction_class_sums'].map { |x| [x['id'], x] }] ftcs1 = ftcs[ftc1.id] expect(ftcs1['name']).to eq ftc1.name diff --git a/spec/factories/article.rb b/spec/factories/article.rb index 7112a2b9..3c85288d 100644 --- a/spec/factories/article.rb +++ b/spec/factories/article.rb @@ -1,7 +1,6 @@ require 'factory_bot' FactoryBot.define do - factory :_article do unit { Faker::Unit.unit } price { rand(0.1..26.0).round(2) } @@ -32,5 +31,4 @@ FactoryBot.define do factory :article_category do sequence(:name) { |n| Faker::Lorem.characters(number: rand(2..12)) + " ##{n}" } end - end diff --git a/spec/factories/bank_transaction_type.rb b/spec/factories/bank_transaction_type.rb index 66da3550..1cf7b0b9 100644 --- a/spec/factories/bank_transaction_type.rb +++ b/spec/factories/bank_transaction_type.rb @@ -1,7 +1,6 @@ require 'factory_bot' FactoryBot.define do - factory :bank_account do name { Faker::Bank.name } iban { Faker::Bank.iban } @@ -11,5 +10,4 @@ FactoryBot.define do date { Faker::Date.backward(days: 14) } text { Faker::Lorem.sentence } end - end diff --git a/spec/factories/doorkeeper.rb b/spec/factories/doorkeeper.rb index 8880d979..95de4eb6 100644 --- a/spec/factories/doorkeeper.rb +++ b/spec/factories/doorkeeper.rb @@ -2,7 +2,6 @@ require 'factory_bot' require 'doorkeeper' FactoryBot.define do - factory :oauth2_application, class: Doorkeeper::Application do name { Faker::App.name } redirect_uri { 'https://example.com:1234/app' } @@ -11,5 +10,4 @@ FactoryBot.define do factory :oauth2_access_token, class: Doorkeeper::AccessToken do application factory: :oauth2_application end - end diff --git a/spec/factories/financial_transaction_type.rb b/spec/factories/financial_transaction_type.rb index 3f4a5543..baa3b290 100644 --- a/spec/factories/financial_transaction_type.rb +++ b/spec/factories/financial_transaction_type.rb @@ -1,7 +1,6 @@ require 'factory_bot' FactoryBot.define do - factory :financial_transaction_class do sequence(:name) { |n| Faker::Lorem.characters(number: rand(2..12)) + " ##{n}" } end @@ -10,5 +9,4 @@ FactoryBot.define do financial_transaction_class sequence(:name) { |n| Faker::Lorem.words(number: rand(2..4)).join(' ') + " ##{n}" } end - end diff --git a/spec/factories/group_order.rb b/spec/factories/group_order.rb index c1f0fc9d..f7e910df 100644 --- a/spec/factories/group_order.rb +++ b/spec/factories/group_order.rb @@ -1,11 +1,9 @@ require 'factory_bot' FactoryBot.define do - # requires order factory :group_order do ordergroup { create(:user, groups: [FactoryBot.create(:ordergroup)]).ordergroup } updated_by { create :user } end - end diff --git a/spec/factories/group_order_article.rb b/spec/factories/group_order_article.rb index e1c9f6e2..4685b119 100644 --- a/spec/factories/group_order_article.rb +++ b/spec/factories/group_order_article.rb @@ -1,9 +1,7 @@ require 'factory_bot' FactoryBot.define do - # requires order_article factory :group_order_article do end - end diff --git a/spec/factories/group_order_article_quantity.rb b/spec/factories/group_order_article_quantity.rb index f3fa5bb6..b414f50b 100644 --- a/spec/factories/group_order_article_quantity.rb +++ b/spec/factories/group_order_article_quantity.rb @@ -1,9 +1,7 @@ require 'factory_bot' FactoryBot.define do - # requires order_article factory :group_order_article_quantity do end - end diff --git a/spec/factories/invoice.rb b/spec/factories/invoice.rb index b52bfea8..b3e65a17 100644 --- a/spec/factories/invoice.rb +++ b/spec/factories/invoice.rb @@ -1,7 +1,6 @@ require 'factory_bot' FactoryBot.define do - factory :invoice do supplier number { rand(1..99999) } @@ -12,5 +11,4 @@ FactoryBot.define do invoice.supplier.reload end end - end diff --git a/spec/factories/order.rb b/spec/factories/order.rb index 9d7f6557..87febae2 100644 --- a/spec/factories/order.rb +++ b/spec/factories/order.rb @@ -1,7 +1,6 @@ require 'factory_bot' FactoryBot.define do - factory :order do starts { Time.now } supplier { create :supplier, article_count: (article_count.nil? ? true : article_count) } @@ -25,5 +24,4 @@ FactoryBot.define do order.reload end end - end diff --git a/spec/factories/supplier.rb b/spec/factories/supplier.rb index c46d1345..c8b680fc 100644 --- a/spec/factories/supplier.rb +++ b/spec/factories/supplier.rb @@ -1,7 +1,6 @@ require 'factory_bot' FactoryBot.define do - factory :supplier do name { Faker::Company.name.truncate(30) } phone { Faker::PhoneNumber.phone_number } @@ -14,6 +13,7 @@ FactoryBot.define do before :create do |supplier, evaluator| next if supplier.class == SharedSupplier next if supplier.supplier_category_id? + supplier.supplier_category = create :supplier_category end @@ -30,5 +30,4 @@ FactoryBot.define do sequence(:name) { |n| Faker::Lorem.characters(number: rand(2..12)) + " ##{n}" } financial_transaction_class end - end diff --git a/spec/factories/user.rb b/spec/factories/user.rb index 2a83f64e..eb12196f 100644 --- a/spec/factories/user.rb +++ b/spec/factories/user.rb @@ -1,9 +1,8 @@ require 'factory_bot' FactoryBot.define do - factory :user do - sequence(:nick) { |n| "user#{n}"} + sequence(:nick) { |n| "user#{n}" } first_name { Faker::Name.first_name } email { Faker::Internet.email } password { new_random_password } @@ -32,7 +31,7 @@ FactoryBot.define do end factory :group do - sequence(:name) {|n| "Group ##{n}"} + sequence(:name) { |n| "Group ##{n}" } factory :workgroup do type { '' } @@ -40,11 +39,10 @@ FactoryBot.define do factory :ordergroup do type { 'Ordergroup' } - sequence(:name) {|n| "Order group ##{n}"} + sequence(:name) { |n| "Order group ##{n}" } # workaround to avoid needing to save the ordergroup # avoids e.g. error after logging in related to applebar after :create do |group| Ordergroup.find(group.id).update_stats! end end end - end diff --git a/spec/i18n_spec.rb b/spec/i18n_spec.rb index b760d124..c74a103d 100644 --- a/spec/i18n_spec.rb +++ b/spec/i18n_spec.rb @@ -7,6 +7,6 @@ Dir.glob('config/locales/??{-*,}.yml').each do |locale_file| # We're currently allowing both German and English as source language # besides, we're using localeapp, so that it's ok if pull requests # don't have this - a localapp pull will fix that right away. - #it { expect(locale_file).to be_a_subset_of 'config/locales/en.yml' } + # it { expect(locale_file).to be_a_subset_of 'config/locales/en.yml' } end end diff --git a/spec/integration/articles_spec.rb b/spec/integration/articles_spec.rb index 40b3a1aa..820317b7 100644 --- a/spec/integration/articles_spec.rb +++ b/spec/integration/articles_spec.rb @@ -1,8 +1,7 @@ -# encoding: utf-8 require_relative '../spec_helper' feature ArticlesController do - let(:user) { create :user, groups:[create(:workgroup, role_article_meta: true)] } + let(:user) { create :user, groups: [create(:workgroup, role_article_meta: true)] } let (:supplier) { create :supplier } let!(:article_category) { create :article_category } before { login user } @@ -28,7 +27,7 @@ feature ArticlesController do fill_in 'article_tax', :with => article.tax fill_in 'article_deposit', :with => article.deposit # "Element cannot be scrolled into view" error, js as workaround - #find('input[type="submit"]').click + # find('input[type="submit"]').click page.execute_script('$("form#new_article").submit();') end expect(page).to have_content(article.name) @@ -52,7 +51,7 @@ feature ArticlesController do expect(find("tr:nth-child(2) #new_articles__name").value).to eq "Pijnboompitten" 4.times do |i| - all("tr:nth-child(#{i+1}) select > option")[1].select_option + all("tr:nth-child(#{i + 1}) select > option")[1].select_option end find('input[type="submit"]').click expect(page).to have_content("Pijnboompitten") diff --git a/spec/integration/balancing_spec.rb b/spec/integration/balancing_spec.rb index 020f33b3..87a7757f 100644 --- a/spec/integration/balancing_spec.rb +++ b/spec/integration/balancing_spec.rb @@ -2,8 +2,8 @@ require_relative '../spec_helper' feature 'settling an order', js: true do let(:ftt) { create :financial_transaction_type } - let(:admin) { create :user, groups:[create(:workgroup, role_finance: true)] } - let(:user) { create :user, groups:[create(:ordergroup)] } + let(:admin) { create :user, groups: [create(:workgroup, role_finance: true)] } + let(:user) { create :user, groups: [create(:ordergroup)] } let(:supplier) { create :supplier } let(:article) { create :article, supplier: supplier, unit_quantity: 1 } let(:order) { create :order, supplier: supplier, article_ids: [article.id] } # need to ref article @@ -95,7 +95,7 @@ feature 'settling an order', js: true do end it 'deletes a GroupOrderArticle with no ordered amounts' do - goa1.update_attributes({:quantity => 0, :tolerance => 0}) + goa1.update_attributes({ :quantity => 0, :tolerance => 0 }) click_link article.name expect(page).to have_selector("#group_order_article_#{goa1.id}") within("#group_order_article_#{goa1.id}") do diff --git a/spec/integration/config_spec.rb b/spec/integration/config_spec.rb index 125b5920..91f376dd 100644 --- a/spec/integration/config_spec.rb +++ b/spec/integration/config_spec.rb @@ -51,13 +51,13 @@ feature 'admin/configs' do end def compact_hash_deep!(h) - h.each do |k,v| + h.each do |k, v| if v.is_a? Hash compact_hash_deep!(v) - v.reject! {|k,v| v.blank?} + v.reject! { |k, v| v.blank? } end end - h.reject! {|k,v| v.blank?} + h.reject! { |k, v| v.blank? } h end end diff --git a/spec/integration/order_spec.rb b/spec/integration/order_spec.rb index 2c8df500..dd768997 100644 --- a/spec/integration/order_spec.rb +++ b/spec/integration/order_spec.rb @@ -1,7 +1,7 @@ require_relative '../spec_helper' feature Order, js: true do - let(:admin) { create :user, groups:[create(:workgroup, role_orders: true)] } + let(:admin) { create :user, groups: [create(:workgroup, role_orders: true)] } let(:article) { create :article, unit_quantity: 1 } let(:order) { create :order, supplier: article.supplier, article_ids: [article.id] } # need to ref article let(:go1) { create :group_order, order: order } @@ -21,7 +21,7 @@ feature Order, js: true do it 'fills in the end date with a schedule' do FoodsoftConfig[:time_zone] = 'UTC' - FoodsoftConfig[:order_schedule] = {ends: {recurr: 'FREQ=MONTHLY;BYMONTHDAY=1', time: '12:00'}} + FoodsoftConfig[:order_schedule] = { ends: { recurr: 'FREQ=MONTHLY;BYMONTHDAY=1', time: '12:00' } } visit new_order_path(supplier_id: article.supplier.id) expect(page).to have_text I18n.t('orders.new.title') expect(find_field('order_ends_time_value').value).to eq '12:00' @@ -40,7 +40,7 @@ feature Order, js: true do it 'can close an order' do setup_and_close_order expect(order).to be_finished - expect(page).to_not have_link I18n.t('orders.index.action_end') + expect(page).not_to have_link I18n.t('orders.index.action_end') expect(oa.units_to_order).to eq 1 end diff --git a/spec/integration/product_distribution_example_spec.rb b/spec/integration/product_distribution_example_spec.rb index ecc8570d..e15642f1 100644 --- a/spec/integration/product_distribution_example_spec.rb +++ b/spec/integration/product_distribution_example_spec.rb @@ -50,10 +50,10 @@ feature 'product distribution', js: true do expect(oa.quantity).to eq(6) expect(oa.tolerance).to eq(1) # Gruppe a bekommt 3 einheiten. - goa_a = oa.group_order_articles.joins(:group_order).where(:group_orders => {:ordergroup_id => user_a.ordergroup.id}).first + goa_a = oa.group_order_articles.joins(:group_order).where(:group_orders => { :ordergroup_id => user_a.ordergroup.id }).first expect(goa_a.result).to eq(3) # gruppe b bekommt 2 einheiten. - goa_b = oa.group_order_articles.joins(:group_order).where(:group_orders => {:ordergroup_id => user_b.ordergroup.id}).first + goa_b = oa.group_order_articles.joins(:group_order).where(:group_orders => { :ordergroup_id => user_b.ordergroup.id }).first expect(goa_b.result).to eq(2) end end diff --git a/spec/integration/receive_spec.rb b/spec/integration/receive_spec.rb index 40106ef4..3b65107e 100644 --- a/spec/integration/receive_spec.rb +++ b/spec/integration/receive_spec.rb @@ -1,7 +1,7 @@ require_relative '../spec_helper' feature 'receiving an order', js: true do - let(:admin) { create :user, groups:[create(:workgroup, role_orders: true)] } + let(:admin) { create :user, groups: [create(:workgroup, role_orders: true)] } let(:supplier) { create :supplier } let(:article) { create :article, supplier: supplier, unit_quantity: 3 } let(:order) { create :order, supplier: supplier, article_ids: [article.id] } # need to ref article @@ -37,53 +37,53 @@ feature 'receiving an order', js: true do before { login admin } it 'has product ordered visible' do - set_quantities [3,0], [0,0] + set_quantities [3, 0], [0, 0] visit receive_order_path(id: order.id) expect(page).to have_content(article.name) expect(page).to have_selector("#order_article_#{oa.id}") end it 'has product not ordered invisible' do - set_quantities [0,0], [0,0] + set_quantities [0, 0], [0, 0] visit receive_order_path(id: order.id) expect(page).to_not have_selector("#order_article_#{oa.id}") end it 'is not received by default' do - set_quantities [3,0], [0,0] + set_quantities [3, 0], [0, 0] visit receive_order_path(id: order.id) expect(find("#order_articles_#{oa.id}_units_received").value).to be_blank end it 'does not change anything when received is ordered' do - set_quantities [2,0], [3,2] + set_quantities [2, 0], [3, 2] visit receive_order_path(id: order.id) fill_in "order_articles_#{oa.id}_units_received", :with => oa.units_to_order find('input[type="submit"]').click expect(page).to have_selector('body') - check_quantities 2, 2, 4 + check_quantities 2, 2, 4 end it 'redistributes properly when received is more' do - set_quantities [2,0], [3,2] + set_quantities [2, 0], [3, 2] visit receive_order_path(id: order.id) fill_in "order_articles_#{oa.id}_units_received", :with => 3 find('input[type="submit"]').click expect(page).to have_selector('body') - check_quantities 3, 2, 5 + check_quantities 3, 2, 5 end it 'redistributes properly when received is less' do - set_quantities [2,0], [3,2] + set_quantities [2, 0], [3, 2] visit receive_order_path(id: order.id) fill_in "order_articles_#{oa.id}_units_received", :with => 1 find('input[type="submit"]').click expect(page).to have_selector('body') - check_quantities 1, 2, 1 + check_quantities 1, 2, 1 end it 'has a locked field when edited elsewhere' do - set_quantities [2,0], [3,2] + set_quantities [2, 0], [3, 2] goa1.result = goa1.result + 1 goa1.save! visit receive_order_path(id: order.id) @@ -91,12 +91,12 @@ feature 'receiving an order', js: true do end it 'leaves locked rows alone when submitted' do - set_quantities [2,0], [3,2] + set_quantities [2, 0], [3, 2] goa1.result = goa1.result + 1 goa1.save! visit receive_order_path(id: order.id) find('input[type="submit"]').click expect(page).to have_selector('body') - check_quantities 2, 3, 4 + check_quantities 2, 3, 4 end end diff --git a/spec/integration/session_spec.rb b/spec/integration/session_spec.rb index 9c1e7af9..0838858d 100644 --- a/spec/integration/session_spec.rb +++ b/spec/integration/session_spec.rb @@ -13,7 +13,7 @@ feature 'the session' do expect(page).to_not have_selector('.alert-error') end it 'does not log me in with wrong password' do - login user.nick, 'XX'+user.password + login user.nick, 'XX' + user.password expect(page).to have_selector('.alert-error') end it 'can log me in using an email address' do @@ -24,5 +24,4 @@ feature 'the session' do expect(page).to_not have_selector('.alert-error') end end - end diff --git a/spec/integration/supplier_spec.rb b/spec/integration/supplier_spec.rb index 10afb6e6..cfd74e87 100644 --- a/spec/integration/supplier_spec.rb +++ b/spec/integration/supplier_spec.rb @@ -1,11 +1,10 @@ -# encoding: utf-8 require_relative '../spec_helper' feature 'supplier' do let(:supplier) { create :supplier } describe 'create new' do - let(:user) { create :user, groups:[create(:workgroup, role_suppliers: true)] } + let(:user) { create :user, groups: [create(:workgroup, role_suppliers: true)] } before { login user } it 'can be created' do diff --git a/spec/lib/bank_account_information_importer_spec.rb b/spec/lib/bank_account_information_importer_spec.rb index 290dba6b..a98441d2 100644 --- a/spec/lib/bank_account_information_importer_spec.rb +++ b/spec/lib/bank_account_information_importer_spec.rb @@ -17,7 +17,7 @@ describe BankTransaction do JSON importer = BankAccountInformationImporter.new(bank_account) - expect{importer.import!(content)}.to raise_error(JSON::ParserError) + expect { importer.import!(content) }.to raise_error(JSON::ParserError) end it 'empty object' do diff --git a/spec/lib/bank_transaction_reference_spec.rb b/spec/lib/bank_transaction_reference_spec.rb index e14944a1..6d5a5490 100644 --- a/spec/lib/bank_transaction_reference_spec.rb +++ b/spec/lib/bank_transaction_reference_spec.rb @@ -92,5 +92,4 @@ describe BankTransactionReference do it 'returns correct value for FS34.56A67.89 with prefix and suffix' do expect(BankTransactionReference.parse('prefix FS34.56A67.89, suffix')).to match({ group: 34, user: 56, parts: { "A" => 67.89 } }) end - end diff --git a/spec/lib/foodsoft_config_spec.rb b/spec/lib/foodsoft_config_spec.rb index 668800e7..be058f38 100644 --- a/spec/lib/foodsoft_config_spec.rb +++ b/spec/lib/foodsoft_config_spec.rb @@ -95,5 +95,4 @@ describe FoodsoftConfig do expect(FoodsoftConfig[:protected]['database']).to eq FoodsoftConfig[:protected][:database] end end - end diff --git a/spec/lib/foodsoft_mail_receiver_spec.rb b/spec/lib/foodsoft_mail_receiver_spec.rb index 5901009e..a154ce62 100644 --- a/spec/lib/foodsoft_mail_receiver_spec.rb +++ b/spec/lib/foodsoft_mail_receiver_spec.rb @@ -1,7 +1,6 @@ require_relative '../spec_helper' describe FoodsoftMailReceiver do - before :all do @server = FoodsoftMailReceiver.new 2525, '127.0.0.1', 4, logger_severity: 5 @server.start @@ -75,5 +74,4 @@ describe FoodsoftMailReceiver do after :all do @server.shutdown end - end diff --git a/spec/lib/token_verifier_spec.rb b/spec/lib/token_verifier_spec.rb index e3e4568e..a5c81d4f 100644 --- a/spec/lib/token_verifier_spec.rb +++ b/spec/lib/token_verifier_spec.rb @@ -6,12 +6,12 @@ describe TokenVerifier do let (:msg) { v.generate } it 'validates' do - expect{ v.verify(msg) }.to_not raise_error + expect { v.verify(msg) }.to_not raise_error end it 'validates when recreated' do v2 = TokenVerifier.new(prefix) - expect{ v2.verify(msg) }.to_not raise_error + expect { v2.verify(msg) }.to_not raise_error end it 'does not validate with a different prefix' do @@ -25,20 +25,19 @@ describe TokenVerifier do begin FoodsoftConfig.scope = Faker::Lorem.words(number: 1) v2 = TokenVerifier.new(prefix) - expect{ v2.verify(msg) }.to raise_error(TokenVerifier::InvalidScope) + expect { v2.verify(msg) }.to raise_error(TokenVerifier::InvalidScope) ensure FoodsoftConfig.scope = oldscope end end it 'does not validate a random string' do - expect{ v.verify(Faker::Lorem.characters(number: 100)) }.to raise_error(ActiveSupport::MessageVerifier::InvalidSignature) + expect { v.verify(Faker::Lorem.characters(number: 100)) }.to raise_error(ActiveSupport::MessageVerifier::InvalidSignature) end it 'returns the message' do - data = [5, {'hi' => :there}, 'bye', []] + data = [5, { 'hi' => :there }, 'bye', []] msg = v.generate(data) expect(v.verify(msg)).to eq data end - end diff --git a/spec/models/article_spec.rb b/spec/models/article_spec.rb index 58453a6a..40201570 100644 --- a/spec/models/article_spec.rb +++ b/spec/models/article_spec.rb @@ -49,7 +49,6 @@ describe Article do expect(article.in_open_order).to eq(order) end - it 'has no shared article by default' do expect(article.shared_article).to be_nil end @@ -72,8 +71,8 @@ describe Article do it 'can be synchronised' do # TODO move article sync from supplier to article article # need to reference for it to exist when syncing - updated_article = supplier.sync_all[0].select{|s| s[0].id==article.id}.first[0] - article.update_attributes updated_article.attributes.reject{|k,v| k=='id' or k=='type'} + updated_article = supplier.sync_all[0].select { |s| s[0].id == article.id }.first[0] + article.update_attributes updated_article.attributes.reject { |k, v| k == 'id' or k == 'type' } expect(article.name).to eq(shared_article.name) # now synchronising shouldn't change anything anymore expect(article.shared_article_changed?).to be_falsey @@ -95,11 +94,11 @@ describe Article do article.shared_updated_on -= 1 # to make update do something article.save! # TODO get sync functionality in article - updated_article = supplier.sync_all[0].select{|s| s[0].id==article.id}.first[0] - article.update_attributes! updated_article.attributes.reject{|k,v| k=='id' or k=='type'} + updated_article = supplier.sync_all[0].select { |s| s[0].id == article.id }.first[0] + article.update_attributes! updated_article.attributes.reject { |k, v| k == 'id' or k == 'type' } expect(article.unit).to eq '200g' expect(article.unit_quantity).to eq 5 - expect(article.price).to be_within(0.005).of(shared_article.price/5) + expect(article.price).to be_within(0.005).of(shared_article.price / 5) end it 'does not synchronise when it has no order number' do diff --git a/spec/models/bank_transaction_spec.rb b/spec/models/bank_transaction_spec.rb index 21d3458f..984d39ae 100644 --- a/spec/models/bank_transaction_spec.rb +++ b/spec/models/bank_transaction_spec.rb @@ -46,7 +46,6 @@ describe BankTransaction do expect(invoice5.paid_on).to eq bank_transaction4.date expect(invoice5.financial_link).to eq bank_transaction4.financial_link end - end describe 'ordergroup' do @@ -102,7 +101,5 @@ describe BankTransaction do it 'ignores transaction with invalid short name' do expect(bank_transaction8.assign_to_ordergroup).to be false end - end - end diff --git a/spec/models/group_order_article_spec.rb b/spec/models/group_order_article_spec.rb index fd47e603..ddb9158a 100644 --- a/spec/models/group_order_article_spec.rb +++ b/spec/models/group_order_article_spec.rb @@ -60,5 +60,4 @@ describe GroupOrderArticle do expect(res).to eq(quantity: 4, tolerance: 0, total: 4) end end - end diff --git a/spec/models/group_order_spec.rb b/spec/models/group_order_spec.rb index d715931c..a2b8a2c5 100644 --- a/spec/models/group_order_spec.rb +++ b/spec/models/group_order_spec.rb @@ -6,13 +6,13 @@ describe GroupOrder do # the following two tests are currently disabled - https://github.com/foodcoops/foodsoft/issues/158 - #it 'needs an order' do - # expect(FactoryBot.build(:group_order, ordergroup: user.ordergroup)).to be_invalid - #end + # it 'needs an order' do + # expect(FactoryBot.build(:group_order, ordergroup: user.ordergroup)).to be_invalid + # end - #it 'needs an ordergroup' do - # expect(FactoryBot.build(:group_order, order: order)).to be_invalid - #end + # it 'needs an ordergroup' do + # expect(FactoryBot.build(:group_order, order: order)).to be_invalid + # end describe do let(:go) { create :group_order, order: order, ordergroup: user.ordergroup } @@ -21,5 +21,4 @@ describe GroupOrder do expect(go.price).to eq(0) end end - end diff --git a/spec/models/order_article_spec.rb b/spec/models/order_article_spec.rb index 07f0db9c..d124678f 100644 --- a/spec/models/order_article_spec.rb +++ b/spec/models/order_article_spec.rb @@ -9,12 +9,10 @@ describe OrderArticle do end [:units_to_order, :units_billed, :units_received].each do |units| - it "is ordered when there are #{units.to_s.gsub '_', ' '}" do oa.update_attribute units, rand(1..99) expect(OrderArticle.ordered.count).to eq 1 end - end it 'knows how many items there are' do @@ -48,7 +46,7 @@ describe OrderArticle do end describe 'redistribution' do - let(:admin) { create :user, groups:[create(:workgroup, role_finance: true)] } + let(:admin) { create :user, groups: [create(:workgroup, role_finance: true)] } let(:article) { create :article, unit_quantity: 3 } let(:order) { create :order, article_ids: [article.id] } let(:go1) { create :group_order, order: order } @@ -74,34 +72,34 @@ describe OrderArticle do end it 'has expected units_to_order' do - set_quantities [3,2], [1,3], [1,0] - expect(oa.units*oa.article.unit_quantity).to eq 6 + set_quantities [3, 2], [1, 3], [1, 0] + expect(oa.units * oa.article.unit_quantity).to eq 6 expect([goa1, goa2, goa3].map(&:result)).to eq [4, 1, 1] end it 'does nothing when nothing has changed' do - set_quantities [3,2], [1,3], [1,0] + set_quantities [3, 2], [1, 3], [1, 0] expect(oa.redistribute 6, [:tolerance, nil]).to eq [1, 0] goa_reload expect([goa1, goa2, goa3].map(&:result).map(&:to_i)).to eq [4, 1, 1] end it 'works when there is nothing to distribute' do - set_quantities [3,2], [1,3], [1,0] + set_quantities [3, 2], [1, 3], [1, 0] expect(oa.redistribute 0, [:tolerance, nil]).to eq [0, 0] goa_reload expect([goa1, goa2, goa3].map(&:result)).to eq [0, 0, 0] end it 'works when quantity needs to be reduced' do - set_quantities [3,2], [1,3], [1,0] + set_quantities [3, 2], [1, 3], [1, 0] expect(oa.redistribute 4, [:tolerance, nil]).to eq [0, 0] goa_reload expect([goa1, goa2, goa3].map(&:result)).to eq [3, 1, 0] end it 'works when quantity is increased within quantity' do - set_quantities [3,0], [2,0], [2,0] + set_quantities [3, 0], [2, 0], [2, 0] expect([goa1, goa2, goa3].map(&:result)).to eq [3, 2, 1] expect(oa.redistribute 7, [:tolerance, nil]).to eq [0, 0] goa_reload @@ -109,26 +107,25 @@ describe OrderArticle do end it 'works when there is just one for the first' do - set_quantities [3,2], [1,3], [1,0] + set_quantities [3, 2], [1, 3], [1, 0] expect(oa.redistribute 1, [:tolerance, nil]).to eq [0, 0] goa_reload expect([goa1, goa2, goa3].map(&:result)).to eq [1, 0, 0] end it 'works when there is tolerance and left-over' do - set_quantities [3,2], [1,1], [1,0] + set_quantities [3, 2], [1, 1], [1, 0] expect(oa.redistribute 10, [:tolerance, nil]).to eq [3, 2] goa_reload expect([goa1, goa2, goa3].map(&:result)).to eq [5, 2, 1] end it 'works when redistributing without tolerance' do - set_quantities [3,2], [1,3], [1,0] + set_quantities [3, 2], [1, 3], [1, 0] expect(oa.redistribute 8, [nil]).to eq [3] goa_reload expect([goa1, goa2, goa3].map(&:result)).to eq [3, 1, 1] end - end describe 'boxfill' do @@ -173,38 +170,37 @@ describe OrderArticle do context 'before the date' do let(:boxfill_from) { 1.hour.from_now } context 'decreasing the missing units' do - include_examples "boxfill", true, [6,0]=>[5,0], [6,0,0]=>[5,0,1] + include_examples "boxfill", true, [6, 0] => [5, 0], [6, 0, 0] => [5, 0, 1] end context 'decreasing the tolerance' do - include_examples "boxfill", true, [1,2]=>[1,1], [1,2,3]=>[1,1,4] + include_examples "boxfill", true, [1, 2] => [1, 1], [1, 2, 3] => [1, 1, 4] end end context 'after the date' do let(:boxfill_from) { 1.second.ago } context 'changing nothing in particular' do - include_examples "boxfill", true, [4,1]=>[4,1], [4,1,1]=>[4,1,1] + include_examples "boxfill", true, [4, 1] => [4, 1], [4, 1, 1] => [4, 1, 1] end context 'increasing missing units' do - include_examples "boxfill", false, [3,0]=>[2,0], [3,0,3]=>[3,0,3] + include_examples "boxfill", false, [3, 0] => [2, 0], [3, 0, 3] => [3, 0, 3] end context 'increasing tolerance' do - include_examples "boxfill", true, [2,1]=>[2,2], [2,1,3]=>[2,2,2] + include_examples "boxfill", true, [2, 1] => [2, 2], [2, 1, 3] => [2, 2, 2] end context 'decreasing quantity to fix missing units' do - include_examples "boxfill", true, [7,0]=>[6,0], [7,0,5]=>[6,0,0] + include_examples "boxfill", true, [7, 0] => [6, 0], [7, 0, 5] => [6, 0, 0] end context 'decreasing quantity keeping missing units equal' do - include_examples "boxfill", false, [7,0]=>[1,0], [7,0,5]=>[7,0,5] + include_examples "boxfill", false, [7, 0] => [1, 0], [7, 0, 5] => [7, 0, 5] end context 'moving tolerance to quantity' do - include_examples "boxfill", true, [4,2]=>[6,0], [4,2,0]=>[6,0,0] + include_examples "boxfill", true, [4, 2] => [6, 0], [4, 2, 0] => [6, 0, 0] end # @todo enable test when tolerance doesn't count in missing_units - #context 'decreasing tolerance' do - # include_examples "boxfill", false, [0,2]=>[0,0], [0,2,0]=>[0,2,0] - #end + # context 'decreasing tolerance' do + # include_examples "boxfill", false, [0,2]=>[0,0], [0,2,0]=>[0,2,0] + # end end end - end diff --git a/spec/models/order_spec.rb b/spec/models/order_spec.rb index b6747cc6..9f84f9c5 100644 --- a/spec/models/order_spec.rb +++ b/spec/models/order_spec.rb @@ -99,7 +99,7 @@ describe Order do it 'is not closed by default' do expect(order).to_not be_closed end it 'has valid order articles' do - order.order_articles.each {|oa| expect(oa).to be_valid } + order.order_articles.each { |oa| expect(oa).to be_valid } end it 'can be finished' do @@ -117,13 +117,12 @@ describe Order do expect(order).to_not be_open expect(order).to be_closed end - end describe 'with a default end date' do let(:order) { create :order } before do - FoodsoftConfig[:order_schedule] = {ends: {recurr: 'FREQ=WEEKLY;BYDAY=MO', time: '9:00'}} + FoodsoftConfig[:order_schedule] = { ends: { recurr: 'FREQ=WEEKLY;BYDAY=MO', time: '9:00' } } order.init_dates end @@ -134,7 +133,6 @@ describe Order do it 'to have a correct time' do expect(order.ends.strftime('%H:%M')).to eq '09:00' end - end describe 'mapped to GroupOrders' do @@ -153,5 +151,4 @@ describe Order do expect(orders[1][:group_order]).to be_nil end end - end diff --git a/spec/models/ordergroup_spec.rb b/spec/models/ordergroup_spec.rb index 07ab3d94..6ac58fd5 100644 --- a/spec/models/ordergroup_spec.rb +++ b/spec/models/ordergroup_spec.rb @@ -6,7 +6,7 @@ describe Ordergroup do let(:ftt1) { create :financial_transaction_type, financial_transaction_class: ftc1 } let(:ftt2) { create :financial_transaction_type, financial_transaction_class: ftc2 } let(:ftt3) { create :financial_transaction_type, financial_transaction_class: ftc2 } - let(:user) { create :user, groups:[create(:ordergroup)] } + let(:user) { create :user, groups: [create(:ordergroup)] } context 'with financial transactions' do before do diff --git a/spec/models/supplier_spec.rb b/spec/models/supplier_spec.rb index 6b0f4a88..72e870ed 100644 --- a/spec/models/supplier_spec.rb +++ b/spec/models/supplier_spec.rb @@ -10,7 +10,7 @@ describe Supplier do it 'has valid articles' do supplier = create :supplier, article_count: true - supplier.articles.each {|a| expect(a).to be_valid } + supplier.articles.each { |a| expect(a).to be_valid } end context 'connected to a shared supplier' do @@ -91,5 +91,4 @@ describe Supplier do end end end - end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 6bafe37e..c90e554a 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -1,11 +1,10 @@ require_relative '../spec_helper' describe User do - it 'is correctly created' do user = create :user, - nick: 'johnnydoe', first_name: 'Johnny', last_name: 'DoeBar', - email: 'johnnydoe@foodcoop.test', phone: '+1234567890' + nick: 'johnnydoe', first_name: 'Johnny', last_name: 'DoeBar', + email: 'johnnydoe@foodcoop.test', phone: '+1234567890' expect(user.nick).to eq('johnnydoe') expect(user.first_name).to eq('Johnny') expect(user.last_name).to eq('DoeBar') @@ -71,5 +70,4 @@ describe User do let(:user) { create :admin } it 'default admin role' do expect(user.role_admin?).to be_truthy end end - end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 1bf89702..88dea423 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -10,9 +10,9 @@ require 'capybara/apparition' Capybara.server = :puma, { Silent: true } Capybara.javascript_driver = :apparition -#TODO: Remove temporary fix to ignore JavaScript errors +# TODO: Remove temporary fix to ignore JavaScript errors Capybara.register_driver :apparition do |app| - Capybara::Apparition::Driver.new(app, {js_errors: false}) + Capybara::Apparition::Driver.new(app, { js_errors: false }) end # Requires supporting ruby files with custom matchers and macros, etc, @@ -70,7 +70,7 @@ end # include default foodsoft scope in urls, so that *_path works # https://github.com/rspec/rspec-rails/issues/255 class ActionDispatch::Routing::RouteSet - def default_url_options(options={}) - {foodcoop: FoodsoftConfig.scope}.merge(options) + def default_url_options(options = {}) + { foodcoop: FoodsoftConfig.scope }.merge(options) end end diff --git a/spec/support/api_helper.rb b/spec/support/api_helper.rb index 66f9bd95..65acc75b 100644 --- a/spec/support/api_helper.rb +++ b/spec/support/api_helper.rb @@ -7,14 +7,14 @@ module ApiHelper let(:api_access_token) { create(:oauth2_access_token, resource_owner_id: user.id, scopes: api_scopes&.join(' ')).token } let(:api_authorization) { "Bearer #{api_access_token}" } - def self.it_handles_invalid_token(method, path, params_block = ->{ api_auth }) + def self.it_handles_invalid_token(method, path, params_block = -> { api_auth }) context 'with invalid access token' do let(:api_access_token) { 'abc' } it { is_expected.to validate(method, path, 401, instance_exec(¶ms_block)) } end end - def self.it_handles_invalid_scope(method, path, params_block = ->{ api_auth }) + def self.it_handles_invalid_scope(method, path, params_block = -> { api_auth }) context 'with invalid scope' do let(:api_scopes) { ['none'] } it { is_expected.to validate(method, path, 403, instance_exec(¶ms_block)) } @@ -32,7 +32,6 @@ module ApiHelper # @return Query parameters with authentication header # @see Swagger::RspecHelpers#validate def api_auth(params = {}) - {'_headers' => {'Authorization' => api_authorization }}.deep_merge(params) + { '_headers' => { 'Authorization' => api_authorization } }.deep_merge(params) end - end diff --git a/spec/support/faker.rb b/spec/support/faker.rb index a2493870..47441ca8 100644 --- a/spec/support/faker.rb +++ b/spec/support/faker.rb @@ -7,4 +7,3 @@ module Faker end end end - diff --git a/spec/support/integration.rb b/spec/support/integration.rb index 0d63f36b..26add35a 100644 --- a/spec/support/integration.rb +++ b/spec/support/integration.rb @@ -1,4 +1,3 @@ - # @see http://stackoverflow.com/a/11048669/2866660 def scrolldown page.execute_script "window.scrollBy(0,10000)" diff --git a/spec/support/session_helper.rb b/spec/support/session_helper.rb index b832e772..31fb0946 100644 --- a/spec/support/session_helper.rb +++ b/spec/support/session_helper.rb @@ -1,7 +1,5 @@ - module SessionHelper - - def login(user=nil, password=nil) + def login(user = nil, password = nil) visit login_path user = FactoryBot.create :user if user.nil? if user.instance_of? ::User @@ -13,5 +11,4 @@ module SessionHelper fill_in 'password', :with => password find('input[type=submit]').click end - end diff --git a/spec/support/shared_database.rb b/spec/support/shared_database.rb index bbe3a314..f6c0ff0a 100644 --- a/spec/support/shared_database.rb +++ b/spec/support/shared_database.rb @@ -12,6 +12,7 @@ ActiveSupport.on_load(:after_initialize) do def category ArticleCategory.where(id: article_category_id).first end + def self.find_by_number(n) find_by_order_number(n) end