From 377fa8cb4e7276f40aba4838778a448c35ad2a05 Mon Sep 17 00:00:00 2001 From: Philipp Rothmann Date: Fri, 26 Jan 2024 17:47:30 +0100 Subject: [PATCH] chore: rubocop -a --regenerate-todo --- .rubocop.yml | 2 + .rubocop_todo.yml | 1741 ++++++----------- Rakefile | 2 +- .../admin/bank_accounts_controller.rb | 26 +- .../admin/bank_gateways_controller.rb | 10 +- app/controllers/admin/configs_controller.rb | 26 +- app/controllers/admin/finances_controller.rb | 6 +- ...inancial_transaction_classes_controller.rb | 20 +- .../financial_transaction_types_controller.rb | 20 +- .../admin/mail_delivery_status_controller.rb | 12 +- .../admin/ordergroups_controller.rb | 13 +- app/controllers/admin/users_controller.rb | 18 +- .../admin/workgroups_controller.rb | 8 +- app/controllers/api/v1/articles_controller.rb | 15 +- app/controllers/api/v1/base_controller.rb | 35 +- .../user/financial_transactions_controller.rb | 3 +- .../user/group_order_articles_controller.rb | 7 +- .../api/v1/user/ordergroup_controller.rb | 4 +- app/controllers/application_controller.rb | 18 +- .../article_categories_controller.rb | 8 +- app/controllers/article_units_controller.rb | 8 +- app/controllers/articles_controller.rb | 162 +- app/controllers/concerns/auth.rb | 38 +- app/controllers/concerns/auth_api.rb | 14 +- app/controllers/concerns/foodcoop_scope.rb | 4 +- app/controllers/concerns/locale.rb | 12 +- app/controllers/concerns/send_order_pdf.rb | 2 +- app/controllers/deliveries_controller.rb | 20 +- app/controllers/feedback_controller.rb | 7 +- .../finance/balancing_controller.rb | 40 +- .../finance/bank_accounts_controller.rb | 8 +- .../finance/bank_transactions_controller.rb | 30 +- .../finance/financial_links_controller.rb | 14 +- .../financial_transactions_controller.rb | 78 +- .../finance/invoices_controller.rb | 30 +- .../finance/ordergroups_controller.rb | 4 +- .../foodcoop/ordergroups_controller.rb | 10 +- app/controllers/foodcoop/users_controller.rb | 7 +- .../foodcoop/workgroups_controller.rb | 8 +- .../group_order_articles_controller.rb | 4 +- app/controllers/group_orders_controller.rb | 70 +- app/controllers/home_controller.rb | 54 +- app/controllers/invites_controller.rb | 8 +- app/controllers/login_controller.rb | 23 +- app/controllers/order_articles_controller.rb | 23 +- app/controllers/order_comments_controller.rb | 6 +- app/controllers/orders_controller.rb | 91 +- app/controllers/sessions_controller.rb | 6 +- app/controllers/stock_takings_controller.rb | 12 +- app/controllers/stockit_controller.rb | 45 +- app/controllers/styles_controller.rb | 2 +- app/controllers/suppliers_controller.rb | 10 +- app/controllers/tasks_controller.rb | 50 +- app/controllers/users_controller.rb | 2 +- app/documents/order_by_articles.rb | 13 +- app/documents/order_by_groups.rb | 6 +- app/documents/order_fax.rb | 39 +- app/documents/order_matrix.rb | 10 +- app/helpers/admin/configs_helper.rb | 19 +- app/helpers/admin/ordergroups_helper.rb | 4 +- app/helpers/application_helper.rb | 86 +- app/helpers/articles_helper.rb | 13 +- app/helpers/deliveries_helper.rb | 18 +- app/helpers/finance/balancing_helper.rb | 6 +- app/helpers/finance/invoices_helper.rb | 4 +- app/helpers/group_order_articles_helper.rb | 21 +- app/helpers/group_orders_helper.rb | 25 +- app/helpers/orders_helper.rb | 68 +- app/helpers/stockit_helper.rb | 10 +- app/helpers/tasks_helper.rb | 12 +- app/inputs/delta_input.rb | 5 +- app/mailers/mailer.rb | 18 +- app/models/article.rb | 144 +- app/models/article_category.rb | 21 +- app/models/article_unit.rb | 6 +- app/models/article_unit_ratio.rb | 4 +- app/models/article_version.rb | 57 +- app/models/bank_account.rb | 14 +- app/models/bank_gateway.rb | 2 +- app/models/bank_transaction.rb | 12 +- app/models/concerns/custom_fields.rb | 2 +- app/models/concerns/find_each_with_order.rb | 4 +- .../concerns/mark_as_deleted_with_name.rb | 2 +- app/models/concerns/price_calculation.rb | 16 +- app/models/delivery.rb | 12 +- app/models/financial_link.rb | 4 +- app/models/financial_transaction.rb | 20 +- app/models/financial_transaction_class.rb | 2 +- app/models/financial_transaction_type.rb | 10 +- app/models/group.rb | 6 +- app/models/group_order.rb | 61 +- app/models/group_order_article.rb | 73 +- app/models/group_order_article_quantity.rb | 2 +- app/models/invite.rb | 20 +- app/models/invoice.rb | 36 +- app/models/membership.rb | 2 +- app/models/order.rb | 160 +- app/models/order_article.rb | 85 +- app/models/order_comment.rb | 4 +- app/models/ordergroup.rb | 52 +- app/models/periodic_task_group.rb | 14 +- app/models/stock_article.rb | 6 +- app/models/stock_change.rb | 6 +- app/models/stock_event.rb | 2 +- app/models/supplier.rb | 82 +- app/models/task.rb | 48 +- app/models/user.rb | 102 +- app/models/workgroup.rb | 18 +- bin/autospec | 4 +- bin/mailcatcher | 4 +- bin/resque | 4 +- bin/resque-web | 4 +- bin/rspec | 4 +- bin/yarn | 12 +- config.ru | 2 +- config/application.rb | 16 +- config/environments/production.rb | 21 +- config/initializers/currency_display.rb | 7 +- config/initializers/doorkeeper.rb | 8 +- config/initializers/exception_notification.rb | 8 +- config/initializers/extensions.rb | 6 +- config/initializers/rack.rb | 2 +- config/initializers/rails6_backports.rb | 6 +- config/initializers/ruby_units.rb | 14 +- config/initializers/secret_token.rb | 10 +- config/initializers/session_store.rb | 2 +- config/initializers/simple_form_bootstrap.rb | 4 +- config/navigation.rb | 31 +- config/puma.rb | 10 +- config/routes.rb | 54 +- config/schedule.rb | 16 +- config/spring.rb | 4 +- db/migrate/001_create_users.rb | 30 +- db/migrate/002_create_groups.rb | 33 +- db/migrate/003_create_suppliers.rb | 20 +- db/migrate/004_create_article_meta.rb | 12 +- .../005_create_financial_transactions.rb | 18 +- db/migrate/006_create_articles.rb | 28 +- db/migrate/007_create_article_prices.rb | 22 +- db/migrate/008_create_orders.rb | 92 +- db/migrate/009_create_order_results.rb | 34 +- db/migrate/011_create_comments.rb | 18 +- db/migrate/012_create_order_clearing.rb | 6 +- db/migrate/013_add_messaging.rb | 14 +- db/migrate/014_create_tasks.rb | 20 +- db/migrate/015_change_result_quantities.rb | 8 +- db/migrate/018_create_invites.rb | 10 +- .../019_remove_uniqueness_of_article_name.rb | 6 +- db/migrate/021_remove_table_article_prices.rb | 86 +- db/migrate/022_add_required_user_for_task.rb | 4 +- db/migrate/024_add_deposit_defaults.rb | 3 +- db/migrate/025_extend_comments.rb | 4 +- .../20090120184410_road_to_version_three.rb | 62 +- .../20090317175355_add_profit_to_orders.rb | 2 +- ...75756_create_pages.foodsoft_wiki_engine.rb | 2 +- ...31156_modify_group_order_article_result.rb | 2 +- .../20090907120012_add_missing_indexes.rb | 39 +- .../20110507184920_add_duration_to_tasks.rb | 2 +- ...7192928_add_task_duration_to_workgroups.rb | 2 +- ..._next_weekly_tasks_number_to_workgroups.rb | 2 +- .../20130622095040_move_weekly_tasks.rb | 30 +- ...0130702113610_update_group_order_totals.rb | 17 +- db/migrate/20130718183100_create_settings.rb | 2 +- .../20130718183101_migrate_user_settings.rb | 7 +- .../20130920201529_allow_missing_nick.rb | 4 +- ...result_computed_to_group_order_articles.rb | 2 +- ...73000_delete_empty_group_order_articles.rb | 3 +- ...20140921104907_remove_stale_memberships.rb | 2 +- ...160217194036_add_role_invoices_to_group.rb | 2 +- ...0160218151041_add_attachment_to_invoice.rb | 2 +- ...e_financial_transaction_class_and_types.rb | 8 +- .../20160224201529_allow_stock_group_order.rb | 4 +- ...ail_to_message.foodsoft_messages_engine.rb | 2 +- ...70801000000_create_mail_delivery_status.rb | 4 +- .../20171002000000_create_financial_links.rb | 6 +- ...0000_create_polls.foodsoft_polls_engine.rb | 4 +- ...ease_choices_size.foodsoft_polls_engine.rb | 2 +- ...te_printer_jobs.foodsoft_printer_engine.rb | 2 +- ...te_message_recipients.foodsoft_messages.rb | 2 +- ...te_active_storage_tables.active_storage.rb | 2 +- ...0257_introduce_received_state_in_orders.rb | 2 +- ...026102300_alter_articles_add_versioning.rb | 56 +- ...2301_alter_articles_add_more_unit_logic.rb | 8 +- db/schema.rb | 1109 ++++++----- db/seeds/hackathon.seeds.rb | 205 +- db/seeds/hackathon_de.seeds.rb | 202 +- db/seeds/minimal.seeds.rb | 36 +- db/seeds/seed_helper.rb | 4 +- db/seeds/small.en.seeds.rb | 457 +++-- db/seeds/small.nl.seeds.rb | 457 +++-- ...204112447_create_articles_and_suppliers.rb | 86 +- db_shared/schema.rb | 90 +- lib/apple_bar.rb | 14 +- lib/article_units_lib.rb | 32 +- lib/articles_csv.rb | 8 +- lib/bank_account_connector.rb | 30 +- lib/bank_account_information_importer.rb | 6 +- lib/bank_transaction_reference.rb | 2 +- lib/date_time_attribute_validate.rb | 58 +- lib/foodsoft/expansion_variables.rb | 6 +- lib/foodsoft_config.rb | 27 +- lib/foodsoft_date_util.rb | 10 +- lib/foodsoft_file.rb | 39 +- lib/foodsoft_mail_receiver.rb | 28 +- lib/invoices_csv.rb | 2 +- lib/order_csv.rb | 3 +- lib/order_pdf.rb | 20 +- lib/order_txt.rb | 17 +- lib/ordergroups_csv.rb | 4 +- lib/render_csv.rb | 4 +- lib/render_pdf.rb | 6 +- lib/tasks/db_shared.rake | 6 +- lib/tasks/foodsoft.rake | 64 +- lib/tasks/foodsoft_setup.rake | 85 +- lib/tasks/multicoops.rake | 24 +- lib/tasks/resque.rake | 26 +- lib/tasks/rspec.rake | 2 +- lib/tasks/temp_export_supplier.rake | 8 +- lib/tasks/units.rake | 29 +- lib/token_verifier.rb | 10 +- .../current_orders/articles_controller.rb | 8 +- .../current_orders/group_orders_controller.rb | 12 +- .../current_orders/ordergroups_controller.rb | 8 +- .../documents/multiple_orders_by_articles.rb | 12 +- .../documents/multiple_orders_by_groups.rb | 14 +- .../app/helpers/current_orders_helper.rb | 3 +- plugins/current_orders/config/routes.rb | 8 +- .../foodsoft_current_orders.gemspec | 23 +- .../lib/foodsoft_current_orders.rb | 4 +- .../lib/foodsoft_current_orders/engine.rb | 11 +- .../lib/foodsoft_current_orders/version.rb | 2 +- plugins/discourse/Rakefile | 4 +- .../app/controllers/discourse_controller.rb | 4 +- .../controllers/discourse_login_controller.rb | 6 +- .../controllers/discourse_sso_controller.rb | 4 +- plugins/discourse/foodsoft_discourse.gemspec | 24 +- .../foodsoft_discourse/redirect_to_login.rb | 4 +- .../lib/foodsoft_discourse/version.rb | 2 +- plugins/documents/Rakefile | 4 +- .../app/controllers/documents_controller.rb | 30 +- plugins/documents/foodsoft_documents.gemspec | 26 +- .../lib/foodsoft_documents/engine.rb | 6 +- .../lib/foodsoft_documents/version.rb | 2 +- plugins/links/Rakefile | 4 +- .../app/controllers/admin/links_controller.rb | 4 +- .../links/app/controllers/links_controller.rb | 10 +- plugins/links/foodsoft_links.gemspec | 24 +- plugins/links/lib/foodsoft_links/engine.rb | 20 +- plugins/links/lib/foodsoft_links/version.rb | 2 +- plugins/messages/Rakefile | 4 +- .../admin/messagegroups_controller.rb | 6 +- .../controllers/messagegroups_controller.rb | 6 +- .../app/controllers/messages_controller.rb | 39 +- .../messages/app/helpers/messages_helper.rb | 6 +- .../mail_receivers/messages_mail_receiver.rb | 46 +- plugins/messages/app/models/message.rb | 38 +- .../messages/app/models/message_recipient.rb | 2 +- plugins/messages/app/models/messagegroup.rb | 2 - plugins/messages/config/routes.rb | 4 +- .../20160226000000_add_email_to_message.rb | 2 +- plugins/messages/foodsoft_messages.gemspec | 32 +- plugins/messages/lib/foodsoft_messages.rb | 8 +- .../messages/lib/foodsoft_messages/engine.rb | 19 +- .../lib/foodsoft_messages/user_link.rb | 4 +- .../messages/lib/foodsoft_messages/version.rb | 2 +- plugins/polls/Rakefile | 4 +- .../polls/app/controllers/polls_controller.rb | 40 +- .../db/migrate/20181110000000_create_polls.rb | 4 +- .../20181120000000_increase_choices_size.rb | 2 +- plugins/polls/foodsoft_polls.gemspec | 24 +- plugins/polls/lib/foodsoft_polls/engine.rb | 6 +- plugins/polls/lib/foodsoft_polls/version.rb | 2 +- plugins/printer/Rakefile | 4 +- .../app/controllers/printer_controller.rb | 7 +- .../controllers/printer_jobs_controller.rb | 6 +- plugins/printer/config/routes.rb | 2 +- .../20181201000000_create_printer_jobs.rb | 2 +- plugins/printer/foodsoft_printer.gemspec | 26 +- .../printer/lib/foodsoft_printer/engine.rb | 13 +- .../foodsoft_printer/order_printer_jobs.rb | 10 +- .../printer/lib/foodsoft_printer/version.rb | 2 +- plugins/uservoice/foodsoft_uservoice.gemspec | 23 +- plugins/uservoice/lib/foodsoft_uservoice.rb | 10 +- .../lib/foodsoft_uservoice/version.rb | 2 +- plugins/wiki/Rakefile | 4 +- .../wiki/app/controllers/pages_controller.rb | 82 +- plugins/wiki/app/helpers/pages_helper.rb | 60 +- plugins/wiki/app/models/page.rb | 59 +- plugins/wiki/app/views/pages/all.rss.builder | 10 +- plugins/wiki/config/routes.rb | 10 +- .../db/migrate/20090325175756_create_pages.rb | 2 +- plugins/wiki/foodsoft_wiki.gemspec | 26 +- plugins/wiki/lib/foodsoft_wiki/engine.rb | 10 +- plugins/wiki/lib/foodsoft_wiki/mailer.rb | 10 +- plugins/wiki/lib/foodsoft_wiki/version.rb | 2 +- plugins/wiki/lib/foodsoft_wiki/wiki_parser.rb | 8 +- script/rails | 4 +- spec/api/v1/order_articles_spec.rb | 22 +- spec/api/v1/swagger_spec.rb | 138 +- .../v1/user/financial_transactions_spec.rb | 62 +- spec/api/v1/user/group_order_articles_spec.rb | 145 +- spec/api/v1/user/ordergroup_spec.rb | 24 +- spec/factories/article.rb | 5 +- spec/factories/article_version.rb | 3 +- spec/factories/doorkeeper.rb | 4 +- spec/factories/group_order.rb | 2 +- spec/factories/invoice.rb | 4 +- spec/factories/order.rb | 6 +- spec/factories/supplier.rb | 2 +- spec/factories/user.rb | 20 +- spec/integration/articles_spec.rb | 58 +- spec/integration/balancing_spec.rb | 86 +- spec/integration/config_spec.rb | 10 +- spec/integration/login_spec.rb | 23 +- spec/integration/order_spec.rb | 18 +- .../product_distribution_example_spec.rb | 24 +- spec/integration/receive_spec.rb | 36 +- spec/integration/session_spec.rb | 19 +- spec/integration/supplier_spec.rb | 17 +- .../bank_account_information_importer_spec.rb | 31 +- spec/lib/bank_transaction_reference_spec.rb | 48 +- spec/lib/foodsoft_config_spec.rb | 2 +- spec/lib/foodsoft_mail_receiver_spec.rb | 82 +- spec/lib/token_verifier_spec.rb | 14 +- spec/models/article_spec.rb | 36 +- spec/models/bank_transaction_spec.rb | 70 +- spec/models/group_order_article_spec.rb | 42 +- spec/models/group_order_spec.rb | 6 +- spec/models/order_article_spec.rb | 80 +- spec/models/order_spec.rb | 84 +- spec/models/ordergroup_spec.rb | 12 +- spec/models/supplier_spec.rb | 32 +- spec/models/user_spec.rb | 46 +- .../api/v1/order_articles_controller_spec.rb | 115 ++ .../v1/user/financial_transactions_spec.rb | 109 ++ spec/spec_helper.rb | 16 +- spec/support/api_helper.rb | 6 +- spec/support/api_oauth.rb | 2 +- spec/support/coverage.rb | 26 +- spec/support/faker.rb | 4 +- spec/support/integration.rb | 2 +- spec/support/session_helper.rb | 9 +- 342 files changed, 5814 insertions(+), 5376 deletions(-) mode change 100644 => 100755 Rakefile mode change 100644 => 100755 plugins/discourse/Rakefile mode change 100644 => 100755 plugins/documents/Rakefile mode change 100644 => 100755 plugins/links/Rakefile mode change 100644 => 100755 plugins/messages/Rakefile mode change 100644 => 100755 plugins/polls/Rakefile mode change 100644 => 100755 plugins/printer/Rakefile mode change 100644 => 100755 plugins/wiki/Rakefile create mode 100644 spec/requests/api/v1/order_articles_controller_spec.rb create mode 100644 spec/requests/api/v1/user/financial_transactions_spec.rb diff --git a/.rubocop.yml b/.rubocop.yml index 42be2b6c..9a529428 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -3,6 +3,8 @@ inherit_from: .rubocop_todo.yml require: - rubocop-rails - rubocop-rspec + - rubocop-capybara + - rubocop-factory_bot AllCops: NewCops: enable diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 5fc56b78..1d011fa1 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,37 +1,60 @@ # This configuration was generated by # `rubocop --auto-gen-config` -# on 2022-02-05 12:00:00 UTC using RuboCop version 1.25.1. +# on 2024-03-15 10:33:02 UTC using RuboCop version 1.60.2. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. -# Offense count: 28 -# Cop supports --auto-correct. -# Configuration parameters: TreatCommentsAsGroupSeparators, ConsiderPunctuation, Include. -# Include: **/*.gemfile, **/Gemfile, **/gems.rb -Bundler/OrderedGems: +# Offense count: 13 +# Configuration parameters: EnforcedStyle. +# SupportedStyles: link_or_button, strict +Capybara/ClickLinkOrButtonStyle: Exclude: - - 'Gemfile' + - 'spec/integration/balancing_spec.rb' -# Offense count: 9 -# Cop supports --auto-correct. +# Offense count: 3 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: DefaultSelector. +Capybara/RSpec/HaveSelector: + Exclude: + - 'spec/integration/product_distribution_example_spec.rb' + +# Offense count: 4 +Capybara/SpecificMatcher: + Exclude: + - 'spec/integration/login_spec.rb' + - 'spec/integration/session_spec.rb' + +# Offense count: 5 # Configuration parameters: Include. -# Include: **/*.gemspec -Gemspec/RequireMFA: +# Include: **/*_spec.rb, **/spec/**/*, **/test/**/*, **/features/support/factories/**/*.rb +FactoryBot/FactoryAssociationWithStrategy: + Exclude: + - 'spec/factories/group_order.rb' + - 'spec/factories/invoice.rb' + - 'spec/factories/order.rb' + +# Offense count: 2 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: Include. +# Include: **/*_spec.rb, **/spec/**/*, **/test/**/*, **/features/support/factories/**/*.rb +FactoryBot/SyntaxMethods: + Exclude: + - 'spec/integration/articles_spec.rb' + - 'spec/models/article_spec.rb' + +# Offense count: 2 +# Configuration parameters: EnforcedStyle, AllowedGems, Include. +# SupportedStyles: Gemfile, gems.rb, gemspec +# Include: **/*.gemspec, **/Gemfile, **/gems.rb +Gemspec/DevelopmentDependencies: Exclude: - - 'plugins/current_orders/foodsoft_current_orders.gemspec' - - 'plugins/discourse/foodsoft_discourse.gemspec' - - 'plugins/documents/foodsoft_documents.gemspec' - - 'plugins/links/foodsoft_links.gemspec' - 'plugins/messages/foodsoft_messages.gemspec' - - 'plugins/polls/foodsoft_polls.gemspec' - - 'plugins/printer/foodsoft_printer.gemspec' - - 'plugins/uservoice/foodsoft_uservoice.gemspec' - 'plugins/wiki/foodsoft_wiki.gemspec' # Offense count: 9 -# Configuration parameters: Include. +# Configuration parameters: Severity, Include. # Include: **/*.gemspec Gemspec/RequiredRubyVersion: Exclude: @@ -45,69 +68,200 @@ Gemspec/RequiredRubyVersion: - 'plugins/uservoice/foodsoft_uservoice.gemspec' - 'plugins/wiki/foodsoft_wiki.gemspec' -# Offense count: 8 -# Configuration parameters: IgnoredMethods. -Lint/AmbiguousBlockAssociation: +# Offense count: 379 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, IndentationWidth. +# SupportedStyles: with_first_argument, with_fixed_indentation +Layout/ArgumentAlignment: + Enabled: false + +# Offense count: 7 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, IndentationWidth. +# SupportedStyles: with_first_element, with_fixed_indentation +Layout/ArrayAlignment: Exclude: - - 'lib/foodsoft/expansion_variables.rb' - - 'spec/api/v1/user/financial_transactions_spec.rb' - - 'spec/api/v1/user/group_order_articles_spec.rb' - - 'spec/models/article_spec.rb' + - 'app/controllers/articles_controller.rb' + - 'app/controllers/stockit_controller.rb' + - 'app/helpers/group_orders_helper.rb' + - 'app/models/article.rb' + - 'app/models/order.rb' + - 'plugins/wiki/app/models/page.rb' -# Offense count: 4 -# Cop supports --auto-correct. -Lint/AmbiguousOperator: +# Offense count: 7 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: IndentationWidth. +Layout/AssignmentIndentation: Exclude: - 'app/mailers/mailer.rb' - - 'spec/models/order_article_spec.rb' + - 'config/environments/production.rb' + - 'lib/article_units_lib.rb' + - 'spec/models/article_spec.rb' + +# Offense count: 54 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyleAlignWith. +# SupportedStylesAlignWith: either, start_of_block, start_of_line +Layout/BlockAlignment: + Enabled: false + +# Offense count: 54 +# This cop supports safe autocorrection (--autocorrect). +Layout/BlockEndNewline: + Enabled: false + +# Offense count: 9 +# This cop supports safe autocorrection (--autocorrect). +Layout/ClosingParenthesisIndentation: + Exclude: + - 'app/documents/order_by_articles.rb' + - 'app/models/group_order.rb' + - 'app/models/group_order_article.rb' + - 'lib/article_units_lib.rb' + - 'lib/order_pdf.rb' # Offense count: 4 -# Cop supports --auto-correct. -Lint/AmbiguousOperatorPrecedence: +# This cop supports safe autocorrection (--autocorrect). +Layout/ElseAlignment: Exclude: - - 'app/models/concerns/price_calculation.rb' - - 'db/seeds/seed_helper.rb' - - 'plugins/messages/app/mail_receivers/messages_mail_receiver.rb' - - 'plugins/wiki/app/helpers/pages_helper.rb' + - 'app/helpers/group_order_articles_helper.rb' + - 'app/helpers/orders_helper.rb' + - 'app/models/group_order.rb' + +# Offense count: 5 +# This cop supports safe autocorrection (--autocorrect). +Layout/EmptyLineAfterGuardClause: + Exclude: + - 'app/models/article_category.rb' + - 'app/models/invoice.rb' + - 'app/models/order.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +Layout/EmptyLines: + Exclude: + - 'app/models/invoice.rb' + +# Offense count: 5 +# This cop supports safe autocorrection (--autocorrect). +Layout/EmptyLinesAroundMethodBody: + Exclude: + - 'app/models/article_category.rb' + - 'app/models/invoice.rb' + - 'app/models/order.rb' + +# Offense count: 5 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyleAlignWith, Severity. +# SupportedStylesAlignWith: keyword, variable, start_of_line +Layout/EndAlignment: + Exclude: + - 'app/helpers/group_order_articles_helper.rb' + - 'app/helpers/orders_helper.rb' + - 'app/models/group_order.rb' + +# Offense count: 9 +# This cop supports safe autocorrection (--autocorrect). +# 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/documents/order_by_articles.rb' + - 'app/models/group_order.rb' + - 'app/models/group_order_article.rb' + - 'lib/article_units_lib.rb' + - 'lib/order_pdf.rb' # Offense count: 2 -# Cop supports --auto-correct. -Lint/AmbiguousRegexpLiteral: +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, IndentationWidth. +# SupportedStyles: special_inside_parentheses, consistent, align_brackets +Layout/FirstArrayElementIndentation: + Exclude: + - 'app/controllers/articles_controller.rb' + +# Offense count: 421 +# This cop supports safe autocorrection (--autocorrect). +# 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: 2 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: normal, indented_internal_methods +Layout/IndentationConsistency: Exclude: - 'app/models/article_category.rb' - - 'lib/foodsoft/expansion_variables.rb' + - 'app/models/order.rb' + +# Offense count: 115 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: Width, AllowedPatterns. +Layout/IndentationWidth: + Enabled: false + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: symmetrical, new_line, same_line +Layout/MultilineArrayBraceLayout: + Exclude: + - 'app/controllers/articles_controller.rb' + +# Offense count: 8 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: symmetrical, new_line, same_line +Layout/MultilineMethodCallBraceLayout: + Exclude: + - 'app/documents/order_by_articles.rb' + - 'app/models/group_order.rb' + - 'app/models/group_order_article.rb' + - 'lib/article_units_lib.rb' + - 'lib/order_pdf.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, IndentationWidth. +# SupportedStyles: with_first_parameter, with_fixed_indentation +Layout/ParameterAlignment: + Exclude: + - 'app/helpers/orders_helper.rb' + +# Offense count: 320 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowInHeredoc. +Layout/TrailingWhitespace: + Enabled: false # Offense count: 40 +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: AllowSafeAssignment. Lint/AssignmentInCondition: Enabled: false -# Offense count: 3 -# Cop supports --auto-correct. -Lint/BigDecimalNew: +# Offense count: 1 +Lint/BinaryOperatorWithIdenticalOperands: Exclude: - - 'app/models/group_order.rb' - - 'config/initializers/extensions.rb' + - 'app/helpers/orders_helper.rb' # Offense count: 1 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). Lint/BooleanSymbol: Exclude: - 'app/models/delivery.rb' -# Offense count: 2 -# Cop supports --auto-correct. -Lint/DeprecatedClassMethods: - Exclude: - - 'config/initializers/secret_token.rb' - - 'lib/tasks/foodsoft_setup.rake' - -# Offense count: 3 +# Offense count: 4 # Configuration parameters: IgnoreLiteralBranches, IgnoreConstantBranches. Lint/DuplicateBranch: Exclude: - 'app/controllers/concerns/auth_api.rb' - 'app/controllers/orders_controller.rb' + - 'plugins/wiki/app/controllers/pages_controller.rb' # Offense count: 3 Lint/DuplicateMethods: @@ -123,25 +277,35 @@ Lint/EmptyBlock: - 'spec/factories/group_order_article_quantity.rb' # Offense count: 1 -# Cop supports --auto-correct. +# Configuration parameters: AllowComments. +Lint/EmptyFile: + Exclude: + - 'db_shared/seeds.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). Lint/EnsureReturn: Exclude: - 'app/controllers/finance/bank_accounts_controller.rb' -# Offense count: 2 +# Offense count: 1 +Lint/FloatComparison: + Exclude: + - 'lib/article_units_lib.rb' + +# Offense count: 1 Lint/IneffectiveAccessModifier: Exclude: - 'lib/foodsoft_mail_receiver.rb' - - 'lib/token_verifier.rb' # Offense count: 1 -# Cop supports --auto-correct-all. +# This cop supports unsafe autocorrection (--autocorrect-all). Lint/InterpolationCheck: Exclude: - 'db/migrate/007_create_article_prices.rb' # Offense count: 1 -# Cop supports --auto-correct-all. +# This cop supports unsafe autocorrection (--autocorrect-all). Lint/Loop: Exclude: - 'app/models/concerns/mark_as_deleted_with_name.rb' @@ -152,47 +316,22 @@ Lint/MixedRegexpCaptureTypes: - 'lib/bank_transaction_reference.rb' - 'lib/foodsoft_mail_receiver.rb' -# Offense count: 1 -# Cop supports --auto-correct-all. +# Offense count: 2 +# This cop supports unsafe autocorrection (--autocorrect-all). Lint/NonDeterministicRequireOrder: Exclude: + - 'lib/tasks/seeds.rake' - 'spec/spec_helper.rb' -# Offense count: 5 -# Cop supports --auto-correct. -Lint/ParenthesesAsGroupedExpression: - Exclude: - - 'spec/integration/articles_spec.rb' - - 'spec/lib/token_verifier_spec.rb' - - 'spec/models/order_article_spec.rb' - # Offense count: 1 Lint/ReturnInVoidContext: Exclude: - 'lib/foodsoft_config.rb' -# Offense count: 8 -# Cop supports --auto-correct. -Lint/ScriptPermission: - Exclude: - - 'Rakefile' - - 'plugins/discourse/Rakefile' - - 'plugins/documents/Rakefile' - - 'plugins/links/Rakefile' - - 'plugins/messages/Rakefile' - - 'plugins/polls/Rakefile' - - 'plugins/printer/Rakefile' - - 'plugins/wiki/Rakefile' - -# Offense count: 7 -# Cop supports --auto-correct. -Lint/SendWithMixinArgument: +# Offense count: 1 +Lint/SelfAssignment: Exclude: - - 'config/initializers/doorkeeper.rb' - - 'plugins/discourse/lib/foodsoft_discourse/redirect_to_login.rb' - - 'plugins/messages/lib/foodsoft_messages/user_link.rb' - - 'plugins/uservoice/lib/foodsoft_uservoice.rb' - - 'plugins/wiki/lib/foodsoft_wiki/mailer.rb' + - 'db/migrate/20181201000100_create_message_recipients.foodsoft_messages.rb' # Offense count: 1 # Configuration parameters: IgnoreImplicitReferences. @@ -200,7 +339,7 @@ Lint/ShadowedArgument: Exclude: - 'app/helpers/deliveries_helper.rb' -# Offense count: 8 +# Offense count: 6 Lint/ShadowingOuterLocalVariable: Exclude: - 'app/documents/order_matrix.rb' @@ -209,9 +348,8 @@ Lint/ShadowingOuterLocalVariable: - 'app/models/group_order_article.rb' - 'plugins/discourse/app/controllers/discourse_login_controller.rb' - 'plugins/polls/app/controllers/polls_controller.rb' - - 'spec/integration/config_spec.rb' -# Offense count: 2 +# Offense count: 3 # Configuration parameters: AllowComments, AllowNil. Lint/SuppressedException: Exclude: @@ -225,57 +363,14 @@ Lint/UnderscorePrefixedVariableName: Exclude: - 'app/models/order_article.rb' -# Offense count: 16 -# Cop supports --auto-correct. -# Configuration parameters: IgnoreEmptyBlocks, AllowUnusedKeywordArguments. -Lint/UnusedBlockArgument: - Exclude: - - 'app/models/article.rb' - - 'app/models/group_order.rb' - - 'config/initializers/exception_notification.rb' - - 'plugins/printer/lib/foodsoft_printer/engine.rb' - - 'plugins/uservoice/lib/foodsoft_uservoice.rb' - - 'plugins/wiki/lib/foodsoft_wiki/wiki_parser.rb' - - 'spec/factories/supplier.rb' - - 'spec/factories/user.rb' - - 'spec/integration/config_spec.rb' - - 'spec/models/article_spec.rb' - -# Offense count: 23 -# Cop supports --auto-correct. -# Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods, IgnoreNotImplementedMethods. -Lint/UnusedMethodArgument: - Exclude: - - 'app/controllers/api/v1/base_controller.rb' - - 'app/controllers/concerns/foodcoop_scope.rb' - - 'app/helpers/application_helper.rb' - - 'app/models/article.rb' - - 'app/models/article_category.rb' - - 'app/models/financial_transaction.rb' - - 'app/models/group_order.rb' - - 'app/models/group_order_article.rb' - - 'app/models/order.rb' - - 'app/models/order_article.rb' - - 'app/models/supplier.rb' - - 'lib/foodsoft_mail_receiver.rb' - - 'lib/order_txt.rb' - - 'lib/render_pdf.rb' - - 'plugins/wiki/lib/foodsoft_wiki/mailer.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: ContextCreatingMethods, MethodCreatingMethods. -Lint/UselessAccessModifier: - Exclude: - - 'lib/token_verifier.rb' - - 'plugins/messages/app/models/messagegroup.rb' - -# Offense count: 14 +# Offense count: 17 +# This cop supports unsafe autocorrection (--autocorrect-all). Lint/UselessAssignment: Exclude: - 'app/controllers/admin/ordergroups_controller.rb' - 'app/helpers/admin/configs_helper.rb' - 'app/inputs/date_picker_time_input.rb' + - 'app/models/article.rb' - 'app/models/order_article.rb' - 'db/migrate/003_create_suppliers.rb' - 'db/migrate/004_create_article_meta.rb' @@ -285,56 +380,51 @@ Lint/UselessAssignment: - 'plugins/current_orders/app/documents/multiple_orders_by_articles.rb' - 'plugins/current_orders/app/documents/multiple_orders_by_groups.rb' - 'spec/lib/foodsoft_config_spec.rb' + - 'spec/models/article_spec.rb' -# Offense count: 1 -# Configuration parameters: CheckForMethodsWithNoSideEffects. -Lint/Void: - Exclude: - - 'lib/foodsoft_config.rb' - -# Offense count: 160 -# Configuration parameters: IgnoredMethods, CountRepeatedAttributes. +# Offense count: 183 +# Configuration parameters: AllowedMethods, AllowedPatterns, CountRepeatedAttributes. Metrics/AbcSize: - Max: 143 + Max: 145 -# Offense count: 73 -# Configuration parameters: CountComments, CountAsOne, ExcludedMethods, IgnoredMethods. -# IgnoredMethods: refine +# Offense count: 27 +# Configuration parameters: CountComments, CountAsOne, AllowedMethods, AllowedPatterns, inherit_mode. +# AllowedMethods: refine Metrics/BlockLength: - Max: 374 + Max: 222 # Offense count: 6 # Configuration parameters: CountBlocks. Metrics/BlockNesting: - Max: 5 + Max: 4 -# Offense count: 18 +# Offense count: 21 # Configuration parameters: CountComments, CountAsOne. Metrics/ClassLength: - Max: 288 + Max: 335 -# Offense count: 51 -# Configuration parameters: IgnoredMethods. +# Offense count: 63 +# Configuration parameters: AllowedMethods, AllowedPatterns. Metrics/CyclomaticComplexity: Max: 22 -# Offense count: 158 -# Configuration parameters: CountComments, CountAsOne, ExcludedMethods, IgnoredMethods. +# Offense count: 187 +# Configuration parameters: CountComments, CountAsOne, AllowedMethods, AllowedPatterns. Metrics/MethodLength: - Max: 112 + Max: 115 # Offense count: 4 # Configuration parameters: CountComments, CountAsOne. Metrics/ModuleLength: - Max: 190 + Max: 194 # Offense count: 1 # Configuration parameters: CountKeywordArgs, MaxOptionalParameters. Metrics/ParameterLists: Max: 6 -# Offense count: 36 -# Configuration parameters: IgnoredMethods. +# Offense count: 48 +# Configuration parameters: AllowedMethods, AllowedPatterns. Metrics/PerceivedComplexity: Max: 23 @@ -353,15 +443,16 @@ Naming/BlockParameterName: - 'db/migrate/008_create_orders.rb' # Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyleForLeadingUnderscores. # SupportedStylesForLeadingUnderscores: disallowed, required, optional Naming/MemoizedInstanceVariableName: Exclude: - 'plugins/messages/app/models/message.rb' -# Offense count: 19 +# Offense count: 18 # Configuration parameters: MinNameLength, AllowNamesEndingInNumbers, AllowedNames, ForbiddenNames. -# AllowedNames: at, by, db, id, in, io, ip, of, on, os, pp, to +# AllowedNames: as, at, by, cc, db, id, if, in, io, ip, of, on, os, pp, to Naming/MethodParameterName: Exclude: - 'app/controllers/api/v1/base_controller.rb' @@ -374,7 +465,6 @@ Naming/MethodParameterName: - 'spec/integration/config_spec.rb' - 'spec/integration/receive_spec.rb' - 'spec/models/order_article_spec.rb' - - 'spec/support/shared_database.rb' # Offense count: 11 # Configuration parameters: NamePrefix, ForbiddenPrefixes, AllowedMethods, MethodDefinitionMacros. @@ -394,14 +484,8 @@ Naming/PredicateName: - 'app/serializers/order_serializer.rb' - 'plugins/messages/app/models/message.rb' -# Offense count: 45 -# Cop supports --auto-correct. -# Configuration parameters: PreferredName. -Naming/RescuedExceptionsVariableName: - Enabled: false - # Offense count: 22 -# Configuration parameters: EnforcedStyle, AllowedIdentifiers. +# Configuration parameters: EnforcedStyle, AllowedIdentifiers, AllowedPatterns. # SupportedStyles: snake_case, camelCase Naming/VariableName: Exclude: @@ -411,9 +495,9 @@ Naming/VariableName: - 'lib/bank_account_information_importer.rb' # Offense count: 23 -# Configuration parameters: EnforcedStyle, CheckMethodNames, CheckSymbols, AllowedIdentifiers. +# Configuration parameters: EnforcedStyle, CheckMethodNames, CheckSymbols, AllowedIdentifiers, AllowedPatterns. # SupportedStyles: snake_case, normalcase, non_integer -# AllowedIdentifiers: capture3, iso8601, rfc1123_date, rfc822, rfc2822, rfc3339 +# AllowedIdentifiers: capture3, iso8601, rfc1123_date, rfc822, rfc2822, rfc3339, x86_64 Naming/VariableNumber: Exclude: - 'app/documents/order_matrix.rb' @@ -433,7 +517,7 @@ RSpec/BeforeAfterAll: - 'spec/lib/foodsoft_mail_receiver_spec.rb' # Offense count: 9 -# Cop supports --auto-correct. +# This cop supports safe autocorrection (--autocorrect). # Configuration parameters: EnabledMethods. RSpec/Capybara/FeatureMethods: Exclude: @@ -448,7 +532,7 @@ RSpec/Capybara/FeatureMethods: - 'spec/integration/supplier_spec.rb' # Offense count: 27 -# Configuration parameters: Prefixes. +# Configuration parameters: Prefixes, AllowedPatterns. # Prefixes: when, with, without RSpec/ContextWording: Exclude: @@ -457,18 +541,25 @@ RSpec/ContextWording: - 'spec/models/order_article_spec.rb' - 'spec/models/supplier_spec.rb' -# Offense count: 1 +# Offense count: 7 # Configuration parameters: IgnoredMetadata. RSpec/DescribeClass: Exclude: - 'spec/api/v1/swagger_spec.rb' + - 'spec/integration/balancing_spec.rb' + - 'spec/integration/config_spec.rb' + - 'spec/integration/product_distribution_example_spec.rb' + - 'spec/integration/receive_spec.rb' + - 'spec/integration/session_spec.rb' + - 'spec/integration/supplier_spec.rb' -# Offense count: 101 -# Cop supports --auto-correct. +# Offense count: 103 +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: SkipBlocks, EnforcedStyle. # SupportedStyles: described_class, explicit RSpec/DescribedClass: Exclude: + - 'spec/integration/order_spec.rb' - 'spec/lib/bank_transaction_reference_spec.rb' - 'spec/lib/foodsoft_config_spec.rb' - 'spec/lib/foodsoft_mail_receiver_spec.rb' @@ -479,113 +570,51 @@ RSpec/DescribedClass: - 'spec/models/ordergroup_spec.rb' - 'spec/models/user_spec.rb' -# Offense count: 9 -# Cop supports --auto-correct. +# Offense count: 6 +# This cop supports safe autocorrection (--autocorrect). # Configuration parameters: AllowConsecutiveOneLiners. RSpec/EmptyLineAfterExample: Exclude: - - 'spec/integration/session_spec.rb' - - 'spec/models/user_spec.rb' + - 'spec/api/v1/swagger_spec.rb' -# Offense count: 6 -# Cop supports --auto-correct. -RSpec/EmptyLineAfterExampleGroup: - Exclude: - - 'spec/models/order_article_spec.rb' +# Offense count: 71 +# Configuration parameters: CountAsOne. +RSpec/ExampleLength: + Max: 81 -# Offense count: 30 -# Cop supports --auto-correct. -RSpec/EmptyLineAfterFinalLet: +# Offense count: 7 +# Configuration parameters: Include, CustomTransform, IgnoreMethods, SpecSuffixOnly. +# Include: **/*_spec*rb*, **/spec/**/* +RSpec/FilePath: Exclude: - 'spec/api/v1/order_articles_spec.rb' - - 'spec/api/v1/swagger_spec.rb' - 'spec/api/v1/user/financial_transactions_spec.rb' - 'spec/api/v1/user/group_order_articles_spec.rb' + - 'spec/api/v1/user/ordergroup_spec.rb' - 'spec/integration/articles_spec.rb' - - 'spec/integration/balancing_spec.rb' - 'spec/integration/login_spec.rb' - - 'spec/integration/supplier_spec.rb' - - 'spec/models/order_article_spec.rb' - - 'spec/models/order_spec.rb' - - 'spec/models/user_spec.rb' - - 'spec/support/api_helper.rb' + - 'spec/lib/bank_account_information_importer_spec.rb' -# Offense count: 17 -# Cop supports --auto-correct. -RSpec/EmptyLineAfterHook: +# Offense count: 6 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: single_line_only, single_statement_only, disallow, require_implicit +RSpec/ImplicitSubject: + Exclude: + - 'spec/api/v1/swagger_spec.rb' + +# Offense count: 59 +# Configuration parameters: Max, AllowedIdentifiers, AllowedPatterns. +RSpec/IndexedLet: Exclude: - 'spec/api/v1/swagger_spec.rb' - 'spec/api/v1/user/financial_transactions_spec.rb' - - 'spec/api/v1/user/group_order_articles_spec.rb' + - 'spec/api/v1/user/ordergroup_spec.rb' - 'spec/integration/balancing_spec.rb' - - 'spec/integration/login_spec.rb' + - 'spec/integration/receive_spec.rb' + - 'spec/models/bank_transaction_spec.rb' - 'spec/models/order_article_spec.rb' - - 'spec/support/api_oauth.rb' - -# Offense count: 59 -# Configuration parameters: CountAsOne. -RSpec/ExampleLength: - Max: 81 - -# Offense count: 7 -# Cop supports --auto-correct. -# Configuration parameters: CustomTransform, IgnoredWords. -RSpec/ExampleWording: - Exclude: - - 'spec/models/order_spec.rb' - -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: Include. -# Include: spec/factories.rb, spec/factories/**/*.rb, features/support/factories/**/*.rb -RSpec/FactoryBot/FactoryClassName: - Exclude: - - 'spec/factories/article.rb' - - 'spec/factories/doorkeeper.rb' - - 'spec/factories/supplier.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -RSpec/FactoryBot/SyntaxMethods: - Exclude: - - 'spec/integration/articles_spec.rb' - - 'spec/models/article_spec.rb' - -# Offense count: 7 -# Configuration parameters: Include, CustomTransform, IgnoreMethods, SpecSuffixOnly. -# Include: **/*_spec*rb*, **/spec/**/* -RSpec/FilePath: - Exclude: - - 'spec/api/v1/order_articles_spec.rb' - - 'spec/api/v1/user/financial_transactions_spec.rb' - - 'spec/api/v1/user/group_order_articles_spec.rb' - - 'spec/api/v1/user/ordergroup_spec.rb' - - 'spec/integration/articles_spec.rb' - - 'spec/integration/login_spec.rb' - - 'spec/lib/bank_account_information_importer_spec.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: implicit, each, example -RSpec/HookArgument: - Exclude: - - 'spec/spec_helper.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -RSpec/HooksBeforeExamples: - Exclude: - - 'spec/integration/balancing_spec.rb' - - 'spec/lib/foodsoft_mail_receiver_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: single_line_only, single_statement_only, disallow -RSpec/ImplicitSubject: - Exclude: - - 'spec/api/v1/swagger_spec.rb' + - 'spec/models/ordergroup_spec.rb' # Offense count: 6 # Configuration parameters: AssignmentOnly. @@ -599,12 +628,6 @@ RSpec/IteratedExpectation: - 'spec/models/order_spec.rb' - 'spec/models/supplier_spec.rb' -# Offense count: 3 -# Cop supports --auto-correct. -RSpec/LetBeforeExamples: - Exclude: - - 'spec/api/v1/swagger_spec.rb' - # Offense count: 13 RSpec/LetSetup: Exclude: @@ -622,38 +645,29 @@ RSpec/MissingExampleGroupArgument: - 'spec/models/group_order_spec.rb' - 'spec/models/user_spec.rb' -# Offense count: 87 +# Offense count: 89 RSpec/MultipleExpectations: Max: 22 -# Offense count: 80 +# Offense count: 82 # Configuration parameters: AllowSubject. RSpec/MultipleMemoizedHelpers: Max: 17 +# Offense count: 7 +# Configuration parameters: EnforcedStyle, IgnoreSharedExamples. +# SupportedStyles: always, named_only +RSpec/NamedSubject: + Exclude: + - 'spec/api/v1/swagger_spec.rb' + # Offense count: 29 +# Configuration parameters: AllowedGroups. RSpec/NestedGroups: Max: 6 -# Offense count: 31 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: not_to, to_not -RSpec/NotToNot: - Exclude: - - 'spec/api/v1/user/financial_transactions_spec.rb' - - 'spec/api/v1/user/group_order_articles_spec.rb' - - 'spec/integration/balancing_spec.rb' - - 'spec/integration/login_spec.rb' - - 'spec/integration/receive_spec.rb' - - 'spec/integration/session_spec.rb' - - 'spec/lib/token_verifier_spec.rb' - - 'spec/models/article_spec.rb' - - 'spec/models/order_spec.rb' - - 'spec/models/supplier_spec.rb' - # Offense count: 8 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: Strict, EnforcedStyle, AllowedExplicitMatchers. # SupportedStyles: inflected, explicit RSpec/PredicateMatcher: @@ -661,6 +675,24 @@ RSpec/PredicateMatcher: - 'spec/models/article_spec.rb' - 'spec/models/user_spec.rb' +# Offense count: 2 +# This cop supports unsafe autocorrection (--autocorrect-all). +RSpec/Rails/HaveHttpStatus: + Exclude: + - 'spec/api/v1/user/financial_transactions_spec.rb' + - 'spec/api/v1/user/group_order_articles_spec.rb' + +# Offense count: 7 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: not_to, be_invalid +RSpec/Rails/NegationBeValid: + Exclude: + - 'spec/models/article_spec.rb' + - 'spec/models/order_spec.rb' + - 'spec/models/supplier_spec.rb' + - 'spec/models/user_spec.rb' + # Offense count: 6 RSpec/RepeatedDescription: Exclude: @@ -674,20 +706,18 @@ RSpec/RepeatedExample: - 'spec/lib/bank_transaction_reference_spec.rb' - 'spec/lib/foodsoft_mail_receiver_spec.rb' -# Offense count: 9 -# Cop supports --auto-correct. -RSpec/ScatteredLet: - Exclude: - - 'spec/api/v1/swagger_spec.rb' - - 'spec/api/v1/user/group_order_articles_spec.rb' - - 'spec/api/v1/user/ordergroup_spec.rb' - # Offense count: 7 -RSpec/ScatteredSetup: +# Configuration parameters: Include, CustomTransform, IgnoreMethods, IgnoreMetadata. +# Include: **/*_spec.rb +RSpec/SpecFilePathFormat: Exclude: + - 'spec/api/v1/order_articles_spec.rb' + - 'spec/api/v1/user/financial_transactions_spec.rb' + - 'spec/api/v1/user/group_order_articles_spec.rb' - 'spec/api/v1/user/ordergroup_spec.rb' - - 'spec/integration/balancing_spec.rb' + - 'spec/integration/articles_spec.rb' - 'spec/integration/login_spec.rb' + - 'spec/lib/bank_account_information_importer_spec.rb' # Offense count: 1 # Configuration parameters: IgnoreNameless, IgnoreSymbolicNames. @@ -695,37 +725,19 @@ RSpec/VerifiedDoubles: Exclude: - 'spec/support/api_oauth.rb' -# Offense count: 45 -# Cop supports --auto-correct. +# Offense count: 44 +# This cop supports unsafe autocorrection (--autocorrect-all). Rails/ActiveRecordAliases: Enabled: false -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: Include. -# Include: app/models/**/*.rb -Rails/ActiveRecordCallbacksOrder: - Exclude: - - 'app/models/financial_transaction_type.rb' - - 'app/models/order.rb' - - 'app/models/stock_change.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: Include. -# Include: db/migrate/*.rb -Rails/AddColumnIndex: - Exclude: - - 'db/migrate/20171002000000_create_financial_links.rb' - # Offense count: 1 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). Rails/ApplicationMailer: Exclude: - 'app/mailers/mailer.rb' # Offense count: 20 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). Rails/ApplicationRecord: Exclude: - 'app/models/supplier_category.rb' @@ -744,26 +756,43 @@ Rails/ApplicationRecord: - 'plugins/printer/app/models/printer_job.rb' - 'plugins/printer/app/models/printer_job_update.rb' -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: NilOrEmpty, NotPresent, UnlessPresent. -Rails/Blank: - Exclude: - - 'app/controllers/api/v1/base_controller.rb' +# Offense count: 33 +# Configuration parameters: Database, Include. +# SupportedDatabases: mysql, postgresql +# Include: db/**/*.rb +Rails/BulkChangeTable: + Exclude: + - 'db/migrate/20130624085246_remove_weekly_task_from_groups.rb' + - 'db/migrate/20130930132511_add_quantities_to_order_article.rb' + - 'db/migrate/20150227161931_add_replyto_and_groupid_to_messages.rb' + - 'db/migrate/20160217164552_add_break_to_group.rb' + - 'db/migrate/20160218151041_add_attachment_to_invoice.rb' + - 'db/migrate/20160226000000_add_email_to_message.foodsoft_messages_engine.rb' + - 'db/migrate/20160309153440_create_doorkeeper_tables.rb' + - 'db/migrate/20171002000000_create_financial_links.rb' + - 'db/migrate/20171201000000_add_name_short_to_financial_transaction_type.rb' + - 'db/migrate/20181201000100_create_message_recipients.foodsoft_messages.rb' + - 'db/migrate/20181201000200_add_deleted_to_financial_transaction_type.rb' + - 'db/migrate/20221026102300_alter_articles_add_versioning.rb' + - 'db/migrate/20221026102301_alter_articles_add_more_unit_logic.rb' + - 'db/migrate/20230414122017_alter_suppliers_sharing_fields.rb' -# Offense count: 1 -# Cop supports --auto-correct. -Rails/ContentTag: +# Offense count: 4 +# This cop supports unsafe autocorrection (--autocorrect-all). +Rails/CompactBlank: Exclude: - - 'plugins/wiki/app/helpers/pages_helper.rb' + - 'app/controllers/orders_controller.rb' + - 'app/helpers/order_articles_helper.rb' + - 'spec/integration/config_spec.rb' -# Offense count: 33 +# Offense count: 35 # Configuration parameters: Include. -# Include: db/migrate/*.rb +# Include: db/**/*.rb Rails/CreateTableWithTimestamps: Enabled: false # Offense count: 5 +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyle, AllowToTime. # SupportedStyles: strict, flexible Rails/Date: @@ -774,47 +803,19 @@ Rails/Date: - 'spec/integration/order_spec.rb' - 'spec/models/order_spec.rb' -# Offense count: 66 -# Cop supports --auto-correct-all. +# Offense count: 70 +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: Whitelist, AllowedMethods, AllowedReceivers. -# Whitelist: find_by_sql -# AllowedMethods: find_by_sql -# AllowedReceivers: Gem::Specification +# Whitelist: find_by_sql, find_by_token_for +# AllowedMethods: find_by_sql, find_by_token_for +# AllowedReceivers: Gem::Specification, page Rails/DynamicFindBy: Enabled: false -# Offense count: 1 -# Cop supports --auto-correct. -Rails/EagerEvaluationLogMessage: - Exclude: - - 'db/migrate/20130718183101_migrate_user_settings.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: Include. -# Include: app/models/**/*.rb -Rails/EnumHash: - Exclude: - - 'app/models/order.rb' - -# Offense count: 9 -# Configuration parameters: EnforcedStyle. -# SupportedStyles: slashes, arguments -Rails/FilePath: - Exclude: - - 'config/application.rb' - - 'config/initializers/secret_token.rb' - - 'lib/order_txt.rb' - - 'lib/render_csv.rb' - - 'lib/render_pdf.rb' - - 'plugins/current_orders/app/documents/multiple_orders_by_groups.rb' - - 'spec/api/v1/swagger_spec.rb' - -# Offense count: 7 -# Cop supports --auto-correct. -# Configuration parameters: Include, IgnoredMethods. -# Include: app/models/**/*.rb -# IgnoredMethods: order, limit, select, lock +# Offense count: 19 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AllowedMethods, AllowedPatterns. +# AllowedMethods: order, limit, select, lock Rails/FindEach: Exclude: - 'app/models/bank_account.rb' @@ -822,8 +823,16 @@ Rails/FindEach: - 'app/models/ordergroup.rb' - 'app/models/periodic_task_group.rb' - 'app/models/task.rb' + - 'db/migrate/20090120184410_road_to_version_three.rb' + - 'db/migrate/20090731132547_add_stats_to_groups.rb' + - 'db/migrate/20130622095040_move_weekly_tasks.rb' + - 'db/migrate/20181201000100_create_message_recipients.foodsoft_messages.rb' + - 'db/migrate/20210205090257_introduce_received_state_in_orders.rb' + - 'db/seeds/seed_helper.rb' + - 'lib/financial_transactions_csv.rb' + - 'lib/order_txt.rb' -# Offense count: 26 +# Offense count: 24 # Configuration parameters: Include. # Include: app/models/**/*.rb Rails/HasManyOrHasOneDependent: @@ -836,7 +845,6 @@ Rails/HasManyOrHasOneDependent: - 'app/models/group_order.rb' - 'app/models/order.rb' - 'app/models/ordergroup.rb' - - 'app/models/shared_supplier.rb' - 'app/models/stock_article.rb' - 'app/models/supplier.rb' - 'app/models/supplier_category.rb' @@ -852,27 +860,20 @@ Rails/HelperInstanceVariable: - 'app/helpers/application_helper.rb' - 'app/helpers/orders_helper.rb' -# Offense count: 14 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: numeric, symbolic -Rails/HttpStatus: +# Offense count: 1 +Rails/I18nLocaleTexts: Exclude: - - 'app/controllers/admin/bank_accounts_controller.rb' - - 'app/controllers/admin/financial_transaction_classes_controller.rb' - - 'app/controllers/admin/financial_transaction_types_controller.rb' - - 'app/controllers/api/v1/base_controller.rb' - - 'app/controllers/styles_controller.rb' - - 'plugins/links/app/controllers/links_controller.rb' + - 'plugins/messages/app/controllers/messages_controller.rb' -# Offense count: 2 -# Cop supports --auto-correct. -Rails/IndexBy: +# Offense count: 3 +# This cop supports safe autocorrection (--autocorrect). +Rails/IndexWith: Exclude: - - 'app/models/order.rb' - - 'spec/api/v1/user/ordergroup_spec.rb' + - 'app/helpers/application_helper.rb' + - 'lib/foodsoft_config.rb' + - 'plugins/wiki/app/controllers/pages_controller.rb' -# Offense count: 23 +# Offense count: 20 # Configuration parameters: IgnoreScopes, Include. # Include: app/models/**/*.rb Rails/InverseOf: @@ -884,8 +885,6 @@ Rails/InverseOf: - 'app/models/invoice.rb' - 'app/models/mail_delivery_status.rb' - 'app/models/order.rb' - - 'app/models/shared_article.rb' - - 'app/models/shared_supplier.rb' - 'app/models/stock_change.rb' - 'app/models/supplier.rb' - 'app/models/task.rb' @@ -894,28 +893,21 @@ Rails/InverseOf: # Offense count: 2 # Configuration parameters: Include. -# Include: app/controllers/**/*.rb +# Include: app/controllers/**/*.rb, app/mailers/**/*.rb Rails/LexicallyScopedActionFilter: Exclude: - 'app/controllers/group_orders_controller.rb' - 'app/controllers/suppliers_controller.rb' -# Offense count: 1 -# Cop supports --auto-correct. -Rails/LinkToBlank: - Exclude: - - 'app/helpers/application_helper.rb' - -# Offense count: 3 -# Cop supports --auto-correct-all. +# Offense count: 2 +# This cop supports unsafe autocorrection (--autocorrect-all). Rails/NegateInclude: Exclude: - 'app/helpers/application_helper.rb' - - 'app/models/supplier.rb' - 'lib/tasks/foodsoft_setup.rake' # Offense count: 34 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: Include. # Include: app/**/*.rb, config/**/*.rb, db/**/*.rb, lib/**/*.rb Rails/Output: @@ -934,7 +926,7 @@ Rails/Output: - 'db/migrate/20090120184410_road_to_version_three.rb' - 'db/migrate/20130622095040_move_weekly_tasks.rb' -# Offense count: 28 +# Offense count: 25 Rails/OutputSafety: Exclude: - 'app/helpers/admin/configs_helper.rb' @@ -946,147 +938,169 @@ Rails/OutputSafety: - 'plugins/wiki/app/helpers/pages_helper.rb' # Offense count: 1 -# Cop supports --auto-correct. -Rails/Pluck: +# This cop supports unsafe autocorrection (--autocorrect-all). +Rails/Pick: Exclude: - - 'lib/ordergroups_csv.rb' + - 'app/controllers/finance/financial_links_controller.rb' -# Offense count: 2 -# Cop supports --auto-correct. -Rails/PluralizationGrammar: +# Offense count: 3 +# This cop supports unsafe autocorrection (--autocorrect-all). +Rails/Pluck: Exclude: - - 'app/controllers/application_controller.rb' - - 'lib/tasks/foodsoft.rake' + - 'app/controllers/articles_controller.rb' + - 'lib/ordergroups_csv.rb' + - 'spec/api/v1/order_articles_spec.rb' # Offense count: 1 -# Cop supports --auto-correct. -Rails/Presence: +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: conservative, aggressive +Rails/PluckInWhere: Exclude: - - 'db/migrate/021_remove_table_article_prices.rb' - -# Offense count: 36 -# Cop supports --auto-correct. -# Configuration parameters: NotNilAndNotEmpty, NotBlank, UnlessBlank. -Rails/Present: - Enabled: false + - 'db/migrate/20140921104907_remove_stale_memberships.rb' -# Offense count: 6 -# Cop supports --auto-correct-all. +# Offense count: 9 +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: Include. # Include: **/Rakefile, **/*.rake Rails/RakeEnvironment: Exclude: + - 'lib/tasks/db_shared.rake' - 'lib/tasks/foodsoft_setup.rake' - 'lib/tasks/resque.rake' -# Offense count: 3 -# Cop supports --auto-correct. -Rails/RedundantForeignKey: +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AllowedReceivers. +# AllowedReceivers: ActionMailer::Preview, ActiveSupport::TimeZone +Rails/RedundantActiveRecordAllMethod: Exclude: - - 'app/models/financial_transaction.rb' - - 'plugins/messages/app/models/message.rb' + - 'db/migrate/20181201000100_create_message_recipients.foodsoft_messages.rb' -# Offense count: 1 -# Cop supports --auto-correct. +# Offense count: 14 +# This cop supports unsafe autocorrection (--autocorrect-all). Rails/RedundantPresenceValidationOnBelongsTo: Exclude: + - 'app/models/article_version.rb' + - 'app/models/bank_transaction.rb' + - 'app/models/delivery.rb' + - 'app/models/financial_transaction.rb' - 'app/models/financial_transaction_type.rb' + - 'app/models/group_order.rb' + - 'app/models/group_order_article.rb' + - 'app/models/group_order_article_quantity.rb' + - 'app/models/invite.rb' + - 'app/models/invoice.rb' + - 'app/models/order_article.rb' + - 'app/models/order_comment.rb' + - 'app/models/stock_change.rb' + +# Offense count: 4 +# This cop supports unsafe autocorrection (--autocorrect-all). +Rails/RootPathnameMethods: + Exclude: + - 'config/application.rb' + - 'lib/tasks/foodsoft_setup.rake' + - 'lib/tasks/seeds.rake' # Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: ConvertTry. -Rails/SafeNavigation: +# This cop supports unsafe autocorrection (--autocorrect-all). +Rails/SelectMap: Exclude: - - 'app/models/group_order_article.rb' + - 'lib/foodsoft/expansion_variables.rb' -# Offense count: 63 +# Offense count: 71 # Configuration parameters: ForbiddenMethods, AllowedMethods. # ForbiddenMethods: decrement!, decrement_counter, increment!, increment_counter, insert, insert!, insert_all, insert_all!, toggle!, touch, touch_all, update_all, update_attribute, update_column, update_columns, update_counters, upsert, upsert_all Rails/SkipsModelValidations: Enabled: false # Offense count: 3 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). Rails/SquishedSQLHeredocs: Exclude: - 'app/controllers/finance/financial_links_controller.rb' - 'app/models/financial_link.rb' - 'db/migrate/20181201000305_ensure_article_for_article_price.rb' -# Offense count: 34 -# Cop supports --auto-correct. +# Offense count: 10 +# Configuration parameters: Include. +# Include: db/**/*.rb +Rails/ThreeStateBooleanColumn: + Exclude: + - 'db/migrate/014_create_tasks.rb' + - 'db/migrate/20090120184410_road_to_version_three.rb' + - 'db/migrate/20090811144901_add_weekly_to_tasks.rb' + - 'db/migrate/20120929155541_add_ignore_apple_restriction_to_groups.rb' + - 'db/migrate/20121216180646_remove_assigned_from_tasks.rb' + - 'db/migrate/20130624084223_remove_weekly_from_tasks.rb' + - 'db/migrate/20130624085246_remove_weekly_task_from_groups.rb' + +# Offense count: 39 +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyle. # SupportedStyles: strict, flexible Rails/TimeZone: Enabled: false -# Offense count: 3 +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +Rails/ToSWithArgument: + Exclude: + - 'plugins/wiki/app/views/pages/all.rss.builder' + +# Offense count: 1 +# Configuration parameters: TransactionMethods. +Rails/TransactionExitStatement: + Exclude: + - 'app/models/bank_transaction.rb' + +# Offense count: 8 # Configuration parameters: Include. # Include: app/models/**/*.rb Rails/UniqueValidationWithoutIndex: Exclude: - 'app/models/bank_account.rb' + - 'app/models/financial_transaction_class.rb' + - 'app/models/financial_transaction_type.rb' + - 'app/models/supplier.rb' - 'app/models/supplier_category.rb' + - 'app/models/user.rb' # Offense count: 2 -# Configuration parameters: Environments. +# Configuration parameters: Severity, Environments. # Environments: development, test, production Rails/UnknownEnv: Exclude: - 'config/initializers/gaffe.rb' - 'config/initializers/secret_token.rb' -# Offense count: 68 -# Cop supports --auto-correct. -# Configuration parameters: Include. -# Include: app/models/**/*.rb -Rails/Validation: - Enabled: false - # Offense count: 2 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). Rails/WhereEquals: Exclude: - 'app/controllers/finance/invoices_controller.rb' - 'app/models/financial_transaction.rb' # Offense count: 1 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyle. # SupportedStyles: exists, where Rails/WhereExists: Exclude: - 'app/models/concerns/mark_as_deleted_with_name.rb' -# Offense count: 2 -# Cop supports --auto-correct. -Rails/WhereNot: - Exclude: - - 'db/migrate/20140921104907_remove_stale_memberships.rb' - - 'db/migrate/20210205090257_introduce_received_state_in_orders.rb' - -# Offense count: 5 -# Cop supports --auto-correct. +# Offense count: 4 +# This cop supports unsafe autocorrection (--autocorrect-all). Security/YAMLLoad: Exclude: - 'app/controllers/finance/bank_accounts_controller.rb' - 'db/migrate/20130718183101_migrate_user_settings.rb' - 'db/migrate/20181201000100_create_message_recipients.foodsoft_messages.rb' - 'lib/foodsoft_config.rb' - - 'spec/api/v1/swagger_spec.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: prefer_alias, prefer_alias_method -Style/Alias: - Exclude: - - 'config/initializers/session_store.rb' - - 'plugins/discourse/lib/foodsoft_discourse/redirect_to_login.rb' - - 'plugins/printer/lib/foodsoft_printer/order_printer_jobs.rb' # Offense count: 4 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyle. # SupportedStyles: always, conditionals Style/AndOr: @@ -1096,68 +1110,30 @@ Style/AndOr: - 'plugins/documents/app/controllers/documents_controller.rb' - 'spec/support/coverage.rb' -# Offense count: 19 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, IgnoredMethods, AllowBracesOnProceduralOneLiners, BracesRequiredMethods. +# Offense count: 50 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, AllowedMethods, AllowedPatterns, AllowBracesOnProceduralOneLiners, BracesRequiredMethods. # SupportedStyles: line_count_based, semantic, braces_for_chaining, always_braces # ProceduralMethods: benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object # FunctionalMethods: let, let!, subject, watch -# IgnoredMethods: lambda, proc, it +# AllowedMethods: lambda, proc, it Style/BlockDelimiters: - Exclude: - - 'app/controllers/api/v1/user/ordergroup_controller.rb' - - 'app/helpers/group_orders_helper.rb' - - 'app/helpers/orders_helper.rb' - - 'app/models/order.rb' - - 'db/migrate/008_create_orders.rb' - - 'lib/tasks/resque.rake' - - 'spec/api/v1/user/group_order_articles_spec.rb' - - 'spec/factories/user.rb' - - 'spec/lib/foodsoft_mail_receiver_spec.rb' - - 'spec/support/coverage.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: AllowOnConstant. -Style/CaseEquality: + Enabled: false + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowOnConstant, AllowOnSelfClass. +Style/CaseEquality: Exclude: - 'lib/tasks/foodsoft_setup.rake' -# Offense count: 7 -# Cop supports --auto-correct-all. -Style/CaseLikeIf: - Exclude: - - 'app/helpers/admin/configs_helper.rb' - - 'app/helpers/group_orders_helper.rb' - - 'app/models/order.rb' - - 'lib/foodsoft_date_util.rb' - - 'lib/render_pdf.rb' - - 'lib/tasks/foodsoft_setup.rake' - - 'plugins/uservoice/lib/foodsoft_uservoice.rb' - -# Offense count: 53 -# Cop supports --auto-correct. +# Offense count: 55 +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyle. # SupportedStyles: nested, compact Style/ClassAndModuleChildren: Enabled: false -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: is_a?, kind_of? -Style/ClassCheck: - Exclude: - - 'app/helpers/orders_helper.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: IgnoredMethods. -# IgnoredMethods: ==, equal?, eql? -Style/ClassEqualityComparison: - Exclude: - - 'spec/factories/supplier.rb' - # Offense count: 3 Style/ClassVars: Exclude: @@ -1165,39 +1141,8 @@ Style/ClassVars: - 'lib/foodsoft/expansion_variables.rb' - 'lib/foodsoft_mail_receiver.rb' -# Offense count: 3 -# Cop supports --auto-correct. -Style/ColonMethodCall: - Exclude: - - 'app/models/supplier.rb' - - 'plugins/discourse/app/controllers/discourse_controller.rb' - - 'plugins/messages/app/mail_receivers/messages_mail_receiver.rb' - -# Offense count: 7 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, AllowInnerBackticks. -# SupportedStyles: backticks, percent_x, mixed -Style/CommandLiteral: - Exclude: - - 'lib/tasks/foodsoft_setup.rake' - -# Offense count: 10 -# Cop supports --auto-correct. -# Configuration parameters: Keywords, RequireColon. -# Keywords: TODO, FIXME, OPTIMIZE, HACK, REVIEW, NOTE -Style/CommentAnnotation: - Exclude: - - 'app/controllers/admin/configs_controller.rb' - - 'app/inputs/delta_input.rb' - - 'app/models/order_article.rb' - - 'app/models/shared_supplier.rb' - - 'config/application.rb' - - 'spec/models/article_spec.rb' - - 'spec/models/order_spec.rb' - - 'spec/support/shared_database.rb' - # Offense count: 12 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). Style/CommentedKeyword: Exclude: - 'app/controllers/deliveries_controller.rb' @@ -1208,106 +1153,29 @@ Style/CommentedKeyword: - 'config/routes.rb' - 'db/migrate/20090120184410_road_to_version_three.rb' -# Offense count: 13 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SingleLineConditionsOnly, IncludeTernaryExpressions. -# SupportedStyles: assign_to_condition, assign_inside_condition -Style/ConditionalAssignment: - Exclude: - - 'app/controllers/application_controller.rb' - - 'app/controllers/articles_controller.rb' - - 'app/controllers/concerns/locale.rb' - - 'app/controllers/finance/bank_transactions_controller.rb' - - 'app/controllers/finance/financial_transactions_controller.rb' - - 'app/controllers/home_controller.rb' - - 'app/controllers/orders_controller.rb' - - 'plugins/documents/app/controllers/documents_controller.rb' - - 'plugins/messages/app/mail_receivers/messages_mail_receiver.rb' - - 'plugins/wiki/app/controllers/pages_controller.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/DefWithParentheses: - Exclude: - - 'app/models/user.rb' - -# Offense count: 314 +# Offense count: 348 # Configuration parameters: AllowedConstants. Style/Documentation: Enabled: false # Offense count: 1 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyle. # SupportedStyles: allowed_in_returns, forbidden Style/DoubleNegation: Exclude: - 'app/controllers/tasks_controller.rb' -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, AllowComments. # SupportedStyles: empty, nil, both Style/EmptyElse: Exclude: - - 'app/helpers/application_helper.rb' - - 'app/models/article.rb' - - 'app/models/order_article.rb' - - 'app/models/user.rb' - - 'lib/token_verifier.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/EmptyLiteral: - Exclude: - - 'plugins/wiki/app/helpers/pages_helper.rb' - -# Offense count: 14 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: compact, expanded -Style/EmptyMethod: - Exclude: - - 'app/controllers/articles_controller.rb' - - 'app/controllers/feedback_controller.rb' - - 'app/controllers/finance/invoices_controller.rb' - - 'app/controllers/home_controller.rb' - - 'app/controllers/login_controller.rb' - - 'app/mailers/mailer.rb' - - 'db/migrate/024_add_deposit_defaults.rb' - - 'db/migrate/20090120184410_road_to_version_three.rb' - - 'db/migrate/20090907120012_add_missing_indexes.rb' - - 'db/migrate/20130702113610_update_group_order_totals.rb' - - 'db/migrate/20130718183101_migrate_user_settings.rb' - - 'db/migrate/20140318173000_delete_empty_group_order_articles.rb' - - 'lib/bank_account_connector.rb' - -# Offense count: 21 -# Cop supports --auto-correct. -Style/ExpandPathArguments: - Enabled: false - -# Offense count: 7 -# Cop supports --auto-correct. -Style/ExplicitBlockArgument: - Exclude: - - 'app/documents/order_fax.rb' - - 'app/helpers/admin/configs_helper.rb' - - 'app/models/concerns/find_each_with_order.rb' - - 'plugins/current_orders/app/documents/multiple_orders_by_articles.rb' - - 'plugins/current_orders/app/documents/multiple_orders_by_groups.rb' - -# Offense count: 4 -# Cop supports --auto-correct. -Style/FileWrite: - Exclude: - - 'config/initializers/secret_token.rb' - - 'lib/order_txt.rb' - - 'lib/render_csv.rb' - - 'lib/render_pdf.rb' + - 'app/models/group_order.rb' # Offense count: 1 -# Cop supports --auto-correct-all. +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyle. # SupportedStyles: left_coerce, right_coerce, single_coerce, fdiv Style/FloatDivision: @@ -1315,7 +1183,7 @@ Style/FloatDivision: - 'app/models/ordergroup.rb' # Offense count: 18 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyle. # SupportedStyles: each, for Style/For: @@ -1331,59 +1199,61 @@ Style/For: - 'plugins/messages/app/mail_receivers/messages_mail_receiver.rb' - 'plugins/wiki/app/views/pages/all.rss.builder' -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: format, sprintf, percent -Style/FormatString: - Exclude: - - 'lib/order_txt.rb' - # Offense count: 6 -# Configuration parameters: MaxUnannotatedPlaceholdersAllowed, IgnoredMethods. +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: MaxUnannotatedPlaceholdersAllowed, AllowedMethods, AllowedPatterns. # SupportedStyles: annotated, template, unannotated +# AllowedMethods: redirect Style/FormatStringToken: EnforcedStyle: unannotated -# Offense count: 490 -# Cop supports --auto-correct. +# Offense count: 515 +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyle. # SupportedStyles: always, always_true, never Style/FrozenStringLiteralComment: Enabled: false # Offense count: 3 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). Style/GlobalStdStream: Exclude: - 'config/environments/production.rb' - 'lib/tasks/foodsoft.rake' - 'lib/tasks/foodsoft_setup.rake' -# Offense count: 61 -# Configuration parameters: MinBodyLength. +# Offense count: 3 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: MinBodyLength, AllowConsecutiveConditionals. Style/GuardClause: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: braces, no_braces -Style/HashAsLastArrayItem: Exclude: + - 'app/models/article_category.rb' - 'app/models/order.rb' + - 'plugins/wiki/app/controllers/pages_controller.rb' -# Offense count: 6 -# Cop supports --auto-correct. +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: AllowSplatArgument. Style/HashConversion: Exclude: - - 'app/helpers/application_helper.rb' - - 'app/models/article.rb' - - 'app/models/order.rb' - 'lib/bank_account_information_importer.rb' - - 'plugins/wiki/app/controllers/pages_controller.rb' - - 'spec/api/v1/user/ordergroup_spec.rb' + +# Offense count: 3 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AllowedReceivers. +# AllowedReceivers: Thread.current +Style/HashEachMethods: + Exclude: + - 'app/controllers/articles_controller.rb' + - 'app/models/group_order.rb' + - 'spec/integration/config_spec.rb' + +# Offense count: 3 +# This cop supports unsafe autocorrection (--autocorrect-all). +Style/HashExcept: + Exclude: + - 'plugins/uservoice/lib/foodsoft_uservoice.rb' + - 'spec/models/article_spec.rb' # Offense count: 8 # Configuration parameters: MinBranchesCount. @@ -1398,46 +1268,22 @@ Style/HashLikeCase: - 'plugins/documents/app/controllers/documents_controller.rb' - 'plugins/wiki/app/controllers/pages_controller.rb' -# Offense count: 3904 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, EnforcedShorthandSyntax, UseHashRocketsWithSymbolValues, PreferHashRocketsForNonAlnumEndingSymbols. -# SupportedStyles: ruby19, hash_rockets, no_mixed_keys, ruby19_no_mixed_keys -# SupportedShorthandSyntax: always, never, either -Style/HashSyntax: - Enabled: false - -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: AllowIfModifier. -Style/IfInsideElse: - Exclude: - - 'app/models/article.rb' - - 'app/models/task.rb' - - 'lib/apple_bar.rb' - - 'plugins/wiki/app/controllers/pages_controller.rb' - -# Offense count: 60 -# Cop supports --auto-correct. -Style/IfUnlessModifier: - Enabled: false - -# Offense count: 2 -# Cop supports --auto-correct. +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: AllowedMethods. # AllowedMethods: nonzero? Style/IfWithBooleanLiteralBranches: Exclude: - 'app/models/order_article.rb' - - 'app/models/task.rb' # Offense count: 1 -# Cop supports --auto-correct-all. +# This cop supports unsafe autocorrection (--autocorrect-all). Style/InfiniteLoop: Exclude: - 'lib/order_pdf.rb' # Offense count: 3 -# Cop supports --auto-correct-all. +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: InverseMethods, InverseBlocks. Style/InverseMethods: Exclude: @@ -1445,473 +1291,182 @@ Style/InverseMethods: - 'app/helpers/deliveries_helper.rb' - 'spec/support/coverage.rb' -# Offense count: 4 -# Cop supports --auto-correct. +# Offense count: 6 +# This cop supports safe autocorrection (--autocorrect). # Configuration parameters: EnforcedStyle. # SupportedStyles: line_count_dependent, lambda, literal Style/Lambda: Exclude: - - 'app/models/financial_link.rb' - - 'lib/foodsoft_mail_receiver.rb' - - 'plugins/messages/app/models/message.rb' + - 'app/models/article.rb' + - 'app/models/financial_transaction.rb' + - 'app/models/order_article.rb' + - 'app/models/supplier.rb' + - 'spec/api/v1/swagger_spec.rb' # Offense count: 5 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). Style/LineEndConcatenation: Exclude: - 'db/migrate/20130702113610_update_group_order_totals.rb' - 'plugins/current_orders/app/documents/multiple_orders_by_articles.rb' # Offense count: 1 -# Cop supports --auto-correct-all. +# This cop supports unsafe autocorrection (--autocorrect-all). Style/MapToHash: Exclude: - - 'lib/foodsoft_config.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: IgnoredMethods. -Style/MethodCallWithoutArgsParentheses: - Exclude: - - 'plugins/discourse/app/controllers/discourse_login_controller.rb' + - 'app/models/article_version.rb' -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: require_parentheses, require_no_parentheses, require_no_parentheses_except_multiline -Style/MethodDefParentheses: +# Offense count: 3 +# This cop supports unsafe autocorrection (--autocorrect-all). +Style/MinMaxComparison: Exclude: - - 'app/controllers/concerns/send_order_pdf.rb' - - 'app/helpers/application_helper.rb' - - 'app/helpers/finance/invoices_helper.rb' - - 'plugins/discourse/app/controllers/discourse_controller.rb' + - 'app/models/group_order_article.rb' + - 'lib/apple_bar.rb' # Offense count: 1 Style/MixinUsage: Exclude: - 'lib/tasks/foodsoft_setup.rake' -# Offense count: 2 +# Offense count: 3 Style/MultilineBlockChain: Exclude: - 'app/helpers/group_orders_helper.rb' - 'app/models/order.rb' - 'config/initializers/rails6_backports.rb' -# Offense count: 2 -# Cop supports --auto-correct. +# Offense count: 33 +# This cop supports safe autocorrection (--autocorrect). Style/MultilineIfModifier: - Exclude: - - 'app/models/user.rb' - - 'plugins/current_orders/app/controllers/current_orders/ordergroups_controller.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -Style/MultilineIfThen: - Exclude: - - 'app/controllers/finance/financial_links_controller.rb' - - 'lib/bank_account_information_importer.rb' - -# Offense count: 12 -# Cop supports --auto-correct. -Style/MultilineWhenThen: - Exclude: - - 'app/controllers/finance/balancing_controller.rb' - - 'app/helpers/application_helper.rb' - - 'app/helpers/finance/balancing_helper.rb' - - 'app/models/order.rb' + Enabled: false -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: AllowMethodComparison. -Style/MultipleComparison: +# Offense count: 4 +# This cop supports safe autocorrection (--autocorrect). +Style/MultilineTernaryOperator: Exclude: - - 'app/models/order.rb' - - 'app/models/order_article.rb' - - 'spec/models/article_spec.rb' + - 'app/helpers/group_order_articles_helper.rb' + - 'app/helpers/orders_helper.rb' + - 'app/models/group_order.rb' # Offense count: 24 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyle. # SupportedStyles: literals, strict Style/MutableConstant: Enabled: false -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: both, prefix, postfix -Style/NegatedIf: - Exclude: - - 'app/controllers/orders_controller.rb' - - 'app/helpers/articles_helper.rb' - -# Offense count: 4 -# Cop supports --auto-correct. -Style/NegatedIfElseCondition: - Exclude: - - 'app/controllers/articles_controller.rb' - - 'app/controllers/concerns/auth.rb' - - 'app/models/article.rb' - -# Offense count: 8 -# Cop supports --auto-correct. -# Configuration parameters: AllowedMethods. -# AllowedMethods: be, be_a, be_an, be_between, be_falsey, be_kind_of, be_instance_of, be_truthy, be_within, eq, eql, end_with, include, match, raise_error, respond_to, start_with -Style/NestedParenthesizedCalls: - Exclude: - - 'app/models/user.rb' - - 'spec/models/order_article_spec.rb' - -# Offense count: 7 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, MinBodyLength. -# SupportedStyles: skip_modifier_ifs, always -Style/Next: - Exclude: - - 'app/controllers/finance/financial_transactions_controller.rb' - - 'app/controllers/orders_controller.rb' - - 'app/helpers/orders_helper.rb' - - 'db/migrate/20130622095040_move_weekly_tasks.rb' - - 'lib/tasks/foodsoft.rake' - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. +# Offense count: 65 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle, AllowedMethods, AllowedPatterns. # SupportedStyles: predicate, comparison -Style/NilComparison: - Exclude: - - 'app/controllers/application_controller.rb' - - 'plugins/wiki/app/helpers/pages_helper.rb' +Style/NumericPredicate: + Enabled: false -# Offense count: 10 -# Cop supports --auto-correct. -Style/Not: +# Offense count: 1 +Style/OpenStructUse: Exclude: - - 'app/controllers/concerns/auth.rb' - - 'app/controllers/orders_controller.rb' - - 'app/helpers/deliveries_helper.rb' - - 'app/models/group_order_article.rb' - - 'app/models/order_article.rb' - - 'app/models/supplier.rb' - - 'app/models/task.rb' - - 'spec/support/coverage.rb' + - 'app/controllers/suppliers_controller.rb' # Offense count: 6 -# Cop supports --auto-correct. -# Configuration parameters: Strict, AllowedNumbers. -Style/NumericLiterals: - MinDigits: 7 - -# Offense count: 60 -# Cop supports --auto-correct-all. -# Configuration parameters: EnforcedStyle, IgnoredMethods. -# SupportedStyles: predicate, comparison -Style/NumericPredicate: - Enabled: false - -# Offense count: 5 # Configuration parameters: AllowedMethods. # AllowedMethods: respond_to_missing? Style/OptionalBooleanParameter: Exclude: - 'app/helpers/application_helper.rb' + - 'app/helpers/group_order_articles_helper.rb' - 'app/helpers/orders_helper.rb' - 'app/models/order_article.rb' - 'lib/tasks/foodsoft_setup.rake' # Offense count: 1 -# Cop supports --auto-correct. -Style/OrAssignment: - Exclude: - - 'app/controllers/articles_controller.rb' - -# Offense count: 8 -# Cop supports --auto-correct. -Style/ParallelAssignment: - Exclude: - - 'app/models/article.rb' - - 'app/models/group_order_article.rb' - - 'app/models/supplier.rb' - - 'app/models/user.rb' - - 'spec/models/group_order_article_spec.rb' - - 'spec/support/session_helper.rb' - -# Offense count: 12 -# Cop supports --auto-correct. -# Configuration parameters: AllowSafeAssignment, AllowInMultilineConditions. -Style/ParenthesesAroundCondition: - Exclude: - - 'app/controllers/login_controller.rb' - - 'app/helpers/application_helper.rb' - - 'app/helpers/group_orders_helper.rb' - - 'app/models/group_order_article.rb' - - 'plugins/wiki/app/controllers/pages_controller.rb' - -# Offense count: 41 -# Cop supports --auto-correct. -# Configuration parameters: PreferredDelimiters. -Style/PercentLiteralDelimiters: - Enabled: false - -# Offense count: 5 -# Cop supports --auto-correct. -Style/PerlBackrefs: - Exclude: - - 'lib/foodsoft/expansion_variables.rb' - - 'plugins/wiki/app/helpers/pages_helper.rb' - -# Offense count: 2 -# Cop supports --auto-correct-all. +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyle. # SupportedStyles: short, verbose Style/PreferredHashMethods: Exclude: - 'app/helpers/admin/configs_helper.rb' - - 'app/helpers/articles_helper.rb' - -# Offense count: 14 -# Cop supports --auto-correct. -Style/Proc: - Exclude: - - 'app/helpers/deliveries_helper.rb' - - 'app/models/user.rb' - - 'config/navigation.rb' - - 'plugins/current_orders/lib/foodsoft_current_orders/engine.rb' - - 'plugins/links/lib/foodsoft_links/engine.rb' - -# Offense count: 6 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, AllowedCompactTypes. -# SupportedStyles: compact, exploded -Style/RaiseArgs: - Exclude: - - 'app/controllers/api/v1/base_controller.rb' - - 'app/controllers/concerns/auth_api.rb' - - 'app/controllers/concerns/foodcoop_scope.rb' - -# Offense count: 5 -# Cop supports --auto-correct. -Style/RandomWithOffset: - Exclude: - - 'db/migrate/007_create_article_prices.rb' - - 'db/migrate/008_create_orders.rb' - - 'db/seeds/seed_helper.rb' - -# Offense count: 1 -# Cop supports --auto-correct-all. -# Configuration parameters: Methods. -Style/RedundantArgument: - Exclude: - - 'app/controllers/articles_controller.rb' - -# Offense count: 8 -# Cop supports --auto-correct. -Style/RedundantBegin: - Exclude: - - 'app/controllers/articles_controller.rb' - - 'app/models/order.rb' - - 'lib/foodsoft_mail_receiver.rb' - - 'lib/tasks/multicoops.rake' - - 'spec/lib/foodsoft_mail_receiver_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/RedundantConditional: - Exclude: - - 'app/models/task.rb' # Offense count: 3 -# Cop supports --auto-correct-all. +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: SafeForConstants. Style/RedundantFetchBlock: Exclude: - 'config/puma.rb' -# Offense count: 2 -# Cop supports --auto-correct. -Style/RedundantFileExtensionInRequire: - Exclude: - - 'db/seeds/small.en.seeds.rb' - - 'db/seeds/small.nl.seeds.rb' - -# Offense count: 5 -# Cop supports --auto-correct. +# Offense count: 8 +# This cop supports unsafe autocorrection (--autocorrect-all). Style/RedundantInterpolation: Exclude: - 'db/migrate/20130718183101_migrate_user_settings.rb' - - 'lib/order_pdf.rb' + - 'lib/order_txt.rb' + - 'lib/render_csv.rb' + - 'lib/render_pdf.rb' + - 'plugins/current_orders/app/documents/multiple_orders_by_groups.rb' - 'spec/i18n_spec.rb' - 'spec/models/user_spec.rb' # Offense count: 1 -# Cop supports --auto-correct. -Style/RedundantRegexpCharacterClass: - Exclude: - - 'plugins/wiki/app/helpers/pages_helper.rb' - -# Offense count: 7 -# Cop supports --auto-correct. -Style/RedundantRegexpEscape: - Exclude: - - 'lib/bank_transaction_reference.rb' - - 'lib/foodsoft_mail_receiver.rb' - - 'plugins/documents/app/controllers/documents_controller.rb' - - 'plugins/wiki/app/models/page.rb' - -# Offense count: 15 -# Cop supports --auto-correct. -# Configuration parameters: AllowMultipleReturnValues. -Style/RedundantReturn: - Exclude: - - 'app/controllers/concerns/auth_api.rb' - - 'app/helpers/application_helper.rb' - - 'app/helpers/deliveries_helper.rb' - - 'app/helpers/group_orders_helper.rb' - - 'app/helpers/orders_helper.rb' - - 'app/models/article.rb' - - 'app/models/bank_transaction.rb' - - 'app/models/periodic_task_group.rb' - - 'app/models/supplier.rb' - - 'lib/bank_transaction_reference.rb' - -# Offense count: 82 -# Cop supports --auto-correct. -Style/RedundantSelf: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -Style/RedundantSelfAssignmentBranch: - Exclude: - - 'db/migrate/20130718183101_migrate_user_settings.rb' - -# Offense count: 1 -# Cop supports --auto-correct-all. +# This cop supports unsafe autocorrection (--autocorrect-all). Style/RedundantSort: Exclude: - 'app/models/article_category.rb' -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, AllowInnerSlashes. -# SupportedStyles: slashes, percent_r, mixed -Style/RegexpLiteral: - Exclude: - - 'plugins/wiki/app/models/page.rb' - - 'spec/support/coverage.rb' - -# Offense count: 16 -# Cop supports --auto-correct. -Style/RescueModifier: +# Offense count: 2 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AllowedMethods, AllowedPatterns. +Style/ReturnNilInPredicateMethodDefinition: Exclude: - - 'app/controllers/invites_controller.rb' + - 'app/controllers/group_orders_controller.rb' - 'app/models/article.rb' - - 'app/models/order.rb' - - 'app/models/ordergroup.rb' - - 'config/application.rb' - - 'lib/apple_bar.rb' - - 'lib/date_time_attribute_validate.rb' - - 'lib/foodsoft_date_util.rb' - - 'plugins/messages/app/models/message.rb' -# Offense count: 50 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: implicit, explicit -Style/RescueStandardError: - Enabled: false - -# Offense count: 9 -# Cop supports --auto-correct. -# Configuration parameters: ConvertCodeThatCanStartToReturnNil, AllowedMethods. +# Offense count: 11 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: ConvertCodeThatCanStartToReturnNil, AllowedMethods, MaxChainLength. # AllowedMethods: present?, blank?, presence, try, try! Style/SafeNavigation: Exclude: - 'app/controllers/concerns/auth_api.rb' + - 'app/controllers/concerns/locale.rb' - 'app/controllers/group_order_articles_controller.rb' + - 'app/models/article.rb' - 'app/models/article_category.rb' + - 'app/models/bank_account.rb' - 'app/models/financial_transaction.rb' - - 'app/models/ordergroup.rb' - 'app/models/user.rb' - 'plugins/printer/app/controllers/printer_controller.rb' - 'spec/factories/order.rb' # Offense count: 1 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). Style/SelectByRegexp: Exclude: - 'lib/foodsoft_config.rb' -# Offense count: 1 -# Cop supports --auto-correct. -Style/SelfAssignment: - Exclude: - - 'app/helpers/application_helper.rb' - -# Offense count: 16 -# Cop supports --auto-correct. -# Configuration parameters: AllowAsExpressionSeparator. -Style/Semicolon: - Exclude: - - 'app/controllers/finance/bank_transactions_controller.rb' - - 'app/controllers/finance/financial_transactions_controller.rb' - - 'app/controllers/finance/invoices_controller.rb' - - 'app/controllers/orders_controller.rb' - - 'app/helpers/group_orders_helper.rb' - - 'db/migrate/20090120184410_road_to_version_three.rb' - - 'spec/api/v1/swagger_spec.rb' - - 'spec/api/v1/user/group_order_articles_spec.rb' - - 'spec/api/v1/user/ordergroup_spec.rb' - - 'spec/models/order_article_spec.rb' - # Offense count: 5 -# Cop supports --auto-correct-all. +# This cop supports unsafe autocorrection (--autocorrect-all). Style/SlicingWithRange: Exclude: - 'app/helpers/admin/configs_helper.rb' - 'config/initializers/session_store.rb' - 'lib/order_pdf.rb' -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: AllowModifier. -Style/SoleNestedConditional: - Exclude: - - 'app/controllers/articles_controller.rb' - - 'app/controllers/concerns/auth.rb' - # Offense count: 9 -# Cop supports --auto-correct. +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: RequireEnglish. -# SupportedStyles: use_perl_names, use_english_names +# SupportedStyles: use_perl_names, use_english_names, use_builtin_english_names Style/SpecialGlobalVars: EnforcedStyle: use_perl_names -# Offense count: 32 -# Cop supports --auto-correct-all. +# Offense count: 35 +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: Mode. Style/StringConcatenation: Enabled: false -# Offense count: 1799 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline. -# SupportedStyles: single_quotes, double_quotes -Style/StringLiterals: - Enabled: false - -# Offense count: 80 -# Cop supports --auto-correct. -# Configuration parameters: MinSize. -# SupportedStyles: percent, brackets -Style/SymbolArray: - EnforcedStyle: brackets - # Offense count: 19 -# Cop supports --auto-correct-all. -# Configuration parameters: AllowMethodsWithArguments, IgnoredMethods. -# IgnoredMethods: respond_to, define_method +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AllowMethodsWithArguments, AllowedMethods, AllowedPatterns, AllowComments. +# AllowedMethods: define_method, mail, respond_to Style/SymbolProc: Exclude: - 'app/controllers/pickups_controller.rb' @@ -1927,87 +1482,17 @@ Style/SymbolProc: - 'db/migrate/20090731132547_add_stats_to_groups.rb' - 'spec/factories/order.rb' -# Offense count: 4 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, AllowSafeAssignment. -# SupportedStyles: require_parentheses, require_no_parentheses, require_parentheses_when_complex -Style/TernaryParentheses: - Exclude: - - 'app/models/order_article.rb' - -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyleForMultiline. -# SupportedStylesForMultiline: comma, consistent_comma, no_comma -Style/TrailingCommaInArrayLiteral: - Exclude: - - 'lib/articles_csv.rb' - - 'lib/invoices_csv.rb' - - 'lib/ordergroups_csv.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyleForMultiline. -# SupportedStylesForMultiline: comma, consistent_comma, no_comma -Style/TrailingCommaInHashLiteral: - Exclude: - - 'app/controllers/finance/financial_transactions_controller.rb' - - 'config/initializers/exception_notification.rb' - - 'lib/bank_account_information_importer.rb' - -# Offense count: 8 -# Cop supports --auto-correct. -# Configuration parameters: ExactNameMatch, AllowPredicates, AllowDSLWriters, IgnoreClassMethods, AllowedMethods. -# AllowedMethods: to_ary, to_a, to_c, to_enum, to_h, to_hash, to_i, to_int, to_io, to_open, to_path, to_proc, to_r, to_regexp, to_str, to_s, to_sym -Style/TrivialAccessors: - Exclude: - - 'app/models/order.rb' - - 'lib/bank_account_connector.rb' - - 'plugins/messages/app/models/message.rb' - -# Offense count: 5 -# Cop supports --auto-correct. -Style/UnlessElse: - Exclude: - - 'app/controllers/home_controller.rb' - - 'app/controllers/orders_controller.rb' - - 'app/helpers/group_order_articles_helper.rb' - - 'plugins/current_orders/app/controllers/current_orders/articles_controller.rb' - - 'plugins/wiki/app/helpers/pages_helper.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/WhileUntilModifier: - Exclude: - - 'app/models/periodic_task_group.rb' - -# Offense count: 11 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, MinSize, WordRegex. -# SupportedStyles: percent, brackets -Style/WordArray: - Exclude: - - 'app/documents/order_matrix.rb' - - 'app/helpers/application_helper.rb' - - 'app/models/supplier.rb' - - 'db/migrate/006_create_articles.rb' - - 'lib/tasks/foodsoft_setup.rake' - - 'plugins/current_orders/app/controllers/current_orders/group_orders_controller.rb' - - 'plugins/wiki/app/controllers/pages_controller.rb' - - 'plugins/wiki/app/helpers/pages_helper.rb' - - 'spec/support/faker.rb' - # Offense count: 3 -# Cop supports --auto-correct-all. +# This cop supports unsafe autocorrection (--autocorrect-all). Style/ZeroLengthPredicate: Exclude: - 'app/models/group_order_article.rb' - 'plugins/current_orders/app/documents/multiple_orders_by_articles.rb' - 'plugins/current_orders/app/documents/multiple_orders_by_groups.rb' -# Offense count: 448 -# Cop supports --auto-correct. -# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. +# Offense count: 805 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, AllowedPatterns. # URISchemes: http, https Layout/LineLength: - Max: 420 + Max: 311 diff --git a/Rakefile b/Rakefile old mode 100644 new mode 100755 index 835180b2..e59b186f --- a/Rakefile +++ b/Rakefile @@ -1,7 +1,7 @@ #!/usr/bin/env rake # Add your own tasks in files placed in lib/tasks ending in .rake, -require File.expand_path('../config/application', __FILE__) +require File.expand_path('config/application', __dir__) require 'rake' require 'rspec-rerun/tasks' if defined?(RSpec) # http://stackoverflow.com/a/16853615/2866660 diff --git a/app/controllers/admin/bank_accounts_controller.rb b/app/controllers/admin/bank_accounts_controller.rb index a54ea798..ac6bb64f 100644 --- a/app/controllers/admin/bank_accounts_controller.rb +++ b/app/controllers/admin/bank_accounts_controller.rb @@ -3,39 +3,39 @@ class Admin::BankAccountsController < Admin::BaseController def new @bank_account = BankAccount.new(params[:bank_account]) - render :layout => false + render layout: false + end + + def edit + @bank_account = BankAccount.find(params[:id]) + render action: 'new', layout: false end def create @bank_account = BankAccount.new(params[:bank_account]) if @bank_account.valid? && @bank_account.save - redirect_to update_bank_accounts_admin_finances_url, :status => 303 + redirect_to update_bank_accounts_admin_finances_url, status: :see_other else - render :action => 'new', :layout => false + render action: 'new', layout: false end end - def edit - @bank_account = BankAccount.find(params[:id]) - render :action => 'new', :layout => false - end - def update @bank_account = BankAccount.find(params[:id]) if @bank_account.update_attributes(params[:bank_account]) - redirect_to update_bank_accounts_admin_finances_url, :status => 303 + redirect_to update_bank_accounts_admin_finances_url, status: :see_other else - render :action => 'new', :layout => false + render action: 'new', layout: false end end def destroy @bank_account = BankAccount.find(params[:id]) @bank_account.destroy - redirect_to update_bank_accounts_admin_finances_url, :status => 303 - rescue => error - flash.now[:alert] = error.message + redirect_to update_bank_accounts_admin_finances_url, status: :see_other + rescue StandardError => e + flash.now[:alert] = e.message render template: 'shared/alert' end end diff --git a/app/controllers/admin/bank_gateways_controller.rb b/app/controllers/admin/bank_gateways_controller.rb index 3965c91b..c7ca5516 100644 --- a/app/controllers/admin/bank_gateways_controller.rb +++ b/app/controllers/admin/bank_gateways_controller.rb @@ -6,6 +6,11 @@ def new render layout: false end + def edit + @bank_gateway = BankGateway.find(params[:id]) + render action: 'new', layout: false + end + def create @bank_gateway = BankGateway.new(params[:bank_gateway]) if @bank_gateway.valid? && @bank_gateway.save @@ -15,11 +20,6 @@ def create end end - def edit - @bank_gateway = BankGateway.find(params[:id]) - render action: 'new', layout: false - end - def update @bank_gateway = BankGateway.find(params[:id]) diff --git a/app/controllers/admin/configs_controller.rb b/app/controllers/admin/configs_controller.rb index 516113af..500c1b87 100644 --- a/app/controllers/admin/configs_controller.rb +++ b/app/controllers/admin/configs_controller.rb @@ -1,5 +1,5 @@ class Admin::ConfigsController < Admin::BaseController - before_action :get_tabs, only: [:show, :list] + before_action :get_tabs, only: %i[show list] def show @current_tab = @tabs.include?(params[:tab]) ? params[:tab] : @tabs.first @@ -16,7 +16,7 @@ def list def update parse_recurring_selects! params[:config][:order_schedule] ActiveRecord::Base.transaction do - # TODO support nested configuration keys + # TODO: support nested configuration keys params[:config].each do |key, val| FoodsoftConfig[key] = convert_config_value val end @@ -29,7 +29,7 @@ def update # Set configuration tab names as `@tabs` def get_tabs - @tabs = %w(foodcoop payment tasks messages layout language security others) + @tabs = %w[foodcoop payment tasks messages layout language security others] # allow engines to modify this list engines = Rails::Engine.subclasses.map(&:instance).select { |e| e.respond_to?(:configuration) } engines.each { |e| e.configuration(@tabs, self) } @@ -38,16 +38,16 @@ def get_tabs # turn recurring rules into something palatable def parse_recurring_selects!(config) - if config - for k in [:pickup, :boxfill, :ends] do - if config[k] - # allow clearing it using dummy value '{}' ('' would break recurring_select) - if config[k][:recurr].present? && config[k][:recurr] != '{}' - config[k][:recurr] = ActiveSupport::JSON.decode(config[k][:recurr]) - config[k][:recurr] = FoodsoftDateUtil.rule_from(config[k][:recurr]).to_ical if config[k][:recurr] - else - config[k] = nil - end + return unless config + + for k in %i[pickup boxfill ends] do + if config[k] + # allow clearing it using dummy value '{}' ('' would break recurring_select) + if config[k][:recurr].present? && config[k][:recurr] != '{}' + config[k][:recurr] = ActiveSupport::JSON.decode(config[k][:recurr]) + config[k][:recurr] = FoodsoftDateUtil.rule_from(config[k][:recurr]).to_ical if config[k][:recurr] + else + config[k] = nil end end end diff --git a/app/controllers/admin/finances_controller.rb b/app/controllers/admin/finances_controller.rb index 76a93619..7d2ddff6 100644 --- a/app/controllers/admin/finances_controller.rb +++ b/app/controllers/admin/finances_controller.rb @@ -9,16 +9,16 @@ def index def update_bank_accounts @bank_accounts = BankAccount.order('name') - render :layout => false + render layout: false end def update_bank_gateways @bank_gateways = BankGateway.order('name') - render :layout => false + render layout: false end def update_transaction_types @financial_transaction_classes = FinancialTransactionClass.includes(:financial_transaction_types).order('name ASC') - render :layout => false + render layout: false end end diff --git a/app/controllers/admin/financial_transaction_classes_controller.rb b/app/controllers/admin/financial_transaction_classes_controller.rb index 10359acd..fe46a422 100644 --- a/app/controllers/admin/financial_transaction_classes_controller.rb +++ b/app/controllers/admin/financial_transaction_classes_controller.rb @@ -6,25 +6,25 @@ def new render layout: false end + def edit + @financial_transaction_class = FinancialTransactionClass.find(params[:id]) + render action: 'new', layout: false + end + def create @financial_transaction_class = FinancialTransactionClass.new(params[:financial_transaction_class]) if @financial_transaction_class.save - redirect_to update_transaction_types_admin_finances_url, status: 303 + redirect_to update_transaction_types_admin_finances_url, status: :see_other else render action: 'new', layout: false end end - def edit - @financial_transaction_class = FinancialTransactionClass.find(params[:id]) - render action: 'new', layout: false - end - def update @financial_transaction_class = FinancialTransactionClass.find(params[:id]) if @financial_transaction_class.update_attributes(params[:financial_transaction_class]) - redirect_to update_transaction_types_admin_finances_url, status: 303 + redirect_to update_transaction_types_admin_finances_url, status: :see_other else render action: 'new', layout: false end @@ -33,9 +33,9 @@ def update def destroy @financial_transaction_class = FinancialTransactionClass.find(params[:id]) @financial_transaction_class.destroy! - redirect_to update_transaction_types_admin_finances_url, status: 303 - rescue => error - flash.now[:alert] = error.message + redirect_to update_transaction_types_admin_finances_url, status: :see_other + rescue StandardError => e + flash.now[:alert] = e.message render template: 'shared/alert' end end diff --git a/app/controllers/admin/financial_transaction_types_controller.rb b/app/controllers/admin/financial_transaction_types_controller.rb index 401f31e7..a3b7abeb 100644 --- a/app/controllers/admin/financial_transaction_types_controller.rb +++ b/app/controllers/admin/financial_transaction_types_controller.rb @@ -7,25 +7,25 @@ def new render layout: false end + def edit + @financial_transaction_type = FinancialTransactionType.find(params[:id]) + render action: 'new', layout: false + end + def create @financial_transaction_type = FinancialTransactionType.new(params[:financial_transaction_type]) if @financial_transaction_type.save - redirect_to update_transaction_types_admin_finances_url, status: 303 + redirect_to update_transaction_types_admin_finances_url, status: :see_other else render action: 'new', layout: false end end - def edit - @financial_transaction_type = FinancialTransactionType.find(params[:id]) - render action: 'new', layout: false - end - def update @financial_transaction_type = FinancialTransactionType.find(params[:id]) if @financial_transaction_type.update_attributes(params[:financial_transaction_type]) - redirect_to update_transaction_types_admin_finances_url, status: 303 + redirect_to update_transaction_types_admin_finances_url, status: :see_other else render action: 'new', layout: false end @@ -34,9 +34,9 @@ def update def destroy @financial_transaction_type = FinancialTransactionType.find(params[:id]) @financial_transaction_type.destroy! - redirect_to update_transaction_types_admin_finances_url, status: 303 - rescue => error - flash.now[:alert] = error.message + redirect_to update_transaction_types_admin_finances_url, status: :see_other + rescue StandardError => e + flash.now[:alert] = e.message render template: 'shared/alert' end end diff --git a/app/controllers/admin/mail_delivery_status_controller.rb b/app/controllers/admin/mail_delivery_status_controller.rb index 52a4db92..c0086044 100644 --- a/app/controllers/admin/mail_delivery_status_controller.rb +++ b/app/controllers/admin/mail_delivery_status_controller.rb @@ -3,28 +3,28 @@ class Admin::MailDeliveryStatusController < Admin::BaseController def index @maildeliverystatus = MailDeliveryStatus.order(created_at: :desc) - @maildeliverystatus = @maildeliverystatus.where(email: params[:email]) unless params[:email].blank? + @maildeliverystatus = @maildeliverystatus.where(email: params[:email]) if params[:email].present? @maildeliverystatus = @maildeliverystatus.page(params[:page]).per(@per_page) end def show @maildeliverystatus = MailDeliveryStatus.find(params[:id]) filename = "maildeliverystatus_#{params[:id]}.#{MIME::Types[@maildeliverystatus.attachment_mime].first.preferred_extension}" - send_data(@maildeliverystatus.attachment_data, :filename => filename, :type => @maildeliverystatus.attachment_mime) + send_data(@maildeliverystatus.attachment_data, filename: filename, type: @maildeliverystatus.attachment_mime) end def destroy_all @maildeliverystatus = MailDeliveryStatus.delete_all redirect_to admin_mail_delivery_status_index_path, notice: t('.notice') - rescue => error - redirect_to admin_mail_delivery_status_index_path, alert: I18n.t('errors.general_msg', msg: error.message) + rescue StandardError => e + redirect_to admin_mail_delivery_status_index_path, alert: I18n.t('errors.general_msg', msg: e.message) end def destroy @maildeliverystatus = MailDeliveryStatus.find(params[:id]) @maildeliverystatus.destroy redirect_to admin_mail_delivery_status_index_path, notice: t('.notice') - rescue => error - redirect_to admin_mail_delivery_status_index_path, alert: I18n.t('errors.general_msg', msg: error.message) + rescue StandardError => e + redirect_to admin_mail_delivery_status_index_path, alert: I18n.t('errors.general_msg', msg: e.message) end end diff --git a/app/controllers/admin/ordergroups_controller.rb b/app/controllers/admin/ordergroups_controller.rb index 279cccdf..4a91f44e 100644 --- a/app/controllers/admin/ordergroups_controller.rb +++ b/app/controllers/admin/ordergroups_controller.rb @@ -5,13 +5,12 @@ def index @ordergroups = Ordergroup.undeleted.order('name ASC') if request.format.csv? - send_data OrdergroupsCsv.new(@ordergroups).to_csv, filename: 'ordergroups.csv', type: 'text/csv' + send_data OrdergroupsCsv.new(@ordergroups).to_csv, filename: 'ordergroups.csv', + type: 'text/csv' end # if somebody uses the search field: - unless params[:query].blank? - @ordergroups = @ordergroups.where('name LIKE ?', "%#{params[:query]}%") - end + @ordergroups = @ordergroups.where('name LIKE ?', "%#{params[:query]}%") if params[:query].present? @ordergroups = @ordergroups.page(params[:page]).per(@per_page) end @@ -19,8 +18,8 @@ def index def destroy @ordergroup = Ordergroup.find(params[:id]) @ordergroup.mark_as_deleted - redirect_to admin_ordergroups_url, notice: t('admin.ordergroups.destroy.notice') - rescue => error - redirect_to admin_ordergroups_url, alert: t('admin.ordergroups.destroy.error') + redirect_to admin_ordergroups_url, notice: t('.notice') + rescue StandardError => e + redirect_to admin_ordergroups_url, alert: t('.error') end end diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb index 97ff4177..132051ee 100644 --- a/app/controllers/admin/users_controller.rb +++ b/app/controllers/admin/users_controller.rb @@ -5,12 +5,10 @@ def index @users = params[:show_deleted] ? User.deleted : User.undeleted @users = @users.includes(:mail_delivery_status) - if request.format.csv? - send_data UsersCsv.new(@users).to_csv, filename: 'users.csv', type: 'text/csv' - end + send_data UsersCsv.new(@users).to_csv, filename: 'users.csv', type: 'text/csv' if request.format.csv? # if somebody uses the search field: - @users = @users.natural_search(params[:user_name]) unless params[:user_name].blank? + @users = @users.natural_search(params[:user_name]) if params[:user_name].present? @users = @users.natural_order.page(params[:page]).per(@per_page) end @@ -18,17 +16,17 @@ def index def destroy @user = User.find(params[:id]) @user.mark_as_deleted - redirect_to admin_users_url, notice: t('admin.users.destroy.notice') - rescue => error - redirect_to admin_users_url, alert: t('admin.users.destroy.error', error: error.message) + redirect_to admin_users_url, notice: t('.notice') + rescue StandardError => e + redirect_to admin_users_url, alert: t('.error', error: e.message) end def restore @user = User.find(params[:id]) @user.restore - redirect_to admin_users_url, notice: t('admin.users.restore.notice') - rescue => error - redirect_to admin_users_url, alert: t('admin.users.restore.error', error: error.message) + redirect_to admin_users_url, notice: t('.notice') + rescue StandardError => e + redirect_to admin_users_url, alert: t('.error', error: e.message) end def sudo diff --git a/app/controllers/admin/workgroups_controller.rb b/app/controllers/admin/workgroups_controller.rb index 184000bd..f5a9c2a3 100644 --- a/app/controllers/admin/workgroups_controller.rb +++ b/app/controllers/admin/workgroups_controller.rb @@ -4,7 +4,7 @@ class Admin::WorkgroupsController < Admin::BaseController def index @workgroups = Workgroup.order('name ASC') # if somebody uses the search field: - @workgroups = @workgroups.where('name LIKE ?', "%#{params[:query]}%") unless params[:query].blank? + @workgroups = @workgroups.where('name LIKE ?', "%#{params[:query]}%") if params[:query].present? @workgroups = @workgroups.page(params[:page]).per(@per_page) end @@ -12,8 +12,8 @@ def index def destroy @workgroup = Workgroup.find(params[:id]) @workgroup.destroy - redirect_to admin_workgroups_url, notice: t('admin.workgroups.destroy.notice') - rescue => error - redirect_to admin_workgroups_url, alert: t('admin.workgroups.destroy.error', error: error.message) + redirect_to admin_workgroups_url, notice: t('.notice') + rescue StandardError => e + redirect_to admin_workgroups_url, alert: t('.error', error: e.message) end end diff --git a/app/controllers/api/v1/articles_controller.rb b/app/controllers/api/v1/articles_controller.rb index 1ecf1375..67850fee 100644 --- a/app/controllers/api/v1/articles_controller.rb +++ b/app/controllers/api/v1/articles_controller.rb @@ -5,9 +5,15 @@ def index supplier = Supplier.find_by_external_uuid(index_params.fetch(:shared_supplier_uuid)) raise ActionController::RoutingError, 'Not Found' if supplier.nil? - @articles = Article.with_latest_versions_and_categories.undeleted.where(supplier_id: supplier, :type => nil) - @articles = @articles.where('article_versions.updated_at > ?', index_params[:updated_after].to_datetime) if index_params.include?(:updated_after) - @articles = @articles.where('article_versions.name LIKE ?', "%#{index_params[:name]}%") if index_params.include?(:name) + @articles = Article.with_latest_versions_and_categories.undeleted.where(supplier_id: supplier, type: nil) + if index_params.include?(:updated_after) + @articles = @articles.where('article_versions.updated_at > ?', + index_params[:updated_after].to_datetime) + end + if index_params.include?(:name) + @articles = @articles.where('article_versions.name LIKE ?', + "%#{index_params[:name]}%") + end @articles = @articles.where(article_versions: { origin: index_params[:origin] }) if index_params.include?(:origin) @articles = @articles.page(index_params[:page]).per(index_params.fetch(:per_page)) if index_params.include?(:page) @@ -23,7 +29,8 @@ def index version_attributes end - latest_update = Article.with_latest_versions_and_categories.undeleted.where(supplier_id: supplier, :type => nil).maximum('article_versions.updated_at') + latest_update = Article.with_latest_versions_and_categories.undeleted.where(supplier_id: supplier, + type: nil).maximum('article_versions.updated_at') latest_update = latest_update.utc unless latest_update.nil? pagination = nil diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rb index 13e903f1..8bed20ec 100644 --- a/app/controllers/api/v1/base_controller.rb +++ b/app/controllers/api/v1/base_controller.rb @@ -20,29 +20,30 @@ def current_ordergroup def require_ordergroup authenticate - unless current_ordergroup.present? - raise Api::Errors::PermissionRequired.new('Forbidden, must be in an ordergroup') - end + return if current_ordergroup.present? + + raise Api::Errors::PermissionRequired, 'Forbidden, must be in an ordergroup' end def require_minimum_balance minimum_balance = FoodsoftConfig[:minimum_balance] or return - if current_ordergroup.account_balance < minimum_balance - raise Api::Errors::PermissionRequired.new(t('application.controller.error_minimum_balance', min: minimum_balance)) - end + return unless current_ordergroup.account_balance < minimum_balance + + raise Api::Errors::PermissionRequired, t('application.controller.error_minimum_balance', min: minimum_balance) end def require_enough_apples - if current_ordergroup.not_enough_apples? - s = t('group_orders.messages.not_enough_apples', apples: current_ordergroup.apples, stop_ordering_under: FoodsoftConfig[:stop_ordering_under]) - raise Api::Errors::PermissionRequired.new(s) - end + return unless current_ordergroup.not_enough_apples? + + s = t('group_orders.messages.not_enough_apples', apples: current_ordergroup.apples, + stop_ordering_under: FoodsoftConfig[:stop_ordering_under]) + raise Api::Errors::PermissionRequired, s end def require_config_enabled(config) - unless FoodsoftConfig[config] - raise Api::Errors::PermissionRequired.new(t('application.controller.error_not_enabled', config: config)) - end + return if FoodsoftConfig[config] + + raise Api::Errors::PermissionRequired, t('application.controller.error_not_enabled', config: config) end def skip_session @@ -52,12 +53,12 @@ def skip_session def not_found_handler(e) # remove where-clauses from error message (not suitable for end-users) msg = e.message.try { |m| m.sub(/\s*\[.*?\]\s*$/, '') } || 'Not found' - render status: 404, json: { error: 'not_found', error_description: msg } + render status: :not_found, json: { error: 'not_found', error_description: msg } end def not_acceptable_handler(e) msg = e.message || 'Data not acceptable' - render status: 422, json: { error: 'not_acceptable', error_description: msg } + render status: :unprocessable_entity, json: { error: 'not_acceptable', error_description: msg } end def doorkeeper_unauthorized_render_options(error:) @@ -70,11 +71,11 @@ def doorkeeper_forbidden_render_options(error:) def permission_required_handler(e) msg = e.message || 'Forbidden, user has no access' - render status: 403, json: { error: 'forbidden', error_description: msg } + render status: :forbidden, json: { error: 'forbidden', error_description: msg } end # @todo something with ApplicationHelper#show_user - def show_user(user = current_user, **options) + def show_user(user = current_user, **_options) user.display end end diff --git a/app/controllers/api/v1/user/financial_transactions_controller.rb b/app/controllers/api/v1/user/financial_transactions_controller.rb index 96b32e28..3de38de9 100644 --- a/app/controllers/api/v1/user/financial_transactions_controller.rb +++ b/app/controllers/api/v1/user/financial_transactions_controller.rb @@ -16,7 +16,8 @@ def show def create transaction_type = FinancialTransactionType.find(create_params[:financial_transaction_type_id]) - ft = current_ordergroup.add_financial_transaction!(create_params[:amount], create_params[:note], current_user, transaction_type) + ft = current_ordergroup.add_financial_transaction!(create_params[:amount], create_params[:note], current_user, + transaction_type) render json: ft end 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 eeeb122c..1a1ec4d3 100644 --- a/app/controllers/api/v1/user/group_order_articles_controller.rb +++ b/app/controllers/api/v1/user/group_order_articles_controller.rb @@ -4,8 +4,8 @@ class Api::V1::User::GroupOrderArticlesController < Api::V1::BaseController before_action -> { doorkeeper_authorize! 'group_orders:user' } before_action :require_ordergroup - before_action :require_minimum_balance, only: [:create, :update] # destroy is ok - before_action :require_enough_apples, only: [:create, :update] # destroy is ok + before_action :require_minimum_balance, only: %i[create update] # destroy is ok + before_action :require_enough_apples, only: %i[create update] # destroy is ok # @todo allow decreasing amounts when minimum balance isn't met def index @@ -35,7 +35,8 @@ def update goa = nil GroupOrderArticle.transaction do goa = scope_for_update.includes(:group_order_article_quantities).find(params.require(:id)) - goa.update_quantities((update_params[:quantity] || goa.quantity).to_i, (update_params[:tolerance] || goa.tolerance).to_i) + goa.update_quantities((update_params[:quantity] || goa.quantity).to_i, + (update_params[:tolerance] || goa.tolerance).to_i) goa.order_article.update_results! goa.group_order.update_price! goa.group_order.update_attributes! updated_by: current_user diff --git a/app/controllers/api/v1/user/ordergroup_controller.rb b/app/controllers/api/v1/user/ordergroup_controller.rb index 08c12b4c..23889fe8 100644 --- a/app/controllers/api/v1/user/ordergroup_controller.rb +++ b/app/controllers/api/v1/user/ordergroup_controller.rb @@ -8,13 +8,13 @@ def financial_overview financial_overview: { account_balance: ordergroup.account_balance.to_f, available_funds: ordergroup.get_available_funds.to_f, - financial_transaction_class_sums: FinancialTransactionClass.sorted.map { |c| + financial_transaction_class_sums: FinancialTransactionClass.sorted.map do |c| { id: c.id, name: c.display, amount: ordergroup["sum_of_class_#{c.id}"].to_f } - } + end } } end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index eb90f9b4..3537f8c4 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -19,10 +19,10 @@ def self.current private def set_user_last_activity - if current_user && (session[:last_activity] == nil || session[:last_activity] < 1.minutes.ago) - current_user.update_attribute(:last_activity, Time.now) - session[:last_activity] = Time.now - end + return unless current_user && (session[:last_activity].nil? || session[:last_activity] < 1.minute.ago) + + current_user.update_attribute(:last_activity, Time.now) + session[:last_activity] = Time.now end # Many plugins can be turned on and off on the fly with a `use_` configuration option. @@ -64,11 +64,11 @@ def find_supplier end def items_per_page - if params[:per_page] && params[:per_page].to_i > 0 && params[:per_page].to_i <= 500 - @per_page = params[:per_page].to_i - else - @per_page = 20 - end + @per_page = if params[:per_page] && params[:per_page].to_i > 0 && params[:per_page].to_i <= 500 + params[:per_page].to_i + else + 20 + end end # Set timezone according to foodcoop preference. diff --git a/app/controllers/article_categories_controller.rb b/app/controllers/article_categories_controller.rb index bfa601d3..810bb3ce 100644 --- a/app/controllers/article_categories_controller.rb +++ b/app/controllers/article_categories_controller.rb @@ -4,17 +4,17 @@ class ArticleCategoriesController < ApplicationController before_action :authenticate_article_meta def create - create!(:notice => I18n.t('article_categories.create.notice')) { article_categories_path } + create!(notice: I18n.t('article_categories.create.notice')) { article_categories_path } end def update - update!(:notice => I18n.t('article_categories.update.notice')) { article_categories_path } + update!(notice: I18n.t('article_categories.update.notice')) { article_categories_path } end def destroy destroy! - rescue => error - redirect_to article_categories_path, alert: I18n.t('article_categories.destroy.error', message: error.message) + rescue StandardError => e + redirect_to article_categories_path, alert: I18n.t('article_categories.destroy.error', message: e.message) end protected diff --git a/app/controllers/article_units_controller.rb b/app/controllers/article_units_controller.rb index 15e76930..783ca883 100644 --- a/app/controllers/article_units_controller.rb +++ b/app/controllers/article_units_controller.rb @@ -1,6 +1,6 @@ class ArticleUnitsController < ApplicationController before_action :authenticate_article_meta - before_action :load_available_units, only: [:search, :create, :destroy] + before_action :load_available_units, only: %i[search create destroy] def index; end @@ -10,13 +10,15 @@ def search existing_article_units = ArticleUnit.all.to_a @article_units = @available_units .to_h do |key, value| - [key, value.merge({ code: key, record: existing_article_units.find { |existing_unit| existing_unit.unit == key } })] + [key, value.merge({ code: key, record: existing_article_units.find do |existing_unit| + existing_unit.unit == key + end })] end unless @query.nil? @article_units = @article_units.select do |_key, value| (value[:name].downcase.include?(@query) || value[:symbol]&.downcase&.include?(@query)) && - (params[:only_recommended] == "0" || !value[:untranslated]) + (params[:only_recommended] == '0' || !value[:untranslated]) end end diff --git a/app/controllers/articles_controller.rb b/app/controllers/articles_controller.rb index aa589c5f..686750f4 100644 --- a/app/controllers/articles_controller.rb +++ b/app/controllers/articles_controller.rb @@ -1,30 +1,32 @@ class ArticlesController < ApplicationController before_action :authenticate_article_meta, :find_supplier - before_action :load_article, only: [:edit, :update] - before_action :load_article_units, only: [:edit, :update, :new, :create, :sync, :update_synchronized] - before_action :load_article_categories, only: [:edit_all, :migrate_units, :update_all] - before_action :new_empty_article_ratio, only: [:edit, :edit_all, :migrate_units, :update, :new, :create, :parse_upload, :sync, :update_synchronized] + before_action :load_article, only: %i[edit update] + before_action :load_article_units, only: %i[edit update new create sync update_synchronized] + before_action :load_article_categories, only: %i[edit_all migrate_units update_all] + before_action :new_empty_article_ratio, + only: %i[edit edit_all migrate_units update new create parse_upload sync update_synchronized] def index - if params['sort'] - sort = case params['sort'] - when "name" then "article_versions.name" - when "unit" then "article_versions.unit" - when "article_category" then "article_categories.name" - when "note" then "article_versions.note" - when "availability" then "article_versions.availability" - when "name_reverse" then "article_versions.name DESC" - when "unit_reverse" then "article_versions.unit DESC" - when "article_category_reverse" then "article_categories.name DESC" - when "note_reverse" then "article_versions.note DESC" - when "availability_reverse" then "article_versions.availability DESC" + sort = if params['sort'] + case params['sort'] + when 'name' then 'article_versions.name' + when 'unit' then 'article_versions.unit' + when 'article_category' then 'article_categories.name' + when 'note' then 'article_versions.note' + when 'availability' then 'article_versions.availability' + when 'name_reverse' then 'article_versions.name DESC' + when 'unit_reverse' then 'article_versions.unit DESC' + when 'article_category_reverse' then 'article_categories.name DESC' + when 'note_reverse' then 'article_versions.note DESC' + when 'availability_reverse' then 'article_versions.availability DESC' end - else - sort = "article_categories.name, article_versions.name" - end + else + 'article_categories.name, article_versions.name' + end - @articles = Article.with_latest_versions_and_categories.order(sort).undeleted.where(supplier_id: @supplier, :type => nil) + @articles = Article.with_latest_versions_and_categories.order(sort).undeleted.where(supplier_id: @supplier, + type: nil) if request.format.csv? send_data ArticlesCsv.new(@articles, encoding: 'utf-8').to_csv, filename: 'articles.csv', type: 'text/csv' @@ -37,23 +39,23 @@ def index respond_to do |format| format.html - format.js { render :layout => false } + format.js { render layout: false } end end def new @article = @supplier.articles.build @article.latest_article_version = @article.article_versions.build - render :layout => false + render layout: false end def copy @article = @supplier.articles.find(params[:article_id]).dup - render :layout => false + render layout: false end def edit - render :action => 'new', layout: false + render action: 'new', layout: false end def create @@ -67,9 +69,9 @@ def create end if valid - render :layout => false + render layout: false else - render :action => 'new', :layout => false + render action: 'new', layout: false end end @@ -77,10 +79,10 @@ def create def update Article.transaction do if @article.update_attributes(latest_article_version_attributes: params[:article_version]) - render :layout => false + render layout: false else Rails.logger.info @article.errors.to_yaml.to_s - render :action => 'new', :layout => false + render action: 'new', layout: false end end end @@ -89,7 +91,7 @@ def update def destroy @article = Article.find(params[:id]) @article.mark_as_deleted unless @order = @article.in_open_order # If article is in an active Order, the Order will be returned - render :layout => false + render layout: false end # Renders a form for editing all articles from a supplier @@ -99,8 +101,7 @@ def edit_all load_article_units end - def prepare_units_migration - end + def prepare_units_migration; end def migrate_units build_article_migration_samples @@ -112,7 +113,7 @@ def complete_units_migration Article.transaction do params[:samples].values.each do |sample| - next unless sample[:apply_migration] == "1" + next unless sample[:apply_migration] == '1' original_unit = nil articles = Article.with_latest_versions_and_categories @@ -130,8 +131,8 @@ def complete_units_migration article_version_params[:billing_unit] = article_version_params[:group_order_unit] article_version_params[:price_unit] = article_version_params[:group_order_unit] article_version_params[:article_unit_ratios_attributes] = {} - unless sample[:first_ratio_unit].blank? - article_version_params[:article_unit_ratios_attributes]["1"] = { + if sample[:first_ratio_unit].present? + article_version_params[:article_unit_ratios_attributes]['1'] = { id: latest_article_version.article_unit_ratios.first&.id, sort: 1, quantity: sample[:first_ratio_quantity], @@ -139,9 +140,7 @@ def complete_units_migration } end article_version_params[:id] = latest_article_version.id - unless article.update_attributes(latest_article_version_attributes: article_version_params) - @invalid_articles << article - end + @invalid_articles << article unless article.update_attributes(latest_article_version_attributes: article_version_params) end errors = articles.find { |a| !a.errors.nil? }&.errors @@ -157,7 +156,7 @@ def complete_units_migration ), articles: articles, errors: errors, - error: !errors.blank? + error: errors.present? } end @supplier.update_attribute(:unit_migration_completed, Time.now) @@ -165,10 +164,12 @@ def complete_units_migration end if @invalid_articles.empty? - redirect_to supplier_articles_path(@supplier), notice: I18n.t('articles.controller.complete_units_migration.notice') + redirect_to supplier_articles_path(@supplier), + notice: I18n.t('articles.controller.complete_units_migration.notice') else additional_units = @samples.map do |sample| - [sample[:conversion_result][:supplier_order_unit], sample[:conversion_result][:group_order_unit], sample[:conversion_result][:first_ratio]&.dig(:unit)] + [sample[:conversion_result][:supplier_order_unit], sample[:conversion_result][:group_order_unit], + sample[:conversion_result][:first_ratio]&.dig(:unit)] end.flatten.uniq.compact load_article_units(additional_units) @@ -225,25 +226,23 @@ def complete_units_migration def update_all invalid_articles = false - begin - Article.transaction do - unless params[:articles].blank? - # Update other article attributes... - @articles = Article.with_latest_versions_and_categories - .includes(latest_article_version: [:article_unit_ratios]) - .find(params[:articles].keys) - @articles.each do |article| - article_version_params = params[:articles][article.id.to_s] - article_version_params["id"] = article.latest_article_version.id - unless article.update_attributes(latest_article_version_attributes: article_version_params) - invalid_articles = true unless invalid_articles # Remember that there are validation errors - end + Article.transaction do + if params[:articles].present? + # Update other article attributes... + @articles = Article.with_latest_versions_and_categories + .includes(latest_article_version: [:article_unit_ratios]) + .find(params[:articles].keys) + @articles.each do |article| + article_version_params = params[:articles][article.id.to_s] + article_version_params['id'] = article.latest_article_version.id + unless article.update_attributes(latest_article_version_attributes: article_version_params) + invalid_articles ||= true # Remember that there are validation errors end + end - @supplier.update_attribute(:unit_migration_completed, Time.now) if params[:complete_migration] + @supplier.update_attribute(:unit_migration_completed, Time.now) if params[:complete_migration] - raise ActiveRecord::Rollback if invalid_articles # Rollback all changes - end + raise ActiveRecord::Rollback if invalid_articles # Rollback all changes end end @@ -280,16 +279,15 @@ def update_selected end end # action succeded - redirect_to supplier_articles_url(@supplier, :per_page => params[:per_page]) - rescue => error - redirect_to supplier_articles_url(@supplier, :per_page => params[:per_page]), - :alert => I18n.t('errors.general_msg', :msg => error) + redirect_to supplier_articles_url(@supplier, per_page: params[:per_page]) + rescue StandardError => e + redirect_to supplier_articles_url(@supplier, per_page: params[:per_page]), + alert: I18n.t('errors.general_msg', msg: e) end # lets start with parsing articles from uploaded file, yeah # Renders the upload form - def upload - end + def upload; end # Update articles from a spreadsheet def parse_upload @@ -297,17 +295,19 @@ def parse_upload options = { filename: uploaded_file.original_filename } options[:outlist_absent] = (params[:articles]['outlist_absent'] == '1') options[:convert_units] = (params[:articles]['convert_units'] == '1') - @updated_article_pairs, @outlisted_articles, @new_articles = @supplier.sync_from_file uploaded_file.tempfile, options + @updated_article_pairs, @outlisted_articles, @new_articles = @supplier.sync_from_file uploaded_file.tempfile, + options @articles = @updated_article_pairs.pluck(0) + @new_articles load_article_units if @updated_article_pairs.empty? && @outlisted_articles.empty? && @new_articles.empty? - redirect_to supplier_articles_path(@supplier), :notice => I18n.t('articles.controller.parse_upload.notice') + redirect_to supplier_articles_path(@supplier), + notice: I18n.t('articles.controller.parse_upload.notice') end @ignored_article_count = 0 - rescue => error - redirect_to upload_supplier_articles_path(@supplier), :alert => I18n.t('errors.general_msg', :msg => error.message) + rescue StandardError => e + redirect_to upload_supplier_articles_path(@supplier), alert: I18n.t('errors.general_msg', msg: e.message) end # sync all articles with the external database @@ -315,17 +315,20 @@ def parse_upload def sync @updated_article_pairs, @outlisted_articles, @new_articles = @supplier.sync_from_remote if @updated_article_pairs.empty? && @outlisted_articles.empty? && @new_articles.empty? - redirect_to supplier_articles_path(@supplier), :notice => I18n.t('articles.controller.parse_upload.notice') + redirect_to supplier_articles_path(@supplier), + notice: I18n.t('articles.controller.parse_upload.notice') end @ignored_article_count = 0 - rescue => error - redirect_to upload_supplier_articles_path(@supplier), :alert => I18n.t('errors.general_msg', :msg => error.message) + rescue StandardError => e + redirect_to upload_supplier_articles_path(@supplier), alert: I18n.t('errors.general_msg', msg: e.message) end # Updates, deletes articles when upload or sync form is submitted def update_synchronized @outlisted_articles = Article.includes(:latest_article_version).where(article_versions: { id: params[:outlisted_articles]&.values || [] }) - @updated_articles = Article.includes(:latest_article_version).where(article_versions: { id: params[:articles]&.values&.map { |v| v[:id] } || [] }) + @updated_articles = Article.includes(:latest_article_version).where(article_versions: { id: params[:articles]&.values&.map do |v| + v[:id] + end || [] }) @new_articles = (params[:new_articles]&.values || []).map do |a| article = @supplier.articles.build article_version = article.article_versions.build(a) @@ -340,7 +343,7 @@ def update_synchronized # delete articles begin @outlisted_articles.each(&:mark_as_deleted) - rescue + rescue StandardError # raises an exception when used in current order has_error = true end @@ -359,15 +362,15 @@ def update_synchronized raise ActiveRecord::Rollback if has_error end - if !has_error - redirect_to supplier_articles_path(@supplier), notice: I18n.t('articles.controller.update_sync.notice') - else + if has_error @updated_article_pairs = @updated_articles.map do |article| orig_article = Article.find(article.id) [article, orig_article.unequal_attributes(article)] end flash.now.alert = I18n.t('articles.controller.error_invalid') render params[:from_action] == 'sync' ? :sync : :parse_upload + else + redirect_to supplier_articles_path(@supplier), notice: I18n.t('articles.controller.update_sync.notice') end end @@ -385,9 +388,7 @@ def build_article_migration_samples article_version.billing_unit != article_version.group_order_unit || article_version.price_unit != article_version.group_order_unit - if ratios.length == 1 && ratios[0].quantity != 1 && ratios[0].unit == 'XPP' - quantity = ratios[0].quantity - end + quantity = ratios[0].quantity if ratios.length == 1 && ratios[0].quantity != 1 && ratios[0].unit == 'XPP' samples_hash[article_version.unit] = {} if samples_hash[article_version.unit].nil? samples_hash[article_version.unit][quantity] = [] if samples_hash[article_version.unit][quantity].nil? @@ -403,7 +404,8 @@ def build_article_migration_samples .reject { |sample| sample[:conversion_result].nil? } additional_units = @samples.map do |sample| - [sample[:conversion_result][:supplier_order_unit], sample[:conversion_result][:group_order_unit], sample[:conversion_result][:first_ratio]&.dig(:unit)] + [sample[:conversion_result][:supplier_order_unit], sample[:conversion_result][:group_order_unit], + sample[:conversion_result][:first_ratio]&.dig(:unit)] end.flatten.uniq.compact load_article_units(additional_units) end @@ -443,7 +445,9 @@ def new_empty_article_ratio # @return [Number] Number of articles not taken into account when syncing (having no number) def ignored_article_count if action_name == 'sync' || params[:from_action] == 'sync' - @ignored_article_count ||= @supplier.articles.includes(:latest_article_version).undeleted.where(article_versions: { order_number: [nil, ''] }).count + @ignored_article_count ||= @supplier.articles.includes(:latest_article_version).undeleted.where(article_versions: { order_number: [ + nil, '' + ] }).count else 0 end diff --git a/app/controllers/concerns/auth.rb b/app/controllers/concerns/auth.rb index 277acd69..f08622ad 100644 --- a/app/controllers/concerns/auth.rb +++ b/app/controllers/concerns/auth.rb @@ -9,15 +9,17 @@ module Concerns::Auth def current_user # check if there is a valid session and return the logged-in user (its object) - if session[:user_id] && params[:foodcoop] - # for shared-host installations. check if the cookie-subdomain fits to request. - @current_user ||= User.undeleted.find_by_id(session[:user_id]) if session[:scope] == FoodsoftConfig.scope - end + return unless session[:user_id] && params[:foodcoop] + + # for shared-host installations. check if the cookie-subdomain fits to request. + @current_user ||= User.undeleted.find_by_id(session[:user_id]) if session[:scope] == FoodsoftConfig.scope end def deny_access session[:return_to] = request.original_url - redirect_to root_url, alert: I18n.t('application.controller.error_denied', sign_in: ActionController::Base.helpers.link_to(t('application.controller.error_denied_sign_in'), login_path)) + redirect_to root_url, + alert: I18n.t('application.controller.error_denied', + sign_in: ActionController::Base.helpers.link_to(t('application.controller.error_denied_sign_in'), login_path)) end private @@ -47,12 +49,7 @@ def logout def authenticate(role = 'any') # Attempt to retrieve authenticated user from controller instance or session... - if !current_user - # No user at all: redirect to login page. - logout - session[:return_to] = request.original_url - redirect_to_login :alert => I18n.t('application.controller.error_authn') - else + if current_user # We have an authenticated user, now check role... # Roles gets the user through his memberships. hasRole = case role @@ -62,9 +59,9 @@ def authenticate(role = 'any') 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 '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 @@ -73,6 +70,11 @@ def authenticate(role = 'any') else deny_access end + else + # No user at all: redirect to login page. + logout + session[:return_to] = request.original_url + redirect_to_login alert: I18n.t('application.controller.error_authn') end end @@ -116,13 +118,13 @@ def authenticate_pickups_or_orders # if fails the user will redirected to startpage def authenticate_membership_or_admin(group_id = params[:id]) @group = Group.find(group_id) - unless @group.member?(@current_user) || @current_user.role_admin? - redirect_to root_path, alert: I18n.t('application.controller.error_members_only') - end + return if @group.member?(@current_user) || @current_user.role_admin? + + redirect_to root_path, alert: I18n.t('application.controller.error_members_only') end def authenticate_or_token(prefix, role = 'any') - if not params[:token].blank? + if params[:token].present? begin TokenVerifier.new(prefix).verify(params[:token]) rescue ActiveSupport::MessageVerifier::InvalidSignature diff --git a/app/controllers/concerns/auth_api.rb b/app/controllers/concerns/auth_api.rb index 2c80dddf..fc16a2c2 100644 --- a/app/controllers/concerns/auth_api.rb +++ b/app/controllers/concerns/auth_api.rb @@ -36,9 +36,9 @@ def doorkeeper_authorize!(*scopes) # Make sure that at least one the given OAuth scopes is valid for the current user's permissions. # @raise Api::Errors::PermissionsRequired def doorkeeper_authorize_roles!(*scopes) - unless scopes.any? { |scope| doorkeeper_scope_permitted?(scope) } - raise Api::Errors::PermissionRequired.new('Forbidden, no permission') - end + return if scopes.any? { |scope| doorkeeper_scope_permitted?(scope) } + + raise Api::Errors::PermissionRequired, 'Forbidden, no permission' end # Check whether a given OAuth scope is permitted for the current user. @@ -48,9 +48,7 @@ def doorkeeper_authorize_roles!(*scopes) def doorkeeper_scope_permitted?(scope) scope_parts = scope.split(':') # user sub-scopes like +config:user+ are always permitted - if scope_parts.last == 'user' - return true - end + return true if scope_parts.last == 'user' case scope_parts.first when 'user' then return true # access to the current user's own profile @@ -64,8 +62,8 @@ def doorkeeper_scope_permitted?(scope) end case scope - when 'orders:read' then return true - when 'orders:write' then return current_user.role_orders? + when 'orders:read' then true + when 'orders:write' then current_user.role_orders? end end end diff --git a/app/controllers/concerns/foodcoop_scope.rb b/app/controllers/concerns/foodcoop_scope.rb index 0a8e382e..7a99adf9 100644 --- a/app/controllers/concerns/foodcoop_scope.rb +++ b/app/controllers/concerns/foodcoop_scope.rb @@ -24,12 +24,12 @@ def select_foodcoop elsif FoodsoftConfig.allowed_foodcoop? foodcoop FoodsoftConfig.select_foodcoop foodcoop else - raise ActionController::RoutingError.new 'Foodcoop Not Found' + raise ActionController::RoutingError, 'Foodcoop Not Found' end end # Always stay in foodcoop url scope - def default_url_options(options = {}) + def default_url_options(_options = {}) super().merge({ foodcoop: FoodsoftConfig.scope }) end end diff --git a/app/controllers/concerns/locale.rb b/app/controllers/concerns/locale.rb index 22686c15..c55d48a2 100644 --- a/app/controllers/concerns/locale.rb +++ b/app/controllers/concerns/locale.rb @@ -30,7 +30,7 @@ def default_language def select_language_according_to_priority language = explicitly_requested_language || session_language || user_settings_language language ||= browser_language unless FoodsoftConfig[:ignore_browser_locale] - language.presence&.to_sym unless language.blank? + language.presence&.to_sym if language.present? end def available_locales @@ -38,11 +38,11 @@ def available_locales end def set_locale - if available_locales.include?(select_language_according_to_priority) - ::I18n.locale = select_language_according_to_priority - else - ::I18n.locale = default_language - end + ::I18n.locale = if available_locales.include?(select_language_according_to_priority) + select_language_according_to_priority + else + default_language + end locale = session[:locale] = ::I18n.locale logger.info("Set locale to #{locale}") diff --git a/app/controllers/concerns/send_order_pdf.rb b/app/controllers/concerns/send_order_pdf.rb index 09225b7c..283512da 100644 --- a/app/controllers/concerns/send_order_pdf.rb +++ b/app/controllers/concerns/send_order_pdf.rb @@ -3,7 +3,7 @@ module Concerns::SendOrderPdf protected - def send_order_pdf order, document + def send_order_pdf(order, document) klass = case document when 'groups' then OrderByGroups when 'articles' then OrderByArticles diff --git a/app/controllers/deliveries_controller.rb b/app/controllers/deliveries_controller.rb index ae8b1095..955cea82 100644 --- a/app/controllers/deliveries_controller.rb +++ b/app/controllers/deliveries_controller.rb @@ -1,5 +1,5 @@ class DeliveriesController < ApplicationController - before_action :find_supplier, :exclude => :fill_new_stock_article_form + before_action :find_supplier, exclude: :fill_new_stock_article_form def index @deliveries = @supplier.deliveries.order('date DESC') @@ -15,6 +15,10 @@ def new @delivery.date = Date.today # TODO: move to model/database end + def edit + @delivery = Delivery.find(params[:id]) + end + def create @delivery = Delivery.new(params[:delivery]) @@ -22,14 +26,10 @@ def create flash[:notice] = I18n.t('deliveries.create.notice') redirect_to [@supplier, @delivery] else - render :action => "new" + render action: 'new' end end - def edit - @delivery = Delivery.find(params[:id]) - end - def update @delivery = Delivery.find(params[:id]) @@ -37,7 +37,7 @@ def update flash[:notice] = I18n.t('deliveries.update.notice') redirect_to [@supplier, @delivery] else - render :action => "edit" + render action: 'edit' end end @@ -52,18 +52,18 @@ def destroy def add_stock_change @stock_change = StockChange.new @stock_change.stock_article = StockArticle.find(params[:stock_article_id]) - render :layout => false + render layout: false end def form_on_stock_article_create # See publish/subscribe design pattern in /doc. @stock_article = StockArticle.find(params[:id]) - render :layout => false + render layout: false end def form_on_stock_article_update # See publish/subscribe design pattern in /doc. @stock_article = StockArticle.find(params[:id]) - render :layout => false + render layout: false end end diff --git a/app/controllers/feedback_controller.rb b/app/controllers/feedback_controller.rb index ada72859..b4e5ea7e 100644 --- a/app/controllers/feedback_controller.rb +++ b/app/controllers/feedback_controller.rb @@ -1,13 +1,12 @@ class FeedbackController < ApplicationController - def new - end + def new; end def create if params[:message].present? Mailer.feedback(current_user, params[:message]).deliver_now - redirect_to root_url, notice: t('feedback.create.notice') + redirect_to root_url, notice: t('.notice') else - render :action => 'new' + render action: 'new' end end end diff --git a/app/controllers/finance/balancing_controller.rb b/app/controllers/finance/balancing_controller.rb index 8d817f02..6f85fd13 100644 --- a/app/controllers/finance/balancing_controller.rb +++ b/app/controllers/finance/balancing_controller.rb @@ -5,7 +5,7 @@ def index def new @order = Order.find(params[:order_id]) - flash.now.alert = t('finance.balancing.new.alert') if @order.closed? + flash.now.alert = t('.alert') if @order.closed? @comments = @order.comments @articles = @order.order_articles.ordered_or_member.includes(article_version: :article, @@ -13,13 +13,13 @@ def new sort_param = params['sort'] || 'name' @articles = case sort_param - when 'name' then + when 'name' @articles.order('article_versions.name ASC') - when 'name_reverse' then + when 'name_reverse' @articles.order('article_versions.name DESC') - when 'order_number' then + when 'order_number' @articles.order('article_versions.order_number ASC') - when 'order_number_reverse' then + when 'order_number_reverse' @articles.order('article_versions.order_number DESC') else @articles @@ -31,13 +31,13 @@ def new def new_on_order_article_create # See publish/subscribe design pattern in /doc. @order_article = OrderArticle.find(params[:order_article_id]) - render :layout => false + render layout: false end def new_on_order_article_update # See publish/subscribe design pattern in /doc. @order_article = OrderArticle.find(params[:order_article_id]) - render :layout => false + render layout: false end def update_summary @@ -46,29 +46,29 @@ def update_summary def edit_note @order = Order.find(params[:id]) - render :layout => false + render layout: false end def update_note @order = Order.find(params[:id]) if @order.update_attributes(params[:order]) - render :layout => false + render layout: false else - render :action => :edit_note, :layout => false + render action: :edit_note, layout: false end end def edit_transport @order = Order.find(params[:id]) - render :layout => false + render layout: false end def update_transport @order = Order.find(params[:id]) @order.update_attributes! params[:order] redirect_to new_finance_order_path(order_id: @order.id) - rescue => error - redirect_to new_finance_order_path(order_id: @order.id), alert: t('errors.general_msg', msg: error.message) + rescue StandardError => e + redirect_to new_finance_order_path(order_id: @order.id), alert: t('errors.general_msg', msg: e.message) end # before the order will booked, a view lists all Ordergroups and its order_prices @@ -81,7 +81,7 @@ def close @order = Order.find(params[:id]) @type = FinancialTransactionType.find_by_id(params.permit(:type)[:type]) @order.close!(@current_user, @type) - redirect_to finance_order_index_url, notice: t('finance.balancing.close.notice') + redirect_to finance_order_index_url, notice: t('.notice') # TODO-article-version # rescue => error # redirect_to new_finance_order_url(order_id: @order.id), alert: t('finance.balancing.close.alert', message: error.message) @@ -91,9 +91,9 @@ def close def close_direct @order = Order.find(params[:id]) @order.close_direct!(@current_user) - redirect_to finance_order_index_url, notice: t('finance.balancing.close_direct.notice') - rescue => error - redirect_to finance_order_index_url, alert: t('finance.balancing.close_direct.alert', message: error.message) + redirect_to finance_order_index_url, notice: t('.notice') + rescue StandardError => e + redirect_to finance_order_index_url, alert: t('.alert', message: e.message) end def close_all_direct_with_invoice @@ -104,8 +104,8 @@ def close_all_direct_with_invoice count += 1 end end - redirect_to finance_order_index_url, notice: t('finance.balancing.close_all_direct_with_invoice.notice', count: count) - rescue => error - redirect_to finance_order_index_url, alert: t('errors.general_msg', msg: error.message) + redirect_to finance_order_index_url, notice: t('.notice', count: count) + rescue StandardError => e + redirect_to finance_order_index_url, alert: t('errors.general_msg', msg: e.message) end end diff --git a/app/controllers/finance/bank_accounts_controller.rb b/app/controllers/finance/bank_accounts_controller.rb index 66d9fddd..81403f6a 100644 --- a/app/controllers/finance/bank_accounts_controller.rb +++ b/app/controllers/finance/bank_accounts_controller.rb @@ -8,8 +8,8 @@ def assign_unlinked_transactions @bank_account = BankAccount.find(params[:id]) count = @bank_account.assign_unlinked_transactions redirect_to finance_bank_account_transactions_url(@bank_account), notice: t('.notice', count: count) - rescue => error - redirect_to finance_bank_account_transactions_url(@bank_account), alert: t('errors.general_msg', msg: error.message) + rescue StandardError => e + redirect_to finance_bank_account_transactions_url(@bank_account), alert: t('errors.general_msg', msg: e.message) end def import @@ -33,8 +33,8 @@ def import end needs_redirect = ok - rescue => error - flash.alert = t('errors.general_msg', msg: error.message) + rescue StandardError => e + flash.alert = t('errors.general_msg', msg: e.message) needs_redirect = true ensure return unless needs_redirect diff --git a/app/controllers/finance/bank_transactions_controller.rb b/app/controllers/finance/bank_transactions_controller.rb index 53c35168..22b38d06 100644 --- a/app/controllers/finance/bank_transactions_controller.rb +++ b/app/controllers/finance/bank_transactions_controller.rb @@ -3,26 +3,30 @@ class Finance::BankTransactionsController < ApplicationController inherit_resources def index - if params["sort"] - sort = case params["sort"] - when "date" then "date" - when "amount" then "amount" - when "financial_link" then "financial_link_id" - when "date_reverse" then "date DESC" - when "amount_reverse" then "amount DESC" - when "financial_link_reverse" then "financial_link_id DESC" + sort = if params['sort'] + case params['sort'] + when 'date' then 'date' + when 'amount' then 'amount' + when 'financial_link' then 'financial_link_id' + when 'date_reverse' then 'date DESC' + when 'amount_reverse' then 'amount DESC' + when 'financial_link_reverse' then 'financial_link_id DESC' end - else - sort = "date DESC" - end + else + 'date DESC' + end @bank_account = BankAccount.find(params[:bank_account_id]) @bank_transactions_all = @bank_account.bank_transactions.order(sort).includes(:financial_link) - @bank_transactions_all = @bank_transactions_all.where('reference LIKE ? OR text LIKE ?', "%#{params[:query]}%", "%#{params[:query]}%") unless params[:query].nil? + unless params[:query].nil? + @bank_transactions_all = @bank_transactions_all.where('reference LIKE ? OR text LIKE ?', "%#{params[:query]}%", + "%#{params[:query]}%") + end @bank_transactions = @bank_transactions_all.page(params[:page]).per(@per_page) respond_to do |format| - format.js; format.html { render } + format.js + format.html { render } format.csv do send_data BankTransactionsCsv.new(@bank_transactions_all).to_csv, filename: 'transactions.csv', type: 'text/csv' end diff --git a/app/controllers/finance/financial_links_controller.rb b/app/controllers/finance/financial_links_controller.rb index 17d8399a..09783640 100644 --- a/app/controllers/finance/financial_links_controller.rb +++ b/app/controllers/finance/financial_links_controller.rb @@ -1,5 +1,5 @@ class Finance::FinancialLinksController < Finance::BaseController - before_action :find_financial_link, except: [:create, :incomplete] + before_action :find_financial_link, except: %i[create incomplete] def show @items = @financial_link.bank_transactions.map do |bt| @@ -37,7 +37,7 @@ def show def create @financial_link = FinancialLink.first_unused_or_create - if params[:bank_transaction] then + if params[:bank_transaction] bank_transaction = BankTransaction.find(params[:bank_transaction]) bank_transaction.update_attribute :financial_link, @financial_link end @@ -72,14 +72,16 @@ def new_financial_transaction def create_financial_transaction financial_transaction = FinancialTransaction.new(financial_transaction_params) - financial_transaction.ordergroup.add_financial_transaction! financial_transaction.amount, financial_transaction.note, current_user, financial_transaction.financial_transaction_type, @financial_link + financial_transaction.ordergroup.add_financial_transaction! financial_transaction.amount, + financial_transaction.note, current_user, financial_transaction.financial_transaction_type, @financial_link redirect_to finance_link_url(@financial_link), notice: t('.notice') - rescue => error - redirect_to finance_link_url(@financial_link), alert: t('errors.general_msg', msg: error) + rescue StandardError => e + redirect_to finance_link_url(@financial_link), alert: t('errors.general_msg', msg: e) end def index_financial_transaction - @financial_transactions = FinancialTransaction.without_financial_link.includes(:financial_transaction_type, :ordergroup) + @financial_transactions = FinancialTransaction.without_financial_link.includes(:financial_transaction_type, + :ordergroup) end def add_financial_transaction diff --git a/app/controllers/finance/financial_transactions_controller.rb b/app/controllers/finance/financial_transactions_controller.rb index 8b9d372d..c1a619a5 100644 --- a/app/controllers/finance/financial_transactions_controller.rb +++ b/app/controllers/finance/financial_transactions_controller.rb @@ -1,22 +1,22 @@ class Finance::FinancialTransactionsController < ApplicationController before_action :authenticate_finance - before_action :find_ordergroup, :except => [:new_collection, :create_collection, :index_collection] + before_action :find_ordergroup, except: %i[new_collection create_collection index_collection] inherit_resources # belongs_to :ordergroup def index - if params['sort'] - sort = case params['sort'] - when "date" then "created_on" - when "note" then "note" - when "amount" then "amount" - when "date_reverse" then "created_on DESC" - when "note_reverse" then "note DESC" - when "amount_reverse" then "amount DESC" + sort = if params['sort'] + case params['sort'] + when 'date' then 'created_on' + when 'note' then 'note' + when 'amount' then 'amount' + when 'date_reverse' then 'created_on DESC' + when 'note_reverse' then 'note DESC' + when 'amount_reverse' then 'amount DESC' end - else - sort = "created_on DESC" - end + else + 'created_on DESC' + end @q = FinancialTransaction.search(params[:q]) @financial_transactions_all = @q.result(distinct: true).includes(:user).order(sort) @@ -26,9 +26,11 @@ def index @financial_transactions = @financial_transactions_all.page(params[:page]).per(@per_page) respond_to do |format| - format.js; format.html { render } + format.js + format.html { render } format.csv do - send_data FinancialTransactionsCsv.new(@financial_transactions_all).to_csv, filename: 'transactions.csv', type: 'text/csv' + send_data FinancialTransactionsCsv.new(@financial_transactions_all).to_csv, filename: 'transactions.csv', + type: 'text/csv' end end end @@ -38,11 +40,11 @@ def index_collection end def new - if @ordergroup - @financial_transaction = @ordergroup.financial_transactions.build - else - @financial_transaction = FinancialTransaction.new - end + @financial_transaction = if @ordergroup + @ordergroup.financial_transactions.build + else + FinancialTransaction.new + end end def create @@ -53,16 +55,18 @@ def create else @financial_transaction.save! end - redirect_to finance_group_transactions_path(@ordergroup), notice: I18n.t('finance.financial_transactions.controller.create.notice') - rescue ActiveRecord::RecordInvalid => error - flash.now[:alert] = error.message - render :action => :new + redirect_to finance_group_transactions_path(@ordergroup), + notice: I18n.t('finance.financial_transactions.controller.create.notice') + rescue ActiveRecord::RecordInvalid => e + flash.now[:alert] = e.message + render action: :new end def destroy transaction = FinancialTransaction.find(params[:id]) transaction.revert!(current_user) - redirect_to finance_group_transactions_path(transaction.ordergroup), notice: t('finance.financial_transactions.controller.destroy.notice') + redirect_to finance_group_transactions_path(transaction.ordergroup), + notice: t('finance.financial_transactions.controller.destroy.notice') end def new_collection @@ -88,17 +92,17 @@ def create_collection params[:financial_transactions].each do |trans| # ignore empty amount fields ... - unless trans[:amount].blank? - amount = trans[:amount].to_f - note = params[:note] - ordergroup = Ordergroup.find(trans[:ordergroup_id]) - if params[:set_balance] - note += " (#{amount})" - amount -= ordergroup.financial_transaction_class_balance(type.financial_transaction_class) - end - ordergroup.add_financial_transaction!(amount, note, @current_user, type, financial_link) - foodcoop_amount -= amount + next if trans[:amount].blank? + + amount = trans[:amount].to_f + note = params[:note] + ordergroup = Ordergroup.find(trans[:ordergroup_id]) + if params[:set_balance] + note += " (#{amount})" + amount -= ordergroup.financial_transaction_class_balance(type.financial_transaction_class) end + ordergroup.add_financial_transaction!(amount, note, @current_user, type, financial_link) + foodcoop_amount -= amount end if params[:create_foodcoop_transaction] @@ -107,7 +111,7 @@ def create_collection user: @current_user, amount: foodcoop_amount, note: params[:note], - financial_link: financial_link, + financial_link: financial_link }) ft.save! end @@ -117,8 +121,8 @@ def create_collection url = financial_link ? finance_link_url(financial_link.id) : finance_ordergroups_url redirect_to url, notice: I18n.t('finance.financial_transactions.controller.create_collection.notice') - rescue => error - flash.now[:alert] = error.message + rescue StandardError => e + flash.now[:alert] = e.message render action: :new_collection end diff --git a/app/controllers/finance/invoices_controller.rb b/app/controllers/finance/invoices_controller.rb index 33949017..64cab6d8 100644 --- a/app/controllers/finance/invoices_controller.rb +++ b/app/controllers/finance/invoices_controller.rb @@ -1,15 +1,16 @@ class Finance::InvoicesController < ApplicationController before_action :authenticate_finance_or_invoices - before_action :find_invoice, only: [:show, :edit, :update, :destroy] - before_action :ensure_can_edit, only: [:edit, :update, :destroy] + before_action :find_invoice, only: %i[show edit update destroy] + before_action :ensure_can_edit, only: %i[edit update destroy] def index @invoices_all = Invoice.includes(:supplier, :deliveries, :orders).order('date DESC') @invoices = @invoices_all.page(params[:page]).per(@per_page) respond_to do |format| - format.js; format.html { render } + format.js + format.html { render } format.csv do send_data InvoicesCsv.new(@invoices_all).to_csv, filename: 'invoices.csv', type: 'text/csv' end @@ -20,11 +21,10 @@ def unpaid @suppliers = Supplier.includes(:invoices).where('invoices.paid_on IS NULL').references(:invoices) end - def show - end + def show; end def new - @invoice = Invoice.new :supplier_id => params[:supplier_id] + @invoice = Invoice.new supplier_id: params[:supplier_id] @invoice.deliveries << Delivery.find_by_id(params[:delivery_id]) if params[:delivery_id] @invoice.orders << Order.find_by_id(params[:order_id]) if params[:order_id] fill_deliveries_and_orders_collection @invoice.id, @invoice.supplier_id @@ -36,12 +36,14 @@ def edit def form_on_supplier_id_change fill_deliveries_and_orders_collection params[:invoice_id], params[:supplier_id] - render :layout => false + render layout: false end def fill_deliveries_and_orders_collection(invoice_id, supplier_id) - @deliveries_collection = Delivery.where('invoice_id = ? OR (invoice_id IS NULL AND supplier_id = ?)', invoice_id, supplier_id).order(date: :desc).limit(25) - @orders_collection = Order.where('invoice_id = ? OR (invoice_id IS NULL AND supplier_id = ?)', invoice_id, supplier_id).order(ends: :desc).limit(25) + @deliveries_collection = Delivery.where('invoice_id = ? OR (invoice_id IS NULL AND supplier_id = ?)', invoice_id, + supplier_id).order(date: :desc).limit(25) + @orders_collection = Order.where('invoice_id = ? OR (invoice_id IS NULL AND supplier_id = ?)', invoice_id, + supplier_id).order(ends: :desc).limit(25) end def create @@ -58,7 +60,7 @@ def create end else fill_deliveries_and_orders_collection @invoice.id, @invoice.supplier_id - render :action => "new" + render action: 'new' end end @@ -81,7 +83,7 @@ def attachment @invoice = Invoice.find(params[:invoice_id]) type = MIME::Types[@invoice.attachment_mime].first filename = "invoice_#{@invoice.id}_attachment.#{type.preferred_extension}" - send_data(@invoice.attachment_data, :filename => filename, :type => type) + send_data(@invoice.attachment_data, filename: filename, type: type) end private @@ -92,8 +94,8 @@ def find_invoice # Returns true if @current_user can edit the invoice.. def ensure_can_edit - unless @invoice.user_can_edit?(current_user) - deny_access - end + return if @invoice.user_can_edit?(current_user) + + deny_access end end diff --git a/app/controllers/finance/ordergroups_controller.rb b/app/controllers/finance/ordergroups_controller.rb index cb661571..a8836f6b 100644 --- a/app/controllers/finance/ordergroups_controller.rb +++ b/app/controllers/finance/ordergroups_controller.rb @@ -1,11 +1,11 @@ class Finance::OrdergroupsController < Finance::BaseController def index - m = /^(?name|sum_of_class_\d+)(?_reverse)?$/.match params["sort"] + m = /^(?name|sum_of_class_\d+)(?_reverse)?$/.match params['sort'] if m sort = m[:col] sort += ' DESC' if m[:reverse] else - sort = "name" + sort = 'name' end @ordergroups = Ordergroup.undeleted.order(sort) diff --git a/app/controllers/foodcoop/ordergroups_controller.rb b/app/controllers/foodcoop/ordergroups_controller.rb index 8aeb977e..a6a6d104 100644 --- a/app/controllers/foodcoop/ordergroups_controller.rb +++ b/app/controllers/foodcoop/ordergroups_controller.rb @@ -2,19 +2,15 @@ class Foodcoop::OrdergroupsController < ApplicationController def index @ordergroups = Ordergroup.undeleted.order('name') - unless params[:name].blank? # Search by name - @ordergroups = @ordergroups.where('name LIKE ?', "%#{params[:name]}%") - end + @ordergroups = @ordergroups.where('name LIKE ?', "%#{params[:name]}%") if params[:name].present? # Search by name - if params[:only_active] # Select only active groups - @ordergroups = @ordergroups.active - end + @ordergroups = @ordergroups.active if params[:only_active] # Select only active groups @ordergroups = @ordergroups.page(params[:page]).per(@per_page) respond_to do |format| format.html # index.html.erb - format.js { render :layout => false } + format.js { render layout: false } end end end diff --git a/app/controllers/foodcoop/users_controller.rb b/app/controllers/foodcoop/users_controller.rb index a3a8bd45..c4684126 100644 --- a/app/controllers/foodcoop/users_controller.rb +++ b/app/controllers/foodcoop/users_controller.rb @@ -3,17 +3,18 @@ def index @users = User.undeleted.natural_order # if somebody uses the search field: - @users = @users.natural_search(params[:user_name]) unless params[:user_name].blank? + @users = @users.natural_search(params[:user_name]) if params[:user_name].present? if params[:ordergroup_name] - @users = @users.joins(:groups).where("groups.type = 'Ordergroup' AND groups.name LIKE ?", "%#{params[:ordergroup_name]}%") + @users = @users.joins(:groups).where("groups.type = 'Ordergroup' AND groups.name LIKE ?", + "%#{params[:ordergroup_name]}%") end @users = @users.page(params[:page]).per(@per_page) respond_to do |format| format.html # index.html.haml - format.js { render :layout => false } # index.js.erb + format.js { render layout: false } # index.js.erb end end end diff --git a/app/controllers/foodcoop/workgroups_controller.rb b/app/controllers/foodcoop/workgroups_controller.rb index 794c21a0..ce63ac84 100644 --- a/app/controllers/foodcoop/workgroups_controller.rb +++ b/app/controllers/foodcoop/workgroups_controller.rb @@ -1,9 +1,9 @@ class Foodcoop::WorkgroupsController < ApplicationController before_action :authenticate_membership_or_admin, - :except => [:index] + except: [:index] def index - @workgroups = Workgroup.order("name") + @workgroups = Workgroup.order('name') end def edit @@ -13,9 +13,9 @@ def edit def update @workgroup = Workgroup.find(params[:id]) if @workgroup.update_attributes(params[:workgroup]) - redirect_to foodcoop_workgroups_url, :notice => I18n.t('workgroups.update.notice') + redirect_to foodcoop_workgroups_url, notice: I18n.t('workgroups.update.notice') else - render :action => 'edit' + render action: 'edit' end end end diff --git a/app/controllers/group_order_articles_controller.rb b/app/controllers/group_order_articles_controller.rb index 339fb223..4351b04b 100644 --- a/app/controllers/group_order_articles_controller.rb +++ b/app/controllers/group_order_articles_controller.rb @@ -1,8 +1,8 @@ class GroupOrderArticlesController < ApplicationController before_action :authenticate_finance - before_action :find_group_order_article, except: [:new, :create] + before_action :find_group_order_article, except: %i[new create] - layout false # We only use this controller to server js snippets, no need for layout rendering + layout false # We only use this controller to server js snippets, no need for layout rendering def new @order_article = OrderArticle.find(params[:order_article_id]) diff --git a/app/controllers/group_orders_controller.rb b/app/controllers/group_orders_controller.rb index 686f0617..e5a442aa 100644 --- a/app/controllers/group_orders_controller.rb +++ b/app/controllers/group_orders_controller.rb @@ -3,9 +3,9 @@ class GroupOrdersController < ApplicationController # Security before_action :ensure_ordergroup_member - before_action :ensure_open_order, :only => [:new, :create, :edit, :update, :order, :stock_order, :saveOrder] - before_action :ensure_my_group_order, only: [:show, :edit, :update] - before_action :enough_apples?, only: [:new, :create] + before_action :ensure_open_order, only: %i[new create edit update order stock_order saveOrder] + before_action :ensure_my_group_order, only: %i[show edit update] + before_action :enough_apples?, only: %i[new create] # Index page. def index @@ -13,9 +13,17 @@ def index @finished_not_closed_orders_including_group_order = Order.finished_not_closed.ordergroup_group_orders_map(@ordergroup) end + def show + @order = @group_order.order + end + def new ordergroup = params[:stock_order] ? nil : @ordergroup - @group_order = @order.group_orders.build(:ordergroup => ordergroup, :updated_by => current_user) + @group_order = @order.group_orders.build(ordergroup: ordergroup, updated_by: current_user) + @ordering_data = @group_order.load_data + end + + def edit @ordering_data = @group_order.load_data end @@ -23,34 +31,26 @@ def create @group_order = GroupOrder.new(params[:group_order]) begin @group_order.save_ordering! - redirect_to group_order_url(@group_order), :notice => I18n.t('group_orders.create.notice') + redirect_to group_order_url(@group_order), notice: I18n.t('group_orders.create.notice') rescue ActiveRecord::StaleObjectError - redirect_to group_orders_url, :alert => I18n.t('group_orders.create.error_stale') - rescue => exception - logger.error('Failed to update order: ' + exception.message) - redirect_to group_orders_url, :alert => I18n.t('group_orders.create.error_general') + redirect_to group_orders_url, alert: I18n.t('group_orders.create.error_stale') + rescue StandardError => e + logger.error('Failed to update order: ' + e.message) + redirect_to group_orders_url, alert: I18n.t('group_orders.create.error_general') end end - def show - @order = @group_order.order - end - - def edit - @ordering_data = @group_order.load_data - end - def update @group_order.attributes = params[:group_order] @group_order.updated_by = current_user begin @group_order.save_ordering! - redirect_to group_order_url(@group_order), :notice => I18n.t('group_orders.update.notice') + redirect_to group_order_url(@group_order), notice: I18n.t('group_orders.update.notice') rescue ActiveRecord::StaleObjectError - redirect_to group_orders_url, :alert => I18n.t('group_orders.update.error_stale') - rescue => exception - logger.error('Failed to update order: ' + exception.message) - redirect_to group_orders_url, :alert => I18n.t('group_orders.update.error_general') + redirect_to group_orders_url, alert: I18n.t('group_orders.update.error_stale') + rescue StandardError => e + logger.error('Failed to update order: ' + e.message) + redirect_to group_orders_url, alert: I18n.t('group_orders.update.error_general') end end @@ -74,16 +74,16 @@ def archive # Used as a :before_action by OrdersController. def ensure_ordergroup_member @ordergroup = @current_user.ordergroup - if @ordergroup.nil? - redirect_to root_url, :alert => I18n.t('group_orders.errors.no_member') - end + return unless @ordergroup.nil? + + redirect_to root_url, alert: I18n.t('group_orders.errors.no_member') end def ensure_open_order - @order = Order.includes([:supplier, :order_articles]).find(order_id_param) + @order = Order.includes(%i[supplier order_articles]).find(order_id_param) unless @order.open? flash[:notice] = I18n.t('group_orders.errors.closed') - redirect_to :action => 'index' + redirect_to action: 'index' end rescue ActiveRecord::RecordNotFound redirect_to group_orders_url, alert: I18n.t('group_orders.errors.notfound') @@ -91,17 +91,17 @@ def ensure_open_order def ensure_my_group_order @group_order = GroupOrder.find(params[:id]) - if @group_order.ordergroup != @ordergroup && (@group_order.ordergroup || !current_user.role_orders?) - redirect_to group_orders_url, alert: I18n.t('group_orders.errors.notfound') - end + return unless @group_order.ordergroup != @ordergroup && (@group_order.ordergroup || !current_user.role_orders?) + + redirect_to group_orders_url, alert: I18n.t('group_orders.errors.notfound') end def enough_apples? - if @ordergroup.not_enough_apples? - redirect_to group_orders_url, - alert: t('not_enough_apples', scope: 'group_orders.messages', apples: @ordergroup.apples, - stop_ordering_under: FoodsoftConfig[:stop_ordering_under]) - end + return unless @ordergroup.not_enough_apples? + + redirect_to group_orders_url, + alert: t('not_enough_apples', scope: 'group_orders.messages', apples: @ordergroup.apples, + stop_ordering_under: FoodsoftConfig[:stop_ordering_under]) end def order_id_param diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index 6f677b6b..50c4dce7 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -9,8 +9,7 @@ def index @unassigned_tasks = Task.order(:due_date).next_unassigned_tasks_for(current_user) end - def profile - end + def profile; end def reference_calculator if current_user.ordergroup @@ -36,40 +35,43 @@ def ordergroup @user = @current_user @ordergroup = @user.ordergroup - unless @ordergroup.nil? + if @ordergroup.nil? + redirect_to root_path, alert: I18n.t('home.no_ordergroups') + else @ordergroup = Ordergroup.include_transaction_class_sum.find(@ordergroup.id) - if params['sort'] - sort = case params['sort'] - when "date" then "created_on" - when "note" then "note" - when "amount" then "amount" - when "date_reverse" then "created_on DESC" - when "note_reverse" then "note DESC" - when "amount_reverse" then "amount DESC" + sort = if params['sort'] + case params['sort'] + when 'date' then 'created_on' + when 'note' then 'note' + when 'amount' then 'amount' + when 'date_reverse' then 'created_on DESC' + when 'note_reverse' then 'note DESC' + when 'amount_reverse' then 'amount DESC' end - else - sort = "created_on DESC" - end + else + 'created_on DESC' + end @financial_transactions = @ordergroup.financial_transactions.visible.page(params[:page]).per(@per_page).order(sort) - @financial_transactions = @financial_transactions.where('financial_transactions.note LIKE ?', "%#{params[:query]}%") if params[:query].present? + if params[:query].present? + @financial_transactions = @financial_transactions.where('financial_transactions.note LIKE ?', + "%#{params[:query]}%") + end - else - redirect_to root_path, alert: I18n.t('home.no_ordergroups') end end # cancel personal memberships direct from the myProfile-page def cancel_membership - if params[:membership_id] - membership = @current_user.memberships.find!(params[:membership_id]) - else - membership = @current_user.memberships.find_by_group_id!(params[:group_id]) - end + membership = if params[:membership_id] + @current_user.memberships.find!(params[:membership_id]) + else + @current_user.memberships.find_by_group_id!(params[:group_id]) + end membership.destroy - redirect_to my_profile_path, notice: I18n.t('home.ordergroup_cancelled', :group => membership.group.name) + redirect_to my_profile_path, notice: I18n.t('home.ordergroup_cancelled', group: membership.group.name) end protected @@ -82,8 +84,8 @@ def user_params end def ordergroup_params - if params[:user][:ordergroup] - params.require(:user).require(:ordergroup).permit(:contact_address) - end + return unless params[:user][:ordergroup] + + params.require(:user).require(:ordergroup).permit(:contact_address) end end diff --git a/app/controllers/invites_controller.rb b/app/controllers/invites_controller.rb index 37fc757b..266a1de5 100644 --- a/app/controllers/invites_controller.rb +++ b/app/controllers/invites_controller.rb @@ -3,7 +3,7 @@ class InvitesController < ApplicationController before_action -> { require_config_disabled :disable_invite } def new - @invite = Invite.new(:user => @current_user, :group => @group) + @invite = Invite.new(user: @current_user, group: @group) end def create @@ -27,6 +27,10 @@ def create protected def authenticate_membership_or_admin_for_invites - authenticate_membership_or_admin((params[:invite][:group_id] rescue params[:id])) + authenticate_membership_or_admin(begin + params[:invite][:group_id] + rescue StandardError + params[:id] + end) end end diff --git a/app/controllers/login_controller.rb b/app/controllers/login_controller.rb index 052231c5..4c2fd95b 100644 --- a/app/controllers/login_controller.rb +++ b/app/controllers/login_controller.rb @@ -1,6 +1,6 @@ class LoginController < ApplicationController skip_before_action :authenticate # no authentication since this is the login page - before_action :validate_token, :only => [:new_password, :update_password] + before_action :validate_token, only: %i[new_password update_password] # Display the form to enter an email address requesting a token to set a new password. def forgot_password @@ -9,20 +9,17 @@ def forgot_password # Sends an email to a user with the token that allows setting a new password through action "password". def reset_password - if request.get? || params[:user].nil? # Catch for get request and give better error message. - redirect_to forgot_password_url, alert: I18n.t('errors.general_again') and return - end + redirect_to forgot_password_url, alert: I18n.t('errors.general_again') and return if request.get? || params[:user].nil? # Catch for get request and give better error message. if (user = User.undeleted.find_by_email(params[:user][:email])) user.request_password_reset! end - redirect_to login_url, :notice => I18n.t('login.controller.reset_password.notice') + redirect_to login_url, notice: I18n.t('login.controller.reset_password.notice') end # Set a new password with a token from the password reminder email. # Called with params :id => User.id and :token => User.reset_password_token to specify a new password. - def new_password - end + def new_password; end # Sets a new password. # Called with params :id => User.id and :token => User.reset_password_token to specify a new password. @@ -32,7 +29,7 @@ def update_password @user.reset_password_token = nil @user.reset_password_expires = nil @user.save - redirect_to login_url, :notice => I18n.t('login.controller.update_password.notice') + redirect_to login_url, notice: I18n.t('login.controller.update_password.notice') else render :new_password end @@ -50,14 +47,14 @@ def accept_invitation @user = User.new(params[:user]) @user.email = @invite.email if @user.save - Membership.new(:user => @user, :group => @invite.group).save! + Membership.new(user: @user, group: @invite.group).save! @invite.destroy session[:locale] = @user.locale redirect_to login_url, notice: I18n.t('login.controller.accept_invitation.notice') end end else - @user = User.new(:email => @invite.email) + @user = User.new(email: @invite.email) end end @@ -65,8 +62,8 @@ def accept_invitation def validate_token @user = User.find_by_id_and_reset_password_token(params[:id], params[:token]) - if (@user.nil? || @user.reset_password_expires < Time.now) - redirect_to forgot_password_url, alert: I18n.t('login.controller.error_token_invalid') - end + return unless @user.nil? || @user.reset_password_expires < Time.now + + redirect_to forgot_password_url, alert: I18n.t('login.controller.error_token_invalid') end end diff --git a/app/controllers/order_articles_controller.rb b/app/controllers/order_articles_controller.rb index c6e81f21..bd5bd33d 100644 --- a/app/controllers/order_articles_controller.rb +++ b/app/controllers/order_articles_controller.rb @@ -1,12 +1,12 @@ class OrderArticlesController < ApplicationController before_action :fetch_order, except: :destroy - before_action :authenticate_finance_or_invoices, except: [:new, :create] - before_action :authenticate_finance_orders_or_pickup, except: [:edit, :update, :destroy] - before_action :load_order_article, only: [:edit, :update] - before_action :load_article_units, only: [:edit, :update] - before_action :new_empty_article_ratio, only: [:edit, :update] + before_action :authenticate_finance_or_invoices, except: %i[new create] + before_action :authenticate_finance_orders_or_pickup, except: %i[edit update destroy] + before_action :load_order_article, only: %i[edit update] + before_action :load_article_units, only: %i[edit update] + before_action :new_empty_article_ratio, only: %i[edit update] - layout false # We only use this controller to serve js snippets, no need for layout rendering + layout false # We only use this controller to serve js snippets, no need for layout rendering def new @order_article = @order.order_articles.build(params[:order_article]) @@ -18,18 +18,17 @@ def create # The article may be ordered with zero units - in that case do not complain. # If order_article is ordered and a new order_article is created, an error message will be # given mentioning that the article already exists, which is desired. - @order_article = @order.order_articles.joins(:article_version).where(article_versions: { :article_id => params[:order_article][:article_version][:article_id] }).first - unless @order_article && @order_article.units_to_order == 0 - @order_article = @order.order_articles.build(params[:order_article]) - end + @order_article = @order.order_articles.joins(:article_version).where(article_versions: { article_id: params[:order_article][:article_version][:article_id] }).first + @order_article = @order.order_articles.build(params[:order_article]) unless @order_article && @order_article.units_to_order == 0 @order_article.save! - rescue + rescue StandardError render action: :new end def update # begin - version_params = params.require(:article_version).permit(:id, :unit, :supplier_order_unit, :minimum_order_quantity, :billing_unit, :group_order_granularity, :group_order_unit, :price, :price_unit, :tax, :deposit, article_unit_ratios_attributes: [:id, :sort, :quantity, :unit, :_destroy]) + version_params = params.require(:article_version).permit(:id, :unit, :supplier_order_unit, :minimum_order_quantity, + :billing_unit, :group_order_granularity, :group_order_unit, :price, :price_unit, :tax, :deposit, article_unit_ratios_attributes: %i[id sort quantity unit _destroy]) @order_article.update_handling_versioning!(params[:order_article], version_params) # TODO-article-version # rescue diff --git a/app/controllers/order_comments_controller.rb b/app/controllers/order_comments_controller.rb index 39067577..3583bb0e 100644 --- a/app/controllers/order_comments_controller.rb +++ b/app/controllers/order_comments_controller.rb @@ -1,15 +1,15 @@ class OrderCommentsController < ApplicationController def new @order = Order.find(params[:order_id]) - @order_comment = @order.comments.build(:user => current_user) + @order_comment = @order.comments.build(user: current_user) end def create @order_comment = OrderComment.new(params[:order_comment]) if @order_comment.save - render :layout => false + render layout: false else - render :action => :new, :layout => false + render action: :new, layout: false end end end diff --git a/app/controllers/orders_controller.rb b/app/controllers/orders_controller.rb index dc8a62bb..b44ee192 100644 --- a/app/controllers/orders_controller.rb +++ b/app/controllers/orders_controller.rb @@ -5,25 +5,26 @@ class OrdersController < ApplicationController include Concerns::SendOrderPdf before_action :authenticate_pickups_or_orders - before_action :authenticate_orders, except: [:receive, :receive_on_order_article_create, :receive_on_order_article_update, :show] - before_action :remove_empty_article, only: [:create, :update] + before_action :authenticate_orders, + except: %i[receive receive_on_order_article_create receive_on_order_article_update show] + before_action :remove_empty_article, only: %i[create update] # List orders def index @open_orders = Order.open.includes(:supplier) @finished_orders = Order.finished_not_closed.includes(:supplier) @per_page = 15 - if params['sort'] - sort = case params['sort'] - when "supplier" then "suppliers.name, ends DESC" - when "pickup" then "pickup DESC" - when "ends" then "ends DESC" - when "supplier_reverse" then "suppliers.name DESC" - when "ends_reverse" then "ends" + sort = if params['sort'] + case params['sort'] + when 'supplier' then 'suppliers.name, ends DESC' + when 'pickup' then 'pickup DESC' + when 'ends' then 'ends DESC' + when 'supplier_reverse' then 'suppliers.name DESC' + when 'ends_reverse' then 'ends' end - else - sort = "ends DESC" - end + else + 'ends DESC' + end @suppliers = Supplier.having_articles.order('suppliers.name') @orders = Order.closed.includes(:supplier).reorder(sort).page(params[:page]).per(@per_page) end @@ -43,7 +44,7 @@ def show respond_to do |format| format.html format.js do - render :layout => false + render layout: false end format.pdf do send_order_pdf @order, params[:document] @@ -66,8 +67,8 @@ def new else @order = Order.new(supplier_id: params[:supplier_id]).init_dates end - rescue => error - redirect_to orders_url, alert: t('errors.general_msg', msg: error.message) + rescue StandardError => e + redirect_to orders_url, alert: t('errors.general_msg', msg: e.message) end # Page to edit an exsiting order. @@ -87,7 +88,7 @@ def create redirect_to @order else logger.debug "[debug] order errors: #{@order.errors.messages}" - render :action => 'new' + render action: 'new' end end @@ -96,16 +97,16 @@ def update @order = Order.find params[:id] if @order.update_attributes params[:order].merge(updated_by: current_user) flash[:notice] = I18n.t('orders.update.notice') - redirect_to :action => 'show', :id => @order + redirect_to action: 'show', id: @order else - render :action => 'edit' + render action: 'edit' end end # Delete an order. def destroy Order.find(params[:id]).destroy - redirect_to :action => 'index' + redirect_to action: 'index' end # Finish a current order. @@ -130,14 +131,12 @@ def send_result_to_supplier def receive @order = Order.find(params[:id]) - unless request.post? - @order_articles = @order.order_articles.ordered_or_member.includes(:article_version).order('article_versions.order_number, article_versions.name') - else + if request.post? Order.transaction do s = update_order_amounts @order.update_attribute(:state, 'received') if @order.state != 'received' - flash[:notice] = (s ? I18n.t('orders.receive.notice', :msg => s) : I18n.t('orders.receive.notice_none')) + flash[:notice] = (s ? I18n.t('orders.receive.notice', msg: s) : I18n.t('orders.receive.notice_none')) end NotifyReceivedOrderJob.perform_later(@order) if current_user.role_orders? || current_user.role_finance? @@ -147,23 +146,25 @@ def receive else redirect_to receive_order_path(@order) end + else + @order_articles = @order.order_articles.ordered_or_member.includes(:article_version).order('article_versions.order_number, article_versions.name') end end def receive_on_order_article_create # See publish/subscribe design pattern in /doc. @order_article = OrderArticle.find(params[:order_article_id]) - render :layout => false + render layout: false end def receive_on_order_article_update # See publish/subscribe design pattern in /doc. @order_article = OrderArticle.find(params[:order_article_id]) - render :layout => false + render layout: false end protected def update_order_amounts - return if not params[:order_articles] + return unless params[:order_articles] # where to leave remainder during redistribution rest_to = [] @@ -178,31 +179,39 @@ def update_order_amounts # "MySQL lock timeout exceeded" errors. It's ok to do # this article-by-article anway. params[:order_articles].each do |oa_id, oa_params| - unless oa_params.blank? - oa = OrderArticle.find(oa_id) - # update attributes; don't use update_attribute because it calls save - # which makes received_changed? not work anymore - oa.attributes = oa_params - if oa.units_received_changed? - counts[0] += 1 - unless oa.units_received.blank? - units_received = oa.article_version.convert_quantity(oa.units_received, oa.article_version.supplier_order_unit, oa.article_version.billing_unit) - cunits[0] += units_received - oacounts = oa.redistribute units_received, rest_to - oacounts.each_with_index { |c, i| cunits[i + 1] += c; counts[i + 1] += 1 if c > 0 } + next if oa_params.blank? + + oa = OrderArticle.find(oa_id) + # update attributes; don't use update_attribute because it calls save + # which makes received_changed? not work anymore + oa.attributes = oa_params + if oa.units_received_changed? + counts[0] += 1 + if oa.units_received.present? + units_received = oa.article_version.convert_quantity(oa.units_received, + oa.article_version.supplier_order_unit, oa.article_version.billing_unit) + cunits[0] += units_received + oacounts = oa.redistribute units_received, rest_to + oacounts.each_with_index do |c, i| + cunits[i + 1] += c + counts[i + 1] += 1 if c > 0 end end - oa.save! end + oa.save! end return nil if counts[0] == 0 notice = [] notice << I18n.t('orders.update_order_amounts.msg1', count: counts[0], units: cunits[0]) - notice << I18n.t('orders.update_order_amounts.msg2', count: counts[1], units: cunits[1]) if params[:rest_to_tolerance] + if params[:rest_to_tolerance] + notice << I18n.t('orders.update_order_amounts.msg2', count: counts[1], + units: cunits[1]) + end notice << I18n.t('orders.update_order_amounts.msg3', count: counts[2], units: cunits[2]) if params[:rest_to_stock] if counts[3] > 0 || cunits[3] > 0 - notice << I18n.t('orders.update_order_amounts.msg4', count: counts[3], units: cunits[3]) + notice << I18n.t('orders.update_order_amounts.msg4', count: counts[3], + units: cunits[3]) end notice.join(', ') end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index 5b3d0780..6cc988ab 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -12,16 +12,16 @@ def create user = User.authenticate(params[:nick], params[:password]) if user user.update_attribute(:last_login, Time.now) - login_and_redirect_to_return_to user, :notice => I18n.t('sessions.logged_in') + login_and_redirect_to_return_to user, notice: I18n.t('sessions.logged_in') else flash.now.alert = I18n.t(FoodsoftConfig[:use_nick] ? 'sessions.login_invalid_nick' : 'sessions.login_invalid_email') - render "new" + render 'new' end end def destroy logout - redirect_to login_url, :notice => I18n.t('sessions.logged_out') + redirect_to login_url, notice: I18n.t('sessions.logged_out') end # redirect to root, going to default foodcoop when none given diff --git a/app/controllers/stock_takings_controller.rb b/app/controllers/stock_takings_controller.rb index e644283a..d61488a0 100644 --- a/app/controllers/stock_takings_controller.rb +++ b/app/controllers/stock_takings_controller.rb @@ -7,21 +7,23 @@ def index def new @stock_taking = StockTaking.new - StockArticle.with_latest_versions_and_categories.undeleted.each { |a| @stock_taking.stock_changes.build(:stock_article => a) } + StockArticle.with_latest_versions_and_categories.undeleted.each do |a| + @stock_taking.stock_changes.build(stock_article: a) + end end def new_on_stock_article_create # See publish/subscribe design pattern in /doc. stock_article = StockArticle.find(params[:stock_article_id]) - @stock_change = StockChange.new(:stock_article => stock_article) + @stock_change = StockChange.new(stock_article: stock_article) - render :layout => false + render layout: false end def create - create!(:notice => I18n.t('stock_takings.create.notice')) + create!(notice: I18n.t('stock_takings.create.notice')) end def update - update!(:notice => I18n.t('stock_takings.update.notice')) + update!(notice: I18n.t('stock_takings.update.notice')) end end diff --git a/app/controllers/stockit_controller.rb b/app/controllers/stockit_controller.rb index 7afab646..6bea7b90 100644 --- a/app/controllers/stockit_controller.rb +++ b/app/controllers/stockit_controller.rb @@ -1,19 +1,21 @@ class StockitController < ApplicationController - before_action :new_empty_article_ratio, only: [:edit, :update, :new, :create, :derive, :copy] - before_action :load_article, only: [:index_on_stock_article_create, :index_on_stock_article_update, :show, :edit, :update, :show_on_stock_article_update, :destroy] - before_action :load_article_units, only: [:edit, :update, :new, :create, :derive, :copy] - before_action :prepare_params_for_create_update, only: [:create, :update] + before_action :new_empty_article_ratio, only: %i[edit update new create derive copy] + before_action :load_article, + only: %i[index_on_stock_article_create index_on_stock_article_update show edit update show_on_stock_article_update + destroy] + before_action :load_article_units, only: %i[edit update new create derive copy] + before_action :prepare_params_for_create_update, only: %i[create update] def index @stock_articles = StockArticle.with_latest_versions_and_categories.joins(:supplier).order('suppliers.name, article_categories.name, article_versions.name').undeleted end def index_on_stock_article_create # See publish/subscribe design pattern in /doc. - render :layout => false + render layout: false end def index_on_stock_article_update # See publish/subscribe design pattern in /doc. - render :layout => false + render layout: false end def show @@ -26,7 +28,7 @@ def new @stock_article = StockArticle.new(params[:stock_article]) @stock_article.latest_article_version = ArticleVersion.new - render :layout => false + render layout: false end # (2) StockArticle as template @@ -35,7 +37,7 @@ def copy @stock_article = stock_article.dup @stock_article.latest_article_version = stock_article.latest_article_version.duplicate_including_article_unit_ratios - render :layout => false + render layout: false end # (3) non-stock Article as template @@ -44,11 +46,11 @@ def derive @stock_article = article.becomes(StockArticle).dup @stock_article.latest_article_version = article.latest_article_version.duplicate_including_article_unit_ratios - render :layout => false + render layout: false end def edit - render :layout => false + render layout: false end def create @@ -57,35 +59,36 @@ def create @stock_article.attributes = { latest_article_version_attributes: params[:article_version] } @stock_article.save end - render :layout => false + render layout: false rescue ActiveRecord::RecordInvalid - render :action => 'new', :layout => false + render action: 'new', layout: false end def update article_version_attributes = params[:article_version] - @stock_article.update_attributes!(supplier_id: @supplier_id, latest_article_version_attributes: article_version_attributes) - render :layout => false + @stock_article.update_attributes!(supplier_id: @supplier_id, + latest_article_version_attributes: article_version_attributes) + render layout: false rescue ActiveRecord::RecordInvalid - render :action => 'edit', :layout => false + render action: 'edit', layout: false end def show_on_stock_article_update # See publish/subscribe design pattern in /doc. - render :layout => false + render layout: false end def destroy @stock_article.mark_as_deleted - render :layout => false - rescue => error - render :partial => "destroy_fail", :layout => false, - :locals => { :fail_msg => I18n.t('errors.general_msg', :msg => error.message) } + render layout: false + rescue StandardError => e + render partial: 'destroy_fail', layout: false, + locals: { fail_msg: I18n.t('errors.general_msg', msg: e.message) } end # TODO: Fix this!! def articles_search @articles = Article.not_in_stock.limit(8).where('name LIKE ?', "%#{params[:term]}%") - render :json => @articles.map(&:name) + render json: @articles.map(&:name) end private diff --git a/app/controllers/styles_controller.rb b/app/controllers/styles_controller.rb index 5636ec03..6d3a9fd1 100644 --- a/app/controllers/styles_controller.rb +++ b/app/controllers/styles_controller.rb @@ -9,7 +9,7 @@ class StylesController < ApplicationController def foodcoop css = FoodsoftConfig[:custom_css] if css.blank? - render body: nil, content_type: 'text/css', status: 404 + render body: nil, content_type: 'text/css', status: :not_found else expires_in 1.week, public: true if params[:md5].present? render body: css, content_type: 'text/css' diff --git a/app/controllers/suppliers_controller.rb b/app/controllers/suppliers_controller.rb index c6cb0778..56ddf224 100644 --- a/app/controllers/suppliers_controller.rb +++ b/app/controllers/suppliers_controller.rb @@ -1,7 +1,7 @@ require 'ostruct' class SuppliersController < ApplicationController - before_action :authenticate_suppliers, :except => [:index, :list] + before_action :authenticate_suppliers, except: %i[index list] helper :deliveries def index @@ -31,7 +31,7 @@ def create flash[:notice] = I18n.t('suppliers.create.notice') redirect_to suppliers_path else - render :action => 'new' + render action: 'new' end end @@ -41,7 +41,7 @@ def update flash[:notice] = I18n.t('suppliers.update.notice') redirect_to @supplier else - render :action => 'edit' + render action: 'edit' end end @@ -50,8 +50,8 @@ def destroy @supplier.mark_as_deleted flash[:notice] = I18n.t('suppliers.destroy.notice') redirect_to suppliers_path - rescue => e - flash[:error] = I18n.t('errors.general_msg', :msg => e.message) + rescue StandardError => e + flash[:error] = I18n.t('errors.general_msg', msg: e.message) redirect_to @supplier end diff --git a/app/controllers/tasks_controller.rb b/app/controllers/tasks_controller.rb index db4ca1ab..352c71ae 100644 --- a/app/controllers/tasks_controller.rb +++ b/app/controllers/tasks_controller.rb @@ -11,35 +11,33 @@ def user @accepted_tasks = Task.accepted_tasks_for(current_user) end + def show + @task = Task.find(params[:id]) + end + def new @task = Task.new(current_user_id: current_user.id) end + def edit + @task = Task.find(params[:id]) + @periodic = !!params[:periodic] + @task.current_user_id = current_user.id + end + def create @task = Task.new(current_user_id: current_user.id) @task.created_by = current_user @task.attributes = (task_params) - if params[:periodic] - @task.periodic_task_group = PeriodicTaskGroup.new - end + @task.periodic_task_group = PeriodicTaskGroup.new if params[:periodic] if @task.save @task.periodic_task_group.create_tasks_for_upfront_days if params[:periodic] - redirect_to tasks_url, :notice => I18n.t('tasks.create.notice') + redirect_to tasks_url, notice: I18n.t('tasks.create.notice') else - render :template => "tasks/new" + render template: 'tasks/new' end end - def show - @task = Task.find(params[:id]) - end - - def edit - @task = Task.find(params[:id]) - @periodic = !!params[:periodic] - @task.current_user_id = current_user.id - end - def update @task = Task.find(params[:id]) task_group = @task.periodic_task_group @@ -50,16 +48,14 @@ def update if @task.errors.empty? && @task.save task_group.update_tasks_including(@task, prev_due_date) if params[:periodic] flash[:notice] = I18n.t('tasks.update.notice') - if was_periodic && !@task.periodic? - flash[:notice] = I18n.t('tasks.update.notice_converted') - end + flash[:notice] = I18n.t('tasks.update.notice_converted') if was_periodic && !@task.periodic? if @task.workgroup redirect_to workgroup_tasks_url(workgroup_id: @task.workgroup_id) else redirect_to tasks_url end else - render :template => "tasks/edit" + render template: 'tasks/edit' end end @@ -75,7 +71,7 @@ def destroy end task.update_ordergroup_stats(user_ids) - redirect_to tasks_url, :notice => I18n.t('tasks.destroy.notice') + redirect_to tasks_url, notice: I18n.t('tasks.destroy.notice') end # assign current_user to the task and set the assignment to "accepted" @@ -85,20 +81,20 @@ def accept if ass = task.is_assigned?(current_user) ass.update_attribute(:accepted, true) else - task.assignments.create(:user => current_user, :accepted => true) + task.assignments.create(user: current_user, accepted: true) end - redirect_to user_tasks_path, :notice => I18n.t('tasks.accept.notice') + redirect_to user_tasks_path, notice: I18n.t('tasks.accept.notice') end # deletes assignment between current_user and given taskcurrent_user_id: current_user.id def reject Task.find(params[:id]).users.delete(current_user) - redirect_to :action => "index" + redirect_to action: 'index' end def set_done Task.find(params[:id]).update_attribute :done, true - redirect_to tasks_url, :notice => I18n.t('tasks.set_done.notice') + redirect_to tasks_url, notice: I18n.t('tasks.set_done.notice') end # Shows all tasks, which are already done @@ -109,9 +105,9 @@ def archive # shows workgroup (normal group) to edit weekly_tasks_template def workgroup @group = Group.find(params[:workgroup_id]) - if @group.is_a? Ordergroup - redirect_to tasks_url, :alert => I18n.t('tasks.error_not_found') - end + return unless @group.is_a? Ordergroup + + redirect_to tasks_url, alert: I18n.t('tasks.error_not_found') end private diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 503bc79b..df56ade0 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -3,7 +3,7 @@ class UsersController < ApplicationController def index @users = User.undeleted.natural_search(params[:q]) respond_to do |format| - format.json { render :json => @users.map(&:token_attributes).to_json } + format.json { render json: @users.map(&:token_attributes).to_json } end end end diff --git a/app/documents/order_by_articles.rb b/app/documents/order_by_articles.rb index 243c4dad..bb8bebcc 100644 --- a/app/documents/order_by_articles.rb +++ b/app/documents/order_by_articles.rb @@ -1,11 +1,11 @@ class OrderByArticles < OrderPdf def filename - I18n.t('documents.order_by_articles.filename', :name => order.name, :date => order.ends.to_date) + '.pdf' + 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'))) + I18n.t('documents.order_by_articles.title', name: order.name, + date: order.ends.strftime(I18n.t('date.formats.default'))) end def body @@ -23,12 +23,15 @@ def body dimrows << rows.length if goa.result == 0 rows << [goa.group_order.ordergroup_name, billign_quantity_with_tolerance(goa), - article_version.convert_quantity(goa.result, article_version.group_order_unit, article_version.billing_unit), + article_version.convert_quantity(goa.result, article_version.group_order_unit, + article_version.billing_unit), number_to_currency(goa.total_price)] end next unless rows.length > 1 - name = "#{article_version.name}, #{format_billing_unit_with_ratios(article_version)}, #{number_to_currency(article_version.convert_quantity(article_version.fc_price, article_version.billing_unit, article_version.supplier_order_unit))}" + name = "#{article_version.name}, #{format_billing_unit_with_ratios(article_version)}, #{number_to_currency(article_version.convert_quantity( + article_version.fc_price, article_version.billing_unit, article_version.supplier_order_unit + ))}" name += " #{order_article.order.name}" if @options[:show_supplier] nice_table name, rows, dimrows do |table| table.column(0).width = bounds.width / 2 diff --git a/app/documents/order_by_groups.rb b/app/documents/order_by_groups.rb index a9690ed1..6d91e98c 100644 --- a/app/documents/order_by_groups.rb +++ b/app/documents/order_by_groups.rb @@ -1,11 +1,11 @@ class OrderByGroups < OrderPdf def filename - I18n.t('documents.order_by_groups.filename', :name => order.name, :date => order.ends.to_date) + '.pdf' + 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'))) + I18n.t('documents.order_by_groups.title', name: order.name, + date: order.ends.strftime(I18n.t('date.formats.default'))) end def body diff --git a/app/documents/order_fax.rb b/app/documents/order_fax.rb index c2b5c0c1..4a1f741c 100644 --- a/app/documents/order_fax.rb +++ b/app/documents/order_fax.rb @@ -4,7 +4,7 @@ class OrderFax < OrderPdf BATCH_SIZE = 250 def filename - I18n.t('documents.order_fax.filename', :name => order.name, :date => order.ends.to_date) + '.pdf' + I18n.t('documents.order_fax.filename', name: order.name, date: order.ends.to_date) + '.pdf' end def title @@ -17,8 +17,8 @@ def body recipient_paragraph articles_paragraph - rescue => exception - Rails.logger.info exception.backtrace + rescue StandardError => e + Rails.logger.info e.backtrace raise # always reraise end @@ -33,16 +33,18 @@ def from_paragraph move_down 5 text "#{contact[:zip_code]} #{contact[:city]}", size: fontsize(9), align: :right move_down 5 - unless order.supplier.try(:customer_number).blank? - text "#{Supplier.human_attribute_name :customer_number}: #{order.supplier[:customer_number]}", size: fontsize(9), align: :right + if order.supplier.try(:customer_number).present? + text "#{Supplier.human_attribute_name :customer_number}: #{order.supplier[:customer_number]}", + size: fontsize(9), align: :right move_down 5 end - unless contact[:phone].blank? + if contact[:phone].present? text "#{Supplier.human_attribute_name :phone}: #{contact[:phone]}", size: fontsize(9), align: :right move_down 5 end - unless contact[:email].blank? - text "#{Supplier.human_attribute_name :email}: #{contact[:email]}", size: fontsize(9), align: :right + if contact[:email].present? + text "#{Supplier.human_attribute_name :email}: #{contact[:email]}", size: fontsize(9), + align: :right end end end @@ -52,7 +54,7 @@ def recipient_paragraph text order.name move_down 5 text order.supplier.try(:address).to_s - unless order.supplier.try(:fax).blank? + if order.supplier.try(:fax).present? move_down 5 text "#{Supplier.human_attribute_name :fax}: #{order.supplier[:fax]}" end @@ -64,10 +66,10 @@ def recipient_paragraph move_down 10 text "#{Delivery.human_attribute_name :date}:" move_down 10 - unless order.supplier.try(:contact_person).blank? - text "#{Supplier.human_attribute_name :contact_person}: #{order.supplier[:contact_person]}" - move_down 10 - end + return if order.supplier.try(:contact_person).blank? + + text "#{Supplier.human_attribute_name :contact_person}: #{order.supplier[:contact_person]}" + move_down 10 end def articles_paragraph @@ -81,7 +83,8 @@ def articles_paragraph oa.units_to_order, oa.article_version.name, # TODO-article-units: Why should we show the supplier the group order unit quantity?: - oa.article_version.convert_quantity(1, oa.article_version.supplier_order_unit, oa.article_version.group_order_unit), + oa.article_version.convert_quantity(1, oa.article_version.supplier_order_unit, + oa.article_version.group_order_unit), format_supplier_order_unit_with_ratios(oa.price), number_to_currency(price), number_to_currency(subtotal)] @@ -95,8 +98,8 @@ def articles_paragraph 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).columns(0..5).borders = %i[top bottom] + table.row(data.length - 1).columns(0).borders = %i[top bottom left] table.row(data.length - 1).border_top_width = 2 end # font_size: fontsize(8), @@ -113,7 +116,7 @@ def order_articles .preload(article_version: :article) end - def each_order_article - order_articles.find_each_with_order(batch_size: BATCH_SIZE) { |oa| yield oa } + def each_order_article(&block) + order_articles.find_each_with_order(batch_size: BATCH_SIZE, &block) end end diff --git a/app/documents/order_matrix.rb b/app/documents/order_matrix.rb index 73397376..9676b760 100644 --- a/app/documents/order_matrix.rb +++ b/app/documents/order_matrix.rb @@ -3,12 +3,12 @@ class OrderMatrix < OrderPdf PLACEHOLDER_CHAR = 'X' def filename - I18n.t('documents.order_matrix.filename', :name => @order.name, :date => @order.ends.to_date) + '.pdf' + I18n.t('documents.order_matrix.filename', name: @order.name, date: @order.ends.to_date) + '.pdf' end def title - I18n.t('documents.order_matrix.title', :name => @order.name, - :date => @order.ends.strftime(I18n.t('date.formats.default'))) + I18n.t('documents.order_matrix.title', name: @order.name, + date: @order.ends.strftime(I18n.t('date.formats.default'))) end def body @@ -87,7 +87,7 @@ def body table.cells.border_width = 0.5 table.cells.border_color = '666666' - table.row(0).borders = [:bottom, :left] + table.row(0).borders = %i[bottom left] table.row(0).padding = [2, 0, 2, 0] table.row(1..-1).height = row_height_1 table.column(0..1).borders = [] @@ -106,7 +106,7 @@ def body table.column(2 + idx).border_width = 2 end - table.row_colors = ['dddddd', 'ffffff'] + table.row_colors = %w[dddddd ffffff] end first_page = false diff --git a/app/helpers/admin/configs_helper.rb b/app/helpers/admin/configs_helper.rb index 0185a0df..3c1da9f0 100644 --- a/app/helpers/admin/configs_helper.rb +++ b/app/helpers/admin/configs_helper.rb @@ -28,7 +28,11 @@ def config_input(form, key, options = {}, &block) options[:default] = options[:input_html].delete(:value) return form.input key, options, &block end - block ||= proc { config_input_field form, key, options.merge(options[:input_html]) } if options[:as] == :select_recurring + if options[:as] == :select_recurring + block ||= proc { + config_input_field form, key, options.merge(options[:input_html]) + } + end form.input key, options, &block end @@ -57,11 +61,12 @@ def config_input_field(form, key, options = {}) unchecked_value = options.delete(:unchecked_value) || '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) + form.hidden_field(key, id: "#{key}_", value: unchecked_value, + as: :hidden) + form.check_box(key, options, checked_value, false) elsif options[:as] == :select_recurring options[:value] = FoodsoftDateUtil.rule_from(options[:value]) options[:rules] ||= [] - options[:rules].unshift options[:value] unless options[:value].blank? + options[:rules].unshift options[:value] if options[:value].present? options[:rules].push [I18n.t('recurring_select.not_recurring'), '{}'] if options.delete(:allow_blank) # blank after current value form.select_recurring key, options.delete(:rules).uniq, options else @@ -73,7 +78,7 @@ def config_input_field(form, key, options = {}) # @param form [ActionView::Helpers::FormBuilder] Form object. # @param key [Symbol, String] Configuration key of a boolean (e.g. +use_messages+). # @option options [String] :label Label to show - def config_use_heading(form, key, options = {}) + def config_use_heading(form, key, options = {}, &block) head = content_tag :label do lbl = options[:label] || config_input_label(form, key) field = config_input_field(form, key, as: :boolean, boolean_style: :inline, @@ -83,9 +88,7 @@ def config_use_heading(form, key, options = {}) 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 - end + fields = content_tag(:fieldset, id: "#{key}-fields", class: "collapse#{' in' if @cfg[key]}", &block) head + fields end @@ -127,7 +130,7 @@ def config_input_tooltip_options(form, key, options) # tooltip with help info to the right cfg_path = form.lookup_model_names[1..-1] + [key] tooltip = I18n.t("config.hints.#{cfg_path.map(&:to_s).join('.')}", default: '') - unless tooltip.blank? + if tooltip.present? options[:data] ||= {} options[:data][:toggle] ||= 'tooltip' options[:data][:placement] ||= 'right' diff --git a/app/helpers/admin/ordergroups_helper.rb b/app/helpers/admin/ordergroups_helper.rb index e74fdde5..ecb4bd39 100644 --- a/app/helpers/admin/ordergroups_helper.rb +++ b/app/helpers/admin/ordergroups_helper.rb @@ -2,9 +2,7 @@ module Admin::OrdergroupsHelper def ordergroup_members_title(ordergroup) s = '' s += ordergroup.users.map(&:name).join(', ') if ordergroup.users.any? - if ordergroup.contact_person.present? - s += "\n" + Ordergroup.human_attribute_name(:contact) + ": " + ordergroup.contact_person - end + s += "\n" + Ordergroup.human_attribute_name(:contact) + ': ' + ordergroup.contact_person if ordergroup.contact_person.present? s end end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 584a3117..5412e1bc 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -4,7 +4,7 @@ module ApplicationHelper include PathHelper def format_time(time = Time.now) - I18n.l(time, :format => "%d.%m.%Y %H:%M") unless time.nil? + I18n.l(time, format: '%d.%m.%Y %H:%M') unless time.nil? end def format_date(time = Time.now) @@ -16,7 +16,7 @@ def format_datetime(time = Time.now) end def format_datetime_timespec(time, format) - I18n.l(time, :format => format) unless (time.nil? || format.nil?) + I18n.l(time, format: format) unless time.nil? || format.nil? end def format_currency(amount) @@ -26,28 +26,28 @@ def format_currency(amount) # Splits an IBAN into groups of 4 digits displayed with margins in between def format_iban(iban) - iban && iban.scan(/..?.?.?/).map { |item| content_tag(:span, item, style: "margin-right: 0.5em;") }.join.html_safe + iban && 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 }) - paginate collection, :params => params, :remote => true + params = params.merge({ per_page: per_page }) + paginate collection, params: params, remote: true end # Link-collection for per_page-options when using the pagination-plugin def items_per_page(options = {}) per_page_options = options[:per_page_options] || [20, 50, 100, 500] current = options[:current] || @per_page - params = 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) + link_to(per_page, params, remote: true, class: link_class) end if options[:wrap] == false @@ -63,21 +63,19 @@ def sort_link_helper(text, key, options = {}) # Hmtl options remote = options[:remote].nil? ? true : options[:remote] class_name = case params[:sort] - when key then + when key 'sortup' - when key + '_reverse' then + when key + '_reverse' '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 + 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] @@ -95,14 +93,16 @@ def sort_link_helper(text, key, options = {}) # 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| !%w[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", + 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 })) - s = raw "#{sshort}" unless sshort.blank? + sshort = model.human_attribute_name(:"#{attribute}_short", + options.merge({ fallback: true, default: '', count: 2 })) + s = raw "#{sshort}" if sshort.present? end s end @@ -117,7 +117,7 @@ def link_to_top # Returns the weekday. 0 is sunday, 1 is monday and so on def weekday(dayNumber) weekdays = I18n.t('date.day_names') - return weekdays[dayNumber] + weekdays[dayNumber] end # to set a title for both the h1-tag and the title in the header @@ -136,13 +136,13 @@ def tab_is_active?(tab) 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 @@ -150,27 +150,29 @@ def icon(name, options = {}) # Remote links with default 'loader'.gif during request def remote_link_to(text, options = {}) remote_options = { - :before => "Element.show('loader')", - :success => "Element.hide('loader')", - :method => :get + before: "Element.show('loader')", + success: "Element.hide('loader')", + method: :get } link_to(text, options[:url], remote_options.merge(options)) end def format_roles(record, icon = false) - roles = %w(suppliers article_meta orders pickups finance invoices admin) + 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}")] }] + names = roles.index_with { |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 do |r| + image_tag("role-#{r}.png", size: '22x22', border: 0, alt: names[r], title: names[r]) + end.join(' ').html_safe else 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" + link_to h(address), "http://maps.google.com/?q=#{h(address)}", title: I18n.t('helpers.application.show_google_maps'), + target: '_blank', rel: 'noopener' end # Returns flash messages html. @@ -186,8 +188,8 @@ def bootstrap_flash_patched type = :success if type == 'notice' type = :error if type == 'alert' text = content_tag(:div, - content_tag(:button, I18n.t('ui.marks.close').html_safe, :class => "close", "data-dismiss" => "alert") + - message, :class => "alert fade in alert-#{type}") + content_tag(:button, I18n.t('ui.marks.close').html_safe, :class => 'close', 'data-dismiss' => 'alert') + + message, class: "alert fade in alert-#{type}") flash_messages << text if message end flash_messages.join("\n").html_safe @@ -195,17 +197,17 @@ def bootstrap_flash_patched # render base errors in a form after failed validation # http://railsapps.github.io/twitter-bootstrap-rails.html - def base_errors resource + 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 = {}) if user.nil? - "?" + '?' elsif FoodsoftConfig[:use_nick] if options[:full] && options[:markup] raw "#{h user.nick} (#{h user.first_name} #{h user.last_name})" @@ -258,10 +260,10 @@ def foodcoop_css_path(options = {}) # @return [String] stylesheet tag for foodcoop CSS style (+custom_css+ foodcoop config) # @see #foodcoop_css_path - def foodcoop_css_tag(options = {}) - unless FoodsoftConfig[:custom_css].blank? - stylesheet_link_tag foodcoop_css_path, media: 'all' - end + def foodcoop_css_tag(_options = {}) + return if FoodsoftConfig[:custom_css].blank? + + stylesheet_link_tag foodcoop_css_path, media: 'all' end def format_number(value) diff --git a/app/helpers/articles_helper.rb b/app/helpers/articles_helper.rb index 341b53dd..45781967 100644 --- a/app/helpers/articles_helper.rb +++ b/app/helpers/articles_helper.rb @@ -5,14 +5,14 @@ def highlight_new(unequal_attributes, attributes) return unless unequal_attributes intersection = (unequal_attributes.keys & attributes) - intersection.empty? ? "" : "background-color: yellow" + intersection.empty? ? '' : 'background-color: yellow' end def row_classes(article) classes = [] - classes << "unavailable" if !article.availability - classes << "just-updated" if article.recently_updated && article.availability - classes.join(" ") + classes << 'unavailable' unless article.availability + classes << 'just-updated' if article.recently_updated && article.availability + classes.join(' ') end def format_unit(unit_property, article) @@ -66,9 +66,10 @@ def format_billing_unit_with_ratios(article) def field_with_preset_value_and_errors(options) form, field, value, field_errors, input_html = options.values_at(:form, :field, :value, :errors, :input_html) - form.input field, label: false, wrapper_html: { class: field_errors.blank? ? '' : 'error' }, input_html: input_html do + form.input field, label: false, wrapper_html: { class: field_errors.blank? ? '' : 'error' }, + input_html: input_html do output = [form.input_field(field, { value: value }.merge(input_html))] - unless field_errors.blank? + if field_errors.present? errors = tag.span(class: 'help-inline') do field_errors.join(', ') end diff --git a/app/helpers/deliveries_helper.rb b/app/helpers/deliveries_helper.rb index 50d92418..6d4aa0f1 100644 --- a/app/helpers/deliveries_helper.rb +++ b/app/helpers/deliveries_helper.rb @@ -11,11 +11,11 @@ def link_to_invoice(delivery) def articles_for_select2(articles, except = [], &block) articles = articles.reorder('article_versions.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| !except.index(a.id).nil? } if except + block_given? or block = proc { |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) @@ -23,10 +23,14 @@ def articles_for_table(articles) 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? + if stock_change_form.object.new_record? + return link_to t('deliveries.stock_change_fields.remove_article'), '#', + class: 'remove_new_stock_change btn btn-small' + end 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 + output += link_to t('deliveries.stock_change_fields.remove_article'), '#', + class: 'destroy_stock_change btn btn-small' + output.html_safe end end diff --git a/app/helpers/finance/balancing_helper.rb b/app/helpers/finance/balancing_helper.rb index bc528f04..a123b161 100644 --- a/app/helpers/finance/balancing_helper.rb +++ b/app/helpers/finance/balancing_helper.rb @@ -2,11 +2,11 @@ module Finance::BalancingHelper def balancing_view_partial view = params[:view] || 'edit_results' case view - when 'edit_results' then + when 'edit_results' 'edit_results_by_articles' - when 'groups_overview' then + when 'groups_overview' 'shared/articles_by/groups' - when 'articles_overview' then + when 'articles_overview' 'shared/articles_by/articles' end end diff --git a/app/helpers/finance/invoices_helper.rb b/app/helpers/finance/invoices_helper.rb index ef01a275..0644b501 100644 --- a/app/helpers/finance/invoices_helper.rb +++ b/app/helpers/finance/invoices_helper.rb @@ -1,9 +1,9 @@ module Finance::InvoicesHelper - def format_delivery_item delivery + def format_delivery_item(delivery) format_date(delivery.date) end - def format_order_item order + def format_order_item(order) "#{format_date(order.ends)} (#{number_to_currency(order.sum)})" end end diff --git a/app/helpers/group_order_articles_helper.rb b/app/helpers/group_order_articles_helper.rb index b8c20c94..db2fd087 100644 --- a/app/helpers/group_order_articles_helper.rb +++ b/app/helpers/group_order_articles_helper.rb @@ -2,18 +2,27 @@ module GroupOrderArticlesHelper # return an edit field for a GroupOrderArticle result def group_order_article_edit_result(goa, convert_to_billing_unit = true) result = number_with_precision goa.result, strip_insignificant_zeros: true - unless goa.group_order.order.finished? && current_user.role_finance? - result - else + if goa.group_order.order.finished? && current_user.role_finance? order_article = goa.order_article article_version = order_article.article_version simple_form_for goa, remote: true, html: { 'data-submit-onchange' => 'changed', class: 'delta-input' } do |f| quantity_data = ratio_quantity_data(order_article, order_article.article_version.billing_unit) - converted_value = convert_to_billing_unit ? article_version.convert_quantity(goa.result, article_version.group_order_unit, article_version.billing_unit) : result + converted_value = if convert_to_billing_unit + article_version.convert_quantity(goa.result, + article_version.group_order_unit, article_version.billing_unit) + else + result + end input_data = { min: 0 }.merge(quantity_data) - input_data = input_data.merge('multiply-before-submit': article_version.convert_quantity(1, article_version.billing_unit, article_version.group_order_unit)) if convert_to_billing_unit - f.input_field(:result, as: :delta, class: 'input-nano', data: input_data, id: "r_#{goa.id}", value: converted_value.round(3)) + if convert_to_billing_unit + input_data = input_data.merge('multiply-before-submit': article_version.convert_quantity(1, + article_version.billing_unit, article_version.group_order_unit)) + end + f.input_field(:result, as: :delta, class: 'input-nano', data: input_data, id: "r_#{goa.id}", + value: converted_value.round(3)) end + else + result end end end diff --git a/app/helpers/group_orders_helper.rb b/app/helpers/group_orders_helper.rb index 7d416b6e..438b1230 100644 --- a/app/helpers/group_orders_helper.rb +++ b/app/helpers/group_orders_helper.rb @@ -1,10 +1,11 @@ module GroupOrdersHelper def data_to_js(ordering_data) - ordering_data[:order_articles].map { |id, data| - [id, data[:price], data[:unit], data[:total_price], data[:others_quantity], data[:others_tolerance], data[:used_quantity], data[:quantity_available]] - }.map { |row| + ordering_data[:order_articles].map do |id, data| + [id, data[:price], data[:unit], data[:total_price], data[:others_quantity], data[:others_tolerance], + data[:used_quantity], data[:quantity_available]] + end.map do |row| "addData(#{row.join(', ')});" - }.join("\n") + end.join("\n") end # Returns a link to the page where a group_order can be edited. @@ -14,9 +15,9 @@ def link_to_ordering(order, options = {}, &block) path = if options[:show] && group_order group_order_path(group_order) elsif group_order - edit_group_order_path(group_order, :order_id => order.id) + edit_group_order_path(group_order, order_id: order.id) else - new_group_order_path(:order_id => order.id) + new_group_order_path(order_id: order.id) end options.delete(:show) name = block_given? ? capture(&block) : order.name @@ -26,7 +27,7 @@ def link_to_ordering(order, options = {}, &block) # Return css class names for order result table def order_article_class_name(quantity, tolerance, result) - if (quantity + tolerance > 0) + if quantity + tolerance > 0 result > 0 ? 'success' : 'failed' else 'ignored' @@ -52,12 +53,12 @@ def requires_tolerance_input?(order_article, ordering_data) end def get_missing_units_css_class(quantity_missing, article_version) - if (quantity_missing == 0) - return '' - elsif (quantity_missing <= article_version.group_order_granularity) - return 'missing-few'; + if quantity_missing == 0 + '' + elsif quantity_missing <= article_version.group_order_granularity + 'missing-few' else - return 'missing-many' + 'missing-many' end end end diff --git a/app/helpers/orders_helper.rb b/app/helpers/orders_helper.rb index 084499e8..91e08a46 100644 --- a/app/helpers/orders_helper.rb +++ b/app/helpers/orders_helper.rb @@ -18,7 +18,7 @@ def order_pdf(order, document, text, options = {}) 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 @@ -30,28 +30,40 @@ def units_history_line(order_article, options = {}) else units_info = [] price = order_article.price - [:units_to_order, :units_billed, :units_received].map do |unit| - if n = order_article.send(unit) - converted_quantity = price.convert_quantity(n, price.supplier_order_unit, price.billing_unit.presence || price.supplier_order_unit) - line = converted_quantity.round(3).to_s + ' ' - line += pkg_helper(price, options) + ' ' unless n == 0 - line += OrderArticle.human_attribute_name("#{unit}_short", count: n) - units_info << line - end + %i[units_to_order units_billed units_received].map do |unit| + next unless n = order_article.send(unit) + + converted_quantity = price.convert_quantity(n, price.supplier_order_unit, + price.billing_unit.presence || price.supplier_order_unit) + line = converted_quantity.round(3).to_s + ' ' + line += pkg_helper(price, options) + ' ' unless n == 0 + line += OrderArticle.human_attribute_name("#{unit}_short", count: n) + units_info << line end units_info.join(', ').html_safe end end - def ordered_quantities_different_from_group_orders?(order_article, ordered_mark = "!", billed_mark = "?", received_mark = "?") + def ordered_quantities_different_from_group_orders?(order_article, ordered_mark = '!', billed_mark = '?', + received_mark = '?') price = order_article.price group_orders_sum_quantity = order_article.group_orders_sum[:quantity] if !order_article.units_received.nil? - price.convert_quantity(order_article.units_received, price.supplier_order_unit, price.group_order_unit).round(3) == group_orders_sum_quantity ? false : received_mark + if price.convert_quantity(order_article.units_received, price.supplier_order_unit, + price.group_order_unit).round(3) == group_orders_sum_quantity + false + else + received_mark + end elsif !order_article.units_billed.nil? order_article.units_billed == group_orders_sum_quantity ? false : billed_mark elsif !order_article.units_to_order.nil? - price.convert_quantity(order_article.units_to_order, price.supplier_order_unit, price.group_order_unit).round(3) == group_orders_sum_quantity ? false : ordered_mark + if price.convert_quantity(order_article.units_to_order, price.supplier_order_unit, + price.group_order_unit).round(3) == group_orders_sum_quantity + false + else + ordered_mark + end end end @@ -87,8 +99,8 @@ def pkg_helper(article, options = {}) def pkg_helper_icon(c = nil, options = {}) options = { tag: 'i', class: '' }.merge(options) if c.nil? - c = " ".html_safe - options[:class] += " icon-only" + c = ' '.html_safe + options[:class] += ' icon-only' end content_tag(options[:tag], c, class: "package #{options[:class]}").html_safe end @@ -112,18 +124,19 @@ def receive_input_field(form) input_classes = 'input input-nano units_received' input_classes += ' package' unless price.unit_quantity == 1 || price.supplier_order_unit != price.billing_unit data = { units_expected: units_expected, billing_unit: price.billing_unit } - data.merge!(self.ratio_quantity_data(order_article, price.billing_unit)) + data.merge!(ratio_quantity_data(order_article, price.billing_unit)) input_html = form.text_field :units_received, class: input_classes, data: data, 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: '')) { + input_html = content_tag(:span, class: 'input-prepend intable', + title: t('orders.edit_amount.field_locked_title', default: '')) do button_tag(nil, type: :button, class: 'btn unlocker') { content_tag(:i, nil, class: 'icon icon-unlock') } + input_html - } + end end input_html.html_safe @@ -131,9 +144,9 @@ def receive_input_field(form) def ratio_quantity_data(order_article, default_unit = nil) data = {} - data["supplier-order-unit"] = order_article.article_version.supplier_order_unit - data["default-unit"] = default_unit - data["custom-unit"] = order_article.article_version.unit + data['supplier-order-unit'] = order_article.article_version.supplier_order_unit + data['default-unit'] = default_unit + data['custom-unit'] = order_article.article_version.unit order_article.article_version.article_unit_ratios.all.each_with_index do |ratio, index| data["ratio-quantity-#{index}"] = ratio.quantity data["ratio-unit-#{index}"] = ratio.unit @@ -147,18 +160,16 @@ def ratio_quantity_data(order_article, default_unit = nil) def ordergroup_count(order) group_orders = order.group_orders.includes(:ordergroup) txt = "#{group_orders.count} #{Ordergroup.model_name.human count: group_orders.count}" - if group_orders.count == 0 - return txt - else - desc = group_orders.includes(:ordergroup).map { |g| g.ordergroup_name }.join(', ') - content_tag(:abbr, txt, title: desc).html_safe - end + return txt if group_orders.count == 0 + + desc = group_orders.includes(:ordergroup).map { |g| g.ordergroup_name }.join(', ') + content_tag(:abbr, txt, title: desc).html_safe end # @param order_or_supplier [Order, Supplier] Order or supplier to link to # @return [String] Link to order or supplier, showing its name. def supplier_link(order_or_supplier) - if order_or_supplier.kind_of?(Order) && order_or_supplier.stockit? + if order_or_supplier.is_a?(Order) && order_or_supplier.stockit? link_to(order_or_supplier.name, stock_articles_path).html_safe else link_to(@order.supplier.name, supplier_path(@order.supplier)).html_safe @@ -190,7 +201,8 @@ def receive_button(order, options = {}) if order.stockit? content_tag :div, t('orders.index.action_receive'), class: "btn disabled #{options[:class]}" else - link_to t('orders.index.action_receive'), receive_order_path(order), class: "btn#{' btn-success' unless order.received?} #{options[:class]}" + link_to t('orders.index.action_receive'), receive_order_path(order), + class: "btn#{' btn-success' unless order.received?} #{options[:class]}" end end end diff --git a/app/helpers/stockit_helper.rb b/app/helpers/stockit_helper.rb index a08e8335..9848198d 100644 --- a/app/helpers/stockit_helper.rb +++ b/app/helpers/stockit_helper.rb @@ -1,8 +1,8 @@ module StockitHelper def stock_article_classes(article) class_names = [] - class_names << "unavailable" if article.quantity_available <= 0 - class_names.join(" ") + class_names << 'unavailable' if article.quantity_available <= 0 + class_names.join(' ') end def link_to_stock_change_reason(stock_change) @@ -17,8 +17,8 @@ def link_to_stock_change_reason(stock_change) 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_link: link_to(t('stockit.form.copy_stock_article'), + stock_article_copy_path(stock_article), + remote: true)) end end diff --git a/app/helpers/tasks_helper.rb b/app/helpers/tasks_helper.rb index f6f1fa14..4b12f7a8 100644 --- a/app/helpers/tasks_helper.rb +++ b/app/helpers/tasks_helper.rb @@ -1,16 +1,16 @@ module TasksHelper def task_assignments(task) task.assignments.map do |ass| - content_tag :span, show_user(ass.user), :class => (ass.accepted? ? 'accepted' : 'unaccepted') - end.join(", ").html_safe + content_tag :span, show_user(ass.user), class: (ass.accepted? ? 'accepted' : 'unaccepted') + end.join(', ').html_safe end # generate colored number of still required users 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) - end + return if 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) end def task_title(task) diff --git a/app/inputs/delta_input.rb b/app/inputs/delta_input.rb index c0e5b19f..12d6fe4f 100644 --- a/app/inputs/delta_input.rb +++ b/app/inputs/delta_input.rb @@ -6,7 +6,7 @@ def input(wrapper_options) options[:data] ||= {} options[:data][:delta] ||= 1 options[:autocomplete] ||= 'off' - # TODO get generated id, don't know how yet - `add_default_name_and_id_for_value` might be an option + # TODO: get generated id, don't know how yet - `add_default_name_and_id_for_value` might be an option template.content_tag :div, class: 'delta-input input-prepend input-append' do delta_button(content_tag(:i, nil, class: 'icon icon-plus'), 1, options) + @@ -21,6 +21,7 @@ def input(wrapper_options) def delta_button(title, direction, options) 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 modify') + template.button_tag(title, type: :button, name: 'delta', value: delta, data: data, tabindex: -1, + class: 'btn modify') end end diff --git a/app/mailers/mailer.rb b/app/mailers/mailer.rb index 4ff340a0..90c8a062 100644 --- a/app/mailers/mailer.rb +++ b/app/mailers/mailer.rb @@ -81,7 +81,7 @@ def order_result_supplier(user, order, options = {}) add_order_result_attachments order, options - subject = I18n.t('mailer.order_result_supplier.subject', :name => order.supplier.name) + subject = I18n.t('mailer.order_result_supplier.subject', name: order.supplier.name) subject += " (#{I18n.t('activerecord.attributes.order.pickup')}: #{format_date(order.pickup)})" if order.pickup mail to: order.supplier.email, @@ -122,10 +122,11 @@ def mail(args) if args[:from].is_a? User args[:reply_to] ||= args[:from] - args[:from] = format_address(FoodsoftConfig[:email_sender], I18n.t('mailer.from_via_foodsoft', name: show_user(args[:from]))) + args[:from] = + format_address(FoodsoftConfig[:email_sender], I18n.t('mailer.from_via_foodsoft', name: show_user(args[:from]))) end - [:bcc, :cc, :reply_to, :sender, :to].each do |k| + %i[bcc cc reply_to sender to].each do |k| user = args[k] args[k] = format_address(user.email, show_user(user)) if user.is_a? User end @@ -145,21 +146,21 @@ def mail(args) def self.deliver_now_with_user_locale(user, &block) I18n.with_locale(user.settings['profile']['language']) do - self.deliver_now &block + deliver_now(&block) end end def self.deliver_now_with_default_locale(&block) I18n.with_locale(FoodsoftConfig[:default_locale]) do - self.deliver_now &block + deliver_now(&block) end end def self.deliver_now message = yield message.deliver_now - rescue => error - MailDeliveryStatus.create email: message.to[0], message: error.message + rescue StandardError => e + MailDeliveryStatus.create email: message.to[0], message: e.message end # separate method to allow plugins to mess with the attachments @@ -169,8 +170,7 @@ def add_order_result_attachments(order, options = {}) end # separate method to allow plugins to mess with the text - def additonal_welcome_text(user) - end + def additonal_welcome_text(user); end private diff --git a/app/models/article.rb b/app/models/article.rb index 46aeb014..e6e73190 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -40,13 +40,15 @@ class Article < ApplicationRecord belongs_to :supplier # @!attribute article_versions # @return [Array] Price history (current price first). - has_many :article_versions, -> { order("created_at DESC") } + has_many :article_versions, -> { order('created_at DESC') } # @!attribute order # @return [Array] Orders this article appears in. has_many :orders, through: :order_articles - has_one :latest_article_version, -> { merge(ArticleVersion.latest) }, foreign_key: :article_id, class_name: :ArticleVersion + has_one :latest_article_version, lambda { + merge(ArticleVersion.latest) + }, foreign_key: :article_id, class_name: :ArticleVersion scope :undeleted, -> { where(deleted_at: nil) } scope :available, -> { undeleted.with_latest_versions_and_categories.where(article_versions: { availability: true }) } @@ -69,7 +71,7 @@ class Article < ApplicationRecord delegate column_name, "#{column_name}=", to: :latest_article_version, allow_nil: true end - rescue + rescue StandardError # Ignore if these delegates cannot be created (can happen if table article_versions doesn't yet exist in migrations) end @@ -81,14 +83,14 @@ class Article < ApplicationRecord before_destroy :check_article_in_use after_save :reload_article_on_version_change - def self.ransackable_attributes(auth_object = nil) + def self.ransackable_attributes(_auth_object = nil) # TODO-article-version - %w(id name supplier_id article_category_id unit note manufacturer origin unit_quantity order_number) + %w[id name supplier_id article_category_id unit note manufacturer origin unit_quantity order_number] end - def self.ransackable_associations(auth_object = nil) + def self.ransackable_associations(_auth_object = nil) # TODO-article-version - %w(article_category supplier order_articles orders) + %w[article_category supplier order_articles orders] end # Returns true if article has been updated at least 2 days ago @@ -117,15 +119,15 @@ def ordered_in_order?(order) def shared_article_changed?(supplier = self.supplier) # skip early if the timestamp hasn't changed shared_article = self.shared_article(supplier) - unless shared_article.nil? || self.shared_updated_on == shared_article.updated_on - attrs = unequal_attributes(shared_article) - if attrs.empty? - # when attributes not changed, update timestamp of article - self.update_attribute(:shared_updated_on, shared_article.updated_on) - false - else - attrs - end + return if shared_article.nil? || shared_updated_on == shared_article.updated_on + + attrs = unequal_attributes(shared_article) + if attrs.empty? + # when attributes not changed, update timestamp of article + update_attribute(:shared_updated_on, shared_article.updated_on) + false + else + attrs end end @@ -136,12 +138,13 @@ def shared_article_changed?(supplier = self.supplier) 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 + new_price = nil + new_unit_quantity = nil else new_price, new_unit_quantity = convert_units(new_article) end if new_price && new_unit_quantity - new_unit = self.unit + new_unit = unit else new_price = new_article.price new_unit_quantity = new_article.unit_quantity @@ -150,26 +153,27 @@ def unequal_attributes(new_article, options = {}) ret = ArticleVersion.compare_attributes( { - :name => [self.latest_article_version.name, new_article.name], - :manufacturer => [self.latest_article_version.manufacturer, new_article.manufacturer.to_s], - :origin => [self.latest_article_version.origin, new_article.origin], - :unit => [self.latest_article_version.unit, new_unit], - :supplier_order_unit => [self.latest_article_version.supplier_order_unit, new_article.supplier_order_unit], - :minimum_order_quantity => [self.latest_article_version.minimum_order_quantity, new_article.minimum_order_quantity], - :billing_unit => [self.latest_article_version.billing_unit || self.latest_article_version.supplier_order_unit, new_article.billing_unit || new_article.supplier_order_unit], - :group_order_granularity => [self.latest_article_version.group_order_granularity, new_article.group_order_granularity], - :group_order_unit => [self.latest_article_version.group_order_unit, new_article.group_order_unit], - :price => [self.latest_article_version.price.to_f.round(2), new_price.to_f.round(2)], - :tax => [self.latest_article_version.tax, new_article.tax], - :deposit => [self.latest_article_version.deposit.to_f.round(2), new_article.deposit.to_f.round(2)], + name: [latest_article_version.name, new_article.name], + manufacturer: [latest_article_version.manufacturer, new_article.manufacturer.to_s], + origin: [latest_article_version.origin, new_article.origin], + unit: [latest_article_version.unit, new_unit], + supplier_order_unit: [latest_article_version.supplier_order_unit, new_article.supplier_order_unit], + minimum_order_quantity: [latest_article_version.minimum_order_quantity, new_article.minimum_order_quantity], + billing_unit: [latest_article_version.billing_unit || latest_article_version.supplier_order_unit, + new_article.billing_unit || new_article.supplier_order_unit], + group_order_granularity: [latest_article_version.group_order_granularity, new_article.group_order_granularity], + group_order_unit: [latest_article_version.group_order_unit, new_article.group_order_unit], + price: [latest_article_version.price.to_f.round(2), new_price.to_f.round(2)], + tax: [latest_article_version.tax, new_article.tax], + deposit: [latest_article_version.deposit.to_f.round(2), new_article.deposit.to_f.round(2)], # take care of different num-objects. # :article_unit_ratios_attributes => [self.latest_article_version.article_unit_ratios, new_unit_quantity.article_unit_ratios], - :note => [self.latest_article_version.note.to_s, new_article.note.to_s] + note: [latest_article_version.note.to_s, new_article.note.to_s] } ) - ratios_differ = self.latest_article_version.article_unit_ratios.length != new_article.article_unit_ratios.length || - self.latest_article_version.article_unit_ratios.each_with_index.any? do |article_unit_ratio, index| + ratios_differ = latest_article_version.article_unit_ratios.length != new_article.article_unit_ratios.length || + latest_article_version.article_unit_ratios.each_with_index.any? do |article_unit_ratio, index| new_article.article_unit_ratios[index].unit != article_unit_ratio.unit || new_article.article_unit_ratios[index].quantity != article_unit_ratio.quantity end @@ -184,8 +188,12 @@ def unequal_attributes(new_article, options = {}) # to get the correspondent shared article def shared_article(supplier = self.supplier) - self.order_number.blank? and return nil - @shared_article ||= supplier.shared_supplier.find_article_by_number(self.order_number) rescue nil + order_number.blank? and return nil + @shared_article ||= begin + supplier.shared_supplier.find_article_by_number(order_number) + rescue StandardError + nil + end end # convert units in foodcoop-size @@ -194,31 +202,37 @@ def shared_article(supplier = self.supplier) # returns false if units aren't foodsoft-compatible # returns nil if units are eqal def convert_units(new_article = shared_article) - if unit != new_article.unit - # legacy, used by foodcoops in Germany - if new_article.unit == "KI" && unit == "ST" # 'KI' means a box, with a different amount of items in it - # 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_unit_quantity] - else - false - end - else # use ruby-units to convert - fc_unit = (::Unit.new(unit) rescue nil) - supplier_unit = (::Unit.new(new_article.unit) rescue nil) - if fc_unit && supplier_unit && fc_unit =~ supplier_unit - conversion_factor = (supplier_unit / fc_unit).to_base.to_r - new_price = new_article.price / conversion_factor - new_unit_quantity = new_article.unit_quantity * conversion_factor - [new_price, new_unit_quantity] - else - false - end + return unless unit != new_article.unit + + # legacy, used by foodcoops in Germany + if new_article.unit == 'KI' && unit == 'ST' # 'KI' means a box, with a different amount of items in it + # 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_unit_quantity] + else + false + end + else # use ruby-units to convert + fc_unit = begin + ::Unit.new(unit) + rescue StandardError + nil + end + supplier_unit = begin + ::Unit.new(new_article.unit) + rescue StandardError + nil + end + if fc_unit && supplier_unit && fc_unit =~ supplier_unit + conversion_factor = (supplier_unit / fc_unit).to_base.to_r + new_price = new_article.price / conversion_factor + new_unit_quantity = new_article.unit_quantity * conversion_factor + [new_price, new_unit_quantity] + else + false end - else - nil end end @@ -242,21 +256,21 @@ def current_article_units # Checks if the article is in use before it will deleted def check_article_in_use - raise I18n.t('articles.model.error_in_use', :article => self.name.to_s) if self.in_open_order + raise I18n.t('articles.model.error_in_use', article: name.to_s) if in_open_order end # Create an ArticleVersion, when the price-attr are changed. def update_or_create_article_version @version_changed_before_save = false - return unless self.version_dup_required? + return unless version_dup_required? - old_version = self.latest_article_version + old_version = latest_article_version new_version = old_version.duplicate_including_article_unit_ratios - self.article_versions << new_version + article_versions << new_version OrderArticle.belonging_to_open_order .joins(:article_version) - .where(article_versions: { article_id: self.id }) + .where(article_versions: { article_id: id }) .update_all(article_version_id: new_version.id) # reload old version to avoid updating it too (would automatically happen after before_save): @@ -266,7 +280,7 @@ def update_or_create_article_version end def reload_article_on_version_change - self.reload if @version_changed_before_save + reload if @version_changed_before_save @version_changed_before_save = false end diff --git a/app/models/article_category.rb b/app/models/article_category.rb index 28597a59..1574b5d5 100644 --- a/app/models/article_category.rb +++ b/app/models/article_category.rb @@ -17,16 +17,16 @@ class ArticleCategory < ApplicationRecord normalize_attributes :name, :description - validates :name, :presence => true, :uniqueness => true, :length => { :minimum => 2 } + validates :name, presence: true, uniqueness: true, length: { minimum: 2 } before_destroy :check_for_associated_articles - def self.ransackable_attributes(auth_object = nil) - %w(id name) + def self.ransackable_attributes(_auth_object = nil) + %w[id name] end - def self.ransackable_associations(auth_object = nil) - %w(articles order_articles orders) + def self.ransackable_associations(_auth_object = nil) + %w[articles order_articles orders] end # Find a category that matches a category name; may return nil. @@ -40,7 +40,11 @@ def self.find_match(category) # 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? + unless c && c.any? + c = ArticleCategory.where('description LIKE ?', "%#{category}%").select do |s| + s.description.match(/(^|,)\s*#{category}\s*(,|$)/i) + end + end # return closest match if there are multiple c = c.sort_by { |s| s.name.length }.first if c.respond_to? :sort_by c @@ -50,6 +54,9 @@ def self.find_match(category) # Deny deleting the category when there are associated articles. def check_for_associated_articles - raise I18n.t('activerecord.errors.has_many_left', collection: Article.model_name.human) if articles.undeleted.exists? + return unless articles.undeleted.exists? + + raise I18n.t('activerecord.errors.has_many_left', + collection: Article.model_name.human) end end diff --git a/app/models/article_unit.rb b/app/models/article_unit.rb index 05da1b0b..296fce54 100644 --- a/app/models/article_unit.rb +++ b/app/models/article_unit.rb @@ -19,7 +19,9 @@ def self.clear_cache def self.as_hash(config = nil) additional_units = config&.dig(:additional_units) || [] available_units = all_cached.map(&:unit) - ArticleUnitsLib.units.to_h { |code, unit| [code, unit.merge({ visible: available_units.include?(code) || additional_units.include?(code) })] } + ArticleUnitsLib.units.to_h do |code, unit| + [code, unit.merge({ visible: available_units.include?(code) || additional_units.include?(code) })] + end end def self.as_options(config = nil) @@ -31,7 +33,7 @@ def self.as_options(config = nil) next unless available_units.include?(code) || additional_units.include?(code) label = unit[:name] - label += " (#{unit[:symbol]})" unless unit[:symbol].blank? + label += " (#{unit[:symbol]})" if unit[:symbol].present? options[label] = code end diff --git a/app/models/article_unit_ratio.rb b/app/models/article_unit_ratio.rb index b23c55d6..be007f98 100644 --- a/app/models/article_unit_ratio.rb +++ b/app/models/article_unit_ratio.rb @@ -1,6 +1,6 @@ class ArticleUnitRatio < ApplicationRecord belongs_to :article_version - validates_presence_of :quantity, :sort, :unit - validates_numericality_of :quantity, :greater_than => 0 + validates :quantity, :sort, :unit, presence: true + validates :quantity, numericality: { greater_than: 0 } end diff --git a/app/models/article_version.rb b/app/models/article_version.rb index 30b8efd9..e7401917 100644 --- a/app/models/article_version.rb +++ b/app/models/article_version.rb @@ -22,24 +22,27 @@ class ArticleVersion < ApplicationRecord # @return [Array] Order articles this price is associated with. has_many :order_articles - has_many :article_unit_ratios, after_add: :on_article_unit_ratios_change, after_remove: :on_article_unit_ratios_change, dependent: :destroy + has_many :article_unit_ratios, after_add: :on_article_unit_ratios_change, + after_remove: :on_article_unit_ratios_change, dependent: :destroy localize_input_of :price, :tax, :deposit # Validations - validates_presence_of :name, :price, :tax, :deposit, :article_category - validates_length_of :name, :in => 4..60 - validates_length_of :unit, :in => 1..15, :unless => :supplier_order_unit - validates_presence_of :supplier_order_unit, :unless => :unit - validates_length_of :note, :maximum => 255 - validates_length_of :origin, :maximum => 255 - validates_length_of :manufacturer, :maximum => 255 - validates_length_of :order_number, :maximum => 255 - validates_numericality_of :price, :greater_than_or_equal_to => 0 - validates_numericality_of :group_order_granularity, :greater_than_or_equal_to => 0 - validates_numericality_of :deposit, :tax - validates_numericality_of :minimum_order_quantity, allow_nil: true, only_integer: false, if: :supplier_order_unit_is_si_convertible - validates_numericality_of :minimum_order_quantity, allow_nil: true, only_integer: true, unless: :supplier_order_unit_is_si_convertible + validates :name, :price, :tax, :deposit, :article_category, presence: true + validates :name, length: { in: 4..60 } + validates :unit, length: { in: 1..15, unless: :supplier_order_unit } + validates :supplier_order_unit, presence: { unless: :unit } + validates :note, length: { maximum: 255 } + validates :origin, length: { maximum: 255 } + validates :manufacturer, length: { maximum: 255 } + validates :order_number, length: { maximum: 255 } + validates :price, numericality: { greater_than_or_equal_to: 0 } + validates :group_order_granularity, numericality: { greater_than_or_equal_to: 0 } + validates :deposit, :tax, numericality: true + validates :minimum_order_quantity, + numericality: { allow_nil: true, only_integer: false, if: :supplier_order_unit_is_si_convertible } + validates :minimum_order_quantity, + numericality: { allow_nil: true, only_integer: true, unless: :supplier_order_unit_is_si_convertible } # 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 @@ -57,15 +60,15 @@ class ArticleVersion < ApplicationRecord } def self.latest_outer_join_sql(article_field_name) - %{ + %( LEFT OUTER JOIN article_versions later_article_versions ON later_article_versions.article_id = #{article_field_name} AND later_article_versions.created_at > article_versions.created_at - } + ) end def supplier_order_unit_is_si_convertible - ArticleUnitsLib.unit_is_si_convertible(self.supplier_order_unit) + ArticleUnitsLib.unit_is_si_convertible(supplier_order_unit) end # TODO: Maybe use the nilify blanks gem instead of the following six methods?: @@ -122,8 +125,8 @@ def self_or_ratios_changed? end def duplicate_including_article_unit_ratios - new_version = self.dup - self.article_unit_ratios.each do |ratio| + new_version = dup + article_unit_ratios.each do |ratio| ratio = ratio.dup ratio.article_version_id = nil new_version.article_unit_ratios << ratio @@ -138,7 +141,9 @@ def duplicate_including_article_unit_ratios # @param attributes [Hash] Attributes with old and new values # @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?) } + unequal_attributes = attributes.select do |_name, values| + values[0] != values[1] && !(values[0].blank? && values[1].blank?) + end unequal_attributes.to_a.map { |a| [a[0], a[1].last] }.to_h end @@ -148,20 +153,22 @@ def self.compare_attributes(attributes) # this came in the way, and we now allow duplicate names for the 'all' methods - expecting foodcoops to # make their own choice among products with different units by making articles available/unavailable. def uniqueness_of_name - matches = Article.includes(latest_article_version: :article_unit_ratios).where(article_versions: { name: name }, supplier_id: article.supplier_id, deleted_at: article.deleted_at, type: article.type) + matches = Article.includes(latest_article_version: :article_unit_ratios).where(article_versions: { name: name }, + supplier_id: article.supplier_id, deleted_at: article.deleted_at, type: article.type) matches = matches.where.not(id: article.id) unless article.new_record? # supplier should always be there - except, perhaps, on initialization (on seeding) if article.supplier && (article.supplier.shared_sync_method.blank? || article.supplier.shared_sync_method == 'import') errors.add :name, :taken if matches.any? - elsif matches.where(article_versions: { unit: unit, supplier_order_unit: nil, article_unit_ratios: { quantity: unit_quantity, unit: 'XPP' } }).any? + elsif matches.where(article_versions: { unit: unit, supplier_order_unit: nil, + article_unit_ratios: { quantity: unit_quantity, unit: 'XPP' } }).any? errors.add :name, :taken_with_unit end end def only_one_unit_type - unless unit.blank? || supplier_order_unit.blank? - errors.add :unit # not specifying a specific error message as this should be prevented by js - end + return if unit.blank? || supplier_order_unit.blank? + + errors.add :unit # not specifying a specific error message as this should be prevented by js end def on_article_unit_ratios_change(_some_change) diff --git a/app/models/bank_account.rb b/app/models/bank_account.rb index de15ee4b..92cefad3 100644 --- a/app/models/bank_account.rb +++ b/app/models/bank_account.rb @@ -5,23 +5,21 @@ class BankAccount < ApplicationRecord normalize_attributes :name, :iban, :description - validates :name, :presence => true, :uniqueness => true, :length => { :minimum => 2 } - validates :iban, :presence => true, :uniqueness => true - validates_format_of :iban, :with => /\A[A-Z]{2}[0-9]{2}[0-9A-Z]{,30}\z/ - validates_numericality_of :balance, :message => I18n.t('bank_account.model.invalid_balance') + validates :name, presence: true, uniqueness: true, length: { minimum: 2 } + validates :iban, presence: true, uniqueness: true + validates :iban, format: { with: /\A[A-Z]{2}[0-9]{2}[0-9A-Z]{,30}\z/ } + validates :balance, numericality: { message: I18n.t('bank_account.model.invalid_balance') } # @return [Function] Method wich can be called to import transaction from a bank or nil if unsupported def find_connector klass = BankAccountConnector.find iban - return klass.new self if klass + klass.new self if klass end def assign_unlinked_transactions count = 0 bank_transactions.without_financial_link.includes(:supplier, :user).each do |t| - if t.assign_to_ordergroup || t.assign_to_invoice - count += 1 - end + count += 1 if t.assign_to_ordergroup || t.assign_to_invoice end count end diff --git a/app/models/bank_gateway.rb b/app/models/bank_gateway.rb index 3811f128..f8043755 100644 --- a/app/models/bank_gateway.rb +++ b/app/models/bank_gateway.rb @@ -4,5 +4,5 @@ class BankGateway < ApplicationRecord scope :with_unattended_support, -> { where.not(unattended_user: nil) } - validates_presence_of :name, :url + validates :name, :url, presence: true end diff --git a/app/models/bank_transaction.rb b/app/models/bank_transaction.rb index fa1a3da5..66454b32 100644 --- a/app/models/bank_transaction.rb +++ b/app/models/bank_transaction.rb @@ -21,8 +21,8 @@ class BankTransaction < ApplicationRecord belongs_to :supplier, optional: true, foreign_key: 'iban', primary_key: 'iban' belongs_to :user, optional: true, foreign_key: 'iban', primary_key: 'iban' - validates_presence_of :date, :amount, :bank_account_id - validates_numericality_of :amount + validates :date, :amount, :bank_account_id, presence: true + validates :amount, numericality: true scope :without_financial_link, -> { where(financial_link: nil) } @@ -30,13 +30,13 @@ class BankTransaction < ApplicationRecord localize_input_of :amount def image_url - 'data:image/png;base64,' + Base64.encode64(self.image) + 'data:image/png;base64,' + Base64.encode64(image) end def assign_to_invoice return false unless supplier - content = text || "" + content = text || '' content += "\n" + reference if reference.present? invoices = supplier.invoices.unpaid.select { |i| content.include? i.number } invoices_sum = invoices.map(&:amount).sum @@ -48,7 +48,7 @@ def assign_to_invoice update_attribute :financial_link, link end - return true + true end def assign_to_ordergroup @@ -77,6 +77,6 @@ def assign_to_ordergroup update_attribute :financial_link, link end - return true + true end end diff --git a/app/models/concerns/custom_fields.rb b/app/models/concerns/custom_fields.rb index d54cebe5..aafec389 100644 --- a/app/models/concerns/custom_fields.rb +++ b/app/models/concerns/custom_fields.rb @@ -10,7 +10,7 @@ module CustomFields end after_save do - self.settings.custom_fields = custom_fields if custom_fields + settings.custom_fields = custom_fields if custom_fields end end end diff --git a/app/models/concerns/find_each_with_order.rb b/app/models/concerns/find_each_with_order.rb index 0e7cd5cd..faf545b2 100644 --- a/app/models/concerns/find_each_with_order.rb +++ b/app/models/concerns/find_each_with_order.rb @@ -3,9 +3,9 @@ module FindEachWithOrder extend ActiveSupport::Concern class_methods do - def find_each_with_order(options = {}) + def find_each_with_order(options = {}, &block) find_in_batches_with_order(options) do |records| - records.each { |record| yield record } + records.each(&block) 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 4b888438..fb0aa590 100644 --- a/app/models/concerns/mark_as_deleted_with_name.rb +++ b/app/models/concerns/mark_as_deleted_with_name.rb @@ -3,7 +3,7 @@ module MarkAsDeletedWithName def mark_as_deleted # get maximum length of name - max_length = 100000 + max_length = 100_000 if lenval = self.class.validators_on(:name).detect { |v| v.is_a?(ActiveModel::Validations::LengthValidator) } max_length = lenval.options[:maximum] end diff --git a/app/models/concerns/price_calculation.rb b/app/models/concerns/price_calculation.rb index dd7ee5ad..b88fb2d8 100644 --- a/app/models/concerns/price_calculation.rb +++ b/app/models/concerns/price_calculation.rb @@ -23,21 +23,21 @@ def fc_price # get the unit ratio quantity in reference to the supplier_order_unit def get_unit_ratio_quantity(unit) - return 1 if unit == self.supplier_order_unit + return 1 if unit == supplier_order_unit - ratio = self.article_unit_ratios.find_by_unit(unit) + ratio = article_unit_ratios.find_by_unit(unit) return ratio.quantity unless ratio.nil? - related_ratio = self.article_unit_ratios.detect { |current_ratio| ArticleUnit.as_hash[current_ratio.unit][:baseUnit] == ArticleUnit.as_hash[unit][:baseUnit] } - unless related_ratio.nil? - return related_ratio.quantity / ArticleUnit.as_hash[unit][:conversionFactor] * ArticleUnit.as_hash[related_ratio.unit][:conversionFactor] + related_ratio = article_unit_ratios.detect do |current_ratio| + ArticleUnit.as_hash[current_ratio.unit][:baseUnit] == ArticleUnit.as_hash[unit][:baseUnit] end + return related_ratio.quantity / ArticleUnit.as_hash[unit][:conversionFactor] * ArticleUnit.as_hash[related_ratio.unit][:conversionFactor] unless related_ratio.nil? - ArticleUnit.as_hash[self.supplier_order_unit][:conversionFactor] / ArticleUnit.as_hash[unit][:conversionFactor] + ArticleUnit.as_hash[supplier_order_unit][:conversionFactor] / ArticleUnit.as_hash[unit][:conversionFactor] end def convert_quantity(quantity, input_unit, output_unit) - quantity / self.get_unit_ratio_quantity(input_unit) * self.get_unit_ratio_quantity(output_unit) + quantity / get_unit_ratio_quantity(input_unit) * get_unit_ratio_quantity(output_unit) end def group_order_price(value = nil) @@ -57,6 +57,6 @@ def fc_group_order_price private def add_percent(value, percent) - (value * (percent * 0.01 + 1)).round(2) + (value * ((percent * 0.01) + 1)).round(2) end end diff --git a/app/models/delivery.rb b/app/models/delivery.rb index ab5ca5ec..bb2aed45 100644 --- a/app/models/delivery.rb +++ b/app/models/delivery.rb @@ -4,10 +4,10 @@ class Delivery < StockEvent scope :recent, -> { order('created_at DESC').limit(10) } - validates_presence_of :supplier_id + validates :supplier_id, presence: true validate :stock_articles_must_be_unique - accepts_nested_attributes_for :stock_changes, :allow_destroy => :true + accepts_nested_attributes_for :stock_changes, allow_destroy: :true def new_stock_changes=(stock_change_attributes) for attributes in stock_change_attributes @@ -16,7 +16,7 @@ def new_stock_changes=(stock_change_attributes) end def includes_article?(article) - self.stock_changes.map { |stock_change| stock_change.stock_article.id }.include? article.id + stock_changes.map { |stock_change| stock_change.stock_article.id }.include? article.id end def sum(type = :gross) @@ -39,8 +39,8 @@ def sum(type = :gross) protected def stock_articles_must_be_unique - 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 + return if 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 diff --git a/app/models/financial_link.rb b/app/models/financial_link.rb index 30a1955c..51108cd2 100644 --- a/app/models/financial_link.rb +++ b/app/models/financial_link.rb @@ -4,13 +4,13 @@ class FinancialLink < ApplicationRecord has_many :invoices scope :incomplete, -> { with_full_sum.where.not('full_sums.full_sum' => 0) } - scope :unused, -> { + scope :unused, lambda { 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 }) } - scope :with_full_sum, -> { + scope :with_full_sum, lambda { select(:id, :note, :full_sum).joins(<<-SQL) LEFT JOIN ( SELECT id, COALESCE(bt_sum, 0) - COALESCE(ft_sum, 0) + COALESCE(i_sum, 0) AS full_sum diff --git a/app/models/financial_transaction.rb b/app/models/financial_transaction.rb index 5c26058b..68882d0d 100644 --- a/app/models/financial_transaction.rb +++ b/app/models/financial_transaction.rb @@ -6,14 +6,16 @@ class FinancialTransaction < ApplicationRecord belongs_to :financial_link, optional: true belongs_to :financial_transaction_type belongs_to :group_order, optional: true - belongs_to :reverts, optional: true, class_name: 'FinancialTransaction', foreign_key: 'reverts_id' + belongs_to :reverts, optional: true, class_name: 'FinancialTransaction' has_one :reverted_by, class_name: 'FinancialTransaction', foreign_key: 'reverts_id' - validates_presence_of :amount, :note, :user_id - validates_numericality_of :amount, greater_then: -100_000, - less_than: 100_000 + validates :amount, :note, :user_id, presence: true + validates :amount, numericality: { greater_then: -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 :visible, lambda { + 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) } scope :with_ordergroup, -> { where.not(ordergroup: nil) } @@ -26,12 +28,12 @@ class FinancialTransaction < ApplicationRecord # @todo remove alias (and rename created_on to created_at below) after #575 ransack_alias :created_at, :created_on - def self.ransackable_attributes(auth_object = nil) - %w(id amount note created_on user_id) + def self.ransackable_attributes(_auth_object = nil) + %w[id amount note created_on user_id] end - def self.ransackable_associations(auth_object = nil) - %w() # none, and certainly not user until we've secured that more + def self.ransackable_associations(_auth_object = nil) + %w[] # none, and certainly not user until we've secured that more end # Use this save method instead of simple save and after callback diff --git a/app/models/financial_transaction_class.rb b/app/models/financial_transaction_class.rb index 43ded5fd..0c924993 100644 --- a/app/models/financial_transaction_class.rb +++ b/app/models/financial_transaction_class.rb @@ -5,7 +5,7 @@ class FinancialTransactionClass < ApplicationRecord has_many :ordergroups, -> { distinct }, through: :financial_transactions validates :name, presence: true - validates_uniqueness_of :name + validates :name, uniqueness: true after_save :update_balance_of_ordergroups diff --git a/app/models/financial_transaction_type.rb b/app/models/financial_transaction_type.rb index 392a1a95..97ed7979 100644 --- a/app/models/financial_transaction_type.rb +++ b/app/models/financial_transaction_type.rb @@ -5,13 +5,13 @@ class FinancialTransactionType < ApplicationRecord has_many :ordergroups, -> { distinct }, through: :financial_transactions validates :name, presence: true - validates_uniqueness_of :name - validates_uniqueness_of :name_short, allow_blank: true, allow_nil: true - validates_format_of :name_short, :with => /\A[A-Za-z]*\z/ + validates :name, uniqueness: true + validates :name_short, uniqueness: { allow_blank: true } + validates :name_short, format: { with: /\A[A-Za-z]*\z/ } validates :financial_transaction_class, presence: true - after_save :update_balance_of_ordergroups before_destroy :restrict_deleting_last_financial_transaction_type + after_save :update_balance_of_ordergroups scope :with_name_short, -> { where.not(name_short: [nil, '']) } @@ -20,7 +20,7 @@ def self.default end def self.has_multiple_types - self.count > 1 + count > 1 end protected diff --git a/app/models/group.rb b/app/models/group.rb index a667ea5a..a4a770eb 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -7,8 +7,8 @@ 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_uniqueness_of :name + validates :name, presence: true, length: { in: 1..25 } + validates :name, uniqueness: true attr_reader :user_tokens @@ -25,7 +25,7 @@ def non_members end def user_tokens=(ids) - self.user_ids = ids.split(",") + self.user_ids = ids.split(',') end def deleted? diff --git a/app/models/group_order.rb b/app/models/group_order.rb index de74a232..b48c9f71 100644 --- a/app/models/group_order.rb +++ b/app/models/group_order.rb @@ -6,14 +6,14 @@ class GroupOrder < ApplicationRecord belongs_to :order belongs_to :ordergroup, optional: true - has_many :group_order_articles, :dependent => :destroy - has_many :order_articles, :through => :group_order_articles + has_many :group_order_articles, dependent: :destroy + has_many :order_articles, through: :group_order_articles has_one :financial_transaction belongs_to :updated_by, optional: true, class_name: 'User', foreign_key: 'updated_by_user_id' - 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 :order_id, presence: true + validates :price, numericality: true + validates :ordergroup_id, uniqueness: { 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) } @@ -21,42 +21,47 @@ class GroupOrder < ApplicationRecord scope :ordered, -> { includes(:ordergroup).order('groups.name') } - def self.ransackable_attributes(auth_object = nil) - %w(id price) + def self.ransackable_attributes(_auth_object = nil) + %w[id price] end - def self.ransackable_associations(auth_object = nil) - %w(order group_order_articles) + def self.ransackable_associations(_auth_object = nil) + %w[order group_order_articles] end # Generate some data for the javascript methods in ordering view def load_data data = {} - data[:account_balance] = ordergroup.nil? ? BigDecimal.new('+Infinity') : ordergroup.account_balance - data[:available_funds] = ordergroup.nil? ? BigDecimal.new('+Infinity') : ordergroup.get_available_funds(self) + data[:account_balance] = ordergroup.nil? ? BigDecimal('+Infinity') : ordergroup.account_balance + data[:available_funds] = ordergroup.nil? ? BigDecimal('+Infinity') : ordergroup.get_available_funds(self) # load prices and other stuff.... data[:order_articles] = {} - order.articles_grouped_by_category.each do |article_category, 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_version.fc_group_order_price, - :unit => order_article.article_version.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, - :ratio_group_order_unit_supplier_unit => order_article.article_version.convert_quantity(1, order_article.article_version.supplier_order_unit, order_article.article_version.group_order_unit), - :quantity_available => (order.stockit? ? order_article.article_version.article.quantity_available : 0), - :minimum_order_quantity => order_article.article_version.minimum_order_quantity ? order_article.article_version.convert_quantity(order_article.article_version.minimum_order_quantity, order_article.article_version.supplier_order_unit, order_article.article_version.group_order_unit) : nil + price: order_article.article_version.fc_group_order_price, + unit: order_article.article_version.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, + ratio_group_order_unit_supplier_unit: order_article.article_version.convert_quantity(1, + order_article.article_version.supplier_order_unit, order_article.article_version.group_order_unit), + quantity_available: (order.stockit? ? order_article.article_version.article.quantity_available : 0), + minimum_order_quantity: if order_article.article_version.minimum_order_quantity + order_article.article_version.convert_quantity( + order_article.article_version.minimum_order_quantity, order_article.article_version.supplier_order_unit, order_article.article_version.group_order_unit + ) + end } end end @@ -71,12 +76,12 @@ def save_group_order_articles # 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_f, quantities[:tolerance].to_f) end # Also update results for the order_article - logger.debug "[save_group_order_articles] update order_article.results!" + logger.debug '[save_group_order_articles] update order_article.results!' order_article.update_results! end @@ -99,7 +104,7 @@ def save_ordering! end def ordergroup_name - ordergroup ? ordergroup.name : I18n.t('model.group_order.stock_ordergroup_name', :user => updated_by.try(:name) || '?') + ordergroup ? ordergroup.name : I18n.t('model.group_order.stock_ordergroup_name', user: updated_by.try(:name) || '?') end def total diff --git a/app/models/group_order_article.rb b/app/models/group_order_article.rb index c00208ab..fdec8365 100644 --- a/app/models/group_order_article.rb +++ b/app/models/group_order_article.rb @@ -6,21 +6,21 @@ class GroupOrderArticle < ApplicationRecord 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 :group_order, :order_article, presence: true + validates :order_article_id, uniqueness: { 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: { greater_than_or_equal_to: 0 } - scope :ordered, -> { includes(:group_order => :ordergroup).order('groups.name') } + scope :ordered, -> { includes(group_order: :ordergroup).order('groups.name') } localize_input_of :result - def self.ransackable_attributes(auth_object = nil) - %w(id quantity tolerance result) + def self.ransackable_attributes(_auth_object = nil) + %w[id quantity tolerance result] end - def self.ransackable_associations(auth_object = nil) - %w(order_article group_order) + def self.ransackable_associations(_auth_object = nil) + %w[order_article group_order] end # Setter used in group_order_article#new @@ -30,7 +30,7 @@ def ordergroup_id=(id) end def ordergroup_id - group_order.try!(:ordergroup_id) + group_order&.ordergroup_id end # Updates the quantity/tolerance for this GroupOrderArticle by updating both GroupOrderArticle properties @@ -43,7 +43,7 @@ def update_quantities(quantity, tolerance) # When quantity and tolerance are zero, we don't serve any purpose if quantity == 0 && tolerance == 0 - logger.debug("Self-destructing since requested quantity and tolerance are zero") + logger.debug('Self-destructing since requested quantity and tolerance are zero') destroy! return end @@ -52,24 +52,26 @@ def update_quantities(quantity, tolerance) quantities = group_order_article_quantities.order('created_on DESC').to_a logger.debug("GroupOrderArticleQuantity items found: #{quantities.size}") - if (quantities.size == 0) + if quantities.size == 0 # There is no GroupOrderArticleQuantity item yet, just insert with desired quantities... - logger.debug("No quantities entry at all, inserting a new one with the desired quantities") - quantities.push(GroupOrderArticleQuantity.new(:group_order_article => self, :quantity => quantity, :tolerance => tolerance)) - self.quantity, self.tolerance = quantity, tolerance + logger.debug('No quantities entry at all, inserting a new one with the desired quantities') + quantities.push(GroupOrderArticleQuantity.new(group_order_article: self, quantity: quantity, + tolerance: tolerance)) + self.quantity = quantity + self.tolerance = tolerance else # Decrease quantity/tolerance if necessary by going through the existing items and decreasing their values... i = 0 - while (i < quantities.size && (quantity < self.quantity || tolerance < self.tolerance)) + while i < quantities.size && (quantity < self.quantity || tolerance < self.tolerance) logger.debug("Need to decrease quantities for GroupOrderArticleQuantity[#{quantities[i].id}]") - if (quantity < self.quantity && quantities[i].quantity > 0) + if quantity < self.quantity && quantities[i].quantity > 0 delta = self.quantity - quantity delta = (delta > quantities[i].quantity ? quantities[i].quantity : delta) logger.debug("Decreasing quantity by #{delta}") quantities[i].quantity -= delta self.quantity -= delta end - if (tolerance < self.tolerance && quantities[i].tolerance > 0) + if tolerance < self.tolerance && quantities[i].tolerance > 0 delta = self.tolerance - tolerance delta = (delta > quantities[i].tolerance ? quantities[i].tolerance : delta) logger.debug("Decreasing tolerance by #{delta}") @@ -79,12 +81,12 @@ def update_quantities(quantity, tolerance) i += 1 end # If there is at least one increased value: insert a new GroupOrderArticleQuantity object - if (quantity > self.quantity || tolerance > self.tolerance) - logger.debug("Inserting a new GroupOrderArticleQuantity") + 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 @@ -93,8 +95,10 @@ def update_quantities(quantity, tolerance) end # Check if something went terribly wrong and quantites have not been adjusted as desired. - if (self.quantity != quantity || self.tolerance != tolerance) - raise ActiveRecord::RecordNotSaved.new("Unable to update GroupOrderArticle/-Quantities to desired quantities! (#{self.quantity} != #{quantity} || #{self.tolerance} != {tolerance})", self) + if self.quantity != quantity || self.tolerance != tolerance + raise ActiveRecord::RecordNotSaved.new( + "Unable to update GroupOrderArticle/-Quantities to desired quantities! (#{self.quantity} != #{quantity} || #{self.tolerance} != {tolerance})", self + ) end # Remove zero-only items. @@ -119,13 +123,14 @@ def calculate_result(total = nil) quantity = tolerance = total_quantity = 0 # Get total - if not total.nil? + if !total.nil? logger.debug "<#{order_article.article_version.name}> => #{total} (given)" elsif order_article.article_version.is_a?(StockArticle) total = order_article.article_version.quantity logger.debug "<#{order_article.article_version.name}> (stock) => #{total}" else - total = order_article.article_version.convert_quantity(order_article.units_to_order, order_article.article_version.supplier_order_unit, order_article.article_version.group_order_unit) + total = order_article.article_version.convert_quantity(order_article.units_to_order, + order_article.article_version.supplier_order_unit, order_article.article_version.group_order_unit) logger.debug "<#{order_article.article_version.name}> units_to_order #{order_article.units_to_order} => #{total}" end @@ -143,7 +148,7 @@ def calculate_result(total = nil) q = goaq.quantity q = [q, total - total_quantity].min if first_order_first_serve total_quantity += q - if goaq.group_order_article_id == self.id + if goaq.group_order_article_id == id logger.debug "increasing quantity by #{q}" quantity += q end @@ -152,11 +157,11 @@ def calculate_result(total = nil) # Determine tolerance to be ordered... if total_quantity < total - logger.debug "determining additional items to be ordered from tolerance" + logger.debug 'determining additional items to be ordered from tolerance' order_quantities.each do |goaq| q = [goaq.tolerance, total - total_quantity].min total_quantity += q - if goaq.group_order_article_id == self.id + if goaq.group_order_article_id == id logger.debug "increasing tolerance by #{q}" tolerance += q end @@ -168,7 +173,7 @@ def calculate_result(total = nil) 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 @@ -183,8 +188,8 @@ def result(type = :total) # This is used for automatic distribution, e.g., in order.finish! or when receiving orders def save_results!(article_total = nil) new_result = calculate_result(article_total)[:total] - self.update_attribute(:result_computed, new_result) - self.update_attribute(:result, new_result) + update_attribute(:result_computed, new_result) + update_attribute(:result, new_result) end # Returns total price for this individual article @@ -212,8 +217,8 @@ def result_manually_changed? private def check_order_not_closed - if order_article.order.closed? - errors.add(:order_article, I18n.t('model.group_order_article.order_closed')) - end + return unless order_article.order.closed? + + errors.add(:order_article, I18n.t('model.group_order_article.order_closed')) end end diff --git a/app/models/group_order_article_quantity.rb b/app/models/group_order_article_quantity.rb index 1e29985f..12832b2c 100644 --- a/app/models/group_order_article_quantity.rb +++ b/app/models/group_order_article_quantity.rb @@ -4,5 +4,5 @@ class GroupOrderArticleQuantity < ApplicationRecord belongs_to :group_order_article - validates_presence_of :group_order_article_id + validates :group_order_article_id, presence: true end diff --git a/app/models/invite.rb b/app/models/invite.rb index e37a8a18..d471aa50 100644 --- a/app/models/invite.rb +++ b/app/models/invite.rb @@ -5,12 +5,12 @@ class Invite < ApplicationRecord belongs_to :user belongs_to :group - validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i - validates_presence_of :user - validates_presence_of :group - validates_presence_of :token - validates_presence_of :expires_at - validate :email_not_already_registered, :on => :create + validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i } + validates :user, presence: true + validates :group, presence: true + validates :token, presence: true + validates :expires_at, presence: true + validate :email_not_already_registered, on: :create before_validation :set_token_and_expires_at @@ -19,15 +19,15 @@ class Invite < ApplicationRecord # Before validation, set token and expires_at. def set_token_and_expires_at self.token = Digest::SHA1.hexdigest(Time.now.to_s + rand(100).to_s) - self.expires_at = Time.now.advance(:days => 7) + self.expires_at = Time.now.advance(days: 7) end private # Custom validation: check that email does not already belong to a registered user. def email_not_already_registered - unless User.find_by_email(self.email).nil? - errors.add(:email, I18n.t('invites.errors.already_member')) - end + return if User.find_by_email(email).nil? + + errors.add(:email, I18n.t('invites.errors.already_member')) end end diff --git a/app/models/invoice.rb b/app/models/invoice.rb index f79cf27f..c379e15e 100644 --- a/app/models/invoice.rb +++ b/app/models/invoice.rb @@ -2,13 +2,13 @@ class Invoice < ApplicationRecord include CustomFields belongs_to :supplier - belongs_to :created_by, :class_name => 'User', :foreign_key => 'created_by_user_id' + belongs_to :created_by, class_name: 'User', foreign_key: 'created_by_user_id' belongs_to :financial_link, optional: true has_many :deliveries, dependent: :nullify has_many :orders, dependent: :nullify - validates_presence_of :supplier_id - validates_numericality_of :amount, :deposit, :deposit_credit + validates :supplier_id, presence: true + validates :amount, :deposit, :deposit_credit, numericality: true validate :valid_attachment scope :unpaid, -> { where(paid_on: nil) } @@ -22,18 +22,18 @@ class Invoice < ApplicationRecord def attachment=(incoming_file) self.attachment_data = incoming_file.read # allow to soft-fail when FileMagic isn't present and removed from Gemfile (e.g. Heroku) - self.attachment_mime = defined?(FileMagic) ? FileMagic.new(FileMagic::MAGIC_MIME).buffer(self.attachment_data) : 'application/octet-stream' + self.attachment_mime = defined?(FileMagic) ? FileMagic.new(FileMagic::MAGIC_MIME).buffer(attachment_data) : 'application/octet-stream' end def delete_attachment=(value) - if value == '1' - self.attachment_data = nil - self.attachment_mime = nil - end + return unless value == '1' + + self.attachment_data = nil + self.attachment_mime = nil end def user_can_edit?(user) - user.role_finance? || (user.role_invoices? && !self.paid_on && self.created_by.try(:id) == user.id) + user.role_finance? || (user.role_invoices? && !paid_on && created_by.try(:id) == user.id) end # Amount without deposit @@ -44,9 +44,9 @@ def net_amount def orders_sum orders .joins(order_articles: [:article_version]) - .sum("COALESCE(order_articles.units_received, order_articles.units_billed, order_articles.units_to_order)" \ - + "* article_versions.unit_quantity" \ - + "* ROUND((article_versions.price + article_versions.deposit) * (100 + article_versions.tax) / 100, 2)") + .sum('COALESCE(order_articles.units_received, order_articles.units_billed, order_articles.units_to_order)' \ + + '* article_versions.unit_quantity' \ + + '* ROUND((article_versions.price + article_versions.deposit) * (100 + article_versions.tax) / 100, 2)') end def orders_transport_sum @@ -62,11 +62,11 @@ def expected_amount protected def valid_attachment - if attachment_data - mime = MIME::Type.simplified(attachment_mime) - unless ['application/pdf', 'image/jpeg'].include? mime - errors.add :attachment, I18n.t('model.invoice.invalid_mime', :mime => mime) - end - end + return unless attachment_data + + mime = MIME::Type.simplified(attachment_mime) + return if ['application/pdf', 'image/jpeg'].include? mime + + errors.add :attachment, I18n.t('model.invoice.invalid_mime', mime: mime) end end diff --git a/app/models/membership.rb b/app/models/membership.rb index bebf00e2..4ebc061c 100644 --- a/app/models/membership.rb +++ b/app/models/membership.rb @@ -8,6 +8,6 @@ class Membership < ApplicationRecord # check if this is the last admin-membership and deny def check_last_admin - raise I18n.t('model.membership.no_admin_delete') if self.group.role_admin? && self.group.memberships.size == 1 && Group.where(role_admin: true).count == 1 + raise I18n.t('model.membership.no_admin_delete') if group.role_admin? && group.memberships.size == 1 && Group.where(role_admin: true).count == 1 end end diff --git a/app/models/order.rb b/app/models/order.rb index 0d5c2f09..db17e345 100644 --- a/app/models/order.rb +++ b/app/models/order.rb @@ -2,30 +2,30 @@ class Order < ApplicationRecord attr_accessor :ignore_warnings, :transport_distribution # Associations - has_many :order_articles, :dependent => :destroy - has_many :article_versions, :through => :order_articles + has_many :order_articles, dependent: :destroy + has_many :article_versions, through: :order_articles has_many :articles, through: :article_versions - has_many :group_orders, :dependent => :destroy - has_many :ordergroups, :through => :group_orders - has_many :users_ordered, :through => :ordergroups, :source => :users - has_many :comments, -> { order('created_at') }, :class_name => "OrderComment" + has_many :group_orders, dependent: :destroy + has_many :ordergroups, through: :group_orders + has_many :users_ordered, through: :ordergroups, source: :users + has_many :comments, -> { order('created_at') }, class_name: 'OrderComment' has_many :stock_changes belongs_to :invoice, optional: true belongs_to :supplier, optional: true - belongs_to :updated_by, :class_name => 'User', :foreign_key => 'updated_by_user_id' - belongs_to :created_by, :class_name => 'User', :foreign_key => 'created_by_user_id' + belongs_to :updated_by, class_name: 'User', foreign_key: 'updated_by_user_id' + belongs_to :created_by, class_name: 'User', foreign_key: 'created_by_user_id' enum end_action: { no_end_action: 0, auto_close: 1, auto_close_and_send: 2, auto_close_and_send_min_quantity: 3 } - enum transport_distribution: [:skip, :ordergroup, :price, :articles] + enum transport_distribution: { skip: 0, ordergroup: 1, price: 2, articles: 3 } # Validations - validates_presence_of :starts + validates :starts, presence: true validate :starts_before_ends, :include_articles validate :keep_ordered_articles + before_validation :distribute_transport # Callbacks after_save :save_order_articles, :update_price_of_group_orders! - before_validation :distribute_transport # Finders scope :started, -> { where('starts <= ?', Time.now) } @@ -50,12 +50,12 @@ class Order < ApplicationRecord include DateTimeAttributeValidate date_time_attribute :starts, :boxfill, :ends - def self.ransackable_attributes(auth_object = nil) - %w(id state supplier_id starts boxfill ends pickup) + def self.ransackable_attributes(_auth_object = nil) + %w[id state supplier_id starts boxfill ends pickup] end - def self.ransackable_associations(auth_object = nil) - %w(supplier articles order_articles) + def self.ransackable_associations(_auth_object = nil) + %w[supplier articles order_articles] end def stockit? @@ -71,9 +71,9 @@ def articles_for_ordering # make sure to include those articles which are no longer available # but which have already been ordered in this stock order StockArticle.available.includes(latest_article_version: :article_category) - .order('article_categories.name', 'article_versions.name').reject { |a| + .order('article_categories.name', 'article_versions.name').reject do |a| a.quantity_available <= 0 && !a.ordered_in_order?(self) - }.group_by { |a| a.article_category.name } + end.group_by { |a| a.article_category.name } else supplier.articles.available.group_by { |a| a.article_category.name } end @@ -88,9 +88,7 @@ def supplier_articles end # Save ids, and create/delete order_articles after successfully saved the order - def article_ids=(ids) - @article_ids = ids - end + attr_writer :article_ids def article_ids @article_ids ||= order_articles.map { |oa| oa.article_version.article_id.to_s } @@ -102,19 +100,19 @@ def erroneous_article_ids end def open? - state == "open" + state == 'open' end def finished? - state == "finished" || state == "received" + state == 'finished' || state == 'received' end def received? - state == "received" + state == 'received' end def closed? - state == "closed" + state == 'closed' end def boxfill? @@ -135,11 +133,18 @@ def init_dates self.starts ||= Time.now if FoodsoftConfig[:order_schedule] # try to be smart when picking a reference day - last = (DateTime.parse(FoodsoftConfig[:order_schedule][:initial]) rescue nil) + last = begin + DateTime.parse(FoodsoftConfig[:order_schedule][:initial]) + rescue StandardError + nil + end last ||= Order.finished.reorder(:starts).first.try(:starts) last ||= self.starts # adjust boxfill and end date - self.boxfill ||= FoodsoftDateUtil.next_occurrence last, self.starts, FoodsoftConfig[:order_schedule][:boxfill] if is_boxfill_useful? + if is_boxfill_useful? + self.boxfill ||= FoodsoftDateUtil.next_occurrence last, self.starts, + FoodsoftConfig[:order_schedule][:boxfill] + end self.ends ||= FoodsoftDateUtil.next_occurrence last, self.starts, FoodsoftConfig[:order_schedule][:ends] end self @@ -150,7 +155,7 @@ def init_dates 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 = group_orders.index_by { |go| go.order_id } orders.map do |order| { order: order, @@ -161,11 +166,11 @@ def self.ordergroup_group_orders_map(ordergroup) # search GroupOrder of given Ordergroup def group_order(ordergroup) - group_orders.where(:ordergroup_id => ordergroup.id).first + group_orders.where(ordergroup_id: ordergroup.id).first end def stock_group_order - group_orders.where(:ordergroup_id => nil).first + group_orders.where(ordergroup_id: nil).first end # Returns OrderArticles in a nested Array, grouped by category and ordered by article name. @@ -173,7 +178,8 @@ def stock_group_order # e.g: [["drugs",[teethpaste, toiletpaper]], ["fruits" => [apple, banana, lemon]]] def articles_grouped_by_category @articles_grouped_by_category ||= order_articles - .includes([:article_version, :group_order_articles, article_version: :article_category]) + .includes([:article_version, :group_order_articles, + { article_version: :article_category }]) .order('article_versions.name') .group_by { |oa| oa.article_version.article_category.name } .sort { |a, b| a[0] <=> b[0] } @@ -190,10 +196,10 @@ def articles_sort_by_category # FIXME: Consider order.foodcoop_result def profit(options = {}) markup = options[:without_markup] || false - if invoice - groups_sum = markup ? sum(:groups_without_markup) : sum(:groups) - groups_sum - invoice.net_amount - end + return unless invoice + + groups_sum = markup ? sum(:groups_without_markup) : sum(:groups) + groups_sum - invoice.net_amount end # Returns the all round price of a finished order @@ -203,9 +209,10 @@ def profit(options = {}) # :fc, guess what... def sum(type = :gross) total = 0 - if type == :net || type == :gross || type == :fc + if %i[net gross fc].include?(type) for oa in order_articles.ordered.includes(:article_version) - quantity = oa.units * oa.article_version.convert_quantity(1, oa.article_version.supplier_order_unit, oa.article_version.group_order_unit) + quantity = oa.units * oa.article_version.convert_quantity(1, oa.article_version.supplier_order_unit, + oa.article_version.group_order_unit) case type when :net total += quantity * oa.article_version.group_order_price @@ -215,7 +222,7 @@ def sum(type = :gross) total += quantity * oa.article_version.fc_group_order_price end end - elsif type == :groups || type == :groups_without_markup + elsif %i[groups groups_without_markup].include?(type) for go in group_orders.includes(group_order_articles: { order_article: :article_version }) for goa in go.group_order_articles case type @@ -233,29 +240,29 @@ def sum(type = :gross) # Finishes this order. This will set the order state to "finish" and the end property to the current time. # Ignored if the order is already finished. def finish!(user) - unless finished? - Order.transaction do - # set new order state (needed by notify_order_finished) - update_attributes!(:state => 'finished', :ends => Time.now, :updated_by => user) - - # Update order_articles. Save the current article_version to keep price consistency - # Also save results for each group_order_result - # Clean up - order_articles.each do |oa| - oa.group_order_articles.each do |goa| - goa.save_results! - end + return if finished? + + Order.transaction do + # set new order state (needed by notify_order_finished) + update_attributes!(state: 'finished', ends: Time.now, updated_by: user) + + # Update order_articles. Save the current article_version to keep price consistency + # Also save results for each group_order_result + # Clean up + order_articles.each do |oa| + oa.group_order_articles.each do |goa| + goa.save_results! end + end - # Update GroupOrder prices - group_orders.each(&:update_price!) + # Update GroupOrder prices + group_orders.each(&:update_price!) - # Stats - ordergroups.each(&:update_stats!) + # Stats + ordergroups.each(&:update_stats!) - # Notifications - NotifyFinishedOrderJob.perform_later(self) - end + # Notifications + NotifyFinishedOrderJob.perform_later(self) end end @@ -271,11 +278,11 @@ def close!(user, transaction_type = nil) if stockit? # Decreases the quantity of stock_articles for oa in order_articles.includes(article_version: :article) oa.update_results! # Update units_to_order of order_article - stock_changes.create! :stock_article => oa.article_version.article, :quantity => oa.units_to_order * -1 + stock_changes.create! stock_article: oa.article_version.article, quantity: oa.units_to_order * -1 end end - self.update_attributes! :state => 'closed', :updated_by => user, :foodcoop_result => profit + update_attributes! state: 'closed', updated_by: user, foodcoop_result: profit end end @@ -283,7 +290,10 @@ def close!(user, transaction_type = nil) 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] + unless FoodsoftConfig[:charge_members_manually] + comments.create(user: user, + text: I18n.t('orders.model.close_direct_message')) + end update_attributes! state: 'closed', updated_by: user end @@ -307,13 +317,12 @@ def do_end_action! end def self.finish_ended! - orders = Order.where.not(end_action: Order.end_actions[:no_end_action]).where(state: 'open').where('ends <= ?', DateTime.now) + orders = Order.where.not(end_action: Order.end_actions[:no_end_action]).where(state: 'open').where('ends <= ?', + DateTime.now) orders.each do |order| - begin - order.do_end_action! - rescue => error - ExceptionNotifier.notify_exception(error, data: { foodcoop: FoodsoftConfig.scope, order_id: order.id }) - end + order.do_end_action! + rescue StandardError => e + ExceptionNotifier.notify_exception(e, data: { foodcoop: FoodsoftConfig.scope, order_id: order.id }) end end @@ -323,7 +332,10 @@ 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) + return unless boxfill && starts && boxfill <= (starts - delta) + + errors.add(:boxfill, + I18n.t('orders.model.error_starts_before_boxfill')) end def include_articles @@ -334,10 +346,10 @@ def keep_ordered_articles chosen_order_articles = order_articles.joins(:article_version).where(article_versions: { article_id: article_ids }) to_be_removed = order_articles - chosen_order_articles to_be_removed_but_ordered = to_be_removed.select { |a| a.quantity > 0 || a.tolerance > 0 } - unless to_be_removed_but_ordered.empty? || ignore_warnings - errors.add(:articles, I18n.t(stockit? ? 'orders.model.warning_ordered_stock' : 'orders.model.warning_ordered')) - @erroneous_article_ids = to_be_removed_but_ordered.map { |oa| oa.article_version.article_id } - end + return if to_be_removed_but_ordered.empty? || ignore_warnings + + errors.add(:articles, I18n.t(stockit? ? 'orders.model.warning_ordered_stock' : 'orders.model.warning_ordered')) + @erroneous_article_ids = to_be_removed_but_ordered.map { |oa| oa.article_version.article_id } end def save_order_articles @@ -345,7 +357,7 @@ def save_order_articles articles_list = Article.find(article_ids) # create new order_articles articles = article_versions.map(&:article) - (articles_list - articles).each { |article| order_articles.create(:article_version => article.latest_article_version) } + (articles_list - articles).each { |article| order_articles.create(article_version: article.latest_article_version) } # delete old order_articles articles.reject { |article| articles_list.include?(article) }.each do |article| order_articles.detect { |order_article| order_article.article_version.article_id == article.id }.destroy @@ -358,17 +370,17 @@ def distribute_transport return unless group_orders.any? case transport_distribution.try(&:to_i) - when Order.transport_distributions[:ordergroup] then + when Order.transport_distributions[:ordergroup] amount = transport / group_orders.size group_orders.each do |go| go.transport = amount.ceil(2) end - when Order.transport_distributions[:price] then + when Order.transport_distributions[:price] amount = transport / group_orders.sum(:price) group_orders.each do |go| go.transport = (amount * go.price).ceil(2) end - when Order.transport_distributions[:articles] then + when Order.transport_distributions[:articles] amount = transport / group_orders.includes(:group_order_articles).sum(:result) group_orders.each do |go| go.transport = (amount * go.group_order_articles.sum(:result)).ceil(2) diff --git a/app/models/order_article.rb b/app/models/order_article.rb index c96a71cd..2c593c8f 100644 --- a/app/models/order_article.rb +++ b/app/models/order_article.rb @@ -6,27 +6,29 @@ class OrderArticle < ApplicationRecord belongs_to :order belongs_to :article_version - has_many :group_order_articles, :dependent => :destroy + has_many :group_order_articles, dependent: :destroy - validates_presence_of :order_id, :article_version_id + validates :order_id, :article_version_id, presence: true validate :article_version_and_price_exist - validates_uniqueness_of :article_version_id, scope: :order_id + validates :article_version_id, uniqueness: { scope: :order_id } - _ordered_sql = "order_articles.units_to_order > 0 OR order_articles.units_billed > 0 OR order_articles.units_received > 0" + _ordered_sql = 'order_articles.units_to_order > 0 OR order_articles.units_billed > 0 OR order_articles.units_received > 0' scope :ordered, -> { where(_ordered_sql) } - scope :ordered_or_member, -> { includes(:group_order_articles).where("#{_ordered_sql} OR order_articles.quantity > 0 OR group_order_articles.result > 0") } + scope :ordered_or_member, lambda { + includes(:group_order_articles).where("#{_ordered_sql} OR order_articles.quantity > 0 OR group_order_articles.result > 0") + } scope :belonging_to_open_order, -> { joins(:order).merge(Order.open) } scope :belonging_to_finished_order, -> { joins(:order).merge(Order.finished) } before_create :init_from_balancing after_destroy :update_ordergroup_prices - def self.ransackable_attributes(auth_object = nil) - %w(id order_id article_id quantity tolerance units_to_order) + def self.ransackable_attributes(_auth_object = nil) + %w[id order_id article_id quantity tolerance units_to_order] end - def self.ransackable_associations(auth_object = nil) - %w(order article) + def self.ransackable_associations(_auth_object = nil) + %w[order article] end # This method returns either the ArticleVersion or the Article @@ -47,7 +49,7 @@ def units # 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_group_order_price } + { quantity: quantity, price: quantity * price.fc_group_order_price } end # Update quantity/tolerance/units_to_order from group_order_articles @@ -82,9 +84,7 @@ def update_results! # 4 | 5 | 4 | 2 # def calculate_units_to_order(quantity, tolerance = 0) - if quantity > 0 && !price.minimum_order_quantity.nil? && quantity < price.minimum_order_quantity && quantity + tolerance >= price.minimum_order_quantity - return price.minimum_order_quantity - end + return price.minimum_order_quantity if quantity > 0 && !price.minimum_order_quantity.nil? && quantity < price.minimum_order_quantity && quantity + tolerance >= price.minimum_order_quantity unit_size = price.convert_quantity(1, price.supplier_order_unit, price.group_order_unit) if price.supplier_order_unit_is_si_convertible @@ -121,13 +121,14 @@ def redistribute(quantity, surplus = [:tolerance], update_totals = true) if surplus.index(:tolerance).nil? qty_for_members = [qty_left, self.quantity].min else - qty_for_members = [qty_left, self.quantity + self.tolerance].min + qty_for_members = [qty_left, self.quantity + tolerance].min counts[surplus.index(:tolerance)] = [0, qty_for_members - self.quantity].max end # Recompute group_order_articles.each do |goa| - group_order_total = article_version.convert_quantity(qty_for_members, article_version.supplier_order_unit, article_version.group_order_unit) + group_order_total = article_version.convert_quantity(qty_for_members, article_version.supplier_order_unit, + article_version.group_order_unit) goa.save_results!(group_order_total) end qty_left -= qty_for_members @@ -139,9 +140,7 @@ def redistribute(quantity, surplus = [:tolerance], update_totals = true) # 2) if not found, create new stock article # avoiding duplicate stock article names end - if qty_left > 0 && surplus.index(nil) - counts[surplus.index(nil)] = qty_left - end + counts[surplus.index(nil)] = qty_left if qty_left > 0 && surplus.index(nil) # Update GroupOrder prices & Ordergroup stats # TODO only affected group_orders, and once after redistributing all articles @@ -150,7 +149,7 @@ def redistribute(quantity, surplus = [:tolerance], update_totals = true) order.ordergroups.each(&:update_stats!) end - # TODO notifications + # TODO: notifications counts end @@ -159,12 +158,12 @@ def redistribute(quantity, surplus = [:tolerance], update_totals = true) def update_handling_versioning!(order_article_attributes, version_attributes) OrderArticle.transaction do # Updates self - self.update_attributes!(order_article_attributes) + update_attributes!(order_article_attributes) # Updates article_version belonging to current order article - original_article_version = self.article_version.duplicate_including_article_unit_ratios - self.article_version.assign_attributes(version_attributes) - if self.article_version.changed? + original_article_version = article_version.duplicate_including_article_unit_ratios + article_version.assign_attributes(version_attributes) + if article_version.changed? update_or_create_article_version(version_attributes, original_article_version) # Updates ordergroup values @@ -174,7 +173,7 @@ def update_handling_versioning!(order_article_attributes, version_attributes) end def update_global_price=(value) - @update_global_price = (value == true || value == '1') ? true : false + @update_global_price = [true, '1'].include?(value) ? true : false end # @return [Number] Units missing for the last +unit_quantity+ of the article. @@ -200,42 +199,45 @@ def difference_received_ordered private def article_version_and_price_exist - errors.add(:article_version, I18n.t('model.order_article.error_price')) if !(article_version = ArticleVersion.find(article_version_id)) || article_version.fc_price.nil? - rescue + if !(article_version = ArticleVersion.find(article_version_id)) || article_version.fc_price.nil? + errors.add(:article_version, + I18n.t('model.order_article.error_price')) + end + rescue StandardError errors.add(:article_version, I18n.t('model.order_article.error_price')) end # Associate with current article price if created in a finished order def init_from_balancing - if order.present? && order.finished? - self.article_version = article_version.article.article_versions.first - end + return unless order.present? && order.finished? + + self.article_version = article_version.article.article_versions.first end def update_or_create_article_version(version_attributes, original_article_version) version_attributes = version_attributes.merge(article_id: article_version.article_id) - modifying_earlier_version = self.article_version.article.latest_article_version.id != self.article_version_id - finished_order_article_using_same_version = OrderArticle.belonging_to_finished_order.where(article_version_id: self.article_version_id).where.not(id: self.id) + modifying_earlier_version = article_version.article.latest_article_version.id != article_version_id + finished_order_article_using_same_version = OrderArticle.belonging_to_finished_order.where(article_version_id: article_version_id).where.not(id: id) if (!update_global_price && modifying_earlier_version && !finished_order_article_using_same_version.exists?) || (update_global_price && !modifying_earlier_version) # update in place: - self.article_version.save + article_version.save else # create new version: - original_version_id = self.article_version.id - self.article_version = self.article_version.duplicate_including_article_unit_ratios - self.article_version.save - self.update_attribute(:article_version_id, self.article_version.id) + original_version_id = article_version.id + self.article_version = article_version.duplicate_including_article_unit_ratios + article_version.save + update_attribute(:article_version_id, article_version.id) if update_global_price # update open order articles: - OrderArticle.belonging_to_open_order.where(article_version_id: original_version_id).update_all(article_version_id: self.article_version.id) + OrderArticle.belonging_to_open_order.where(article_version_id: original_version_id).update_all(article_version_id: article_version.id) else # create yet *another* version, wich contains the old data, so new orders will continue using that data: # (The checkbox "Also update the price of future orders" not being checked implies that) - original_article_version.created_at = self.article_version.created_at + 1.second + original_article_version.created_at = article_version.created_at + 1.second original_article_version.save end end @@ -260,14 +262,13 @@ def enforce_boxfill unless (delta_q == 0 && delta_t >= 0) || (delta_mis < 0 && delta_box >= 0 && delta_t >= 0) || (delta_q > 0 && delta_q == -delta_t) - raise ActiveRecord::RecordNotSaved.new("Change not acceptable in boxfill phase for '#{article.name}', sorry.", self) + raise ActiveRecord::RecordNotSaved.new("Change not acceptable in boxfill phase for '#{article.name}', sorry.", + self) end end def _missing_units(unit_ratio, quantity, tolerance, minimum_order_quantity) - if !minimum_order_quantity.nil? && quantity > 0 && quantity + tolerance < minimum_order_quantity - return minimum_order_quantity - quantity - tolerance - end + return minimum_order_quantity - quantity - tolerance if !minimum_order_quantity.nil? && quantity > 0 && quantity + tolerance < minimum_order_quantity return 0 if article_version.supplier_order_unit_is_si_convertible diff --git a/app/models/order_comment.rb b/app/models/order_comment.rb index 5f35d98c..b11388b0 100644 --- a/app/models/order_comment.rb +++ b/app/models/order_comment.rb @@ -2,6 +2,6 @@ class OrderComment < ApplicationRecord belongs_to :order belongs_to :user - validates_presence_of :order_id, :user_id, :text - validates_length_of :text, :minimum => 3 + validates :order_id, :user_id, :text, presence: true + validates :text, length: { minimum: 3 } end diff --git a/app/models/ordergroup.rb b/app/models/ordergroup.rb index f699755b..88b01bd4 100644 --- a/app/models/ordergroup.rb +++ b/app/models/ordergroup.rb @@ -15,7 +15,7 @@ class Ordergroup < Group has_many :orders, through: :group_orders has_many :group_order_articles, through: :group_orders - validates_numericality_of :account_balance, :message => I18n.t('ordergroups.model.invalid_balance') + validates :account_balance, numericality: { message: I18n.t('ordergroups.model.invalid_balance') } validate :uniqueness_of_name, :uniqueness_of_members after_create :update_stats! @@ -27,7 +27,7 @@ def contact end def non_members - User.natural_order.all.reject { |u| (users.include?(u) || u.ordergroup) } + User.natural_order.all.reject { |u| users.include?(u) || u.ordergroup } end def self.include_transaction_class_sum @@ -51,9 +51,9 @@ def self.custom_fields def last_user_activity last_active_user = users.order('users.last_activity DESC').first - if last_active_user - last_active_user.last_activity - end + return unless last_active_user + + last_active_user.last_activity end # the most recent order this ordergroup was participating in @@ -86,12 +86,14 @@ def financial_transaction_class_balance(klass) # Throws an exception if it fails. def add_financial_transaction!(amount, note, user, transaction_type, link = nil, group_order = nil) transaction do - t = FinancialTransaction.new(ordergroup: self, amount: amount, note: note, user: user, financial_transaction_type: transaction_type, financial_link: link, group_order: group_order) + t = FinancialTransaction.new(ordergroup: self, amount: amount, note: note, user: user, + financial_transaction_type: transaction_type, financial_link: link, group_order: group_order) t.save! update_balance! # Notify only when order group had a positive balance before the last transaction: - if t.amount < 0 && self.account_balance < 0 && self.account_balance - t.amount >= 0 - NotifyNegativeBalanceJob.perform_later(self, t) + if t.amount < 0 && account_balance < 0 && account_balance - t.amount >= 0 + NotifyNegativeBalanceJob.perform_later(self, + t) end t end @@ -101,10 +103,11 @@ def update_stats! # Get hours for every job of each user in period jobs = users.to_a.sum { |u| u.tasks.done.where('updated_on > ?', APPLE_MONTH_AGO.month.ago).sum(:duration) } # Get group_order.price for every finished order in this period - orders_sum = group_orders.includes(:order).merge(Order.finished).where('orders.ends >= ?', APPLE_MONTH_AGO.month.ago).references(:orders).sum(:price) + 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! @@ -116,13 +119,17 @@ def update_balance! end def avg_jobs_per_euro - stats[:jobs_size].to_f / stats[:orders_sum].to_f rescue 0 + stats[:jobs_size].to_f / stats[:orders_sum].to_f + rescue StandardError + 0 end # 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 + ((avg_jobs_per_euro / Ordergroup.avg_jobs_per_euro) * 100).to_i + rescue StandardError + 0 end # If the the option stop_ordering_under is set, the ordergroup is only allowed to participate in an order, @@ -141,7 +148,11 @@ def not_enough_apples? # 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 + begin + stats.sum { |s| s[:jobs_size].to_f } / stats.sum { |s| s[:orders_sum].to_f } + rescue StandardError + 0 + end end def account_updated @@ -153,17 +164,20 @@ def account_updated # Make sure, that a user can only be in one ordergroup def uniqueness_of_members users.each do |user| - errors.add :user_tokens, I18n.t('ordergroups.model.error_single_group', :user => user.display) if user.groups.where(:type => 'Ordergroup').size > 1 + if user.groups.where(type: 'Ordergroup').size > 1 + errors.add :user_tokens, + I18n.t('ordergroups.model.error_single_group', user: user.display) + end end end # Make sure, the name is uniq, add usefull message if uniq group is already deleted def uniqueness_of_name group = Ordergroup.where(name: name) - group = group.where.not(id: self.id) unless new_record? - if group.exists? - message = group.first.deleted? ? :taken_with_deleted : :taken - errors.add :name, message - end + group = group.where.not(id: id) unless new_record? + return unless group.exists? + + message = group.first.deleted? ? :taken_with_deleted : :taken + errors.add :name, message end end diff --git a/app/models/periodic_task_group.rb b/app/models/periodic_task_group.rb index c0a2b10f..3415bce9 100644 --- a/app/models/periodic_task_group.rb +++ b/app/models/periodic_task_group.rb @@ -5,7 +5,7 @@ def has_next_task? return false if tasks.empty? return false if tasks.first.due_date.nil? - return true + true end def create_next_task @@ -18,15 +18,13 @@ def create_next_task next_task.save self.next_task_date += period_days - self.save + save end def create_tasks_until(create_until) - if has_next_task? - while next_task_date.nil? || next_task_date < create_until - create_next_task - end - end + return unless has_next_task? + + create_next_task while next_task_date.nil? || next_task_date < create_until end def create_tasks_for_upfront_days @@ -53,7 +51,7 @@ def update_tasks_including(template_task, prev_due_date) due_date: task.due_date + due_date_delta) end group_tasks.each do |task| - task.update_columns(periodic_task_group_id: self.id) + task.update_columns(periodic_task_group_id: id) end end diff --git a/app/models/stock_article.rb b/app/models/stock_article.rb index d26c3e30..30c5b079 100644 --- a/app/models/stock_article.rb +++ b/app/models/stock_article.rb @@ -10,11 +10,11 @@ class StockArticle < Article ransack_alias :quantity_available, :quantity # in-line with {StockArticleSerializer} def self.ransackable_attributes(auth_object = nil) - super(auth_object) - %w(supplier_id) + %w(quantity) + super(auth_object) - %w[supplier_id] + %w[quantity] end def self.ransackable_associations(auth_object = nil) - super(auth_object) - %w(supplier) + super(auth_object) - %w[supplier] end # Update the quantity of items in stock @@ -48,7 +48,7 @@ def mark_as_deleted protected def check_quantity - raise I18n.t('stockit.check.not_empty', :name => name) unless quantity == 0 + raise I18n.t('stockit.check.not_empty', name: name) unless quantity == 0 end # Overwrite Price history of Article. For StockArticles isn't it necessary. diff --git a/app/models/stock_change.rb b/app/models/stock_change.rb index 4cbd8939..03d92c74 100644 --- a/app/models/stock_change.rb +++ b/app/models/stock_change.rb @@ -4,11 +4,11 @@ class StockChange < ApplicationRecord belongs_to :stock_taking, optional: true, foreign_key: 'stock_event_id' belongs_to :stock_article - validates_presence_of :stock_article_id, :quantity - validates_numericality_of :quantity + validates :stock_article_id, :quantity, presence: true + validates :quantity, numericality: true - after_save :update_article_quantity after_destroy :update_article_quantity + after_save :update_article_quantity protected diff --git a/app/models/stock_event.rb b/app/models/stock_event.rb index 4fd82864..7134f7b0 100644 --- a/app/models/stock_event.rb +++ b/app/models/stock_event.rb @@ -2,5 +2,5 @@ class StockEvent < ApplicationRecord has_many :stock_changes, dependent: :destroy has_many :stock_articles, through: :stock_changes - validates_presence_of :date + validates :date, presence: true end diff --git a/app/models/supplier.rb b/app/models/supplier.rb index c920260a..f0c750fa 100644 --- a/app/models/supplier.rb +++ b/app/models/supplier.rb @@ -4,34 +4,38 @@ class Supplier < ApplicationRecord include MarkAsDeletedWithName include CustomFields - has_many :articles, -> { merge(Article.not_in_stock.with_latest_versions_and_categories.order('article_categories.name, article_versions.name')) } - has_many :stock_articles, -> { merge(StockArticle.with_latest_versions_and_categories.order('article_categories.name, article_versions.name')) } + has_many :articles, lambda { + merge(Article.not_in_stock.with_latest_versions_and_categories.order('article_categories.name, article_versions.name')) + } + has_many :stock_articles, lambda { + merge(StockArticle.with_latest_versions_and_categories.order('article_categories.name, article_versions.name')) + } has_many :orders has_many :deliveries has_many :invoices belongs_to :supplier_category - validates :name, :presence => true, :length => { :in => 4..30 } - validates :phone, :presence => true, :length => { :in => 8..25 } - validates :address, :presence => true, :length => { :in => 8..50 } - validates_format_of :iban, :with => /\A[A-Z]{2}[0-9]{2}[0-9A-Z]{,30}\z/, :allow_blank => true - validates_uniqueness_of :iban, :case_sensitive => false, :allow_blank => true - validates_length_of :order_howto, :note, maximum: 250 + validates :name, presence: true, length: { in: 4..30 } + validates :phone, presence: true, length: { in: 8..25 } + validates :address, presence: true, length: { in: 8..50 } + validates :iban, format: { with: /\A[A-Z]{2}[0-9]{2}[0-9A-Z]{,30}\z/, allow_blank: true } + validates :iban, uniqueness: { case_sensitive: false, allow_blank: true } + validates :order_howto, :note, length: { maximum: 250 } validate :uniqueness_of_name validates :shared_sync_method, presence: true, unless: -> { supplier_remote_source.blank? } validates :shared_sync_method, absence: true, if: -> { supplier_remote_source.blank? } - enum shared_sync_method: { :all_available => 'all_available', :all_unavailable => 'all_unavailable', :import => 'import' } + enum shared_sync_method: { all_available: 'all_available', all_unavailable: 'all_unavailable', import: 'import' } scope :undeleted, -> { where(deleted_at: nil) } scope :having_articles, -> { where(id: Article.undeleted.select(:supplier_id).distinct) } - def self.ransackable_attributes(auth_object = nil) - %w(id name) + def self.ransackable_attributes(_auth_object = nil) + %w[id name] end - def self.ransackable_associations(auth_object = nil) - %w(articles stock_articles orders) + def self.ransackable_associations(_auth_object = nil) + %w[articles stock_articles orders] end # sync all articles with the external database @@ -39,7 +43,9 @@ def self.ransackable_associations(auth_object = nil) # also returns an array with outlisted_articles, which should be deleted # also returns an array with new articles, which should be added (depending on shared_sync_method) def sync_all - updated_article_pairs, outlisted_articles, new_articles = [], [], [] + updated_article_pairs = [] + outlisted_articles = [] + new_articles = [] existing_articles = Set.new for article in articles.undeleted # try to find the associated shared_article @@ -48,23 +54,21 @@ def sync_all if shared_article # article will be updated existing_articles.add(shared_article.id) unequal_attributes = article.shared_article_changed?(self) - unless unequal_attributes.blank? # skip if shared_article has not been changed - if unequal_attributes.key?(:article_unit_ratios_attributes) - article.latest_article_version.article_unit_ratios.each(&:delete) - end + if unequal_attributes.present? # skip if shared_article has not been changed + article.latest_article_version.article_unit_ratios.each(&:delete) if unequal_attributes.key?(:article_unit_ratios_attributes) article.latest_article_version.reload article.latest_article_version.attributes = unequal_attributes updated_article_pairs << [article, unequal_attributes] end # Articles with no order number can be used to put non-shared articles # in a shared supplier, with sync keeping them. - elsif not article.order_number.blank? + elsif article.order_number.present? # article isn't in external database anymore outlisted_articles << article end end # Find any new articles, unless the import is manual - if ['all_available', 'all_unavailable'].include?(shared_sync_method) + if %w[all_available all_unavailable].include?(shared_sync_method) # build new articles shared_supplier .shared_articles @@ -72,10 +76,12 @@ def sync_all .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.latest_article_version.availability = false } + new_articles.each do |new_article| + new_article.latest_article_version.availability = false + end end end - return [updated_article_pairs, outlisted_articles, new_articles] + [updated_article_pairs, outlisted_articles, new_articles] end # Synchronise articles with spreadsheet. @@ -85,12 +91,12 @@ def sync_all # @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 = {}) - data = FoodsoftFile::parse(file, options) - self.parse_import_data({ articles: data }, options) + data = FoodsoftFile.parse(file, options) + parse_import_data({ articles: data }, options) end def read_from_remote(search_params = {}) - url = URI(self.supplier_remote_source) + url = URI(supplier_remote_source) url.query = URI.encode_www_form(search_params) unless search_params.nil? http = Net::HTTP.new(url.host, url.port) http.use_ssl = url.scheme == 'https' @@ -102,7 +108,7 @@ def read_from_remote(search_params = {}) def sync_from_remote(options = {}) data = read_from_remote(options[:search_params]) - self.parse_import_data(data, options) + parse_import_data(data, options) end def deleted? @@ -144,22 +150,26 @@ def shared_sync_method=(value) # Make sure, the name is uniq, add usefull message if uniq group is already deleted def uniqueness_of_name supplier = Supplier.where(name: name) - supplier = supplier.where.not(id: self.id) unless new_record? - if supplier.exists? - message = supplier.first.deleted? ? :taken_with_deleted : :taken - errors.add :name, message - end + supplier = supplier.where.not(id: id) unless new_record? + return unless supplier.exists? + + message = supplier.first.deleted? ? :taken_with_deleted : :taken + errors.add :name, message end def parse_import_data(data, options = {}) all_order_numbers = [] - updated_article_pairs, outlisted_articles, new_articles = [], [], [] + updated_article_pairs = [] + outlisted_articles = [] + new_articles = [] data[:articles].each do |new_attrs| article = articles.includes(:latest_article_version).undeleted.where(article_versions: { order_number: new_attrs[:order_number] }).first new_attrs[:article_category] = ArticleCategory.find_match(new_attrs[:article_category]) new_attrs[:tax] ||= FoodsoftConfig[:tax_default] - new_attrs[:article_unit_ratios] = new_attrs[:article_unit_ratios].map { |ratio_hash| ArticleUnitRatio.new(ratio_hash) } + new_attrs[:article_unit_ratios] = new_attrs[:article_unit_ratios].map do |ratio_hash| + ArticleUnitRatio.new(ratio_hash) + end new_article = articles.build new_article_version = new_article.article_versions.build(new_attrs) new_article.article_versions << new_article_version @@ -184,9 +194,7 @@ def parse_import_data(data, options = {}) end all_order_numbers << article.order_number if article end - if options[:outlist_absent] - outlisted_articles += articles.includes(:latest_article_version).undeleted.where.not(article_versions: { order_number: all_order_numbers + [nil] }) - end - return [updated_article_pairs, outlisted_articles, new_articles] + outlisted_articles += articles.includes(:latest_article_version).undeleted.where.not(article_versions: { order_number: all_order_numbers + [nil] }) if options[:outlist_absent] + [updated_article_pairs, outlisted_articles, new_articles] end end diff --git a/app/models/task.rb b/app/models/task.rb index cd748eb3..ead9eb24 100644 --- a/app/models/task.rb +++ b/app/models/task.rb @@ -1,9 +1,9 @@ class Task < ApplicationRecord - has_many :assignments, :dependent => :destroy - has_many :users, :through => :assignments + has_many :assignments, dependent: :destroy + has_many :users, through: :assignments belongs_to :workgroup, optional: true belongs_to :periodic_task_group, optional: true - belongs_to :created_by, :class_name => 'User', :foreign_key => 'created_by_user_id', optional: true + belongs_to :created_by, class_name: 'User', foreign_key: 'created_by_user_id', optional: true scope :non_group, -> { where(workgroup_id: nil, done: false) } scope :done, -> { where(done: true) } @@ -11,12 +11,12 @@ class Task < ApplicationRecord attr_accessor :current_user_id - validates :name, :presence => true, :length => { :minimum => 3 } - validates :required_users, :presence => true - validates_numericality_of :duration, :required_users, :only_integer => true, :greater_than => 0 - validates_length_of :description, maximum: 250 + validates :name, presence: true, length: { minimum: 3 } + validates :required_users, presence: true + validates :duration, :required_users, numericality: { only_integer: true, greater_than: 0 } + validates :description, length: { maximum: 250 } validates :done, exclusion: { in: [true] }, if: :periodic?, on: :create - validates_presence_of :due_date, if: :periodic? + validates :due_date, presence: { if: :periodic? } before_save :exclude_from_periodic_task_group, if: :changed?, unless: :new_record? after_save :update_ordergroup_stats @@ -35,7 +35,7 @@ def self.accepted_tasks_for(user) # 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]) + .where(['tasks.due_date >= ? AND tasks.due_date <= ?', Time.now, number.days.from_now]) end # count tasks with not enough responsible people @@ -49,7 +49,7 @@ def self.unassigned_tasks_for(user) def self.next_unassigned_tasks_for(user, max = 2) periodic_task_group_count = {} - self.unassigned_tasks_for(user).reject do |item| + unassigned_tasks_for(user).reject do |item| next false unless item.periodic_task_group count = periodic_task_group_count[item.periodic_task_group] || 0 @@ -59,19 +59,19 @@ def self.next_unassigned_tasks_for(user, max = 2) end def periodic? - not periodic_task_group.nil? + !periodic_task_group.nil? end def is_assigned?(user) - self.assignments.detect { |ass| ass.user_id == user.id } + assignments.detect { |ass| ass.user_id == user.id } end def is_accepted?(user) - self.assignments.detect { |ass| ass.user_id == user.id && ass.accepted } + assignments.detect { |ass| ass.user_id == user.id && ass.accepted } end def enough_users_assigned? - assignments.to_a.count(&:accepted) >= required_users ? true : false + assignments.to_a.count(&:accepted) >= required_users end def still_required_users @@ -82,35 +82,31 @@ def still_required_users # and makes the users responsible for the task # TODO: check for maximal number of users def user_list=(ids) - list = ids.split(",").map(&:to_i) + list = ids.split(',').map(&:to_i) new_users = (list - users.collect(&:id)).uniq old_users = users.reject { |user| list.include?(user.id) } self.class.transaction do # delete old assignments - if old_users.any? - assignments.where(user_id: old_users.map(&:id)).each(&:destroy) - end + assignments.where(user_id: old_users.map(&:id)).each(&:destroy) if old_users.any? # create new assignments new_users.each do |id| user = User.find(id) if user.blank? errors.add(:user_list) + elsif id == current_user_id.to_i + assignments.build user: user, accepted: true + # current_user will accept, when he puts himself to the list of users else - 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 - # normal assignement - self.assignments.build :user => user - end + # normal assignement + assignments.build user: user end end end end def user_list - @user_list ||= users.collect(&:id).join(", ") + @user_list ||= users.collect(&:id).join(', ') end def update_ordergroup_stats(user_ids = self.user_ids) diff --git a/app/models/user.rb b/app/models/user.rb index 82d80ed5..7dcba174 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -4,19 +4,19 @@ class User < ApplicationRecord include CustomFields # TODO: acts_as_paraniod ?? - has_many :memberships, :dependent => :destroy - has_many :groups, :through => :memberships + has_many :memberships, dependent: :destroy + has_many :groups, through: :memberships # 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: id }).first end - has_many :workgroups, :through => :memberships, :source => :group, :class_name => "Workgroup" - has_many :assignments, :dependent => :destroy - has_many :tasks, :through => :assignments - has_many :send_messages, :class_name => "Message", :foreign_key => "sender_id" - has_many :created_orders, :class_name => 'Order', :foreign_key => 'created_by_user_id', :dependent => :nullify - has_many :mail_delivery_status, :class_name => 'MailDeliveryStatus', :foreign_key => 'email', :primary_key => 'email' + has_many :workgroups, through: :memberships, source: :group, class_name: 'Workgroup' + has_many :assignments, dependent: :destroy + has_many :tasks, through: :assignments + has_many :send_messages, class_name: 'Message', foreign_key: 'sender_id' + has_many :created_orders, class_name: 'Order', foreign_key: 'created_by_user_id', dependent: :nullify + has_many :mail_delivery_status, class_name: 'MailDeliveryStatus', foreign_key: 'email', primary_key: 'email' attr_accessor :create_ordergroup, :password, :send_welcome_mail, :settings_attributes @@ -26,22 +26,22 @@ def ordergroup # makes the current_user (logged-in-user) available in models cattr_accessor :current_user - validates_presence_of :email - validates_presence_of :password, :on => :create - validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i - validates_uniqueness_of :email, :case_sensitive => false - validates_presence_of :first_name # for simple_form validations - validates_length_of :first_name, :in => 2..50 - validates_confirmation_of :password - validates_length_of :password, :in => 5..50, :allow_blank => true + validates :email, presence: true + validates :password, presence: { on: :create } + validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i } + validates :email, uniqueness: { case_sensitive: false } + validates :first_name, presence: true # for simple_form validations + validates :first_name, length: { in: 2..50 } + validates :password, confirmation: true + validates :password, length: { in: 5..50, allow_blank: true } # allow nick to be nil depending on foodcoop config # TODO Rails 4 may have a more beautiful way # http://stackoverflow.com/questions/19845910/conditional-allow-nil-part-of-validation - validates_length_of :nick, :in => 2..25, :allow_nil => true, :unless => Proc.new { FoodsoftConfig[:use_nick] } - validates_length_of :nick, :in => 2..25, :allow_nil => false, :if => Proc.new { FoodsoftConfig[:use_nick] } - validates_uniqueness_of :nick, :case_sensitive => false, :allow_nil => true # allow_nil in length validation - validates_format_of :iban, :with => /\A[A-Z]{2}[0-9]{2}[0-9A-Z]{,30}\z/, :allow_blank => true - validates_uniqueness_of :iban, :case_sensitive => false, :allow_blank => true + validates :nick, length: { in: 2..25, allow_nil: true, unless: proc { FoodsoftConfig[:use_nick] } } + validates :nick, length: { in: 2..25, allow_nil: false, if: proc { FoodsoftConfig[:use_nick] } } + validates :nick, uniqueness: { case_sensitive: false, allow_nil: true } # allow_nil in length validation + validates :iban, format: { with: /\A[A-Z]{2}[0-9]{2}[0-9A-Z]{,30}\z/, allow_blank: true } + validates :iban, uniqueness: { case_sensitive: false, allow_blank: true } before_validation :set_password after_initialize do @@ -58,17 +58,19 @@ def ordergroup end after_save do - settings_attributes.each do |key, value| - value.each do |k, v| - case v - when '1' - value[k] = true - when '0' - value[k] = false + if settings_attributes + settings_attributes.each do |key, value| + value.each do |k, v| + case v + when '1' + value[k] = true + when '0' + value[k] = false + end end + settings.merge!(key, value) end - self.settings.merge!(key, value) - end if settings_attributes + end if ActiveModel::Type::Boolean.new.cast(create_ordergroup) og = Ordergroup.new({ name: name }) @@ -103,7 +105,7 @@ def self.natural_search(q) match_name = q.split.map do |a| users[:first_name].matches("%#{a}%").or users[:last_name].matches("%#{a}%") end.reduce(:and) - User.where(match_nick.or match_name) + User.where(match_nick.or(match_name)) end def locale @@ -111,7 +113,7 @@ def locale end def name - [first_name, last_name].join(" ") + [first_name, last_name].join(' ') end def receive_email? @@ -120,22 +122,24 @@ def receive_email? # 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 - self.password_hash, self.password_salt = Digest::SHA1.hexdigest(password + salt), salt - end + return if password.blank? + + salt = [Array.new(6) { rand(256).chr }.join].pack('m').chomp + self.password_hash = Digest::SHA1.hexdigest(password + salt) + self.password_salt = salt end # Returns true if the password argument matches the user's password. def has_password(password) - Digest::SHA1.hexdigest(password + self.password_salt) == self.password_hash + Digest::SHA1.hexdigest(password + password_salt) == password_hash end # Returns a random password. def new_random_password(size = 6) - c = %w(b c d f g h j k l m n p qu r s t v w x z ch cr fr nd ng nk nt ph pr rd sh sl sp st th tr) - v = %w(a e i o u y) - f, r = true, '' + c = %w[b c d f g h j k l m n p qu r s t v w x z ch cr fr nd ng nk nt ph pr rd sh sl sp st th tr] + v = %w[a e i o u y] + f = true + r = '' (size * 2).times do r << (f ? c[rand * c.size] : v[rand * v.size]) f = !f @@ -198,12 +202,12 @@ def ordergroup_name # returns true if user is a member of a given group def member_of?(group) - group.users.exists?(self.id) + group.users.exists?(id) end # Returns an array with the users groups (but without the Ordergroups -> because tpye=>"") - def member_of_groups() - self.groups.where(type: '') + def member_of_groups + groups.where(type: '') end def deleted? @@ -220,11 +224,9 @@ def restore def self.authenticate(login, password) user = find_by_nick(login) || find_by_email(login) - if user && password && user.has_password(password) - user - else - nil - end + return unless user && password && user.has_password(password) + + user end def self.custom_fields @@ -248,6 +250,6 @@ def display 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 bf50c27b..271dec8d 100644 --- a/app/models/workgroup.rb +++ b/app/models/workgroup.rb @@ -3,26 +3,26 @@ class Workgroup < Group has_many :tasks # returns all non-finished tasks - has_many :open_tasks, -> { where(:done => false).order('due_date', 'name') }, :class_name => 'Task' + has_many :open_tasks, -> { where(done: false).order('due_date', 'name') }, class_name: 'Task' - validates_uniqueness_of :name - validate :last_admin_on_earth, :on => :update + validates :name, uniqueness: true + validate :last_admin_on_earth, on: :update before_destroy :check_last_admin_group protected # Check before destroy a group, if this is the last group with admin role def check_last_admin_group - if role_admin && Workgroup.where(role_admin: true).size == 1 - raise I18n.t('workgroups.error_last_admin_group') - end + return unless role_admin && Workgroup.where(role_admin: true).size == 1 + + raise I18n.t('workgroups.error_last_admin_group') end # add validation check on update # Return an error if this is the last group with admin role and role_admin should set to false def last_admin_on_earth - if !role_admin && !Workgroup.where(role_admin: true).where.not(id: id).exists? - errors.add(:role_admin, I18n.t('workgroups.error_last_admin_role')) - end + return unless !role_admin && !Workgroup.where(role_admin: true).where.not(id: id).exists? + + errors.add(:role_admin, I18n.t('workgroups.error_last_admin_role')) end end diff --git a/bin/autospec b/bin/autospec index 64dcb9cb..602d5c82 100755 --- a/bin/autospec +++ b/bin/autospec @@ -7,8 +7,8 @@ # require 'pathname' -ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", - Pathname.new(__FILE__).realpath) +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', + Pathname.new(__FILE__).realpath) require 'rubygems' require 'bundler/setup' diff --git a/bin/mailcatcher b/bin/mailcatcher index a4b2c248..67d7b036 100755 --- a/bin/mailcatcher +++ b/bin/mailcatcher @@ -7,8 +7,8 @@ # require 'pathname' -ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", - Pathname.new(__FILE__).realpath) +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', + Pathname.new(__FILE__).realpath) require 'rubygems' require 'bundler/setup' diff --git a/bin/resque b/bin/resque index 2e40831b..f018141c 100755 --- a/bin/resque +++ b/bin/resque @@ -7,8 +7,8 @@ # require 'pathname' -ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", - Pathname.new(__FILE__).realpath) +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', + Pathname.new(__FILE__).realpath) require 'rubygems' require 'bundler/setup' diff --git a/bin/resque-web b/bin/resque-web index b49543cd..22ad07e0 100755 --- a/bin/resque-web +++ b/bin/resque-web @@ -7,8 +7,8 @@ # require 'pathname' -ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", - Pathname.new(__FILE__).realpath) +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', + Pathname.new(__FILE__).realpath) require 'rubygems' require 'bundler/setup' diff --git a/bin/rspec b/bin/rspec index 0c86b5c6..8bc84617 100755 --- a/bin/rspec +++ b/bin/rspec @@ -7,8 +7,8 @@ # require 'pathname' -ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", - Pathname.new(__FILE__).realpath) +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', + Pathname.new(__FILE__).realpath) require 'rubygems' require 'bundler/setup' diff --git a/bin/yarn b/bin/yarn index 460dd565..d3627c34 100755 --- a/bin/yarn +++ b/bin/yarn @@ -1,11 +1,9 @@ #!/usr/bin/env ruby APP_ROOT = File.expand_path('..', __dir__) Dir.chdir(APP_ROOT) do - begin - exec "yarnpkg", *ARGV - rescue Errno::ENOENT - $stderr.puts "Yarn executable was not detected in the system." - $stderr.puts "Download Yarn at https://yarnpkg.com/en/docs/install" - exit 1 - end + exec 'yarnpkg', *ARGV +rescue Errno::ENOENT + warn 'Yarn executable was not detected in the system.' + warn 'Download Yarn at https://yarnpkg.com/en/docs/install' + exit 1 end diff --git a/config.ru b/config.ru index e0faca0f..7417cc9a 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', __dir__) # https://gist.github.com/ebeigarts/5450422 map ENV['RAILS_RELATIVE_URL_ROOT'] || '/' do diff --git a/config/application.rb b/config/application.rb index 38c9a6d4..02048377 100644 --- a/config/application.rb +++ b/config/application.rb @@ -28,13 +28,15 @@ class Application < Rails::Application # config.time_zone = 'Central Time (US & Canada)' # 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.load_path += Dir[Rails.root.join('config/locales/*.yml')] + config.i18n.available_locales = Pathname.glob(Rails.root.join('config/locales/{??,???}{-*,}.yml')).map do |p| + p.basename('.yml').to_s + end config.i18n.default_locale = :en config.i18n.fallbacks = [:en] # Configure the default encoding used in templates for Ruby 1.9. - config.encoding = "utf-8" + config.encoding = 'utf-8' # Enable escaping HTML in JSON. config.active_support.escape_html_entities_in_json = true @@ -44,7 +46,7 @@ class Application < Rails::Application # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql - # TODO Disable this. Uncommenting this line will currently cause rspec to fail. + # TODO: Disable this. Uncommenting this line will currently cause rspec to fail. config.action_controller.permit_all_parameters = true config.active_job.queue_adapter = :resque @@ -76,5 +78,9 @@ class Application < Rails::Application # Foodsoft version VERSION = File.read(Rails.root.join('VERSION')).strip # Current revision, or +nil+ - REVISION = (File.read(Rails.root.join('REVISION')).strip rescue nil) + REVISION = begin + File.read(Rails.root.join('REVISION')).strip + rescue StandardError + nil + end end diff --git a/config/environments/production.rb b/config/environments/production.rb index 0560b38d..12571fda 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -49,7 +49,7 @@ # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. - config.force_ssl = ENV["RAILS_FORCE_SSL"] != "false" + config.force_ssl = ENV['RAILS_FORCE_SSL'] != 'false' # Set to :debug to see everything in the log. config.log_level = :info @@ -89,22 +89,31 @@ config.action_mailer.smtp_settings[:domain] = ENV['SMTP_DOMAIN'] if ENV['SMTP_DOMAIN'].present? config.action_mailer.smtp_settings[:user_name] = ENV['SMTP_USER_NAME'] if ENV['SMTP_USER_NAME'].present? config.action_mailer.smtp_settings[:password] = ENV['SMTP_PASSWORD'] if ENV['SMTP_PASSWORD'].present? - config.action_mailer.smtp_settings[:authentication] = ENV['SMTP_AUTHENTICATION'] if ENV['SMTP_AUTHENTICATION'].present? - config.action_mailer.smtp_settings[:enable_starttls_auto] = ENV['SMTP_ENABLE_STARTTLS_AUTO'] == 'true' if ENV['SMTP_ENABLE_STARTTLS_AUTO'].present? - config.action_mailer.smtp_settings[:openssl_verify_mode] = ENV['SMTP_OPENSSL_VERIFY_MODE'] if ENV['SMTP_OPENSSL_VERIFY_MODE'].present? + if ENV['SMTP_AUTHENTICATION'].present? + config.action_mailer.smtp_settings[:authentication] = + ENV['SMTP_AUTHENTICATION'] + end + if ENV['SMTP_ENABLE_STARTTLS_AUTO'].present? + config.action_mailer.smtp_settings[:enable_starttls_auto] = + ENV['SMTP_ENABLE_STARTTLS_AUTO'] == 'true' + end + if ENV['SMTP_OPENSSL_VERIFY_MODE'].present? + config.action_mailer.smtp_settings[:openssl_verify_mode] = + ENV['SMTP_OPENSSL_VERIFY_MODE'] + end else # Use sendmail as default to avoid ssl cert problems config.action_mailer.delivery_method = :sendmail end # Use default logging formatter so that PID and timestamp are not suppressed. - config.log_formatter = ::Logger::Formatter.new + config.log_formatter = Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') - if ENV["RAILS_LOG_TO_STDOUT"].present? + if ENV['RAILS_LOG_TO_STDOUT'].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) diff --git a/config/initializers/currency_display.rb b/config/initializers/currency_display.rb index 7caa6a64..24ceeb8b 100644 --- a/config/initializers/currency_display.rb +++ b/config/initializers/currency_display.rb @@ -1,7 +1,8 @@ # remove all currency translations, so that we can set the default language and # 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.available_locales.each do |locale| + unless locale == I18n.default_locale + I18n.backend.store_translations(locale, + number: { currency: { format: { unit: nil } } }) end end diff --git a/config/initializers/doorkeeper.rb b/config/initializers/doorkeeper.rb index 958b9e9a..64541987 100644 --- a/config/initializers/doorkeeper.rb +++ b/config/initializers/doorkeeper.rb @@ -98,7 +98,7 @@ # http://tools.ietf.org/html/rfc6819#section-4.4.2 # http://tools.ietf.org/html/rfc6819#section-4.4.3 # - grant_flows %w(authorization_code implicit password) + grant_flows %w[authorization_code implicit password] # Under some circumstances you might want to have applications auto-approved, # so that the user skips the authorization step. @@ -114,7 +114,7 @@ # my take on https://github.com/doorkeeper-gem/doorkeeper/issues/465 ActiveSupport.on_load(:after_initialize) do - Doorkeeper::ApplicationController.send :include, Concerns::Locale - Doorkeeper::ApplicationController.send :include, Concerns::FoodcoopScope - Doorkeeper::ApplicationController.send :include, Concerns::Auth + Doorkeeper::ApplicationController.include Concerns::Locale + Doorkeeper::ApplicationController.include Concerns::FoodcoopScope + Doorkeeper::ApplicationController.include Concerns::Auth end diff --git a/config/initializers/exception_notification.rb b/config/initializers/exception_notification.rb index 10107865..3d342465 100644 --- a/config/initializers/exception_notification.rb +++ b/config/initializers/exception_notification.rb @@ -14,7 +14,7 @@ # Adds a condition to decide when an exception must be ignored or not. # The ignore_if method can be invoked multiple times to add extra conditions. - config.ignore_if do |exception, options| + config.ignore_if do |_exception, _options| Rails.env.development? || Rails.env.test? end @@ -23,9 +23,9 @@ # Email notifier sends notifications by email. if notification = FoodsoftConfig[:notification] config.add_notifier :email, { - :email_prefix => notification[:email_prefix], - :sender_address => notification[:sender_address], - :exception_recipients => notification[:error_recipients], + email_prefix: notification[:email_prefix], + sender_address: notification[:sender_address], + exception_recipients: notification[:error_recipients] } end diff --git a/config/initializers/extensions.rb b/config/initializers/extensions.rb index 799f52e6..d276aecb 100644 --- a/config/initializers/extensions.rb +++ b/config/initializers/extensions.rb @@ -2,8 +2,8 @@ class String # remove comma from decimal inputs def self.delocalized_decimal(string) - if !string.blank? and string.is_a?(String) - BigDecimal.new(string.sub(',', '.')) + if string.present? and string.is_a?(String) + BigDecimal(string.sub(',', '.')) else string end @@ -13,6 +13,6 @@ def self.delocalized_decimal(string) class Array def cumulative_sum csum = 0 - self.map { |val| csum += val } + map { |val| csum += val } end end diff --git a/config/initializers/rack.rb b/config/initializers/rack.rb index 30970ec9..aa462561 100644 --- a/config/initializers/rack.rb +++ b/config/initializers/rack.rb @@ -1,3 +1,3 @@ # Increase key space for post request. # Warning, this is dangerous. See http://stackoverflow.com/questions/12243694/getting-error-exceeded-available-parameter-key-space -Rack::Utils.key_space_limit = 262144 +Rack::Utils.key_space_limit = 262_144 diff --git a/config/initializers/rails6_backports.rb b/config/initializers/rails6_backports.rb index b72f4220..d56f8eee 100644 --- a/config/initializers/rails6_backports.rb +++ b/config/initializers/rails6_backports.rb @@ -1,6 +1,6 @@ raise "Remove no-longer-needed #{__FILE__}!" if Rails::VERSION::MAJOR >= 6 -require "weakref" +require 'weakref' module ActiveRecord # Backport https://github.com/rails/rails/pull/36998 and https://github.com/rails/rails/pull/36999 @@ -15,9 +15,7 @@ class Reaper class << self def register_pool(pool, frequency) # :nodoc: @mutex.synchronize do - unless @threads[frequency]&.alive? - @threads[frequency] = spawn_thread(frequency) - end + @threads[frequency] = spawn_thread(frequency) unless @threads[frequency]&.alive? @pools[frequency] ||= [] @pools[frequency] << WeakRef.new(pool) end diff --git a/config/initializers/ruby_units.rb b/config/initializers/ruby_units.rb index b8b56cca..af422fcb 100644 --- a/config/initializers/ruby_units.rb +++ b/config/initializers/ruby_units.rb @@ -2,28 +2,28 @@ if defined? RubyUnits RubyUnits::Unit.redefine!('liter') do |unit| - unit.aliases += %w{ltr} + unit.aliases += %w[ltr] end RubyUnits::Unit.redefine!('kilogram') do |unit| - unit.aliases += %w{KG} + unit.aliases += %w[KG] end RubyUnits::Unit.redefine!('gram') do |unit| - unit.aliases += %w{gr} + unit.aliases += %w[gr] end RubyUnits::Unit.define('piece') do |unit| unit.definition = RubyUnits::Unit.new('1 each') - unit.aliases = %w{pc pcs piece pieces} # locale: en - unit.aliases += %w{st stuk stuks} # locale: nl + unit.aliases = %w[pc pcs piece pieces] # locale: en + unit.aliases += %w[st stuk stuks] # locale: nl unit.kind = :counting end RubyUnits::Unit.define('bag') do |unit| unit.definition = RubyUnits::Unit.new('1 each') - unit.aliases = %w{bag bags blt sachet sachets} # locale: en - unit.aliases += %w{zak zakken zakje zakjes} # locale: nl + unit.aliases = %w[bag bags blt sachet sachets] # locale: en + unit.aliases += %w[zak zakken zakje zakjes] # locale: nl unit.kind = :counting end diff --git a/config/initializers/secret_token.rb b/config/initializers/secret_token.rb index 14054341..142c4849 100644 --- a/config/initializers/secret_token.rb +++ b/config/initializers/secret_token.rb @@ -5,20 +5,20 @@ # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. Foodsoft::Application.config.secret_key_base = begin - if (token = ENV['SECRET_KEY_BASE']).present? + if (token = ENV.fetch('SECRET_KEY_BASE', nil)).present? token elsif Rails.env.production? || Rails.env.staging? - raise "You must set SECRET_KEY_BASE" + raise 'You must set SECRET_KEY_BASE' elsif Rails.env.test? SecureRandom.hex(30) # doesn't really matter else - sf = Rails.root.join('tmp', 'secret_key_base') - if File.exists?(sf) + sf = Rails.root.join('tmp/secret_key_base') + if File.exist?(sf) File.read(sf) else puts "=> Generating initial SECRET_KEY_BASE in #{sf}" token = SecureRandom.hex(30) - File.open(sf, 'w') { |f| f.write(token) } + File.write(sf, token) token end end diff --git a/config/initializers/session_store.rb b/config/initializers/session_store.rb index d7841180..370a202e 100644 --- a/config/initializers/session_store.rb +++ b/config/initializers/session_store.rb @@ -3,7 +3,7 @@ module ActionDispatch module Session class SlugCookieStore < CookieStore - alias_method :orig_set_cookie, :set_cookie + alias orig_set_cookie set_cookie def set_cookie(request, session_id, cookie) if script_name = FoodsoftConfig[:script_name] diff --git a/config/initializers/simple_form_bootstrap.rb b/config/initializers/simple_form_bootstrap.rb index a95278d0..1292ac83 100644 --- a/config/initializers/simple_form_bootstrap.rb +++ b/config/initializers/simple_form_bootstrap.rb @@ -11,7 +11,7 @@ end end - config.wrappers :prepend, tag: 'div', class: "control-group", error_class: 'error' do |b| + config.wrappers :prepend, tag: 'div', class: 'control-group', error_class: 'error' do |b| b.use :html5 b.use :placeholder b.use :label @@ -24,7 +24,7 @@ end end - config.wrappers :append, tag: 'div', class: "control-group", error_class: 'error' do |b| + config.wrappers :append, tag: 'div', class: 'control-group', error_class: 'error' do |b| b.use :html5 b.use :placeholder b.use :label diff --git a/config/navigation.rb b/config/navigation.rb index a2018105..c671c18c 100644 --- a/config/navigation.rb +++ b/config/navigation.rb @@ -21,32 +21,43 @@ primary.item :orders, I18n.t('navigation.orders.title'), '#' do |subnav| subnav.item :ordering, I18n.t('navigation.orders.ordering'), group_orders_path subnav.item :ordering_archive, I18n.t('navigation.orders.archive'), archive_group_orders_path - subnav.item :orders, I18n.t('navigation.orders.manage'), orders_path, if: Proc.new { current_user.role_orders? } - subnav.item :pickups, I18n.t('navigation.orders.pickups'), pickups_path, if: Proc.new { current_user.role_pickups? } + subnav.item :orders, I18n.t('navigation.orders.manage'), orders_path, if: proc { current_user.role_orders? } + subnav.item :pickups, I18n.t('navigation.orders.pickups'), pickups_path, if: proc { current_user.role_pickups? } end primary.item :articles, I18n.t('navigation.articles.title'), '#', - if: Proc.new { current_user.role_article_meta? or current_user.role_suppliers? } do |subnav| + if: proc { current_user.role_article_meta? or current_user.role_suppliers? } do |subnav| subnav.item :suppliers, I18n.t('navigation.articles.suppliers'), suppliers_path subnav.item :stockit, I18n.t('navigation.articles.stock'), stock_articles_path subnav.item :categories, I18n.t('navigation.articles.categories'), article_categories_path subnav.item :article_units, I18n.t('navigation.articles.article_units'), article_units_path end - primary.item :finance, I18n.t('navigation.finances.title'), '#', if: Proc.new { current_user.role_finance? || current_user.role_invoices? } do |subnav| - subnav.item :finance_home, I18n.t('navigation.finances.home'), finance_root_path, if: Proc.new { current_user.role_finance? } - subnav.item :finance_home, I18n.t('navigation.finances.bank_accounts'), finance_bank_accounts_path, if: Proc.new { current_user.role_finance? } - subnav.item :accounts, I18n.t('navigation.finances.accounts'), finance_ordergroups_path, if: Proc.new { current_user.role_finance? } - subnav.item :balancing, I18n.t('navigation.finances.balancing'), finance_order_index_path, if: Proc.new { current_user.role_finance? } + primary.item :finance, I18n.t('navigation.finances.title'), '#', if: proc { + current_user.role_finance? || current_user.role_invoices? + } do |subnav| + subnav.item :finance_home, I18n.t('navigation.finances.home'), finance_root_path, if: proc { + current_user.role_finance? + } + subnav.item :finance_home, I18n.t('navigation.finances.bank_accounts'), finance_bank_accounts_path, if: proc { + current_user.role_finance? + } + subnav.item :accounts, I18n.t('navigation.finances.accounts'), finance_ordergroups_path, if: proc { + current_user.role_finance? + } + subnav.item :balancing, I18n.t('navigation.finances.balancing'), finance_order_index_path, if: proc { + current_user.role_finance? + } subnav.item :invoices, I18n.t('navigation.finances.invoices'), finance_invoices_path end - primary.item :admin, I18n.t('navigation.admin.title'), '#', if: Proc.new { current_user.role_admin? } do |subnav| + primary.item :admin, I18n.t('navigation.admin.title'), '#', if: proc { current_user.role_admin? } do |subnav| subnav.item :admin_home, I18n.t('navigation.admin.home'), admin_root_path subnav.item :users, I18n.t('navigation.admin.users'), admin_users_path subnav.item :ordergroups, I18n.t('navigation.admin.ordergroups'), admin_ordergroups_path subnav.item :workgroups, I18n.t('navigation.admin.workgroups'), admin_workgroups_path - subnav.item :mail_delivery_status, I18n.t('navigation.admin.mail_delivery_status'), admin_mail_delivery_status_index_path + subnav.item :mail_delivery_status, I18n.t('navigation.admin.mail_delivery_status'), + admin_mail_delivery_status_index_path subnav.item :finances, I18n.t('navigation.admin.finance'), admin_finances_path subnav.item :config, I18n.t('navigation.admin.config'), admin_config_path end diff --git a/config/puma.rb b/config/puma.rb index 6f77f346..a7a3c1d3 100644 --- a/config/puma.rb +++ b/config/puma.rb @@ -4,16 +4,16 @@ # the maximum value specified for Puma. Default is set to 5 threads for minimum # and maximum; this matches the default thread size of Active Record. # -threads_count = ENV.fetch("RAILS_MAX_THREADS") { 1 } +threads_count = ENV.fetch('RAILS_MAX_THREADS') { 1 } threads threads_count, threads_count # Specifies the `port` that Puma will listen on to receive requests; default is 3000. # -port ENV.fetch("PORT") { 3000 } +port ENV.fetch('PORT') { 3000 } # Specifies the `environment` that Puma will run in. # -environment ENV.fetch("RAILS_ENV") { "development" } +environment ENV.fetch('RAILS_ENV') { 'development' } # Specifies the number of `workers` to boot in clustered mode. # Workers are forked webserver processes. If using threads and workers together @@ -21,7 +21,7 @@ # Workers do not work on JRuby or Windows (both of which do not support # processes). # -workers ENV.fetch("WEB_CONCURRENCY") { 8 } +workers ENV.fetch('WEB_CONCURRENCY') { 8 } # Use the `preload_app!` method when specifying a `workers` number. # This directive tells Puma to first boot the application and load code @@ -55,6 +55,6 @@ plugin :tmp_restart if ENV.fetch('RAILS_ENV') == 'development' - Rails.logger.info "development => worker_timeout 3600" + Rails.logger.info 'development => worker_timeout 3600' worker_timeout 3600 end diff --git a/config/routes.rb b/config/routes.rb index 8f3cd852..4f54918b 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,9 +1,9 @@ Rails.application.routes.draw do - get "order_comments/new" + get 'order_comments/new' - get "comments/new" + get 'comments/new' - get "sessions/new" + get 'sessions/new' root to: 'sessions#redirect_to_foodcoop', as: nil @@ -21,8 +21,8 @@ post '/login/reset_password' => 'login#reset_password', as: :reset_password get '/login/new_password' => 'login#new_password', as: :new_password patch '/login/update_password' => 'login#update_password', as: :update_password - match '/login/accept_invitation/:token' => 'login#accept_invitation', as: :accept_invitation, via: [:get, :post] - resources :sessions, only: [:new, :create, :destroy] + match '/login/accept_invitation/:token' => 'login#accept_invitation', as: :accept_invitation, via: %i[get post] + resources :sessions, only: %i[new create destroy] get '/foodcoop.css' => 'styles#foodcoop', as: 'foodcoop_css' @@ -62,11 +62,11 @@ resources :group_order_articles - resources :order_comments, only: [:new, :create] + resources :order_comments, only: %i[new create] ############ Foodcoop orga - resources :invites, only: [:new, :create] + resources :invites, only: %i[new create] resources :tasks do collection do @@ -88,7 +88,7 @@ resources :ordergroups, only: [:index] - resources :workgroups, only: [:index, :edit, :update] + resources :workgroups, only: %i[index edit update] end ########### Article management @@ -119,7 +119,7 @@ resources :suppliers do get :remote_articles - resource :share, only: [:create, :destroy], controller: :supplier_shares + resource :share, only: %i[create destroy], controller: :supplier_shares resources :deliveries do collection do @@ -180,7 +180,7 @@ get :unpaid, on: :collection end - resources :links, controller: 'financial_links', only: [:create, :show] do + resources :links, controller: 'financial_links', only: %i[create show] do collection do get :incomplete end @@ -190,8 +190,10 @@ delete 'bank_transactions/:bank_transaction', action: 'remove_bank_transaction', as: 'remove_bank_transaction' get :index_financial_transaction - put 'financial_transactions/:financial_transaction', action: 'add_financial_transaction', as: 'add_financial_transaction' - delete 'financial_transactions/:financial_transaction', action: 'remove_financial_transaction', as: 'remove_financial_transaction' + put 'financial_transactions/:financial_transaction', action: 'add_financial_transaction', + as: 'add_financial_transaction' + delete 'financial_transactions/:financial_transaction', action: 'remove_financial_transaction', + as: 'remove_financial_transaction' get :index_invoice put 'invoices/:invoice', action: 'add_invoice', as: 'add_invoice' @@ -205,12 +207,14 @@ resources :ordergroups, only: [:index] do resources :financial_transactions, as: :transactions end - resources :financial_transactions, as: :foodcoop_financial_transactions, path: 'foodcoop/financial_transactions', only: [:index, :new, :create] + resources :financial_transactions, as: :foodcoop_financial_transactions, path: 'foodcoop/financial_transactions', + only: %i[index new create] get :transactions, controller: :financial_transactions, action: :index_collection delete 'transactions/:id', controller: :financial_transactions, action: :destroy, as: :transaction get 'transactions/new_collection' => 'financial_transactions#new_collection', as: 'new_transaction_collection' - post 'transactions/create_collection' => 'financial_transactions#create_collection', as: 'create_transaction_collection' + post 'transactions/create_collection' => 'financial_transactions#create_collection', + as: 'create_transaction_collection' resources :bank_accounts, only: [:index] do member do @@ -222,7 +226,7 @@ resources :bank_transactions, as: :transactions end - resources :bank_transactions, only: [:index, :show] + resources :bank_transactions, only: %i[index show] end ########### Administration @@ -254,11 +258,11 @@ get :memberships, on: :member end - resources :mail_delivery_status, only: [:index, :show, :destroy] do + resources :mail_delivery_status, only: %i[index show destroy] do delete :index, on: :collection, action: :destroy_all end - resource :config, only: [:show, :update] do + resource :config, only: %i[show update] do get :list end end @@ -273,17 +277,17 @@ namespace :user do root to: 'users#show' get :financial_overview, to: 'ordergroup#financial_overview' - resources :financial_transactions, only: [:index, :show, :create] + resources :financial_transactions, only: %i[index show create] resources :group_order_articles end - resources :financial_transaction_classes, only: [:index, :show] - resources :financial_transaction_types, only: [:index, :show] - resources :financial_transactions, only: [:index, :show] - resources :orders, only: [:index, :show] - resources :order_articles, only: [:index, :show] + resources :financial_transaction_classes, only: %i[index show] + resources :financial_transaction_types, only: %i[index show] + resources :financial_transactions, only: %i[index show] + resources :orders, only: %i[index show] + resources :order_articles, only: %i[index show] resources :group_order_articles - resources :article_categories, only: [:index, :show] + resources :article_categories, only: %i[index show] resources :shared_suppliers, param: :uuid, only: [] do resources :articles, only: [:index] @@ -293,7 +297,7 @@ ############## Feedback - resource :feedback, only: [:new, :create], controller: 'feedback' + resource :feedback, only: %i[new create], controller: 'feedback' ############## The rest diff --git a/config/schedule.rb b/config/schedule.rb index f22c1348..72e3cbcc 100644 --- a/config/schedule.rb +++ b/config/schedule.rb @@ -2,22 +2,22 @@ # Learn more: http://github.com/javan/whenever # Upcoming tasks notifier -every :day, :at => '7:20 am' do - rake "multicoops:run TASK=foodsoft:notify_upcoming_tasks" - rake "multicoops:run TASK=foodsoft:notify_users_of_weekly_task" +every :day, at: '7:20 am' do + rake 'multicoops:run TASK=foodsoft:notify_upcoming_tasks' + rake 'multicoops:run TASK=foodsoft:notify_users_of_weekly_task' end # Import and assign bank transactions -every :weekday, :at => %w(5:56am 6:04pm) do - rake "multicoops:run TASK=foodsoft:import_and_assign_bank_transactions" +every :weekday, at: %w[5:56am 6:04pm] do + rake 'multicoops:run TASK=foodsoft:import_and_assign_bank_transactions' end # Weekly taks -every :sunday, :at => '7:14 am' do - rake "multicoops:run TASK=foodsoft:create_upcoming_periodic_tasks" +every :sunday, at: '7:14 am' do + rake 'multicoops:run TASK=foodsoft:create_upcoming_periodic_tasks' end # Finish ended orders every 1.minute do - rake "multicoops:run TASK=foodsoft:finish_ended_orders" + rake 'multicoops:run TASK=foodsoft:finish_ended_orders' end diff --git a/config/spring.rb b/config/spring.rb index c9119b40..9fa7863f 100644 --- a/config/spring.rb +++ b/config/spring.rb @@ -1,6 +1,6 @@ -%w( +%w[ .ruby-version .rbenv-vars tmp/restart.txt tmp/caching-dev.txt -).each { |path| Spring.watch(path) } +].each { |path| Spring.watch(path) } diff --git a/db/migrate/001_create_users.rb b/db/migrate/001_create_users.rb index ab4a560a..3bdd0952 100644 --- a/db/migrate/001_create_users.rb +++ b/db/migrate/001_create_users.rb @@ -4,30 +4,30 @@ class CreateUsers < ActiveRecord::Migration[4.2] def self.up create_table :users do |t| - t.column :nick, :string, :null => false - t.column :password_hash, :string, :null => false - t.column :password_salt, :string, :null => false - t.column :first_name, :string, :null => false - t.column :last_name, :string, :null => false - t.column :email, :string, :null => false + t.column :nick, :string, null: false + t.column :password_hash, :string, null: false + t.column :password_salt, :string, null: false + t.column :first_name, :string, null: false + t.column :last_name, :string, null: false + t.column :email, :string, null: false t.column :phone, :string t.column :address, :string - t.column :created_on, :timestamp, :null => false + t.column :created_on, :timestamp, null: false end - add_index(:users, :nick, :unique => true) - add_index(:users, :email, :unique => true) + 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") + 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") - user.password = "foobar" - raise "Failed!" unless user.save && User.find_by_nick(USER_TEST).has_password("foobar") + user = User.new(nick: USER_TEST, first_name: 'Tim', last_name: 'Tester', email: 'test@foo.test') + user.password = 'foobar' + raise 'Failed!' unless user.save && User.find_by_nick(USER_TEST).has_password('foobar') end def self.down diff --git a/db/migrate/002_create_groups.rb b/db/migrate/002_create_groups.rb index bb7427b9..cffa19cc 100644 --- a/db/migrate/002_create_groups.rb +++ b/db/migrate/002_create_groups.rb @@ -4,47 +4,48 @@ class CreateGroups < ActiveRecord::Migration[4.2] 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 :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_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 + t.column :created_on, :timestamp, null: false + t.column :role_admin, :boolean, default: false, null: false end - add_index(:groups, :name, :unique => true) + 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 + t.column :group_id, :integer, null: false + t.column :user_id, :integer, null: false end - add_index(:memberships, [:user_id, :group_id], :unique => true) + add_index(:memberships, %i[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) + 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) + 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 + 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 + 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 2b38c9c1..72e148b8 100644 --- a/db/migrate/003_create_suppliers.rb +++ b/db/migrate/003_create_suppliers.rb @@ -2,17 +2,17 @@ class CreateSuppliers < ActiveRecord::Migration[4.2] SUPPLIER_SAMPLE = 'Sample Supplier' def self.up - add_column :groups, :role_suppliers, :boolean, :default => false, :null => false + 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? + 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 @@ def self.up 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) + Supplier.create(name: SUPPLIER_SAMPLE, address: 'Organic City', phone: '0123-555555') + 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 eb81f550..36c22f65 100644 --- a/db/migrate/004_create_article_meta.rb +++ b/db/migrate/004_create_article_meta.rb @@ -5,24 +5,24 @@ class CreateArticleMeta < ActiveRecord::Migration[4.2] 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 '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 :name, :string, null: false t.column :description, :string end - add_index(:article_categories, :name, :unique => true) + 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) + ArticleCategory.create(name: CATEGORY_SAMPLE, description: 'This is just a sample article category.') + 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 0b1cef89..7ca0e83c 100644 --- a/db/migrate/005_create_financial_transactions.rb +++ b/db/migrate/005_create_financial_transactions.rb @@ -2,19 +2,19 @@ class CreateFinancialTransactions < ActiveRecord::Migration[4.2] def self.up # Create Financial Transactions create_table :financial_transactions do |t| - t.column :order_group_id, :integer, :null => false - t.column :amount, :decimal, :precision => 8, :scale => 2, :null => false - t.column :note, :text, :null => false - t.column :user_id, :integer, :null => false - t.column :created_on, :datetime, :null => false + t.column :order_group_id, :integer, null: false + t.column :amount, :decimal, precision: 8, scale: 2, null: false + t.column :note, :text, null: false + t.column :user_id, :integer, null: false + t.column :created_on, :datetime, null: false end # add column for the finance role puts 'add column in "groups" for the finance role' - add_column :groups, :role_finance, :boolean, :default => false, :null => false + add_column :groups, :role_finance, :boolean, default: false, null: false Group.reset_column_information puts "Give #{CreateGroups::GROUP_ADMIN} the role finance .." - raise "Failed" unless Group.find_by_name(CreateGroups::GROUP_ADMIN).update_attribute(:role_finance, true) + raise 'Failed' unless Group.find_by_name(CreateGroups::GROUP_ADMIN).update_attribute(:role_finance, true) raise 'Cannot find admin user!' unless admin = User.find_by_nick(CreateUsers::USER_ADMIN) raise 'Failed to enable role_finance with admin user!' unless admin.role_finance? @@ -27,8 +27,8 @@ def self.up 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 to update account_balance!" unless OrderGroup.find(ordergroup.id).account_balance == balance + 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 diff --git a/db/migrate/006_create_articles.rb b/db/migrate/006_create_articles.rb index 9a43c8dc..fd11e659 100644 --- a/db/migrate/006_create_articles.rb +++ b/db/migrate/006_create_articles.rb @@ -1,17 +1,17 @@ class CreateArticles < ActiveRecord::Migration[4.2] - SAMPLE_ARTICLE_NAMES = ['banana', 'kiwi', 'strawberry'] + SAMPLE_ARTICLE_NAMES = %w[banana kiwi strawberry] def self.up create_table :articles do |t| - t.column :name, :string, :null => false - t.column :supplier_id, :integer, :null => false - t.column :article_category_id, :integer, :null => false - t.column :unit, :string, :null => false + t.column :name, :string, null: false + t.column :supplier_id, :integer, null: false + t.column :article_category_id, :integer, null: false + t.column :unit, :string, null: false t.column :note, :string - t.column :availability, :boolean, :default => true, :null => false + 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}'..." @@ -20,14 +20,14 @@ def self.up 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) + 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 + 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 32488794..68ed0915 100644 --- a/db/migrate/007_create_article_prices.rb +++ b/db/migrate/007_create_article_prices.rb @@ -1,13 +1,13 @@ class CreateArticlePrices < ActiveRecord::Migration[4.2] def self.up 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 :tax, :float, :null => false, :default => 0 - t.column :refund, :decimal, :precision => 8, :scale => 2, :null => false, :default => 0 + 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 :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 :unit_quantity, :int, default: 1, null: false t.column :order_number, :string end add_index(:article_prices, :article_id) @@ -18,11 +18,11 @@ def self.up 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)) + new_price = ArticlePrice.new(clear_price: rand(1..4), + tax: 7.0, + refund: 0, + unit_quantity: rand(1..10), + order_number: rand(9999)) article.add_price(new_price) raise 'Failed!' unless ArticlePrice.find_by_article_id(article.id) end diff --git a/db/migrate/008_create_orders.rb b/db/migrate/008_create_orders.rb index 6eb8c921..0106fc32 100644 --- a/db/migrate/008_create_orders.rb +++ b/db/migrate/008_create_orders.rb @@ -4,28 +4,28 @@ class CreateOrders < ActiveRecord::Migration[4.2] def self.up # Order role - add_column :groups, :role_orders, :boolean, :default => false, :null => false + add_column :groups, :role_orders, :boolean, default: false, null: false Group.reset_column_information puts "Give #{CreateGroups::GROUP_ADMIN} the role finance .." - raise "Failed" unless Group.find_by_name(CreateGroups::GROUP_ADMIN).update_attribute(:role_orders, true) + 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) + 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 - t.column :supplier_id, :integer, :null => false - t.column :starts, :datetime, :null => false + t.column :name, :string, null: false + t.column :supplier_id, :integer, null: false + t.column :starts, :datetime, null: false t.column :ends, :datetime t.column :note, :string - t.column :finished, :boolean, :default => false, :null => false - t.column :booked, :boolean, :null => false, :default => false - t.column :lock_version, :integer, :null => false, :default => 0 + t.column :finished, :boolean, default: false, null: false + t.column :booked, :boolean, null: false, default: false + t.column :lock_version, :integer, null: false, default: 0 t.column :updated_by_user_id, :integer end add_index(:orders, :starts) @@ -35,74 +35,76 @@ def self.up 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) + Order.create(name: ORDER_TEST, supplier: supplier, starts: Time.now) raise 'Creating test order failed!' unless order = Order.find_by_name(ORDER_TEST) # OrderArticle create_table :order_articles do |t| - t.column :order_id, :integer, :null => false - t.column :article_id, :integer, :null => false - t.column :quantity, :integer, :null => false, :default => 0 - t.column :tolerance, :integer, :null => false, :default => 0 - t.column :units_to_order, :integer, :null => false, :default => 0 - t.column :lock_version, :integer, :null => false, :default => 0 + t.column :order_id, :integer, null: false + t.column :article_id, :integer, null: false + t.column :quantity, :integer, null: false, default: 0 + t.column :tolerance, :integer, null: false, default: 0 + t.column :units_to_order, :integer, null: false, default: 0 + t.column :lock_version, :integer, null: false, default: 0 end - add_index(:order_articles, [:order_id, :article_id], :unique => true) + add_index(:order_articles, %i[order_id article_id], unique: true) puts 'Adding articles to the order...' - CreateArticles::SAMPLE_ARTICLE_NAMES.each { |a| + CreateArticles::SAMPLE_ARTICLE_NAMES.each do |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) + OrderArticle.create(order: order, article: article) raise 'Creating OrderArticle failed!' unless OrderArticle.find_by_order_id_and_article_id(order.id, article.id) - } + end 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 - t.column :order_id, :integer, :null => false - t.column :price, :decimal, :precision => 8, :scale => 2, :null => false, :default => 0 - t.column :lock_version, :integer, :null => false, :default => 0 - t.column :updated_on, :timestamp, :null => false - t.column :updated_by_user_id, :integer, :null => false + t.column :order_group_id, :integer, null: false + t.column :order_id, :integer, null: false + t.column :price, :decimal, precision: 8, scale: 2, null: false, default: 0 + t.column :lock_version, :integer, null: false, default: 0 + 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, %i[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}") + 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 - t.column :order_article_id, :integer, :null => false - t.column :quantity, :integer, :null => false - t.column :tolerance, :integer, :null => false - t.column :updated_on, :timestamp, :null => false + t.column :group_order_id, :integer, null: false + t.column :order_article_id, :integer, null: false + t.column :quantity, :integer, null: false + t.column :tolerance, :integer, null: false + t.column :updated_on, :timestamp, null: false end - add_index(:group_order_articles, [:group_order_id, :order_article_id], :unique => true, :name => "goa_index") + add_index(:group_order_articles, %i[group_order_id order_article_id], unique: true, name: 'goa_index') # GroupOrderArticleQuantity create_table :group_order_article_quantities do |t| - t.column :group_order_article_id, :int, :null => false - t.column :quantity, :int, :default => 0 - t.column :tolerance, :int, :default => 0 - t.column :created_on, :timestamp, :null => false + t.column :group_order_article_id, :int, null: false + t.column :quantity, :int, default: 0 + 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 do |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}") + 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) - } + article.updateQuantities(rand(1..6), rand(1..4)) + end raise 'Failed to create orders!' unless groupOrder.order_articles.size == order.order_articles.size groupOrder.updatePrice diff --git a/db/migrate/009_create_order_results.rb b/db/migrate/009_create_order_results.rb index 20b75193..6b1cc65a 100644 --- a/db/migrate/009_create_order_results.rb +++ b/db/migrate/009_create_order_results.rb @@ -1,32 +1,32 @@ class CreateOrderResults < ActiveRecord::Migration[4.2] def self.up create_table :group_order_results do |t| - t.column :order_id, :int, :null => false - t.column :group_name, :string, :null => false - t.column :price, :decimal, :precision => 8, :scale => 2, :null => false, :default => 0 + t.column :order_id, :int, null: false + t.column :group_name, :string, null: false + t.column :price, :decimal, precision: 8, scale: 2, null: false, default: 0 end - add_index(:group_order_results, [:group_name, :order_id], :unique => true) + add_index(:group_order_results, %i[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 - t.column :unit, :string, :null => false + t.column :order_id, :int, null: false + t.column :name, :string, null: false + t.column :unit, :string, null: false t.column :note, :string - t.column :clear_price, :decimal, :precision => 8, :scale => 2, :null => false - t.column :gross_price, :decimal, :precision => 8, :scale => 2, :null => false - t.column :tax, :float, :null => false, :default => 0 - t.column :refund, :decimal, :precision => 8, :scale => 2 - t.column :fc_markup, :float, :null => false + t.column :clear_price, :decimal, precision: 8, scale: 2, null: false + t.column :gross_price, :decimal, precision: 8, scale: 2, null: false + t.column :tax, :float, null: false, default: 0 + t.column :refund, :decimal, precision: 8, scale: 2 + t.column :fc_markup, :float, null: false t.column :order_number, :string - t.column :unit_quantity, :int, :null => false - t.column :units_to_order, :int, :null => false + t.column :unit_quantity, :int, null: false + 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 - t.column :quantity, :int, :null => false + t.column :order_article_result_id, :int, null: false + t.column :group_order_result_id, :int, null: false + t.column :quantity, :int, null: false t.column :tolerance, :int end add_index(:group_order_article_results, :order_article_result_id) diff --git a/db/migrate/011_create_comments.rb b/db/migrate/011_create_comments.rb index 28fc0428..55148d08 100644 --- a/db/migrate/011_create_comments.rb +++ b/db/migrate/011_create_comments.rb @@ -1,16 +1,16 @@ class CreateComments < ActiveRecord::Migration[4.2] def self.up - create_table :comments, :force => true do |t| - t.column :title, :string, :limit => 50, :default => "" - t.column :comment, :string, :default => "" - 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 - t.column :user_id, :integer, :default => 0, :null => false + create_table :comments, force: true do |t| + t.column :title, :string, limit: 50, default: '' + t.column :comment, :string, default: '' + 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 + t.column :user_id, :integer, default: 0, null: false end - add_index :comments, ["user_id"], :name => "fk_comments_user" + add_index :comments, ['user_id'], name: 'fk_comments_user' end def self.down diff --git a/db/migrate/012_create_order_clearing.rb b/db/migrate/012_create_order_clearing.rb index 1d3133fd..9ddb4ad3 100644 --- a/db/migrate/012_create_order_clearing.rb +++ b/db/migrate/012_create_order_clearing.rb @@ -1,8 +1,8 @@ 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 - add_column :orders, :refund_credit, :decimal, :precision => 8, :scale => 2, :null => false, :default => 0 + 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 + add_column :orders, :refund_credit, :decimal, precision: 8, scale: 2, null: false, default: 0 add_column :orders, :invoice_number, :string add_column :orders, :invoice_date, :string end diff --git a/db/migrate/013_add_messaging.rb b/db/migrate/013_add_messaging.rb index 84ba8d6f..7f01b2dd 100644 --- a/db/migrate/013_add_messaging.rb +++ b/db/migrate/013_add_messaging.rb @@ -3,13 +3,13 @@ def self.up # Table that holds the messages: create_table :messages do |t| t.column :sender_id, :integer - t.column :recipient_id, :integer, :null => false - t.column :recipients, :string, :null => false - t.column :subject, :string, :null => false - t.column :body, :text, :null => false - t.column :read, :boolean, :null => false, :default => false - t.column :email_state, :integer, :null => false - t.column :created_on, :timestamp, :null => false + t.column :recipient_id, :integer, null: false + t.column :recipients, :string, null: false + t.column :subject, :string, null: false + t.column :body, :text, null: false + t.column :read, :boolean, null: false, default: false + t.column :email_state, :integer, null: false + t.column :created_on, :timestamp, null: false end add_index(:messages, :sender_id) add_index(:messages, :recipient_id) diff --git a/db/migrate/014_create_tasks.rb b/db/migrate/014_create_tasks.rb index db878546..8872523e 100644 --- a/db/migrate/014_create_tasks.rb +++ b/db/migrate/014_create_tasks.rb @@ -1,26 +1,26 @@ class CreateTasks < ActiveRecord::Migration[4.2] def self.up create_table :tasks do |t| - t.column :name, :string, :null => false + t.column :name, :string, null: false t.column :description, :string t.column :due_date, :date - t.column :done, :boolean, :default => false + t.column :done, :boolean, default: false t.column :group_id, :integer - t.column :assigned, :boolean, :default => false - t.column :created_on, :datetime, :null => false - t.column :updated_on, :datetime, :null => false + t.column :assigned, :boolean, default: false + t.column :created_on, :datetime, null: false + t.column :updated_on, :datetime, null: false 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 + 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_index :assignments, %i[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, :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 add_column :groups, :task_description, :string diff --git a/db/migrate/015_change_result_quantities.rb b/db/migrate/015_change_result_quantities.rb index 23731334..56020eab 100644 --- a/db/migrate/015_change_result_quantities.rb +++ b/db/migrate/015_change_result_quantities.rb @@ -1,11 +1,11 @@ class ChangeResultQuantities < ActiveRecord::Migration[4.2] def self.up - change_column :group_order_article_results, :quantity, :decimal, :precision => 6, :scale => 3 - change_column :order_article_results, :units_to_order, :decimal, :precision => 6, :scale => 3, :null => false + change_column :group_order_article_results, :quantity, :decimal, precision: 6, scale: 3 + change_column :order_article_results, :units_to_order, :decimal, precision: 6, scale: 3, null: false end 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 :group_order_article_results, :quantity, :integer, null: false + change_column :order_article_results, :units_to_order, :integer, default: 0, null: false end end diff --git a/db/migrate/018_create_invites.rb b/db/migrate/018_create_invites.rb index cc8a1ebc..49c3edf9 100644 --- a/db/migrate/018_create_invites.rb +++ b/db/migrate/018_create_invites.rb @@ -1,11 +1,11 @@ class CreateInvites < ActiveRecord::Migration[4.2] def self.up create_table :invites do |t| - t.column :token, :string, :null => false - t.column :expires_at, :timestamp, :null => false - t.column :group_id, :integer, :null => false - t.column :user_id, :integer, :null => false - t.column :email, :string, :null => false + t.column :token, :string, null: false + t.column :expires_at, :timestamp, null: false + t.column :group_id, :integer, null: false + t.column :user_id, :integer, null: false + t.column :email, :string, null: false end add_index :invites, :token end diff --git a/db/migrate/019_remove_uniqueness_of_article_name.rb b/db/migrate/019_remove_uniqueness_of_article_name.rb index 7504a66a..50170cb8 100644 --- a/db/migrate/019_remove_uniqueness_of_article_name.rb +++ b/db/migrate/019_remove_uniqueness_of_article_name.rb @@ -1,11 +1,11 @@ class RemoveUniquenessOfArticleName < ActiveRecord::Migration[4.2] def self.up remove_index :articles, :name - add_index :articles, [:name, :supplier_id] + add_index :articles, %i[name supplier_id] end def self.down - remove_index :articles, [:name, :supplier_id] - add_index :articles, :name, :unique => true + remove_index :articles, %i[name supplier_id] + add_index :articles, :name, unique: true end end diff --git a/db/migrate/021_remove_table_article_prices.rb b/db/migrate/021_remove_table_article_prices.rb index dc664347..fdbf312d 100644 --- a/db/migrate/021_remove_table_article_prices.rb +++ b/db/migrate/021_remove_table_article_prices.rb @@ -1,71 +1,71 @@ 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 - add_column "articles", "tax", :float - add_column "articles", "refund", :decimal, :precision => 8, :scale => 2, :default => 0.0, :null => false - add_column "articles", "unit_quantity", :integer, :default => 1, :null => false - add_column "articles", "order_number", :string - add_column "articles", "created_at", :datetime - add_column "articles", "updated_at", :datetime + 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 + add_column 'articles', 'tax', :float + add_column 'articles', 'refund', :decimal, precision: 8, scale: 2, default: 0.0, null: false + add_column 'articles', 'unit_quantity', :integer, default: 1, null: false + 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..." + 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) + 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) end - puts "delete article_prices, current_price attribute" + puts 'delete article_prices, current_price attribute' drop_table :article_prices remove_column :articles, :current_price_id end def self.down add_column :articles, :current_price_id, :integer - create_table "article_prices", :force => true do |t| - t.integer "article_id", :default => 0, :null => false - 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.datetime "updated_on" - t.integer "unit_quantity", :default => 1, :null => false - t.string "order_number" + create_table 'article_prices', force: true do |t| + t.integer 'article_id', default: 0, null: false + 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.datetime 'updated_on' + 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) + 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.presence, + 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", "gross_price" - remove_column "articles", "tax" - remove_column "articles", "refund" - remove_column "articles", "unit_quantity" - remove_column "articles", "order_number" - remove_column "articles", "created_at" - remove_column "articles", "updated_at" + remove_column 'articles', 'clear_price' + remove_column 'articles', 'gross_price' + remove_column 'articles', 'tax' + remove_column 'articles', 'refund' + remove_column 'articles', 'unit_quantity' + remove_column 'articles', 'order_number' + remove_column 'articles', 'created_at' + remove_column 'articles', 'updated_at' end end diff --git a/db/migrate/022_add_required_user_for_task.rb b/db/migrate/022_add_required_user_for_task.rb index 9e8d9621..105e1593 100644 --- a/db/migrate/022_add_required_user_for_task.rb +++ b/db/migrate/022_add_required_user_for_task.rb @@ -1,7 +1,7 @@ class AddRequiredUserForTask < ActiveRecord::Migration[4.2] def self.up - add_column :tasks, :required_users, :integer, :default => 1 - add_column :groups, :task_required_users, :integer, :default => 1 + add_column :tasks, :required_users, :integer, default: 1 + add_column :groups, :task_required_users, :integer, default: 1 # add default values to every task and group Task.find(:all).each { |task| task.update_attribute :required_users, 1 } Group.workgroups.each { |group| group.update_attribute :task_required_users, 1 } diff --git a/db/migrate/024_add_deposit_defaults.rb b/db/migrate/024_add_deposit_defaults.rb index ed9da063..68afdf5a 100644 --- a/db/migrate/024_add_deposit_defaults.rb +++ b/db/migrate/024_add_deposit_defaults.rb @@ -7,6 +7,5 @@ def self.up change_column_default :orders, :deposit_credit, 0.0 end - def self.down - end + def self.down; end end diff --git a/db/migrate/025_extend_comments.rb b/db/migrate/025_extend_comments.rb index 662b92fd..3b1b1da2 100644 --- a/db/migrate/025_extend_comments.rb +++ b/db/migrate/025_extend_comments.rb @@ -1,9 +1,9 @@ class ExtendComments < ActiveRecord::Migration[4.2] def self.up - change_column :comments, :comment, :text, :default => "" + change_column :comments, :comment, :text, default: '' end def self.down - change_column :comments, :comment, :string, :default => "" + change_column :comments, :comment, :string, default: '' end end diff --git a/db/migrate/20090120184410_road_to_version_three.rb b/db/migrate/20090120184410_road_to_version_three.rb index 4b8aa9ab..c7adfc87 100644 --- a/db/migrate/20090120184410_road_to_version_three.rb +++ b/db/migrate/20090120184410_road_to_version_three.rb @@ -10,10 +10,10 @@ def self.up create_table :messages do |t| t.references :sender t.text :recipients_ids - t.string :subject, :null => false + t.string :subject, null: false t.text :body - t.integer :email_state, :default => 0, :null => false - t.boolean :private, :default => false + t.integer :email_state, default: 0, null: false + t.boolean :private, default: false t.datetime :created_at end @@ -23,9 +23,9 @@ def self.up add_column :groups, :deleted_at, :datetime # == Workgroups - puts "Migrate all groups to workgroups.." - Group.find(:all, :conditions => { :type => "" }).each do |workgroup| - workgroup.update_attribute(:type, "Workgroup") + puts 'Migrate all groups to workgroups..' + Group.find(:all, conditions: { type: '' }).each do |workgroup| + workgroup.update_attribute(:type, 'Workgroup') end # == Ordergroups @@ -34,11 +34,11 @@ def self.up rename_column :financial_transactions, :order_group_id, :ordergroup_id rename_column :group_orders, :order_group_id, :ordergroup_id rename_column :tasks, :group_id, :workgroup_id - remove_index :group_orders, :name => "index_group_orders_on_order_group_id_and_order_id" - add_index :group_orders, [:ordergroup_id, :order_id], :unique => true + remove_index :group_orders, name: 'index_group_orders_on_order_group_id_and_order_id' + add_index :group_orders, %i[ordergroup_id order_id], unique: true - Group.find(:all, :conditions => { :type => "OrderGroup" }).each do |ordergroup| - ordergroup.update_attribute(:type, "Ordergroup") + Group.find(:all, conditions: { type: 'OrderGroup' }).each do |ordergroup| + ordergroup.update_attribute(:type, 'Ordergroup') end # move contact-infos from users to ordergroups add_column :groups, :contact_person, :string @@ -47,8 +47,8 @@ def self.up Ordergroup.all.each do |ordergroup| contact = ordergroup.users.first if contact - ordergroup.update_attributes :contact_person => contact.name, - :contact_phone => contact.phone, :contact_address => contact.address + ordergroup.update_attributes contact_person: contact.name, + contact_phone: contact.phone, contact_address: contact.address end end remove_column :users, :address @@ -58,15 +58,18 @@ def self.up drop_table :group_order_results drop_table :order_article_results drop_table :group_order_article_results - GroupOrder.delete_all; OrderArticle.delete_all; GroupOrderArticle.delete_all; GroupOrderArticleQuantity.delete_all + GroupOrder.delete_all + OrderArticle.delete_all + GroupOrderArticle.delete_all + GroupOrderArticleQuantity.delete_all create_table :orders do |t| t.references :supplier t.text :note t.datetime :starts t.datetime :ends - t.string :state, :default => "open" # Statemachine ... open -> finished -> closed - t.integer :lock_version, :default => 0, :null => false + t.string :state, default: 'open' # Statemachine ... open -> finished -> closed + t.integer :lock_version, default: 0, null: false t.integer :updated_by_user_id end @@ -79,9 +82,9 @@ def self.up t.date :date 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 :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.timestamps end @@ -108,41 +111,41 @@ def self.up # == ArticlePrice create_table :article_prices do |t| t.references :article - t.decimal :price, :precision => 8, :scale => 2, :default => 0.0, :null => false - t.decimal :tax, :precision => 8, :scale => 2, :default => 0.0, :null => false - t.decimal :deposit, :precision => 8, :scale => 2, :default => 0.0, :null => false + t.decimal :price, precision: 8, scale: 2, default: 0.0, null: false + t.decimal :tax, precision: 8, scale: 2, default: 0.0, null: false + t.decimal :deposit, precision: 8, scale: 2, default: 0.0, null: false t.integer :unit_quantity t.datetime :created_at end # 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 + a.article_prices.create price: a.price, tax: a.tax, + 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.all(conditions: { article_category_id: nil }).each do |article| article.update_attribute(:article_category, ArticleCategory.first) end # order-articles add_column :order_articles, :article_price_id, :integer # == GroupOrder - change_column :group_orders, :updated_by_user_id, :integer, :default => nil, :null => true + change_column :group_orders, :updated_by_user_id, :integer, default: nil, null: true # == GroupOrderArticle # The total order result in ordergroup is now saved! - add_column :group_order_articles, :result, :integer, :default => nil + add_column :group_order_articles, :result, :integer, default: nil # == StockArticle add_column :articles, :type, :string - add_column :articles, :quantity, :integer, :default => 0 + add_column :articles, :quantity, :integer, default: 0 # == StockChanges create_table :stock_changes do |t| t.references :delivery t.references :order t.references :stock_article - t.integer :quantity, :default => 0 + t.integer :quantity, default: 0 t.datetime :created_at end @@ -159,6 +162,5 @@ def self.up User.all.each { |u| u.settings['notify.upcoming_tasks'] = 1 } end - def self.down - end + def self.down; end end diff --git a/db/migrate/20090317175355_add_profit_to_orders.rb b/db/migrate/20090317175355_add_profit_to_orders.rb index 59f79609..78013f7d 100644 --- a/db/migrate/20090317175355_add_profit_to_orders.rb +++ b/db/migrate/20090317175355_add_profit_to_orders.rb @@ -1,6 +1,6 @@ class AddProfitToOrders < ActiveRecord::Migration[4.2] def self.up - add_column :orders, :foodcoop_result, :decimal, :precision => 8, :scale => 2 + add_column :orders, :foodcoop_result, :decimal, precision: 8, scale: 2 Order.closed.each do |order| order.update_attribute(:foodcoop_result, order.profit) diff --git a/db/migrate/20090325175756_create_pages.foodsoft_wiki_engine.rb b/db/migrate/20090325175756_create_pages.foodsoft_wiki_engine.rb index c5692f35..d2221013 100644 --- a/db/migrate/20090325175756_create_pages.foodsoft_wiki_engine.rb +++ b/db/migrate/20090325175756_create_pages.foodsoft_wiki_engine.rb @@ -5,7 +5,7 @@ def self.up t.string :title t.text :body t.string :permalink - t.integer :lock_version, :default => 0 + t.integer :lock_version, default: 0 t.integer :updated_by t.integer :redirect t.integer :parent_id diff --git a/db/migrate/20090405131156_modify_group_order_article_result.rb b/db/migrate/20090405131156_modify_group_order_article_result.rb index 44e0dea8..b979422e 100644 --- a/db/migrate/20090405131156_modify_group_order_article_result.rb +++ b/db/migrate/20090405131156_modify_group_order_article_result.rb @@ -1,6 +1,6 @@ class ModifyGroupOrderArticleResult < ActiveRecord::Migration[4.2] def self.up - change_column :group_order_articles, :result, :decimal, :precision => 8, :scale => 3 + change_column :group_order_articles, :result, :decimal, precision: 8, scale: 3 end def self.down diff --git a/db/migrate/20090907120012_add_missing_indexes.rb b/db/migrate/20090907120012_add_missing_indexes.rb index 189b0417..93ea8771 100644 --- a/db/migrate/20090907120012_add_missing_indexes.rb +++ b/db/migrate/20090907120012_add_missing_indexes.rb @@ -1,35 +1,34 @@ class AddMissingIndexes < ActiveRecord::Migration[4.2] def self.up - add_index "article_prices", ["article_id"] + add_index 'article_prices', ['article_id'] - add_index "articles", ["supplier_id"] - add_index "articles", ["article_category_id"] - add_index "articles", ["type"] + add_index 'articles', ['supplier_id'] + add_index 'articles', ['article_category_id'] + add_index 'articles', ['type'] - add_index "deliveries", ["supplier_id"] + add_index 'deliveries', ['supplier_id'] - add_index "financial_transactions", ["ordergroup_id"] + add_index 'financial_transactions', ['ordergroup_id'] - add_index "group_order_article_quantities", ["group_order_article_id"] - add_index "group_orders", ["order_id"] - add_index "group_orders", ["ordergroup_id"] + add_index 'group_order_article_quantities', ['group_order_article_id'] + add_index 'group_orders', ['order_id'] + add_index 'group_orders', ['ordergroup_id'] - add_index "invoices", ["supplier_id"] - add_index "invoices", ["delivery_id"] + add_index 'invoices', ['supplier_id'] + add_index 'invoices', ['delivery_id'] - add_index "order_articles", ["order_id"] + add_index 'order_articles', ['order_id'] - add_index "order_comments", ["order_id"] + add_index 'order_comments', ['order_id'] - add_index "orders", ["state"] + add_index 'orders', ['state'] - add_index "stock_changes", ["delivery_id"] - add_index "stock_changes", ["stock_article_id"] - add_index "stock_changes", ["stock_taking_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 - end + def self.down; end end diff --git a/db/migrate/20110507184920_add_duration_to_tasks.rb b/db/migrate/20110507184920_add_duration_to_tasks.rb index 33a11494..86347508 100644 --- a/db/migrate/20110507184920_add_duration_to_tasks.rb +++ b/db/migrate/20110507184920_add_duration_to_tasks.rb @@ -1,6 +1,6 @@ class AddDurationToTasks < ActiveRecord::Migration[4.2] def self.up - add_column :tasks, :duration, :integer, :default => 1 + add_column :tasks, :duration, :integer, default: 1 end def self.down diff --git a/db/migrate/20110507192928_add_task_duration_to_workgroups.rb b/db/migrate/20110507192928_add_task_duration_to_workgroups.rb index c5b4844b..fd703d17 100644 --- a/db/migrate/20110507192928_add_task_duration_to_workgroups.rb +++ b/db/migrate/20110507192928_add_task_duration_to_workgroups.rb @@ -1,6 +1,6 @@ class AddTaskDurationToWorkgroups < ActiveRecord::Migration[4.2] def self.up - add_column :groups, :task_duration, :integer, :default => 1 + add_column :groups, :task_duration, :integer, default: 1 end def self.down diff --git a/db/migrate/20120622094337_add_next_weekly_tasks_number_to_workgroups.rb b/db/migrate/20120622094337_add_next_weekly_tasks_number_to_workgroups.rb index b8ac8c81..eeca92b3 100644 --- a/db/migrate/20120622094337_add_next_weekly_tasks_number_to_workgroups.rb +++ b/db/migrate/20120622094337_add_next_weekly_tasks_number_to_workgroups.rb @@ -1,6 +1,6 @@ class AddNextWeeklyTasksNumberToWorkgroups < ActiveRecord::Migration[4.2] def self.up - add_column :groups, :next_weekly_tasks_number, :integer, :default => 8 + add_column :groups, :next_weekly_tasks_number, :integer, default: 8 end def self.down diff --git a/db/migrate/20130622095040_move_weekly_tasks.rb b/db/migrate/20130622095040_move_weekly_tasks.rb index b780f3e9..f0bea5e2 100644 --- a/db/migrate/20130622095040_move_weekly_tasks.rb +++ b/db/migrate/20130622095040_move_weekly_tasks.rb @@ -15,21 +15,21 @@ def up def down PeriodicTaskGroup.all.each do |task_group| - unless task_group.tasks.empty? - task = task_group.tasks.first - workgroup = task.workgroup - puts "Writing task data of group #{task_group.id} to workgroup #{workgroup.name}" - workgroup_attributes = { - weekly_task: true, - weekday: task.due_date.days_to_week_start(:sunday), - task_name: task.name, - task_description: task.description, - task_required_users: task.required_users, - task_duration: task.duration - } - workgroup.update_attributes workgroup_attributes - task_group.tasks.update_all weekly: true - end + next if task_group.tasks.empty? + + task = task_group.tasks.first + workgroup = task.workgroup + puts "Writing task data of group #{task_group.id} to workgroup #{workgroup.name}" + workgroup_attributes = { + weekly_task: true, + weekday: task.due_date.days_to_week_start(:sunday), + task_name: task.name, + task_description: task.description, + task_required_users: task.required_users, + task_duration: task.duration + } + workgroup.update_attributes workgroup_attributes + task_group.tasks.update_all weekly: true end end diff --git a/db/migrate/20130702113610_update_group_order_totals.rb b/db/migrate/20130702113610_update_group_order_totals.rb index da57126a..52edbad4 100644 --- a/db/migrate/20130702113610_update_group_order_totals.rb +++ b/db/migrate/20130702113610_update_group_order_totals.rb @@ -1,18 +1,17 @@ class UpdateGroupOrderTotals < ActiveRecord::Migration[4.2] def self.up say "If you have ever modified an order after it was settled, the group_order's " + - "price may be calculated incorrectly. This can take a lot of time on a " + - "large database." + 'price may be calculated incorrectly. This can take a lot of time on a ' + + 'large database.' - say "If you do want to update the ordergroup totals, open the rails console " + - "(by running `rails c`), and enter:" + say 'If you do want to update the ordergroup totals, open the rails console ' + + '(by running `rails c`), and enter:' - say "GroupOrder.all.each { |go| go.order.closed? and go.update_price! }", subitem: true + say 'GroupOrder.all.each { |go| go.order.closed? and go.update_price! }', subitem: true - say "You may want to check first that no undesired accounting issues are introduced. " + - "It may be wise to discuss this with those responsible for the ordering finances." + say 'You may want to check first that no undesired accounting issues are introduced. ' + + 'It may be wise to discuss this with those responsible for the ordering finances.' end - def self.down - end + def self.down; end end diff --git a/db/migrate/20130718183100_create_settings.rb b/db/migrate/20130718183100_create_settings.rb index 9928a9b3..90639d71 100644 --- a/db/migrate/20130718183100_create_settings.rb +++ b/db/migrate/20130718183100_create_settings.rb @@ -8,7 +8,7 @@ def self.up t.timestamps end - add_index :settings, [:thing_type, :thing_id, :var], unique: true + add_index :settings, %i[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 cd173e45..2d0e3c56 100644 --- a/db/migrate/20130718183101_migrate_user_settings.rb +++ b/db/migrate/20130718183101_migrate_user_settings.rb @@ -16,7 +16,7 @@ def up begin user = type.constantize.find(id) rescue ActiveRecord::RecordNotFound - Rails.logger.debug "Can't find configurable object with type: #{type.inspect}, id: #{id.inspect}" + Rails.logger.debug { "Can't find configurable object with type: #{type.inspect}, id: #{id.inspect}" } next end @@ -27,7 +27,7 @@ def up # prepare value value = YAML.load(old_setting.value) - value = value.nil? ? false : value + value = false if value.nil? # set the settings_attributes (thanks to settings.merge! we can set them one by one) user.settings_attributes = { @@ -46,8 +46,7 @@ def up drop_table :configurable_settings end - def down - end + def down; end end # this is the base class of all configurable settings diff --git a/db/migrate/20130920201529_allow_missing_nick.rb b/db/migrate/20130920201529_allow_missing_nick.rb index ed818860..fcf1d8c8 100644 --- a/db/migrate/20130920201529_allow_missing_nick.rb +++ b/db/migrate/20130920201529_allow_missing_nick.rb @@ -1,9 +1,9 @@ class AllowMissingNick < ActiveRecord::Migration[4.2] def self.up - change_column :users, :nick, :string, :default => nil, :null => true + change_column :users, :nick, :string, default: nil, null: true end def self.down - change_column :users, :nick, :string, :default => "", :null => false + change_column :users, :nick, :string, default: '', null: false end 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 dd9fc407..0bb885d9 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/20140318173000_delete_empty_group_order_articles.rb b/db/migrate/20140318173000_delete_empty_group_order_articles.rb index 1e053c3c..c5b396ed 100644 --- a/db/migrate/20140318173000_delete_empty_group_order_articles.rb +++ b/db/migrate/20140318173000_delete_empty_group_order_articles.rb @@ -4,6 +4,5 @@ def up GroupOrderArticle.where(quantity: 0, tolerance: 0, result: [0, nil], result_computed: [0, nil]).delete_all end - def down - end + def down; end end diff --git a/db/migrate/20140921104907_remove_stale_memberships.rb b/db/migrate/20140921104907_remove_stale_memberships.rb index de5b719b..26b6c834 100644 --- a/db/migrate/20140921104907_remove_stale_memberships.rb +++ b/db/migrate/20140921104907_remove_stale_memberships.rb @@ -1,5 +1,5 @@ class RemoveStaleMemberships < ActiveRecord::Migration[4.2] def up - Membership.where("group_id NOT IN (?)", Group.ids).delete_all + Membership.where.not(group_id: Group.ids).delete_all end end diff --git a/db/migrate/20160217194036_add_role_invoices_to_group.rb b/db/migrate/20160217194036_add_role_invoices_to_group.rb index 6946fe05..5a86f425 100644 --- a/db/migrate/20160217194036_add_role_invoices_to_group.rb +++ b/db/migrate/20160217194036_add_role_invoices_to_group.rb @@ -1,5 +1,5 @@ class AddRoleInvoicesToGroup < ActiveRecord::Migration[4.2] def change - add_column :groups, :role_invoices, :boolean, :default => false, :null => false + add_column :groups, :role_invoices, :boolean, default: false, null: false end end diff --git a/db/migrate/20160218151041_add_attachment_to_invoice.rb b/db/migrate/20160218151041_add_attachment_to_invoice.rb index 58bac66d..1767905c 100644 --- a/db/migrate/20160218151041_add_attachment_to_invoice.rb +++ b/db/migrate/20160218151041_add_attachment_to_invoice.rb @@ -1,6 +1,6 @@ class AddAttachmentToInvoice < ActiveRecord::Migration[4.2] def change add_column :invoices, :attachment_mime, :string - add_column :invoices, :attachment_data, :binary, :limit => 8.megabyte + add_column :invoices, :attachment_data, :binary, limit: 8.megabyte end end diff --git a/db/migrate/20160219123220_create_financial_transaction_class_and_types.rb b/db/migrate/20160219123220_create_financial_transaction_class_and_types.rb index 5fcf318b..3c05035d 100644 --- a/db/migrate/20160219123220_create_financial_transaction_class_and_types.rb +++ b/db/migrate/20160219123220_create_financial_transaction_class_and_types.rb @@ -1,12 +1,12 @@ class CreateFinancialTransactionClassAndTypes < ActiveRecord::Migration[4.2] def change create_table :financial_transaction_classes do |t| - t.string :name, :null => false + t.string :name, null: false end create_table :financial_transaction_types do |t| - t.string :name, :null => false - t.references :financial_transaction_class, :null => false + t.string :name, null: false + t.references :financial_transaction_class, null: false end change_table :financial_transactions do |t| @@ -17,7 +17,7 @@ def change dir.up do execute "INSERT INTO financial_transaction_classes (id, name) VALUES (1, 'Standard')" execute "INSERT INTO financial_transaction_types (id, name, financial_transaction_class_id) VALUES (1, 'Foodsoft', 1)" - execute "UPDATE financial_transactions SET financial_transaction_type_id = 1" + execute 'UPDATE financial_transactions SET financial_transaction_type_id = 1' end end diff --git a/db/migrate/20160224201529_allow_stock_group_order.rb b/db/migrate/20160224201529_allow_stock_group_order.rb index a77879e3..6c9197f0 100644 --- a/db/migrate/20160224201529_allow_stock_group_order.rb +++ b/db/migrate/20160224201529_allow_stock_group_order.rb @@ -1,9 +1,9 @@ class AllowStockGroupOrder < ActiveRecord::Migration[4.2] def self.up - change_column :group_orders, :ordergroup_id, :integer, :default => nil, :null => true + change_column :group_orders, :ordergroup_id, :integer, default: nil, null: true end def self.down - change_column :group_orders, :ordergroup_id, :integer, :default => 0, :null => false + change_column :group_orders, :ordergroup_id, :integer, default: 0, null: false end end diff --git a/db/migrate/20160226000000_add_email_to_message.foodsoft_messages_engine.rb b/db/migrate/20160226000000_add_email_to_message.foodsoft_messages_engine.rb index 95b35273..ceeafa15 100644 --- a/db/migrate/20160226000000_add_email_to_message.foodsoft_messages_engine.rb +++ b/db/migrate/20160226000000_add_email_to_message.foodsoft_messages_engine.rb @@ -2,6 +2,6 @@ class AddEmailToMessage < ActiveRecord::Migration[4.2] def change add_column :messages, :salt, :string - add_column :messages, :received_email, :binary, :limit => 1.megabyte + add_column :messages, :received_email, :binary, limit: 1.megabyte end end diff --git a/db/migrate/20170801000000_create_mail_delivery_status.rb b/db/migrate/20170801000000_create_mail_delivery_status.rb index 2fd40674..69fa1b75 100644 --- a/db/migrate/20170801000000_create_mail_delivery_status.rb +++ b/db/migrate/20170801000000_create_mail_delivery_status.rb @@ -2,8 +2,8 @@ class CreateMailDeliveryStatus < ActiveRecord::Migration[4.2] def change create_table :mail_delivery_status do |t| t.datetime :created_at - t.string :email, :null => false - t.string :message, :null => false + t.string :email, null: false + t.string :message, null: false t.string :attachment_mime t.binary :attachment_data, limit: 16.megabyte diff --git a/db/migrate/20171002000000_create_financial_links.rb b/db/migrate/20171002000000_create_financial_links.rb index 5f42ec2e..c906869b 100644 --- a/db/migrate/20171002000000_create_financial_links.rb +++ b/db/migrate/20171002000000_create_financial_links.rb @@ -4,7 +4,9 @@ def change t.text :note end - add_column :financial_transactions, :financial_link_id, :integer, index: true - add_column :invoices, :financial_link_id, :integer, index: true + add_column :financial_transactions, :financial_link_id, :integer + add_index :financial_transactions, :financial_link_id + add_column :invoices, :financial_link_id, :integer + add_index :invoices, :financial_link_id end end diff --git a/db/migrate/20181110000000_create_polls.foodsoft_polls_engine.rb b/db/migrate/20181110000000_create_polls.foodsoft_polls_engine.rb index 990e75f0..120b7eef 100644 --- a/db/migrate/20181110000000_create_polls.foodsoft_polls_engine.rb +++ b/db/migrate/20181110000000_create_polls.foodsoft_polls_engine.rb @@ -24,14 +24,14 @@ def change t.references :ordergroup t.text :note t.timestamps - t.index [:poll_id, :user_id, :ordergroup_id], unique: true + t.index %i[poll_id user_id ordergroup_id], unique: true end create_table :poll_choices do |t| t.references :poll_vote, null: false t.integer :choice, null: false t.integer :value, null: false - t.index [:poll_vote_id, :choice], unique: true + t.index %i[poll_vote_id choice], unique: true end end end diff --git a/db/migrate/20181120000000_increase_choices_size.foodsoft_polls_engine.rb b/db/migrate/20181120000000_increase_choices_size.foodsoft_polls_engine.rb index d809e3ea..621863dd 100644 --- a/db/migrate/20181120000000_increase_choices_size.foodsoft_polls_engine.rb +++ b/db/migrate/20181120000000_increase_choices_size.foodsoft_polls_engine.rb @@ -1,5 +1,5 @@ class IncreaseChoicesSize < ActiveRecord::Migration[4.2] def up - change_column :polls, :choices, :text, limit: 65535 + change_column :polls, :choices, :text, limit: 65_535 end end diff --git a/db/migrate/20181201000000_create_printer_jobs.foodsoft_printer_engine.rb b/db/migrate/20181201000000_create_printer_jobs.foodsoft_printer_engine.rb index ee7665e4..36d175c5 100644 --- a/db/migrate/20181201000000_create_printer_jobs.foodsoft_printer_engine.rb +++ b/db/migrate/20181201000000_create_printer_jobs.foodsoft_printer_engine.rb @@ -15,6 +15,6 @@ def change t.text :message end - add_index :printer_job_updates, [:printer_job_id, :created_at] + add_index :printer_job_updates, %i[printer_job_id created_at] end end diff --git a/db/migrate/20181201000100_create_message_recipients.foodsoft_messages.rb b/db/migrate/20181201000100_create_message_recipients.foodsoft_messages.rb index e931f748..b1d0d51c 100644 --- a/db/migrate/20181201000100_create_message_recipients.foodsoft_messages.rb +++ b/db/migrate/20181201000100_create_message_recipients.foodsoft_messages.rb @@ -14,7 +14,7 @@ def up t.datetime :read_at end - add_index :message_recipients, [:user_id, :read_at] + add_index :message_recipients, %i[user_id read_at] Message.all.each do |m| recipients = YAML.load(m.recipients_ids).map do |r| diff --git a/db/migrate/20190101000000_create_active_storage_tables.active_storage.rb b/db/migrate/20190101000000_create_active_storage_tables.active_storage.rb index 3739c2e8..650274b4 100644 --- a/db/migrate/20190101000000_create_active_storage_tables.active_storage.rb +++ b/db/migrate/20190101000000_create_active_storage_tables.active_storage.rb @@ -20,7 +20,7 @@ def change t.datetime :created_at, null: false - t.index [:record_type, :record_id, :name, :blob_id], name: "index_active_storage_attachments_uniqueness", unique: true + t.index %i[record_type record_id name blob_id], name: 'index_active_storage_attachments_uniqueness', unique: true t.foreign_key :active_storage_blobs, column: :blob_id end end diff --git a/db/migrate/20210205090257_introduce_received_state_in_orders.rb b/db/migrate/20210205090257_introduce_received_state_in_orders.rb index ffeff588..ca7ce999 100644 --- a/db/migrate/20210205090257_introduce_received_state_in_orders.rb +++ b/db/migrate/20210205090257_introduce_received_state_in_orders.rb @@ -1,7 +1,7 @@ class IntroduceReceivedStateInOrders < ActiveRecord::Migration[5.2] def up Order.where(state: 'finished').each do |order| - order.update_attribute(:state, 'received') if order.order_articles.where('units_received IS NOT NULL').any? + order.update_attribute(:state, 'received') if order.order_articles.where.not(units_received: nil).any? end end diff --git a/db/migrate/20221026102300_alter_articles_add_versioning.rb b/db/migrate/20221026102300_alter_articles_add_versioning.rb index bcc2aea8..7914c8cd 100644 --- a/db/migrate/20221026102300_alter_articles_add_versioning.rb +++ b/db/migrate/20221026102300_alter_articles_add_versioning.rb @@ -4,9 +4,9 @@ def up rename_column :order_articles, :article_price_id, :article_version_id change_table :article_versions do |t| - t.string :name, default: "", null: false + t.string :name, default: '', null: false t.integer :article_category_id, default: 0, null: false - t.string :unit, default: "" + t.string :unit, default: '' t.string :note t.boolean :availability, default: true, null: false t.string :manufacturer @@ -18,7 +18,7 @@ def up # copy all article fields into article_versions articles = select_all('SELECT article_versions.id AS article_version_id, articles.* FROM article_versions JOIN articles ON articles.id = article_versions.article_id') articles.each do |article| - update(%{ + update(%( UPDATE article_versions SET name = #{quote article['name']}, article_category_id = #{quote article['article_category_id']}, @@ -30,10 +30,10 @@ def up order_number = #{quote article['order_number']}, updated_at = #{quote article['updated_at']} WHERE id = #{quote article['article_version_id']} - }) + )) end - remove_index :articles, [:name, :supplier_id] + remove_index :articles, %i[name supplier_id] # drop article columns (now superfluous as they exist in article_versions): change_table :articles do |t| @@ -53,7 +53,7 @@ def up end # remove order_articles' reference to articles (reference now always goes through article_versions): - articles = select_all(%{ + articles = select_all(%( SELECT articles.id AS article_id, article_versions.id AS article_version_id FROM articles JOIN article_versions ON article_versions.article_id = articles.id @@ -61,19 +61,19 @@ def up WHERE order_articles.article_version_id IS NULL GROUP BY article_versions.article_id ORDER BY article_versions.created_at DESC - }) + )) articles.each do |article| - update(%{ + update(%( UPDATE order_articles SET article_version_id = #{quote article['article_version_id']} WHERE order_articles.article_version_id IS NULL AND order_articles.article_id = #{quote article['article_id']} - }) + )) end # Remove orphaned order articles (db inconsistencies due to lack of foreign key constraints): - delete("DELETE FROM order_articles WHERE order_articles.article_version_id IS NULL") + delete('DELETE FROM order_articles WHERE order_articles.article_version_id IS NULL') # De-duplicate article version (db inconsistencies due to lack of unique key for created_at and article_id): duplicate_article_versions = select_all(%{ @@ -84,12 +84,12 @@ def up }) duplicate_article_versions.each do |duplicate_article_version| - article_versions = select_all(%{ + article_versions = select_all(%( SELECT id FROM article_versions WHERE article_id = #{quote duplicate_article_version['article_id']} AND created_at = #{quote duplicate_article_version['created_at']} - }) + )) latest_version = article_versions.last article_versions[0..-2].each do |obsolete_version| @@ -98,13 +98,13 @@ def up end end - remove_index :order_articles, [:order_id, :article_id] + remove_index :order_articles, %i[order_id article_id] remove_column :order_articles, :article_id change_column_null :order_articles, :article_version_id, false - add_index :order_articles, [:order_id, :article_version_id], unique: true + add_index :order_articles, %i[order_id article_version_id], unique: true add_index :order_articles, :article_version_id remove_index :article_versions, :article_id - add_index :article_versions, [:article_id, :created_at], unique: true + add_index :article_versions, %i[article_id created_at], unique: true add_index :article_versions, [:article_category_id] end @@ -112,18 +112,18 @@ def down rename_table :article_versions, :article_prices rename_column :order_articles, :article_version_id, :article_price_id - remove_index :order_articles, [:order_id, :article_price_id] + remove_index :order_articles, %i[order_id article_price_id] remove_index :order_articles, :article_price_id - remove_index :article_prices, [:article_id, :created_at] + remove_index :article_prices, %i[article_id created_at] remove_index :article_prices, [:article_category_id] add_column :order_articles, :article_id, :integer change_column_null :order_articles, :article_price_id, true change_table :articles do |t| - t.string :name, default: "", null: false + t.string :name, default: '', null: false t.integer :article_category_id, default: 0, null: false - t.string :unit, default: "" + t.string :unit, default: '' t.string :note t.boolean :availability, default: true, null: false t.string :manufacturer @@ -132,7 +132,7 @@ def down t.datetime :updated_at t.decimal :price, precision: 8, scale: 2 t.float :tax - t.decimal :deposit, precision: 8, scale: 2, default: "0.0" + t.decimal :deposit, precision: 8, scale: 2, default: '0.0' t.integer :unit_quantity, null: false, default: 0 end @@ -148,7 +148,7 @@ def down AND latest_article_prices.max_created_at = article_prices.created_at }) article_prices.each do |article_price| - update(%{ + update(%( UPDATE articles SET name = #{quote article_price['name']}, article_category_id = #{quote article_price['article_category_id']}, @@ -165,21 +165,21 @@ def down deposit = #{quote article_price['deposit']}, unit_quantity = #{quote article_price['unit_quantity']} WHERE id = #{quote article_price['article_id']} - }) + )) end - order_articles = select_all(%{ + order_articles = select_all(%( SELECT order_articles.id, article_prices.article_id FROM order_articles JOIN article_prices ON article_prices.id = order_articles.article_price_id - }) + )) order_articles.each do |order_article| - update(%{ + update(%( UPDATE order_articles SET article_id = #{quote order_article['article_id']} WHERE id = #{quote order_article['id']} - }) + )) end update(%{ @@ -202,9 +202,9 @@ def down change_column_default :articles, :unit_quantity, nil change_column_null :order_articles, :article_id, false - add_index :order_articles, [:order_id, :article_id], unique: true + add_index :order_articles, %i[order_id article_id], unique: true add_index :article_prices, :article_id - add_index :articles, [:name, :supplier_id] + add_index :articles, %i[name supplier_id] end protected diff --git a/db/migrate/20221026102301_alter_articles_add_more_unit_logic.rb b/db/migrate/20221026102301_alter_articles_add_more_unit_logic.rb index 7f3d254a..35740693 100644 --- a/db/migrate/20221026102301_alter_articles_add_more_unit_logic.rb +++ b/db/migrate/20221026102301_alter_articles_add_more_unit_logic.rb @@ -31,7 +31,7 @@ def up }) compound_unit = "#{article_version['unit_quantity']}x#{article_version['unit']}" - update(%{ + update(%( UPDATE article_versions SET unit = #{quote compound_unit}, group_order_granularity = #{quote 1}, @@ -40,7 +40,7 @@ def up price_unit = #{quote 'XPP'}, billing_unit = #{quote 'XPP'} WHERE article_versions.id = #{quote article_version['id']} - }) + )) end change_table :article_versions do |t| @@ -78,11 +78,11 @@ def down article_unit_ratios = select_all('SELECT article_version_id, quantity FROM article_unit_ratios WHERE sort=1') article_unit_ratios.each do |article_unit_ratio| - update(%{ + update(%( UPDATE article_versions SET unit_quantity = #{quote article_unit_ratio['quantity']} WHERE id = #{quote article_unit_ratio['article_version_id']} - }) + )) end drop_table :article_unit_ratios diff --git a/db/schema.rb b/db/schema.rb index 2b23929d..b403900b 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,559 +10,558 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2023_12_10_181807) do - - create_table "active_storage_attachments", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "name", null: false - t.string "record_type", null: false - t.bigint "record_id", null: false - t.bigint "blob_id", null: false - t.datetime "created_at", null: false - t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id" - t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true - end - - create_table "active_storage_blobs", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "key", null: false - t.string "filename", null: false - t.string "content_type" - t.text "metadata" - t.bigint "byte_size", null: false - t.string "checksum", null: false - t.datetime "created_at", null: false - t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true - end - - create_table "article_categories", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "name", default: "", null: false - t.string "description" - t.index ["name"], name: "index_article_categories_on_name", unique: true - end - - create_table "article_unit_ratios", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.bigint "article_version_id", null: false - t.integer "sort", null: false - t.decimal "quantity", precision: 8, scale: 3, null: false - t.string "unit" - t.index ["article_version_id"], name: "index_article_unit_ratios_on_article_version_id" - t.index ["sort"], name: "index_article_unit_ratios_on_sort" - end - - create_table "article_units", id: false, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "unit", null: false - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.index ["unit"], name: "index_article_units_on_unit", unique: true - end - - create_table "article_versions", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "article_id", null: false - t.decimal "price", precision: 8, scale: 2, default: "0.0", null: false - t.decimal "tax", precision: 8, scale: 2, default: "0.0", null: false - t.decimal "deposit", precision: 8, scale: 2, default: "0.0", null: false - t.datetime "created_at" - t.string "name", default: "", null: false - t.integer "article_category_id", default: 0, null: false - t.string "unit" - t.string "note" - t.boolean "availability", default: true, null: false - t.string "manufacturer" - t.string "origin" - t.string "order_number" - t.datetime "updated_at" - t.string "supplier_order_unit" - t.string "price_unit" - t.string "billing_unit" - t.string "group_order_unit" - t.decimal "group_order_granularity", precision: 8, scale: 3, default: "1.0", null: false - t.float "minimum_order_quantity" - t.index ["article_category_id"], name: "index_article_versions_on_article_category_id" - t.index ["article_id", "created_at"], name: "index_article_versions_on_article_id_and_created_at", unique: true - end - - create_table "articles", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "supplier_id", default: 0, null: false - t.datetime "shared_updated_on" - t.datetime "created_at" - t.datetime "deleted_at" - t.string "type" - t.integer "quantity", default: 0 - t.index ["supplier_id"], name: "index_articles_on_supplier_id" - t.index ["type"], name: "index_articles_on_type" - end - - create_table "assignments", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "user_id", default: 0, null: false - t.integer "task_id", default: 0, null: false - t.boolean "accepted", default: false - t.index ["user_id", "task_id"], name: "index_assignments_on_user_id_and_task_id", unique: true - end - - create_table "bank_accounts", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "name", null: false - t.string "iban" - t.string "description" - t.decimal "balance", precision: 12, scale: 2, default: "0.0", null: false - t.datetime "last_import" - t.string "import_continuation_point" - t.integer "bank_gateway_id" - end - - create_table "bank_gateways", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "name", null: false - t.string "url", null: false - t.string "authorization" - t.integer "unattended_user_id" - end - - create_table "bank_transactions", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "bank_account_id", null: false - t.string "external_id" - t.date "date" - t.decimal "amount", precision: 8, scale: 2, null: false - t.string "iban" - t.string "reference" - t.text "text" - t.text "receipt" - t.integer "financial_link_id" - t.index ["financial_link_id"], name: "index_bank_transactions_on_financial_link_id" - end - - create_table "documents", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "name" - t.string "mime" - t.binary "data", limit: 16777215 - t.integer "created_by_user_id" - t.datetime "created_at" - t.datetime "updated_at" - t.integer "parent_id" - t.index ["parent_id"], name: "index_documents_on_parent_id" - end - - create_table "financial_links", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci ROW_FORMAT=COMPACT", force: :cascade do |t| - t.text "note" - end - - create_table "financial_transaction_classes", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "name", null: false - t.boolean "ignore_for_account_balance", default: false, null: false - end - - create_table "financial_transaction_types", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "name", null: false - t.integer "financial_transaction_class_id", null: false - t.string "name_short" - t.integer "bank_account_id" - t.index ["name_short"], name: "index_financial_transaction_types_on_name_short" - end - - create_table "financial_transactions", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "ordergroup_id" - t.decimal "amount", precision: 8, scale: 2, default: "0.0", null: false - t.text "note", null: false - t.integer "user_id", default: 0, null: false - t.datetime "created_on", null: false - t.integer "financial_link_id" - t.integer "financial_transaction_type_id", null: false - t.integer "reverts_id" - t.integer "group_order_id" - t.index ["ordergroup_id"], name: "index_financial_transactions_on_ordergroup_id" - t.index ["reverts_id"], name: "index_financial_transactions_on_reverts_id", unique: true - end - - create_table "group_order_article_quantities", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "group_order_article_id", default: 0, null: false - t.decimal "quantity", precision: 8, scale: 3, default: "0.0", null: false - t.decimal "tolerance", precision: 8, scale: 3, default: "0.0", null: false - t.datetime "created_on", null: false - t.index ["group_order_article_id"], name: "index_group_order_article_quantities_on_group_order_article_id" - end - - create_table "group_order_articles", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "group_order_id", default: 0, null: false - t.integer "order_article_id", default: 0, null: false - t.decimal "quantity", precision: 8, scale: 3, default: "0.0", null: false - t.decimal "tolerance", precision: 8, scale: 3, default: "0.0", null: false - t.datetime "updated_on", null: false - t.decimal "result", precision: 8, scale: 3 - t.decimal "result_computed", precision: 8, scale: 3 - t.index ["group_order_id", "order_article_id"], name: "goa_index", unique: true - t.index ["group_order_id"], name: "index_group_order_articles_on_group_order_id" - t.index ["order_article_id"], name: "index_group_order_articles_on_order_article_id" - end - - create_table "group_orders", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "ordergroup_id" - t.integer "order_id", default: 0, null: false - t.decimal "price", precision: 8, scale: 2, default: "0.0", null: false - t.integer "lock_version", default: 0, null: false - t.datetime "updated_on", null: false - t.integer "updated_by_user_id" - t.decimal "transport", precision: 8, scale: 2 - t.index ["order_id"], name: "index_group_orders_on_order_id" - t.index ["ordergroup_id", "order_id"], name: "index_group_orders_on_ordergroup_id_and_order_id", unique: true - t.index ["ordergroup_id"], name: "index_group_orders_on_ordergroup_id" - end - - create_table "groups", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "type", default: "", null: false - t.string "name", default: "", null: false - t.string "description" - t.decimal "account_balance", precision: 12, scale: 2, default: "0.0", null: false - t.datetime "created_on", null: false - t.boolean "role_admin", default: false, null: false - t.boolean "role_suppliers", default: false, null: false - t.boolean "role_article_meta", default: false, null: false - t.boolean "role_finance", default: false, null: false - t.boolean "role_orders", default: false, null: false - t.datetime "deleted_at" - t.string "contact_person" - t.string "contact_phone" - t.string "contact_address" - t.text "stats" - t.integer "next_weekly_tasks_number", default: 8 - t.boolean "ignore_apple_restriction", default: false - t.boolean "role_invoices", default: false, null: false - t.date "break_start" - t.date "break_end" - t.boolean "role_pickups", default: false, null: false - t.index ["name"], name: "index_groups_on_name", unique: true - end - - create_table "invites", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "token", default: "", null: false - t.datetime "expires_at", null: false - t.integer "group_id", default: 0, null: false - t.integer "user_id", default: 0, null: false - t.string "email", default: "", null: false - t.index ["token"], name: "index_invites_on_token" - end - - create_table "invoices", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "supplier_id" - t.string "number" - t.date "date" - t.date "paid_on" - t.text "note" - t.decimal "amount", 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.datetime "created_at" - t.datetime "updated_at" - t.integer "created_by_user_id" - t.string "attachment_mime" - t.binary "attachment_data", limit: 16777215 - t.integer "financial_link_id" - t.index ["supplier_id"], name: "index_invoices_on_supplier_id" - end - - create_table "links", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "name", null: false - t.string "url", null: false - t.integer "workgroup_id" - t.boolean "indirect", default: false, null: false - t.string "authorization" - end - - create_table "mail_delivery_status", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.datetime "created_at" - t.string "email", null: false - t.string "message", null: false - t.string "attachment_mime" - t.binary "attachment_data", limit: 16777215 - t.index ["email"], name: "index_mail_delivery_status_on_email" - end - - create_table "memberships", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "group_id", default: 0, null: false - t.integer "user_id", default: 0, null: false - t.index ["user_id", "group_id"], name: "index_memberships_on_user_id_and_group_id", unique: true - end - - create_table "message_recipients", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "message_id", null: false - t.integer "user_id", null: false - t.integer "email_state", default: 0, null: false - t.datetime "read_at" - t.index ["message_id"], name: "index_message_recipients_on_message_id" - t.index ["user_id", "read_at"], name: "index_message_recipients_on_user_id_and_read_at" - end - - create_table "messages", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "sender_id" - t.string "subject", null: false - t.text "body" - t.boolean "private", default: false - t.datetime "created_at" - t.integer "reply_to" - t.integer "group_id" - t.string "salt" - t.binary "received_email", limit: 16777215 - end - - create_table "oauth_access_grants", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "resource_owner_id", null: false - t.integer "application_id", null: false - t.string "token", null: false - t.integer "expires_in", null: false - t.text "redirect_uri", null: false - t.datetime "created_at", null: false - t.datetime "revoked_at" - t.string "scopes" - t.index ["token"], name: "index_oauth_access_grants_on_token", unique: true - end - - create_table "oauth_access_tokens", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "resource_owner_id" - t.integer "application_id" - t.string "token", null: false - t.string "refresh_token" - t.integer "expires_in" - t.datetime "revoked_at" - t.datetime "created_at", null: false - t.string "scopes" - t.index ["refresh_token"], name: "index_oauth_access_tokens_on_refresh_token", unique: true - t.index ["resource_owner_id"], name: "index_oauth_access_tokens_on_resource_owner_id" - t.index ["token"], name: "index_oauth_access_tokens_on_token", unique: true - end - - create_table "oauth_applications", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "name", null: false - t.string "uid", null: false - t.string "secret", null: false - t.text "redirect_uri", null: false - t.string "scopes", default: "", null: false - t.datetime "created_at" - t.datetime "updated_at" - t.boolean "confidential", default: true, null: false - t.index ["uid"], name: "index_oauth_applications_on_uid", unique: true - end - - create_table "order_articles", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "order_id", default: 0, null: false - t.decimal "quantity", precision: 8, scale: 3, default: "0.0", null: false - t.decimal "tolerance", precision: 8, scale: 3, default: "0.0", null: false - t.decimal "units_to_order", precision: 8, scale: 3, default: "0.0", null: false - t.integer "lock_version", default: 0, null: false - t.integer "article_version_id", null: false - t.decimal "units_billed", precision: 8, scale: 3 - t.decimal "units_received", precision: 8, scale: 3 - t.index ["article_version_id"], name: "index_order_articles_on_article_version_id" - t.index ["order_id", "article_version_id"], name: "index_order_articles_on_order_id_and_article_version_id", unique: true - t.index ["order_id"], name: "index_order_articles_on_order_id" - end - - create_table "order_comments", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "order_id" - t.integer "user_id" - t.text "text" - t.datetime "created_at" - t.index ["order_id"], name: "index_order_comments_on_order_id" - end - - create_table "orders", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "supplier_id" - t.text "note" - t.datetime "starts" - t.datetime "ends" - t.string "state", default: "open" - t.integer "lock_version", default: 0, null: false - t.integer "updated_by_user_id" - t.decimal "foodcoop_result", precision: 8, scale: 2 - t.integer "created_by_user_id" - t.datetime "boxfill" - t.date "pickup" - t.integer "invoice_id" - t.datetime "last_sent_mail" - t.integer "end_action", default: 0, null: false - t.decimal "transport", precision: 8, scale: 2 - t.index ["state"], name: "index_orders_on_state" - end - - create_table "page_versions", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "page_id" - t.integer "lock_version" - t.text "body" - t.integer "updated_by" - t.integer "redirect" - t.integer "parent_id" - t.datetime "updated_at" - t.index ["page_id"], name: "index_page_versions_on_page_id" - end - - create_table "pages", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "title" - t.text "body" - t.string "permalink" - t.integer "lock_version", default: 0 - t.integer "updated_by" - t.integer "redirect" - t.integer "parent_id" - t.datetime "created_at" - t.datetime "updated_at" - t.index ["permalink"], name: "index_pages_on_permalink" - t.index ["title"], name: "index_pages_on_title" - end - - create_table "periodic_task_groups", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.date "next_task_date" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - end - - create_table "poll_choices", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "poll_vote_id", null: false - t.integer "choice", null: false - t.integer "value", null: false - t.index ["poll_vote_id", "choice"], name: "index_poll_choices_on_poll_vote_id_and_choice", unique: true - end - - create_table "poll_votes", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "poll_id", null: false - t.integer "user_id", null: false - t.integer "ordergroup_id" - t.text "note" - t.datetime "created_at" - t.datetime "updated_at" - t.index ["poll_id", "user_id", "ordergroup_id"], name: "index_poll_votes_on_poll_id_and_user_id_and_ordergroup_id", unique: true - end - - create_table "polls", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "created_by_user_id", null: false - t.string "name", null: false - t.text "description" - t.datetime "starts" - t.datetime "ends" - t.boolean "one_vote_per_ordergroup", default: false, null: false - t.text "required_ordergroup_custom_fields" - t.text "required_user_custom_fields" - t.integer "voting_method", null: false - t.text "choices", null: false - t.integer "final_choice" - t.integer "multi_select_count", default: 0, null: false - t.integer "min_points" - t.integer "max_points" - t.datetime "created_at" - t.datetime "updated_at" - t.index ["final_choice"], name: "index_polls_on_final_choice" - end - - create_table "printer_job_updates", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "printer_job_id", null: false - t.datetime "created_at", null: false - t.string "state", null: false - t.text "message" - t.index ["printer_job_id", "created_at"], name: "index_printer_job_updates_on_printer_job_id_and_created_at" - end - - create_table "printer_jobs", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "order_id" - t.string "document", null: false - t.integer "created_by_user_id", null: false - t.integer "finished_by_user_id" - t.datetime "finished_at" - t.index ["finished_at"], name: "index_printer_jobs_on_finished_at" - end - - create_table "settings", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "var", null: false - t.text "value" - t.integer "thing_id" - t.string "thing_type", limit: 30 - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.index ["thing_type", "thing_id", "var"], name: "index_settings_on_thing_type_and_thing_id_and_var", unique: true - end - - create_table "stock_changes", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "stock_event_id" - t.integer "order_id" - t.integer "stock_article_id" - t.integer "quantity", default: 0 - t.datetime "created_at" - t.index ["stock_article_id"], name: "index_stock_changes_on_stock_article_id" - t.index ["stock_event_id"], name: "index_stock_changes_on_stock_event_id" - end - - create_table "stock_events", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.integer "supplier_id" - t.date "date" - t.datetime "created_at" - t.text "note" - t.integer "invoice_id" - t.string "type", null: false - t.index ["supplier_id"], name: "index_stock_events_on_supplier_id" - end - - create_table "supplier_categories", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "name", null: false - t.string "description" - t.integer "financial_transaction_class_id", null: false - t.integer "bank_account_id" - end - - create_table "suppliers", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "name", default: "", null: false - t.string "address", default: "", null: false - t.string "phone", default: "", null: false - t.string "phone2" - t.string "fax" - t.string "email" - t.string "url" - t.string "contact_person" - t.string "customer_number" - t.string "delivery_days" - t.string "order_howto" - t.string "note" - t.string "min_order_quantity" - t.datetime "deleted_at" - t.string "shared_sync_method" - t.string "iban" - t.integer "supplier_category_id", null: false - t.string "supplier_remote_source" - t.string "external_uuid" - t.datetime "unit_migration_completed" - t.index ["external_uuid"], name: "index_suppliers_on_external_uuid", unique: true - t.index ["name"], name: "index_suppliers_on_name", unique: true - end - - create_table "tasks", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "name", default: "", null: false - t.text "description" - t.date "due_date" - t.boolean "done", default: false - t.integer "workgroup_id" - t.datetime "created_on", null: false - t.datetime "updated_on", null: false - t.integer "required_users", default: 1 - t.integer "duration", default: 1 - t.integer "periodic_task_group_id" - t.integer "created_by_user_id" - t.index ["due_date"], name: "index_tasks_on_due_date" - t.index ["name"], name: "index_tasks_on_name" - t.index ["workgroup_id"], name: "index_tasks_on_workgroup_id" - end - - create_table "users", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci", force: :cascade do |t| - t.string "nick" - t.string "password_hash", default: "", null: false - t.string "password_salt", default: "", null: false - t.string "first_name", default: "", null: false - t.string "last_name", default: "", null: false - t.string "email", default: "", null: false - t.string "phone" - t.datetime "created_on", null: false - t.string "reset_password_token" - t.datetime "reset_password_expires" - t.datetime "last_login" - t.datetime "last_activity" - t.datetime "deleted_at" - t.string "iban" - t.string "attachment_mime" - t.binary "attachment_data", limit: 16777215 - t.index ["email"], name: "index_users_on_email", unique: true - t.index ["nick"], name: "index_users_on_nick", unique: true - end - - add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id" +ActiveRecord::Schema.define(version: 20_231_210_181_807) do + create_table 'active_storage_attachments', options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'name', null: false + t.string 'record_type', null: false + t.bigint 'record_id', null: false + t.bigint 'blob_id', null: false + t.datetime 'created_at', null: false + t.index ['blob_id'], name: 'index_active_storage_attachments_on_blob_id' + t.index %w[record_type record_id name blob_id], name: 'index_active_storage_attachments_uniqueness', unique: true + end + + create_table 'active_storage_blobs', options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'key', null: false + t.string 'filename', null: false + t.string 'content_type' + t.text 'metadata' + t.bigint 'byte_size', null: false + t.string 'checksum', null: false + t.datetime 'created_at', null: false + t.index ['key'], name: 'index_active_storage_blobs_on_key', unique: true + end + + create_table 'article_categories', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'name', default: '', null: false + t.string 'description' + t.index ['name'], name: 'index_article_categories_on_name', unique: true + end + + create_table 'article_unit_ratios', options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.bigint 'article_version_id', null: false + t.integer 'sort', null: false + t.decimal 'quantity', precision: 8, scale: 3, null: false + t.string 'unit' + t.index ['article_version_id'], name: 'index_article_unit_ratios_on_article_version_id' + t.index ['sort'], name: 'index_article_unit_ratios_on_sort' + end + + create_table 'article_units', id: false, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'unit', null: false + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.index ['unit'], name: 'index_article_units_on_unit', unique: true + end + + create_table 'article_versions', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'article_id', null: false + t.decimal 'price', precision: 8, scale: 2, default: '0.0', null: false + t.decimal 'tax', precision: 8, scale: 2, default: '0.0', null: false + t.decimal 'deposit', precision: 8, scale: 2, default: '0.0', null: false + t.datetime 'created_at' + t.string 'name', default: '', null: false + t.integer 'article_category_id', default: 0, null: false + t.string 'unit' + t.string 'note' + t.boolean 'availability', default: true, null: false + t.string 'manufacturer' + t.string 'origin' + t.string 'order_number' + t.datetime 'updated_at' + t.string 'supplier_order_unit' + t.string 'price_unit' + t.string 'billing_unit' + t.string 'group_order_unit' + t.decimal 'group_order_granularity', precision: 8, scale: 3, default: '1.0', null: false + t.float 'minimum_order_quantity' + t.index ['article_category_id'], name: 'index_article_versions_on_article_category_id' + t.index %w[article_id created_at], name: 'index_article_versions_on_article_id_and_created_at', unique: true + end + + create_table 'articles', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'supplier_id', default: 0, null: false + t.datetime 'shared_updated_on' + t.datetime 'created_at' + t.datetime 'deleted_at' + t.string 'type' + t.integer 'quantity', default: 0 + t.index ['supplier_id'], name: 'index_articles_on_supplier_id' + t.index ['type'], name: 'index_articles_on_type' + end + + create_table 'assignments', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'user_id', default: 0, null: false + t.integer 'task_id', default: 0, null: false + t.boolean 'accepted', default: false + t.index %w[user_id task_id], name: 'index_assignments_on_user_id_and_task_id', unique: true + end + + create_table 'bank_accounts', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'name', null: false + t.string 'iban' + t.string 'description' + t.decimal 'balance', precision: 12, scale: 2, default: '0.0', null: false + t.datetime 'last_import' + t.string 'import_continuation_point' + t.integer 'bank_gateway_id' + end + + create_table 'bank_gateways', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'name', null: false + t.string 'url', null: false + t.string 'authorization' + t.integer 'unattended_user_id' + end + + create_table 'bank_transactions', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'bank_account_id', null: false + t.string 'external_id' + t.date 'date' + t.decimal 'amount', precision: 8, scale: 2, null: false + t.string 'iban' + t.string 'reference' + t.text 'text' + t.text 'receipt' + t.integer 'financial_link_id' + t.index ['financial_link_id'], name: 'index_bank_transactions_on_financial_link_id' + end + + create_table 'documents', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'name' + t.string 'mime' + t.binary 'data', limit: 16_777_215 + t.integer 'created_by_user_id' + t.datetime 'created_at' + t.datetime 'updated_at' + t.integer 'parent_id' + t.index ['parent_id'], name: 'index_documents_on_parent_id' + end + + create_table 'financial_links', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci ROW_FORMAT=COMPACT', force: :cascade do |t| + t.text 'note' + end + + create_table 'financial_transaction_classes', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'name', null: false + t.boolean 'ignore_for_account_balance', default: false, null: false + end + + create_table 'financial_transaction_types', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'name', null: false + t.integer 'financial_transaction_class_id', null: false + t.string 'name_short' + t.integer 'bank_account_id' + t.index ['name_short'], name: 'index_financial_transaction_types_on_name_short' + end + + create_table 'financial_transactions', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'ordergroup_id' + t.decimal 'amount', precision: 8, scale: 2, default: '0.0', null: false + t.text 'note', null: false + t.integer 'user_id', default: 0, null: false + t.datetime 'created_on', null: false + t.integer 'financial_link_id' + t.integer 'financial_transaction_type_id', null: false + t.integer 'reverts_id' + t.integer 'group_order_id' + t.index ['ordergroup_id'], name: 'index_financial_transactions_on_ordergroup_id' + t.index ['reverts_id'], name: 'index_financial_transactions_on_reverts_id', unique: true + end + + create_table 'group_order_article_quantities', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'group_order_article_id', default: 0, null: false + t.decimal 'quantity', precision: 8, scale: 3, default: '0.0', null: false + t.decimal 'tolerance', precision: 8, scale: 3, default: '0.0', null: false + t.datetime 'created_on', null: false + t.index ['group_order_article_id'], name: 'index_group_order_article_quantities_on_group_order_article_id' + end + + create_table 'group_order_articles', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'group_order_id', default: 0, null: false + t.integer 'order_article_id', default: 0, null: false + t.decimal 'quantity', precision: 8, scale: 3, default: '0.0', null: false + t.decimal 'tolerance', precision: 8, scale: 3, default: '0.0', null: false + t.datetime 'updated_on', null: false + t.decimal 'result', precision: 8, scale: 3 + t.decimal 'result_computed', precision: 8, scale: 3 + t.index %w[group_order_id order_article_id], name: 'goa_index', unique: true + t.index ['group_order_id'], name: 'index_group_order_articles_on_group_order_id' + t.index ['order_article_id'], name: 'index_group_order_articles_on_order_article_id' + end + + create_table 'group_orders', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'ordergroup_id' + t.integer 'order_id', default: 0, null: false + t.decimal 'price', precision: 8, scale: 2, default: '0.0', null: false + t.integer 'lock_version', default: 0, null: false + t.datetime 'updated_on', null: false + t.integer 'updated_by_user_id' + t.decimal 'transport', precision: 8, scale: 2 + t.index ['order_id'], name: 'index_group_orders_on_order_id' + t.index %w[ordergroup_id order_id], name: 'index_group_orders_on_ordergroup_id_and_order_id', unique: true + t.index ['ordergroup_id'], name: 'index_group_orders_on_ordergroup_id' + end + + create_table 'groups', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'type', default: '', null: false + t.string 'name', default: '', null: false + t.string 'description' + t.decimal 'account_balance', precision: 12, scale: 2, default: '0.0', null: false + t.datetime 'created_on', null: false + t.boolean 'role_admin', default: false, null: false + t.boolean 'role_suppliers', default: false, null: false + t.boolean 'role_article_meta', default: false, null: false + t.boolean 'role_finance', default: false, null: false + t.boolean 'role_orders', default: false, null: false + t.datetime 'deleted_at' + t.string 'contact_person' + t.string 'contact_phone' + t.string 'contact_address' + t.text 'stats' + t.integer 'next_weekly_tasks_number', default: 8 + t.boolean 'ignore_apple_restriction', default: false + t.boolean 'role_invoices', default: false, null: false + t.date 'break_start' + t.date 'break_end' + t.boolean 'role_pickups', default: false, null: false + t.index ['name'], name: 'index_groups_on_name', unique: true + end + + create_table 'invites', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'token', default: '', null: false + t.datetime 'expires_at', null: false + t.integer 'group_id', default: 0, null: false + t.integer 'user_id', default: 0, null: false + t.string 'email', default: '', null: false + t.index ['token'], name: 'index_invites_on_token' + end + + create_table 'invoices', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'supplier_id' + t.string 'number' + t.date 'date' + t.date 'paid_on' + t.text 'note' + t.decimal 'amount', 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.datetime 'created_at' + t.datetime 'updated_at' + t.integer 'created_by_user_id' + t.string 'attachment_mime' + t.binary 'attachment_data', limit: 16_777_215 + t.integer 'financial_link_id' + t.index ['supplier_id'], name: 'index_invoices_on_supplier_id' + end + + create_table 'links', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'name', null: false + t.string 'url', null: false + t.integer 'workgroup_id' + t.boolean 'indirect', default: false, null: false + t.string 'authorization' + end + + create_table 'mail_delivery_status', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.datetime 'created_at' + t.string 'email', null: false + t.string 'message', null: false + t.string 'attachment_mime' + t.binary 'attachment_data', limit: 16_777_215 + t.index ['email'], name: 'index_mail_delivery_status_on_email' + end + + create_table 'memberships', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'group_id', default: 0, null: false + t.integer 'user_id', default: 0, null: false + t.index %w[user_id group_id], name: 'index_memberships_on_user_id_and_group_id', unique: true + end + + create_table 'message_recipients', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'message_id', null: false + t.integer 'user_id', null: false + t.integer 'email_state', default: 0, null: false + t.datetime 'read_at' + t.index ['message_id'], name: 'index_message_recipients_on_message_id' + t.index %w[user_id read_at], name: 'index_message_recipients_on_user_id_and_read_at' + end + + create_table 'messages', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'sender_id' + t.string 'subject', null: false + t.text 'body' + t.boolean 'private', default: false + t.datetime 'created_at' + t.integer 'reply_to' + t.integer 'group_id' + t.string 'salt' + t.binary 'received_email', limit: 16_777_215 + end + + create_table 'oauth_access_grants', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'resource_owner_id', null: false + t.integer 'application_id', null: false + t.string 'token', null: false + t.integer 'expires_in', null: false + t.text 'redirect_uri', null: false + t.datetime 'created_at', null: false + t.datetime 'revoked_at' + t.string 'scopes' + t.index ['token'], name: 'index_oauth_access_grants_on_token', unique: true + end + + create_table 'oauth_access_tokens', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'resource_owner_id' + t.integer 'application_id' + t.string 'token', null: false + t.string 'refresh_token' + t.integer 'expires_in' + t.datetime 'revoked_at' + t.datetime 'created_at', null: false + t.string 'scopes' + t.index ['refresh_token'], name: 'index_oauth_access_tokens_on_refresh_token', unique: true + t.index ['resource_owner_id'], name: 'index_oauth_access_tokens_on_resource_owner_id' + t.index ['token'], name: 'index_oauth_access_tokens_on_token', unique: true + end + + create_table 'oauth_applications', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'name', null: false + t.string 'uid', null: false + t.string 'secret', null: false + t.text 'redirect_uri', null: false + t.string 'scopes', default: '', null: false + t.datetime 'created_at' + t.datetime 'updated_at' + t.boolean 'confidential', default: true, null: false + t.index ['uid'], name: 'index_oauth_applications_on_uid', unique: true + end + + create_table 'order_articles', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'order_id', default: 0, null: false + t.decimal 'quantity', precision: 8, scale: 3, default: '0.0', null: false + t.decimal 'tolerance', precision: 8, scale: 3, default: '0.0', null: false + t.decimal 'units_to_order', precision: 8, scale: 3, default: '0.0', null: false + t.integer 'lock_version', default: 0, null: false + t.integer 'article_version_id', null: false + t.decimal 'units_billed', precision: 8, scale: 3 + t.decimal 'units_received', precision: 8, scale: 3 + t.index ['article_version_id'], name: 'index_order_articles_on_article_version_id' + t.index %w[order_id article_version_id], name: 'index_order_articles_on_order_id_and_article_version_id', unique: true + t.index ['order_id'], name: 'index_order_articles_on_order_id' + end + + create_table 'order_comments', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'order_id' + t.integer 'user_id' + t.text 'text' + t.datetime 'created_at' + t.index ['order_id'], name: 'index_order_comments_on_order_id' + end + + create_table 'orders', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'supplier_id' + t.text 'note' + t.datetime 'starts' + t.datetime 'ends' + t.string 'state', default: 'open' + t.integer 'lock_version', default: 0, null: false + t.integer 'updated_by_user_id' + t.decimal 'foodcoop_result', precision: 8, scale: 2 + t.integer 'created_by_user_id' + t.datetime 'boxfill' + t.date 'pickup' + t.integer 'invoice_id' + t.datetime 'last_sent_mail' + t.integer 'end_action', default: 0, null: false + t.decimal 'transport', precision: 8, scale: 2 + t.index ['state'], name: 'index_orders_on_state' + end + + create_table 'page_versions', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'page_id' + t.integer 'lock_version' + t.text 'body' + t.integer 'updated_by' + t.integer 'redirect' + t.integer 'parent_id' + t.datetime 'updated_at' + t.index ['page_id'], name: 'index_page_versions_on_page_id' + end + + create_table 'pages', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'title' + t.text 'body' + t.string 'permalink' + t.integer 'lock_version', default: 0 + t.integer 'updated_by' + t.integer 'redirect' + t.integer 'parent_id' + t.datetime 'created_at' + t.datetime 'updated_at' + t.index ['permalink'], name: 'index_pages_on_permalink' + t.index ['title'], name: 'index_pages_on_title' + end + + create_table 'periodic_task_groups', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.date 'next_task_date' + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + end + + create_table 'poll_choices', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'poll_vote_id', null: false + t.integer 'choice', null: false + t.integer 'value', null: false + t.index %w[poll_vote_id choice], name: 'index_poll_choices_on_poll_vote_id_and_choice', unique: true + end + + create_table 'poll_votes', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'poll_id', null: false + t.integer 'user_id', null: false + t.integer 'ordergroup_id' + t.text 'note' + t.datetime 'created_at' + t.datetime 'updated_at' + t.index %w[poll_id user_id ordergroup_id], name: 'index_poll_votes_on_poll_id_and_user_id_and_ordergroup_id', unique: true + end + + create_table 'polls', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'created_by_user_id', null: false + t.string 'name', null: false + t.text 'description' + t.datetime 'starts' + t.datetime 'ends' + t.boolean 'one_vote_per_ordergroup', default: false, null: false + t.text 'required_ordergroup_custom_fields' + t.text 'required_user_custom_fields' + t.integer 'voting_method', null: false + t.text 'choices', null: false + t.integer 'final_choice' + t.integer 'multi_select_count', default: 0, null: false + t.integer 'min_points' + t.integer 'max_points' + t.datetime 'created_at' + t.datetime 'updated_at' + t.index ['final_choice'], name: 'index_polls_on_final_choice' + end + + create_table 'printer_job_updates', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'printer_job_id', null: false + t.datetime 'created_at', null: false + t.string 'state', null: false + t.text 'message' + t.index %w[printer_job_id created_at], name: 'index_printer_job_updates_on_printer_job_id_and_created_at' + end + + create_table 'printer_jobs', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'order_id' + t.string 'document', null: false + t.integer 'created_by_user_id', null: false + t.integer 'finished_by_user_id' + t.datetime 'finished_at' + t.index ['finished_at'], name: 'index_printer_jobs_on_finished_at' + end + + create_table 'settings', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'var', null: false + t.text 'value' + t.integer 'thing_id' + t.string 'thing_type', limit: 30 + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.index %w[thing_type thing_id var], name: 'index_settings_on_thing_type_and_thing_id_and_var', unique: true + end + + create_table 'stock_changes', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'stock_event_id' + t.integer 'order_id' + t.integer 'stock_article_id' + t.integer 'quantity', default: 0 + t.datetime 'created_at' + t.index ['stock_article_id'], name: 'index_stock_changes_on_stock_article_id' + t.index ['stock_event_id'], name: 'index_stock_changes_on_stock_event_id' + end + + create_table 'stock_events', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.integer 'supplier_id' + t.date 'date' + t.datetime 'created_at' + t.text 'note' + t.integer 'invoice_id' + t.string 'type', null: false + t.index ['supplier_id'], name: 'index_stock_events_on_supplier_id' + end + + create_table 'supplier_categories', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'name', null: false + t.string 'description' + t.integer 'financial_transaction_class_id', null: false + t.integer 'bank_account_id' + end + + create_table 'suppliers', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'name', default: '', null: false + t.string 'address', default: '', null: false + t.string 'phone', default: '', null: false + t.string 'phone2' + t.string 'fax' + t.string 'email' + t.string 'url' + t.string 'contact_person' + t.string 'customer_number' + t.string 'delivery_days' + t.string 'order_howto' + t.string 'note' + t.string 'min_order_quantity' + t.datetime 'deleted_at' + t.string 'shared_sync_method' + t.string 'iban' + t.integer 'supplier_category_id', null: false + t.string 'supplier_remote_source' + t.string 'external_uuid' + t.datetime 'unit_migration_completed' + t.index ['external_uuid'], name: 'index_suppliers_on_external_uuid', unique: true + t.index ['name'], name: 'index_suppliers_on_name', unique: true + end + + create_table 'tasks', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'name', default: '', null: false + t.text 'description' + t.date 'due_date' + t.boolean 'done', default: false + t.integer 'workgroup_id' + t.datetime 'created_on', null: false + t.datetime 'updated_on', null: false + t.integer 'required_users', default: 1 + t.integer 'duration', default: 1 + t.integer 'periodic_task_group_id' + t.integer 'created_by_user_id' + t.index ['due_date'], name: 'index_tasks_on_due_date' + t.index ['name'], name: 'index_tasks_on_name' + t.index ['workgroup_id'], name: 'index_tasks_on_workgroup_id' + end + + create_table 'users', id: :integer, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci', force: :cascade do |t| + t.string 'nick' + t.string 'password_hash', default: '', null: false + t.string 'password_salt', default: '', null: false + t.string 'first_name', default: '', null: false + t.string 'last_name', default: '', null: false + t.string 'email', default: '', null: false + t.string 'phone' + t.datetime 'created_on', null: false + t.string 'reset_password_token' + t.datetime 'reset_password_expires' + t.datetime 'last_login' + t.datetime 'last_activity' + t.datetime 'deleted_at' + t.string 'iban' + t.string 'attachment_mime' + t.binary 'attachment_data', limit: 16_777_215 + t.index ['email'], name: 'index_users_on_email', unique: true + t.index ['nick'], name: 'index_users_on_nick', unique: true + end + + add_foreign_key 'active_storage_attachments', 'active_storage_blobs', column: 'blob_id' end diff --git a/db/seeds/hackathon.seeds.rb b/db/seeds/hackathon.seeds.rb index 2d0b5161..81d88fd3 100644 --- a/db/seeds/hackathon.seeds.rb +++ b/db/seeds/hackathon.seeds.rb @@ -2,8 +2,8 @@ ## Financial transaction classes -FinancialTransactionClass.create!(:id => 1, :name => 'Standard') -FinancialTransactionClass.create!(:id => 2, :name => 'Foodsoft') +FinancialTransactionClass.create!(id: 1, name: 'Standard') +FinancialTransactionClass.create!(id: 2, name: 'Foodsoft') ## Article units @@ -13,88 +13,128 @@ ## Suppliers & articles -SupplierCategory.create!(:id => 1, :name => "Other", :financial_transaction_class_id => 1) +SupplierCategory.create!(id: 1, name: 'Other', financial_transaction_class_id: 1) Supplier.create!([ - { :id => 1, :name => "Hackathon", :supplier_category_id => 1, :address => "Smallstreet 1, Cookilage", :phone => "0123456789", :email => "info@bbakery.test", :min_order_quantity => "100", :unit_migration_completed => Time.now } + { id: 1, name: 'Hackathon', supplier_category_id: 1, address: 'Smallstreet 1, Cookilage', + phone: '0123456789', email: 'info@bbakery.test', min_order_quantity: '100', unit_migration_completed: Time.now } ]) -ArticleCategory.create!(:id => 1, :name => "Other", :description => "other, misc, unknown") -ArticleCategory.create!(:id => 2, :name => "Fruit") -ArticleCategory.create!(:id => 3, :name => "Vegetables") -ArticleCategory.create!(:id => 4, :name => "Potatoes & onions") -ArticleCategory.create!(:id => 5, :name => "Bread & Bakery") -ArticleCategory.create!(:id => 6, :name => "Drinks", :description => "juice, fruit juice, vegetable juice, soda") -ArticleCategory.create!(:id => 7, :name => "Herbs & Spices") -ArticleCategory.create!(:id => 8, :name => "Milk & products", :description => "milk, butter, cream, yoghurt, cheese, eggs, milk substitutes") -ArticleCategory.create!(:id => 9, :name => "Fish & Sea") -ArticleCategory.create!(:id => 10, :name => "Meat") -ArticleCategory.create!(:id => 11, :name => "Oils & Fats") -ArticleCategory.create!(:id => 12, :name => "Grains & Legumes") -ArticleCategory.create!(:id => 13, :name => "Nuts & Seeds") -ArticleCategory.create!(:id => 14, :name => "Sugar & Sweets") - -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Carrots", article_category_id: 3, unit: nil, price: 3, tax: 7.0, deposit: "0.0", supplier_order_unit: "KGM", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "KGM", group_order_granularity: 0.001 }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Pumpkin", article_category_id: 3, unit: nil, price: 1.5, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "XPP", :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1.3, :unit => 'KGM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Bread", article_category_id: 5, unit: nil, price: 2.1, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "XPP", group_order_granularity: 0.5, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 700, :unit => 'GRM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Bread rolls", article_category_id: 5, unit: nil, price: 1, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "XPP", group_order_unit: "XPP", minimum_order_quantity: 5, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 350, :unit => 'GRM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Muesli", article_category_id: 13, unit: nil, price: 2.5, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "XPP", billing_unit: "XPP", group_order_unit: "XPP", - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 500, :unit => 'GRM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Smoked tofu", article_category_id: 8, unit: nil, price: 2.4, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "HGM", billing_unit: "GRM", group_order_unit: "XPP", - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 160, :unit => 'GRM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Beer", article_category_id: 6, unit: nil, price: 52, tax: 7.0, deposit: "0.0", supplier_order_unit: "XCR", price_unit: "XBO", billing_unit: "XBO", group_order_unit: "XBO", - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 20, :unit => 'XBO' }), ArticleUnitRatio.new({ :sort => 2, :quantity => 10, :unit => 'LTR' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Detergent", article_category_id: 1, unit: nil, price: 20, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "LTR", billing_unit: "LTR", group_order_unit: "LTR", group_order_granularity: 0.001, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 2, :quantity => 20, :unit => 'LTR' }), ArticleUnitRatio.new({ :sort => 2, :quantity => 25, :unit => 'KGM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Rice", article_category_id: 12, unit: nil, price: 6.75, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "KGM", group_order_granularity: 0.05, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 25, :unit => 'KGM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Potatoes", article_category_id: 3, unit: nil, price: 1.5, tax: 7.0, deposit: "0.0", supplier_order_unit: "KGM", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "GRM" }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Wheat", article_category_id: 12, unit: nil, price: 25, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "KGM", group_order_granularity: 0.05, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 25, :unit => 'KGM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Oranges", article_category_id: 2, unit: nil, price: 36, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "KGM", group_order_granularity: 0.05, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 12, :unit => 'KGM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Lentils", article_category_id: 12, unit: nil, price: 2.7, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "KGM", group_order_granularity: 0.05, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 500, :unit => 'GRM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Oyster mushrooms", article_category_id: 3, unit: nil, price: 3, tax: 7.0, deposit: "0.0", supplier_order_unit: "KGM", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "KGM", group_order_granularity: 0.001, minimum_order_quantity: 1.2 }) +ArticleCategory.create!(id: 1, name: 'Other', description: 'other, misc, unknown') +ArticleCategory.create!(id: 2, name: 'Fruit') +ArticleCategory.create!(id: 3, name: 'Vegetables') +ArticleCategory.create!(id: 4, name: 'Potatoes & onions') +ArticleCategory.create!(id: 5, name: 'Bread & Bakery') +ArticleCategory.create!(id: 6, name: 'Drinks', description: 'juice, fruit juice, vegetable juice, soda') +ArticleCategory.create!(id: 7, name: 'Herbs & Spices') +ArticleCategory.create!(id: 8, name: 'Milk & products', + description: 'milk, butter, cream, yoghurt, cheese, eggs, milk substitutes') +ArticleCategory.create!(id: 9, name: 'Fish & Sea') +ArticleCategory.create!(id: 10, name: 'Meat') +ArticleCategory.create!(id: 11, name: 'Oils & Fats') +ArticleCategory.create!(id: 12, name: 'Grains & Legumes') +ArticleCategory.create!(id: 13, name: 'Nuts & Seeds') +ArticleCategory.create!(id: 14, name: 'Sugar & Sweets') + +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Carrots', article_category_id: 3, unit: nil, price: 3, tax: 7.0, + deposit: '0.0', supplier_order_unit: 'KGM', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'KGM', group_order_granularity: 0.001 }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Pumpkin', article_category_id: 3, unit: nil, price: 1.5, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'XPP', + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1.3, unit: 'KGM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Bread', article_category_id: 5, unit: nil, price: 2.1, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'XPP', group_order_granularity: 0.5, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 700, unit: 'GRM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Bread rolls', article_category_id: 5, unit: nil, price: 1, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'XPP', group_order_unit: 'XPP', minimum_order_quantity: 5, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 350, unit: 'GRM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Muesli', article_category_id: 13, unit: nil, price: 2.5, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'XPP', billing_unit: 'XPP', group_order_unit: 'XPP', + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 500, unit: 'GRM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Smoked tofu', article_category_id: 8, unit: nil, price: 2.4, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'HGM', billing_unit: 'GRM', group_order_unit: 'XPP', + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 160, unit: 'GRM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Beer', article_category_id: 6, unit: nil, price: 52, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XCR', price_unit: 'XBO', billing_unit: 'XBO', group_order_unit: 'XBO', + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 20, unit: 'XBO' }), ArticleUnitRatio.new({ sort: 2, quantity: 10, unit: 'LTR' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Detergent', article_category_id: 1, unit: nil, price: 20, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'LTR', billing_unit: 'LTR', group_order_unit: 'LTR', group_order_granularity: 0.001, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 2, quantity: 20, unit: 'LTR' }), ArticleUnitRatio.new({ sort: 2, quantity: 25, unit: 'KGM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Rice', article_category_id: 12, unit: nil, price: 6.75, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'KGM', group_order_granularity: 0.05, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 25, unit: 'KGM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Potatoes', article_category_id: 3, unit: nil, price: 1.5, tax: 7.0, + deposit: '0.0', supplier_order_unit: 'KGM', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'GRM' }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Wheat', article_category_id: 12, unit: nil, price: 25, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'KGM', group_order_granularity: 0.05, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 25, unit: 'KGM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Oranges', article_category_id: 2, unit: nil, price: 36, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'KGM', group_order_granularity: 0.05, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 12, unit: 'KGM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Lentils', article_category_id: 12, unit: nil, price: 2.7, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'KGM', group_order_granularity: 0.05, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 500, unit: 'GRM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Oyster mushrooms', article_category_id: 3, unit: nil, + price: 3, tax: 7.0, deposit: '0.0', supplier_order_unit: 'KGM', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'KGM', group_order_granularity: 0.001, minimum_order_quantity: 1.2 }) Supplier.create!([ - { :id => 2, :name => "Unit migration test", :supplier_category_id => 1, :address => "Smallstreet 2, Cookilage", :phone => "0123456789", :email => "info@bbakery.test", :min_order_quantity => "100", :unit_migration_completed => nil } + { id: 2, name: 'Unit migration test', supplier_category_id: 1, address: 'Smallstreet 2, Cookilage', + phone: '0123456789', email: 'info@bbakery.test', min_order_quantity: '100', unit_migration_completed: nil } ]) -Article.create!({ supplier_id: 2, quantity: 0 }).article_versions.create({ name: "Goat cheese", article_category_id: 8, unit: "250g", price: 3, tax: 7.0, deposit: "0.0", supplier_order_unit: nil, price_unit: nil, billing_unit: nil, group_order_unit: nil, group_order_granularity: 1 }) -Article.create!({ supplier_id: 2, quantity: 0 }).article_versions.create({ name: "Butter", article_category_id: 8, unit: "4x250g", price: 3, tax: 7.0, deposit: "0.0", supplier_order_unit: nil, price_unit: 'XPP', billing_unit: 'XPP', group_order_unit: 'XPP', group_order_granularity: 1, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 4, :unit => 'XPP' })] }) -Article.create!({ supplier_id: 2, quantity: 0 }).article_versions.create({ name: "Bread", article_category_id: 5, unit: "pc", price: 3, tax: 7.0, deposit: "0.0", supplier_order_unit: nil, price_unit: nil, billing_unit: nil, group_order_unit: nil, group_order_granularity: 1 }) +Article.create!({ supplier_id: 2, + quantity: 0 }).article_versions.create({ name: 'Goat cheese', article_category_id: 8, unit: '250g', price: 3, tax: 7.0, + deposit: '0.0', supplier_order_unit: nil, price_unit: nil, billing_unit: nil, group_order_unit: nil, group_order_granularity: 1 }) +Article.create!({ supplier_id: 2, + quantity: 0 }).article_versions.create({ name: 'Butter', article_category_id: 8, unit: '4x250g', price: 3, tax: 7.0, deposit: '0.0', supplier_order_unit: nil, price_unit: 'XPP', billing_unit: 'XPP', group_order_unit: 'XPP', group_order_granularity: 1, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 4, unit: 'XPP' })] }) +Article.create!({ supplier_id: 2, + quantity: 0 }).article_versions.create({ name: 'Bread', article_category_id: 5, unit: 'pc', price: 3, tax: 7.0, + deposit: '0.0', supplier_order_unit: nil, price_unit: nil, billing_unit: nil, group_order_unit: nil, group_order_granularity: 1 }) ## 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') -User.create!(:id => 2, :nick => "john", :password => "secret", :first_name => "John", :last_name => "Doe", :email => "john@doe.test", :created_on => 'Sun, 19 Jan 2014 17:38:22 UTC +00:00') -User.create!(:id => 3, :nick => "peter", :password => "secret", :first_name => "Peter", :last_name => "Peters", :email => "peter@peters.test", :created_on => 'Sat, 25 Jan 2014 20:20:36 UTC +00:00') -User.create!(:id => 4, :nick => "jan", :password => "secret", :first_name => "Jan", :last_name => "Lou", :email => "jan@lou.test", :created_on => 'Mon, 27 Jan 2014 16:22:14 UTC +00:00') -User.create!(:id => 5, :nick => "mary", :password => "secret", :first_name => "Mary", :last_name => "Lou", :email => "marie@lou.test", :created_on => 'Mon, 03 Feb 2014 11:47:17 UTC +00:00') - -Workgroup.create!(:id => 1, :name => "Administrators", :description => "System administrators.", :account_balance => 0.0, :created_on => 'Wed, 15 Jan 2014 16:15:33 UTC +00:00', :role_admin => true, :role_suppliers => true, :role_article_meta => true, :role_finance => true, :role_orders => true, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) -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) - -Membership.create!(:group_id => 1, :user_id => 1) -Membership.create!(:group_id => 5, :user_id => 1) -Membership.create!(:group_id => 2, :user_id => 2) -Membership.create!(:group_id => 8, :user_id => 2) -Membership.create!(:group_id => 6, :user_id => 3) -Membership.create!(:group_id => 7, :user_id => 4) -Membership.create!(:group_id => 8, :user_id => 4) -Membership.create!(:group_id => 3, :user_id => 4) -Membership.create!(:group_id => 7, :user_id => 5) -Membership.create!(:group_id => 3, :user_id => 5) -Membership.create!(:group_id => 4, :user_id => 5) +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') +User.create!(id: 2, nick: 'john', password: 'secret', first_name: 'John', last_name: 'Doe', email: 'john@doe.test', + created_on: 'Sun, 19 Jan 2014 17:38:22 UTC +00:00') +User.create!(id: 3, nick: 'peter', password: 'secret', first_name: 'Peter', last_name: 'Peters', + email: 'peter@peters.test', created_on: 'Sat, 25 Jan 2014 20:20:36 UTC +00:00') +User.create!(id: 4, nick: 'jan', password: 'secret', first_name: 'Jan', last_name: 'Lou', email: 'jan@lou.test', + created_on: 'Mon, 27 Jan 2014 16:22:14 UTC +00:00') +User.create!(id: 5, nick: 'mary', password: 'secret', first_name: 'Mary', last_name: 'Lou', email: 'marie@lou.test', + created_on: 'Mon, 03 Feb 2014 11:47:17 UTC +00:00') + +Workgroup.create!(id: 1, name: 'Administrators', description: 'System administrators.', account_balance: 0.0, created_on: 'Wed, 15 Jan 2014 16:15:33 UTC +00:00', role_admin: true, role_suppliers: true, role_article_meta: true, role_finance: true, role_orders: true, + next_weekly_tasks_number: 8, ignore_apple_restriction: false) +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) + +Membership.create!(group_id: 1, user_id: 1) +Membership.create!(group_id: 5, user_id: 1) +Membership.create!(group_id: 2, user_id: 2) +Membership.create!(group_id: 8, user_id: 2) +Membership.create!(group_id: 6, user_id: 3) +Membership.create!(group_id: 7, user_id: 4) +Membership.create!(group_id: 8, user_id: 4) +Membership.create!(group_id: 3, user_id: 4) +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 @@ -102,12 +142,17 @@ ## Finances -FinancialTransactionType.create!(:id => 1, :name => "Foodcoop", :financial_transaction_class_id => 1) - -FinancialTransaction.create!(:id => 1, :ordergroup_id => 5, :amount => -0.35E2, :note => "Membership fee for ordergroup", :user_id => 1, :created_on => 'Sat, 18 Jan 2014 00:38:48 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 3, :ordergroup_id => 6, :amount => -0.35E2, :note => "Membership fee for ordergroup", :user_id => 1, :created_on => 'Sat, 25 Jan 2014 20:20:37 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 4, :ordergroup_id => 7, :amount => -0.35E2, :note => "Membership fee for ordergroup", :user_id => 1, :created_on => 'Mon, 27 Jan 2014 16:22:14 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 5, :ordergroup_id => 5, :amount => 0.35E2, :note => "payment", :user_id => 2, :created_on => 'Wed, 05 Feb 2014 16:49:24 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 6, :ordergroup_id => 8, :amount => 0.90E2, :note => "Bank transfer", :user_id => 2, :created_on => 'Mon, 17 Feb 2014 16:19:34 UTC +00:00', :financial_transaction_type_id => 1) +FinancialTransactionType.create!(id: 1, name: 'Foodcoop', financial_transaction_class_id: 1) + +FinancialTransaction.create!(id: 1, ordergroup_id: 5, amount: -0.35E2, note: 'Membership fee for ordergroup', + user_id: 1, created_on: 'Sat, 18 Jan 2014 00:38:48 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 3, ordergroup_id: 6, amount: -0.35E2, note: 'Membership fee for ordergroup', + user_id: 1, created_on: 'Sat, 25 Jan 2014 20:20:37 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 4, ordergroup_id: 7, amount: -0.35E2, note: 'Membership fee for ordergroup', + user_id: 1, created_on: 'Mon, 27 Jan 2014 16:22:14 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 5, ordergroup_id: 5, amount: 0.35E2, note: 'payment', user_id: 2, + created_on: 'Wed, 05 Feb 2014 16:49:24 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 6, ordergroup_id: 8, amount: 0.90E2, note: 'Bank transfer', user_id: 2, + created_on: 'Mon, 17 Feb 2014 16:19:34 UTC +00:00', financial_transaction_type_id: 1) FoodsoftConfig[:minimum_balance] = '-10000' diff --git a/db/seeds/hackathon_de.seeds.rb b/db/seeds/hackathon_de.seeds.rb index 7cc61eed..3e645e47 100644 --- a/db/seeds/hackathon_de.seeds.rb +++ b/db/seeds/hackathon_de.seeds.rb @@ -2,8 +2,8 @@ ## Financial transaction classes -FinancialTransactionClass.create!(:id => 1, :name => 'Standard') -FinancialTransactionClass.create!(:id => 2, :name => 'Foodsoft') +FinancialTransactionClass.create!(id: 1, name: 'Standard') +FinancialTransactionClass.create!(id: 2, name: 'Foodsoft') ## Article units @@ -13,89 +13,128 @@ ## Suppliers & articles -SupplierCategory.create!(:id => 1, :name => "Other", :financial_transaction_class_id => 1) +SupplierCategory.create!(id: 1, name: 'Other', financial_transaction_class_id: 1) Supplier.create!([ - { :id => 1, :name => "Hackathon", :supplier_category_id => 1, :address => "Smallstreet 1, Cookilage", :phone => "0123456789", :email => "info@bbakery.test", :min_order_quantity => "100", :unit_migration_completed => Time.now } + { id: 1, name: 'Hackathon', supplier_category_id: 1, address: 'Smallstreet 1, Cookilage', + phone: '0123456789', email: 'info@bbakery.test', min_order_quantity: '100', unit_migration_completed: Time.now } ]) -ArticleCategory.create!(:id => 1, :name => "Sonstiges") -ArticleCategory.create!(:id => 2, :name => "Obst") -ArticleCategory.create!(:id => 3, :name => "Gemüse") -ArticleCategory.create!(:id => 4, :name => "Kartoffel & Zwiebel") -ArticleCategory.create!(:id => 5, :name => "Backwaren") -ArticleCategory.create!(:id => 6, :name => "Getränke") -ArticleCategory.create!(:id => 7, :name => "Kräuter & Gewürze") -ArticleCategory.create!(:id => 8, :name => "Mich & Milchprodukte") -ArticleCategory.create!(:id => 9, :name => "Fisch & Meeresfrüchte") -ArticleCategory.create!(:id => 10, :name => "Fleisch") -ArticleCategory.create!(:id => 11, :name => "Öle & Fett") -ArticleCategory.create!(:id => 12, :name => "Getreide & Bohnen") -ArticleCategory.create!(:id => 13, :name => "Nüsse & Samen") -ArticleCategory.create!(:id => 14, :name => "Zucker & Süßigkeiten") - -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Karotten", article_category_id: 3, unit: nil, price: 3, tax: 7.0, deposit: "0.0", supplier_order_unit: "KGM", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "KGM", group_order_granularity: 0.001 }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Kürbis", article_category_id: 3, unit: nil, price: 1.5, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "XPP", :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1.3, :unit => 'KGM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Brot", article_category_id: 5, unit: nil, price: 2.1, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "XPP", group_order_granularity: 0.5, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 700, :unit => 'GRM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Semmeln", article_category_id: 5, unit: nil, price: 1, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "XPP", group_order_unit: "XPP", minimum_order_quantity: 5, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 350, :unit => 'GRM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Müsli", article_category_id: 13, unit: nil, price: 2.5, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "XPP", billing_unit: "XPP", group_order_unit: "XPP", - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 500, :unit => 'GRM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Räuchertofu", article_category_id: 8, unit: nil, price: 2.4, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "HGM", billing_unit: "GRM", group_order_unit: "XPP", - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 160, :unit => 'GRM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Bier", article_category_id: 6, unit: nil, price: 52, tax: 7.0, deposit: "0.0", supplier_order_unit: "XCR", price_unit: "XBO", billing_unit: "XBO", group_order_unit: "XBO", - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 20, :unit => 'XBO' }), ArticleUnitRatio.new({ :sort => 2, :quantity => 10, :unit => 'LTR' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Waschmittel", article_category_id: 1, unit: nil, price: 20, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "LTR", billing_unit: "LTR", group_order_unit: "LTR", group_order_granularity: 0.001, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 2, :quantity => 20, :unit => 'LTR' }), ArticleUnitRatio.new({ :sort => 2, :quantity => 25, :unit => 'KGM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Reis", article_category_id: 12, unit: nil, price: 6.75, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "KGM", group_order_granularity: 0.05, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 25, :unit => 'KGM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Kartoffeln", article_category_id: 3, unit: nil, price: 1.5, tax: 7.0, deposit: "0.0", supplier_order_unit: "KGM", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "GRM" }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Weizen", article_category_id: 12, unit: nil, price: 25, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "KGM", group_order_granularity: 0.05, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 25, :unit => 'KGM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Orangen", article_category_id: 2, unit: nil, price: 36, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "KGM", group_order_granularity: 0.05, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 12, :unit => 'KGM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Linsen", article_category_id: 12, unit: nil, price: 2.7, tax: 7.0, deposit: "0.0", supplier_order_unit: "XPP", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "KGM", group_order_granularity: 0.05, - :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 500, :unit => 'GRM' })] }) -Article.create!({ supplier_id: 1, quantity: 0 }).article_versions.create({ name: "Austernpilze", article_category_id: 3, unit: nil, price: 3, tax: 7.0, deposit: "0.0", supplier_order_unit: "KGM", price_unit: "KGM", billing_unit: "KGM", group_order_unit: "KGM", group_order_granularity: 0.001, minimum_order_quantity: 1.2 }) +ArticleCategory.create!(id: 1, name: 'Sonstiges') +ArticleCategory.create!(id: 2, name: 'Obst') +ArticleCategory.create!(id: 3, name: 'Gemüse') +ArticleCategory.create!(id: 4, name: 'Kartoffel & Zwiebel') +ArticleCategory.create!(id: 5, name: 'Backwaren') +ArticleCategory.create!(id: 6, name: 'Getränke') +ArticleCategory.create!(id: 7, name: 'Kräuter & Gewürze') +ArticleCategory.create!(id: 8, name: 'Mich & Milchprodukte') +ArticleCategory.create!(id: 9, name: 'Fisch & Meeresfrüchte') +ArticleCategory.create!(id: 10, name: 'Fleisch') +ArticleCategory.create!(id: 11, name: 'Öle & Fett') +ArticleCategory.create!(id: 12, name: 'Getreide & Bohnen') +ArticleCategory.create!(id: 13, name: 'Nüsse & Samen') +ArticleCategory.create!(id: 14, name: 'Zucker & Süßigkeiten') + +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Karotten', article_category_id: 3, unit: nil, price: 3, tax: 7.0, + deposit: '0.0', supplier_order_unit: 'KGM', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'KGM', group_order_granularity: 0.001 }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Kürbis', article_category_id: 3, unit: nil, price: 1.5, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'XPP', + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1.3, unit: 'KGM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Brot', article_category_id: 5, unit: nil, price: 2.1, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'XPP', group_order_granularity: 0.5, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 700, unit: 'GRM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Semmeln', article_category_id: 5, unit: nil, price: 1, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'XPP', group_order_unit: 'XPP', minimum_order_quantity: 5, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 350, unit: 'GRM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Müsli', article_category_id: 13, unit: nil, price: 2.5, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'XPP', billing_unit: 'XPP', group_order_unit: 'XPP', + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 500, unit: 'GRM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Räuchertofu', article_category_id: 8, unit: nil, price: 2.4, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'HGM', billing_unit: 'GRM', group_order_unit: 'XPP', + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 160, unit: 'GRM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Bier', article_category_id: 6, unit: nil, price: 52, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XCR', price_unit: 'XBO', billing_unit: 'XBO', group_order_unit: 'XBO', + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 20, unit: 'XBO' }), ArticleUnitRatio.new({ sort: 2, quantity: 10, unit: 'LTR' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Waschmittel', article_category_id: 1, unit: nil, price: 20, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'LTR', billing_unit: 'LTR', group_order_unit: 'LTR', group_order_granularity: 0.001, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 2, quantity: 20, unit: 'LTR' }), ArticleUnitRatio.new({ sort: 2, quantity: 25, unit: 'KGM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Reis', article_category_id: 12, unit: nil, price: 6.75, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'KGM', group_order_granularity: 0.05, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 25, unit: 'KGM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Kartoffeln', article_category_id: 3, unit: nil, price: 1.5, tax: 7.0, + deposit: '0.0', supplier_order_unit: 'KGM', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'GRM' }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Weizen', article_category_id: 12, unit: nil, price: 25, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'KGM', group_order_granularity: 0.05, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 25, unit: 'KGM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Orangen', article_category_id: 2, unit: nil, price: 36, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'KGM', group_order_granularity: 0.05, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 12, unit: 'KGM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Linsen', article_category_id: 12, unit: nil, price: 2.7, tax: 7.0, deposit: '0.0', supplier_order_unit: 'XPP', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'KGM', group_order_granularity: 0.05, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 500, unit: 'GRM' })] }) +Article.create!({ supplier_id: 1, + quantity: 0 }).article_versions.create({ name: 'Austernpilze', article_category_id: 3, unit: nil, + price: 3, tax: 7.0, deposit: '0.0', supplier_order_unit: 'KGM', price_unit: 'KGM', billing_unit: 'KGM', group_order_unit: 'KGM', group_order_granularity: 0.001, minimum_order_quantity: 1.2 }) Supplier.create!([ - { :id => 2, :name => "Einheiten-Migrations-Test", :supplier_category_id => 1, :address => "Smallstreet 2, Cookilage", :phone => "0123456789", :email => "info@bbakery.test", :min_order_quantity => "100", :unit_migration_completed => nil } + { id: 2, name: 'Einheiten-Migrations-Test', supplier_category_id: 1, + address: 'Smallstreet 2, Cookilage', phone: '0123456789', email: 'info@bbakery.test', min_order_quantity: '100', unit_migration_completed: nil } ]) -Article.create!({ supplier_id: 2, quantity: 0 }).article_versions.create({ name: "Ziegenkäse", article_category_id: 8, unit: "250g", price: 3, tax: 7.0, deposit: "0.0", supplier_order_unit: nil, price_unit: nil, billing_unit: nil, group_order_unit: nil, group_order_granularity: 1 }) -Article.create!({ supplier_id: 2, quantity: 0 }).article_versions.create({ name: "Butter", article_category_id: 8, unit: "4x250g", price: 3, tax: 7.0, deposit: "0.0", supplier_order_unit: nil, price_unit: 'XPP', billing_unit: 'XPP', group_order_unit: 'XPP', group_order_granularity: 1, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 4, :unit => 'XPP' })] }) -Article.create!({ supplier_id: 2, quantity: 0 }).article_versions.create({ name: "Brot", article_category_id: 5, unit: "Stk", price: 3, tax: 7.0, deposit: "0.0", supplier_order_unit: nil, price_unit: nil, billing_unit: nil, group_order_unit: nil, group_order_granularity: 1 }) +Article.create!({ supplier_id: 2, + quantity: 0 }).article_versions.create({ name: 'Ziegenkäse', article_category_id: 8, unit: '250g', price: 3, tax: 7.0, + deposit: '0.0', supplier_order_unit: nil, price_unit: nil, billing_unit: nil, group_order_unit: nil, group_order_granularity: 1 }) +Article.create!({ supplier_id: 2, + quantity: 0 }).article_versions.create({ name: 'Butter', article_category_id: 8, unit: '4x250g', price: 3, tax: 7.0, deposit: '0.0', supplier_order_unit: nil, price_unit: 'XPP', billing_unit: 'XPP', group_order_unit: 'XPP', group_order_granularity: 1, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 4, unit: 'XPP' })] }) +Article.create!({ supplier_id: 2, + quantity: 0 }).article_versions.create({ name: 'Brot', article_category_id: 5, unit: 'Stk', price: 3, tax: 7.0, + deposit: '0.0', supplier_order_unit: nil, price_unit: nil, billing_unit: nil, group_order_unit: nil, group_order_granularity: 1 }) ## 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') -User.create!(:id => 2, :nick => "john", :password => "secret", :first_name => "John", :last_name => "Doe", :email => "john@doe.test", :created_on => 'Sun, 19 Jan 2014 17:38:22 UTC +00:00') -User.create!(:id => 3, :nick => "peter", :password => "secret", :first_name => "Peter", :last_name => "Peters", :email => "peter@peters.test", :created_on => 'Sat, 25 Jan 2014 20:20:36 UTC +00:00') -User.create!(:id => 4, :nick => "jan", :password => "secret", :first_name => "Jan", :last_name => "Lou", :email => "jan@lou.test", :created_on => 'Mon, 27 Jan 2014 16:22:14 UTC +00:00') -User.create!(:id => 5, :nick => "mary", :password => "secret", :first_name => "Mary", :last_name => "Lou", :email => "marie@lou.test", :created_on => 'Mon, 03 Feb 2014 11:47:17 UTC +00:00') +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') +User.create!(id: 2, nick: 'john', password: 'secret', first_name: 'John', last_name: 'Doe', email: 'john@doe.test', + created_on: 'Sun, 19 Jan 2014 17:38:22 UTC +00:00') +User.create!(id: 3, nick: 'peter', password: 'secret', first_name: 'Peter', last_name: 'Peters', + email: 'peter@peters.test', created_on: 'Sat, 25 Jan 2014 20:20:36 UTC +00:00') +User.create!(id: 4, nick: 'jan', password: 'secret', first_name: 'Jan', last_name: 'Lou', email: 'jan@lou.test', + created_on: 'Mon, 27 Jan 2014 16:22:14 UTC +00:00') +User.create!(id: 5, nick: 'mary', password: 'secret', first_name: 'Mary', last_name: 'Lou', email: 'marie@lou.test', + created_on: 'Mon, 03 Feb 2014 11:47:17 UTC +00:00') User.find(1).settings['profile'] = { language: :de } -Workgroup.create!(:id => 1, :name => "Administrators", :description => "System administrators.", :account_balance => 0.0, :created_on => 'Wed, 15 Jan 2014 16:15:33 UTC +00:00', :role_admin => true, :role_suppliers => true, :role_article_meta => true, :role_finance => true, :role_orders => true, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) -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) - -Membership.create!(:group_id => 1, :user_id => 1) -Membership.create!(:group_id => 5, :user_id => 1) -Membership.create!(:group_id => 2, :user_id => 2) -Membership.create!(:group_id => 8, :user_id => 2) -Membership.create!(:group_id => 6, :user_id => 3) -Membership.create!(:group_id => 7, :user_id => 4) -Membership.create!(:group_id => 8, :user_id => 4) -Membership.create!(:group_id => 3, :user_id => 4) -Membership.create!(:group_id => 7, :user_id => 5) -Membership.create!(:group_id => 3, :user_id => 5) -Membership.create!(:group_id => 4, :user_id => 5) +Workgroup.create!(id: 1, name: 'Administrators', description: 'System administrators.', account_balance: 0.0, created_on: 'Wed, 15 Jan 2014 16:15:33 UTC +00:00', role_admin: true, role_suppliers: true, role_article_meta: true, role_finance: true, role_orders: true, + next_weekly_tasks_number: 8, ignore_apple_restriction: false) +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) + +Membership.create!(group_id: 1, user_id: 1) +Membership.create!(group_id: 5, user_id: 1) +Membership.create!(group_id: 2, user_id: 2) +Membership.create!(group_id: 8, user_id: 2) +Membership.create!(group_id: 6, user_id: 3) +Membership.create!(group_id: 7, user_id: 4) +Membership.create!(group_id: 8, user_id: 4) +Membership.create!(group_id: 3, user_id: 4) +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 @@ -103,12 +142,17 @@ ## Finances -FinancialTransactionType.create!(:id => 1, :name => "Foodcoop", :financial_transaction_class_id => 1) - -FinancialTransaction.create!(:id => 1, :ordergroup_id => 5, :amount => -0.35E2, :note => "Membership fee for ordergroup", :user_id => 1, :created_on => 'Sat, 18 Jan 2014 00:38:48 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 3, :ordergroup_id => 6, :amount => -0.35E2, :note => "Membership fee for ordergroup", :user_id => 1, :created_on => 'Sat, 25 Jan 2014 20:20:37 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 4, :ordergroup_id => 7, :amount => -0.35E2, :note => "Membership fee for ordergroup", :user_id => 1, :created_on => 'Mon, 27 Jan 2014 16:22:14 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 5, :ordergroup_id => 5, :amount => 0.35E2, :note => "payment", :user_id => 2, :created_on => 'Wed, 05 Feb 2014 16:49:24 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 6, :ordergroup_id => 8, :amount => 0.90E2, :note => "Bank transfer", :user_id => 2, :created_on => 'Mon, 17 Feb 2014 16:19:34 UTC +00:00', :financial_transaction_type_id => 1) +FinancialTransactionType.create!(id: 1, name: 'Foodcoop', financial_transaction_class_id: 1) + +FinancialTransaction.create!(id: 1, ordergroup_id: 5, amount: -0.35E2, note: 'Membership fee for ordergroup', + user_id: 1, created_on: 'Sat, 18 Jan 2014 00:38:48 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 3, ordergroup_id: 6, amount: -0.35E2, note: 'Membership fee for ordergroup', + user_id: 1, created_on: 'Sat, 25 Jan 2014 20:20:37 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 4, ordergroup_id: 7, amount: -0.35E2, note: 'Membership fee for ordergroup', + user_id: 1, created_on: 'Mon, 27 Jan 2014 16:22:14 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 5, ordergroup_id: 5, amount: 0.35E2, note: 'payment', user_id: 2, + created_on: 'Wed, 05 Feb 2014 16:49:24 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 6, ordergroup_id: 8, amount: 0.90E2, note: 'Bank transfer', user_id: 2, + created_on: 'Mon, 17 Feb 2014 16:19:34 UTC +00:00', financial_transaction_type_id: 1) FoodsoftConfig[:minimum_balance] = '-10000' diff --git a/db/seeds/minimal.seeds.rb b/db/seeds/minimal.seeds.rb index d38ef10e..bbf97e10 100644 --- a/db/seeds/minimal.seeds.rb +++ b/db/seeds/minimal.seeds.rb @@ -2,30 +2,30 @@ # 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 -financial_transaction_class = FinancialTransactionClass.create!(:name => "Other") -FinancialTransactionType.create!(:name => "Foodcoop", :financial_transaction_class_id => financial_transaction_class.id) +financial_transaction_class = FinancialTransactionClass.create!(name: 'Other') +FinancialTransactionType.create!(name: 'Foodcoop', financial_transaction_class_id: financial_transaction_class.id) # First entry for article categories -SupplierCategory.create!(:name => "Other", :financial_transaction_class_id => financial_transaction_class.id) -ArticleCategory.create!(:name => "Other", :description => "other, misc, unknown") +SupplierCategory.create!(name: 'Other', financial_transaction_class_id: financial_transaction_class.id) +ArticleCategory.create!(name: 'Other', description: 'other, misc, unknown') diff --git a/db/seeds/seed_helper.rb b/db/seeds/seed_helper.rb index 9eeb960f..f46fc863 100644 --- a/db/seeds/seed_helper.rb +++ b/db/seeds/seed_helper.rb @@ -8,10 +8,10 @@ def seed_group_orders # order 3..12 times a random article go = og.group_orders.create!(order: order, updated_by_user_id: 1) - (3 + rand(10)).times do + rand(3..12).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.article_version.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 diff --git a/db/seeds/small.en.seeds.rb b/db/seeds/small.en.seeds.rb index 2d2f5fa3..71dd6c9b 100644 --- a/db/seeds/small.en.seeds.rb +++ b/db/seeds/small.en.seeds.rb @@ -1,173 +1,299 @@ -require_relative 'seed_helper.rb' +require_relative 'seed_helper' ## Financial transaction classes -FinancialTransactionClass.create!(:id => 1, :name => 'Standard') -FinancialTransactionClass.create!(:id => 2, :name => 'Foodsoft') +FinancialTransactionClass.create!(id: 1, name: 'Standard') +FinancialTransactionClass.create!(id: 2, name: 'Foodsoft') ## Suppliers & articles -SupplierCategory.create!(:id => 1, :name => "Other", :financial_transaction_class_id => 1) +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") -ArticleCategory.create!(:id => 3, :name => "Vegetables") -ArticleCategory.create!(:id => 4, :name => "Potatoes & onions") -ArticleCategory.create!(:id => 5, :name => "Bread & Bakery") -ArticleCategory.create!(:id => 6, :name => "Drinks", :description => "juice, fruit juice, vegetable juice, soda") -ArticleCategory.create!(:id => 7, :name => "Herbs & Spices") -ArticleCategory.create!(:id => 8, :name => "Milk & products", :description => "milk, butter, cream, yoghurt, cheese, eggs, milk substitutes") -ArticleCategory.create!(:id => 9, :name => "Fish & Sea") -ArticleCategory.create!(:id => 10, :name => "Meat") -ArticleCategory.create!(:id => 11, :name => "Oils & Fats") -ArticleCategory.create!(:id => 12, :name => "Grains & Legumes") -ArticleCategory.create!(:id => 13, :name => "Nuts & Seeds") -ArticleCategory.create!(:id => 14, :name => "Sugar & Sweets") - -Article.create!(:name => "Brown whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.22E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Brown half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Brown sesame whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.22E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Brown sesame half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Light wheat whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.22E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Light wheat half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Bread with sunflower seeds whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Bread with sunflower seeds half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Bread with walnuts whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Bread with walnuts half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Kennemerlandbread whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Kennemerlandbread half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Maize bread whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Maize bread half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Oberlander 1200 gram whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Oberlander 1200 gram half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Oberlander 900 gram whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Oberlander 900 gram half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Speltbread whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Speltbread half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Country bread 900gram whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Country bread 900gram half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "White whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "White half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "White with poppy seeds whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "White with poppy seeds half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Fig bread whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Fig bread half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Beer-based bread whole", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Beer-based bread half", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.22E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Raisin bun", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.99E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Muesli bun", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Brioche", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.99E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Brown croissant", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Croissants", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Cheese croissants", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Chocolatecroissants", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Soepstengels white", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Soepstengels volkoren", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.99E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Pumpkin-seed buns", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.88E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "White buns", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.66E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Brown buns", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.66E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Tomato-feta bread", :supplier_id => 1, :article_category_id => 5, :unit => "pc", :note => "organic", :availability => true, :manufacturer => "The Baker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Chocolate Bar Milk (37%)", :supplier_id => 2, :article_category_id => 14, :unit => "90gr", :note => "organic", :availability => true, :manufacturer => "Chocolatemakers", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Chocolate Bar Pure (68%)", :supplier_id => 2, :article_category_id => 14, :unit => "90gr", :note => "organic", :availability => true, :manufacturer => "Chocolatemakers", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Chocolate Bar Milk (40%)", :supplier_id => 2, :article_category_id => 14, :unit => "90gr", :note => "organic", :availability => true, :manufacturer => "Chocolatemakers", :origin => "NL", :price => 0.22E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Chocolate Bar Pure (75%)", :supplier_id => 2, :article_category_id => 14, :unit => "90gr", :note => "organic", :availability => true, :manufacturer => "Chocolatemakers", :origin => "NL", :price => 0.22E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Chocolate Bar Swan Pure (75%)", :supplier_id => 2, :article_category_id => 14, :unit => "120gr", :note => "organic", :availability => true, :manufacturer => "Chocolatemakers", :origin => "NL", :price => 0.66E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Cacao nibs", :supplier_id => 2, :article_category_id => 14, :unit => "1 kg", :note => "organic", :availability => true, :manufacturer => "Chocolatemakers", :origin => "NL", :price => 0.11E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Cheese Cow-young", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "organic", :availability => true, :manufacturer => "Cheesefarm", :origin => "NL", :price => 0.88E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Cheese cow- young matured", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "organic", :availability => true, :manufacturer => "Cheesefarm", :origin => "NL", :price => 0.99E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Cheese cow- matured", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "organic", :availability => true, :manufacturer => "Cheesefarm", :origin => "NL", :price => 0.11E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 12, :unit => 'XPP' })]) -Article.create!(:name => "Cheese cow- extra matured", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "organic", :availability => true, :manufacturer => "Cheesefarm", :origin => "NL", :price => 0.12E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "cheese Cow- old", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "organic", :availability => true, :manufacturer => "Cheesefarm", :origin => "NL", :price => 0.11E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "cheese cow -very old", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "organic", :availability => true, :manufacturer => "Cheesefarm", :origin => "NL", :price => 0.12E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Cheese Cow-nettle young", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "organic", :availability => true, :manufacturer => "Cheesefarm", :origin => "NL", :price => 0.99E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Cheese cow- nettle young matured", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "organic", :availability => true, :manufacturer => "Cheesefarm", :origin => "NL", :price => 0.1075E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Cheese cow- nettle matured", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "organic", :availability => true, :manufacturer => "Cheesefarm", :origin => "NL", :price => 0.11E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Cheese Cow-cumin young", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "organic", :availability => true, :manufacturer => "Cheesefarm", :origin => "NL", :price => 0.99E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Cheese cow- cumin young matured", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "organic", :availability => true, :manufacturer => "Cheesefarm", :origin => "NL", :price => 0.1075E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Cheese cow- cumin matured", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "organic", :availability => true, :manufacturer => "Cheesefarm", :origin => "NL", :price => 0.11E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Cashew nuts", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "organic", :availability => true, :price => 0.4444E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 22, :unit => 'XPP' })], :order_number => ":b936051") -Article.create!(:name => "Hazel white", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "organic", :availability => true, :price => 0.3333E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 10, :unit => 'XPP' })], :order_number => ":9e3f85b") -Article.create!(:name => "Hazel brown", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "organic", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 10, :unit => 'XPP' })], :order_number => ":d278041") -Article.create!(:name => "Almond Brown Spanish", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "organic", :availability => true, :price => 0.999E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 10, :unit => 'XPP' })], :order_number => ":0b51a8d") -Article.create!(:name => "Brazil nuts (organic)", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "organic", :availability => true, :price => 0.6666E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 20, :unit => 'XPP' })], :order_number => ":01e59e3") -Article.create!(:name => "Organic walnut light halves", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "organic", :availability => true, :price => 0.333E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 10, :unit => 'XPP' })], :order_number => ":7ff8587") -Article.create!(:name => "Pinenuts", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "organic", :availability => true, :price => 0.888E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 25, :unit => 'XPP' })], :order_number => ":aa88d9f") -Article.create!(:name => "Pumpkin", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "organic", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 25, :unit => 'XPP' })], :order_number => ":e63069b") -Article.create!(:name => "Sunflower seeds (organic)", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "organic", :availability => true, :price => 0.999E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 25, :unit => 'XPP' })], :order_number => ":0428388") -Article.create!(:name => "Amandel White Spaans", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "organic", :availability => true, :price => 0.66666E3, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 10, :unit => 'XPP' })], :order_number => ":a8f0734") -Article.create!(:name => "Cashew", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.6666E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":1d26958") -Article.create!(:name => "Almonds blanched", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.333E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":31439e2") -Article.create!(:name => "Almonds natural", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":9c49374") -Article.create!(:name => "Walnut ELH halves", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.4444E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":92907d1") -Article.create!(:name => "Walnut ELP parts", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.8888E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":395640e") -Article.create!(:name => "Brazil nuts", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.8888E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":710acbb") -Article.create!(:name => "Macadamia type 0", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.3333E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":bbaf40b") -Article.create!(:name => "Pecan", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.55555E3, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":7958183") -Article.create!(:name => "Hazelnuts natural", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.6666E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":50392a8") -Article.create!(:name => "Hazelnuts blanched", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.3333E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":4fe6525") -Article.create!(:name => "Mixed Nuts", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.333E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":c051b22") -Article.create!(:name => "Peanuts", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.777E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":f507577") -Article.create!(:name => "Small peanuts", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.8888E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":ce563bb") -Article.create!(:name => "Medjoul dates", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.3333E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":8232061") -Article.create!(:name => "Turkish apricots natural", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.888E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":185084f") -Article.create!(:name => "Turkish apricots sulfurised", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":2b2fb20") -Article.create!(:name => "Spanish Figs", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.444E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":82590b1") -Article.create!(:name => "Turkish Figs", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.555E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":cabeeb6") -Article.create!(:name => "Sour Apricots South-Africa", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":2ac18b7") -Article.create!(:name => "Blue raisins Flames", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":16bfa75") -Article.create!(:name => "Yellow Raisins", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.2222E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":1c59324") -Article.create!(:name => "Red Raisins", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":c3fcd84") -Article.create!(:name => "Cranberries whole", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.222E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":921c168") -Article.create!(:name => "Dried apples", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.555E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":902c67b") -Article.create!(:name => "Dried plums without core", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.222E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":a847f91") -Article.create!(:name => "Pumpkin seeds", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.111E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":535645f") -Article.create!(:name => "Sunflower seeds", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.666E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":4ab9a83") -Article.create!(:name => "Linseed", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.55E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":04be223") -Article.create!(:name => "Poppy seeds", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.7777E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":ec5b2b9") -Article.create!(:name => "Pine nuts medium china", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.2222E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":0e5b0b8") -Article.create!(:name => "Goji berries", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.888E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":d52ee00") -Article.create!(:name => "Mulberries", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.5555E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":5f46bd5") -Article.create!(:name => "Peeled Hemp", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.5555E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":c39165b") -Article.create!(:name => "Incaberries", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.888E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":8d44fe7") -Article.create!(:name => "Blueberries", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.2222E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":9a95422") -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, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :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, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":b3f65e4") +ArticleCategory.create!(id: 1, name: 'Other', description: 'other, misc, unknown') +ArticleCategory.create!(id: 2, name: 'Fruit') +ArticleCategory.create!(id: 3, name: 'Vegetables') +ArticleCategory.create!(id: 4, name: 'Potatoes & onions') +ArticleCategory.create!(id: 5, name: 'Bread & Bakery') +ArticleCategory.create!(id: 6, name: 'Drinks', description: 'juice, fruit juice, vegetable juice, soda') +ArticleCategory.create!(id: 7, name: 'Herbs & Spices') +ArticleCategory.create!(id: 8, name: 'Milk & products', + description: 'milk, butter, cream, yoghurt, cheese, eggs, milk substitutes') +ArticleCategory.create!(id: 9, name: 'Fish & Sea') +ArticleCategory.create!(id: 10, name: 'Meat') +ArticleCategory.create!(id: 11, name: 'Oils & Fats') +ArticleCategory.create!(id: 12, name: 'Grains & Legumes') +ArticleCategory.create!(id: 13, name: 'Nuts & Seeds') +ArticleCategory.create!(id: 14, name: 'Sugar & Sweets') + +Article.create!(name: 'Brown whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.22E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Brown half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Brown sesame whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.22E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Brown sesame half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Light wheat whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.22E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Light wheat half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Bread with sunflower seeds whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Bread with sunflower seeds half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Bread with walnuts whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Bread with walnuts half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Kennemerlandbread whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Kennemerlandbread half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Maize bread whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Maize bread half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Oberlander 1200 gram whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Oberlander 1200 gram half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Oberlander 900 gram whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Oberlander 900 gram half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Speltbread whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Speltbread half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Country bread 900gram whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Country bread 900gram half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'White whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'White half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'White with poppy seeds whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'White with poppy seeds half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Fig bread whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Fig bread half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Beer-based bread whole', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Beer-based bread half', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.22E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Raisin bun', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.99E0, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Muesli bun', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Brioche', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.99E0, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Brown croissant', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Croissants', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Cheese croissants', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Chocolatecroissants', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Soepstengels white', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Soepstengels volkoren', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.99E0, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Pumpkin-seed buns', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.88E0, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'White buns', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.66E0, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Brown buns', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.66E0, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Tomato-feta bread', supplier_id: 1, article_category_id: 5, unit: 'pc', note: 'organic', availability: true, manufacturer: 'The Baker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Chocolate Bar Milk (37%)', supplier_id: 2, article_category_id: 14, unit: '90gr', note: 'organic', availability: true, manufacturer: 'Chocolatemakers', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Chocolate Bar Pure (68%)', supplier_id: 2, article_category_id: 14, unit: '90gr', note: 'organic', availability: true, manufacturer: 'Chocolatemakers', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Chocolate Bar Milk (40%)', supplier_id: 2, article_category_id: 14, unit: '90gr', note: 'organic', availability: true, manufacturer: 'Chocolatemakers', origin: 'NL', price: 0.22E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Chocolate Bar Pure (75%)', supplier_id: 2, article_category_id: 14, unit: '90gr', note: 'organic', availability: true, manufacturer: 'Chocolatemakers', origin: 'NL', price: 0.22E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Chocolate Bar Swan Pure (75%)', supplier_id: 2, article_category_id: 14, unit: '120gr', note: 'organic', availability: true, manufacturer: 'Chocolatemakers', origin: 'NL', price: 0.66E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Cacao nibs', supplier_id: 2, article_category_id: 14, unit: '1 kg', note: 'organic', availability: true, manufacturer: 'Chocolatemakers', origin: 'NL', price: 0.11E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Cheese Cow-young', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'organic', availability: true, manufacturer: 'Cheesefarm', origin: 'NL', price: 0.88E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Cheese cow- young matured', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'organic', availability: true, manufacturer: 'Cheesefarm', origin: 'NL', price: 0.99E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Cheese cow- matured', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'organic', availability: true, manufacturer: 'Cheesefarm', origin: 'NL', price: 0.11E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 12, unit: 'XPP' })]) +Article.create!(name: 'Cheese cow- extra matured', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'organic', availability: true, manufacturer: 'Cheesefarm', origin: 'NL', price: 0.12E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'cheese Cow- old', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'organic', availability: true, manufacturer: 'Cheesefarm', origin: 'NL', price: 0.11E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'cheese cow -very old', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'organic', availability: true, manufacturer: 'Cheesefarm', origin: 'NL', price: 0.12E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Cheese Cow-nettle young', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'organic', availability: true, manufacturer: 'Cheesefarm', origin: 'NL', price: 0.99E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Cheese cow- nettle young matured', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'organic', availability: true, manufacturer: 'Cheesefarm', origin: 'NL', price: 0.1075E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Cheese cow- nettle matured', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'organic', availability: true, manufacturer: 'Cheesefarm', origin: 'NL', price: 0.11E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Cheese Cow-cumin young', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'organic', availability: true, manufacturer: 'Cheesefarm', origin: 'NL', price: 0.99E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Cheese cow- cumin young matured', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'organic', availability: true, manufacturer: 'Cheesefarm', origin: 'NL', price: 0.1075E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Cheese cow- cumin matured', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'organic', availability: true, manufacturer: 'Cheesefarm', origin: 'NL', price: 0.11E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Cashew nuts', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'organic', + availability: true, price: 0.4444E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 22, unit: 'XPP' })], order_number: ':b936051') +Article.create!(name: 'Hazel white', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'organic', + availability: true, price: 0.3333E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 10, unit: 'XPP' })], order_number: ':9e3f85b') +Article.create!(name: 'Hazel brown', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'organic', + availability: true, price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 10, unit: 'XPP' })], order_number: ':d278041') +Article.create!(name: 'Almond Brown Spanish', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'organic', availability: true, price: 0.999E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 10, unit: 'XPP' })], + order_number: ':0b51a8d') +Article.create!(name: 'Brazil nuts (organic)', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'organic', availability: true, price: 0.6666E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 20, unit: 'XPP' })], + order_number: ':01e59e3') +Article.create!(name: 'Organic walnut light halves', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'organic', availability: true, price: 0.333E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 10, unit: 'XPP' })], + order_number: ':7ff8587') +Article.create!(name: 'Pinenuts', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'organic', + availability: true, price: 0.888E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 25, unit: 'XPP' })], order_number: ':aa88d9f') +Article.create!(name: 'Pumpkin', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'organic', + availability: true, price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 25, unit: 'XPP' })], order_number: ':e63069b') +Article.create!(name: 'Sunflower seeds (organic)', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'organic', availability: true, price: 0.999E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 25, unit: 'XPP' })], + order_number: ':0428388') +Article.create!(name: 'Amandel White Spaans', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'organic', availability: true, price: 0.66666E3, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 10, unit: 'XPP' })], + order_number: ':a8f0734') +Article.create!(name: 'Cashew', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.6666E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':1d26958') +Article.create!(name: 'Almonds blanched', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.333E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':31439e2') +Article.create!(name: 'Almonds natural', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':9c49374') +Article.create!(name: 'Walnut ELH halves', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.4444E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':92907d1') +Article.create!(name: 'Walnut ELP parts', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.8888E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':395640e') +Article.create!(name: 'Brazil nuts', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.8888E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':710acbb') +Article.create!(name: 'Macadamia type 0', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.3333E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':bbaf40b') +Article.create!(name: 'Pecan', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.55555E3, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':7958183') +Article.create!(name: 'Hazelnuts natural', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.6666E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':50392a8') +Article.create!(name: 'Hazelnuts blanched', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.3333E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':4fe6525') +Article.create!(name: 'Mixed Nuts', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.333E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':c051b22') +Article.create!(name: 'Peanuts', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.777E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':f507577') +Article.create!(name: 'Small peanuts', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.8888E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':ce563bb') +Article.create!(name: 'Medjoul dates', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.3333E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':8232061') +Article.create!(name: 'Turkish apricots natural', supplier_id: 4, article_category_id: 13, unit: 'kg', + availability: true, price: 0.888E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':185084f') +Article.create!(name: 'Turkish apricots sulfurised', supplier_id: 4, article_category_id: 13, unit: 'kg', + availability: true, price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':2b2fb20') +Article.create!(name: 'Spanish Figs', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.444E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':82590b1') +Article.create!(name: 'Turkish Figs', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.555E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':cabeeb6') +Article.create!(name: 'Sour Apricots South-Africa', supplier_id: 4, article_category_id: 13, unit: 'kg', + availability: true, price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':2ac18b7') +Article.create!(name: 'Blue raisins Flames', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':16bfa75') +Article.create!(name: 'Yellow Raisins', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.2222E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':1c59324') +Article.create!(name: 'Red Raisins', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':c3fcd84') +Article.create!(name: 'Cranberries whole', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.222E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':921c168') +Article.create!(name: 'Dried apples', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.555E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':902c67b') +Article.create!(name: 'Dried plums without core', supplier_id: 4, article_category_id: 13, unit: 'kg', + availability: true, price: 0.222E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':a847f91') +Article.create!(name: 'Pumpkin seeds', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.111E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':535645f') +Article.create!(name: 'Sunflower seeds', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.666E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':4ab9a83') +Article.create!(name: 'Linseed', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.55E0, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':04be223') +Article.create!(name: 'Poppy seeds', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.7777E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':ec5b2b9') +Article.create!(name: 'Pine nuts medium china', supplier_id: 4, article_category_id: 13, unit: 'kg', + availability: true, price: 0.2222E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':0e5b0b8') +Article.create!(name: 'Goji berries', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.888E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':d52ee00') +Article.create!(name: 'Mulberries', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.5555E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':5f46bd5') +Article.create!(name: 'Peeled Hemp', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.5555E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':c39165b') +Article.create!(name: 'Incaberries', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.888E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':8d44fe7') +Article.create!(name: 'Blueberries', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.2222E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':9a95422') +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, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], 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, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], 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') -User.create!(:id => 2, :nick => "john", :password => "secret", :first_name => "John", :last_name => "Doe", :email => "john@doe.test", :created_on => 'Sun, 19 Jan 2014 17:38:22 UTC +00:00') -User.create!(:id => 3, :nick => "peter", :password => "secret", :first_name => "Peter", :last_name => "Peters", :email => "peter@peters.test", :created_on => 'Sat, 25 Jan 2014 20:20:36 UTC +00:00') -User.create!(:id => 4, :nick => "jan", :password => "secret", :first_name => "Jan", :last_name => "Lou", :email => "jan@lou.test", :created_on => 'Mon, 27 Jan 2014 16:22:14 UTC +00:00') -User.create!(:id => 5, :nick => "mary", :password => "secret", :first_name => "Mary", :last_name => "Lou", :email => "marie@lou.test", :created_on => 'Mon, 03 Feb 2014 11:47:17 UTC +00:00') - -Workgroup.create!(:id => 1, :name => "Administrators", :description => "System administrators.", :account_balance => 0.0, :created_on => 'Wed, 15 Jan 2014 16:15:33 UTC +00:00', :role_admin => true, :role_suppliers => true, :role_article_meta => true, :role_finance => true, :role_orders => true, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) -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) - -Membership.create!(:group_id => 1, :user_id => 1) -Membership.create!(:group_id => 5, :user_id => 1) -Membership.create!(:group_id => 2, :user_id => 2) -Membership.create!(:group_id => 8, :user_id => 2) -Membership.create!(:group_id => 6, :user_id => 3) -Membership.create!(:group_id => 7, :user_id => 4) -Membership.create!(:group_id => 8, :user_id => 4) -Membership.create!(:group_id => 3, :user_id => 4) -Membership.create!(:group_id => 7, :user_id => 5) -Membership.create!(:group_id => 3, :user_id => 5) -Membership.create!(:group_id => 4, :user_id => 5) +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') +User.create!(id: 2, nick: 'john', password: 'secret', first_name: 'John', last_name: 'Doe', email: 'john@doe.test', + created_on: 'Sun, 19 Jan 2014 17:38:22 UTC +00:00') +User.create!(id: 3, nick: 'peter', password: 'secret', first_name: 'Peter', last_name: 'Peters', + email: 'peter@peters.test', created_on: 'Sat, 25 Jan 2014 20:20:36 UTC +00:00') +User.create!(id: 4, nick: 'jan', password: 'secret', first_name: 'Jan', last_name: 'Lou', email: 'jan@lou.test', + created_on: 'Mon, 27 Jan 2014 16:22:14 UTC +00:00') +User.create!(id: 5, nick: 'mary', password: 'secret', first_name: 'Mary', last_name: 'Lou', email: 'marie@lou.test', + created_on: 'Mon, 03 Feb 2014 11:47:17 UTC +00:00') + +Workgroup.create!(id: 1, name: 'Administrators', description: 'System administrators.', account_balance: 0.0, created_on: 'Wed, 15 Jan 2014 16:15:33 UTC +00:00', role_admin: true, role_suppliers: true, role_article_meta: true, role_finance: true, role_orders: true, + next_weekly_tasks_number: 8, ignore_apple_restriction: false) +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) + +Membership.create!(group_id: 1, user_id: 1) +Membership.create!(group_id: 5, user_id: 1) +Membership.create!(group_id: 2, user_id: 2) +Membership.create!(group_id: 8, user_id: 2) +Membership.create!(group_id: 6, user_id: 3) +Membership.create!(group_id: 7, user_id: 4) +Membership.create!(group_id: 8, user_id: 4) +Membership.create!(group_id: 3, user_id: 4) +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 @@ -181,10 +307,15 @@ ## Finances -FinancialTransactionType.create!(:id => 1, :name => "Foodcoop", :financial_transaction_class_id => 1) +FinancialTransactionType.create!(id: 1, name: 'Foodcoop', financial_transaction_class_id: 1) -FinancialTransaction.create!(:id => 1, :ordergroup_id => 5, :amount => -0.35E2, :note => "Membership fee for ordergroup", :user_id => 1, :created_on => 'Sat, 18 Jan 2014 00:38:48 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 3, :ordergroup_id => 6, :amount => -0.35E2, :note => "Membership fee for ordergroup", :user_id => 1, :created_on => 'Sat, 25 Jan 2014 20:20:37 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 4, :ordergroup_id => 7, :amount => -0.35E2, :note => "Membership fee for ordergroup", :user_id => 1, :created_on => 'Mon, 27 Jan 2014 16:22:14 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 5, :ordergroup_id => 5, :amount => 0.35E2, :note => "payment", :user_id => 2, :created_on => 'Wed, 05 Feb 2014 16:49:24 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 6, :ordergroup_id => 8, :amount => 0.90E2, :note => "Bank transfer", :user_id => 2, :created_on => 'Mon, 17 Feb 2014 16:19:34 UTC +00:00', :financial_transaction_type_id => 1) +FinancialTransaction.create!(id: 1, ordergroup_id: 5, amount: -0.35E2, note: 'Membership fee for ordergroup', + user_id: 1, created_on: 'Sat, 18 Jan 2014 00:38:48 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 3, ordergroup_id: 6, amount: -0.35E2, note: 'Membership fee for ordergroup', + user_id: 1, created_on: 'Sat, 25 Jan 2014 20:20:37 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 4, ordergroup_id: 7, amount: -0.35E2, note: 'Membership fee for ordergroup', + user_id: 1, created_on: 'Mon, 27 Jan 2014 16:22:14 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 5, ordergroup_id: 5, amount: 0.35E2, note: 'payment', user_id: 2, + created_on: 'Wed, 05 Feb 2014 16:49:24 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 6, ordergroup_id: 8, amount: 0.90E2, note: 'Bank transfer', user_id: 2, + created_on: 'Mon, 17 Feb 2014 16:19:34 UTC +00:00', financial_transaction_type_id: 1) diff --git a/db/seeds/small.nl.seeds.rb b/db/seeds/small.nl.seeds.rb index 1729feb1..9912eaf1 100644 --- a/db/seeds/small.nl.seeds.rb +++ b/db/seeds/small.nl.seeds.rb @@ -1,173 +1,299 @@ -require_relative 'seed_helper.rb' +require_relative 'seed_helper' ## Financial transaction classes -FinancialTransactionClass.create!(:id => 1, :name => 'Standaard') -FinancialTransactionClass.create!(:id => 2, :name => 'Foodsoft') +FinancialTransactionClass.create!(id: 1, name: 'Standaard') +FinancialTransactionClass.create!(id: 2, name: 'Foodsoft') ## Suppliers & articles -SupplierCategory.create!(:id => 1, :name => "Other", :financial_transaction_class_id => 1) +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") -ArticleCategory.create!(:id => 3, :name => "Groenten") -ArticleCategory.create!(:id => 4, :name => "Aardappels & uien") -ArticleCategory.create!(:id => 5, :name => "Brood & Bakkerij") -ArticleCategory.create!(:id => 6, :name => "Dranken", :description => "sap, fruitsap, groentesap, frisdrank") -ArticleCategory.create!(:id => 7, :name => "Kruiden", :description => "kruiden, specerijen, conserveringsmiddelen, extracten") -ArticleCategory.create!(:id => 8, :name => "Zuivel", :description => "melk, boter, room, yoghurt, kaas, eieren, zuivelvervangers") -ArticleCategory.create!(:id => 9, :name => "Vis & Zee", :description => "vis, schaaldieren, schelpdieren") -ArticleCategory.create!(:id => 10, :name => "Vlees & Gevogelte") -ArticleCategory.create!(:id => 11, :name => "Oliën & Vetten") -ArticleCategory.create!(:id => 12, :name => "Graan & Peulvruchten") -ArticleCategory.create!(:id => 13, :name => "Noten & Zaden") -ArticleCategory.create!(:id => 14, :name => "Zoetwaren & Zoetstof") - -Article.create!(:name => "Volkoren heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.22E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Volkoren half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Volkoren sesam heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.22E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Volkoren sesam half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Licht tarwe heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.22E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Licht tarwe half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Zonnebloempitbrood heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Zonnebloempitbrood half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Walnoten vloer heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Walnoten vloer half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Kennemerlandbrood heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Kennemerlandbrood half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Maisbrood heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Maisbrood half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Oberlander 1200 gram heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Oberlander 1200 gram half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Oberlander 900 gram heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Oberlander 900 gram half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Speltbrood heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Speltbrood half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Landbrood 900gram heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Landbrood 900gram half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Wit heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Wit half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Wit met maanzaad heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Wit met maanzaad half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Vijgenbrood heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Vijgenbrood half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Bierborstelbrood heel", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.33E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Bierborstelbrood half", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Krentenbol", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.99E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Mueslibol", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Brioche", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.91E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Volkoren croissant", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Croissants", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Kaas croissants", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Chocoladecroissants", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Soepstengels wit", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Soepstengels volkoren", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.99E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Pompoenpitten broodjes", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.88E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Witte kadetjes", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.66E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Bruine kadetjes", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.66E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Tomaten feta broodje", :supplier_id => 1, :article_category_id => 5, :unit => "stuk", :note => "bio", :availability => true, :manufacturer => "De Bakker", :origin => "NL", :price => 0.11E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Chocoladereep Melk (37%)", :supplier_id => 2, :article_category_id => 14, :unit => "90gr", :note => "bio", :availability => true, :manufacturer => "Chocolademakkers", :origin => "NL", :price => 0.22E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Chocoladereep Puur (68%)", :supplier_id => 2, :article_category_id => 14, :unit => "90gr", :note => "bio", :availability => true, :manufacturer => "Chocolademakkers", :origin => "NL", :price => 0.22E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Chocoladereep Drie Mensen Melk (40%)", :supplier_id => 2, :article_category_id => 14, :unit => "90gr", :note => "bio", :availability => true, :manufacturer => "Chocolademakkers", :origin => "NL", :price => 0.22E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Chocoladereep Drie Mensen Puur (75%)", :supplier_id => 2, :article_category_id => 14, :unit => "90gr", :note => "bio", :availability => true, :manufacturer => "Chocolademakkers", :origin => "NL", :price => 0.22E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Chocoladereep Zwaan Puur (75%)", :supplier_id => 2, :article_category_id => 14, :unit => "120gr", :note => "bio", :availability => true, :manufacturer => "Chocolademakkers", :origin => "NL", :price => 0.66E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Cacao nibs", :supplier_id => 2, :article_category_id => 14, :unit => "1 kg", :note => "bio", :availability => true, :manufacturer => "Chocolademakkers", :origin => "NL", :price => 0.10E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })]) -Article.create!(:name => "Kaas Koe-jong", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "bio", :availability => true, :manufacturer => "Kaasboerderij", :origin => "NL", :price => 0.88E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Kaas koe- jong belegen", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "bio", :availability => true, :manufacturer => "Kaasboerderij", :origin => "NL", :price => 0.99E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Kaas koe- belegen", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "bio", :availability => true, :manufacturer => "Kaasboerderij", :origin => "NL", :price => 0.11E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 12, :unit => 'XPP' })]) -Article.create!(:name => "Kaas koe- extra belegen", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "bio", :availability => true, :manufacturer => "Kaasboerderij", :origin => "NL", :price => 0.11E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "kaas Koe- oud", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "bio", :availability => true, :manufacturer => "Kaasboerderij", :origin => "NL", :price => 0.1375E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "kaas koe -overjarig", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "bio", :availability => true, :manufacturer => "Kaasboerderij", :origin => "NL", :price => 0.11E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Kaas Koe-brandnetel jong", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "bio", :availability => true, :manufacturer => "Kaasboerderij", :origin => "NL", :price => 0.99E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Kaas koe- brandnetel jong belegen", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "bio", :availability => true, :manufacturer => "Kaasboerderij", :origin => "NL", :price => 0.11E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Kaas koe- brandnetel belegen", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "bio", :availability => true, :manufacturer => "Kaasboerderij", :origin => "NL", :price => 0.11E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Kaas Koe-komijn jong", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "bio", :availability => true, :manufacturer => "Kaasboerderij", :origin => "NL", :price => 0.99E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Kaas koe- komijn jong belegen", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "bio", :availability => true, :manufacturer => "Kaasboerderij", :origin => "NL", :price => 0.11E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Kaas koe- komijn belegen", :supplier_id => 3, :article_category_id => 8, :unit => "kg", :note => "bio", :availability => true, :manufacturer => "Kaasboerderij", :origin => "NL", :price => 0.11E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 8, :unit => 'XPP' })]) -Article.create!(:name => "Cashewnoten", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "bio", :availability => true, :price => 0.4444E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 22, :unit => 'XPP' })], :order_number => ":b936051") -Article.create!(:name => "Hazel wit", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "bio", :availability => true, :price => 0.3333E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 10, :unit => 'XPP' })], :order_number => ":9e3f85b") -Article.create!(:name => "Hazel bruin", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "bio", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 10, :unit => 'XPP' })], :order_number => ":d278041") -Article.create!(:name => "Amandel Bruin Spaans", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "bio", :availability => true, :price => 0.999E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 10, :unit => 'XPP' })], :order_number => ":0b51a8d") -Article.create!(:name => "Paranoten (bio)", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "bio", :availability => true, :price => 0.6666E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 20, :unit => 'XPP' })], :order_number => ":01e59e3") -Article.create!(:name => "Bio walnoten light halfjes", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "bio", :availability => true, :price => 0.333E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 10, :unit => 'XPP' })], :order_number => ":7ff8587") -Article.create!(:name => "Pijnboompitten", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "bio", :availability => true, :price => 0.888E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 25, :unit => 'XPP' })], :order_number => ":aa88d9f") -Article.create!(:name => "Pompoen", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "bio", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 25, :unit => 'XPP' })], :order_number => ":e63069b") -Article.create!(:name => "Zonnepitten (bio)", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "bio", :availability => true, :price => 0.999E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 25, :unit => 'XPP' })], :order_number => ":0428388") -Article.create!(:name => "Amandel Wit Spaans", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :note => "bio", :availability => true, :price => 0.66666E3, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 10, :unit => 'XPP' })], :order_number => ":a8f0734") -Article.create!(:name => "Cashew", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.6666E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":1d26958") -Article.create!(:name => "Amandelen geblancheerd", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.333E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":31439e2") -Article.create!(:name => "Amandelen naturel", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":9c49374") -Article.create!(:name => "Walnoot ELH hafjes", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.4444E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":92907d1") -Article.create!(:name => "Walnoot ELP stukjes", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.8888E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":395640e") -Article.create!(:name => "Paranoten", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.8888E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":710acbb") -Article.create!(:name => "Macadamia Stijl 0", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.3333E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":bbaf40b") -Article.create!(:name => "Pecan", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.55555E3, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":7958183") -Article.create!(:name => "Hazelnoten naturel", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.6666E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":50392a8") -Article.create!(:name => "Hazelnoten geblancheerd", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.3333E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":4fe6525") -Article.create!(:name => "Gemengde Noten", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.333E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":c051b22") -Article.create!(:name => "Pinda's", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.777E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":f507577") -Article.create!(:name => "Vliespinda's klein", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.8888E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":ce563bb") -Article.create!(:name => "Medjoul dadels", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.3333E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":8232061") -Article.create!(:name => "Turkse Abrikozen ongezwaveld", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.888E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":185084f") -Article.create!(:name => "Turkse Abrikozen gezwaveld", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":2b2fb20") -Article.create!(:name => "Spaanse Vijgen", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.444E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":82590b1") -Article.create!(:name => "Turkse Vijgen", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.555E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":cabeeb6") -Article.create!(:name => "Zure Abrikozen Zuid Afrika", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":2ac18b7") -Article.create!(:name => "Blauwe rozijnen Flames", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":16bfa75") -Article.create!(:name => "Gele Rozijnen", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.2222E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":1c59324") -Article.create!(:name => "Rode Rozijnen", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.1111E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":c3fcd84") -Article.create!(:name => "Cranberries heel", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.222E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":921c168") -Article.create!(:name => "Gedroogde Appeltjes", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.555E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":902c67b") -Article.create!(:name => "Gedroogde pruimen zonder pit", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.222E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":a847f91") -Article.create!(:name => "Pompoenpitten", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.111E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":535645f") -Article.create!(:name => "Zonnenbloepitten", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.666E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":4ab9a83") -Article.create!(:name => "Lijnzaad", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.55E0, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":04be223") -Article.create!(:name => "Maanzaad", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.7777E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":ec5b2b9") -Article.create!(:name => "Pijnboompitten medium china", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.2222E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":0e5b0b8") -Article.create!(:name => "Goji bessen", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.888E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":d52ee00") -Article.create!(:name => "Mulberries", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.5555E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":5f46bd5") -Article.create!(:name => "Gepelde Hennep", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.5555E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":c39165b") -Article.create!(:name => "Incaberries", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.888E1, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":8d44fe7") -Article.create!(:name => "Blueberries", :supplier_id => 4, :article_category_id => 13, :unit => "kg", :availability => true, :price => 0.2222E2, :tax => 6.0, :deposit => 0.0, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":9a95422") -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, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :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, :article_unit_ratios => [ArticleUnitRatio.new({ :sort => 1, :quantity => 1, :unit => 'XPP' })], :order_number => ":b3f65e4") +ArticleCategory.create!(id: 1, name: 'Other', description: 'overig, anders, onbekend') +ArticleCategory.create!(id: 2, name: 'Fruit') +ArticleCategory.create!(id: 3, name: 'Groenten') +ArticleCategory.create!(id: 4, name: 'Aardappels & uien') +ArticleCategory.create!(id: 5, name: 'Brood & Bakkerij') +ArticleCategory.create!(id: 6, name: 'Dranken', description: 'sap, fruitsap, groentesap, frisdrank') +ArticleCategory.create!(id: 7, name: 'Kruiden', description: 'kruiden, specerijen, conserveringsmiddelen, extracten') +ArticleCategory.create!(id: 8, name: 'Zuivel', + description: 'melk, boter, room, yoghurt, kaas, eieren, zuivelvervangers') +ArticleCategory.create!(id: 9, name: 'Vis & Zee', description: 'vis, schaaldieren, schelpdieren') +ArticleCategory.create!(id: 10, name: 'Vlees & Gevogelte') +ArticleCategory.create!(id: 11, name: 'Oliën & Vetten') +ArticleCategory.create!(id: 12, name: 'Graan & Peulvruchten') +ArticleCategory.create!(id: 13, name: 'Noten & Zaden') +ArticleCategory.create!(id: 14, name: 'Zoetwaren & Zoetstof') + +Article.create!(name: 'Volkoren heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.22E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Volkoren half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Volkoren sesam heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.22E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Volkoren sesam half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Licht tarwe heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.22E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Licht tarwe half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Zonnebloempitbrood heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Zonnebloempitbrood half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Walnoten vloer heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Walnoten vloer half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Kennemerlandbrood heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Kennemerlandbrood half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Maisbrood heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Maisbrood half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Oberlander 1200 gram heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Oberlander 1200 gram half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Oberlander 900 gram heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Oberlander 900 gram half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Speltbrood heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Speltbrood half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Landbrood 900gram heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Landbrood 900gram half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Wit heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Wit half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Wit met maanzaad heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Wit met maanzaad half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Vijgenbrood heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Vijgenbrood half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Bierborstelbrood heel', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.33E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Bierborstelbrood half', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Krentenbol', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.99E0, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Mueslibol', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Brioche', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.91E0, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Volkoren croissant', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Croissants', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Kaas croissants', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Chocoladecroissants', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Soepstengels wit', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Soepstengels volkoren', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.99E0, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Pompoenpitten broodjes', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.88E0, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Witte kadetjes', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.66E0, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Bruine kadetjes', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.66E0, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Tomaten feta broodje', supplier_id: 1, article_category_id: 5, unit: 'stuk', note: 'bio', availability: true, manufacturer: 'De Bakker', origin: 'NL', price: 0.11E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Chocoladereep Melk (37%)', supplier_id: 2, article_category_id: 14, unit: '90gr', note: 'bio', availability: true, manufacturer: 'Chocolademakkers', origin: 'NL', price: 0.22E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Chocoladereep Puur (68%)', supplier_id: 2, article_category_id: 14, unit: '90gr', note: 'bio', availability: true, manufacturer: 'Chocolademakkers', origin: 'NL', price: 0.22E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Chocoladereep Drie Mensen Melk (40%)', supplier_id: 2, article_category_id: 14, unit: '90gr', note: 'bio', availability: true, manufacturer: 'Chocolademakkers', origin: 'NL', price: 0.22E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Chocoladereep Drie Mensen Puur (75%)', supplier_id: 2, article_category_id: 14, unit: '90gr', note: 'bio', availability: true, manufacturer: 'Chocolademakkers', origin: 'NL', price: 0.22E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Chocoladereep Zwaan Puur (75%)', supplier_id: 2, article_category_id: 14, unit: '120gr', note: 'bio', availability: true, manufacturer: 'Chocolademakkers', origin: 'NL', price: 0.66E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Cacao nibs', supplier_id: 2, article_category_id: 14, unit: '1 kg', note: 'bio', availability: true, manufacturer: 'Chocolademakkers', origin: 'NL', price: 0.10E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })]) +Article.create!(name: 'Kaas Koe-jong', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'bio', availability: true, manufacturer: 'Kaasboerderij', origin: 'NL', price: 0.88E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Kaas koe- jong belegen', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'bio', availability: true, manufacturer: 'Kaasboerderij', origin: 'NL', price: 0.99E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Kaas koe- belegen', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'bio', availability: true, manufacturer: 'Kaasboerderij', origin: 'NL', price: 0.11E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 12, unit: 'XPP' })]) +Article.create!(name: 'Kaas koe- extra belegen', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'bio', availability: true, manufacturer: 'Kaasboerderij', origin: 'NL', price: 0.11E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'kaas Koe- oud', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'bio', availability: true, manufacturer: 'Kaasboerderij', origin: 'NL', price: 0.1375E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'kaas koe -overjarig', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'bio', availability: true, manufacturer: 'Kaasboerderij', origin: 'NL', price: 0.11E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Kaas Koe-brandnetel jong', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'bio', availability: true, manufacturer: 'Kaasboerderij', origin: 'NL', price: 0.99E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Kaas koe- brandnetel jong belegen', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'bio', availability: true, manufacturer: 'Kaasboerderij', origin: 'NL', price: 0.11E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Kaas koe- brandnetel belegen', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'bio', availability: true, manufacturer: 'Kaasboerderij', origin: 'NL', price: 0.11E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Kaas Koe-komijn jong', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'bio', availability: true, manufacturer: 'Kaasboerderij', origin: 'NL', price: 0.99E1, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Kaas koe- komijn jong belegen', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'bio', availability: true, manufacturer: 'Kaasboerderij', origin: 'NL', price: 0.11E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Kaas koe- komijn belegen', supplier_id: 3, article_category_id: 8, unit: 'kg', note: 'bio', availability: true, manufacturer: 'Kaasboerderij', origin: 'NL', price: 0.11E2, tax: 6.0, deposit: 0.0, + article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 8, unit: 'XPP' })]) +Article.create!(name: 'Cashewnoten', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'bio', + availability: true, price: 0.4444E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 22, unit: 'XPP' })], order_number: ':b936051') +Article.create!(name: 'Hazel wit', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'bio', + availability: true, price: 0.3333E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 10, unit: 'XPP' })], order_number: ':9e3f85b') +Article.create!(name: 'Hazel bruin', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'bio', + availability: true, price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 10, unit: 'XPP' })], order_number: ':d278041') +Article.create!(name: 'Amandel Bruin Spaans', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'bio', availability: true, price: 0.999E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 10, unit: 'XPP' })], + order_number: ':0b51a8d') +Article.create!(name: 'Paranoten (bio)', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'bio', + availability: true, price: 0.6666E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 20, unit: 'XPP' })], order_number: ':01e59e3') +Article.create!(name: 'Bio walnoten light halfjes', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'bio', availability: true, price: 0.333E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 10, unit: 'XPP' })], + order_number: ':7ff8587') +Article.create!(name: 'Pijnboompitten', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'bio', + availability: true, price: 0.888E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 25, unit: 'XPP' })], order_number: ':aa88d9f') +Article.create!(name: 'Pompoen', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'bio', availability: true, + price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 25, unit: 'XPP' })], order_number: ':e63069b') +Article.create!(name: 'Zonnepitten (bio)', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'bio', availability: true, price: 0.999E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 25, unit: 'XPP' })], + order_number: ':0428388') +Article.create!(name: 'Amandel Wit Spaans', supplier_id: 4, article_category_id: 13, unit: 'kg', note: 'bio', availability: true, price: 0.66666E3, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 10, unit: 'XPP' })], + order_number: ':a8f0734') +Article.create!(name: 'Cashew', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.6666E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':1d26958') +Article.create!(name: 'Amandelen geblancheerd', supplier_id: 4, article_category_id: 13, unit: 'kg', + availability: true, price: 0.333E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':31439e2') +Article.create!(name: 'Amandelen naturel', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':9c49374') +Article.create!(name: 'Walnoot ELH hafjes', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.4444E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':92907d1') +Article.create!(name: 'Walnoot ELP stukjes', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.8888E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':395640e') +Article.create!(name: 'Paranoten', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.8888E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':710acbb') +Article.create!(name: 'Macadamia Stijl 0', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.3333E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':bbaf40b') +Article.create!(name: 'Pecan', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.55555E3, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':7958183') +Article.create!(name: 'Hazelnoten naturel', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.6666E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':50392a8') +Article.create!(name: 'Hazelnoten geblancheerd', supplier_id: 4, article_category_id: 13, unit: 'kg', + availability: true, price: 0.3333E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':4fe6525') +Article.create!(name: 'Gemengde Noten', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.333E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':c051b22') +Article.create!(name: "Pinda's", supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.777E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':f507577') +Article.create!(name: "Vliespinda's klein", supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.8888E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':ce563bb') +Article.create!(name: 'Medjoul dadels', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.3333E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':8232061') +Article.create!(name: 'Turkse Abrikozen ongezwaveld', supplier_id: 4, article_category_id: 13, unit: 'kg', + availability: true, price: 0.888E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':185084f') +Article.create!(name: 'Turkse Abrikozen gezwaveld', supplier_id: 4, article_category_id: 13, unit: 'kg', + availability: true, price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':2b2fb20') +Article.create!(name: 'Spaanse Vijgen', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.444E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':82590b1') +Article.create!(name: 'Turkse Vijgen', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.555E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':cabeeb6') +Article.create!(name: 'Zure Abrikozen Zuid Afrika', supplier_id: 4, article_category_id: 13, unit: 'kg', + availability: true, price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':2ac18b7') +Article.create!(name: 'Blauwe rozijnen Flames', supplier_id: 4, article_category_id: 13, unit: 'kg', + availability: true, price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':16bfa75') +Article.create!(name: 'Gele Rozijnen', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.2222E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':1c59324') +Article.create!(name: 'Rode Rozijnen', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.1111E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':c3fcd84') +Article.create!(name: 'Cranberries heel', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.222E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':921c168') +Article.create!(name: 'Gedroogde Appeltjes', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.555E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':902c67b') +Article.create!(name: 'Gedroogde pruimen zonder pit', supplier_id: 4, article_category_id: 13, unit: 'kg', + availability: true, price: 0.222E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':a847f91') +Article.create!(name: 'Pompoenpitten', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.111E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':535645f') +Article.create!(name: 'Zonnenbloepitten', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.666E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':4ab9a83') +Article.create!(name: 'Lijnzaad', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.55E0, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':04be223') +Article.create!(name: 'Maanzaad', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.7777E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':ec5b2b9') +Article.create!(name: 'Pijnboompitten medium china', supplier_id: 4, article_category_id: 13, unit: 'kg', + availability: true, price: 0.2222E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':0e5b0b8') +Article.create!(name: 'Goji bessen', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.888E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':d52ee00') +Article.create!(name: 'Mulberries', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.5555E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':5f46bd5') +Article.create!(name: 'Gepelde Hennep', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.5555E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':c39165b') +Article.create!(name: 'Incaberries', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.888E1, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':8d44fe7') +Article.create!(name: 'Blueberries', supplier_id: 4, article_category_id: 13, unit: 'kg', availability: true, + price: 0.2222E2, tax: 6.0, deposit: 0.0, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], order_number: ':9a95422') +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, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], 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, article_unit_ratios: [ArticleUnitRatio.new({ sort: 1, quantity: 1, unit: 'XPP' })], 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') -User.create!(:id => 2, :nick => "john", :password => "secret", :first_name => "John", :last_name => "Doe", :email => "john@doe.test", :created_on => 'Sun, 19 Jan 2014 17:38:22 UTC +00:00') -User.create!(:id => 3, :nick => "peter", :password => "secret", :first_name => "Peter", :last_name => "Pieterssen", :email => "peter@pieterssen.test", :created_on => 'Sat, 25 Jan 2014 20:20:36 UTC +00:00') -User.create!(:id => 4, :nick => "jan", :password => "secret", :first_name => "Jan", :last_name => "Klaassen", :email => "jan@klaassen.test", :created_on => 'Mon, 27 Jan 2014 16:22:14 UTC +00:00') -User.create!(:id => 5, :nick => "mary", :password => "secret", :first_name => "Marie", :last_name => "Klaassen", :email => "mary@klaassen.test", :created_on => 'Mon, 03 Feb 2014 11:47:17 UTC +00:00') - -Workgroup.create!(:id => 1, :name => "Admins", :description => "Beheerders", :account_balance => 0.0, :created_on => 'Wed, 15 Jan 2014 16:15:33 UTC +00:00', :role_admin => true, :role_suppliers => true, :role_article_meta => true, :role_finance => true, :role_orders => true, :next_weekly_tasks_number => 8, :ignore_apple_restriction => false) -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) - -Membership.create!(:group_id => 1, :user_id => 1) -Membership.create!(:group_id => 5, :user_id => 1) -Membership.create!(:group_id => 2, :user_id => 2) -Membership.create!(:group_id => 8, :user_id => 2) -Membership.create!(:group_id => 6, :user_id => 3) -Membership.create!(:group_id => 7, :user_id => 4) -Membership.create!(:group_id => 8, :user_id => 4) -Membership.create!(:group_id => 3, :user_id => 4) -Membership.create!(:group_id => 7, :user_id => 5) -Membership.create!(:group_id => 3, :user_id => 5) -Membership.create!(:group_id => 4, :user_id => 5) +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') +User.create!(id: 2, nick: 'john', password: 'secret', first_name: 'John', last_name: 'Doe', email: 'john@doe.test', + created_on: 'Sun, 19 Jan 2014 17:38:22 UTC +00:00') +User.create!(id: 3, nick: 'peter', password: 'secret', first_name: 'Peter', last_name: 'Pieterssen', + email: 'peter@pieterssen.test', created_on: 'Sat, 25 Jan 2014 20:20:36 UTC +00:00') +User.create!(id: 4, nick: 'jan', password: 'secret', first_name: 'Jan', last_name: 'Klaassen', + email: 'jan@klaassen.test', created_on: 'Mon, 27 Jan 2014 16:22:14 UTC +00:00') +User.create!(id: 5, nick: 'mary', password: 'secret', first_name: 'Marie', last_name: 'Klaassen', + email: 'mary@klaassen.test', created_on: 'Mon, 03 Feb 2014 11:47:17 UTC +00:00') + +Workgroup.create!(id: 1, name: 'Admins', description: 'Beheerders', account_balance: 0.0, created_on: 'Wed, 15 Jan 2014 16:15:33 UTC +00:00', role_admin: true, role_suppliers: true, role_article_meta: true, role_finance: true, role_orders: true, next_weekly_tasks_number: 8, + ignore_apple_restriction: false) +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) + +Membership.create!(group_id: 1, user_id: 1) +Membership.create!(group_id: 5, user_id: 1) +Membership.create!(group_id: 2, user_id: 2) +Membership.create!(group_id: 8, user_id: 2) +Membership.create!(group_id: 6, user_id: 3) +Membership.create!(group_id: 7, user_id: 4) +Membership.create!(group_id: 8, user_id: 4) +Membership.create!(group_id: 3, user_id: 4) +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 @@ -181,10 +307,15 @@ ## Finances -FinancialTransactionType.create!(:id => 1, :name => "Foodcoop", :financial_transaction_class_id => 1) +FinancialTransactionType.create!(id: 1, name: 'Foodcoop', financial_transaction_class_id: 1) -FinancialTransaction.create!(:id => 1, :ordergroup_id => 5, :amount => -0.35E2, :note => "Membership fee for ordergroup", :user_id => 1, :created_on => 'Sat, 18 Jan 2014 00:38:48 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 3, :ordergroup_id => 6, :amount => -0.35E2, :note => "Membership fee for ordergroup", :user_id => 1, :created_on => 'Sat, 25 Jan 2014 20:20:37 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 4, :ordergroup_id => 7, :amount => -0.35E2, :note => "Membership fee for ordergroup", :user_id => 1, :created_on => 'Mon, 27 Jan 2014 16:22:14 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 5, :ordergroup_id => 5, :amount => 0.35E2, :note => "payment", :user_id => 2, :created_on => 'Wed, 05 Feb 2014 16:49:24 UTC +00:00', :financial_transaction_type_id => 1) -FinancialTransaction.create!(:id => 6, :ordergroup_id => 8, :amount => 0.90E2, :note => "Bank transfer", :user_id => 2, :created_on => 'Mon, 17 Feb 2014 16:19:34 UTC +00:00', :financial_transaction_type_id => 1) +FinancialTransaction.create!(id: 1, ordergroup_id: 5, amount: -0.35E2, note: 'Membership fee for ordergroup', + user_id: 1, created_on: 'Sat, 18 Jan 2014 00:38:48 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 3, ordergroup_id: 6, amount: -0.35E2, note: 'Membership fee for ordergroup', + user_id: 1, created_on: 'Sat, 25 Jan 2014 20:20:37 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 4, ordergroup_id: 7, amount: -0.35E2, note: 'Membership fee for ordergroup', + user_id: 1, created_on: 'Mon, 27 Jan 2014 16:22:14 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 5, ordergroup_id: 5, amount: 0.35E2, note: 'payment', user_id: 2, + created_on: 'Wed, 05 Feb 2014 16:49:24 UTC +00:00', financial_transaction_type_id: 1) +FinancialTransaction.create!(id: 6, ordergroup_id: 8, amount: 0.90E2, note: 'Bank transfer', user_id: 2, + created_on: 'Mon, 17 Feb 2014 16:19:34 UTC +00:00', financial_transaction_type_id: 1) diff --git a/db_shared/migrate/20221204112447_create_articles_and_suppliers.rb b/db_shared/migrate/20221204112447_create_articles_and_suppliers.rb index 33634e55..f39909cd 100644 --- a/db_shared/migrate/20221204112447_create_articles_and_suppliers.rb +++ b/db_shared/migrate/20221204112447_create_articles_and_suppliers.rb @@ -1,50 +1,50 @@ class CreateArticlesAndSuppliers < ActiveRecord::Migration[5.2] def change - create_table "articles", force: :cascade do |t| - t.string "name", null: false - t.integer "supplier_id", null: false - t.string "number" - t.string "note" - t.string "manufacturer" - t.string "origin" - t.string "unit" - t.decimal "price", precision: 8, scale: 2, default: "0.0", null: false - t.decimal "tax", precision: 3, scale: 1, default: "7.0", null: false - t.decimal "deposit", precision: 8, scale: 2, default: "0.0", null: false - t.decimal "unit_quantity", precision: 4, scale: 1, default: "1.0", null: false - t.decimal "scale_quantity", precision: 4, scale: 2 - t.decimal "scale_price", precision: 8, scale: 2 - t.datetime "created_on" - t.datetime "updated_on" - t.string "category" - t.index ["name"], name: "index_articles_on_name" - t.index %w[number supplier_id], name: "index_articles_on_number_and_supplier_id", unique: true + create_table 'articles', force: :cascade do |t| + t.string 'name', null: false + t.integer 'supplier_id', null: false + t.string 'number' + t.string 'note' + t.string 'manufacturer' + t.string 'origin' + t.string 'unit' + t.decimal 'price', precision: 8, scale: 2, default: '0.0', null: false + t.decimal 'tax', precision: 3, scale: 1, default: '7.0', null: false + t.decimal 'deposit', precision: 8, scale: 2, default: '0.0', null: false + t.decimal 'unit_quantity', precision: 4, scale: 1, default: '1.0', null: false + t.decimal 'scale_quantity', precision: 4, scale: 2 + t.decimal 'scale_price', precision: 8, scale: 2 + t.datetime 'created_on' + t.datetime 'updated_on' + t.string 'category' + t.index ['name'], name: 'index_articles_on_name' + t.index %w[number supplier_id], name: 'index_articles_on_number_and_supplier_id', unique: true end - create_table "suppliers", force: :cascade do |t| - t.string "name", null: false - t.string "address", null: false - t.string "phone", null: false - t.string "phone2" - t.string "fax" - t.string "email" - t.string "url" - t.string "delivery_days" - t.string "note" - t.datetime "created_on" - t.datetime "updated_on" - t.boolean "ftp_sync", default: false - t.string "ftp_host" - t.string "ftp_user" - t.string "ftp_password" - t.string "ftp_type", default: "bnn", null: false - t.string "ftp_regexp", default: "^([.]/)?PL" - t.boolean "mail_sync" - t.string "mail_from" - t.string "mail_subject" - t.string "mail_type" - t.string "salt", null: true - t.index ["name"], name: "index_suppliers_on_name", unique: true + create_table 'suppliers', force: :cascade do |t| + t.string 'name', null: false + t.string 'address', null: false + t.string 'phone', null: false + t.string 'phone2' + t.string 'fax' + t.string 'email' + t.string 'url' + t.string 'delivery_days' + t.string 'note' + t.datetime 'created_on' + t.datetime 'updated_on' + t.boolean 'ftp_sync', default: false + t.string 'ftp_host' + t.string 'ftp_user' + t.string 'ftp_password' + t.string 'ftp_type', default: 'bnn', null: false + t.string 'ftp_regexp', default: '^([.]/)?PL' + t.boolean 'mail_sync' + t.string 'mail_from' + t.string 'mail_subject' + t.string 'mail_type' + t.string 'salt', null: true + t.index ['name'], name: 'index_suppliers_on_name', unique: true end end end diff --git a/db_shared/schema.rb b/db_shared/schema.rb index 67cb6a6d..19fbca91 100644 --- a/db_shared/schema.rb +++ b/db_shared/schema.rb @@ -10,53 +10,51 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2022_12_04_112447) do - - create_table "articles", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t| - t.string "name", null: false - t.integer "supplier_id", null: false - t.string "number" - t.string "note" - t.string "manufacturer" - t.string "origin" - t.string "unit" - t.decimal "price", precision: 8, scale: 2, default: "0.0", null: false - t.decimal "tax", precision: 3, scale: 1, default: "7.0", null: false - t.decimal "deposit", precision: 8, scale: 2, default: "0.0", null: false - t.decimal "unit_quantity", precision: 4, scale: 1, default: "1.0", null: false - t.decimal "scale_quantity", precision: 4, scale: 2 - t.decimal "scale_price", precision: 8, scale: 2 - t.datetime "created_on" - t.datetime "updated_on" - t.string "category" - t.index ["name"], name: "index_articles_on_name" - t.index ["number", "supplier_id"], name: "index_articles_on_number_and_supplier_id", unique: true +ActiveRecord::Schema.define(version: 20_221_204_112_447) do + create_table 'articles', options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4', force: :cascade do |t| + t.string 'name', null: false + t.integer 'supplier_id', null: false + t.string 'number' + t.string 'note' + t.string 'manufacturer' + t.string 'origin' + t.string 'unit' + t.decimal 'price', precision: 8, scale: 2, default: '0.0', null: false + t.decimal 'tax', precision: 3, scale: 1, default: '7.0', null: false + t.decimal 'deposit', precision: 8, scale: 2, default: '0.0', null: false + t.decimal 'unit_quantity', precision: 4, scale: 1, default: '1.0', null: false + t.decimal 'scale_quantity', precision: 4, scale: 2 + t.decimal 'scale_price', precision: 8, scale: 2 + t.datetime 'created_on' + t.datetime 'updated_on' + t.string 'category' + t.index ['name'], name: 'index_articles_on_name' + t.index %w[number supplier_id], name: 'index_articles_on_number_and_supplier_id', unique: true end - create_table "suppliers", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t| - t.string "name", null: false - t.string "address", null: false - t.string "phone", null: false - t.string "phone2" - t.string "fax" - t.string "email" - t.string "url" - t.string "delivery_days" - t.string "note" - t.datetime "created_on" - t.datetime "updated_on" - t.boolean "ftp_sync", default: false - t.string "ftp_host" - t.string "ftp_user" - t.string "ftp_password" - t.string "ftp_type", default: "bnn", null: false - t.string "ftp_regexp", default: "^([.]/)?PL" - t.boolean "mail_sync" - t.string "mail_from" - t.string "mail_subject" - t.string "mail_type" - t.string "salt" - t.index ["name"], name: "index_suppliers_on_name", unique: true + create_table 'suppliers', options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4', force: :cascade do |t| + t.string 'name', null: false + t.string 'address', null: false + t.string 'phone', null: false + t.string 'phone2' + t.string 'fax' + t.string 'email' + t.string 'url' + t.string 'delivery_days' + t.string 'note' + t.datetime 'created_on' + t.datetime 'updated_on' + t.boolean 'ftp_sync', default: false + t.string 'ftp_host' + t.string 'ftp_user' + t.string 'ftp_password' + t.string 'ftp_type', default: 'bnn', null: false + t.string 'ftp_regexp', default: '^([.]/)?PL' + t.boolean 'mail_sync' + t.string 'mail_from' + t.string 'mail_subject' + t.string 'mail_type' + t.string 'salt' + t.index ['name'], name: 'index_suppliers_on_name', unique: true end - end diff --git a/lib/apple_bar.rb b/lib/apple_bar.rb index a2176ea3..3f81197d 100644 --- a/lib/apple_bar.rb +++ b/lib/apple_bar.rb @@ -14,13 +14,11 @@ def initialize(ordergroup) def group_bar_state if apples >= 100 'success' + elsif FoodsoftConfig[:stop_ordering_under].present? and + apples >= FoodsoftConfig[:stop_ordering_under] + 'warning' else - if FoodsoftConfig[:stop_ordering_under].present? and - apples >= FoodsoftConfig[:stop_ordering_under] - 'warning' - else - 'danger' - end + 'danger' end end @@ -30,7 +28,9 @@ def group_bar_width end def mean_order_amount_per_job - (1 / @global_avg).round rescue 0 + (1 / @global_avg).round + rescue StandardError + 0 end def apples diff --git a/lib/article_units_lib.rb b/lib/article_units_lib.rb index 92fae514..b99aded5 100644 --- a/lib/article_units_lib.rb +++ b/lib/article_units_lib.rb @@ -1,6 +1,9 @@ class ArticleUnitsLib - @un_ece_20_units = YAML.safe_load(ERB.new(File.read(File.expand_path('config/units-of-measure/un-ece-20-remastered.yml', Rails.root))).result) - @un_ece_21_units = YAML.safe_load(ERB.new(File.read(File.expand_path('config/units-of-measure/un-ece-21.yml', Rails.root))).result) + @un_ece_20_units = YAML.safe_load(ERB.new(File.read(File.expand_path( + 'config/units-of-measure/un-ece-20-remastered.yml', Rails.root + ))).result) + @un_ece_21_units = YAML.safe_load(ERB.new(File.read(File.expand_path('config/units-of-measure/un-ece-21.yml', + Rails.root))).result) def self.untranslated_units return @untranslated_units unless @untranslated_units.nil? @@ -10,7 +13,9 @@ def self.untranslated_units @un_ece_20_units.each do |unit| code = unit['CommonCode'] base_unit = unit['conversion']['base_units'].nil? ? nil : unit['conversion']['base_units'][0] - options[code] = { name: unit['Name'], description: unit['Description'], baseUnit: base_unit, conversionFactor: unit['conversion']['factor'], symbol: unit['Symbol'] } + options[code] = + { name: unit['Name'], description: unit['Description'], baseUnit: base_unit, + conversionFactor: unit['conversion']['factor'], symbol: unit['Symbol'] } end @un_ece_21_units.each do |unit| @@ -18,7 +23,8 @@ def self.untranslated_units name = unit['Name'] name[0] = name[0].downcase - options[code] = { name: name, description: unit['Description'], baseUnit: nil, conversionFactor: nil, symbol: unit['Symbol'] } + options[code] = + { name: name, description: unit['Description'], baseUnit: nil, conversionFactor: nil, symbol: unit['Symbol'] } end options.each do |code, option| @@ -31,13 +37,15 @@ def self.untranslated_units def self.unit_translations return @unit_translations unless @unit_translations.nil? - @unit_translations = YAML.safe_load(ERB.new(File.read(File.expand_path("config/units-of-measure/locales/unece_#{I18n.locale}.yml", Rails.root))).result) || {} + @unit_translations = YAML.safe_load(ERB.new(File.read(File.expand_path( + "config/units-of-measure/locales/unece_#{I18n.locale}.yml", Rails.root + ))).result) || {} end def self.units return @units unless @units.nil? - units = self.untranslated_units + units = untranslated_units @units = units.to_h do |code, unit| translated_name = ArticleUnitsLib.get_translated_name_for_code(code, default_nil: true) unit = unit.clone @@ -57,31 +65,31 @@ def self.unit_is_si_convertible(code) def self.get_translated_name_for_code(code, default_nil: false) return nil if code.blank? - self.unit_translations&.dig('unece_units')&.dig(code)&.dig('name') || (default_nil ? nil : self.untranslated_units[code][:name]) + unit_translations&.dig('unece_units')&.dig(code)&.dig('name') || (default_nil ? nil : untranslated_units[code][:name]) end def self.get_translated_symbol_for_code(code) return nil if code.blank? - self.unit_translations&.dig('unece_units')&.dig(code)&.dig('symbols')&.dig(0) || self.untranslated_units[code][:symbol] + unit_translations&.dig('unece_units')&.dig(code)&.dig('symbols')&.dig(0) || untranslated_units[code][:symbol] end def self.get_translated_aliases_for_code(code) return nil if code.blank? - self.unit_translations&.dig('unece_units')&.dig(code)&.dig('aliases') + unit_translations&.dig('unece_units')&.dig(code)&.dig('aliases') end def self.get_code_for_unit_name(name) return nil if name.blank? - translation = self.unit_translations&.dig('unece_units')&.find do |_code, translations| + translation = unit_translations&.dig('unece_units')&.find do |_code, translations| translations['name'] == name end return translation[0] unless translation.nil? - matching_unit = self.units.find do |_code, unit| + matching_unit = units.find do |_code, unit| unit[:name] == name end @@ -160,7 +168,7 @@ def self.sort_by_translation_state(unit_a, unit_b) def self.matches_unit(unit_code, unit, unit_str) return true if unit[:symbol] == unit_str - translation_data = self.unit_translations&.dig('unece_units')&.dig(unit_code) + translation_data = unit_translations&.dig('unece_units')&.dig(unit_code) return true if translation_data&.dig('symbols')&.include?(unit_str) diff --git a/lib/articles_csv.rb b/lib/articles_csv.rb index c1f7fc7f..8202547f 100644 --- a/lib/articles_csv.rb +++ b/lib/articles_csv.rb @@ -20,7 +20,7 @@ def header Article.human_attribute_name(:minimum_order_quantity), Article.human_attribute_name(:billing_unit), Article.human_attribute_name(:article_category), - Article.human_attribute_name(:ratios_to_supplier_order_unit), + Article.human_attribute_name(:ratios_to_supplier_order_unit) ] end @@ -44,12 +44,14 @@ def data article.minimum_order_quantity, ArticleUnitsLib.get_translated_name_for_code(article.billing_unit), article.article_category.try(:name), - article.article_unit_ratios.map { |ratio| "#{ratio.quantity} #{escape_csv_ratio(ArticleUnitsLib.get_translated_name_for_code(ratio.unit))}" }.join(", ") + article.article_unit_ratios.map do |ratio| + "#{ratio.quantity} #{escape_csv_ratio(ArticleUnitsLib.get_translated_name_for_code(ratio.unit))}" + end.join(', ') ] end end def escape_csv_ratio(str) - str.gsub("\\", "\\\\").gsub(",", "\\,") + str.gsub('\\', '\\\\').gsub(',', '\\,') end end diff --git a/lib/bank_account_connector.rb b/lib/bank_account_connector.rb index 93e7cc7c..b728ebb9 100644 --- a/lib/bank_account_connector.rb +++ b/lib/bank_account_connector.rb @@ -8,9 +8,7 @@ def name nil end - def text - @text - end + attr_reader :text end class TextField @@ -24,13 +22,7 @@ def type nil end - def name - @name - end - - def value - @value - end + attr_reader :name, :value def label @label || @name.to_s @@ -73,17 +65,7 @@ def iban @bank_account.iban end - def auto_submit - @auto_submit - end - - def controls - @controls - end - - def count - @count - end + attr_reader :auto_submit, :controls, :count def text(data) @controls += [TextItem.new(data)] @@ -142,11 +124,9 @@ def finish @bank_account.save! end - def load(data) - end + def load(data); end - def dump - end + def dump; end def t(key, args = {}) return t(".fields.#{key}") unless key.is_a? String diff --git a/lib/bank_account_information_importer.rb b/lib/bank_account_information_importer.rb index 517f91c2..8e6626ad 100644 --- a/lib/bank_account_information_importer.rb +++ b/lib/bank_account_information_importer.rb @@ -24,16 +24,16 @@ def import!(content) iban: entityAccount && entityAccount[:iban], reference: t[:remittanceInformationUnstructured], text: entityName, - receipt: t[:additionalInformation], + receipt: t[:additionalInformation] }) ret += 1 end 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| + %w[closingBooked expected authorised openingBooked interimAvailable forwardAvailable nonInvoiced].each do |type| value = balances[type] - if value then + if value balance = value break end diff --git a/lib/bank_transaction_reference.rb b/lib/bank_transaction_reference.rb index d033c544..5e44f0ef 100644 --- a/lib/bank_transaction_reference.rb +++ b/lib/bank_transaction_reference.rb @@ -13,7 +13,7 @@ def self.parse(data) ret = { group: m[:group].to_i, parts: parts } ret[:user] = m[:user].to_i if m[:user] - return ret + ret end def self.js_code_for_user(user) diff --git a/lib/date_time_attribute_validate.rb b/lib/date_time_attribute_validate.rb index 08138d02..17b40d36 100644 --- a/lib/date_time_attribute_validate.rb +++ b/lib/date_time_attribute_validate.rb @@ -10,51 +10,67 @@ def date_time_attribute(*attributes) super attributes.each do |attribute| - validate -> { self.send("#{attribute}_datetime_value_valid") } + validate -> { send("#{attribute}_datetime_value_valid") } # allow resetting the field to nil before_validation do - if self.instance_variable_get("@#{attribute}_is_set") - date = self.instance_variable_get("@#{attribute}_date_value") - time = self.instance_variable_get("@#{attribute}_time_value") - if date.blank? && time.blank? - self.send("#{attribute}=", nil) - end + if instance_variable_get("@#{attribute}_is_set") + date = instance_variable_get("@#{attribute}_date_value") + time = instance_variable_get("@#{attribute}_time_value") + send("#{attribute}=", nil) if date.blank? && time.blank? end end # remember old date and time values define_method("#{attribute}_date_value=") do |val| - self.instance_variable_set("@#{attribute}_is_set", true) - self.instance_variable_set("@#{attribute}_date_value", val) - self.send("#{attribute}_date=", val) rescue nil + instance_variable_set("@#{attribute}_is_set", true) + instance_variable_set("@#{attribute}_date_value", val) + begin + send("#{attribute}_date=", val) + rescue StandardError + nil + end end define_method("#{attribute}_time_value=") do |val| - self.instance_variable_set("@#{attribute}_is_set", true) - self.instance_variable_set("@#{attribute}_time_value", val) - self.send("#{attribute}_time=", val) rescue nil + instance_variable_set("@#{attribute}_is_set", true) + instance_variable_set("@#{attribute}_time_value", val) + begin + send("#{attribute}_time=", val) + rescue StandardError + nil + end end # 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') } + instance_variable_get("@#{attribute}_date_value") || send("#{attribute}_date").try do |e| + e.strftime('%Y-%m-%d') + end end define_method("#{attribute}_time_value") do - self.instance_variable_get("@#{attribute}_time_value") || self.send("#{attribute}_time").try { |e| e.strftime('%H:%M') } + instance_variable_get("@#{attribute}_time_value") || send("#{attribute}_time").try { |e| e.strftime('%H:%M') } end private # validate date and time define_method("#{attribute}_datetime_value_valid") do - date = self.instance_variable_get("@#{attribute}_date_value") - unless date.blank? || (Date.parse(date) rescue nil) - errors.add(attribute, "is not a valid date") # @todo I18n + date = instance_variable_get("@#{attribute}_date_value") + unless date.blank? || begin + Date.parse(date) + rescue StandardError + nil end - time = self.instance_variable_get("@#{attribute}_time_value") - unless time.blank? || (Time.parse(time) rescue nil) - errors.add(attribute, "is not a valid time") # @todo I18n + errors.add(attribute, 'is not a valid date') # @todo I18n end + time = instance_variable_get("@#{attribute}_time_value") + return if time.blank? || begin + Time.parse(time) + rescue StandardError + nil + end + + errors.add(attribute, 'is not a valid time') # @todo I18n end end end diff --git a/lib/foodsoft/expansion_variables.rb b/lib/foodsoft/expansion_variables.rb index bcf67e7a..5ee54acb 100644 --- a/lib/foodsoft/expansion_variables.rb +++ b/lib/foodsoft/expansion_variables.rb @@ -39,7 +39,7 @@ module ExpansionVariables '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 } } + 'first_order_date' => -> { I18n.l(Order.first.try { |o| o.starts.to_date }) } } # Return expanded variable @@ -54,8 +54,8 @@ def self.get(var) # @param options [Hash] Extra variables to expand # @return [String] Expanded string def self.expand(str, options = {}) - str.gsub /{{([._a-zA-Z0-9]+)}}/ do - options[$1] || self.get($1) + str.gsub(/{{([._a-zA-Z0-9]+)}}/) do + options[::Regexp.last_match(1)] || get(::Regexp.last_match(1)) end end diff --git a/lib/foodsoft_config.rb b/lib/foodsoft_config.rb index 33fa9e45..3f6b893d 100644 --- a/lib/foodsoft_config.rb +++ b/lib/foodsoft_config.rb @@ -68,7 +68,7 @@ def init(filename = APP_CONFIG_FILE) # Load initial config from development or production set_config Rails.env # Overwrite scope to have a better namescope than 'production' - self.scope = config[:default_scope] or raise "No default_scope is set" + self.scope = config[:default_scope] or raise 'No default_scope is set' # Set defaults for backward-compatibility set_missing # Make sure relevant configuration is applied, also in single coops mode, @@ -77,7 +77,7 @@ def init(filename = APP_CONFIG_FILE) end def init_mailing - [:protocol, :host, :port, :script_name].each do |k| + %i[protocol host port script_name].each do |k| ActionMailer::Base.default_url_options[k] = self[k] if self[k] end end @@ -115,7 +115,7 @@ def select_multifoodcoop(foodcoop) # @return [Object] Value of the key. def [](key) if RailsSettings::CachedSettings.table_exists? && allowed_key?(key) - value = RailsSettings::CachedSettings["foodcoop.#{self.scope}.#{key}"] + value = RailsSettings::CachedSettings["foodcoop.#{scope}.#{key}"] value = config[key] if value.nil? value else @@ -137,20 +137,19 @@ def []=(key, value) if config[key] == value || (config[key].nil? && value == false) # delete (ok if it was already deleted) begin - RailsSettings::CachedSettings.destroy "foodcoop.#{self.scope}.#{key}" + RailsSettings::CachedSettings.destroy "foodcoop.#{scope}.#{key}" rescue RailsSettings::Settings::SettingNotFound end else # or store - RailsSettings::CachedSettings["foodcoop.#{self.scope}.#{key}"] = value + RailsSettings::CachedSettings["foodcoop.#{scope}.#{key}"] = value end - 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 = RailsSettings::CachedSettings.get_all("foodcoop.#{scope}.").try(:keys) || [] + keys.map! { |k| k.gsub(/^foodcoop\.#{scope}\./, '') } keys += config.keys keys.map(&:to_s).uniq end @@ -179,17 +178,17 @@ def allowed_foodcoop?(foodcoop) # @return [Boolean] Whether this key may be set in the database def allowed_key?(key) # fast check for keys without nesting - if self.config[:protected].include? key - !self.config[:protected][key] + if config[:protected].include? key + !config[:protected][key] else - !self.config[:protected][:all] + !config[:protected][:all] end # @todo allow to check nested keys as well end # @return [Hash] Full configuration. def to_hash - keys.map { |k| [k, self[k]] }.to_h + keys.index_with { |k| self[k] } end # for using active_model_serializer in the api/v1/configs controller @@ -286,7 +285,9 @@ def get_default_config def normalize_value(value) 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 do |a| + [a[0], normalize_value(a[1])] + end] end case value when 'true' then true diff --git a/lib/foodsoft_date_util.rb b/lib/foodsoft_date_util.rb index 98dc1c61..b1bc7430 100644 --- a/lib/foodsoft_date_util.rb +++ b/lib/foodsoft_date_util.rb @@ -6,11 +6,13 @@ def self.next_occurrence(start = Time.now, from = start, options = {}) schedule = IceCube::Schedule.new(start) schedule.add_recurrence_rule rule_from(options[:recurr]) # @todo handle ical parse errors - occ = (schedule.next_occurrence(from).to_time rescue nil) - end - if options && options[:time] && occ - occ = occ.beginning_of_day.advance(seconds: Time.parse(options[:time]).seconds_since_midnight) + occ = begin + schedule.next_occurrence(from).to_time + rescue StandardError + nil + end end + occ = occ.beginning_of_day.advance(seconds: Time.parse(options[:time]).seconds_since_midnight) if options && options[:time] && occ occ end diff --git a/lib/foodsoft_file.rb b/lib/foodsoft_file.rb index 09c12bf0..4276fcea 100644 --- a/lib/foodsoft_file.rb +++ b/lib/foodsoft_file.rb @@ -8,24 +8,24 @@ def self.parse(file, options = {}) SpreadsheetFile.parse file, options do |row| next if row[2].blank? - article = { :availability => row[0]&.strip&.downcase != 'x', - :order_number => row[1], - :name => row[2], - :note => row[3], - :manufacturer => row[4], - :origin => row[5], - :unit => row[6], - :price => row[7], - :tax => row[8], - :deposit => (row[9].nil? ? "0" : row[9]), - :supplier_order_unit => ArticleUnitsLib.get_code_for_unit_name(row[10]), - :price_unit => ArticleUnitsLib.get_code_for_unit_name(row[11]), - :group_order_unit => ArticleUnitsLib.get_code_for_unit_name(row[12]), - :group_order_granularity => row[13], - :minimum_order_quantity => row[14], - :billing_unit => ArticleUnitsLib.get_code_for_unit_name(row[15]), - :article_category => row[16], - :article_unit_ratios => FoodsoftFile.parse_ratios_cell(row[17]) } + article = { availability: row[0]&.strip&.downcase != 'x', + order_number: row[1], + name: row[2], + note: row[3], + manufacturer: row[4], + origin: row[5], + unit: row[6], + price: row[7], + tax: row[8], + deposit: (row[9].nil? ? '0' : row[9]), + supplier_order_unit: ArticleUnitsLib.get_code_for_unit_name(row[10]), + price_unit: ArticleUnitsLib.get_code_for_unit_name(row[11]), + group_order_unit: ArticleUnitsLib.get_code_for_unit_name(row[12]), + group_order_granularity: row[13], + minimum_order_quantity: row[14], + billing_unit: ArticleUnitsLib.get_code_for_unit_name(row[15]), + article_category: row[16], + article_unit_ratios: FoodsoftFile.parse_ratios_cell(row[17]) } articles << article end @@ -36,7 +36,8 @@ def self.parse_ratios_cell(ratios_cell) return [] if ratios_cell.blank? ratios = ratios_cell.split(/(?[+-]?(?:[0-9]*[.])?[0-9]+) (?.*)/) + md = ratio_str.gsub('\\\\', '\\').gsub('\\,', + ',').match(/(?[+-]?(?:[0-9]*[.])?[0-9]+) (?.*)/) { sort: index + 1, quantity: md[:quantity], diff --git a/lib/foodsoft_mail_receiver.rb b/lib/foodsoft_mail_receiver.rb index 560e7edd..7c5918a7 100644 --- a/lib/foodsoft_mail_receiver.rb +++ b/lib/foodsoft_mail_receiver.rb @@ -19,31 +19,29 @@ def start private - def on_rcpt_to_event(ctx, rcpt_to) + def on_rcpt_to_event(_ctx, rcpt_to) recipient = rcpt_to.gsub(/^\s*<\s*(.*)\s*>\s*$/, '\1') @handlers << self.class.find_handler(recipient) rcpt_to - rescue => error - logger.info("Can not accept mail for '#{rcpt_to}': #{error}") + rescue StandardError => e + logger.info("Can not accept mail for '#{rcpt_to}': #{e}") raise MidiSmtpServer::Smtpd550Exception end def on_message_data_event(ctx) - begin - @handlers.each do |handler| - handler.call(ctx[:message][:data]) - end - rescue => error - ExceptionNotifier.notify_exception(error, data: ctx) - raise error - ensure - @handlers.clear + @handlers.each do |handler| + handler.call(ctx[:message][:data]) end + rescue StandardError => e + ExceptionNotifier.notify_exception(e, data: ctx) + raise e + ensure + @handlers.clear end def self.find_handler(recipient) m = /(?[^@\.]+)\.(?
[^@]+)(@(?[^@]+))?/.match recipient - raise "recipient is missing or has an invalid format" if m.nil? + 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] @@ -51,10 +49,10 @@ def self.find_handler(recipient) @@registered_classes.each do |klass| if match = klass.regexp.match(m[:address]) handler = klass.new match - return lambda { |data| handler.received(data) } + return ->(data) { handler.received(data) } end end - raise "invalid format for recipient" + raise 'invalid format for recipient' end end diff --git a/lib/invoices_csv.rb b/lib/invoices_csv.rb index aa20cd08..ebd1f0a9 100644 --- a/lib/invoices_csv.rb +++ b/lib/invoices_csv.rb @@ -32,7 +32,7 @@ def data t.deposit, t.deposit_credit, t.paid_on, - t.note, + t.note ] end end diff --git a/lib/order_csv.rb b/lib/order_csv.rb index 2817bc1f..173b74fb 100644 --- a/lib/order_csv.rb +++ b/lib/order_csv.rb @@ -24,7 +24,8 @@ def data oa.article_version.name, format_supplier_order_unit_with_ratios(oa.article_version), # TODO-article-units: Why should we show the supplier the group order unit quantity?: - oa.article_version.convert_quantity(1, oa.article_version.supplier_order_unit, oa.article_version.group_order_unit), + oa.article_version.convert_quantity(1, oa.article_version.supplier_order_unit, + oa.article_version.group_order_unit), number_to_currency(oa.article_version.price), number_to_currency(oa.total_price) ] diff --git a/lib/order_pdf.rb b/lib/order_pdf.rb index 66a68619..a5ca69c1 100644 --- a/lib/order_pdf.rb +++ b/lib/order_pdf.rb @@ -57,13 +57,20 @@ def order_article_price_per_unit(order_article) def price_per_billing_unit(goa) article_version = goa.order_article.article_version - "#{number_to_currency(article_version.convert_quantity(article_version.fc_price, article_version.billing_unit, article_version.supplier_order_unit))} / #{format_billing_unit_with_ratios(article_version)}" + "#{number_to_currency(article_version.convert_quantity(article_version.fc_price, article_version.billing_unit, + article_version.supplier_order_unit))} / #{format_billing_unit_with_ratios(article_version)}" end def billign_quantity_with_tolerance(goa) article_version = goa.order_article.article_version - quantity = number_with_precision(article_version.convert_quantity(goa.quantity, article_version.group_order_unit, article_version.billing_unit), strip_insignificant_zeros: true, precision: 2) - tolerance = number_with_precision(article_version.convert_quantity(goa.tolerance, article_version.group_order_unit, article_version.billing_unit), strip_insignificant_zeros: true, precision: 2) + quantity = number_with_precision( + article_version.convert_quantity(goa.quantity, article_version.group_order_unit, + article_version.billing_unit), strip_insignificant_zeros: true, precision: 2 + ) + tolerance = number_with_precision( + article_version.convert_quantity(goa.tolerance, article_version.group_order_unit, + article_version.billing_unit), strip_insignificant_zeros: true, precision: 2 + ) goa.tolerance > 0 ? "#{quantity} + #{tolerance}" : quantity end @@ -73,7 +80,10 @@ def group_order_article_result(goa) def billing_article_result(goa) article_version = goa.order_article.article_version - number_with_precision(article_version.convert_quantity(goa.result, article_version.group_order_unit, article_version.billing_unit), precision: 2, strip_insignificant_zeros: true) + number_with_precision( + article_version.convert_quantity(goa.result, article_version.group_order_unit, + article_version.billing_unit), precision: 2, strip_insignificant_zeros: true + ) end def group_order_articles(ordergroup) @@ -150,7 +160,7 @@ def each_group_order_article_for_ordergroup(ordergroup, &block) group_order_articles(ordergroup) .includes(order_article: { article_version: { article: :supplier } }) .order('suppliers.name, article_versions.name') - .preload(order_article: [:article_version, :order]) + .preload(order_article: %i[article_version order]) .each(&block) end diff --git a/lib/order_txt.rb b/lib/order_txt.rb index 2c848eec..adb25698 100644 --- a/lib/order_txt.rb +++ b/lib/order_txt.rb @@ -1,5 +1,5 @@ class OrderTxt - def initialize(order, options = {}) + def initialize(order, _options = {}) @order = order end @@ -8,23 +8,24 @@ def initialize(order, options = {}) def to_txt supplier = @order.supplier contact = FoodsoftConfig[:contact].symbolize_keys - text = I18n.t('orders.fax.heading', :name => FoodsoftConfig[:name]) - text += "\n#{Supplier.human_attribute_name(:customer_number)}: #{supplier.customer_number}" unless supplier.customer_number.blank? + text = I18n.t('orders.fax.heading', name: FoodsoftConfig[:name]) + text += "\n#{Supplier.human_attribute_name(:customer_number)}: #{supplier.customer_number}" if supplier.customer_number.present? text += "\n" + I18n.t('orders.fax.delivery_day') text += "\n\n#{supplier.name}\n#{supplier.address}\n#{Supplier.human_attribute_name(:fax)}: #{supplier.fax}\n\n" - text += "****** " + I18n.t('orders.fax.to_address') + "\n\n" + 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 += '****** ' + I18n.t('orders.fax.articles') + "\n\n" + text += format("%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_version).each do |oa| - text += "%8s %8d %s\n" % [oa.article_version.order_number, oa.units_to_order.to_i, oa.article_version.name] + text += format("%8s %8d %s\n", oa.article_version.order_number, oa.units_to_order.to_i, oa.article_version.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.write("#{Rails.root.join("tmp/#{self.class.to_s.underscore}.txt")}", to_csv.force_encoding('UTF-8')) end end diff --git a/lib/ordergroups_csv.rb b/lib/ordergroups_csv.rb index c41d2e83..534bfc06 100644 --- a/lib/ordergroups_csv.rb +++ b/lib/ordergroups_csv.rb @@ -14,7 +14,7 @@ def header Ordergroup.human_attribute_name(:break_start), Ordergroup.human_attribute_name(:break_end), Ordergroup.human_attribute_name(:last_user_activity), - Ordergroup.human_attribute_name(:last_order), + Ordergroup.human_attribute_name(:last_order) ] row + Ordergroup.custom_fields.map { |f| f[:label] } end @@ -33,7 +33,7 @@ def data o.break_start, o.break_end, o.last_user_activity, - o.last_order.try(:starts), + o.last_order.try(:starts) ] yield row + Ordergroup.custom_fields.map { |f| o.settings.custom_fields[f[:name]] } end diff --git a/lib/render_csv.rb b/lib/render_csv.rb index aad84251..5c1203b9 100644 --- a/lib/render_csv.rb +++ b/lib/render_csv.rb @@ -13,7 +13,7 @@ def initialize(object, options = {}) 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 @@ -34,7 +34,7 @@ def data # 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.write("#{Rails.root.join("tmp/#{self.class.to_s.underscore}.csv")}", to_csv.force_encoding(encoding)) end # XXX disable unit to avoid encoding problems, both in unit and whitespace. Also allows computations in spreadsheet. diff --git a/lib/render_pdf.rb b/lib/render_pdf.rb index b79e2a55..4ef65064 100644 --- a/lib/render_pdf.rb +++ b/lib/render_pdf.rb @@ -18,7 +18,7 @@ def skew (height + (border_top_width / 2.0) + (border_bottom_width / 2.0)) / tan_rotation end - def styled_width_of(text) + def styled_width_of(_text) options = @text_options.reject { |k| k == :style } with_font { (@pdf.height_of(@content, options) + padding_top + padding_bottom) / tan_rotation } end @@ -120,7 +120,7 @@ def to_pdf # 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.write("#{Rails.root.join("tmp/#{self.class.to_s.underscore}.pdf")}", to_pdf.force_encoding('UTF-8')) end # @todo avoid underscore instead of unicode whitespace in pdf :/ @@ -166,6 +166,6 @@ def pdf_add_page_breaks?(docid = nil) end def font_path(name) - File.join(Rails.root, 'vendor', 'assets', 'fonts', name) + Rails.root.join('vendor', 'assets', 'fonts', name).to_s end end diff --git a/lib/tasks/db_shared.rake b/lib/tasks/db_shared.rake index eb0230b4..3f4a7e49 100644 --- a/lib/tasks/db_shared.rake +++ b/lib/tasks/db_shared.rake @@ -2,14 +2,14 @@ task spec: ['shared:db:test:prepare'] namespace :shared do namespace :db do |ns| - [:drop, :create, :setup, :migrate, :rollback, :seed, :version].each do |task_name| + %i[drop create setup migrate rollback seed version].each do |task_name| task task_name do Rake::Task["db:#{task_name}"].invoke end end namespace :schema do - [:load, :dump].each do |task_name| + %i[load dump].each do |task_name| task task_name do Rake::Task["db:schema:#{task_name}"].invoke end @@ -33,7 +33,7 @@ namespace :shared do task set_custom_config: :environment do # save current vars @original_config = { - env_schema: ENV['SCHEMA'], + env_schema: ENV.fetch('SCHEMA', nil), config: Rails.application.config.dup } diff --git a/lib/tasks/foodsoft.rake b/lib/tasks/foodsoft.rake index 5a5c6fa0..218bb39f 100644 --- a/lib/tasks/foodsoft.rake +++ b/lib/tasks/foodsoft.rake @@ -1,71 +1,71 @@ # put in here all foodsoft tasks # => :environment loads the environment an gives easy access to the application namespace :foodsoft do - desc "Finish ended orders" - task :finish_ended_orders => :environment do + desc 'Finish ended orders' + task finish_ended_orders: :environment do Order.finish_ended! end - desc "Notify users of upcoming tasks" - task :notify_upcoming_tasks => :environment do + desc 'Notify users of upcoming tasks' + task notify_upcoming_tasks: :environment do tasks = Task.where(done: false, due_date: 1.day.from_now.to_date) for task in tasks rake_say "Send notifications for #{task.name} to .." for user in task.users - if user.settings.notify['upcoming_tasks'] - Mailer.deliver_now_with_user_locale user do - Mailer.upcoming_tasks(user, task) - end + next unless user.settings.notify['upcoming_tasks'] + + Mailer.deliver_now_with_user_locale user do + Mailer.upcoming_tasks(user, task) end end end end - desc "Notify workgroup of upcoming weekly task" - task :notify_users_of_weekly_task => :environment do - tasks = Task.where(done: false, due_date: 7.day.from_now.to_date) + desc 'Notify workgroup of upcoming weekly task' + task notify_users_of_weekly_task: :environment do + tasks = Task.where(done: false, due_date: 7.days.from_now.to_date) for task in tasks - unless task.enough_users_assigned? - workgroup = task.workgroup - if workgroup - rake_say "Notify workgroup: #{workgroup.name} for task #{task.name}" - for user in workgroup.users - if user.receive_email? - Mailer.deliver_now_with_user_locale user do - Mailer.not_enough_users_assigned(task, user) - end - end - end + next if task.enough_users_assigned? + + workgroup = task.workgroup + next unless workgroup + + rake_say "Notify workgroup: #{workgroup.name} for task #{task.name}" + for user in workgroup.users + next unless user.receive_email? + + Mailer.deliver_now_with_user_locale user do + Mailer.not_enough_users_assigned(task, user) end end end end - desc "Create upcoming periodic tasks" - task :create_upcoming_periodic_tasks => :environment do + desc 'Create upcoming periodic tasks' + task create_upcoming_periodic_tasks: :environment do for tg in PeriodicTaskGroup.all created_until = tg.create_tasks_for_upfront_days rake_say "created until #{created_until}" end end - desc "Parse incoming email on stdin (options: RECIPIENT=foodcoop.handling)" - task :parse_reply_email => :environment do - FoodsoftMailReceiver.received ENV['RECIPIENT'], STDIN.read + desc 'Parse incoming email on stdin (options: RECIPIENT=foodcoop.handling)' + task parse_reply_email: :environment do + FoodsoftMailReceiver.received ENV.fetch('RECIPIENT', nil), STDIN.read end - desc "Start STMP server for incoming email (options: SMTP_SERVER_PORT=2525, SMTP_SERVER_HOST=0.0.0.0)" - task :reply_email_smtp_server => :environment do + desc 'Start STMP server for incoming email (options: SMTP_SERVER_PORT=2525, SMTP_SERVER_HOST=0.0.0.0)' + task reply_email_smtp_server: :environment do port = ENV['SMTP_SERVER_PORT'].present? ? ENV['SMTP_SERVER_PORT'].to_i : 2525 - host = ENV['SMTP_SERVER_HOST'] + host = ENV.fetch('SMTP_SERVER_HOST', nil) rake_say "Started SMTP server for incoming email on port #{port}." server = FoodsoftMailReceiver.new(ports: port, hosts: host, max_processings: 1, logger: Rails.logger) server.start server.join end - desc "Import and assign bank transactions" - task :import_and_assign_bank_transactions => :environment do + desc 'Import and assign bank transactions' + task import_and_assign_bank_transactions: :environment do BankAccount.find_each do |ba| importer = ba.find_connector next unless importer diff --git a/lib/tasks/foodsoft_setup.rake b/lib/tasks/foodsoft_setup.rake index baa483d1..70b96f26 100644 --- a/lib/tasks/foodsoft_setup.rake +++ b/lib/tasks/foodsoft_setup.rake @@ -9,14 +9,14 @@ module Colors 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) @@ -26,31 +26,31 @@ end include Colors namespace :foodsoft do - desc "Setup foodsoft" + desc 'Setup foodsoft' task :setup_development do - puts yellow "This task will help you get your foodcoop running in development." + puts yellow 'This task will help you get your foodcoop running in development.' setup_bundler setup_app_config setup_development setup_database setup_storage start_mailcatcher - puts yellow "All done! Your foodsoft setup should be running smoothly." + puts yellow 'All done! Your foodsoft setup should be running smoothly.' start_server end - desc "Setup foodsoft" + desc 'Setup foodsoft' task :setup_development_docker do - puts yellow "This task will help you get your foodcoop running in development via docker." + puts yellow 'This task will help you get your foodcoop running in development via docker.' setup_app_config setup_development setup_storage setup_run_rake_db_setup - puts yellow "All done! Your foodsoft setup should be running smoothly via docker." + puts yellow 'All done! Your foodsoft setup should be running smoothly via docker.' end namespace :setup do - desc "Initialize stock configuration" + desc 'Initialize stock configuration' task :stock_config do setup_app_config setup_development @@ -59,39 +59,39 @@ namespace :foodsoft do end def setup_bundler - puts yellow "Installing bundler if not installed..." + puts yellow 'Installing bundler if not installed...' %x(if [ -z `which bundle` ]; then gem install bundler --no-rdoc --no-ri; fi) - puts yellow "Executing bundle install..." - %x(bundle install) + puts yellow 'Executing bundle install...' + `bundle install` end def setup_database file = 'config/database.yml' if ENV['DATABASE_URL'] - puts blue "DATABASE_URL found, please remember to also set it when running Foodsoft" + puts blue 'DATABASE_URL found, please remember to also set it when running Foodsoft' 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"]) - if database == "1" - puts yellow "Using MySQL..." - %x(cp -p #{Rails.root.join("#{file}.MySQL_SAMPLE")} #{Rails.root.join(file)}) - elsif database == "2" - puts yellow "Using SQLite..." - %x(cp -p #{Rails.root.join("#{file}.SQLite_SAMPLE")} #{Rails.root.join(file)}) + database = ask("What kind of database do you use?\nOptions:\n(1) MySQL\n(2) SQLite", %w[1 2]) + if database == '1' + puts yellow 'Using MySQL...' + `cp -p #{Rails.root.join("#{file}.MySQL_SAMPLE")} #{Rails.root.join(file)}` + elsif database == '2' + puts yellow 'Using SQLite...' + `cp -p #{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"]) + 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']) setup_run_rake_db_setup if finished end def setup_run_rake_db_setup - Rake::Task["db:setup"].reenable - db_setup = capture_stdout { Rake::Task["db:setup"].invoke } + Rake::Task['db:setup'].reenable + db_setup = capture_stdout { Rake::Task['db:setup'].invoke } puts db_setup end @@ -101,7 +101,7 @@ def setup_app_config return nil if skip?(file) puts yellow "Copying #{file}..." - %x(cp -p #{sample} #{Rails.root.join(file)}) + `cp -p #{sample} #{Rails.root.join(file)}` reminder(file) end @@ -110,7 +110,7 @@ def setup_development return nil if skip?(file) puts yellow "Copying #{file}..." - %x(cp -p #{Rails.root.join("#{file}.SAMPLE")} #{Rails.root.join(file)}) + `cp -p #{Rails.root.join("#{file}.SAMPLE")} #{Rails.root.join(file)}` reminder(file) end @@ -119,18 +119,18 @@ def setup_storage return nil if skip?(file) puts yellow "Copying #{file}..." - %x(cp -p #{Rails.root.join("#{file}.SAMPLE")} #{Rails.root.join(file)}) + `cp -p #{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"]) - if mailcatcher === "y" - puts yellow "Starting mailcatcher at http://localhost:1080..." - %x(mailcatcher) - end + mailcatcher = ask("Do you want to start mailcatcher?\nOptions:\n(y) Yes\n(n) No", %w[y n]) + return unless mailcatcher === 'y' + + puts yellow 'Starting mailcatcher at http://localhost:1080...' + `mailcatcher` end def start_server @@ -143,7 +143,7 @@ def ask(question, answers = false) puts question input = STDIN.gets.chomp if input.blank? || (answers && !answers.include?(input)) - puts red "Your Input is not valid. Try again!" + puts red 'Your Input is not valid. Try again!' input = ask(question, answers) end input @@ -151,8 +151,11 @@ 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)) - output = true if skip == "1" + if File.exist?(Rails.root.join(file)) + skip = ask(cyan("We found #{file}!\nOptions:\n(1) Skip step\n(2) Force rewrite"), + %w[1 2]) + end + output = true if skip == '1' output end diff --git a/lib/tasks/multicoops.rake b/lib/tasks/multicoops.rake index cb2f280a..1e5ef44d 100644 --- a/lib/tasks/multicoops.rake +++ b/lib/tasks/multicoops.rake @@ -4,26 +4,24 @@ 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'] + task run: :environment do + task_to_run = ENV.fetch('TASK', nil) last_error = nil FoodsoftConfig.each_coop do |coop| - begin - rake_say "Run '#{task_to_run}' for #{coop}" - Rake::Task[task_to_run].execute - rescue => error - last_error = error - ExceptionNotifier.notify_exception(error, data: { foodcoop: coop }) - end + rake_say "Run '#{task_to_run}' for #{coop}" + Rake::Task[task_to_run].execute + rescue StandardError => e + last_error = e + ExceptionNotifier.notify_exception(e, data: { foodcoop: coop }) end raise last_error if last_error end desc 'Runs a specific rake task for a single coop, use rake mutlicoops:run_single TASK=db:migrate FOODCOOP=demo' - task :run_single => :environment do - task_to_run = ENV['TASK'] - FoodsoftConfig.select_foodcoop ENV['FOODCOOP'] - rake_say "Run '#{task_to_run}' for #{ENV['FOODCOOP']}" + task run_single: :environment do + task_to_run = ENV.fetch('TASK', nil) + FoodsoftConfig.select_foodcoop ENV.fetch('FOODCOOP', nil) + rake_say "Run '#{task_to_run}' for #{ENV.fetch('FOODCOOP', nil)}" Rake::Task[task_to_run].execute end end diff --git a/lib/tasks/resque.rake b/lib/tasks/resque.rake index 2c50bf69..8705035a 100644 --- a/lib/tasks/resque.rake +++ b/lib/tasks/resque.rake @@ -1,32 +1,32 @@ -require "resque/tasks" +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" } - count.times { + 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 do ## Using Kernel.spawn and Process.detach because regular system() call would ## cause the processes to quit when capistrano finishes - pid = spawn(env_vars, "bundle exec rake resque:work", ops) + pid = spawn(env_vars, 'bundle exec rake resque:work', ops) Process.detach(pid) - } + end end namespace :resque do - task :setup => :environment + task setup: :environment - desc "Restart running workers" + desc 'Restart running workers' task :restart_workers do Rake::Task['resque:stop_workers'].invoke Rake::Task['resque:start_workers'].invoke end - desc "Quit running workers" + desc 'Quit running workers' task :stop_workers do pids = File.read('tmp/pids/resque_worker_foodsoft_notifier.pid').split("\n") if pids.empty? - puts "No workers to kill" + puts 'No workers to kill' else syscmd = "kill -s QUIT #{pids.join(' ')}" puts "Running syscmd: #{syscmd}" @@ -34,8 +34,8 @@ namespace :resque do end end - desc "Start workers" + 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 4f0c4081..a90fa407 100644 --- a/lib/tasks/rspec.rake +++ b/lib/tasks/rspec.rake @@ -2,7 +2,7 @@ begin require 'rspec/core/rake_task' task(:spec).clear RSpec::Core::RakeTask.new(:spec) - task :default => :spec + task default: :spec # 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: diff --git a/lib/tasks/temp_export_supplier.rake b/lib/tasks/temp_export_supplier.rake index 9d367ab9..f0826768 100644 --- a/lib/tasks/temp_export_supplier.rake +++ b/lib/tasks/temp_export_supplier.rake @@ -1,12 +1,14 @@ namespace :temp_supplier do - task :export => :environment do + task export: :environment do supplier_id = ENV['SUPPLIER_ID']&.to_i - raise "Missing supplier id" if supplier_id.nil? + raise 'Missing supplier id' if supplier_id.nil? s = Supplier.find_by_id(supplier_id) article_hashes = s.articles.map do |a| article_attributes = a.attributes.delete_if { |key| %w[quantity type deleted_at shared_updated_on].include?(key) } - latest_version_attributes = a.latest_article_version.attributes.delete_if { |key| %w[article_id id].include?(key) } + latest_version_attributes = a.latest_article_version.attributes.delete_if do |key| + %w[article_id id].include?(key) + end aur = a.article_unit_ratios.map do |ratio| attributes = ratio.attributes attributes.delete_if { |key| %w[id sort].include?(key) } diff --git a/lib/tasks/units.rake b/lib/tasks/units.rake index 8b4a8a4a..3dde517c 100644 --- a/lib/tasks/units.rake +++ b/lib/tasks/units.rake @@ -1,8 +1,9 @@ namespace :units do - task :clean_unece20_source => :environment do + task clean_unece20_source: :environment do base_unit_entries = [] - un_ece_20_units = YAML.safe_load(ERB.new(File.read(File.expand_path('config/units-of-measure/un-ece-20.yml', Rails.root))).result) + un_ece_20_units = YAML.safe_load(ERB.new(File.read(File.expand_path('config/units-of-measure/un-ece-20.yml', + Rails.root))).result) re = /^(?:([, 0-9]*)(?: x )!?)?([, 0-9⁰-⁹⁻¹²³]*)?(.*)?$/ un_ece_20_units.each do |unit| fixed_conversion_factor = fix_conversion_factor(unit['ConversionFactor']) @@ -35,7 +36,7 @@ namespace :units do base_unit_multiplier = multiplier base_unit_multiplier *= (10**power_of_ten) unless power_of_ten.nil? unit['conversion']['factor'] = base_unit_multiplier.to_s.to_f - is_base_unit = !base_unit.blank? && potency.blank? && multiplier == 1 + is_base_unit = base_unit.present? && potency.blank? && multiplier == 1 base_unit_entries << unit if is_base_unit end @@ -57,7 +58,7 @@ namespace :units do File.write(File.expand_path('config/units-of-measure/un-ece-20-remastered.yml', Rails.root), result) end - task :build_i18n_from_csv => :environment do + task build_i18n_from_csv: :environment do translations = { de: {}, en: {} } csv_options = { csv_options: { col_sep: ',' } } SpreadsheetFile.parse 'config/units-of-measure/translations_piece.csv', csv_options do |row, index| @@ -67,17 +68,17 @@ namespace :units do next if code.nil? # empty csv row translation_en = { name: row[2].strip } - translation_en[:abbreviation] = row[3].strip unless row[3].blank? - translation_en[:aliases] = row[4].split(', ') unless row[4].blank? + translation_en[:abbreviation] = row[3].strip if row[3].present? + translation_en[:aliases] = row[4].split(', ') if row[4].present? translations[:en][code] = translation_en translation_de = { name: row[5].strip } - translation_de[:abbreviation] = row[6].strip unless row[6].blank? - translation_de[:aliases] = row[7].split(', ') unless row[7].blank? + translation_de[:abbreviation] = row[6].strip if row[6].present? + translation_de[:aliases] = row[7].split(', ') if row[7].present? translations[:de][code] = translation_de end - [:en, :de].each do |locale| + %i[en de].each do |locale| SpreadsheetFile.parse "config/units-of-measure/translations_scalar-#{locale}.csv", csv_options do |row, index| next if index == 0 @@ -86,14 +87,14 @@ namespace :units do translation = { name: row[2].strip, long_name: row[1].strip } translation[:symbols] = [] - translation[:symbols] << row[3].strip unless row[3].blank? + translation[:symbols] << row[3].strip if row[3].present? alternate_symbols = row[4]&.strip - unless alternate_symbols.blank? + if alternate_symbols.present? alternate_symbols.split(', ').each do |symbol| translation[:symbols] << symbol.strip end end - translation[:aliases] = row[5].split(', ') unless row[5].blank? + translation[:aliases] = row[5].split(', ') if row[5].present? translations[locale][code] = translation end result = "# This file has been autogenerated by `rake units:build_i18n_from_csv`\n#{{ unece_units: translations[locale] }.deep_stringify_keys.to_yaml}" @@ -129,5 +130,7 @@ def fix_conversion_factor(conversion_factor) conversion_factor = conversion_factor.gsub(%r{(\s|^|/)m3(\s|$|/)}, '\1m³\2') # 10-15 m³ -> 10⁻¹⁵ m³: - conversion_factor.gsub(%r{(\s|^|/)10 ?(- ?[0-9]+)(\s|$|/)}) { Regexp.last_match[1] + "10" + number_to_superscript(Regexp.last_match[2]) + Regexp.last_match[3] } + conversion_factor.gsub(%r{(\s|^|/)10 ?(- ?[0-9]+)(\s|$|/)}) do + Regexp.last_match[1] + '10' + number_to_superscript(Regexp.last_match[2]) + Regexp.last_match[3] + end end diff --git a/lib/token_verifier.rb b/lib/token_verifier.rb index a8a0f1eb..5f389943 100644 --- a/lib/token_verifier.rb +++ b/lib/token_verifier.rb @@ -19,11 +19,9 @@ def verify(message) raise InvalidPrefix unless r[1] == @_prefix # return original message - if r.length > 2 - r[2] - else - nil - end + return unless r.length > 2 + + r[2] end class InvalidMessage < ActiveSupport::MessageVerifier::InvalidSignature; end @@ -32,8 +30,6 @@ class InvalidScope < ActiveSupport::MessageVerifier::InvalidSignature; end class InvalidPrefix < ActiveSupport::MessageVerifier::InvalidSignature; end - protected - def self.secret # 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 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 9923d774..3f48d995 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,6 @@ class CurrentOrders::ArticlesController < ApplicationController before_action :authenticate_orders - before_action :find_order_and_order_article, only: [:index, :show] + before_action :find_order_and_order_article, only: %i[index show] def index # sometimes need to pass id as parameter for forms @@ -26,11 +26,11 @@ def show_on_group_order_article_update def find_order_and_order_article @current_orders = Order.finished_not_closed - unless params[:order_id].blank? + if params[:order_id].blank? + @order_articles = OrderArticle.where(order_id: @current_orders.all.map(&:id)) + else @order = Order.find(params[:order_id]) @order_articles = @order.order_articles - else - @order_articles = OrderArticle.where(order_id: @current_orders.all.map(&:id)) end @q = OrderArticle.search(params[:q]) @order_articles = @order_articles.ordered.merge(@q.result).includes(:article, :article_version) 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 41f071c5..20f6e172 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 @@ -4,10 +4,10 @@ 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) + @order_ids = Order.where(state: %w[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 }) + @articles_grouped_by_category = @goas.includes(order_article: { article: :article_category }) .order('articles.name') .group_by { |a| a.order_article.article_version.article_category.name } .sort { |a, b| a[0] <=> b[0] } @@ -18,8 +18,8 @@ def index # XXX code duplication from GroupOrdersController def ensure_ordergroup_member @ordergroup = @current_user.ordergroup - if @ordergroup.nil? - redirect_to root_url, :alert => I18n.t('group_orders.errors.no_member') - end + return unless @ordergroup.nil? + + redirect_to root_url, alert: I18n.t('group_orders.errors.no_member') end 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 767bf739..62d5d36e 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,6 @@ class CurrentOrders::OrdergroupsController < ApplicationController before_action :authenticate_orders - before_action :find_group_orders, only: [:index, :show] + before_action :find_group_orders, only: %i[index show] def index # sometimes need to pass id as parameter for forms @@ -34,8 +34,10 @@ def find_group_orders @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_version]) - .where(group_orders: { order_id: @order_ids, ordergroup_id: @ordergroup.id }).ordered.all unless @ordergroup.nil? + return if @ordergroup.nil? + + @goas = GroupOrderArticle.includes(:group_order, order_article: %i[article article_version]) + .where(group_orders: { order_id: @order_ids, ordergroup_id: @ordergroup.id }).ordered.all end helper_method \ 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 61d863b4..43966e3b 100644 --- a/plugins/current_orders/app/documents/multiple_orders_by_articles.rb +++ b/plugins/current_orders/app/documents/multiple_orders_by_articles.rb @@ -69,7 +69,7 @@ def body protected def pdf_add_page_breaks? - super 'order_by_articles' + super('order_by_articles') end def order_articles @@ -77,11 +77,11 @@ def order_articles .includes(:article).references(:article) .reorder('order_articles.order_id, articles.name') .preload(:article_version) # preload not join, just in case it went missing - .preload(:order, :group_order_articles => { :group_order => :ordergroup }) + .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 } + def each_order_article(&block) + order_articles.find_each_with_order(batch_size: BATCH_SIZE, &block) end def group_order_articles_for(order_article) @@ -90,7 +90,7 @@ def group_order_articles_for(order_article) goas end - def each_group_order_article_for(group_order) - group_order_articles_for(group_order).each { |goa| yield goa } + def each_group_order_article_for(group_order, &block) + group_order_articles_for(group_order).each(&block) 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 c429d541..866f788d 100644 --- a/plugins/current_orders/app/documents/multiple_orders_by_groups.rb +++ b/plugins/current_orders/app/documents/multiple_orders_by_groups.rb @@ -56,7 +56,7 @@ def body 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.join('app/assets/images/package-bg.png')}", scale: 0.6, position: :center } ] # last column showing unit_quantity is useless if they're all one @@ -100,7 +100,7 @@ def body protected def pdf_add_page_breaks? - super 'order_by_groups' + super('order_by_groups') end def ordergroups @@ -113,7 +113,7 @@ def ordergroups s end - def each_ordergroup + def each_ordergroup(&block) ordergroups.find_in_batches_with_order(batch_size: BATCH_SIZE) do |ordergroups| @group_order_article_batch = GroupOrderArticle .joins(:group_order) @@ -121,8 +121,8 @@ def each_ordergroup .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_version, :order]) - ordergroups.each { |ordergroup| yield ordergroup } + .preload(order_article: %i[article article_version order]) + ordergroups.each(&block) end end @@ -130,7 +130,7 @@ def group_order_articles_for(ordergroup) @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 } + def each_group_order_article_for(ordergroup, &block) + group_order_articles_for(ordergroup).each(&block) 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 3bbab482..40c0fe45 100644 --- a/plugins/current_orders/app/helpers/current_orders_helper.rb +++ b/plugins/current_orders/app/helpers/current_orders_helper.rb @@ -6,7 +6,8 @@ def to_pay_message(ordergroup) elsif funds == 0 I18n.t('helpers.current_orders.pay_none') else - content_tag :b, I18n.t('helpers.current_orders.pay_amount', amount: number_to_currency(-ordergroup.get_available_funds)) + 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/config/routes.rb b/plugins/current_orders/config/routes.rb index f642fc31..aeb2b014 100644 --- a/plugins/current_orders/config/routes.rb +++ b/plugins/current_orders/config/routes.rb @@ -1,27 +1,27 @@ Rails.application.routes.draw do scope '/:foodcoop' do namespace :current_orders do - resources :ordergroups, :only => [:index, :show] do + resources :ordergroups, only: %i[index show] do collection do get :show_on_group_order_article_create get :show_on_group_order_article_update end end - resources :articles, :only => [:index, :show] do + resources :articles, only: %i[index show] do collection do get :show_on_group_order_article_create end end - resource :orders, :only => [:show] do + resource :orders, only: [:show] do collection do get :my get :receive end end - resources :group_orders, :only => [:index] + resources :group_orders, only: [:index] end end end diff --git a/plugins/current_orders/foodsoft_current_orders.gemspec b/plugins/current_orders/foodsoft_current_orders.gemspec index c444fbec..f8e22ce6 100644 --- a/plugins/current_orders/foodsoft_current_orders.gemspec +++ b/plugins/current_orders/foodsoft_current_orders.gemspec @@ -1,20 +1,21 @@ -$:.push File.expand_path("../lib", __FILE__) +$:.push File.expand_path('lib', __dir__) # Maintain your gem's version: -require "foodsoft_current_orders/version" +require 'foodsoft_current_orders/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| - s.name = "foodsoft_current_orders" + s.name = 'foodsoft_current_orders' s.version = FoodsoftCurrentOrders::VERSION - s.authors = ["wvengen"] - s.email = ["dev-voko@willem.engen.nl"] - s.homepage = "https://github.com/foodcoop-adam/foodsoft" - s.summary = "Quick support for working on all currently active orders in foodsoft." - s.description = "" + s.authors = ['wvengen'] + s.email = ['dev-voko@willem.engen.nl'] + s.homepage = 'https://github.com/foodcoop-adam/foodsoft' + s.summary = 'Quick support for working on all currently active orders in foodsoft.' + s.description = '' - s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"] + s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md'] - s.add_dependency "rails" - s.add_dependency "deface", "~> 1.0" + s.add_dependency 'rails' + s.add_dependency 'deface', '~> 1.0' + s.metadata['rubygems_mfa_required'] = 'true' end diff --git a/plugins/current_orders/lib/foodsoft_current_orders.rb b/plugins/current_orders/lib/foodsoft_current_orders.rb index 5a9a7c82..8227bea4 100644 --- a/plugins/current_orders/lib/foodsoft_current_orders.rb +++ b/plugins/current_orders/lib/foodsoft_current_orders.rb @@ -1,5 +1,5 @@ -require "deface" -require "foodsoft_current_orders/engine" +require 'deface' +require 'foodsoft_current_orders/engine' module FoodsoftCurrentOrders def self.enabled? diff --git a/plugins/current_orders/lib/foodsoft_current_orders/engine.rb b/plugins/current_orders/lib/foodsoft_current_orders/engine.rb index 07427b56..c6236acb 100644 --- a/plugins/current_orders/lib/foodsoft_current_orders/engine.rb +++ b/plugins/current_orders/lib/foodsoft_current_orders/engine.rb @@ -4,12 +4,15 @@ def navigation(primary, context) return unless FoodsoftCurrentOrders.enabled? return if primary[:orders].nil? - cond = Proc.new { current_user.role_orders? } + cond = proc { 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) + 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 } end end diff --git a/plugins/current_orders/lib/foodsoft_current_orders/version.rb b/plugins/current_orders/lib/foodsoft_current_orders/version.rb index af58aa9c..9e916ba6 100644 --- a/plugins/current_orders/lib/foodsoft_current_orders/version.rb +++ b/plugins/current_orders/lib/foodsoft_current_orders/version.rb @@ -1,3 +1,3 @@ module FoodsoftCurrentOrders - VERSION = "0.0.1" + VERSION = '0.0.1' end diff --git a/plugins/discourse/Rakefile b/plugins/discourse/Rakefile old mode 100644 new mode 100755 index cb56e2e5..abec3d42 --- a/plugins/discourse/Rakefile +++ b/plugins/discourse/Rakefile @@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_files.include('lib/**/*.rb') end -APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) +APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__) load 'rails/tasks/engine.rake' Bundler::GemHelper.install_tasks @@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end -task :default => :test +task default: :test diff --git a/plugins/discourse/app/controllers/discourse_controller.rb b/plugins/discourse/app/controllers/discourse_controller.rb index 5a65f61c..0e62f14d 100644 --- a/plugins/discourse/app/controllers/discourse_controller.rb +++ b/plugins/discourse/app/controllers/discourse_controller.rb @@ -11,7 +11,7 @@ def valid_signature? def redirect_to_with_payload(url, payload) base64_payload = Base64.strict_encode64 payload.to_query - sso = CGI::escape base64_payload + sso = CGI.escape base64_payload sig = get_hmac_hex_string base64_payload redirect_to "#{url}#{url.include?('?') ? '&' : '?'}sso=#{sso}&sig=#{sig}" end @@ -21,7 +21,7 @@ def parse_payload payload.symbolize_keys! end - def get_hmac_hex_string payload + def get_hmac_hex_string(payload) discourse_sso_secret = FoodsoftConfig[:discourse_sso_secret] OpenSSL::HMAC.hexdigest 'sha256', discourse_sso_secret, payload end diff --git a/plugins/discourse/app/controllers/discourse_login_controller.rb b/plugins/discourse/app/controllers/discourse_login_controller.rb index 1c8fe938..bd7a81e3 100644 --- a/plugins/discourse/app/controllers/discourse_login_controller.rb +++ b/plugins/discourse/app/controllers/discourse_login_controller.rb @@ -5,7 +5,7 @@ class DiscourseLoginController < DiscourseController def initiate discourse_url = FoodsoftConfig[:discourse_url] - nonce = SecureRandom.hex() + nonce = SecureRandom.hex return_sso_url = url_for(action: :callback, only_path: false) session[:discourse_sso_nonce] = nonce @@ -36,7 +36,7 @@ def callback user.save! login_and_redirect_to_return_to user, notice: I18n.t('discourse.callback.logged_in') - rescue => error - redirect_to login_url, alert: error.to_s + rescue StandardError => e + redirect_to login_url, alert: e.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 e8f742b6..04dc8d1c 100644 --- a/plugins/discourse/app/controllers/discourse_sso_controller.rb +++ b/plugins/discourse/app/controllers/discourse_sso_controller.rb @@ -17,7 +17,7 @@ def sso 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 + rescue StandardError => e + redirect_to root_url, alert: e.to_s end end diff --git a/plugins/discourse/foodsoft_discourse.gemspec b/plugins/discourse/foodsoft_discourse.gemspec index 6d2fb5d4..1e6113ce 100644 --- a/plugins/discourse/foodsoft_discourse.gemspec +++ b/plugins/discourse/foodsoft_discourse.gemspec @@ -1,21 +1,21 @@ -$:.push File.expand_path("../lib", __FILE__) +$:.push File.expand_path('lib', __dir__) # Maintain your gem's version: -require "foodsoft_discourse/version" +require 'foodsoft_discourse/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| - s.name = "foodsoft_discourse" + s.name = 'foodsoft_discourse' s.version = FoodsoftDiscourse::VERSION - s.authors = ["paroga"] - s.email = ["paroga@paroga.com"] - s.homepage = "https://github.com/foodcoops/foodsoft" - s.summary = "Discourse plugin for foodsoft." - s.description = "Allow SSO login via Discourse" + s.authors = ['paroga'] + s.email = ['paroga@paroga.com'] + s.homepage = 'https://github.com/foodcoops/foodsoft' + s.summary = 'Discourse plugin for foodsoft.' + s.description = 'Allow SSO login via Discourse' - s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"] - s.test_files = Dir["test/**/*"] + s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md'] - s.add_dependency "rails" - s.add_dependency "deface", "~> 1.0" + s.add_dependency 'rails' + s.add_dependency 'deface', '~> 1.0' + s.metadata['rubygems_mfa_required'] = 'true' end diff --git a/plugins/discourse/lib/foodsoft_discourse/redirect_to_login.rb b/plugins/discourse/lib/foodsoft_discourse/redirect_to_login.rb index 901979b1..6ddfdb13 100644 --- a/plugins/discourse/lib/foodsoft_discourse/redirect_to_login.rb +++ b/plugins/discourse/lib/foodsoft_discourse/redirect_to_login.rb @@ -2,7 +2,7 @@ module FoodsoftDiscourse module RedirectToLogin def self.included(base) # :nodoc: base.class_eval do - alias foodsoft_discourse_orig_redirect_to_login redirect_to_login + alias_method :foodsoft_discourse_orig_redirect_to_login, :redirect_to_login def redirect_to_login(options = {}) if FoodsoftDiscourse.enabled? && !FoodsoftConfig[:discourse_sso] @@ -18,5 +18,5 @@ def redirect_to_login(options = {}) # modify existing helper ActiveSupport.on_load(:after_initialize) do - Concerns::Auth.send :include, FoodsoftDiscourse::RedirectToLogin + Concerns::Auth.include FoodsoftDiscourse::RedirectToLogin end diff --git a/plugins/discourse/lib/foodsoft_discourse/version.rb b/plugins/discourse/lib/foodsoft_discourse/version.rb index 2b8d4138..60d38a51 100644 --- a/plugins/discourse/lib/foodsoft_discourse/version.rb +++ b/plugins/discourse/lib/foodsoft_discourse/version.rb @@ -1,3 +1,3 @@ module FoodsoftDiscourse - VERSION = "0.0.1" + VERSION = '0.0.1' end diff --git a/plugins/documents/Rakefile b/plugins/documents/Rakefile old mode 100644 new mode 100755 index 2834c5f3..861a530a --- a/plugins/documents/Rakefile +++ b/plugins/documents/Rakefile @@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_files.include('lib/**/*.rb') end -APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) +APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__) load 'rails/tasks/engine.rake' Bundler::GemHelper.install_tasks @@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end -task :default => :test +task default: :test diff --git a/plugins/documents/app/controllers/documents_controller.rb b/plugins/documents/app/controllers/documents_controller.rb index b97470a5..7d1aea30 100644 --- a/plugins/documents/app/controllers/documents_controller.rb +++ b/plugins/documents/app/controllers/documents_controller.rb @@ -4,16 +4,16 @@ class DocumentsController < ApplicationController before_action -> { require_plugin_enabled FoodsoftDocuments } 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" + sort = if params['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' end - else - sort = "data IS NULL DESC, name" - end + else + 'data IS NULL DESC, name' + end @documents = Document.where(parent: @document).page(params[:page]).per(@per_page).order(sort) end @@ -40,16 +40,16 @@ def create @document.created_by = current_user @document.save! redirect_to @document.parent || documents_path, notice: t('.notice') - rescue => error - redirect_to @document.parent || documents_path, alert: t('.error', error: error.message) + rescue StandardError => e + redirect_to @document.parent || documents_path, alert: t('.error', error: e.message) end def update @document = Document.find(params[:id]) @document.update_attribute(:parent_id, params[:parent_id]) redirect_to @document.parent || documents_path, notice: t('.notice') - rescue => error - redirect_to @document.parent || documents_path, alert: t('errors.general_msg', msg: error.message) + rescue StandardError => e + redirect_to @document.parent || documents_path, alert: t('errors.general_msg', msg: e.message) end def destroy @@ -60,8 +60,8 @@ def destroy else redirect_to documents_path, alert: t('.no_right') end - rescue => error - redirect_to documents_path, alert: t('.error', error: error.message) + rescue StandardError => e + redirect_to documents_path, alert: t('.error', error: e.message) end def show diff --git a/plugins/documents/foodsoft_documents.gemspec b/plugins/documents/foodsoft_documents.gemspec index c0a4f8fd..63d3b428 100644 --- a/plugins/documents/foodsoft_documents.gemspec +++ b/plugins/documents/foodsoft_documents.gemspec @@ -1,22 +1,22 @@ -$:.push File.expand_path("../lib", __FILE__) +$:.push File.expand_path('lib', __dir__) # Maintain your gem's version: -require "foodsoft_documents/version" +require 'foodsoft_documents/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| - s.name = "foodsoft_documents" + s.name = 'foodsoft_documents' s.version = FoodsoftDocuments::VERSION - s.authors = ["paroga"] - s.email = ["paroga@paroga.com"] - s.homepage = "https://github.com/foodcoops/foodsoft" - s.summary = "Documents plugin for foodsoft." - s.description = "Adds simple document management to foodsoft." + s.authors = ['paroga'] + s.email = ['paroga@paroga.com'] + s.homepage = 'https://github.com/foodcoops/foodsoft' + s.summary = 'Documents plugin for foodsoft.' + s.description = 'Adds simple document management to foodsoft.' - s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"] - s.test_files = Dir["test/**/*"] + s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md'] - s.add_dependency "rails" - s.add_dependency "deface", "~> 1.0" - s.add_dependency "ruby-filemagic" + s.add_dependency 'rails' + s.add_dependency 'deface', '~> 1.0' + s.add_dependency 'ruby-filemagic' + s.metadata['rubygems_mfa_required'] = 'true' end diff --git a/plugins/documents/lib/foodsoft_documents/engine.rb b/plugins/documents/lib/foodsoft_documents/engine.rb index 970b3aa5..de81904c 100644 --- a/plugins/documents/lib/foodsoft_documents/engine.rb +++ b/plugins/documents/lib/foodsoft_documents/engine.rb @@ -8,9 +8,9 @@ def navigation(primary, context) sub_nav.items << SimpleNavigation::Item.new(primary, :documents, I18n.t('navigation.documents'), context.documents_path) # move to right before tasks item - if i = sub_nav.items.index(sub_nav[:tasks]) - sub_nav.items.insert(i, sub_nav.items.delete_at(-1)) - end + return unless i = sub_nav.items.index(sub_nav[:tasks]) + + sub_nav.items.insert(i, sub_nav.items.delete_at(-1)) end def default_foodsoft_config(cfg) diff --git a/plugins/documents/lib/foodsoft_documents/version.rb b/plugins/documents/lib/foodsoft_documents/version.rb index 6e57dbb3..7096e468 100644 --- a/plugins/documents/lib/foodsoft_documents/version.rb +++ b/plugins/documents/lib/foodsoft_documents/version.rb @@ -1,3 +1,3 @@ module FoodsoftDocuments - VERSION = "0.0.1" + VERSION = '0.0.1' end diff --git a/plugins/links/Rakefile b/plugins/links/Rakefile old mode 100644 new mode 100755 index fb6356f8..a9902fd3 --- a/plugins/links/Rakefile +++ b/plugins/links/Rakefile @@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_files.include('lib/**/*.rb') end -APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) +APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__) load 'rails/tasks/engine.rake' Bundler::GemHelper.install_tasks @@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end -task :default => :test +task default: :test diff --git a/plugins/links/app/controllers/admin/links_controller.rb b/plugins/links/app/controllers/admin/links_controller.rb index e7b60aa5..580c8a93 100644 --- a/plugins/links/app/controllers/admin/links_controller.rb +++ b/plugins/links/app/controllers/admin/links_controller.rb @@ -37,8 +37,8 @@ def destroy link = Link.find(params[:id]) link.destroy! redirect_to admin_links_path - rescue => error - redirect_to admin_links_path, I18n.t('errors.general_msg', msg: error.message) + rescue StandardError => e + redirect_to admin_links_path, I18n.t('errors.general_msg', msg: e.message) end private diff --git a/plugins/links/app/controllers/links_controller.rb b/plugins/links/app/controllers/links_controller.rb index 143fc63d..27615517 100644 --- a/plugins/links/app/controllers/links_controller.rb +++ b/plugins/links/app/controllers/links_controller.rb @@ -5,9 +5,7 @@ def show link = Link.find(params[:id]) url = link.url - if link.workgroup && !current_user.role_admin? && !link.workgroup.member?(current_user) - return deny_access - end + return deny_access if link.workgroup && !current_user.role_admin? && !link.workgroup.member?(current_user) if link.indirect uri = URI.parse url @@ -19,11 +17,9 @@ def show url = result.header['Location'] - unless url - return redirect_to root_url, alert: t('.indirect_no_location') - end + return redirect_to root_url, alert: t('.indirect_no_location') unless url end - redirect_to url, status: 302 + redirect_to url, status: :found end end diff --git a/plugins/links/foodsoft_links.gemspec b/plugins/links/foodsoft_links.gemspec index 04fc03f9..c879f4b1 100644 --- a/plugins/links/foodsoft_links.gemspec +++ b/plugins/links/foodsoft_links.gemspec @@ -1,21 +1,21 @@ -$:.push File.expand_path("../lib", __FILE__) +$:.push File.expand_path('lib', __dir__) # Maintain your gem's version: -require "foodsoft_links/version" +require 'foodsoft_links/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| - s.name = "foodsoft_links" + s.name = 'foodsoft_links' s.version = FoodsoftLinks::VERSION - s.authors = ["paroga"] - s.email = ["paroga@paroga.com"] - s.homepage = "https://github.com/foodcoops/foodsoft" - s.summary = "Links plugin for foodsoft." - s.description = "Adds simple link management to foodsoft." + s.authors = ['paroga'] + s.email = ['paroga@paroga.com'] + s.homepage = 'https://github.com/foodcoops/foodsoft' + s.summary = 'Links plugin for foodsoft.' + s.description = 'Adds simple link management to foodsoft.' - s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"] - s.test_files = Dir["test/**/*"] + s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md'] - s.add_dependency "rails" - s.add_dependency "deface", "~> 1.0" + s.add_dependency 'rails' + s.add_dependency 'deface', '~> 1.0' + s.metadata['rubygems_mfa_required'] = 'true' end diff --git a/plugins/links/lib/foodsoft_links/engine.rb b/plugins/links/lib/foodsoft_links/engine.rb index ab6d9175..52672597 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 { visble_links(context).any? } do |subnav| visble_links(context).each do |link| subnav.item link.id, link.name, context.link_path(link) end @@ -11,15 +11,15 @@ def navigation(primary, context) primary.items.insert(i, primary.items.delete_at(-1)) end - unless primary[:admin].nil? - sub_nav = primary[:admin].sub_navigation - sub_nav.items << - SimpleNavigation::Item.new(primary, :links, I18n.t('navigation.admin.links'), context.admin_links_path) - # move to right before config item - if i = sub_nav.items.index(sub_nav[:config]) - sub_nav.items.insert(i, sub_nav.items.delete_at(-1)) - end - end + return if primary[:admin].nil? + + sub_nav = primary[:admin].sub_navigation + sub_nav.items << + SimpleNavigation::Item.new(primary, :links, I18n.t('navigation.admin.links'), context.admin_links_path) + # move to right before config item + return unless i = sub_nav.items.index(sub_nav[:config]) + + sub_nav.items.insert(i, sub_nav.items.delete_at(-1)) end def visble_links(context) diff --git a/plugins/links/lib/foodsoft_links/version.rb b/plugins/links/lib/foodsoft_links/version.rb index 20341ca4..707cfdb3 100644 --- a/plugins/links/lib/foodsoft_links/version.rb +++ b/plugins/links/lib/foodsoft_links/version.rb @@ -1,3 +1,3 @@ module FoodsoftLinks - VERSION = "0.0.1" + VERSION = '0.0.1' end diff --git a/plugins/messages/Rakefile b/plugins/messages/Rakefile old mode 100644 new mode 100755 index ac014bdd..9e2cbeab --- a/plugins/messages/Rakefile +++ b/plugins/messages/Rakefile @@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_files.include('lib/**/*.rb') end -APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) +APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__) load 'rails/tasks/engine.rake' Bundler::GemHelper.install_tasks @@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end -task :default => :test +task default: :test diff --git a/plugins/messages/app/controllers/admin/messagegroups_controller.rb b/plugins/messages/app/controllers/admin/messagegroups_controller.rb index cce57474..76fbbfb9 100644 --- a/plugins/messages/app/controllers/admin/messagegroups_controller.rb +++ b/plugins/messages/app/controllers/admin/messagegroups_controller.rb @@ -4,7 +4,7 @@ class Admin::MessagegroupsController < Admin::BaseController def index @messagegroups = Messagegroup.order('name ASC') # if somebody uses the search field: - @messagegroups = @messagegroups.where('name LIKE ?', "%#{params[:query]}%") unless params[:query].blank? + @messagegroups = @messagegroups.where('name LIKE ?', "%#{params[:query]}%") if params[:query].present? @messagegroups = @messagegroups.page(params[:page]).per(@per_page) end @@ -13,7 +13,7 @@ def destroy @messagegroup = Messagegroup.find(params[:id]) @messagegroup.destroy redirect_to admin_messagegroups_url, notice: t('admin.messagegroups.destroy.notice') - rescue => error - redirect_to admin_messagegroups_url, alert: t('admin.messagegroups.destroy.error', error: error.message) + rescue StandardError => e + redirect_to admin_messagegroups_url, alert: t('admin.messagegroups.destroy.error', error: e.message) end end diff --git a/plugins/messages/app/controllers/messagegroups_controller.rb b/plugins/messages/app/controllers/messagegroups_controller.rb index e9ba6770..7629eab8 100644 --- a/plugins/messages/app/controllers/messagegroups_controller.rb +++ b/plugins/messages/app/controllers/messagegroups_controller.rb @@ -1,17 +1,17 @@ class MessagegroupsController < ApplicationController def index - @messagegroups = Messagegroup.order("name") + @messagegroups = Messagegroup.order('name') end def join @messagegroup = Messagegroup.find(params[:id]) @messagegroup.users << current_user - redirect_to messagegroups_url, :notice => I18n.t('messagegroups.join.notice') + redirect_to messagegroups_url, notice: I18n.t('messagegroups.join.notice') end def leave @messagegroup = Messagegroup.find(params[:id]) @messagegroup.users.destroy(current_user) - redirect_to messagegroups_url, :notice => I18n.t('messagegroups.leave.notice') + redirect_to messagegroups_url, notice: I18n.t('messagegroups.leave.notice') end end diff --git a/plugins/messages/app/controllers/messages_controller.rb b/plugins/messages/app/controllers/messages_controller.rb index 2c594da3..bd043d58 100644 --- a/plugins/messages/app/controllers/messages_controller.rb +++ b/plugins/messages/app/controllers/messages_controller.rb @@ -10,21 +10,20 @@ def index def new @message = Message.new(params[:message]) - if @message.reply_to - original_message = Message.find(@message.reply_to) - if original_message.reply_to - @message.reply_to = original_message.reply_to - end - if original_message.is_readable_for?(current_user) - @message.add_recipients [original_message.sender_id] - @message.group_id = original_message.group_id - @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) } - else - redirect_to new_message_url, alert: I18n.t('messages.new.error_private') - end + return unless @message.reply_to + + original_message = Message.find(@message.reply_to) + @message.reply_to = original_message.reply_to if original_message.reply_to + if original_message.is_readable_for?(current_user) + @message.add_recipients [original_message.sender_id] + @message.group_id = original_message.group_id + @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) } + else + redirect_to new_message_url, alert: I18n.t('messages.new.error_private') end end @@ -33,18 +32,18 @@ def create @message = @current_user.send_messages.new(params[:message]) if @message.save DeliverMessageJob.perform_later(@message) - redirect_to messages_url, :notice => I18n.t('messages.create.notice') + redirect_to messages_url, notice: I18n.t('messages.create.notice') else - render :action => 'new' + render action: 'new' end end # Shows a single message. def show @message = Message.find(params[:id]) - unless @message.is_readable_for?(current_user) - redirect_to messages_url, alert: 'Nachricht ist privat!' - end + return if @message.is_readable_for?(current_user) + + redirect_to messages_url, alert: 'Nachricht ist privat!' end def toggle_private diff --git a/plugins/messages/app/helpers/messages_helper.rb b/plugins/messages/app/helpers/messages_helper.rb index d5371fe4..adb8fe88 100644 --- a/plugins/messages/app/helpers/messages_helper.rb +++ b/plugins/messages/app/helpers/messages_helper.rb @@ -1,11 +1,11 @@ module MessagesHelper def format_subject(message, length) if message.subject.length > length - subject = truncate(message.subject, :length => length) - body = "" + subject = truncate(message.subject, length: length) + body = '' else subject = message.subject - body = truncate(message.body, :length => length - subject.length) + body = truncate(message.body, length: length - subject.length) end "#{link_to(h(subject), message)} #{h(body)}".html_safe end diff --git a/plugins/messages/app/mail_receivers/messages_mail_receiver.rb b/plugins/messages/app/mail_receivers/messages_mail_receiver.rb index e9ca99f3..7b8a0356 100644 --- a/plugins/messages/app/mail_receivers/messages_mail_receiver.rb +++ b/plugins/messages/app/mail_receivers/messages_mail_receiver.rb @@ -1,4 +1,4 @@ -require "email_reply_trimmer" +require 'email_reply_trimmer' class MessagesMailReceiver def self.regexp @@ -9,29 +9,25 @@ def initialize(match) @message = Message.find_by_id(match[:message_id]) @user = User.find_by_id(match[:user_id]) - raise "Message could not be found" if @message.nil? - raise "User could not be found" if @user.nil? + raise 'Message could not be found' if @message.nil? + raise 'User could not be found' if @user.nil? hash = @message.mail_hash_for_user(@user) - raise "Hash does not match expectations" unless hash.casecmp(match[:hash]) == 0 + raise 'Hash does not match expectations' unless hash.casecmp(match[:hash]) == 0 end def received(data) mail = Mail.new data mail_part = get_mail_part(mail) - raise "No valid content could be found" if mail_part.nil? + raise 'No valid content could be found' if mail_part.nil? body = mail_part.body.decoded - unless mail_part.content_type_parameters.nil? - body = body.force_encoding mail_part.content_type_parameters[:charset] - end + body = body.force_encoding mail_part.content_type_parameters[:charset] unless mail_part.content_type_parameters.nil? - if MIME::Type.simplified(mail_part.content_type) == "text/html" - body = Nokogiri::HTML(body).text - end + body = Nokogiri::HTML(body).text if MIME::Type.simplified(mail_part.content_type) == 'text/html' - body.encode!(Encoding::default_internal) + body.encode!(Encoding.default_internal) body = EmailReplyTrimmer.trim(body) raise BlankBodyException if body.empty? @@ -39,16 +35,16 @@ def received(data) group: @message.group, private: @message.private, received_email: data - if @message.reply_to - message.reply_to_message = @message.reply_to_message - else - message.reply_to_message = @message - end - if mail.subject - message.subject = mail.subject.gsub("[#{FoodsoftConfig[:name]}] ", "") - else - message.subject = I18n.t('messages.model.reply_subject', subject: message.reply_to_message.subject) - end + message.reply_to_message = if @message.reply_to + @message.reply_to_message + else + @message + end + message.subject = if mail.subject + mail.subject.gsub("[#{FoodsoftConfig[:name]}] ", '') + else + I18n.t('messages.model.reply_subject', subject: message.reply_to_message.subject) + end message.add_recipients [@message.sender_id] message.save! @@ -64,16 +60,14 @@ def get_mail_part(mail) for part in mail.parts part = get_mail_part(part) content_type = MIME::Type.simplified(part.content_type) - if content_type == "text/plain" || !mail_part && content_type == "text/html" - mail_part = part - end + mail_part = part if content_type == 'text/plain' || (!mail_part && content_type == 'text/html') end mail_part end class BlankBodyException < MidiSmtpServer::SmtpdException def initialize(msg = nil) - super msg, 541, 'The recipient address rejected your message because of a blank plain body' + 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 f6b03c10..b6554322 100644 --- a/plugins/messages/app/models/message.rb +++ b/plugins/messages/app/models/message.rb @@ -1,17 +1,17 @@ -require "base32" +require 'base32' class Message < ApplicationRecord - belongs_to :sender, class_name: 'User', foreign_key: 'sender_id' - belongs_to :group, optional: true, class_name: 'Group', foreign_key: 'group_id' + belongs_to :sender, class_name: 'User' + belongs_to :group, optional: true, class_name: 'Group' belongs_to :reply_to_message, optional: true, class_name: 'Message', foreign_key: 'reply_to' has_many :message_recipients, dependent: :destroy has_many :recipients, through: :message_recipients, source: :user 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 :threads, -> { where(reply_to: nil) } + scope :thread, ->(id) { where('id = ? OR reply_to = ?', id, id) } + scope :readable_for, lambda { |user| user_id = user.try(&:id) joins(:message_recipients) @@ -20,7 +20,7 @@ class Message < ApplicationRecord } validates_presence_of :message_recipients, :subject, :body - validates_length_of :subject, :in => 1..255 + validates_length_of :subject, in: 1..255 after_initialize do @recipients_ids ||= [] @@ -33,7 +33,7 @@ class Message < ApplicationRecord def create_message_recipients user_ids = @recipients_ids user_ids += User.undeleted.pluck(:id) if send_method == 'all' - user_ids += Group.find(group_id).users.pluck(:id) unless group_id.blank? + user_ids += Group.find(group_id).users.pluck(:id) if group_id.present? user_ids += Order.find(order_id).users_ordered.pluck(:id) if send_method == 'order' user_ids.uniq.each do |user_id| @@ -47,7 +47,7 @@ def add_recipients(users) end def group_id=(group_id) - group = Group.find(group_id) unless group_id.blank? + group = Group.find(group_id) if group_id.present? if group @send_method = 'workgroup' if group.type == 'Workgroup' @send_method = 'ordergroup' if group.type == 'Ordergroup' @@ -96,29 +96,29 @@ def mail_to=(user_id) def mail_hash_for_user(user) digest = Digest::SHA1.new - digest.update self.id.to_s - digest.update ":" + digest.update id.to_s + digest.update ':' digest.update salt - digest.update ":" + digest.update ':' digest.update user.id.to_s Base32.encode digest.digest end # Returns true if this message is a system message, i.e. was sent automatically by Foodsoft itself. def system_message? - self.sender_id.nil? + sender_id.nil? end def sender_name - system_message? ? I18n.t('layouts.foodsoft') : sender.display rescue "?" + system_message? ? I18n.t('layouts.foodsoft') : sender.display + rescue StandardError + '?' end - def recipients_ids - @recipients_ids - end + attr_reader :recipients_ids def last_reply - Message.where(reply_to: self.id).order(:created_at).last + Message.where(reply_to: id).order(:created_at).last end def is_readable_for?(user) @@ -135,6 +135,6 @@ def can_toggle_private?(user) 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/message_recipient.rb b/plugins/messages/app/models/message_recipient.rb index e205ea5b..671b557d 100644 --- a/plugins/messages/app/models/message_recipient.rb +++ b/plugins/messages/app/models/message_recipient.rb @@ -2,5 +2,5 @@ class MessageRecipient < ActiveRecord::Base belongs_to :message belongs_to :user - enum email_state: [:pending, :sent, :skipped] + enum email_state: %i[pending sent skipped] end diff --git a/plugins/messages/app/models/messagegroup.rb b/plugins/messages/app/models/messagegroup.rb index 7c7f6c03..93666dd5 100644 --- a/plugins/messages/app/models/messagegroup.rb +++ b/plugins/messages/app/models/messagegroup.rb @@ -1,5 +1,3 @@ class Messagegroup < Group validates_uniqueness_of :name - - protected end diff --git a/plugins/messages/config/routes.rb b/plugins/messages/config/routes.rb index d66eebdd..6d276428 100644 --- a/plugins/messages/config/routes.rb +++ b/plugins/messages/config/routes.rb @@ -1,13 +1,13 @@ Rails.application.routes.draw do scope '/:foodcoop' do - resources :messages, :only => [:index, :show, :new, :create] do + resources :messages, only: %i[index show new create] do member do get :thread post :toggle_private end end - resources :message_threads, :only => [:index, :show] + resources :message_threads, only: %i[index show] resources :messagegroups, only: [:index] do member do diff --git a/plugins/messages/db/migrate/20160226000000_add_email_to_message.rb b/plugins/messages/db/migrate/20160226000000_add_email_to_message.rb index 411600c7..034b023b 100644 --- a/plugins/messages/db/migrate/20160226000000_add_email_to_message.rb +++ b/plugins/messages/db/migrate/20160226000000_add_email_to_message.rb @@ -1,6 +1,6 @@ class AddEmailToMessage < ActiveRecord::Migration[4.2] def change add_column :messages, :salt, :string - add_column :messages, :received_email, :binary, :limit => 1.megabyte + add_column :messages, :received_email, :binary, limit: 1.megabyte end end diff --git a/plugins/messages/foodsoft_messages.gemspec b/plugins/messages/foodsoft_messages.gemspec index 13050bf8..e7967191 100644 --- a/plugins/messages/foodsoft_messages.gemspec +++ b/plugins/messages/foodsoft_messages.gemspec @@ -1,26 +1,26 @@ -$:.push File.expand_path("../lib", __FILE__) +$:.push File.expand_path('lib', __dir__) # Maintain your gem's version: -require "foodsoft_messages/version" +require 'foodsoft_messages/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| - s.name = "foodsoft_messages" + s.name = 'foodsoft_messages' s.version = FoodsoftMessages::VERSION - s.authors = ["robwa"] - s.email = ["foodsoft-messages@ini.tiative.net"] - s.homepage = "https://github.com/foodcoops/foodsoft" - s.summary = "Messaging plugin for foodsoft." - s.description = "Adds the ability to exchange messages to foodsoft." + s.authors = ['robwa'] + s.email = ['foodsoft-messages@ini.tiative.net'] + s.homepage = 'https://github.com/foodcoops/foodsoft' + s.summary = 'Messaging plugin for foodsoft.' + s.description = 'Adds the ability to exchange messages to foodsoft.' - s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"] - s.test_files = Dir["test/**/*"] + s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md'] - s.add_dependency "rails" - s.add_dependency "base32" - s.add_dependency "deface", "~> 1.0" - s.add_dependency "email_reply_trimmer" - s.add_dependency "mail" + s.add_dependency 'rails' + s.add_dependency 'base32' + s.add_dependency 'deface', '~> 1.0' + s.add_dependency 'email_reply_trimmer' + s.add_dependency 'mail' - s.add_development_dependency "sqlite3" + s.add_development_dependency 'sqlite3' + s.metadata['rubygems_mfa_required'] = 'true' end diff --git a/plugins/messages/lib/foodsoft_messages.rb b/plugins/messages/lib/foodsoft_messages.rb index b457c8f1..9fc71928 100644 --- a/plugins/messages/lib/foodsoft_messages.rb +++ b/plugins/messages/lib/foodsoft_messages.rb @@ -1,7 +1,7 @@ -require "foodsoft_messages/engine" -require "foodsoft_messages/mail_receiver" -require "foodsoft_messages/user_link" -require "deface" +require 'foodsoft_messages/engine' +require 'foodsoft_messages/mail_receiver' +require 'foodsoft_messages/user_link' +require 'deface' module FoodsoftMessages # Return whether messages are used or not. diff --git a/plugins/messages/lib/foodsoft_messages/engine.rb b/plugins/messages/lib/foodsoft_messages/engine.rb index 0f67abb7..f054ada6 100644 --- a/plugins/messages/lib/foodsoft_messages/engine.rb +++ b/plugins/messages/lib/foodsoft_messages/engine.rb @@ -12,15 +12,16 @@ def navigation(primary, context) sub_nav.items.insert(i, sub_nav.items.delete_at(-1)) end end - unless primary[:admin].nil? - sub_nav = primary[:admin].sub_navigation - sub_nav.items << - SimpleNavigation::Item.new(primary, :messagegroups, I18n.t('navigation.admin.messagegroups'), context.admin_messagegroups_path) - # move to right before config item - if i = sub_nav.items.index(sub_nav[:config]) - sub_nav.items.insert(i, sub_nav.items.delete_at(-1)) - end - end + return if primary[:admin].nil? + + sub_nav = primary[:admin].sub_navigation + sub_nav.items << + SimpleNavigation::Item.new(primary, :messagegroups, I18n.t('navigation.admin.messagegroups'), + context.admin_messagegroups_path) + # move to right before config item + return unless i = sub_nav.items.index(sub_nav[:config]) + + sub_nav.items.insert(i, sub_nav.items.delete_at(-1)) end def default_foodsoft_config(cfg) diff --git a/plugins/messages/lib/foodsoft_messages/user_link.rb b/plugins/messages/lib/foodsoft_messages/user_link.rb index bfab42b6..6fcf99c4 100644 --- a/plugins/messages/lib/foodsoft_messages/user_link.rb +++ b/plugins/messages/lib/foodsoft_messages/user_link.rb @@ -8,7 +8,7 @@ def show_user_link(user = @current_user) 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 @@ -18,5 +18,5 @@ def show_user_link(user = @current_user) # modify existing helper ActiveSupport.on_load(:after_initialize) do - ApplicationHelper.send :include, FoodsoftMessages::UserLink + ApplicationHelper.include FoodsoftMessages::UserLink end diff --git a/plugins/messages/lib/foodsoft_messages/version.rb b/plugins/messages/lib/foodsoft_messages/version.rb index 2da75575..6209100d 100644 --- a/plugins/messages/lib/foodsoft_messages/version.rb +++ b/plugins/messages/lib/foodsoft_messages/version.rb @@ -1,3 +1,3 @@ module FoodsoftMessages - VERSION = "0.0.1" + VERSION = '0.0.1' end diff --git a/plugins/polls/Rakefile b/plugins/polls/Rakefile old mode 100644 new mode 100755 index 2834c5f3..861a530a --- a/plugins/polls/Rakefile +++ b/plugins/polls/Rakefile @@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_files.include('lib/**/*.rb') end -APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) +APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__) load 'rails/tasks/engine.rake' Bundler::GemHelper.install_tasks @@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end -task :default => :test +task default: :test diff --git a/plugins/polls/app/controllers/polls_controller.rb b/plugins/polls/app/controllers/polls_controller.rb index aac4ef0e..91934f6e 100644 --- a/plugins/polls/app/controllers/polls_controller.rb +++ b/plugins/polls/app/controllers/polls_controller.rb @@ -27,9 +27,9 @@ def create def edit @poll = Poll.find(params[:id]) - if user_has_no_right - redirect_to polls_path, alert: t('.no_right') - end + return unless user_has_no_right + + redirect_to polls_path, alert: t('.no_right') end def update @@ -53,8 +53,8 @@ def destroy @poll.destroy redirect_to polls_path, notice: t('.notice') end - rescue => error - redirect_to polls_path, alert: t('.error', error: error.message) + rescue StandardError => e + redirect_to polls_path, alert: t('.error', error: e.message) end def vote @@ -73,25 +73,25 @@ def vote @poll_vote = @poll.poll_votes.where(attributes).first_or_initialize - if request.post? - @poll_vote.update!(note: params[:note], user: current_user) + return unless request.post? - if @poll.single_select? - choices = {} - choice = params[:choice] - choices[choice] = '1' if choice - else - choices = params[:choices].try(:to_h) || {} - end + @poll_vote.update!(note: params[:note], user: current_user) - @poll_vote.poll_choices = choices.map do |choice, value| - poll_choice = @poll_vote.poll_choices.where(choice: choice).first_or_initialize - poll_choice.update!(value: value) - poll_choice - end + if @poll.single_select? + choices = {} + choice = params[:choice] + choices[choice] = '1' if choice + else + choices = params[:choices].try(:to_h) || {} + end - redirect_to @poll + @poll_vote.poll_choices = choices.map do |choice, value| + poll_choice = @poll_vote.poll_choices.where(choice: choice).first_or_initialize + poll_choice.update!(value: value) + poll_choice end + + redirect_to @poll end private diff --git a/plugins/polls/db/migrate/20181110000000_create_polls.rb b/plugins/polls/db/migrate/20181110000000_create_polls.rb index 990e75f0..120b7eef 100644 --- a/plugins/polls/db/migrate/20181110000000_create_polls.rb +++ b/plugins/polls/db/migrate/20181110000000_create_polls.rb @@ -24,14 +24,14 @@ def change t.references :ordergroup t.text :note t.timestamps - t.index [:poll_id, :user_id, :ordergroup_id], unique: true + t.index %i[poll_id user_id ordergroup_id], unique: true end create_table :poll_choices do |t| t.references :poll_vote, null: false t.integer :choice, null: false t.integer :value, null: false - t.index [:poll_vote_id, :choice], unique: true + t.index %i[poll_vote_id choice], unique: true end end end diff --git a/plugins/polls/db/migrate/20181120000000_increase_choices_size.rb b/plugins/polls/db/migrate/20181120000000_increase_choices_size.rb index d809e3ea..621863dd 100644 --- a/plugins/polls/db/migrate/20181120000000_increase_choices_size.rb +++ b/plugins/polls/db/migrate/20181120000000_increase_choices_size.rb @@ -1,5 +1,5 @@ class IncreaseChoicesSize < ActiveRecord::Migration[4.2] def up - change_column :polls, :choices, :text, limit: 65535 + change_column :polls, :choices, :text, limit: 65_535 end end diff --git a/plugins/polls/foodsoft_polls.gemspec b/plugins/polls/foodsoft_polls.gemspec index e5b25173..607a1276 100644 --- a/plugins/polls/foodsoft_polls.gemspec +++ b/plugins/polls/foodsoft_polls.gemspec @@ -1,21 +1,21 @@ -$:.push File.expand_path("../lib", __FILE__) +$:.push File.expand_path('lib', __dir__) # Maintain your gem's version: -require "foodsoft_polls/version" +require 'foodsoft_polls/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| - s.name = "foodsoft_polls" + s.name = 'foodsoft_polls' s.version = FoodsoftPolls::VERSION - s.authors = ["paroga"] - s.email = ["paroga@paroga.com"] - s.homepage = "https://github.com/foodcoops/foodsoft" - s.summary = "Polls plugin for foodsoft." - s.description = "Adds possibility to do polls with foodsoft." + s.authors = ['paroga'] + s.email = ['paroga@paroga.com'] + s.homepage = 'https://github.com/foodcoops/foodsoft' + s.summary = 'Polls plugin for foodsoft.' + s.description = 'Adds possibility to do polls with foodsoft.' - s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"] - s.test_files = Dir["test/**/*"] + s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md'] - s.add_dependency "rails" - s.add_dependency "deface", "~> 1.0" + s.add_dependency 'rails' + s.add_dependency 'deface', '~> 1.0' + s.metadata['rubygems_mfa_required'] = 'true' end diff --git a/plugins/polls/lib/foodsoft_polls/engine.rb b/plugins/polls/lib/foodsoft_polls/engine.rb index a76399f0..e4812345 100644 --- a/plugins/polls/lib/foodsoft_polls/engine.rb +++ b/plugins/polls/lib/foodsoft_polls/engine.rb @@ -8,9 +8,9 @@ def navigation(primary, context) sub_nav.items << SimpleNavigation::Item.new(primary, :polls, I18n.t('navigation.polls'), context.polls_path) # move to right before tasks item - if i = sub_nav.items.index(sub_nav[:tasks]) - sub_nav.items.insert(i, sub_nav.items.delete_at(-1)) - end + return unless i = sub_nav.items.index(sub_nav[:tasks]) + + sub_nav.items.insert(i, sub_nav.items.delete_at(-1)) end end end diff --git a/plugins/polls/lib/foodsoft_polls/version.rb b/plugins/polls/lib/foodsoft_polls/version.rb index 5f3fb96d..84369283 100644 --- a/plugins/polls/lib/foodsoft_polls/version.rb +++ b/plugins/polls/lib/foodsoft_polls/version.rb @@ -1,3 +1,3 @@ module FoodsoftPolls - VERSION = "0.0.1" + VERSION = '0.0.1' end diff --git a/plugins/printer/Rakefile b/plugins/printer/Rakefile old mode 100644 new mode 100755 index 1c9d9839..fbf50e1d --- a/plugins/printer/Rakefile +++ b/plugins/printer/Rakefile @@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_files.include('lib/**/*.rb') end -APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) +APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__) load 'rails/tasks/engine.rake' Bundler::GemHelper.install_tasks @@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end -task :default => :test +task default: :test diff --git a/plugins/printer/app/controllers/printer_controller.rb b/plugins/printer/app/controllers/printer_controller.rb index 178787da..f07ac805 100644 --- a/plugins/printer/app/controllers/printer_controller.rb +++ b/plugins/printer/app/controllers/printer_controller.rb @@ -37,9 +37,7 @@ def update_job(data) job = PrinterJob.unfinished.find_by_id(json[:id]) return unless job - if json[:state] - job.add_update! json[:state], json[:message] - end + job.add_update! json[:state], json[:message] if json[:state] job.finish! if json[:finish] end @@ -53,6 +51,7 @@ def bearer_token def authenticate_printer return head(:unauthorized) unless bearer_token - return head(:forbidden) if bearer_token != FoodsoftConfig[:printer_token] + + 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 17333fb5..da89d106 100644 --- a/plugins/printer/app/controllers/printer_jobs_controller.rb +++ b/plugins/printer/app/controllers/printer_jobs_controller.rb @@ -15,7 +15,7 @@ def create state = order.open? ? 'queued' : 'ready' count = 0 PrinterJob.transaction do - %w(articles fax groups matrix).each do |document| + %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 @@ -39,7 +39,7 @@ def destroy job = PrinterJob.find(params[:id]) job.finish! current_user redirect_to printer_jobs_path, notice: t('.notice') - rescue => error - redirect_to printer_jobs_path, t('errors.general_msg', msg: error.message) + rescue StandardError => e + redirect_to printer_jobs_path, t('errors.general_msg', msg: e.message) end end diff --git a/plugins/printer/config/routes.rb b/plugins/printer/config/routes.rb index 5b1a4784..84a634c5 100644 --- a/plugins/printer/config/routes.rb +++ b/plugins/printer/config/routes.rb @@ -4,7 +4,7 @@ get :socket, on: :collection end - resources :printer_jobs, only: [:index, :create, :show, :destroy] do + resources :printer_jobs, only: %i[index create show destroy] do get :document, on: :member end end diff --git a/plugins/printer/db/migrate/20181201000000_create_printer_jobs.rb b/plugins/printer/db/migrate/20181201000000_create_printer_jobs.rb index ee7665e4..36d175c5 100644 --- a/plugins/printer/db/migrate/20181201000000_create_printer_jobs.rb +++ b/plugins/printer/db/migrate/20181201000000_create_printer_jobs.rb @@ -15,6 +15,6 @@ def change t.text :message end - add_index :printer_job_updates, [:printer_job_id, :created_at] + add_index :printer_job_updates, %i[printer_job_id created_at] end end diff --git a/plugins/printer/foodsoft_printer.gemspec b/plugins/printer/foodsoft_printer.gemspec index cf249593..a6e54455 100644 --- a/plugins/printer/foodsoft_printer.gemspec +++ b/plugins/printer/foodsoft_printer.gemspec @@ -1,22 +1,22 @@ -$:.push File.expand_path("../lib", __FILE__) +$:.push File.expand_path('lib', __dir__) # Maintain your gem's version: -require "foodsoft_printer/version" +require 'foodsoft_printer/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| - s.name = "foodsoft_printer" + s.name = 'foodsoft_printer' s.version = FoodsoftPrinter::VERSION - s.authors = ["paroga"] - s.email = ["paroga@paroga.com"] - s.homepage = "https://github.com/foodcoops/foodsoft" - s.summary = "Printer plugin for foodsoft." - s.description = "Add a printer queue to foodsoft." + s.authors = ['paroga'] + s.email = ['paroga@paroga.com'] + s.homepage = 'https://github.com/foodcoops/foodsoft' + s.summary = 'Printer plugin for foodsoft.' + s.description = 'Add a printer queue to foodsoft.' - s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"] - s.test_files = Dir["test/**/*"] + s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md'] - s.add_dependency "rails" - s.add_dependency "deface", "~> 1.0" - s.add_dependency "tubesock" + s.add_dependency 'rails' + s.add_dependency 'deface', '~> 1.0' + s.add_dependency 'tubesock' + s.metadata['rubygems_mfa_required'] = 'true' end diff --git a/plugins/printer/lib/foodsoft_printer/engine.rb b/plugins/printer/lib/foodsoft_printer/engine.rb index 22144e30..8f1f00cc 100644 --- a/plugins/printer/lib/foodsoft_printer/engine.rb +++ b/plugins/printer/lib/foodsoft_printer/engine.rb @@ -3,18 +3,19 @@ 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 << - SimpleNavigation::Item.new(primary, :printer_jobs, I18n.t('navigation.orders.printer_jobs'), context.printer_jobs_path) - end + return if primary[:orders].nil? + + sub_nav = primary[:orders].sub_navigation + sub_nav.items << + SimpleNavigation::Item.new(primary, :printer_jobs, I18n.t('navigation.orders.printer_jobs'), + context.printer_jobs_path) end def default_foodsoft_config(cfg) cfg[:use_printer] = false end - initializer 'foodsoft_printer.order_printer_jobs' do |app| + initializer 'foodsoft_printer.order_printer_jobs' do |_app| if Rails.configuration.cache_classes OrderPrinterJobs.install else diff --git a/plugins/printer/lib/foodsoft_printer/order_printer_jobs.rb b/plugins/printer/lib/foodsoft_printer/order_printer_jobs.rb index 7501a69e..4c7eeeaa 100644 --- a/plugins/printer/lib/foodsoft_printer/order_printer_jobs.rb +++ b/plugins/printer/lib/foodsoft_printer/order_printer_jobs.rb @@ -4,14 +4,14 @@ def self.included(base) # :nodoc: base.class_eval do has_many :printer_jobs, dependent: :destroy - alias foodsoft_printer_orig_finish! finish! + alias_method :foodsoft_printer_orig_finish!, :finish! def finish!(user) foodsoft_printer_orig_finish!(user) - unless finished? - printer_jobs.unfinished.each do |job| - job.add_update! 'ready' - end + return if finished? + + printer_jobs.unfinished.each do |job| + job.add_update! 'ready' end end end diff --git a/plugins/printer/lib/foodsoft_printer/version.rb b/plugins/printer/lib/foodsoft_printer/version.rb index 17bd39cb..e9d2ad84 100644 --- a/plugins/printer/lib/foodsoft_printer/version.rb +++ b/plugins/printer/lib/foodsoft_printer/version.rb @@ -1,3 +1,3 @@ module FoodsoftPrinter - VERSION = "0.0.1" + VERSION = '0.0.1' end diff --git a/plugins/uservoice/foodsoft_uservoice.gemspec b/plugins/uservoice/foodsoft_uservoice.gemspec index f33760fb..4defe395 100644 --- a/plugins/uservoice/foodsoft_uservoice.gemspec +++ b/plugins/uservoice/foodsoft_uservoice.gemspec @@ -1,20 +1,21 @@ -$:.push File.expand_path("../lib", __FILE__) +$:.push File.expand_path('lib', __dir__) # Maintain your gem's version: -require "foodsoft_uservoice/version" +require 'foodsoft_uservoice/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| - s.name = "foodsoft_uservoice" + s.name = 'foodsoft_uservoice' s.version = FoodsoftUservoice::VERSION - s.authors = ["wvengen"] - s.email = ["dev-foodsoft@willem.engen.nl"] - s.homepage = "https://github.com/foodcoops/foodsoft" - s.summary = "Uservoice plugin for foodsoft." - s.description = "Adds a uservoice feedback button to foodsoft." + s.authors = ['wvengen'] + s.email = ['dev-foodsoft@willem.engen.nl'] + s.homepage = 'https://github.com/foodcoops/foodsoft' + s.summary = 'Uservoice plugin for foodsoft.' + s.description = 'Adds a uservoice feedback button to foodsoft.' - s.files = Dir["{app,config,db,lib}/**/*"] + ["README.md"] + s.files = Dir['{app,config,db,lib}/**/*'] + ['README.md'] - s.add_dependency "rails" - s.add_dependency "content_for_in_controllers" + s.add_dependency 'rails' + s.add_dependency 'content_for_in_controllers' + s.metadata['rubygems_mfa_required'] = 'true' end diff --git a/plugins/uservoice/lib/foodsoft_uservoice.rb b/plugins/uservoice/lib/foodsoft_uservoice.rb index b4718445..19b52ddc 100644 --- a/plugins/uservoice/lib/foodsoft_uservoice.rb +++ b/plugins/uservoice/lib/foodsoft_uservoice.rb @@ -1,5 +1,5 @@ -require "content_for_in_controllers" -require "foodsoft_uservoice/engine" +require 'content_for_in_controllers' +require 'foodsoft_uservoice/engine' module FoodsoftUservoice # enabled when configured, but can still be disabled by use_uservoice option @@ -19,11 +19,11 @@ def add_uservoice_script # include uservoice javascript api_key = FoodsoftConfig[:uservoice]['api_key'] - js_pre = "UserVoice=window.UserVoice||[];" + js_pre = 'UserVoice=window.UserVoice||[];' 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 = 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') @@ -48,5 +48,5 @@ def add_uservoice_script end ActiveSupport.on_load(:after_initialize) do - ApplicationController.send :include, FoodsoftUservoice::LoadUservoice + ApplicationController.include FoodsoftUservoice::LoadUservoice end diff --git a/plugins/uservoice/lib/foodsoft_uservoice/version.rb b/plugins/uservoice/lib/foodsoft_uservoice/version.rb index 8d78e3de..e806ff1d 100644 --- a/plugins/uservoice/lib/foodsoft_uservoice/version.rb +++ b/plugins/uservoice/lib/foodsoft_uservoice/version.rb @@ -1,3 +1,3 @@ module FoodsoftUservoice - VERSION = "0.0.1" + VERSION = '0.0.1' end diff --git a/plugins/wiki/Rakefile b/plugins/wiki/Rakefile old mode 100644 new mode 100755 index 5d2e31db..dd14bed8 --- a/plugins/wiki/Rakefile +++ b/plugins/wiki/Rakefile @@ -20,7 +20,7 @@ RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_files.include('lib/**/*.rb') end -APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) +APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__) load 'rails/tasks/engine.rake' Bundler::GemHelper.install_tasks @@ -34,4 +34,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end -task :default => :test +task default: :test diff --git a/plugins/wiki/app/controllers/pages_controller.rb b/plugins/wiki/app/controllers/pages_controller.rb index c065abe7..4a8c9a5f 100644 --- a/plugins/wiki/app/controllers/pages_controller.rb +++ b/plugins/wiki/app/controllers/pages_controller.rb @@ -1,20 +1,20 @@ class PagesController < ApplicationController before_action -> { require_plugin_enabled FoodsoftWiki } - before_action :catch_special_pages, only: [:show, :new] + before_action :catch_special_pages, only: %i[show new] - skip_before_action :authenticate, :only => :all - before_action :only => :all do - authenticate_or_token(['wiki', 'all']) + skip_before_action :authenticate, only: :all + before_action only: :all do + authenticate_or_token(%w[wiki all]) end before_action do content_for :head, view_context.rss_meta_tag end def index - @page = Page.find_by_permalink "Home" + @page = Page.find_by_permalink 'Home' if @page - render :action => 'show' + render action: 'show' else redirect_to all_pages_path end @@ -34,11 +34,11 @@ def show end if @page.nil? - redirect_to new_page_path(:title => params[:permalink]) + redirect_to new_page_path(title: params[:permalink]) elsif @page.redirect? page = Page.find_by_id(@page.redirect) unless page.nil? - flash[:notice] = I18n.t('pages.cshow.redirect_notice', :page => @page.title) + flash[:notice] = I18n.t('pages.cshow.redirect_notice', page: @page.title) redirect_to wiki_page_path(page.permalink) end end @@ -46,12 +46,12 @@ def show def new @page = Page.new - @page.title = params[:title].gsub("_", " ") if params[:title] + @page.title = params[:title].gsub('_', ' ') if params[:title] @page.parent = Page.find_by_permalink(params[:parent]) if params[:parent] respond_to do |format| format.html # new.html.erb - format.xml { render :xml => @page } + format.xml { render xml: @page } end end @@ -60,36 +60,32 @@ def edit 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' + render action: 'new' + elsif @page.save + flash[:notice] = I18n.t('pages.create.notice') + redirect_to(wiki_page_path(@page.permalink)) else - if @page.save - flash[:notice] = I18n.t('pages.create.notice') - redirect_to(wiki_page_path(@page.permalink)) - else - render :action => "new" - end + render action: 'new' end end 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] - render :action => 'edit' + render action: 'edit' + elsif @page.save + @page.parent_id = parent_id if params[:parent_id].present? \ + && params[:parent_id] != @page_id + flash[:notice] = I18n.t('pages.update.notice') + redirect_to wiki_page_path(@page.permalink) else - if @page.save - @page.parent_id = parent_id if (!params[:parent_id].blank? \ - && params[:parent_id] != @page_id) - flash[:notice] = I18n.t('pages.update.notice') - redirect_to wiki_page_path(@page.permalink) - else - render :action => "edit" - end + render action: 'edit' end rescue ActiveRecord::StaleObjectError flash[:error] = I18n.t('pages.error_stale_object') @@ -100,7 +96,7 @@ def destroy @page = Page.find(params[:id]) @page.destroy - flash[:notice] = I18n.t('pages.destroy.notice', :page => @page.title) + flash[:notice] = I18n.t('pages.destroy.notice', page: @page.title) redirect_to wiki_path end @@ -109,23 +105,23 @@ def all @partial = params[:view] || 'site_map' if params[:name] - @pages = @pages.where("title LIKE ?", "%#{params[:name]}%").limit(20) + @pages = @pages.where('title LIKE ?', "%#{params[:name]}%").limit(20) @partial = 'title_list' 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" + sort = if params[: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 - else - sort = "title" - end + else + 'title' + end @pages = @pages.order(sort) respond_to do |format| format.html - format.rss { render :layout => false } + format.rss { render layout: false } end end @@ -150,15 +146,13 @@ def revert def variables keys = Foodsoft::ExpansionVariables.variables.keys - @variables = Hash[keys.map { |k| [k, Foodsoft::ExpansionVariables.get(k)] }] + @variables = keys.index_with { |k| Foodsoft::ExpansionVariables.get(k) } render 'variables' end private def catch_special_pages - if params[:id] == 'Help:Foodsoft_variables' - variables - end + variables if params[:id] == 'Help:Foodsoft_variables' end end diff --git a/plugins/wiki/app/helpers/pages_helper.rb b/plugins/wiki/app/helpers/pages_helper.rb index 551a169d..60ab988a 100644 --- a/plugins/wiki/app/helpers/pages_helper.rb +++ b/plugins/wiki/app/helpers/pages_helper.rb @@ -2,70 +2,70 @@ module PagesHelper include WikiCloth def rss_meta_tag - tag('link', :rel => "alternate", :type => "application/rss+xml", :title => "RSS", :href => all_pages_rss_url).html_safe + tag.link(rel: 'alternate', type: 'application/rss+xml', title: 'RSS', href: all_pages_rss_url).html_safe end def wikified_body(body, title = nil) FoodsoftWiki::WikiParser.new(data: body + "\n", params: { referer: title }).to_html(noedit: true).html_safe - rescue => e + rescue StandardError => e # try the following with line breaks: === one === == two == = three = content_tag :span, class: 'alert alert-error' do - I18n.t '.wikicloth_exception', :msg => e + I18n.t '.wikicloth_exception', msg: e end.html_safe end def link_to_wikipage(page, text = nil) - if text == nil - link_to page.title, wiki_page_path(:permalink => page.permalink) + if text.nil? + link_to page.title, wiki_page_path(permalink: page.permalink) else - link_to text, wiki_page_path(:permalink => page.permalink) + link_to text, wiki_page_path(permalink: page.permalink) 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) - else - link_to text, new_page_path(:title => permalink) - end + return if permalink.blank? + + page = Page.find_by_permalink(permalink) + if page.nil? + if text.nil? + link_to permalink, new_page_path(title: permalink) else - link_to_wikipage(page, text) + link_to text, new_page_path(title: permalink) end + else + link_to_wikipage(page, text) end end def generate_toc(body) toc = String.new body.gsub(/^([=]{1,6})\s*(.*?)\s*(\1)/) do - number = $1.length - 1 - name = $2 + number = ::Regexp.last_match(1).length - 1 + name = ::Regexp.last_match(2) - toc << "*" * number + " #{name}\n" + toc << (('*' * number) + " #{name}\n") end - unless toc.blank? - FoodsoftWiki::WikiParser.new(data: toc).to_html.gsub(/
  • ([^<>\n]*)/) do - name = $1 - anchor = name.gsub(/\s/, '_').gsub(/[^a-zA-Z_]/, '') - "
  • #{name.truncate(20)}" - end.html_safe - end + return if toc.blank? + + FoodsoftWiki::WikiParser.new(data: toc).to_html.gsub(/
  • ([^<>\n]*)/) do + name = ::Regexp.last_match(1) + anchor = name.gsub(/\s/, '_').gsub(/[^a-zA-Z_]/, '') + "
  • #{name.truncate(20)}" + end.html_safe end def parent_pages_to_select(current_page) - unless current_page.homepage? # Homepage is the page trees root! + if current_page.homepage? + [] + else # Homepage is the page trees root! Page.non_redirected.reject { |p| p == current_page || p.ancestors.include?(current_page) } - else - Array.new end end # return url for all_pages rss feed def all_pages_rss_url(options = {}) - token = TokenVerifier.new(['wiki', 'all']).generate - all_pages_url({ :format => 'rss', :token => token }.merge(options)) + token = TokenVerifier.new(%w[wiki all]).generate + 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 e773afa7..fae004ce 100644 --- a/plugins/wiki/app/models/page.rb +++ b/plugins/wiki/app/models/page.rb @@ -1,61 +1,62 @@ class Page < ApplicationRecord include ActsAsTree - belongs_to :user, :foreign_key => 'updated_by' + belongs_to :user, foreign_key: 'updated_by' acts_as_versioned version_column: :lock_version - self.non_versioned_columns += %w(permalink created_at title) + self.non_versioned_columns += %w[permalink created_at title] - acts_as_tree :order => "title" + acts_as_tree order: 'title' attr_accessor :old_title # Save title to create redirect page when editing title validates_presence_of :title, :body validates_uniqueness_of :permalink, :title - before_validation :set_permalink, :on => :create - before_validation :update_permalink, :on => :update + before_validation :set_permalink, on: :create + before_validation :update_permalink, on: :update after_update :create_redirect - scope :non_redirected, -> { where(:redirect => nil) } - scope :no_parent, -> { where(:parent_id => nil) } + scope :non_redirected, -> { where(redirect: nil) } + scope :no_parent, -> { where(parent_id: nil) } def self.permalink(title) - title.gsub(/[\/\.,;@\s]/, "_").gsub(/[\"\']/, "") + title.gsub(%r{[/\.,;@\s]}, '_').gsub(/[\"\']/, '') end def homepage? - permalink == "Home" + permalink == 'Home' end def self.dashboard - where(permalink: "Dashboard").first + where(permalink: 'Dashboard').first end def self.public_front_page - where(permalink: "Public_frontpage").first + where(permalink: 'Public_frontpage').first end def self.welcome_mail - where(permalink: "Welcome_mail").first + where(permalink: 'Welcome_mail').first end def set_permalink - unless title.blank? - self.permalink = Page.count == 0 ? "Home" : Page.permalink(title) - end + return if title.blank? + + self.permalink = Page.count == 0 ? 'Home' : Page.permalink(title) end def diff current = versions.latest - old = versions.where(["page_id = ? and lock_version < ?", current.page_id, current.lock_version]).order('lock_version DESC').first + old = versions.where(['page_id = ? and lock_version < ?', current.page_id, + current.lock_version]).order('lock_version DESC').first if old o = '' Diffy::Diff.new(old.body, current.body).each do |line| case line - when /^\+/ then o += "#{line.chomp}
    " unless line.chomp == "+" - when /^-/ then o += "#{line.chomp}
    " unless line.chomp == "-" + when /^\+/ then o += "#{line.chomp}
    " unless line.chomp == '+' + when /^-/ then o += "#{line.chomp}
    " unless line.chomp == '-' end end o @@ -67,19 +68,19 @@ def diff protected def update_permalink - if changed.include?("title") - set_permalink - self.old_title = changes["title"].first # Save title for creating redirect - end + return unless changed.include?('title') + + set_permalink + self.old_title = changes['title'].first # Save title for creating redirect end 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 - end + return if 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 end end diff --git a/plugins/wiki/app/views/pages/all.rss.builder b/plugins/wiki/app/views/pages/all.rss.builder index f7194763..e0340188 100644 --- a/plugins/wiki/app/views/pages/all.rss.builder +++ b/plugins/wiki/app/views/pages/all.rss.builder @@ -1,14 +1,14 @@ -xml.instruct! :xml, :version => "1.0" -xml.rss :version => "2.0" do +xml.instruct! :xml, version: '1.0' +xml.rss version: '2.0' do xml.channel do - xml.title FoodsoftConfig[:name] + " Wiki" - xml.description "" + xml.title FoodsoftConfig[:name] + ' Wiki' + xml.description '' xml.link FoodsoftConfig[:homepage] for page in @pages xml.item do xml.title page.title - xml.description page.diff, :type => "html" + xml.description page.diff, type: 'html' xml.author User.find_by_id(page.updated_by).try(:display) xml.pubDate page.updated_at.to_s(:rfc822) xml.link wiki_page_path(page.permalink) diff --git a/plugins/wiki/config/routes.rb b/plugins/wiki/config/routes.rb index 4ebad572..ad713366 100644 --- a/plugins/wiki/config/routes.rb +++ b/plugins/wiki/config/routes.rb @@ -1,12 +1,12 @@ Rails.application.routes.draw do scope '/:foodcoop' do resources :pages do - get :all, :on => :collection - get :version, :on => :member - get :revert, :on => :member - get :diff, :on => :member + get :all, on: :collection + get :version, on: :member + get :revert, on: :member + 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/db/migrate/20090325175756_create_pages.rb b/plugins/wiki/db/migrate/20090325175756_create_pages.rb index 846decf8..cdd00e2b 100644 --- a/plugins/wiki/db/migrate/20090325175756_create_pages.rb +++ b/plugins/wiki/db/migrate/20090325175756_create_pages.rb @@ -4,7 +4,7 @@ def self.up t.string :title t.text :body t.string :permalink - t.integer :lock_version, :default => 0 + t.integer :lock_version, default: 0 t.integer :updated_by t.integer :redirect t.integer :parent_id diff --git a/plugins/wiki/foodsoft_wiki.gemspec b/plugins/wiki/foodsoft_wiki.gemspec index 07f0c182..58be331d 100644 --- a/plugins/wiki/foodsoft_wiki.gemspec +++ b/plugins/wiki/foodsoft_wiki.gemspec @@ -1,27 +1,27 @@ -$:.push File.expand_path("../lib", __FILE__) +$:.push File.expand_path('lib', __dir__) # Maintain your gem's version: -require "foodsoft_wiki/version" +require 'foodsoft_wiki/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| - s.name = "foodsoft_wiki" + s.name = 'foodsoft_wiki' s.version = FoodsoftWiki::VERSION - s.authors = ["wvengen"] - s.email = ["dev-foodsoft@willem.engen.nl"] - s.homepage = "https://github.com/foodcoops/foodsoft" - s.summary = "Wiki plugin for foodsoft." - s.description = "Adds a wiki to foodsoft." + s.authors = ['wvengen'] + s.email = ['dev-foodsoft@willem.engen.nl'] + s.homepage = 'https://github.com/foodcoops/foodsoft' + s.summary = 'Wiki plugin for foodsoft.' + s.description = 'Adds a wiki to foodsoft.' - s.files = Dir["{app,config,db,lib}/**/*"] + ["Rakefile", "README.md"] - s.test_files = Dir["test/**/*"] + s.files = Dir['{app,config,db,lib}/**/*'] + ['Rakefile', 'README.md'] - s.add_dependency "rails" + s.add_dependency 'rails' s.add_dependency 'wikicloth' s.add_dependency 'twitter-text', '~> 1.14' # wikicloth doesn't support version 2 s.add_dependency 'acts_as_versioned' # need git version, make sure that is included in foodsoft's Gemfile - s.add_dependency "deface", "~> 1.0" + s.add_dependency 'deface', '~> 1.0' s.add_dependency 'diffy' s.add_dependency 'content_for_in_controllers' - s.add_development_dependency "sqlite3" + s.add_development_dependency 'sqlite3' + s.metadata['rubygems_mfa_required'] = 'true' end diff --git a/plugins/wiki/lib/foodsoft_wiki/engine.rb b/plugins/wiki/lib/foodsoft_wiki/engine.rb index 4cc20f6a..ae2ce462 100644 --- a/plugins/wiki/lib/foodsoft_wiki/engine.rb +++ b/plugins/wiki/lib/foodsoft_wiki/engine.rb @@ -8,17 +8,17 @@ def navigation(primary, ctx) 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)) - end + return unless i = primary.items.index(primary[:foodcoop]) + + primary.items.insert(i + 1, primary.items.delete_at(-1)) end def default_foodsoft_config(cfg) cfg[:use_wiki] = true end - initializer "foodsoft_wiki.assets.precompile" do |app| - app.config.assets.precompile += %w(icons/feed-icon-14x14.png) + initializer 'foodsoft_wiki.assets.precompile' do |app| + app.config.assets.precompile += %w[icons/feed-icon-14x14.png] end end end diff --git a/plugins/wiki/lib/foodsoft_wiki/mailer.rb b/plugins/wiki/lib/foodsoft_wiki/mailer.rb index 83a110f1..4b7a892d 100644 --- a/plugins/wiki/lib/foodsoft_wiki/mailer.rb +++ b/plugins/wiki/lib/foodsoft_wiki/mailer.rb @@ -3,10 +3,10 @@ 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 + def additonal_welcome_text(_user) + return unless FoodsoftWiki.enabled? && (page = Page.welcome_mail) + + page.body end end end @@ -15,5 +15,5 @@ def additonal_welcome_text(user) # modify existing helper ActiveSupport.on_load(:after_initialize) do - Mailer.send :include, FoodsoftWiki::Mailer + Mailer.include FoodsoftWiki::Mailer end diff --git a/plugins/wiki/lib/foodsoft_wiki/version.rb b/plugins/wiki/lib/foodsoft_wiki/version.rb index 2a67a94e..580ee3ed 100644 --- a/plugins/wiki/lib/foodsoft_wiki/version.rb +++ b/plugins/wiki/lib/foodsoft_wiki/version.rb @@ -1,3 +1,3 @@ module FoodsoftWiki - VERSION = "0.0.1" + VERSION = '0.0.1' end diff --git a/plugins/wiki/lib/foodsoft_wiki/wiki_parser.rb b/plugins/wiki/lib/foodsoft_wiki/wiki_parser.rb index 37e58465..6e14d2a8 100644 --- a/plugins/wiki/lib/foodsoft_wiki/wiki_parser.rb +++ b/plugins/wiki/lib/foodsoft_wiki/wiki_parser.rb @@ -10,7 +10,7 @@ class WikiParser < WikiCloth::Parser link_attributes_for do |page| permalink = Page.permalink(page) - if Page.exists?(:permalink => permalink) + if Page.exists?(permalink: permalink) { href: url_for(:wiki_page_path, permalink: permalink) } elsif page.include? '#' # If "Foo#Bar" does not exist then consider "Foo" with anchor. @@ -20,8 +20,8 @@ class WikiParser < WikiCloth::Parser end end - section_link do |section| - "" + section_link do |_section| + '' end def to_html(render_options = {}) @@ -41,7 +41,7 @@ def link_attributes_if_number_sign_contained_in_nonexistent(page, referer) return { href: '#' + anchor } if page.empty? permalink = Page.permalink(page) - if Page.exists?(:permalink => permalink) + if Page.exists?(permalink: permalink) { href: url_for(:wiki_page_path, permalink: permalink, anchor: anchor) } else # Do not suggest to use number signs in the title. diff --git a/script/rails b/script/rails index bd79dce5..3c234a25 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', __dir__) +require File.expand_path('../config/boot', __dir__) require 'rails/commands' diff --git a/spec/api/v1/order_articles_spec.rb b/spec/api/v1/order_articles_spec.rb index 2639a41d..8be3b463 100644 --- a/spec/api/v1/order_articles_spec.rb +++ b/spec/api/v1/order_articles_spec.rb @@ -6,12 +6,13 @@ 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 + describe 'GET :index' do + context 'with param q[ordered]' do let(:order) { create(:order, article_count: 4) } let(:order_articles) { order.order_articles } + before do order_articles[0].update_attributes! quantity: 0, tolerance: 0, units_to_order: 0 order_articles[1].update_attributes! quantity: 1, tolerance: 0, units_to_order: 0 @@ -19,35 +20,36 @@ order_articles[3].update_attributes! quantity: 0, tolerance: 0, units_to_order: 1 end - it "(unset)" do + it '(unset)' do get :index, params: { foodcoop: 'f' } expect(json_order_articles.count).to eq 4 end - it "all" do + it 'all' do get :index, params: { foodcoop: 'f', q: { ordered: 'all' } } expect(json_order_article_ids).to match_array order_articles[1..2].map(&:id) end - it "supplier" do + it 'supplier' do get :index, params: { foodcoop: 'f', q: { ordered: 'supplier' } } - expect(json_order_article_ids).to match_array [order_articles[3].id] + expect(json_order_article_ids).to contain_exactly(order_articles[3].id) end - it "member" do + it 'member' do get :index, params: { foodcoop: 'f', q: { ordered: 'member' } } expect(json_order_articles.count).to eq 0 end - context "when ordered by user" do + context 'when ordered by user' do let(:user) { create(:user, :ordergroup) } let(:go) { create(:group_order, order: order, ordergroup: user.ordergroup) } + before do create(:group_order_article, group_order: go, order_article: order_articles[1], quantity: 1) create(:group_order_article, group_order: go, order_article: order_articles[2], tolerance: 0) end - it "member" do + it 'member' do get :index, params: { foodcoop: 'f', q: { ordered: 'member' } } expect(json_order_article_ids).to match_array order_articles[1..2].map(&:id) end diff --git a/spec/api/v1/swagger_spec.rb b/spec/api/v1/swagger_spec.rb index a481155c..5c0f043a 100644 --- a/spec/api/v1/swagger_spec.rb +++ b/spec/api/v1/swagger_spec.rb @@ -4,22 +4,22 @@ # we want to load a local file in YAML-format instead of a served JSON file class SwaggerCheckerFile < Apivore::SwaggerChecker def fetch_swagger! - YAML.load(File.read(swagger_path)) + YAML.load_file(swagger_path) end end -describe 'API v1', type: :apivore, order: :defined do +describe 'API v1', order: :defined, type: :apivore do include ApiHelper - subject { SwaggerCheckerFile.instance_for Rails.root.join('doc', 'swagger.v1.yml') } + subject { SwaggerCheckerFile.instance_for Rails.root.join('doc/swagger.v1.yml') } context 'has valid paths' do context 'user' do let(:api_scopes) { ['user:read'] } # create multiple users to make sure we're getting the authenticated user, not just any - let!(:other_user_1) { create :user } - let!(:user) { create :user } - let!(:other_user_2) { create :user } + let!(:other_user_1) { create(:user) } + let!(:user) { create(:user) } + let!(:other_user_2) { create(:user) } it { is_expected.to validate(:get, '/user', 200, api_auth) } it { is_expected.to validate(:get, '/user', 401) } @@ -29,7 +29,7 @@ def fetch_swagger! context 'user/financial_overview' do let(:api_scopes) { ['finance:user'] } - let!(:user) { create :user, :ordergroup } + let!(:user) { create(:user, :ordergroup) } it { is_expected.to validate(:get, '/user/financial_overview', 200, api_auth) } it { is_expected.to validate(:get, '/user/financial_overview', 401) } @@ -39,26 +39,39 @@ def fetch_swagger! context 'user/financial_transactions' do let(:api_scopes) { ['finance:user'] } - let(:other_user) { create :user, :ordergroup } - let!(:other_ft_1) { create :financial_transaction, ordergroup: other_user.ordergroup } + let(:other_user) { create(:user, :ordergroup) } + let!(:other_ft_1) { create(:financial_transaction, ordergroup: other_user.ordergroup) } 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 { + expect(subject).to validate(:get, '/user/financial_transactions/{id}', 403, api_auth({ 'id' => other_ft_1.id })) + } end context 'with ordergroup' do - let(:user) { create :user, :ordergroup } - let!(:ft_1) { create :financial_transaction, ordergroup: user.ordergroup } - let!(:ft_2) { create :financial_transaction, ordergroup: user.ordergroup } - let!(:ft_3) { create :financial_transaction, ordergroup: user.ordergroup } + let(:user) { create(:user, :ordergroup) } + let!(:ft_1) { create(:financial_transaction, ordergroup: user.ordergroup) } + let!(:ft_2) { create(:financial_transaction, ordergroup: user.ordergroup) } + let!(:ft_3) { create(:financial_transaction, ordergroup: user.ordergroup) } + + let(:create_params) do + { '_data' => { financial_transaction: { amount: 1, financial_transaction_type_id: ft_1.financial_transaction_type.id, + note: 'note' } } } + end 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 })) } - let(:create_params) { { '_data' => { financial_transaction: { amount: 1, financial_transaction_type_id: ft_1.financial_transaction_type.id, note: 'note' } } } } + it { + expect(subject).to validate(:get, '/user/financial_transactions/{id}', 404, api_auth({ 'id' => other_ft_1.id })) + } + + it { + expect(subject).to validate(:get, '/user/financial_transactions/{id}', 404, + api_auth({ 'id' => FinancialTransaction.last.id + 1 })) + } context 'without using self service' do it { is_expected.to validate(:post, '/user/financial_transactions', 403, api_auth(create_params)) } @@ -70,19 +83,25 @@ def fetch_swagger! 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) do + { '_data' => { financial_transaction: { amount: 1, financial_transaction_type_id: -1, note: 'note' } } } + end 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) do + { '_data' => { financial_transaction: { amount: 1, + financial_transaction_type_id: ft_1.financial_transaction_type.id } } } + end it { is_expected.to validate(:post, '/user/financial_transactions', 422, api_auth(create_params)) } end context 'without enough balance' do before { FoodsoftConfig[:minimum_balance] = 1000 } + it { is_expected.to validate(:post, '/user/financial_transactions', 403, api_auth(create_params)) } end end @@ -97,10 +116,14 @@ def fetch_swagger! let(:api_scopes) { ['group_orders:user'] } let(:order) { create(:order, article_count: 2) } - let(:user_2) { create :user, :ordergroup } + let(:user_2) { create(:user, :ordergroup) } let(:group_order_2) { create(:group_order, order: order, ordergroup: user_2.ordergroup) } - let!(:goa_2) { create :group_order_article, order_article: order.order_articles[0], group_order: group_order_2 } - before { group_order_2.update_price!; user_2.ordergroup.update_stats! } + let!(:goa_2) { create(:group_order_article, order_article: order.order_articles[0], group_order: group_order_2) } + + before do + group_order_2.update_price! + user_2.ordergroup.update_stats! + end context 'without ordergroup' do it { is_expected.to validate(:get, '/user/group_order_articles', 403, api_auth) } @@ -108,31 +131,46 @@ def fetch_swagger! end context 'with ordergroup' do - let(:user) { create :user, :ordergroup } + let(:user) { create(:user, :ordergroup) } + let(:update_params) do + { 'id' => goa.id, '_data' => { group_order_article: { quantity: goa.quantity + 1, tolerance: 0 } } } + end + let(:create_params) do + { '_data' => { group_order_article: { order_article_id: order.order_articles[1].id, quantity: 1 } } } + end let(:group_order) { create(:group_order, order: order, ordergroup: user.ordergroup) } - let!(:goa) { create :group_order_article, order_article: order.order_articles[0], group_order: group_order } - before { group_order.update_price!; user.ordergroup.update_stats! } + let!(:goa) { create(:group_order_article, order_article: order.order_articles[0], group_order: group_order) } + + before do + group_order.update_price! + user.ordergroup.update_stats! + end 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 })) } - 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 { + expect(subject).to validate(:get, '/user/group_order_articles/{id}', 404, + api_auth({ 'id' => GroupOrderArticle.last.id + 1 })) + } 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 })) } 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) do + { '_data' => { group_order_article: { order_article_id: order.order_articles[0].id, quantity: 1 } } } + end 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(:create_params) do + { '_data' => { group_order_article: { order_article_id: order.order_articles[0].id, quantity: -1 } } } + end 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)) } @@ -149,6 +187,7 @@ def fetch_swagger! 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 })) } @@ -156,6 +195,7 @@ def fetch_swagger! context 'without enough apple points' do 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 })) } @@ -165,7 +205,9 @@ def fetch_swagger! 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(:delete, '/user/group_order_articles/{id}', lambda { + api_auth({ 'id' => goa.id }) + }) end end @@ -188,16 +230,21 @@ def fetch_swagger! context 'financial_transactions' do let(:api_scopes) { ['finance:read'] } let(:user) { create(:user, :role_finance) } - let(:other_user) { create :user, :ordergroup } - let!(:ft_1) { create :financial_transaction, ordergroup: other_user.ordergroup } - let!(:ft_2) { create :financial_transaction, ordergroup: other_user.ordergroup } + let(:other_user) { create(:user, :ordergroup) } + let!(:ft_1) { create(:financial_transaction, ordergroup: other_user.ordergroup) } + 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 { + expect(subject).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 })) } end @@ -207,20 +254,23 @@ def fetch_swagger! end context 'financial_transaction_classes' do - let!(:cla_1) { create :financial_transaction_class } - let!(:cla_2) { create :financial_transaction_class } + let!(:cla_1) { create(:financial_transaction_class) } + 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 { + expect(subject).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 }) }) end context 'financial_transaction_types' do - let!(:tpy_1) { create :financial_transaction_type } - let!(:tpy_2) { create :financial_transaction_type } + let!(:tpy_1) { create(:financial_transaction_type) } + 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 })) } @@ -232,7 +282,7 @@ def fetch_swagger! context 'orders' do let(:api_scopes) { ['orders:read'] } - let!(:order) { create :order } + 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 })) } @@ -258,8 +308,8 @@ def fetch_swagger! end context 'article_categories' do - let!(:cat_1) { create :article_category } - let!(:cat_2) { create :article_category } + let!(:cat_1) { create(:article_category) } + 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 })) } @@ -273,7 +323,7 @@ def fetch_swagger! # needs to be last context so it is always run at the end context 'and finally' do it 'tests all documented routes' do - is_expected.to validate_all_paths + expect(subject).to validate_all_paths end end end diff --git a/spec/api/v1/user/financial_transactions_spec.rb b/spec/api/v1/user/financial_transactions_spec.rb index a5952b67..62b50e4c 100644 --- a/spec/api/v1/user/financial_transactions_spec.rb +++ b/spec/api/v1/user/financial_transactions_spec.rb @@ -6,29 +6,29 @@ let(:user) { create(:user, :ordergroup) } let(:api_scopes) { ['finance:user'] } - let(:ftc1) { create :financial_transaction_class } - let(:ftc2) { create :financial_transaction_class } - 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(:ftc1) { create(:financial_transaction_class) } + let(:ftc2) { create(:financial_transaction_class) } + 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(:amount) { rand(-100..100) } let(:note) { Faker::Lorem.sentence } let(:json_ft) { json_response['financial_transaction'] } - shared_examples "financial_transactions endpoint success" do + shared_examples 'financial_transactions endpoint success' do before { request } - it "returns status 200" do + it 'returns status 200' do expect(response.status).to eq 200 end end - shared_examples "financial_transactions create/update success" do - include_examples "financial_transactions endpoint success" + shared_examples 'financial_transactions create/update success' do + include_examples 'financial_transactions endpoint success' - it "returns the financial_transaction" do + it 'returns the financial_transaction' do expect(json_ft['id']).to be_present expect(json_ft['financial_transaction_type_id']).to eq ftt1.id expect(json_ft['financial_transaction_type_name']).to eq ftt1.name @@ -37,7 +37,7 @@ expect(json_ft['user_id']).to eq user.id end - it "updates the financial_transaction" do + it 'updates the financial_transaction' do resulting_ft = FinancialTransaction.where(id: json_ft['id']).first expect(resulting_ft).to be_present expect(resulting_ft.financial_transaction_type).to eq ftt1 @@ -47,58 +47,62 @@ end end - shared_examples "financial_transactions endpoint failure" do |status| + shared_examples 'financial_transactions endpoint failure' do |status| it "returns status #{status}" do request expect(response.status).to eq status end - it "does not change the ordergroup" do - expect { request }.to_not change { + it 'does not change the ordergroup' do + expect { request }.not_to(change do user.ordergroup.attributes - } + end) end - it "does not change the financial_transactions of ordergroup" do - expect { request }.to_not change { + it 'does not change the financial_transactions of ordergroup' do + expect { request }.not_to(change do user.ordergroup.financial_transactions.count - } + end) end end - describe "POST :create" do + 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' } } context 'without using self service' do - include_examples "financial_transactions endpoint failure", 403 + include_examples 'financial_transactions endpoint failure', 403 end context 'with using self service' do before { FoodsoftConfig[:use_self_service] = true } - context "with no existing financial transaction" do - include_examples "financial_transactions create/update success" + context 'with no existing financial transaction' do + include_examples 'financial_transactions create/update success' end - context "with existing financial transaction" do + context 'with existing financial transaction' do before { user.ordergroup.add_financial_transaction! 5000, 'for ordering', user, ftt3 } - include_examples "financial_transactions create/update success" + + include_examples 'financial_transactions create/update success' end - context "with invalid financial transaction type" do + context 'with invalid financial transaction type' do let(:ft_params) { { amount: amount, financial_transaction_type_id: -1, note: note } } - include_examples "financial_transactions endpoint failure", 404 + + include_examples 'financial_transactions endpoint failure', 404 end - context "without note" do + context 'without note' do let(:ft_params) { { amount: amount, financial_transaction_type_id: ftt1.id } } - include_examples "financial_transactions endpoint failure", 422 + + include_examples 'financial_transactions endpoint failure', 422 end context 'without enough balance' do before { FoodsoftConfig[:minimum_balance] = 1000 } - include_examples "financial_transactions endpoint failure", 403 + + include_examples 'financial_transactions endpoint failure', 403 end end end diff --git a/spec/api/v1/user/group_order_articles_spec.rb b/spec/api/v1/user/group_order_articles_spec.rb index 27fbe843..d440d60b 100644 --- a/spec/api/v1/user/group_order_articles_spec.rb +++ b/spec/api/v1/user/group_order_articles_spec.rb @@ -4,6 +4,8 @@ describe Api::V1::User::GroupOrderArticlesController, type: :controller do include ApiOAuth let(:user) { create(:user, :ordergroup) } + let(:json_goa) { json_response['group_order_article'] } + let(:json_oa) { json_response['order_article'] } let(:api_scopes) { ['group_orders:user'] } let(:order) { create(:order, article_count: 1) } @@ -13,46 +15,50 @@ 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!(: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!(:goa_other) do + create(:group_order_article, group_order: go_other, order_article: oa_1, quantity: other_quantity, + tolerance: other_tolerance) + end - let(:json_goa) { json_response['group_order_article'] } - let(:json_oa) { json_response['order_article'] } + before do + go_other.update_price! + user_other.ordergroup.update_stats! + end - shared_examples "group_order_articles endpoint success" do + shared_examples 'group_order_articles endpoint success' do before { request } - it "returns status 200" do + it 'returns status 200' do expect(response.status).to eq 200 end - it "returns the order_article" do + it 'returns the order_article' do expect(json_oa['id']).to eq oa_1.id expect(json_oa['quantity']).to eq new_quantity + other_quantity expect(json_oa['tolerance']).to eq new_tolerance + other_tolerance end - it "updates the group_order" do + it 'updates the group_order' do go = nil - expect { + expect do request go = user.ordergroup.group_orders.where(order: order).last - }.to change { go&.updated_by }.to(user) - .and change { go&.price } + end.to change { go&.updated_by }.to(user) + .and(change { go&.price }) end end - shared_examples "group_order_articles create/update success" do - include_examples "group_order_articles endpoint success" + shared_examples 'group_order_articles create/update success' do + include_examples 'group_order_articles endpoint success' - it "returns the group_order_article" do + it 'returns the group_order_article' do expect(json_goa['id']).to be_present expect(json_goa['order_article_id']).to eq oa_1.id expect(json_goa['quantity']).to eq new_quantity expect(json_goa['tolerance']).to eq new_tolerance end - it "updates the group_order_article" do + it 'updates the group_order_article' do resulting_goa = GroupOrderArticle.where(id: json_goa['id']).first expect(resulting_goa).to be_present expect(resulting_goa.quantity).to eq new_quantity @@ -60,147 +66,170 @@ end end - shared_examples "group_order_articles endpoint failure" do |status| + shared_examples 'group_order_articles endpoint failure' do |status| it "returns status #{status}" do request expect(response.status).to eq status end - it "does not change the group_order" do - expect { request }.to_not change { + it 'does not change the group_order' do + expect { request }.not_to(change do go = user.ordergroup.group_orders.where(order: order).last go&.attributes - } + end) end - it "does not change the group_order_article" do - expect { request }.to_not change { + it 'does not change the group_order_article' do + expect { request }.not_to(change do goa = GroupOrderArticle.joins(:group_order) .where(order_article_id: oa_1.id, group_orders: { ordergroup: user.ordergroup }).last goa&.attributes - } + end) end end - describe "POST :create" do + describe 'POST :create' do let(:new_quantity) { rand(1..10) } let(:new_tolerance) { rand(1..10) } let(:goa_params) { { order_article_id: oa_1.id, quantity: new_quantity, tolerance: new_tolerance } } let(:request) { post :create, params: { group_order_article: goa_params, foodcoop: 'f' } } - context "with no existing group_order" do - include_examples "group_order_articles create/update success" + context 'with no existing group_order' do + include_examples 'group_order_articles create/update success' end - context "with an existing group_order" do + context 'with an existing group_order' do let!(:go) { create(:group_order, order: order, ordergroup: user.ordergroup) } - include_examples "group_order_articles create/update success" + + include_examples 'group_order_articles create/update success' end - context "with an existing group_order_article" do + context 'with an existing group_order_article' do let!(:go) { create(:group_order, order: order, ordergroup: user.ordergroup) } let!(:goa) { create(:group_order_article, group_order: go, order_article: oa_1, quantity: 0, tolerance: 1) } - before { go.update_price!; user.ordergroup.update_stats! } - include_examples "group_order_articles endpoint failure", 422 + + before do + go.update_price! + user.ordergroup.update_stats! + end + + include_examples 'group_order_articles endpoint failure', 422 end - context "with invalid parameter values" do + context 'with invalid parameter values' do let(:goa_params) { { order_article_id: oa_1.id, quantity: -1, tolerance: new_tolerance } } - include_examples "group_order_articles endpoint failure", 422 + + include_examples 'group_order_articles endpoint failure', 422 end context 'with a closed order' do let(:order) { create(:order, article_count: 1, state: :finished) } - include_examples "group_order_articles endpoint failure", 404 + + include_examples 'group_order_articles endpoint failure', 404 end context 'without enough balance' do before { FoodsoftConfig[:minimum_balance] = 1000 } - include_examples "group_order_articles endpoint failure", 403 + + include_examples 'group_order_articles endpoint failure', 403 end context 'without enough apple points' do before { allow_any_instance_of(Ordergroup).to receive(:not_enough_apples?).and_return(true) } - include_examples "group_order_articles endpoint failure", 403 + + include_examples 'group_order_articles endpoint failure', 403 end end - describe "PATCH :update" do + describe 'PATCH :update' do let(:new_quantity) { rand(2..10) } + let(:goa_params) { { quantity: new_quantity, tolerance: new_tolerance } } + let(:request) { patch :update, params: { id: goa.id, group_order_article: goa_params, foodcoop: 'f' } } let(:new_tolerance) { rand(2..10) } let!(:go) { create(:group_order, order: order, ordergroup: user.ordergroup) } let!(:goa) { create(:group_order_article, group_order: go, order_article: oa_1, quantity: 1, tolerance: 0) } - before { go.update_price!; user.ordergroup.update_stats! } - let(:goa_params) { { quantity: new_quantity, tolerance: new_tolerance } } - let(:request) { patch :update, params: { id: goa.id, group_order_article: goa_params, foodcoop: 'f' } } + before do + go.update_price! + user.ordergroup.update_stats! + end - context "happy flow" do - include_examples "group_order_articles create/update success" + context 'happy flow' do + include_examples 'group_order_articles create/update success' end - context "with invalid parameter values" do + context 'with invalid parameter values' do let(:goa_params) { { order_article_id: oa_1.id, quantity: -1, tolerance: new_tolerance } } - include_examples "group_order_articles endpoint failure", 422 + + include_examples 'group_order_articles endpoint failure', 422 end context 'with a closed order' do let(:order) { create(:order, article_count: 1, state: :finished) } - include_examples "group_order_articles endpoint failure", 404 + + include_examples 'group_order_articles endpoint failure', 404 end context 'without enough balance' do before { FoodsoftConfig[:minimum_balance] = 1000 } - include_examples "group_order_articles endpoint failure", 403 + + include_examples 'group_order_articles endpoint failure', 403 end context 'without enough apple points' do before { allow_any_instance_of(Ordergroup).to receive(:not_enough_apples?).and_return(true) } - include_examples "group_order_articles endpoint failure", 403 + + include_examples 'group_order_articles endpoint failure', 403 end end - describe "DELETE :destroy" do + describe 'DELETE :destroy' do let(:new_quantity) { 0 } + let(:request) { delete :destroy, params: { id: goa.id, foodcoop: 'f' } } let(:new_tolerance) { 0 } let!(:go) { create(:group_order, order: order, ordergroup: user.ordergroup) } let!(:goa) { create(:group_order_article, group_order: go, order_article: oa_1) } - before { go.update_price!; user.ordergroup.update_stats! } - let(:request) { delete :destroy, params: { id: goa.id, foodcoop: 'f' } } + before do + go.update_price! + user.ordergroup.update_stats! + end - shared_examples "group_order_articles destroy success" do - include_examples "group_order_articles endpoint success" + shared_examples 'group_order_articles destroy success' do + include_examples 'group_order_articles endpoint success' - it "does not return the group_order_article" do + it 'does not return the group_order_article' do expect(json_goa).to be_nil end - it "deletes the group_order_article" do + it 'deletes the group_order_article' do expect(GroupOrderArticle.where(id: goa.id)).to be_empty end end - context "happy flow" do - include_examples "group_order_articles destroy success" + context 'happy flow' do + include_examples 'group_order_articles destroy success' end context 'with a closed order' do let(:order) { create(:order, article_count: 1, state: :finished) } - include_examples "group_order_articles endpoint failure", 404 + + include_examples 'group_order_articles endpoint failure', 404 end context 'without enough balance' do before { FoodsoftConfig[:minimum_balance] = 1000 } - include_examples "group_order_articles destroy success" + + include_examples 'group_order_articles destroy success' end context 'without enough apple points' do before { allow_any_instance_of(Ordergroup).to receive(:not_enough_apples?).and_return(true) } - include_examples "group_order_articles destroy success" + + include_examples 'group_order_articles destroy success' end end end diff --git a/spec/api/v1/user/ordergroup_spec.rb b/spec/api/v1/user/ordergroup_spec.rb index 32d1053a..afc764f9 100644 --- a/spec/api/v1/user/ordergroup_spec.rb +++ b/spec/api/v1/user/ordergroup_spec.rb @@ -2,26 +2,26 @@ describe Api::V1::User::OrdergroupController, type: :controller do include ApiOAuth - let(:user) { create :user, :ordergroup } + let(:user) { create(:user, :ordergroup) } let(:api_scopes) { ['finance:user'] } - let(:ftc1) { create :financial_transaction_class } - let(:ftc2) { create :financial_transaction_class } - 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(:ftc1) { create(:financial_transaction_class) } + let(:ftc2) { create(:financial_transaction_class) } + 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) } - describe "GET :financial_overview" do + describe 'GET :financial_overview' do let(:order) { create(:order, article_count: 1) } + let(:json_financial_overview) { json_response['financial_overview'] } let(:oa_1) { order.order_articles.first } let!(:go) { create(:group_order, order: order, ordergroup: user.ordergroup) } let!(:goa) { create(:group_order_article, group_order: go, order_article: oa_1, quantity: 1, tolerance: 0) } - before { go.update_price!; user.ordergroup.update_stats! } - - let(:json_financial_overview) { json_response['financial_overview'] } before do + go.update_price! + user.ordergroup.update_stats! og = user.ordergroup og.add_financial_transaction!(-1, '-1', user, ftt1) og.add_financial_transaction!(2, '2', user, ftt1) @@ -36,12 +36,12 @@ og.add_financial_transaction!(300, '300', user, ftt3) end - it "returns correct values" do + it 'returns correct values' do get :financial_overview, params: { foodcoop: 'f' } 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 = json_financial_overview['financial_transaction_class_sums'].index_by { |x| x['id'] } ftcs1 = ftcs[ftc1.id] expect(ftcs1['name']).to eq ftc1.name diff --git a/spec/factories/article.rb b/spec/factories/article.rb index 83fd2f9d..c920968f 100644 --- a/spec/factories/article.rb +++ b/spec/factories/article.rb @@ -12,13 +12,14 @@ end after(:create) do |article, evaluator| - create_list(:article_version, evaluator.article_version_count, article: article, order_number: evaluator.order_number, unit_quantity: evaluator.unit_quantity) + create_list(:article_version, evaluator.article_version_count, article: article, + order_number: evaluator.order_number, unit_quantity: evaluator.unit_quantity) article.reload end end - factory :stock_article, class: StockArticle do + factory :stock_article, class: 'StockArticle' do supplier transient do diff --git a/spec/factories/article_version.rb b/spec/factories/article_version.rb index cd4b36be..df620e10 100644 --- a/spec/factories/article_version.rb +++ b/spec/factories/article_version.rb @@ -20,7 +20,8 @@ article_version.supplier_order_unit = nil article_version.save end - build_list(:article_unit_ratio, evaluator.article_unit_ratio_count, article_version: article_version) do |record, i| + build_list(:article_unit_ratio, evaluator.article_unit_ratio_count, + article_version: article_version) do |record, i| if !evaluator.unit_quantity.nil? && i == 0 record.quantity = evaluator.unit_quantity record.unit = 'XPP' diff --git a/spec/factories/doorkeeper.rb b/spec/factories/doorkeeper.rb index 95de4eb6..81cefd35 100644 --- a/spec/factories/doorkeeper.rb +++ b/spec/factories/doorkeeper.rb @@ -2,12 +2,12 @@ require 'doorkeeper' FactoryBot.define do - factory :oauth2_application, class: Doorkeeper::Application do + factory :oauth2_application, class: 'Doorkeeper::Application' do name { Faker::App.name } redirect_uri { 'https://example.com:1234/app' } end - factory :oauth2_access_token, class: Doorkeeper::AccessToken do + factory :oauth2_access_token, class: 'Doorkeeper::AccessToken' do application factory: :oauth2_application end end diff --git a/spec/factories/group_order.rb b/spec/factories/group_order.rb index f7e910df..d62172ea 100644 --- a/spec/factories/group_order.rb +++ b/spec/factories/group_order.rb @@ -4,6 +4,6 @@ # requires order factory :group_order do ordergroup { create(:user, groups: [FactoryBot.create(:ordergroup)]).ordergroup } - updated_by { create :user } + updated_by { create(:user) } end end diff --git a/spec/factories/invoice.rb b/spec/factories/invoice.rb index b3e65a17..3564d977 100644 --- a/spec/factories/invoice.rb +++ b/spec/factories/invoice.rb @@ -3,9 +3,9 @@ FactoryBot.define do factory :invoice do supplier - number { rand(1..99999) } + number { rand(1..99_999) } amount { rand(0.1..26.0).round(2) } - created_by { create :user } + created_by { create(:user) } after :create do |invoice| invoice.supplier.reload diff --git a/spec/factories/order.rb b/spec/factories/order.rb index 87febae2..970bd040 100644 --- a/spec/factories/order.rb +++ b/spec/factories/order.rb @@ -3,10 +3,10 @@ FactoryBot.define do factory :order do starts { Time.now } - supplier { create :supplier, article_count: (article_count.nil? ? true : article_count) } + supplier { create(:supplier, article_count: (article_count.nil? ? true : article_count)) } article_ids { supplier.articles.map(&:id) unless supplier.nil? } - created_by { create :user } - updated_by { create :user } + created_by { create(:user) } + updated_by { create(:user) } transient do article_count { true } diff --git a/spec/factories/supplier.rb b/spec/factories/supplier.rb index 21ea01c0..be082f77 100644 --- a/spec/factories/supplier.rb +++ b/spec/factories/supplier.rb @@ -10,7 +10,7 @@ article_count { 0 } end - before :create do |supplier, evaluator| + before :create do |supplier, _evaluator| next if supplier.supplier_category_id? supplier.supplier_category = create :supplier_category diff --git a/spec/factories/user.rb b/spec/factories/user.rb index eb12196f..fec68254 100644 --- a/spec/factories/user.rb +++ b/spec/factories/user.rb @@ -10,21 +10,21 @@ factory :admin do sequence(:nick) { |n| "admin#{n}" } first_name { 'Administrator' } - after :create do |user, evaluator| - create :workgroup, role_admin: true, user_ids: [user.id] + after :create do |user, _evaluator| + create(:workgroup, role_admin: true, user_ids: [user.id]) end end trait :ordergroup do - after :create do |user, evaluator| - create :ordergroup, user_ids: [user.id] + after :create do |user, _evaluator| + create(:ordergroup, user_ids: [user.id]) end end - [:ordergroup, :finance, :invoices, :article_meta, :suppliers, :pickups, :orders].each do |role| - trait "role_#{role}".to_sym do - after :create do |user, evaluator| - create :workgroup, "role_#{role}" => true, user_ids: [user.id] + %i[ordergroup finance invoices article_meta suppliers pickups orders].each do |role| + trait :"role_#{role}" do + after :create do |user, _evaluator| + create(:workgroup, "role_#{role}" => true, user_ids: [user.id]) end end end @@ -42,7 +42,9 @@ 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 + after :create do |group| + Ordergroup.find(group.id).update_stats! + end end end end diff --git a/spec/integration/articles_spec.rb b/spec/integration/articles_spec.rb index 88b3e869..c453c42a 100644 --- a/spec/integration/articles_spec.rb +++ b/spec/integration/articles_spec.rb @@ -1,12 +1,13 @@ require_relative '../spec_helper' -feature ArticlesController do - let(:user) { create :user, groups: [create(:workgroup, role_article_meta: true)] } - let (:supplier) { create :supplier } - let!(:article_category) { create :article_category } +describe ArticlesController do + let(:user) { create(:user, groups: [create(:workgroup, role_article_meta: true)]) } + let(:supplier) { create(:supplier) } + let!(:article_category) { create(:article_category) } + before { login user } - describe ':index', js: true do + describe ':index', :js do before { visit supplier_articles_path(supplier_id: supplier.id) } it 'can visit supplier articles path' do @@ -16,16 +17,16 @@ it 'can create a new article' do click_on I18n.t('articles.index.new') - expect(page).to have_selector('form#new_article') - article = FactoryBot.build :article, supplier: supplier, article_category: article_category + expect(page).to have_css('form#new_article') + article = FactoryBot.build(:article, supplier: supplier, article_category: article_category) within('#new_article') do - fill_in 'article_name', :with => article.name - fill_in 'article_unit', :with => article.unit - select article.article_category.name, :from => 'article_article_category_id' - fill_in 'article_version', :with => article.price - fill_in 'article_unit_quantity', :with => article.unit_quantity - fill_in 'article_tax', :with => article.tax - fill_in 'article_deposit', :with => article.deposit + fill_in 'article_name', with: article.name + fill_in 'article_unit', with: article.unit + select article.article_category.name, from: 'article_article_category_id' + fill_in 'article_version', with: article.price + fill_in 'article_unit_quantity', with: article.unit_quantity + 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 page.execute_script('$("form#new_article").submit();') @@ -37,6 +38,7 @@ describe ':upload' do let(:filename) { 'foodsoft_file_02.csv' } let(:file) { Rails.root.join("spec/fixtures/#{filename}") } + before do visit upload_supplier_articles_path(supplier_id: supplier.id) attach_file 'articles_file', file @@ -45,24 +47,26 @@ Dir.glob('spec/fixtures/foodsoft_file_01.*') do |test_file| describe "can import articles from #{test_file}" do let(:file) { Rails.root.join(test_file) } + it do find('input[type="submit"]').click - expect(find("tr:nth-child(1) #new_articles__note").value).to eq "bio ◎" - expect(find("tr:nth-child(2) #new_articles__name").value).to eq "Pijnboompitten" + expect(find('tr:nth-child(1) #new_articles__note').value).to eq 'bio ◎' + 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 end find('input[type="submit"]').click - expect(page).to have_content("Pijnboompitten") + expect(page).to have_content('Pijnboompitten') expect(supplier.articles.count).to eq 4 end end end - describe "can update existing article" do - let!(:article) { create :article, supplier: supplier, name: 'Foobar', order_number: 1, unit: '250 g' } + describe 'can update existing article' do + let!(:article) { create(:article, supplier: supplier, name: 'Foobar', order_number: 1, unit: '250 g') } + it do find('input[type="submit"]').click expect(find("#articles_#{article.id}_name").value).to eq 'Tomatoes' @@ -73,34 +77,36 @@ end end - describe "handles missing data" do + describe 'handles missing data' do it do find('input[type="submit"]').click # to overview find('input[type="submit"]').click # missing category, re-show form expect(find('tr.alert')).to be_present expect(supplier.articles.count).to eq 0 - all("tr select > option")[1].select_option + all('tr select > option')[1].select_option find('input[type="submit"]').click # now it should succeed expect(supplier.articles.count).to eq 1 end end - describe "can remove an existing article" do - let!(:article) { create :article, supplier: supplier, name: 'Foobar', order_number: 99999 } + describe 'can remove an existing article' do + let!(:article) { create(:article, supplier: supplier, name: 'Foobar', order_number: 99_999) } + it do check('articles_outlist_absent') find('input[type="submit"]').click expect(find("#outlisted_articles_#{article.id}", visible: :all)).to be_present - all("tr select > option")[1].select_option + all('tr select > option')[1].select_option find('input[type="submit"]').click expect(article.reload.deleted?).to be true end end - describe "can convert units when updating" do - let!(:article) { create :article, supplier: supplier, order_number: 1, unit: '250 g' } + describe 'can convert units when updating' do + let!(:article) { create(:article, supplier: supplier, order_number: 1, unit: '250 g') } + it do check('articles_convert_units') find('input[type="submit"]').click diff --git a/spec/integration/balancing_spec.rb b/spec/integration/balancing_spec.rb index 87a7757f..78ea97ad 100644 --- a/spec/integration/balancing_spec.rb +++ b/spec/integration/balancing_spec.rb @@ -1,17 +1,18 @@ 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(: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 - let(:go1) { create :group_order, order: order } - let(:go2) { create :group_order, order: order } +describe 'settling an order', :js 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(: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 + let(:go1) { create(:group_order, order: order) } + let(:go2) { create(:group_order, order: order) } let(:oa) { order.order_articles.find_by_article_id(article.id) } - let(:goa1) { create :group_order_article, group_order: go1, order_article: oa } - let(:goa2) { create :group_order_article, group_order: go2, order_article: oa } + let(:goa1) { create(:group_order_article, group_order: go1, order_article: oa) } + let(:goa2) { create(:group_order_article, group_order: go2, order_article: oa) } + before do goa1.update_quantities(3, 0) goa2.update_quantities(1, 0) @@ -19,6 +20,10 @@ order.finish!(admin) goa1.reload goa2.reload + login admin + visit new_finance_order_path(order_id: order.id) + visit new_finance_order_path(order_id: order.id) + login admin end it 'has correct order result' do @@ -28,25 +33,22 @@ expect(goa2.result).to eq(1) end - before { login admin } - before { visit new_finance_order_path(order_id: order.id) } - it 'has product ordered visible' do expect(page).to have_content(article.name) - expect(page).to have_selector("#order_article_#{oa.id}") + expect(page).to have_css("#order_article_#{oa.id}") end it 'shows order result' do click_link article.name - expect(page).to have_selector("#group_order_articles_#{oa.id}") + expect(page).to have_css("#group_order_articles_#{oa.id}") within("#group_order_articles_#{oa.id}") do # make sure these ordergroup names are in the list for this product expect(page).to have_content(go1.ordergroup_name) expect(page).to have_content(go2.ordergroup_name) # and that their order results match what we expect - expect(page).to have_selector("#r_#{goa1.id}") + expect(page).to have_css("#r_#{goa1.id}") expect(find("#r_#{goa1.id}").value.to_f).to eq(3) - expect(page).to have_selector("#r_#{goa2.id}") + expect(page).to have_css("#r_#{goa2.id}") expect(find("#r_#{goa2.id}").value.to_f).to eq(1) end end @@ -57,7 +59,7 @@ click_link I18n.t('ui.delete') end end - expect(page).to_not have_selector("#order_article_#{oa.id}") + expect(page).to have_no_css("#order_article_#{oa.id}") expect(OrderArticle.exists?(oa.id)).to be true oa.reload expect(oa.quantity).to eq(4) @@ -75,17 +77,17 @@ click_link I18n.t('ui.delete') end end - expect(page).to_not have_selector("#order_article_#{oa.id}") + expect(page).to have_no_css("#order_article_#{oa.id}") expect(OrderArticle.exists?(oa.id)).to be false end it 'keeps ordered quantities when GroupOrderArticle is deleted from resulting order' do click_link article.name - expect(page).to have_selector("#group_order_article_#{goa1.id}") + expect(page).to have_css("#group_order_article_#{goa1.id}") within("#group_order_article_#{goa1.id}") do click_link I18n.t('ui.delete') end - expect(page).to_not have_selector("#group_order_article_#{goa1.id}") + expect(page).to have_no_css("#group_order_article_#{goa1.id}") expect(OrderArticle.exists?(oa.id)).to be true expect(GroupOrderArticle.exists?(goa1.id)).to be true goa1.reload @@ -95,13 +97,13 @@ 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}") + expect(page).to have_css("#group_order_article_#{goa1.id}") within("#group_order_article_#{goa1.id}") do click_link I18n.t('ui.delete') end - expect(page).to_not have_selector("#group_order_article_#{goa1.id}") + expect(page).to have_no_css("#group_order_article_#{goa1.id}") expect(OrderArticle.exists?(oa.id)).to be true expect(GroupOrderArticle.exists?(goa1.id)).to be false end @@ -111,14 +113,14 @@ click_link I18n.t('ui.edit') end within("#edit_order_article_#{oa.id}") do - find('#order_article_units_to_order').set(0) + find_by_id('order_article_units_to_order').set(0) sleep 0.25 find('input[type="submit"]').click end - expect(page).to have_selector("#order_article_#{oa.id}") + expect(page).to have_css("#order_article_#{oa.id}") # make sure it still works after reloading visit new_finance_order_path(order_id: order.id) - expect(page).to have_selector("#order_article_#{oa.id}") + expect(page).to have_css("#order_article_#{oa.id}") expect(OrderArticle.exists?(oa.id)).to be true oa.reload expect(oa.units_to_order).to eq(0) @@ -130,19 +132,19 @@ within("#group_order_articles_#{oa.id}") do click_link I18n.t('finance.balancing.group_order_articles.add_group') end - expect(page).to have_selector('form#new_group_order_article') + expect(page).to have_css('form#new_group_order_article') within('#new_group_order_article') do - select user.ordergroup.name, :from => 'group_order_article_ordergroup_id' - find('#group_order_article_result').set(8) + select user.ordergroup.name, from: 'group_order_article_ordergroup_id' + find_by_id('group_order_article_result').set(8) sleep 0.25 find('input[type="submit"]').click end - expect(page).to_not have_selector('form#new_group_order_article') + expect(page).to have_no_css('form#new_group_order_article') expect(page).to have_content(user.ordergroup.name) goa = GroupOrderArticle.last - expect(goa).to_not be_nil + expect(goa).not_to be_nil expect(goa.result).to eq 8 - expect(page).to have_selector("#group_order_article_#{goa.id}") + expect(page).to have_css("#group_order_article_#{goa.id}") expect(find("#r_#{goa.id}").value.to_f).to eq 8 end @@ -151,7 +153,7 @@ within("#group_order_articles_#{oa.id}") do find("#r_#{goa1.id}").set(5).send_keys(:tab) # tab to blur and let js update end - expect(page).to have_selector('#summaryChangedWarning') # becomes visible after request is done + expect(page).to have_css('#summaryChangedWarning') # becomes visible after request is done expect(goa1.reload.result).to eq 5 expect(find("#group_order_articles_#{oa.id} tfoot td:nth-child(3)").text.to_f).to eq 6 end @@ -161,23 +163,23 @@ within("#group_order_article_#{goa1.id}") do 4.times { find('button[data-increment]').click } end - expect(page).to have_selector('#summaryChangedWarning') # becomes visible after request is done + expect(page).to have_css('#summaryChangedWarning') # becomes visible after request is done expect(goa1.reload.result).to eq 7 expect(find("#group_order_articles_#{oa.id} tfoot td:nth-child(3)").text.to_f).to eq 8 end it 'can add an article' do - new_article = create :article, supplier: supplier - expect(page).to_not have_content(new_article.name) + new_article = create(:article, supplier: supplier) + expect(page).to have_no_content(new_article.name) click_link I18n.t('finance.balancing.edit_results_by_articles.add_article') - expect(page).to have_selector('form#new_order_article') + expect(page).to have_css('form#new_order_article') within('#new_order_article') do - find('#order_article_article_id').select(new_article.name) + find_by_id('order_article_article_id').select(new_article.name) sleep 0.25 find('input[type="submit"]').click end - expect(page).to_not have_selector('form#new_order_article') + expect(page).to have_no_css('form#new_order_article') expect(page).to have_content(new_article.name) - expect(order.order_articles.where(article_id: new_article.id)).to_not be nil + expect(order.order_articles.where(article_id: new_article.id)).not_to be_nil end end diff --git a/spec/integration/config_spec.rb b/spec/integration/config_spec.rb index 91f376dd..d7d496a3 100644 --- a/spec/integration/config_spec.rb +++ b/spec/integration/config_spec.rb @@ -1,9 +1,9 @@ require_relative '../spec_helper' -feature 'admin/configs' do +describe 'admin/configs' do let(:name) { Faker::Lorem.words(number: rand(2..4)).join(' ') } let(:email) { Faker::Internet.email } - let(:admin) { create :admin } + let(:admin) { create(:admin) } before { login admin } @@ -51,13 +51,13 @@ def get_full_config 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/login_spec.rb b/spec/integration/login_spec.rb index 0195ec8c..e0e63ffd 100644 --- a/spec/integration/login_spec.rb +++ b/spec/integration/login_spec.rb @@ -1,18 +1,19 @@ require_relative '../spec_helper' -feature LoginController do - let(:user) { create :user } +describe LoginController do + let(:user) { create(:user) } describe 'forgot password' do before { visit forgot_password_path } + it 'is accessible' do - expect(page).to have_selector 'input[id=user_email]' + expect(page).to have_css 'input[id=user_email]' end it 'sends a reset email' do fill_in 'user_email', with: user.email find('input[type=submit]').click - expect(page).to have_selector '.alert-success' + expect(page).to have_css '.alert-success' email = ActionMailer::Base.deliveries.first expect(email.to).to eq [user.email] end @@ -21,18 +22,22 @@ describe 'and reset it' do let(:token) { user.reset_password_token } let(:newpass) { user.new_random_password } - before { user.request_password_reset! } - before { visit new_password_path(id: user.id, token: token) } + + before do + user.request_password_reset! + visit new_password_path(id: user.id, token: token) + end it 'is accessible' do - expect(page).to have_selector 'input[type=password]' + expect(page).to have_css 'input[type=password]' end describe 'with wrong token' do let(:token) { 'foobar' } + it 'is not accessible' do - expect(page).to have_selector '.alert-error' - expect(page).to_not have_selector 'input[type=password]' + expect(page).to have_css '.alert-error' + expect(page).to have_no_css 'input[type=password]' end end diff --git a/spec/integration/order_spec.rb b/spec/integration/order_spec.rb index dd768997..12e027a2 100644 --- a/spec/integration/order_spec.rb +++ b/spec/integration/order_spec.rb @@ -1,12 +1,12 @@ require_relative '../spec_helper' -feature Order, js: true do - 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 } +describe Order, :js do + 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) } let(:oa) { order.order_articles.find_by_article_id(article.id) } - let(:goa1) { create :group_order_article, group_order: go1, order_article: oa } + let(:goa1) { create(:group_order_article, group_order: go1, order_article: oa) } before { login admin } @@ -32,7 +32,7 @@ visit new_order_path(supplier_id: article.supplier_id) expect(page).to have_text I18n.t('orders.new.title') find('input[type="submit"]').click - expect(page).to have_selector('.alert-success') + expect(page).to have_css('.alert-success') expect(Order.count).to eq 1 expect(Order.first.supplier).to eq article.supplier end @@ -40,7 +40,7 @@ it 'can close an order' do setup_and_close_order expect(order).to be_finished - expect(page).not_to have_link I18n.t('orders.index.action_end') + expect(page).to have_no_link I18n.t('orders.index.action_end') expect(oa.units_to_order).to eq 1 end @@ -53,7 +53,7 @@ def setup_and_close_order accept_confirm do click_link_or_button I18n.t('orders.index.action_end') end - expect(page).to have_selector('.alert-success') + expect(page).to have_css('.alert-success') order.reload oa.reload end diff --git a/spec/integration/product_distribution_example_spec.rb b/spec/integration/product_distribution_example_spec.rb index e15642f1..b3e85def 100644 --- a/spec/integration/product_distribution_example_spec.rb +++ b/spec/integration/product_distribution_example_spec.rb @@ -1,12 +1,12 @@ require_relative '../spec_helper' -feature 'product distribution', js: true do - let(:ftt) { create :financial_transaction_type } - let(:admin) { create :admin } - let(:user_a) { create :user, groups: [create(:ordergroup)] } - let(:user_b) { create :user, groups: [create(:ordergroup)] } - let(:supplier) { create :supplier } - let(:article) { create :article, supplier: supplier, unit_quantity: 5 } +describe 'product distribution', :js do + let(:ftt) { create(:financial_transaction_type) } + let(:admin) { create(:admin) } + let(:user_a) { create(:user, groups: [create(:ordergroup)]) } + let(:user_b) { create(:user, groups: [create(:ordergroup)]) } + let(:supplier) { create(:supplier) } + let(:article) { create(:article, supplier: supplier, unit_quantity: 5) } let(:order) { create(:order, supplier: supplier, article_ids: [article.id]) } let(:oa) { order.order_articles.first } @@ -27,14 +27,14 @@ 2.times { find("[data-increase_quantity='#{oa.id}']").click } 3.times { find("[data-increase_tolerance='#{oa.id}']").click } find('input[type=submit]').click - expect(page).to have_selector('body') + expect(page).to have_css('body') # gruppe b bestellt 2(0) login user_b visit new_group_order_path(order_id: order.id) scrolldown 2.times { find("[data-increase_quantity='#{oa.id}']").click } find('input[type=submit]').click - expect(page).to have_selector('body') + expect(page).to have_css('body') # gruppe a faellt ein dass sie doch noch mehr braucht von x und aendert auf 4(1). login user_a visit edit_group_order_path(id: order.group_order(user_a.ordergroup).id, order_id: order.id) @@ -42,7 +42,7 @@ 2.times { find("[data-increase_quantity='#{oa.id}']").click } 2.times { find("[data-decrease_tolerance='#{oa.id}']").click } find('input[type=submit]').click - expect(page).to have_selector('body') + expect(page).to have_css('body') # die zuteilung order.finish!(admin) oa.reload @@ -50,10 +50,10 @@ 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 3b65107e..f1d1ec3e 100644 --- a/spec/integration/receive_spec.rb +++ b/spec/integration/receive_spec.rb @@ -1,15 +1,15 @@ require_relative '../spec_helper' -feature 'receiving an order', js: true do - 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 - let(:go1) { create :group_order, order: order } - let(:go2) { create :group_order, order: order } +describe 'receiving an order', :js do + 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 + let(:go1) { create(:group_order, order: order) } + let(:go2) { create(:group_order, order: order) } let(:oa) { order.order_articles.find_by_article_id(article.id) } - let(:goa1) { create :group_order_article, group_order: go1, order_article: oa } - let(:goa2) { create :group_order_article, group_order: go2, order_article: oa } + let(:goa1) { create(:group_order_article, group_order: go1, order_article: oa) } + let(:goa2) { create(:group_order_article, group_order: go2, order_article: oa) } # set quantities of group_order_articles def set_quantities(q1, q2) @@ -40,13 +40,13 @@ def check_quantities(units, q1, q2) 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}") + expect(page).to have_css("#order_article_#{oa.id}") end it 'has product not ordered invisible' do set_quantities [0, 0], [0, 0] visit receive_order_path(id: order.id) - expect(page).to_not have_selector("#order_article_#{oa.id}") + expect(page).to have_no_css("#order_article_#{oa.id}") end it 'is not received by default' do @@ -58,27 +58,27 @@ def check_quantities(units, q1, q2) it 'does not change anything when received is ordered' do 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 + fill_in "order_articles_#{oa.id}_units_received", with: oa.units_to_order find('input[type="submit"]').click - expect(page).to have_selector('body') + expect(page).to have_css('body') check_quantities 2, 2, 4 end it 'redistributes properly when received is more' do set_quantities [2, 0], [3, 2] visit receive_order_path(id: order.id) - fill_in "order_articles_#{oa.id}_units_received", :with => 3 + fill_in "order_articles_#{oa.id}_units_received", with: 3 find('input[type="submit"]').click - expect(page).to have_selector('body') + expect(page).to have_css('body') check_quantities 3, 2, 5 end it 'redistributes properly when received is less' do set_quantities [2, 0], [3, 2] visit receive_order_path(id: order.id) - fill_in "order_articles_#{oa.id}_units_received", :with => 1 + fill_in "order_articles_#{oa.id}_units_received", with: 1 find('input[type="submit"]').click - expect(page).to have_selector('body') + expect(page).to have_css('body') check_quantities 1, 2, 1 end @@ -96,7 +96,7 @@ def check_quantities(units, q1, q2) goa1.save! visit receive_order_path(id: order.id) find('input[type="submit"]').click - expect(page).to have_selector('body') + expect(page).to have_css('body') check_quantities 2, 3, 4 end end diff --git a/spec/integration/session_spec.rb b/spec/integration/session_spec.rb index 0838858d..bde3e622 100644 --- a/spec/integration/session_spec.rb +++ b/spec/integration/session_spec.rb @@ -1,27 +1,30 @@ require_relative '../spec_helper' -feature 'the session' do - let(:user) { create :user } +describe 'the session' do + let(:user) { create(:user) } describe 'login page' do it 'is accessible' do visit login_path - expect(page).to have_selector('input[type=password]') + expect(page).to have_css('input[type=password]') end + it 'logs me in' do login user - expect(page).to_not have_selector('.alert-error') + expect(page).to have_no_css('.alert-error') end + it 'does not log me in with wrong password' do login user.nick, 'XX' + user.password - expect(page).to have_selector('.alert-error') + expect(page).to have_css('.alert-error') end + it 'can log me in using an email address' do visit login_path - fill_in 'nick', :with => user.email - fill_in 'password', :with => user.password + fill_in 'nick', with: user.email + fill_in 'password', with: user.password find('input[type=submit]').click - expect(page).to_not have_selector('.alert-error') + expect(page).to have_no_css('.alert-error') end end end diff --git a/spec/integration/supplier_spec.rb b/spec/integration/supplier_spec.rb index cfd74e87..9710e800 100644 --- a/spec/integration/supplier_spec.rb +++ b/spec/integration/supplier_spec.rb @@ -1,21 +1,22 @@ require_relative '../spec_helper' -feature 'supplier' do - let(:supplier) { create :supplier } +describe '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 - create :supplier_category + create(:supplier_category) visit suppliers_path click_on I18n.t('suppliers.index.action_new') - supplier = build :supplier + supplier = build(:supplier) within('#new_supplier') do - fill_in 'supplier_name', :with => supplier.name - fill_in 'supplier_address', :with => supplier.address - fill_in 'supplier_phone', :with => supplier.phone + fill_in 'supplier_name', with: supplier.name + fill_in 'supplier_address', with: supplier.address + fill_in 'supplier_phone', with: supplier.phone find('input[type="submit"]').click end expect(page).to have_content(supplier.name) diff --git a/spec/lib/bank_account_information_importer_spec.rb b/spec/lib/bank_account_information_importer_spec.rb index a98441d2..928acf7f 100644 --- a/spec/lib/bank_account_information_importer_spec.rb +++ b/spec/lib/bank_account_information_importer_spec.rb @@ -1,14 +1,13 @@ require_relative '../spec_helper' describe BankTransaction do - let(:bank_account) { create :bank_account } + let(:bank_account) { create(:bank_account) } it 'empty content' do - content = <<-JSON - JSON + content = '' importer = BankAccountInformationImporter.new(bank_account) - expect(importer.import!(content)).to be(nil) + expect(importer.import!(content)).to be_nil end it 'invalid JSON' do @@ -189,7 +188,7 @@ expect(bt.date).to eq('2019-02-13'.to_date) expect(bt.text).to eq('Deutsche Bundesbahn') expect(bt.iban).to eq('DE72957284895783674747') - expect(bt.reference).to eq("743574386368 Muenchen-Hamburg 27.03.2019") + expect(bt.reference).to eq('743574386368 Muenchen-Hamburg 27.03.2019') expect(bt.receipt).to eq('Lastschrift') end @@ -241,7 +240,7 @@ expect(bt.amount).to eq(-238.68) expect(bt.date).to eq('2019-02-13'.to_date) expect(bt.text).to eq('Hammersmith Inc.') - expect(bt.iban).to be(nil) + expect(bt.iban).to be_nil expect(bt.reference).to eq('Martin Schöneicher, Inv# 123453423, Thx') expect(bt.receipt).to eq('Auslands-Überweisung') end @@ -277,8 +276,8 @@ expect(bt.amount).to eq(-12.3) expect(bt.date).to eq('2019-02-14'.to_date) expect(bt.text).to eq('superbank AG') - expect(bt.iban).to be(nil) - expect(bt.reference).to eq("Überweisung US, Wechselspesen u Provision") + expect(bt.iban).to be_nil + expect(bt.reference).to eq('Überweisung US, Wechselspesen u Provision') expect(bt.receipt).to eq('Spesen/Gebühren') end @@ -385,28 +384,28 @@ expect(bank_account.last_transaction_date).to eq('2020-01-01'.to_date) expect(bank_account.balance).to eq(22) - bt1 = bank_account.bank_transactions.find_by_external_id("T1") + bt1 = bank_account.bank_transactions.find_by_external_id('T1') expect(bt1.amount).to eq(11) expect(bt1.date).to eq('2020-01-01'.to_date) expect(bt1.text).to eq('DN1') expect(bt1.iban).to eq('DE72957284895783674747') - expect(bt1.reference).to be(nil) + expect(bt1.reference).to be_nil expect(bt1.receipt).to eq('AI1') - bt2 = bank_account.bank_transactions.find_by_external_id("T2") + bt2 = bank_account.bank_transactions.find_by_external_id('T2') expect(bt2.amount).to eq(-22) expect(bt2.date).to eq('2010-02-01'.to_date) expect(bt2.text).to eq('CN2') expect(bt2.iban).to eq('CH9300762011623852957') expect(bt2.reference).to eq('RI2') - expect(bt2.receipt).to be(nil) + expect(bt2.receipt).to be_nil - bt3 = bank_account.bank_transactions.find_by_external_id("T3") + bt3 = bank_account.bank_transactions.find_by_external_id('T3') expect(bt3.amount).to eq(33) expect(bt3.date).to eq('2000-03-01'.to_date) expect(bt3.text).to eq('DN3') - expect(bt3.iban).to be(nil) - expect(bt3.reference).to be(nil) - expect(bt3.receipt).to be(nil) + expect(bt3.iban).to be_nil + expect(bt3.reference).to be_nil + expect(bt3.receipt).to be_nil end end diff --git a/spec/lib/bank_transaction_reference_spec.rb b/spec/lib/bank_transaction_reference_spec.rb index 6d5a5490..ece0e614 100644 --- a/spec/lib/bank_transaction_reference_spec.rb +++ b/spec/lib/bank_transaction_reference_spec.rb @@ -2,94 +2,96 @@ describe BankTransactionReference do it 'returns nil for empty input' do - expect(BankTransactionReference.parse('')).to be nil + expect(BankTransactionReference.parse('')).to be_nil end it 'returns nil for invalid string' do - expect(BankTransactionReference.parse('invalid')).to be nil + expect(BankTransactionReference.parse('invalid')).to be_nil end it 'returns nil for FS1A' do - expect(BankTransactionReference.parse('FS1A')).to be nil + expect(BankTransactionReference.parse('FS1A')).to be_nil end it 'returns nil for FS1.1A' do - expect(BankTransactionReference.parse('FS1.1A')).to be nil + expect(BankTransactionReference.parse('FS1.1A')).to be_nil end it 'returns nil for xFS1A1' do - expect(BankTransactionReference.parse('xFS1A1')).to be nil + expect(BankTransactionReference.parse('xFS1A1')).to be_nil end it 'returns nil for .FS1A1' do - expect(BankTransactionReference.parse('.FS1A1')).to be nil + expect(BankTransactionReference.parse('.FS1A1')).to be_nil end it 'returns nil for FS1A1x' do - expect(BankTransactionReference.parse('FS1A1x')).to be nil + expect(BankTransactionReference.parse('FS1A1x')).to be_nil end it 'returns nil for FS1A1.' do - expect(BankTransactionReference.parse('FS1A1.')).to be nil + expect(BankTransactionReference.parse('FS1A1.')).to be_nil end it 'returns correct value for FS1A1' do - expect(BankTransactionReference.parse('FS1A1')).to match({ group: 1, parts: { "A" => 1 } }) + expect(BankTransactionReference.parse('FS1A1')).to match({ group: 1, parts: { 'A' => 1 } }) end it 'returns correct value for FS1.2A3' do - expect(BankTransactionReference.parse('FS1.2A3')).to match({ group: 1, user: 2, parts: { "A" => 3 } }) + expect(BankTransactionReference.parse('FS1.2A3')).to match({ group: 1, user: 2, parts: { 'A' => 3 } }) end it 'returns correct value for FS1A2B3C4' do - expect(BankTransactionReference.parse('FS1A2B3C4')).to match({ group: 1, parts: { "A" => 2, "B" => 3, "C" => 4 } }) + expect(BankTransactionReference.parse('FS1A2B3C4')).to match({ group: 1, parts: { 'A' => 2, 'B' => 3, 'C' => 4 } }) end it 'returns correct value for FS1A2B3A4' do - expect(BankTransactionReference.parse('FS1A2B3A4')).to match({ group: 1, parts: { "A" => 6, "B" => 3 } }) + expect(BankTransactionReference.parse('FS1A2B3A4')).to match({ group: 1, parts: { 'A' => 6, 'B' => 3 } }) end it 'returns correct value for FS1A2.34B5.67C8.90' do - expect(BankTransactionReference.parse('FS1A2.34B5.67C8.90')).to match({ group: 1, parts: { "A" => 2.34, "B" => 5.67, "C" => 8.90 } }) + expect(BankTransactionReference.parse('FS1A2.34B5.67C8.90')).to match({ group: 1, + parts: { 'A' => 2.34, 'B' => 5.67, 'C' => 8.90 } }) end it 'returns correct value for FS123A456 with comma-separated prefix' do - expect(BankTransactionReference.parse('x,FS123A456')).to match({ group: 123, parts: { "A" => 456 } }) + expect(BankTransactionReference.parse('x,FS123A456')).to match({ group: 123, parts: { 'A' => 456 } }) end it 'returns correct value for FS123A456 with minus-separated prefix' do - expect(BankTransactionReference.parse('x-FS123A456')).to match({ group: 123, parts: { "A" => 456 } }) + expect(BankTransactionReference.parse('x-FS123A456')).to match({ group: 123, parts: { 'A' => 456 } }) end it 'returns correct value for FS123A456 with semicolon-separated prefix' do - expect(BankTransactionReference.parse('x;FS123A456')).to match({ group: 123, parts: { "A" => 456 } }) + expect(BankTransactionReference.parse('x;FS123A456')).to match({ group: 123, parts: { 'A' => 456 } }) end it 'returns correct value for FS123A456 with space-separated prefix' do - expect(BankTransactionReference.parse('x FS123A456')).to match({ group: 123, parts: { "A" => 456 } }) + expect(BankTransactionReference.parse('x FS123A456')).to match({ group: 123, parts: { 'A' => 456 } }) end it 'returns correct value for FS234A567 with comma-separated suffix' do - expect(BankTransactionReference.parse('FS234A567,x')).to match({ group: 234, parts: { "A" => 567 } }) + expect(BankTransactionReference.parse('FS234A567,x')).to match({ group: 234, parts: { 'A' => 567 } }) end it 'returns correct value for FS234A567 with minus-separated suffix' do - expect(BankTransactionReference.parse('FS234A567-x')).to match({ group: 234, parts: { "A" => 567 } }) + expect(BankTransactionReference.parse('FS234A567-x')).to match({ group: 234, parts: { 'A' => 567 } }) end it 'returns correct value for FS234A567 with space-separated suffix' do - expect(BankTransactionReference.parse('FS234A567 x')).to match({ group: 234, parts: { "A" => 567 } }) + expect(BankTransactionReference.parse('FS234A567 x')).to match({ group: 234, parts: { 'A' => 567 } }) end it 'returns correct value for FS234A567 with semicolon-separated suffix' do - expect(BankTransactionReference.parse('FS234A567;x')).to match({ group: 234, parts: { "A" => 567 } }) + expect(BankTransactionReference.parse('FS234A567;x')).to match({ group: 234, parts: { 'A' => 567 } }) end it 'returns correct value for FS234A567 with minus-separated suffix' do - expect(BankTransactionReference.parse('FS234A567-x')).to match({ group: 234, parts: { "A" => 567 } }) + expect(BankTransactionReference.parse('FS234A567-x')).to match({ group: 234, parts: { 'A' => 567 } }) end 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 } }) + 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 be058f38..a6aa0539 100644 --- a/spec/lib/foodsoft_config_spec.rb +++ b/spec/lib/foodsoft_config_spec.rb @@ -9,7 +9,7 @@ end it 'returns an empty default value' do - expect(FoodsoftConfig[:protected][:LIUhniuyGNKUQTWfbiOQIWYexngo78hqexul]).to be nil + expect(FoodsoftConfig[:protected][:LIUhniuyGNKUQTWfbiOQIWYexngo78hqexul]).to be_nil end it 'returns a configuration value' do diff --git a/spec/lib/foodsoft_mail_receiver_spec.rb b/spec/lib/foodsoft_mail_receiver_spec.rb index 59eab47b..47ddb57d 100644 --- a/spec/lib/foodsoft_mail_receiver_spec.rb +++ b/spec/lib/foodsoft_mail_receiver_spec.rb @@ -6,72 +6,64 @@ @server.start end + # TODO: Reanable this test. + # It raised "Mysql2::Error: Lock wait timeout exceeded" at time of writing. + # it 'accepts bounce mails via SMTP' do + # MailDeliveryStatus.delete_all + # + # Net::SMTP.start(@server.host, @server.port) do |smtp| + # address = "#{FoodsoftConfig[:default_scope]}.bounce+user=example.com" + # smtp.send_message 'report', 'from@example.com', address + # end + # + # mds = MailDeliveryStatus.last + # expect(mds.email).to eq 'user@example.com' + # expect(mds.attachment_mime).to eq 'message/rfc822' + # expect(mds.attachment_data).to include 'report' + # end + + after :all do + @server.shutdown + end + it 'does not accept empty addresses' do - begin - FoodsoftMailReceiver.received('', 'body') - rescue => error - expect(error.to_s).to include 'missing' - end + FoodsoftMailReceiver.received('', 'body') + rescue StandardError => e + expect(e.to_s).to include 'missing' end it 'does not accept invalid addresses' do - begin - FoodsoftMailReceiver.received('invalid', 'body') - rescue => error - expect(error.to_s).to include 'has an invalid format' - end + FoodsoftMailReceiver.received('invalid', 'body') + rescue StandardError => e + expect(e.to_s).to include 'has an invalid format' end it 'does not accept invalid scope in address' do - begin - FoodsoftMailReceiver.received('invalid.invalid', 'body') - rescue => error - expect(error.to_s).to include 'could not be found' - end + FoodsoftMailReceiver.received('invalid.invalid', 'body') + rescue StandardError => e + expect(e.to_s).to include 'could not be found' end it 'does not accept address without handler' do - begin - address = "#{FoodsoftConfig[:default_scope]}.invalid" - FoodsoftMailReceiver.received(address, 'body') - rescue => error - expect(error.to_s).to include 'invalid format for recipient' - end + address = "#{FoodsoftConfig[:default_scope]}.invalid" + FoodsoftMailReceiver.received(address, 'body') + rescue StandardError => e + expect(e.to_s).to include 'invalid format for recipient' end it 'does not accept invalid addresses via SMTP' do - expect { + expect do Net::SMTP.start(@server.hosts.first, @server.ports.first) do |smtp| smtp.send_message 'body', 'from@example.com', 'invalid' end - }.to raise_error(Net::SMTPFatalError) + end.to raise_error(Net::SMTPFatalError) end it 'does not accept invalid addresses via SMTP' do - expect { + expect do Net::SMTP.start(@server.hosts.first, @server.ports.first) do |smtp| smtp.send_message 'body', 'from@example.com', 'invalid' end - }.to raise_error(Net::SMTPFatalError) - end - - # TODO: Reanable this test. - # It raised "Mysql2::Error: Lock wait timeout exceeded" at time of writing. - # it 'accepts bounce mails via SMTP' do - # MailDeliveryStatus.delete_all - # - # Net::SMTP.start(@server.host, @server.port) do |smtp| - # address = "#{FoodsoftConfig[:default_scope]}.bounce+user=example.com" - # smtp.send_message 'report', 'from@example.com', address - # end - # - # mds = MailDeliveryStatus.last - # expect(mds.email).to eq 'user@example.com' - # expect(mds.attachment_mime).to eq 'message/rfc822' - # expect(mds.attachment_data).to include 'report' - # end - - after :all do - @server.shutdown + end.to raise_error(Net::SMTPFatalError) end end diff --git a/spec/lib/token_verifier_spec.rb b/spec/lib/token_verifier_spec.rb index a5c81d4f..3097e888 100644 --- a/spec/lib/token_verifier_spec.rb +++ b/spec/lib/token_verifier_spec.rb @@ -1,17 +1,17 @@ require_relative '../spec_helper' describe TokenVerifier do - let (:prefix) { 'xyz' } - let (:v) { TokenVerifier.new(prefix) } - let (:msg) { v.generate } + let(:prefix) { 'xyz' } + let(:v) { TokenVerifier.new(prefix) } + let(:msg) { v.generate } it 'validates' do - expect { v.verify(msg) }.to_not raise_error + expect { v.verify(msg) }.not_to raise_error end it 'validates when recreated' do v2 = TokenVerifier.new(prefix) - expect { v2.verify(msg) }.to_not raise_error + expect { v2.verify(msg) }.not_to raise_error end it 'does not validate with a different prefix' do @@ -32,7 +32,9 @@ end it 'does not validate a random string' do - expect { v.verify(Faker::Lorem.characters(number: 100)) }.to raise_error(ActiveSupport::MessageVerifier::InvalidSignature) + expect do + v.verify(Faker::Lorem.characters(number: 100)) + end.to raise_error(ActiveSupport::MessageVerifier::InvalidSignature) end it 'returns the message' do diff --git a/spec/models/article_spec.rb b/spec/models/article_spec.rb index b0c50e7c..51bd6140 100644 --- a/spec/models/article_spec.rb +++ b/spec/models/article_spec.rb @@ -1,13 +1,14 @@ require_relative '../spec_helper' describe Article do - let(:supplier) { create :supplier } - let(:article) { create :article, supplier: supplier } - let(:user) { create :user, groups: [create(:ordergroup)] } + let(:supplier) { create(:supplier) } + let(:article) { create(:article, supplier: supplier) } + let(:user) { create(:user, groups: [create(:ordergroup)]) } it 'has a unique name' do article_version_copy = article.latest_article_version.dup - article2 = FactoryBot.build :article, name: article.name, supplier_id: article.supplier_id, latest_article_version: article_version_copy + article2 = FactoryBot.build(:article, name: article.name, supplier_id: article.supplier_id, + latest_article_version: article_version_copy) article2.latest_article_version.article = article2 expect(article2.latest_article_version).to be_invalid end @@ -44,7 +45,7 @@ end it 'keeps an article history for articles referenced by closed orders' do - order = create :order, created_by: user, starts: Date.yesterday, ends: 1.hour.ago, end_action: :auto_close + order = create(:order, created_by: user, starts: Date.yesterday, ends: 1.hour.ago, end_action: :auto_close) order.close!(user) article = order.order_articles.first.article_version.article @@ -62,7 +63,7 @@ end it 'is knows its open order' do - order = create :order, supplier: supplier, article_ids: [article.id] + order = create(:order, supplier: supplier, article_ids: [article.id]) expect(article.in_open_order).to eq(order) end @@ -70,9 +71,9 @@ expect(article.shared_article).to be_nil end - describe 'connected to a shared database', :type => :feature do - let(:shared_article) { create :shared_article } - let(:supplier) { create :supplier, shared_supplier_id: shared_article.supplier_id } + describe 'connected to a shared database', type: :feature do + let(:shared_article) { create(:shared_article) } + let(:supplier) { create(:supplier, shared_supplier_id: shared_article.supplier_id) } let(:article) do article = create(:article, supplier: supplier) article_version = article.latest_article_version @@ -82,21 +83,21 @@ end it 'can be found in the shared database' do - expect(article.shared_article).to_not be_nil + expect(article.shared_article).not_to be_nil end it 'can find updates' do changed = article.shared_article_changed? - expect(changed).to_not be_falsey + expect(changed).not_to be_falsey expect(changed.length).to be > 1 end it 'can be synchronised' do - # TODO move article sync from supplier to article + # TODO: move article sync from supplier to article article # need to reference for it to exist when syncing sync_data = supplier.sync_all updated_article = sync_data[0].select { |s| s[0].id == article.id }.first[0] - version_attributes = updated_article.latest_article_version.attributes.reject { |k, v| k == 'id' } + version_attributes = updated_article.latest_article_version.attributes.reject { |k, _v| k == 'id' } version_attributes[:id] = article.latest_article_version.id article.update_attributes(latest_article_version_attributes: version_attributes) expect(article.name).to eq(shared_article.name) @@ -128,11 +129,12 @@ article_version.unit = '200g' article.article_versions << article_version article.reload - # TODO get sync functionality in article + # TODO: get sync functionality in article sync_data = supplier.sync_all updated_article = sync_data[0].select { |s| s[0].id == article.id }.first[0] - version_attributes = updated_article.latest_article_version.attributes.reject { |k, v| k == 'id' } - version_attributes[:article_unit_ratios_attributes] = updated_article.latest_article_version.article_unit_ratios.map(&:attributes) + version_attributes = updated_article.latest_article_version.attributes.reject { |k, _v| k == 'id' } + version_attributes[:article_unit_ratios_attributes] = + updated_article.latest_article_version.article_unit_ratios.map(&:attributes) version_attributes[:id] = article.latest_article_version.id article.update_attributes(latest_article_version_attributes: version_attributes) @@ -142,7 +144,7 @@ end it 'does not synchronise when it has no order number' do - article.update_attributes :order_number => nil + article.update_attributes order_number: nil expect(supplier.sync_all).to eq [[], [], []] end end diff --git a/spec/models/bank_transaction_spec.rb b/spec/models/bank_transaction_spec.rb index 984d39ae..14172676 100644 --- a/spec/models/bank_transaction_spec.rb +++ b/spec/models/bank_transaction_spec.rb @@ -1,24 +1,32 @@ require_relative '../spec_helper' describe BankTransaction do - let(:bank_account) { create :bank_account } - let(:ordergroup) { create :ordergroup } - let(:supplier) { create :supplier, iban: Faker::Bank.iban } - let!(:user) { create :user, groups: [ordergroup] } - let!(:ftt_a) { create :financial_transaction_type, name_short: 'A' } - let!(:ftt_b) { create :financial_transaction_type, name_short: 'B' } + let(:bank_account) { create(:bank_account) } + let(:ordergroup) { create(:ordergroup) } + let(:supplier) { create(:supplier, iban: Faker::Bank.iban) } + let!(:user) { create(:user, groups: [ordergroup]) } + let!(:ftt_a) { create(:financial_transaction_type, name_short: 'A') } + let!(:ftt_b) { create(:financial_transaction_type, name_short: 'B') } describe 'supplier' do - let!(:invoice1) { create :invoice, supplier: supplier, number: '11', amount: 10 } - let!(:invoice2) { create :invoice, supplier: supplier, number: '22', amount: 20 } - let!(:invoice3) { create :invoice, supplier: supplier, number: '33', amount: 30 } - let!(:invoice4) { create :invoice, supplier: supplier, number: '44', amount: 40 } - let!(:invoice5) { create :invoice, supplier: supplier, number: '55', amount: 50 } - - let!(:bank_transaction1) { create :bank_transaction, bank_account: bank_account, iban: supplier.iban, reference: '11', amount: 10 } - let!(:bank_transaction2) { create :bank_transaction, bank_account: bank_account, iban: supplier.iban, reference: '22', amount: -20 } - let!(:bank_transaction3) { create :bank_transaction, bank_account: bank_account, iban: supplier.iban, reference: '33,44', amount: -70 } - let!(:bank_transaction4) { create :bank_transaction, bank_account: bank_account, iban: supplier.iban, text: '55', amount: -50 } + let!(:invoice1) { create(:invoice, supplier: supplier, number: '11', amount: 10) } + let!(:invoice2) { create(:invoice, supplier: supplier, number: '22', amount: 20) } + let!(:invoice3) { create(:invoice, supplier: supplier, number: '33', amount: 30) } + let!(:invoice4) { create(:invoice, supplier: supplier, number: '44', amount: 40) } + let!(:invoice5) { create(:invoice, supplier: supplier, number: '55', amount: 50) } + + let!(:bank_transaction1) do + create(:bank_transaction, bank_account: bank_account, iban: supplier.iban, reference: '11', amount: 10) + end + let!(:bank_transaction2) do + create(:bank_transaction, bank_account: bank_account, iban: supplier.iban, reference: '22', amount: -20) + end + let!(:bank_transaction3) do + create(:bank_transaction, bank_account: bank_account, iban: supplier.iban, reference: '33,44', amount: -70) + end + let!(:bank_transaction4) do + create(:bank_transaction, bank_account: bank_account, iban: supplier.iban, text: '55', amount: -50) + end it 'ignores invoices with invalid amount' do expect(bank_transaction1.assign_to_invoice).to be false @@ -49,17 +57,29 @@ end describe 'ordergroup' do - let!(:bank_transaction1) { create :bank_transaction, bank_account: bank_account, reference: "invalid", amount: 10 } - let!(:bank_transaction2) { create :bank_transaction, bank_account: bank_account, reference: "FS99A10", amount: 10 } - let!(:bank_transaction3) { create :bank_transaction, bank_account: bank_account, reference: "FS#{ordergroup.id}.99A10", amount: 10 } - let!(:bank_transaction4) { create :bank_transaction, bank_account: bank_account, reference: "FS#{ordergroup.id}A10", amount: 99 } - let!(:bank_transaction5) { create :bank_transaction, bank_account: bank_account, reference: "FS#{ordergroup.id}A10", amount: 10 } - let!(:bank_transaction6) { create :bank_transaction, bank_account: bank_account, reference: "FS#{ordergroup.id}A10B20", amount: 30 } - let!(:bank_transaction7) { create :bank_transaction, bank_account: bank_account, reference: "FS#{ordergroup.id}.#{user.id}A10", amount: 10 } - let!(:bank_transaction8) { create :bank_transaction, bank_account: bank_account, reference: "FS#{ordergroup.id}X10", amount: 10 } + let!(:bank_transaction1) { create(:bank_transaction, bank_account: bank_account, reference: 'invalid', amount: 10) } + let!(:bank_transaction2) { create(:bank_transaction, bank_account: bank_account, reference: 'FS99A10', amount: 10) } + let!(:bank_transaction3) do + create(:bank_transaction, bank_account: bank_account, reference: "FS#{ordergroup.id}.99A10", amount: 10) + end + let!(:bank_transaction4) do + create(:bank_transaction, bank_account: bank_account, reference: "FS#{ordergroup.id}A10", amount: 99) + end + let!(:bank_transaction5) do + create(:bank_transaction, bank_account: bank_account, reference: "FS#{ordergroup.id}A10", amount: 10) + end + let!(:bank_transaction6) do + create(:bank_transaction, bank_account: bank_account, reference: "FS#{ordergroup.id}A10B20", amount: 30) + end + let!(:bank_transaction7) do + create(:bank_transaction, bank_account: bank_account, reference: "FS#{ordergroup.id}.#{user.id}A10", amount: 10) + end + let!(:bank_transaction8) do + create(:bank_transaction, bank_account: bank_account, reference: "FS#{ordergroup.id}X10", amount: 10) + end it 'ignores transaction with invalid reference' do - expect(bank_transaction1.assign_to_ordergroup).to be nil + expect(bank_transaction1.assign_to_ordergroup).to be_nil end it 'ignores transaction with invalid ordergroup' do diff --git a/spec/models/group_order_article_spec.rb b/spec/models/group_order_article_spec.rb index 91e94680..b777eb89 100644 --- a/spec/models/group_order_article_spec.rb +++ b/spec/models/group_order_article_spec.rb @@ -1,20 +1,31 @@ require_relative '../spec_helper' describe GroupOrderArticle do - let(:user) { create :user, groups: [create(:ordergroup)] } + let(:user) { create(:user, groups: [create(:ordergroup)]) } let(:order) { create(:order) } - let(:go) { create :group_order, order: order, ordergroup: user.ordergroup } - let(:goa) { create :group_order_article, group_order: go, order_article: order.order_articles.first } + let(:go) { create(:group_order, order: order, ordergroup: user.ordergroup) } + let(:goa) { create(:group_order_article, group_order: go, order_article: order.order_articles.first) } - it 'has zero quantity by default' do expect(goa.quantity).to eq(0) end - it 'has zero tolerance by default' do expect(goa.tolerance).to eq(0) end - it 'has zero result by default' do expect(goa.result).to eq(0) end - it 'has zero total price by default' do expect(goa.total_price).to eq(0) end + it 'has zero quantity by default' do + expect(goa.quantity).to eq(0) + end + + it 'has zero tolerance by default' do + expect(goa.tolerance).to eq(0) + end + + it 'has zero result by default' do + expect(goa.result).to eq(0) + end + + it 'has zero total price by default' do + expect(goa.total_price).to eq(0) + end describe do - let(:article) { create :article, supplier: order.supplier, unit_quantity: 1 } - let(:oa) { order.order_articles.create(:article => article) } - let(:goa) { create :group_order_article, group_order: go, order_article: oa } + let(:article) { create(:article, supplier: order.supplier, unit_quantity: 1) } + let(:oa) { order.order_articles.create(article: article) } + let(:goa) { create(:group_order_article, group_order: go, order_article: oa) } it 'can be ordered by piece' do goa.update_quantities(1, 0) @@ -23,7 +34,8 @@ end it 'can be ordered in larger amounts' do - quantity, tolerance = rand(13..99), rand(0..99) + quantity = rand(13..99) + tolerance = rand(0..99) goa.update_quantities(quantity, tolerance) expect(goa.quantity).to eq(quantity) expect(goa.tolerance).to eq(tolerance) @@ -43,10 +55,10 @@ end describe 'distribution strategy' do - let(:article) { create :article, supplier: order.supplier, unit_quantity: 1 } - let(:oa) { order.order_articles.create(:article => article) } - let(:goa) { create :group_order_article, group_order: go, order_article: oa } - let!(:goaq) { create :group_order_article_quantity, group_order_article: goa, quantity: 4 } + let(:article) { create(:article, supplier: order.supplier, unit_quantity: 1) } + let(:oa) { order.order_articles.create(article: article) } + let(:goa) { create(:group_order_article, group_order: go, order_article: oa) } + let!(:goaq) { create(:group_order_article_quantity, group_order_article: goa, quantity: 4) } it 'can calculate the result for the distribution strategy "first order first serve"' do res = goa.calculate_result(2) diff --git a/spec/models/group_order_spec.rb b/spec/models/group_order_spec.rb index a2b8a2c5..648fa100 100644 --- a/spec/models/group_order_spec.rb +++ b/spec/models/group_order_spec.rb @@ -1,8 +1,8 @@ require_relative '../spec_helper' describe GroupOrder do - let(:user) { create :user, groups: [create(:ordergroup)] } - let(:order) { create :order } + let(:user) { create(:user, groups: [create(:ordergroup)]) } + let(:order) { create(:order) } # the following two tests are currently disabled - https://github.com/foodcoops/foodsoft/issues/158 @@ -15,7 +15,7 @@ # end describe do - let(:go) { create :group_order, order: order, ordergroup: user.ordergroup } + let(:go) { create(:group_order, order: order, ordergroup: user.ordergroup) } it 'has zero price initially' do expect(go.price).to eq(0) diff --git a/spec/models/order_article_spec.rb b/spec/models/order_article_spec.rb index 568283d6..acade0ee 100644 --- a/spec/models/order_article_spec.rb +++ b/spec/models/order_article_spec.rb @@ -1,14 +1,14 @@ require 'spec_helper' describe OrderArticle do - let(:order) { create :order, article_count: 1 } + let(:order) { create(:order, article_count: 1) } let(:oa) { order.order_articles.first } it 'is not ordered by default' do expect(OrderArticle.ordered.count).to eq 0 end - [:units_to_order, :units_billed, :units_received].each do |units| + %i[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 @@ -46,15 +46,15 @@ end describe 'redistribution' do - 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 } - let(:go2) { create :group_order, order: order } - let(:go3) { create :group_order, order: order } - let(:goa1) { create :group_order_article, group_order: go1, order_article: oa } - let(:goa2) { create :group_order_article, group_order: go2, order_article: oa } - let(:goa3) { create :group_order_article, group_order: go3, order_article: oa } + 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) } + let(:go2) { create(:group_order, order: order) } + let(:go3) { create(:group_order, order: order) } + let(:goa1) { create(:group_order_article, group_order: go1, order_article: oa) } + let(:goa2) { create(:group_order_article, group_order: go2, order_article: oa) } + let(:goa3) { create(:group_order_article, group_order: go3, order_article: oa) } # set quantities of group_order_articles def set_quantities(q1, q2, q3) @@ -79,21 +79,21 @@ def goa_reload it 'does nothing when nothing has changed' do set_quantities [3, 2], [1, 3], [1, 0] - expect(oa.redistribute 6, [:tolerance, nil]).to eq [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] - expect(oa.redistribute 0, [:tolerance, nil]).to eq [0, 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] - expect(oa.redistribute 4, [:tolerance, nil]).to eq [0, 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 @@ -101,28 +101,28 @@ def goa_reload it 'works when quantity is increased within quantity' do 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] + expect(oa.redistribute(7, [:tolerance, nil])).to eq [0, 0] goa_reload expect([goa1, goa2, goa3].map(&:result).map(&:to_i)).to eq [3, 2, 2] end it 'works when there is just one for the first' do set_quantities [3, 2], [1, 3], [1, 0] - expect(oa.redistribute 1, [:tolerance, nil]).to eq [0, 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] - expect(oa.redistribute 10, [:tolerance, nil]).to eq [3, 2] + 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] - expect(oa.redistribute 8, [nil]).to eq [3] + expect(oa.redistribute(8, [nil])).to eq [3] goa_reload expect([goa1, goa2, goa3].map(&:result)).to eq [3, 1, 1] end @@ -130,17 +130,19 @@ def goa_reload describe 'boxfill' do before { FoodsoftConfig[:use_boxfill] = true } - let(:article) { create :article, unit_quantity: 6 } - let(:order) { create :order, article_ids: [article.id], starts: 1.week.ago } + + let(:article) { create(:article, unit_quantity: 6) } + let(:order) { create(:order, article_ids: [article.id], starts: 1.week.ago) } let(:oa) { order.order_articles.first } - let(:go) { create :group_order, order: order } - let(:goa) { create :group_order_article, group_order: go, order_article: oa } + let(:go) { create(:group_order, order: order) } + let(:goa) { create(:group_order_article, group_order: go, order_article: oa) } - shared_examples "boxfill" do |success, q| + shared_examples 'boxfill' do |success, q| # initial situation before do - goa.update_quantities *q.keys[0] - oa.update_results!; oa.reload + goa.update_quantities(*q.keys[0]) + oa.update_results! + oa.reload end # check starting condition @@ -149,11 +151,11 @@ def goa_reload end # actual test - it (success ? 'succeeds' : 'fails') do + it(success ? 'succeeds' : 'fails') do order.update_attributes(boxfill: boxfill_from) r = proc { - goa.update_quantities *q.values[0] + goa.update_quantities(*q.values[0]) oa.update_results! } if success @@ -169,33 +171,41 @@ def goa_reload 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 diff --git a/spec/models/order_spec.rb b/spec/models/order_spec.rb index 10a91a7e..18a478b4 100644 --- a/spec/models/order_spec.rb +++ b/spec/models/order_spec.rb @@ -1,14 +1,14 @@ require_relative '../spec_helper' describe Order do - let!(:ftt) { create :financial_transaction_type } - let(:user) { create :user, groups: [create(:ordergroup)] } + let!(:ftt) { create(:financial_transaction_type) } + let(:user) { create(:user, groups: [create(:ordergroup)]) } it 'automaticly finishes ended' do - create :order, created_by: user, starts: Date.yesterday, ends: 1.hour.from_now - create :order, created_by: user, starts: Date.yesterday, ends: 1.hour.ago - create :order, created_by: user, starts: Date.yesterday, ends: 1.hour.from_now, end_action: :auto_close - order = create :order, created_by: user, starts: Date.yesterday, ends: 1.hour.ago, end_action: :auto_close + create(:order, created_by: user, starts: Date.yesterday, ends: 1.hour.from_now) + create(:order, created_by: user, starts: Date.yesterday, ends: 1.hour.ago) + create(:order, created_by: user, starts: Date.yesterday, ends: 1.hour.from_now, end_action: :auto_close) + order = create(:order, created_by: user, starts: Date.yesterday, ends: 1.hour.ago, end_action: :auto_close) Order.finish_ended! order.reload @@ -19,51 +19,51 @@ end describe 'state scopes and boolean getters' do - let!(:open_order) { create :order, state: 'open' } - let!(:finished_order) { create :order, state: 'finished' } - let!(:received_order) { create :order, state: 'received' } - let!(:closed_order) { create :order, state: 'closed' } + let!(:open_order) { create(:order, state: 'open') } + let!(:finished_order) { create(:order, state: 'finished') } + let!(:received_order) { create(:order, state: 'received') } + let!(:closed_order) { create(:order, state: 'closed') } - it 'should retrieve open orders in the "open" scope' do + it 'retrieves open orders in the "open" scope' do expect(Order.open.count).to eq(1) expect(Order.open.where(id: open_order.id)).to exist end - it 'should retrieve finished, received and closed orders in the "finished" scope' do + it 'retrieves finished, received and closed orders in the "finished" scope' do expect(Order.finished.count).to eq(3) expect(Order.finished.where(id: finished_order.id)).to exist expect(Order.finished.where(id: received_order.id)).to exist expect(Order.finished.where(id: closed_order.id)).to exist end - it 'should retrieve finished and received orders in the "finished_not_closed" scope' do + it 'retrieves finished and received orders in the "finished_not_closed" scope' do expect(Order.finished_not_closed.count).to eq(2) expect(Order.finished_not_closed.where(id: finished_order.id)).to exist expect(Order.finished_not_closed.where(id: received_order.id)).to exist end - it 'should return valid boolean states for open orders' do + it 'returns valid boolean states for open orders' do expect(open_order.open?).to be(true) expect(open_order.finished?).to be(false) expect(open_order.received?).to be(false) expect(open_order.closed?).to be(false) end - it 'should return valid boolean states for finished orders' do + it 'returns valid boolean states for finished orders' do expect(finished_order.open?).to be(false) expect(finished_order.finished?).to be(true) expect(finished_order.received?).to be(false) expect(finished_order.closed?).to be(false) end - it 'should return valid boolean states for received orders' do + it 'returns valid boolean states for received orders' do expect(received_order.open?).to be(false) expect(received_order.finished?).to be(true) expect(received_order.received?).to be(true) expect(received_order.closed?).to be(false) end - it 'should return valid boolean states for closed orders' do + it 'returns valid boolean states for closed orders' do expect(closed_order.open?).to be(false) expect(closed_order.finished?).to be(false) expect(closed_order.received?).to be(false) @@ -72,8 +72,9 @@ end it 'sends mail if min_order_quantity has been reached' do - create :user, groups: [create(:ordergroup)] - create :order, created_by: user, starts: Date.yesterday, ends: 1.hour.ago, end_action: :auto_close_and_send_min_quantity + create(:user, groups: [create(:ordergroup)]) + create(:order, created_by: user, starts: Date.yesterday, ends: 1.hour.ago, + end_action: :auto_close_and_send_min_quantity) Order.finish_ended! expect(ActionMailer::Base.deliveries.count).to eq 1 @@ -84,7 +85,7 @@ end it 'needs order articles' do - supplier = create :supplier, article_count: 0 + supplier = create(:supplier, article_count: 0) expect(build(:order, supplier: supplier)).to be_invalid end @@ -93,35 +94,44 @@ end describe 'with articles' do - let(:order) { create :order } + let(:order) { create(:order) } - it 'is open by default' do expect(order).to be_open end - it 'is not finished by default' do expect(order).to_not be_finished end - it 'is not closed by default' do expect(order).to_not be_closed end + it 'is open by default' do + expect(order).to be_open + end + + it 'is not finished by default' do + expect(order).not_to be_finished + end + + it 'is not closed by default' do + expect(order).not_to be_closed + end it 'has valid order articles' do order.order_articles.each { |oa| expect(oa).to be_valid } end it 'can be finished' do - # TODO randomise user + # TODO: randomise user order.finish!(user) - expect(order).to_not be_open + expect(order).not_to be_open expect(order).to be_finished - expect(order).to_not be_closed + expect(order).not_to be_closed end it 'can be closed' do - # TODO randomise user + # TODO: randomise user order.finish!(user) order.close!(user) - expect(order).to_not be_open + expect(order).not_to be_open expect(order).to be_closed end end describe 'with a default end date' do - let(:order) { create :order } + let(:order) { create(:order) } + before do FoodsoftConfig[:order_schedule] = { ends: { recurr: 'FREQ=WEEKLY;BYDAY=MO', time: '9:00' } } order.init_dates @@ -137,10 +147,10 @@ end describe 'mapped to GroupOrders' do - let!(:user) { create :user, groups: [create(:ordergroup)] } - let!(:order) { create :order } - let!(:order2) { create :order } - let!(:go) { create :group_order, order: order, ordergroup: user.ordergroup } + let!(:user) { create(:user, groups: [create(:ordergroup)]) } + let!(:order) { create(:order) } + let!(:order2) { create(:order) } + let!(:go) { create(:group_order, order: order, ordergroup: user.ordergroup) } it 'to map a user\'s GroupOrders to a list of Orders' do orders = Order.ordergroup_group_orders_map(user.ordergroup) @@ -155,10 +165,10 @@ describe 'balancing charges correct amounts' do let!(:transport) { rand(0.1..26.0).round(2) } - let!(:order) { create :order, article_count: 1 } + let!(:order) { create(:order, article_count: 1) } let!(:oa) { order.order_articles.first } - let!(:go) { create :group_order, order: order, transport: transport } - let!(:goa) { create :group_order_article, group_order: go, order_article: oa, quantity: 1 } + let!(:go) { create(:group_order, order: order, transport: transport) } + let!(:goa) { create(:group_order_article, group_order: go, order_article: oa, quantity: 1) } before do goa.update_quantities(1, 0) diff --git a/spec/models/ordergroup_spec.rb b/spec/models/ordergroup_spec.rb index 6ac58fd5..565ad32f 100644 --- a/spec/models/ordergroup_spec.rb +++ b/spec/models/ordergroup_spec.rb @@ -1,12 +1,12 @@ require_relative '../spec_helper' describe Ordergroup do - let(:ftc1) { create :financial_transaction_class } - let(:ftc2) { create :financial_transaction_class } - 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(:ftc1) { create(:financial_transaction_class) } + let(:ftc2) { create(:financial_transaction_class) } + 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)]) } context 'with financial transactions' do before do diff --git a/spec/models/supplier_spec.rb b/spec/models/supplier_spec.rb index c156aa35..f92e140c 100644 --- a/spec/models/supplier_spec.rb +++ b/spec/models/supplier_spec.rb @@ -1,28 +1,28 @@ require_relative '../spec_helper' describe Supplier do - let(:supplier) { create :supplier } + let(:supplier) { create(:supplier) } it 'has a unique name' do - supplier2 = build :supplier, name: supplier.name + supplier2 = build(:supplier, name: supplier.name) expect(supplier2).to be_invalid end it 'has valid articles' do - supplier = create :supplier, article_count: true + supplier = create(:supplier, article_count: true) supplier.articles.each { |a| expect(a).to be_valid } end context 'connected to a shared supplier' do let(:shared_sync_method) { nil } - let(:shared_supplier) { create :shared_supplier } - let(:supplier) { create :supplier, shared_supplier: shared_supplier, shared_sync_method: shared_sync_method } + let(:shared_supplier) { create(:shared_supplier) } + let(:supplier) { create(:supplier, shared_supplier: shared_supplier, shared_sync_method: shared_sync_method) } - let!(:synced_shared_article) { create :shared_article, shared_supplier: shared_supplier } - let!(:updated_shared_article) { create :shared_article, shared_supplier: shared_supplier } - let!(:new_shared_article) { create :shared_article, shared_supplier: shared_supplier } + let!(:synced_shared_article) { create(:shared_article, shared_supplier: shared_supplier) } + let!(:updated_shared_article) { create(:shared_article, shared_supplier: shared_supplier) } + let!(:new_shared_article) { create(:shared_article, shared_supplier: shared_supplier) } - let!(:removed_article) { create :article, supplier: supplier, order_number: '10001-ABC' } + let!(:removed_article) { create(:article, supplier: supplier, order_number: '10001-ABC') } let!(:updated_article) do updated_shared_article.build_new_article(supplier).tap do |article| article_version = article.latest_article_version @@ -36,7 +36,7 @@ article_version.article_category = create :article_category article_version.unit = '200g' - article_version.origin = "FubarX1" + article_version.origin = 'FubarX1' article.article_versions << article_version article.reload end @@ -65,10 +65,10 @@ it 'returns the expected articles' do updated_article_pairs, outlisted_articles, new_articles = supplier.sync_all - expect(updated_article_pairs).to_not be_empty + expect(updated_article_pairs).not_to be_empty index = updated_article_pairs.index { |pair| pair[0].id == updated_article.id } - expect(index).to_not be_nil + expect(index).not_to be_nil expect(updated_article_pairs[index][1].keys).to include :origin expect(outlisted_articles).to eq [removed_article] @@ -84,12 +84,12 @@ updated_article_pairs, outlisted_articles, new_articles = supplier.sync_all index = updated_article_pairs.index { |pair| pair[0].id == updated_article.id } - expect(index).to_not be_nil + expect(index).not_to be_nil expect(updated_article_pairs[index][1].keys).to include :origin expect(outlisted_articles).to eq [removed_article] - expect(new_articles).to_not be_empty + expect(new_articles).not_to be_empty expect(new_articles[0].order_number).to eq new_shared_article.number expect(new_articles[0].availability).to be true end @@ -102,12 +102,12 @@ updated_article_pairs, outlisted_articles, new_articles = supplier.sync_all index = updated_article_pairs.index { |pair| pair[0].id == updated_article.id } - expect(index).to_not be_nil + expect(index).not_to be_nil expect(updated_article_pairs[index][1].keys).to include :origin expect(outlisted_articles).to eq [removed_article] - expect(new_articles).to_not be_empty + expect(new_articles).not_to be_empty expect(new_articles[0].order_number).to eq new_shared_article.number expect(new_articles[0].availability).to be false end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 2415cae8..9eb5f7d9 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -2,9 +2,9 @@ describe User do it 'is correctly created' do - user = create :user, + user = create(:user, nick: 'johnnydoe', first_name: 'Johnny', last_name: 'DoeBar', - email: 'johnnydoe@foodcoop.test', phone: '+1234567890' + 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') @@ -14,34 +14,54 @@ end describe 'does not have the role' do - let(:user) { create :user } - it 'admin' do expect(user.role_admin?).to be_falsey end - it 'finance' do expect(user.role_finance?).to be_falsey end - it 'article_meta' do expect(user.role_article_meta?).to be_falsey end - it 'suppliers' do expect(user.role_suppliers?).to be_falsey end - it 'orders' do expect(user.role_orders?).to be_falsey end + let(:user) { create(:user) } + + it 'admin' do + expect(user.role_admin?).to be_falsey + end + + it 'finance' do + expect(user.role_finance?).to be_falsey + end + + it 'article_meta' do + expect(user.role_article_meta?).to be_falsey + end + + it 'suppliers' do + expect(user.role_suppliers?).to be_falsey + end + + it 'orders' do + expect(user.role_orders?).to be_falsey + end end describe do - let(:user) { create :user, password: 'blahblahblah' } + let(:user) { create(:user, password: 'blahblahblah') } it 'can authenticate with correct password' do expect(User.authenticate(user.nick, 'blahblahblah')).to be_truthy end + it 'can not authenticate with incorrect password' do expect(User.authenticate(user.nick, 'foobar')).to be_nil end + it 'can not authenticate with nil nick' do expect(User.authenticate(nil, 'blahblahblah')).to be_nil end + it 'can not authenticate with nil password' do expect(User.authenticate(user.nick, nil)).to be_nil end + it 'can not set a password without matching confirmation' do user.password = 'abcdefghijkl' user.password_confirmation = 'foobaruvwxyz' expect(user).to be_invalid end + it 'can set a password with matching confirmation' do user.password = 'abcdefghijkl' user.password_confirmation = 'abcdefghijkl' @@ -51,6 +71,7 @@ it 'has a unique nick' do expect(build(:user, nick: user.nick, email: "x-#{user.email}")).to be_invalid end + it 'has a unique email' do expect(build(:user, email: "#{user.email}")).to be_invalid end @@ -67,7 +88,10 @@ end describe 'admin' do - let(:user) { create :admin } - it 'default admin role' do expect(user.role_admin?).to be_truthy end + let(:user) { create(:admin) } + + it 'default admin role' do + expect(user.role_admin?).to be_truthy + end end end diff --git a/spec/requests/api/v1/order_articles_controller_spec.rb b/spec/requests/api/v1/order_articles_controller_spec.rb new file mode 100644 index 00000000..31d6510f --- /dev/null +++ b/spec/requests/api/v1/order_articles_controller_spec.rb @@ -0,0 +1,115 @@ +require 'swagger_helper' + +describe Api::V1::OrderArticlesController do + include ApiHelper + + path '/order_articles' do + get 'order articles' do + tags 'Order' + produces 'application/json' + pagination_param + q_ordered_url_param + + let(:api_scopes) { ['orders:read', 'orders:write'] } + let(:order) { create(:order, article_count: 4) } + let(:order_articles) { order.order_articles } + + before do + order_articles[0].update! quantity: 0, tolerance: 0, units_to_order: 0 + order_articles[1].update! quantity: 1, tolerance: 0, units_to_order: 0 + order_articles[2].update! quantity: 0, tolerance: 1, units_to_order: 0 + order_articles[3].update! quantity: 0, tolerance: 0, units_to_order: 1 + end + + response '200', 'success' do + schema type: :object, properties: { + meta: { '$ref' => '#/components/schemas/Meta' }, + order_articles: { + type: :array, + items: { + '$ref': '#/components/schemas/OrderArticle' + } + } + } + describe '(unset)' do + run_test! + end + + describe 'all' do + let(:q) { { q: { ordered: 'all' } } } + + run_test! do |response| + json_order_articles = JSON.parse(response.body)['order_articles'] + json_order_article_ids = json_order_articles.map { |d| d['id'].to_i } + expect(json_order_article_ids).to match_array order_articles[1..2].map(&:id) + end + end + + describe 'when ordered by supplier' do + let(:q) { { q: { ordered: 'supplier' } } } + + run_test! do |response| + json_order_articles = JSON.parse(response.body)['order_articles'] + json_order_article_ids = json_order_articles.map { |d| d['id'].to_i } + expect(json_order_article_ids).to contain_exactly(order_articles[3].id) + end + end + + describe 'when ordered by member' do + let(:q) { { q: { ordered: 'member' } } } + + run_test! do |response| + json_order_articles = JSON.parse(response.body)['order_articles'] + expect(json_order_articles.count).to eq 0 + end + end + + context 'when ordered by user' do + let(:user) { create(:user, :ordergroup) } + let(:go) { create(:group_order, order: order, ordergroup: user.ordergroup) } + + before do + create(:group_order_article, group_order: go, order_article: order_articles[1], quantity: 1) + create(:group_order_article, group_order: go, order_article: order_articles[2], tolerance: 0) + end + + describe 'member' do + let(:q) { { q: { ordered: 'member' } } } + + run_test! do |response| + json_order_articles = JSON.parse(response.body)['order_articles'] + json_order_article_ids = json_order_articles.map { |d| d['id'].to_i } + expect(json_order_article_ids).to match_array order_articles[1..2].map(&:id) + end + end + end + end + + it_handles_invalid_token_and_scope + end + end + + path '/order_articles/{id}' do + get 'order articles' do + tags 'Order' + produces 'application/json' + id_url_param + let(:api_scopes) { ['orders:read', 'orders:write'] } + + response '200', 'success' do + schema type: :object, properties: { + order_article: { + '$ref': '#/components/schemas/OrderArticle' + } + } + let(:order) { create(:order, article_count: 1) } + let(:id) { order.order_articles.first.id } + + run_test! + end + + it_handles_invalid_token_and_scope + it_cannot_find_object 'order article not found' + end + end +end diff --git a/spec/requests/api/v1/user/financial_transactions_spec.rb b/spec/requests/api/v1/user/financial_transactions_spec.rb new file mode 100644 index 00000000..91a6fff0 --- /dev/null +++ b/spec/requests/api/v1/user/financial_transactions_spec.rb @@ -0,0 +1,109 @@ +require 'swagger_helper' + +describe 'User' do + include ApiHelper + + let(:api_scopes) { ['finance:user'] } + let(:user) { create(:user, groups: [create(:ordergroup)]) } + let(:other_user2) { create(:user) } + let(:ft) { create(:financial_transaction, user: user, ordergroup: user.ordergroup) } + + before do + ft + end + + path '/user/financial_transactions' do + post 'create new financial transaction (requires enabled self service)' do + tags 'Financial Transaction' + consumes 'application/json' + produces 'application/json' + + parameter name: :financial_transaction, in: :body, schema: { + type: :object, + properties: { + amount: { type: :integer }, + financial_transaction_type: { type: :integer }, + note: { type: :string } + } + } + + let(:financial_transaction) do + { amount: 3, financial_transaction_type_id: create(:financial_transaction_type).id, note: 'lirum larum' } + end + + response '200', 'success' do + schema type: :object, properties: { + financial_transaction: { '$ref': '#/components/schemas/FinancialTransaction' } + } + run_test! + end + + it_handles_invalid_token_with_id + it_handles_invalid_scope_with_id 'user has no ordergroup, is below minimum balance, self service is disabled, or missing scope' + + response '404', 'financial transaction type not found' do + schema '$ref' => '#/components/schemas/Error404' + let(:financial_transaction) { { amount: 3, financial_transaction_type_id: 'invalid', note: 'lirum larum' } } + run_test! + end + + response '422', 'invalid parameter value' do + schema '$ref' => '#/components/schemas/Error422' + let(:financial_transaction) do + { amount: 'abc', financial_transaction_type_id: create(:financial_transaction_type).id, note: 'foo bar' } + end + run_test! + end + end + + get "financial transactions of the member's ordergroup" do + tags 'User', 'Financial Transaction' + produces 'application/json' + pagination_param + + response '200', 'success' do + schema type: :object, properties: { + meta: { '$ref': '#/components/schemas/Meta' }, + financial_transaction: { + type: :array, + items: { + '$ref': '#/components/schemas/FinancialTransaction' + } + } + } + + run_test! do |response| + data = JSON.parse(response.body) + expect(data['financial_transactions'].first['id']).to eq(ft.id) + end + end + + it_handles_invalid_token_and_scope + end + end + + path '/user/financial_transactions/{id}' do + get 'find financial transaction by id' do + tags 'User', 'Financial Transaction' + produces 'application/json' + id_url_param + + response '200', 'success' do + schema type: :object, properties: { + financial_transaction: { + '$ref': '#/components/schemas/FinancialTransaction' + } + } + let(:id) { ft.id } + run_test! do |response| + data = JSON.parse(response.body) + expect(data['financial_transaction']['id']).to eq(ft.id) + end + end + + it_handles_invalid_token_with_id + it_handles_invalid_scope_with_id 'user has no ordergroup or missing scope' + it_cannot_find_object 'financial transaction not found' + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 88dea423..c1a3df21 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,8 +1,8 @@ # This file is copied to spec/ when you run 'rails generate rspec:install' -ENV["RAILS_ENV"] ||= 'test' -ENV["FOODSOFT_APP_CONFIG"] ||= 'spec/app_config.yml' # load special foodsoft config +ENV['RAILS_ENV'] ||= 'test' +ENV['FOODSOFT_APP_CONFIG'] ||= 'spec/app_config.yml' # load special foodsoft config require_relative 'support/coverage' # needs to be first -require File.expand_path("../../config/environment", __FILE__) +require File.expand_path('../config/environment', __dir__) require 'rspec/rails' require 'capybara/rails' require 'capybara/apparition' @@ -17,17 +17,17 @@ # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. -Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } +Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } RSpec.configure do |config| # We use capybara with webkit, and need database_cleaner - config.before(:each) do + config.before do DatabaseCleaner.strategy = (RSpec.current_example.metadata[:js] ? :truncation : :transaction) DatabaseCleaner.start # clean slate mail queues, not sure why needed - https://github.com/rspec/rspec-rails/issues/661 ActionMailer::Base.deliveries.clear end - config.after(:each) do + config.after do DatabaseCleaner.clean # Need to clear cache for RailsSettings::CachedSettings Rails.cache.clear @@ -35,7 +35,7 @@ # reload foodsoft configuration, so that tests can use FoodsoftConfig.config[:foo]=x # without messing up tests run after that - config.before(:each) do + config.before do FoodsoftConfig.init FoodsoftConfig.init_mailing end @@ -49,7 +49,7 @@ # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 - config.order = "random" + config.order = 'random' config.include SessionHelper, type: :feature diff --git a/spec/support/api_helper.rb b/spec/support/api_helper.rb index 65acc75b..752e19b6 100644 --- a/spec/support/api_helper.rb +++ b/spec/support/api_helper.rb @@ -4,12 +4,15 @@ module ApiHelper included do let(:user) { create(:user) } let(:api_scopes) { [] } # empty scopes for stricter testing (in reality this would be default_scopes) - let(:api_access_token) { create(:oauth2_access_token, resource_owner_id: user.id, scopes: api_scopes&.join(' ')).token } + let(:api_access_token) do + create(:oauth2_access_token, resource_owner_id: user.id, scopes: api_scopes&.join(' ')).token + end let(:api_authorization) { "Bearer #{api_access_token}" } 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 @@ -17,6 +20,7 @@ def self.it_handles_invalid_token(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)) } end end diff --git a/spec/support/api_oauth.rb b/spec/support/api_oauth.rb index 8cf283f4..9d701349 100644 --- a/spec/support/api_oauth.rb +++ b/spec/support/api_oauth.rb @@ -5,7 +5,7 @@ module ApiOAuth included do let(:user) { build(:user) } let(:api_scopes) { [] } # empty scopes for stricter testing (in reality this would be default_scopes) - let(:api_access_token) { double(:acceptable? => true, :accessible? => true, scopes: api_scopes) } + let(:api_access_token) { double(acceptable?: true, accessible?: true, scopes: api_scopes) } before { allow(controller).to receive(:doorkeeper_token) { api_access_token } } before { allow(controller).to receive(:current_user) { user } } diff --git a/spec/support/coverage.rb b/spec/support/coverage.rb index 20bbdcf3..443da12d 100644 --- a/spec/support/coverage.rb +++ b/spec/support/coverage.rb @@ -11,16 +11,28 @@ # slightly tweaked coverage reporting def cov_no_plugins(source_file, path) - source_file.filename =~ /#{path}/ and not source_file.filename =~ /\/lib\/foodsoft_.*\// + source_file.filename =~ /#{path}/ and !(source_file.filename =~ %r{/lib/foodsoft_.*/}) end SimpleCov.start do add_filter '/spec/' add_filter '/test/' - add_group 'Models' do |s| cov_no_plugins s, '/app/models/' end - add_group 'Controllers' do |s| cov_no_plugins s, '/app/controllers/' end - add_group 'Helpers' do |s| cov_no_plugins s, '/app/helpers/' end - add_group 'Documents' do |s| cov_no_plugins s, '/app/documents/' end - add_group 'Libraries' do |s| cov_no_plugins s, '/lib/' end - add_group 'Plugins' do |s| s.filename =~ /\/lib\/foodsoft_.*\// end + add_group 'Models' do |s| + cov_no_plugins s, '/app/models/' + end + add_group 'Controllers' do |s| + cov_no_plugins s, '/app/controllers/' + end + add_group 'Helpers' do |s| + cov_no_plugins s, '/app/helpers/' + end + add_group 'Documents' do |s| + cov_no_plugins s, '/app/documents/' + end + add_group 'Libraries' do |s| + cov_no_plugins s, '/lib/' + end + add_group 'Plugins' do |s| + s.filename =~ %r{/lib/foodsoft_.*/} + end end end diff --git a/spec/support/faker.rb b/spec/support/faker.rb index 7d4694c5..e4857f8a 100644 --- a/spec/support/faker.rb +++ b/spec/support/faker.rb @@ -2,7 +2,7 @@ module Faker class LegacyUnit class << self def unit - ['kg', '1L', '100ml', 'piece', 'bunch', '500g'].sample + %w[kg 1L 100ml piece bunch 500g].sample end end end @@ -10,7 +10,7 @@ def unit class Unit class << self def units - ['KGM', 'GRM', 'LTR'] + %w[KGM GRM LTR] end def unit diff --git a/spec/support/integration.rb b/spec/support/integration.rb index 26add35a..6882ac5a 100644 --- a/spec/support/integration.rb +++ b/spec/support/integration.rb @@ -1,4 +1,4 @@ # @see http://stackoverflow.com/a/11048669/2866660 def scrolldown - page.execute_script "window.scrollBy(0,10000)" + page.execute_script 'window.scrollBy(0,10000)' end diff --git a/spec/support/session_helper.rb b/spec/support/session_helper.rb index 31fb0946..1075695e 100644 --- a/spec/support/session_helper.rb +++ b/spec/support/session_helper.rb @@ -1,14 +1,15 @@ module SessionHelper def login(user = nil, password = nil) visit login_path - user = FactoryBot.create :user if user.nil? + user = FactoryBot.create(:user) if user.nil? if user.instance_of? ::User - nick, password = user.nick, user.password + nick = user.nick + password = user.password else nick = user end - fill_in 'nick', :with => nick - fill_in 'password', :with => password + fill_in 'nick', with: nick + fill_in 'password', with: password find('input[type=submit]').click end end